@rizzxdc/baileys 8.0.10 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/LICENSE +4 -2
  2. package/README.md +107 -245
  3. package/WAProto/index.d.ts +15795 -0
  4. package/WAProto/index.js +25587 -4867
  5. package/lib/Defaults/index.d.ts +147 -0
  6. package/lib/Defaults/index.js +134 -104
  7. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  8. package/lib/Signal/Group/ciphertext-message.js +9 -11
  9. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  10. package/lib/Signal/Group/group-session-builder.js +5 -8
  11. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  12. package/lib/Signal/Group/group_cipher.js +72 -75
  13. package/lib/Signal/Group/index.d.ts +12 -0
  14. package/lib/Signal/Group/index.js +11 -13
  15. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  16. package/lib/Signal/Group/keyhelper.js +11 -14
  17. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  18. package/lib/Signal/Group/sender-chain-key.js +23 -26
  19. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.js +58 -61
  21. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  22. package/lib/Signal/Group/sender-key-message.js +61 -64
  23. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  24. package/lib/Signal/Group/sender-key-name.js +39 -44
  25. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  26. package/lib/Signal/Group/sender-key-record.js +35 -38
  27. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  28. package/lib/Signal/Group/sender-key-state.js +76 -79
  29. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  30. package/lib/Signal/Group/sender-message-key.js +23 -26
  31. package/lib/Signal/libsignal.d.ts +55 -0
  32. package/lib/Signal/libsignal.js +414 -308
  33. package/lib/Signal/lid-mapping.d.ts +21 -0
  34. package/lib/Signal/lid-mapping.js +270 -149
  35. package/lib/Socket/Client/index.d.ts +3 -0
  36. package/lib/Socket/Client/index.js +2 -4
  37. package/lib/Socket/Client/types.d.ts +6 -0
  38. package/lib/Socket/Client/types.js +8 -11
  39. package/lib/Socket/Client/websocket.d.ts +13 -0
  40. package/lib/Socket/Client/websocket.js +51 -50
  41. package/lib/Socket/business.d.ts +395 -0
  42. package/lib/Socket/business.js +357 -355
  43. package/lib/Socket/chats.d.ts +137 -0
  44. package/lib/Socket/chats.js +1195 -867
  45. package/lib/Socket/communities.d.ts +562 -0
  46. package/lib/Socket/communities.js +416 -398
  47. package/lib/Socket/dugong.js +8 -1
  48. package/lib/Socket/groups.d.ts +286 -0
  49. package/lib/Socket/groups.js +336 -301
  50. package/lib/Socket/index.d.ts +530 -0
  51. package/lib/Socket/index.js +8 -13
  52. package/lib/Socket/messages-recv.d.ts +334 -0
  53. package/lib/Socket/messages-recv.js +1729 -1121
  54. package/lib/Socket/messages-send.d.ts +330 -0
  55. package/lib/Socket/messages-send.js +684 -462
  56. package/lib/Socket/mex.d.ts +2 -0
  57. package/lib/Socket/mex.js +36 -40
  58. package/lib/Socket/newsletter.d.ts +284 -0
  59. package/lib/Socket/newsletter.js +247 -237
  60. package/lib/Socket/socket.d.ts +61 -0
  61. package/lib/Socket/socket.js +968 -790
  62. package/lib/Store/index.d.ts +4 -0
  63. package/lib/Store/index.js +4 -6
  64. package/lib/Store/make-cache-manager-store.js +2 -2
  65. package/lib/Store/make-in-memory-store.d.ts +63 -0
  66. package/lib/Store/make-in-memory-store.js +414 -284
  67. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  68. package/lib/Store/make-ordered-dictionary.js +75 -76
  69. package/lib/Store/object-repository.d.ts +11 -0
  70. package/lib/Store/object-repository.js +21 -23
  71. package/lib/Types/Auth.d.ts +2 -0
  72. package/lib/Types/Auth.js +0 -2
  73. package/lib/Types/Bussines.d.ts +2 -0
  74. package/lib/Types/Bussines.js +0 -2
  75. package/lib/Types/Call.d.ts +2 -0
  76. package/lib/Types/Call.js +0 -2
  77. package/lib/Types/Chat.d.ts +2 -0
  78. package/lib/Types/Chat.js +5 -7
  79. package/lib/Types/Contact.d.ts +2 -0
  80. package/lib/Types/Contact.js +0 -2
  81. package/lib/Types/Events.d.ts +2 -0
  82. package/lib/Types/Events.js +1 -3
  83. package/lib/Types/GroupMetadata.d.ts +2 -0
  84. package/lib/Types/GroupMetadata.js +0 -2
  85. package/lib/Types/Label.d.ts +3 -0
  86. package/lib/Types/Label.js +21 -22
  87. package/lib/Types/LabelAssociation.d.ts +3 -0
  88. package/lib/Types/LabelAssociation.js +3 -4
  89. package/lib/Types/Message.d.ts +12 -0
  90. package/lib/Types/Message.js +11 -6
  91. package/lib/Types/Mex.d.ts +3 -0
  92. package/lib/Types/Mex.js +38 -0
  93. package/lib/Types/Product.d.ts +2 -0
  94. package/lib/Types/Product.js +0 -2
  95. package/lib/Types/RichType.d.ts +3 -0
  96. package/lib/Types/RichType.js +22 -0
  97. package/lib/Types/Signal.d.ts +2 -0
  98. package/lib/Types/Signal.js +1 -3
  99. package/lib/Types/Socket.d.ts +2 -0
  100. package/lib/Types/Socket.js +1 -4
  101. package/lib/Types/State.d.ts +6 -0
  102. package/lib/Types/State.js +52 -8
  103. package/lib/Types/USync.d.ts +2 -0
  104. package/lib/Types/USync.js +1 -3
  105. package/lib/Types/index.d.ts +14 -0
  106. package/lib/Types/index.js +22 -25
  107. package/lib/Utils/auth-utils.d.ts +58 -0
  108. package/lib/Utils/auth-utils.js +285 -203
  109. package/lib/Utils/browser-utils.d.ts +9 -0
  110. package/lib/Utils/browser-utils.js +21 -19
  111. package/lib/Utils/business.d.ts +50 -0
  112. package/lib/Utils/business.js +206 -209
  113. package/lib/Utils/chat-utils.d.ts +409 -0
  114. package/lib/Utils/chat-utils.js +825 -706
  115. package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
  116. package/lib/Utils/companion-reg-client-utils.js +39 -0
  117. package/lib/Utils/crypto.d.ts +40 -0
  118. package/lib/Utils/crypto.js +88 -101
  119. package/lib/Utils/decode-wa-message.d.ts +84 -0
  120. package/lib/Utils/decode-wa-message.js +287 -238
  121. package/lib/Utils/event-buffer.d.ts +13 -0
  122. package/lib/Utils/event-buffer.js +602 -509
  123. package/lib/Utils/generics.d.ts +64 -0
  124. package/lib/Utils/generics.js +334 -295
  125. package/lib/Utils/history.d.ts +76 -0
  126. package/lib/Utils/history.js +125 -79
  127. package/lib/Utils/identity-change-handler.d.ts +14 -0
  128. package/lib/Utils/identity-change-handler.js +49 -0
  129. package/lib/Utils/index.d.ts +25 -0
  130. package/lib/Utils/index.js +25 -21
  131. package/lib/Utils/link-preview.d.ts +13 -0
  132. package/lib/Utils/link-preview.js +73 -70
  133. package/lib/Utils/logger.d.ts +3 -0
  134. package/lib/Utils/logger.js +1 -4
  135. package/lib/Utils/lt-hash.d.ts +7 -0
  136. package/lib/Utils/lt-hash.js +7 -45
  137. package/lib/Utils/make-mutex.d.ts +7 -0
  138. package/lib/Utils/make-mutex.js +27 -31
  139. package/lib/Utils/message-retry-manager.d.ts +80 -0
  140. package/lib/Utils/message-retry-manager.js +165 -14
  141. package/lib/Utils/messages-media.d.ts +137 -0
  142. package/lib/Utils/messages-media.js +768 -572
  143. package/lib/Utils/messages.d.ts +46 -0
  144. package/lib/Utils/messages.js +1082 -130
  145. package/lib/Utils/noise-handler.d.ts +21 -0
  146. package/lib/Utils/noise-handler.js +191 -135
  147. package/lib/Utils/offline-node-processor.d.ts +10 -0
  148. package/lib/Utils/offline-node-processor.js +39 -0
  149. package/lib/Utils/pre-key-manager.d.ts +26 -0
  150. package/lib/Utils/pre-key-manager.js +96 -76
  151. package/lib/Utils/process-message.d.ts +84 -0
  152. package/lib/Utils/process-message.js +718 -311
  153. package/lib/Utils/reporting-utils.d.ts +13 -0
  154. package/lib/Utils/reporting-utils.js +257 -0
  155. package/lib/Utils/rich-message-utils.d.ts +49 -0
  156. package/lib/Utils/rich-message-utils.js +257 -0
  157. package/lib/Utils/signal.d.ts +83 -0
  158. package/lib/Utils/signal.js +174 -135
  159. package/lib/Utils/stanza-ack.d.ts +17 -0
  160. package/lib/Utils/stanza-ack.js +37 -0
  161. package/lib/Utils/sync-action-utils.d.ts +3 -0
  162. package/lib/Utils/sync-action-utils.js +48 -0
  163. package/lib/Utils/tc-token-utils.d.ts +30 -0
  164. package/lib/Utils/tc-token-utils.js +162 -0
  165. package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
  166. package/lib/Utils/use-multi-file-auth-state.js +104 -95
  167. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  168. package/lib/Utils/use-single-file-auth-state.js +108 -0
  169. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  170. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  171. package/lib/Utils/validate-connection.d.ts +44 -0
  172. package/lib/Utils/validate-connection.js +182 -180
  173. package/lib/WABinary/constants.d.ts +62 -0
  174. package/lib/WABinary/constants.js +1455 -1292
  175. package/lib/WABinary/decode.d.ts +10 -0
  176. package/lib/WABinary/decode.js +249 -228
  177. package/lib/WABinary/encode.d.ts +3 -0
  178. package/lib/WABinary/encode.js +207 -206
  179. package/lib/WABinary/generic-utils.d.ts +77 -0
  180. package/lib/WABinary/generic-utils.js +135 -99
  181. package/lib/WABinary/index.d.ts +6 -0
  182. package/lib/WABinary/index.js +5 -7
  183. package/lib/WABinary/jid-utils.d.ts +29 -0
  184. package/lib/WABinary/jid-utils.js +80 -78
  185. package/lib/WABinary/types.d.ts +2 -0
  186. package/lib/WABinary/types.js +1 -3
  187. package/lib/WAM/BinaryInfo.d.ts +8 -0
  188. package/lib/WAM/BinaryInfo.js +7 -9
  189. package/lib/WAM/constants.d.ts +34927 -0
  190. package/lib/WAM/constants.js +22847 -22848
  191. package/lib/WAM/encode.d.ts +2 -0
  192. package/lib/WAM/encode.js +129 -134
  193. package/lib/WAM/index.d.ts +4 -0
  194. package/lib/WAM/index.js +3 -5
  195. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  196. package/lib/WAUSync/Protocols/USyncContactProtocol.js +48 -27
  197. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  198. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -48
  199. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  200. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -26
  201. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  202. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -35
  203. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  204. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  205. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  206. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +46 -49
  207. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +23 -25
  209. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  210. package/lib/WAUSync/Protocols/index.js +5 -6
  211. package/lib/WAUSync/USyncQuery.d.ts +21 -0
  212. package/lib/WAUSync/USyncQuery.js +92 -85
  213. package/lib/WAUSync/USyncUser.d.ts +17 -0
  214. package/lib/WAUSync/USyncUser.js +28 -22
  215. package/lib/WAUSync/index.d.ts +4 -0
  216. package/lib/WAUSync/index.js +3 -5
  217. package/lib/index.d.ts +12 -0
  218. package/lib/index.js +31 -19
  219. package/package.json +12 -6
  220. package/lib/Types/Newsletter.js +0 -33
@@ -1,267 +1,316 @@
1
- //=======================================================//
2
- import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidGroup, isJidMetaAI, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser } from "../WABinary/index.js";
3
- import { unpadRandomMax16 } from "./generics.js";
4
- import { proto } from "../../WAProto/index.js";
5
- import { Boom } from "@hapi/boom";
6
- //=======================================================//
1
+ import { Boom } from '@hapi/boom';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidGroup, isJidMetaAI, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser
4
+ // transferDevice
5
+ } from '../WABinary/index.js';
6
+ import { unpadRandomMax16 } from './generics.js';
7
7
  export const getDecryptionJid = async (sender, repository) => {
8
- if (isLidUser(sender) || isHostedLidUser(sender)) {
9
- return sender;
10
- }
11
- const mapped = await repository.lidMapping.getLIDForPN(sender);
12
- return mapped || sender;
8
+ if (isLidUser(sender) || isHostedLidUser(sender)) {
9
+ return sender;
10
+ }
11
+ const mapped = await repository.lidMapping.getLIDForPN(sender);
12
+ return mapped || sender;
13
13
  };
14
- //=======================================================//
15
14
  const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJid, logger) => {
16
- const { senderAlt } = extractAddressingContext(stanza);
17
- if (senderAlt && isLidUser(senderAlt) && isPnUser(sender) && decryptionJid === sender) {
18
- try {
19
- await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }]);
20
- await repository.migrateSession(sender, senderAlt);
21
- logger.debug({ sender, senderAlt }, "Stored LID mapping from envelope");
22
- }
23
- catch (error) {
24
- logger.warn({ sender, senderAlt, error }, "Failed to store LID mapping");
15
+ // TODO: Handle hosted IDs
16
+ const { senderAlt } = extractAddressingContext(stanza);
17
+ if (senderAlt && isLidUser(senderAlt) && isPnUser(sender) && decryptionJid === sender) {
18
+ try {
19
+ await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }]);
20
+ await repository.migrateSession(sender, senderAlt);
21
+ logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope');
22
+ }
23
+ catch (error) {
24
+ logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping');
25
+ }
25
26
  }
26
- }
27
27
  };
28
- //=======================================================//
29
- export const NO_MESSAGE_FOUND_ERROR_TEXT = "Message absent from node";
30
- export const MISSING_KEYS_ERROR_TEXT = "Key used already or never filled";
31
- //=======================================================//
28
+ export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
29
+ export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
30
+ export const ACCOUNT_RESTRICTED_TEXT = 'Your account has been restricted';
31
+ // Retry configuration for failed decryption
32
32
  export const DECRYPTION_RETRY_CONFIG = {
33
- maxRetries: 3,
34
- baseDelayMs: 100,
35
- sessionRecordErrors: ["No session record", "SessionError: No session record"]
33
+ maxRetries: 3,
34
+ baseDelayMs: 100,
35
+ sessionRecordErrors: ['No session record', 'SessionError: No session record']
36
36
  };
37
- //=======================================================//
37
+ /** NACK reason codes we send to the server (client → server) */
38
38
  export const NACK_REASONS = {
39
- ParsingError: 487,
40
- UnrecognizedStanza: 488,
41
- UnrecognizedStanzaClass: 489,
42
- UnrecognizedStanzaType: 490,
43
- InvalidProtobuf: 491,
44
- InvalidHostedCompanionStanza: 493,
45
- MissingMessageSecret: 495,
46
- SignalErrorOldCounter: 496,
47
- MessageDeletedOnPeer: 499,
48
- UnhandledError: 500,
49
- UnsupportedAdminRevoke: 550,
50
- UnsupportedLIDGroup: 551,
51
- DBOperationFailed: 552
39
+ SenderReachoutTimelocked: 463,
40
+ ParsingError: 487,
41
+ UnrecognizedStanza: 488,
42
+ UnrecognizedStanzaClass: 489,
43
+ UnrecognizedStanzaType: 490,
44
+ InvalidProtobuf: 491,
45
+ InvalidHostedCompanionStanza: 493,
46
+ MissingMessageSecret: 495,
47
+ SignalErrorOldCounter: 496,
48
+ MessageDeletedOnPeer: 499,
49
+ UnhandledError: 500,
50
+ UnsupportedAdminRevoke: 550,
51
+ UnsupportedLIDGroup: 551,
52
+ DBOperationFailed: 552
53
+ };
54
+ /**
55
+ * Server-side error codes returned in ack stanzas (server → client) that we
56
+ * currently have dedicated handlers for. Extend as more handlers are added.
57
+ * Distinct from the client-side NackReason enum (WAWebCreateNackFromStanza).
58
+ */
59
+ export const SERVER_ERROR_CODES = {
60
+ /**
61
+ * 1:1 message missing privacy token (tctoken). Usually means the account is
62
+ * restricted: WhatsApp blocks starting new chats but preserves existing ones,
63
+ * since established chats already carry a tctoken.
64
+ */
65
+ MessageAccountRestriction: '463',
66
+ /** Stanza validation failure (SMAX_INVALID) — likely stale device session */
67
+ SmaxInvalid: '479'
52
68
  };
53
- //=======================================================//
54
69
  export const extractAddressingContext = (stanza) => {
55
- let senderAlt;
56
- let recipientAlt;
57
- const sender = stanza.attrs.participant || stanza.attrs.from;
58
- const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith("lid") ? "lid" : "pn");
59
- if (addressingMode === "lid") {
60
- senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn;
61
- recipientAlt = stanza.attrs.recipient_pn;
62
- }
63
- else {
64
- senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid;
65
- recipientAlt = stanza.attrs.recipient_lid;
66
- }
67
- return {
68
- addressingMode,
69
- senderAlt,
70
- recipientAlt
71
- };
70
+ let senderAlt;
71
+ let recipientAlt;
72
+ const sender = stanza.attrs.participant || stanza.attrs.from;
73
+ const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn');
74
+ if (addressingMode === 'lid') {
75
+ // Message is LID-addressed: sender is LID, extract corresponding PN
76
+ // without device data
77
+ senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn;
78
+ recipientAlt = stanza.attrs.recipient_pn;
79
+ // with device data
80
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
81
+ }
82
+ else {
83
+ // Message is PN-addressed: sender is PN, extract corresponding LID
84
+ // without device data
85
+ senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid;
86
+ recipientAlt = stanza.attrs.recipient_lid;
87
+ //with device data
88
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
89
+ }
90
+ return {
91
+ addressingMode,
92
+ senderAlt,
93
+ recipientAlt
94
+ };
72
95
  };
73
- //=======================================================//
96
+ /**
97
+ * Decode the received node as a message.
98
+ * @note this will only parse the message, not decrypt it
99
+ */
74
100
  export function decodeMessageNode(stanza, meId, meLid) {
75
- let msgType;
76
- let chatId;
77
- let author;
78
- let fromMe = false;
79
- const msgId = stanza.attrs.id;
80
- const from = stanza.attrs.from;
81
- const participant = stanza.attrs.participant;
82
- const recipient = stanza.attrs.recipient;
83
- const addressingContext = extractAddressingContext(stanza);
84
- const isMe = (jid) => areJidsSameUser(jid, meId);
85
- const isMeLid = (jid) => areJidsSameUser(jid, meLid);
86
- if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
87
- if (recipient && !isJidMetaAI(recipient)) {
88
- if (!isMe(from) && !isMeLid(from)) {
89
- throw new Boom("receipient present, but msg not from me", { data: stanza });
90
- }
91
- if (isMe(from) || isMeLid(from)) {
92
- fromMe = true;
93
- }
94
- chatId = recipient;
101
+ let msgType;
102
+ let chatId;
103
+ let author;
104
+ let fromMe = false;
105
+ const msgId = stanza.attrs.id;
106
+ const from = stanza.attrs.from;
107
+ const participant = stanza.attrs.participant;
108
+ const recipient = stanza.attrs.recipient;
109
+ if (!msgId) {
110
+ throw new Boom('Invalid message stanza: missing id attribute', { data: stanza });
95
111
  }
96
- else {
97
- chatId = from;
112
+ if (!from) {
113
+ throw new Boom('Invalid message stanza: missing from attribute', { data: stanza });
98
114
  }
99
- msgType = "chat";
100
- author = from;
101
- }
102
- else if (isJidGroup(from)) {
103
- if (!participant) {
104
- throw new Boom("No participant in group message");
115
+ const addressingContext = extractAddressingContext(stanza);
116
+ const isMe = (jid) => areJidsSameUser(jid, meId);
117
+ const isMeLid = (jid) => areJidsSameUser(jid, meLid);
118
+ if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
119
+ if (recipient && !isJidMetaAI(recipient)) {
120
+ if (!isMe(from) && !isMeLid(from)) {
121
+ throw new Boom('receipient present, but msg not from me', { data: stanza });
122
+ }
123
+ if (isMe(from) || isMeLid(from)) {
124
+ fromMe = true;
125
+ }
126
+ chatId = recipient;
127
+ }
128
+ else {
129
+ // Peer-routed self stanzas (history sync, app-state sync, etc.) arrive
130
+ // with `from` set to our own device but no `recipient` attribute —
131
+ // still mark as fromMe so self-only protocolMessage handlers run.
132
+ if (isMe(from) || isMeLid(from)) {
133
+ fromMe = true;
134
+ }
135
+ chatId = from;
136
+ }
137
+ msgType = 'chat';
138
+ author = from;
105
139
  }
106
- if (isMe(participant) || isMeLid(participant)) {
107
- fromMe = true;
140
+ else if (isJidGroup(from)) {
141
+ if (!participant) {
142
+ throw new Boom('No participant in group message');
143
+ }
144
+ if (isMe(participant) || isMeLid(participant)) {
145
+ fromMe = true;
146
+ }
147
+ msgType = 'group';
148
+ author = participant;
149
+ chatId = from;
108
150
  }
109
- msgType = "group";
110
- author = participant;
111
- chatId = from;
112
- }
113
- else if (isJidBroadcast(from)) {
114
- if (!participant) {
115
- throw new Boom("No participant in group message");
151
+ else if (isJidBroadcast(from)) {
152
+ if (!participant) {
153
+ throw new Boom('No participant in group message');
154
+ }
155
+ const isParticipantMe = isMe(participant);
156
+ if (isJidStatusBroadcast(from)) {
157
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
158
+ }
159
+ else {
160
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
161
+ }
162
+ fromMe = isParticipantMe;
163
+ chatId = from;
164
+ author = participant;
116
165
  }
117
- const isParticipantMe = isMe(participant);
118
- if (isJidStatusBroadcast(from)) {
119
- msgType = isParticipantMe ? "direct_peer_status" : "other_status";
166
+ else if (isJidNewsletter(from)) {
167
+ msgType = 'newsletter';
168
+ chatId = from;
169
+ author = from;
170
+ if (isMe(from) || isMeLid(from)) {
171
+ fromMe = true;
172
+ }
120
173
  }
121
174
  else {
122
- msgType = isParticipantMe ? "peer_broadcast" : "other_broadcast";
175
+ throw new Boom('Unknown message type', { data: stanza });
123
176
  }
124
- fromMe = isParticipantMe;
125
- chatId = from;
126
- author = participant;
127
- }
128
- else if (isJidNewsletter(from)) {
129
- msgType = "newsletter";
130
- chatId = from;
131
- author = from;
132
- if (isMe(from) || isMeLid(from)) {
133
- fromMe = true;
177
+ const pushname = stanza?.attrs?.notify;
178
+ const key = {
179
+ remoteJid: chatId,
180
+ remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
181
+ remoteJidUsername: !isJidGroup(chatId)
182
+ ? stanza.attrs.peer_recipient_username || stanza.attrs.recipient_username
183
+ : undefined,
184
+ fromMe,
185
+ id: msgId,
186
+ participant,
187
+ participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
188
+ participantUsername: stanza.attrs.participant ? stanza.attrs.participant_username : undefined,
189
+ addressingMode: addressingContext.addressingMode,
190
+ ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
191
+ };
192
+ const fullMessage = {
193
+ key,
194
+ category: stanza.attrs.category,
195
+ messageTimestamp: +stanza.attrs.t,
196
+ pushName: pushname,
197
+ broadcast: isJidBroadcast(from)
198
+ };
199
+ if (key.fromMe) {
200
+ fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK;
134
201
  }
135
- }
136
- else {
137
- throw new Boom("Unknown message type", { data: stanza });
138
- }
139
- const pushname = stanza?.attrs?.notify;
140
- const key = {
141
- remoteJid: chatId,
142
- remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
143
- fromMe,
144
- id: msgId,
145
- participant,
146
- participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
147
- addressingMode: addressingContext.addressingMode,
148
- ...(msgType === "newsletter" && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
149
- };
150
- const fullMessage = {
151
- key,
152
- messageTimestamp: +stanza.attrs.t,
153
- pushName: pushname,
154
- broadcast: isJidBroadcast(from)
155
- };
156
- if (key.fromMe) {
157
- fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK;
158
- }
159
- return {
160
- fullMessage,
161
- author,
162
- sender: msgType === "chat" ? author : chatId
163
- };
202
+ return {
203
+ fullMessage,
204
+ author,
205
+ sender: msgType === 'chat' ? author : chatId
206
+ };
164
207
  }
165
- //=======================================================//
166
208
  export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
167
- const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
168
- return {
169
- fullMessage,
170
- category: stanza.attrs.category,
171
- author,
172
- async decrypt() {
173
- let decryptables = 0;
174
- if (Array.isArray(stanza.content)) {
175
- for (const { tag, attrs, content } of stanza.content) {
176
- if (tag === "verified_name" && content instanceof Uint8Array) {
177
- const cert = proto.VerifiedNameCertificate.decode(content);
178
- const details = proto.VerifiedNameCertificate.Details.decode(cert.details);
179
- fullMessage.verifiedBizName = details.verifiedName;
180
- }
181
- if (tag === "unavailable" && attrs.type === "view_once") {
182
- fullMessage.key.isViewOnce = true;
183
- }
184
- if (tag !== "enc" && tag !== "plaintext") {
185
- continue;
186
- }
187
- if (!(content instanceof Uint8Array)) {
188
- continue;
189
- }
190
- decryptables += 1;
191
- let msgBuffer;
192
- const decryptionJid = await getDecryptionJid(author, repository);
193
- if (tag !== "plaintext") {
194
- await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger);
195
- }
196
- try {
197
- const e2eType = tag === "plaintext" ? "plaintext" : attrs.type;
198
- switch (e2eType) {
199
- case "skmsg":
200
- msgBuffer = await repository.decryptGroupMessage({
201
- group: sender,
202
- authorJid: author,
203
- msg: content
204
- });
205
- break;
206
- case "pkmsg":
207
- case "msg":
208
- msgBuffer = await repository.decryptMessage({
209
- jid: decryptionJid,
210
- type: e2eType,
211
- ciphertext: content
212
- });
213
- break;
214
- case "plaintext":
215
- msgBuffer = content;
216
- break;
217
- default:
218
- throw new Error(`Unknown e2e type: ${e2eType}`);
219
- }
220
- let msg = proto.Message.decode(e2eType !== "plaintext" ? unpadRandomMax16(msgBuffer) : msgBuffer);
221
- msg = msg.deviceSentMessage?.message || msg;
222
- if (msg.senderKeyDistributionMessage) {
223
- try {
224
- await repository.processSenderKeyDistributionMessage({
225
- authorJid: author,
226
- item: msg.senderKeyDistributionMessage
227
- });
228
- }
229
- catch (err) {
230
- logger.error({ key: fullMessage.key, err }, "failed to process sender key distribution message");
231
- }
209
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
210
+ return {
211
+ fullMessage,
212
+ category: stanza.attrs.category,
213
+ author,
214
+ async decrypt() {
215
+ let decryptables = 0;
216
+ if (Array.isArray(stanza.content)) {
217
+ for (const { tag, attrs, content } of stanza.content) {
218
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
219
+ const cert = proto.VerifiedNameCertificate.decode(content);
220
+ const details = proto.VerifiedNameCertificate.Details.decode(cert.details);
221
+ fullMessage.verifiedBizName = details.verifiedName;
222
+ }
223
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
224
+ fullMessage.key.isViewOnce = true; // TODO: remove from here and add a STUB TYPE
225
+ }
226
+ if (attrs.count && tag === 'enc') {
227
+ fullMessage.retryCount = Number(attrs.count);
228
+ }
229
+ if (tag !== 'enc' && tag !== 'plaintext') {
230
+ continue;
231
+ }
232
+ if (!(content instanceof Uint8Array)) {
233
+ continue;
234
+ }
235
+ decryptables += 1;
236
+ let msgBuffer;
237
+ const decryptionJid = await getDecryptionJid(author, repository);
238
+ if (tag !== 'plaintext') {
239
+ // TODO: Handle hosted devices
240
+ await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger);
241
+ }
242
+ try {
243
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
244
+ switch (e2eType) {
245
+ case 'skmsg':
246
+ msgBuffer = await repository.decryptGroupMessage({
247
+ group: sender,
248
+ authorJid: author,
249
+ msg: content
250
+ });
251
+ break;
252
+ case 'pkmsg':
253
+ case 'msg':
254
+ msgBuffer = await repository.decryptMessage({
255
+ jid: decryptionJid,
256
+ type: e2eType,
257
+ ciphertext: content
258
+ });
259
+ break;
260
+ case 'plaintext':
261
+ msgBuffer = content;
262
+ break;
263
+ default:
264
+ throw new Error(`Unknown e2e type: ${e2eType}`);
265
+ }
266
+ let msg = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer);
267
+ msg = msg.deviceSentMessage?.message || msg;
268
+ if (msg.senderKeyDistributionMessage) {
269
+ //eslint-disable-next-line max-depth
270
+ try {
271
+ await repository.processSenderKeyDistributionMessage({
272
+ authorJid: author,
273
+ item: msg.senderKeyDistributionMessage
274
+ });
275
+ }
276
+ catch (err) {
277
+ logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message');
278
+ }
279
+ }
280
+ if (fullMessage.message) {
281
+ Object.assign(fullMessage.message, msg);
282
+ }
283
+ else {
284
+ fullMessage.message = msg;
285
+ }
286
+ }
287
+ catch (err) {
288
+ const errorContext = {
289
+ key: fullMessage.key,
290
+ err,
291
+ messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
292
+ sender,
293
+ author,
294
+ isSessionRecordError: isSessionRecordError(err)
295
+ };
296
+ logger.error(errorContext, 'failed to decrypt message');
297
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
298
+ fullMessage.messageStubParameters = [err.message.toString()];
299
+ }
300
+ }
232
301
  }
233
- if (fullMessage.message) {
234
- Object.assign(fullMessage.message, msg);
302
+ // if nothing was found to decrypt
303
+ if (!decryptables && !fullMessage.key?.isViewOnce) {
304
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
305
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT];
235
306
  }
236
- else {
237
- fullMessage.message = msg;
238
- }
239
- }
240
- catch (err) {
241
- const errorContext = {
242
- key: fullMessage.key,
243
- err,
244
- messageType: tag === "plaintext" ? "plaintext" : attrs.type,
245
- sender,
246
- author,
247
- isSessionRecordError: isSessionRecordError(err)
248
- };
249
- logger.error(errorContext, "failed to decrypt message");
250
- fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
251
- fullMessage.messageStubParameters = [err.message.toString()];
252
- }
253
307
  }
254
- }
255
- if (!decryptables) {
256
- fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
257
- fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT];
258
- }
259
- }
260
- };
308
+ };
261
309
  };
262
- //=======================================================//
310
+ /**
311
+ * Utility function to check if an error is related to missing session record
312
+ */
263
313
  function isSessionRecordError(error) {
264
- const errorMessage = error?.message || error?.toString() || "";
265
- return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern));
314
+ const errorMessage = error?.message || error?.toString() || '';
315
+ return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern));
266
316
  }
267
- //=======================================================//
@@ -0,0 +1,13 @@
1
+ export function makeEventBuffer(logger: any): {
2
+ process(handler: any): () => void;
3
+ emit(event: any, evData: any): any;
4
+ isBuffering(): boolean;
5
+ buffer: () => void;
6
+ flush: () => boolean;
7
+ createBufferedFunction(work: any): (...args: any[]) => Promise<any>;
8
+ on: (...args: any[]) => any;
9
+ off: (...args: any[]) => any;
10
+ removeAllListeners: (...args: any[]) => any;
11
+ destroy(): void;
12
+ };
13
+ //# sourceMappingURL=event-buffer.d.ts.map