@mrlegendbot/baileys 1.2.5 → 1.2.7

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 (212) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/fix-imports.js +85 -0
  3. package/WAProto/index.d.ts +14017 -0
  4. package/WAProto/index.js +97691 -2
  5. package/lib/Defaults/index.d.ts +75 -0
  6. package/lib/Defaults/index.js +92 -89
  7. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  8. package/lib/Signal/Group/ciphertext-message.js +10 -9
  9. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  10. package/lib/Signal/Group/group-session-builder.js +22 -21
  11. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  12. package/lib/Signal/Group/group_cipher.js +69 -75
  13. package/lib/Signal/Group/index.d.ts +12 -0
  14. package/lib/Signal/Group/index.js +1 -0
  15. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  16. package/lib/Signal/Group/keyhelper.js +10 -9
  17. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  18. package/lib/Signal/Group/sender-chain-key.js +22 -21
  19. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.js +60 -51
  21. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  22. package/lib/Signal/Group/sender-key-message.js +62 -56
  23. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  24. package/lib/Signal/Group/sender-key-name.js +40 -38
  25. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  26. package/lib/Signal/Group/sender-key-record.js +34 -33
  27. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  28. package/lib/Signal/Group/sender-key-state.js +76 -72
  29. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  30. package/lib/Signal/Group/sender-message-key.js +23 -22
  31. package/lib/Signal/libsignal.d.ts +5 -0
  32. package/lib/Signal/libsignal.js +405 -506
  33. package/lib/Signal/lid-mapping.d.ts +23 -0
  34. package/lib/Signal/lid-mapping.js +258 -276
  35. package/lib/Socket/Client/index.d.ts +3 -0
  36. package/lib/Socket/Client/index.js +1 -0
  37. package/lib/Socket/Client/types.d.ts +16 -0
  38. package/lib/Socket/Client/types.js +7 -6
  39. package/lib/Socket/Client/websocket.d.ts +13 -0
  40. package/lib/Socket/Client/websocket.js +49 -48
  41. package/lib/Socket/business.d.ts +217 -0
  42. package/lib/Socket/business.js +369 -349
  43. package/lib/Socket/chats.d.ts +125 -0
  44. package/lib/Socket/chats.js +1148 -1172
  45. package/lib/Socket/communities.d.ts +273 -0
  46. package/lib/Socket/communities.js +413 -473
  47. package/lib/Socket/groups.d.ts +161 -0
  48. package/lib/Socket/groups.js +331 -387
  49. package/lib/Socket/index.d.ts +260 -0
  50. package/lib/Socket/index.js +8 -6
  51. package/lib/Socket/messages-recv.d.ts +203 -0
  52. package/lib/Socket/messages-recv.js +1719 -1782
  53. package/lib/Socket/messages-send.d.ts +200 -0
  54. package/lib/Socket/messages-send.js +2508 -1384
  55. package/lib/Socket/mex.d.ts +3 -0
  56. package/lib/Socket/mex.js +35 -40
  57. package/lib/Socket/newsletter.d.ts +170 -0
  58. package/lib/Socket/newsletter.js +191 -239
  59. package/lib/Socket/socket.d.ts +59 -0
  60. package/lib/Socket/socket.js +923 -992
  61. package/lib/Types/Auth.d.ts +117 -0
  62. package/lib/Types/Auth.js +1 -0
  63. package/lib/Types/Bussines.d.ts +25 -0
  64. package/lib/Types/Bussines.js +1 -0
  65. package/lib/Types/Call.d.ts +15 -0
  66. package/lib/Types/Call.js +1 -0
  67. package/lib/Types/Chat.d.ts +124 -0
  68. package/lib/Types/Chat.js +8 -1
  69. package/lib/Types/Contact.d.ts +26 -0
  70. package/lib/Types/Contact.js +1 -0
  71. package/lib/Types/Events.d.ts +256 -0
  72. package/lib/Types/Events.js +2 -1
  73. package/lib/Types/GroupMetadata.d.ts +71 -0
  74. package/lib/Types/GroupMetadata.js +1 -0
  75. package/lib/Types/Label.d.ts +47 -0
  76. package/lib/Types/Label.js +22 -20
  77. package/lib/Types/LabelAssociation.d.ts +30 -0
  78. package/lib/Types/LabelAssociation.js +4 -2
  79. package/lib/Types/Message.d.ts +320 -0
  80. package/lib/Types/Message.js +5 -3
  81. package/lib/Types/Mex.d.ts +141 -0
  82. package/lib/Types/Mex.js +31 -26
  83. package/lib/Types/Product.d.ts +79 -0
  84. package/lib/Types/Product.js +1 -0
  85. package/lib/Types/Signal.d.ts +87 -0
  86. package/lib/Types/Signal.js +2 -1
  87. package/lib/Types/Socket.d.ts +136 -0
  88. package/lib/Types/Socket.js +3 -2
  89. package/lib/Types/State.d.ts +97 -0
  90. package/lib/Types/State.js +52 -4
  91. package/lib/Types/USync.d.ts +26 -0
  92. package/lib/Types/USync.js +1 -0
  93. package/lib/Types/index.d.ts +66 -0
  94. package/lib/Types/index.js +11 -10
  95. package/lib/Utils/auth-utils.d.ts +24 -0
  96. package/lib/Utils/auth-utils.js +277 -240
  97. package/lib/Utils/browser-utils.d.ts +4 -0
  98. package/lib/Utils/browser-utils.js +23 -20
  99. package/lib/Utils/business.d.ts +23 -0
  100. package/lib/Utils/business.js +204 -200
  101. package/lib/Utils/chat-utils.d.ts +100 -0
  102. package/lib/Utils/chat-utils.js +810 -836
  103. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  104. package/lib/Utils/companion-reg-client-utils.js +25 -23
  105. package/lib/Utils/crypto.d.ts +37 -0
  106. package/lib/Utils/crypto.js +86 -70
  107. package/lib/Utils/decode-wa-message.d.ts +66 -0
  108. package/lib/Utils/decode-wa-message.js +284 -277
  109. package/lib/Utils/event-buffer.d.ts +36 -0
  110. package/lib/Utils/event-buffer.js +595 -592
  111. package/lib/Utils/generics.d.ts +92 -0
  112. package/lib/Utils/generics.js +335 -312
  113. package/lib/Utils/history.d.ts +24 -0
  114. package/lib/Utils/history.js +115 -123
  115. package/lib/Utils/identity-change-handler.d.ts +44 -0
  116. package/lib/Utils/identity-change-handler.js +50 -0
  117. package/lib/Utils/index.d.ts +22 -0
  118. package/lib/Utils/index.js +2 -1
  119. package/lib/Utils/link-preview.d.ts +21 -0
  120. package/lib/Utils/link-preview.js +73 -74
  121. package/lib/Utils/logger.d.ts +12 -0
  122. package/lib/Utils/logger.js +2 -3
  123. package/lib/Utils/lt-hash.d.ts +8 -0
  124. package/lib/Utils/lt-hash.js +6 -0
  125. package/lib/Utils/make-mutex.d.ts +9 -0
  126. package/lib/Utils/make-mutex.js +27 -27
  127. package/lib/Utils/message-retry-manager.d.ts +115 -0
  128. package/lib/Utils/message-retry-manager.js +254 -213
  129. package/lib/Utils/messages-media.d.ts +133 -0
  130. package/lib/Utils/messages-media.js +715 -741
  131. package/lib/Utils/messages.d.ts +91 -0
  132. package/lib/Utils/messages.js +827 -791
  133. package/lib/Utils/noise-handler.d.ts +20 -0
  134. package/lib/Utils/noise-handler.js +187 -215
  135. package/lib/Utils/offline-node-processor.d.ts +17 -0
  136. package/lib/Utils/offline-node-processor.js +40 -0
  137. package/lib/Utils/pre-key-manager.d.ts +28 -0
  138. package/lib/Utils/pre-key-manager.js +98 -69
  139. package/lib/Utils/process-message.d.ts +60 -0
  140. package/lib/Utils/process-message.js +586 -617
  141. package/lib/Utils/reporting-utils.d.ts +11 -0
  142. package/lib/Utils/reporting-utils.js +234 -553
  143. package/lib/Utils/signal.d.ts +47 -0
  144. package/lib/Utils/signal.js +170 -217
  145. package/lib/Utils/stanza-ack.d.ts +11 -0
  146. package/lib/Utils/stanza-ack.js +35 -27
  147. package/lib/Utils/sync-action-utils.d.ts +19 -0
  148. package/lib/Utils/sync-action-utils.js +41 -37
  149. package/lib/Utils/tc-token-utils.d.ts +37 -0
  150. package/lib/Utils/tc-token-utils.js +141 -120
  151. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  152. package/lib/Utils/use-multi-file-auth-state.js +105 -87
  153. package/lib/Utils/validate-connection.d.ts +11 -0
  154. package/lib/Utils/validate-connection.js +188 -190
  155. package/lib/WABinary/constants.d.ts +28 -0
  156. package/lib/WABinary/constants.js +1294 -28
  157. package/lib/WABinary/decode.d.ts +7 -0
  158. package/lib/WABinary/decode.js +249 -245
  159. package/lib/WABinary/encode.d.ts +3 -0
  160. package/lib/WABinary/encode.js +206 -201
  161. package/lib/WABinary/generic-utils.d.ts +15 -0
  162. package/lib/WABinary/generic-utils.js +89 -86
  163. package/lib/WABinary/index.d.ts +6 -0
  164. package/lib/WABinary/index.js +1 -0
  165. package/lib/WABinary/jid-utils.d.ts +48 -0
  166. package/lib/WABinary/jid-utils.js +77 -68
  167. package/lib/WABinary/types.d.ts +19 -0
  168. package/lib/WABinary/types.js +1 -0
  169. package/lib/WAM/BinaryInfo.d.ts +9 -0
  170. package/lib/WAM/BinaryInfo.js +8 -7
  171. package/lib/WAM/constants.d.ts +40 -0
  172. package/lib/WAM/constants.js +22853 -19892
  173. package/lib/WAM/encode.d.ts +3 -0
  174. package/lib/WAM/encode.js +132 -121
  175. package/lib/WAM/index.d.ts +4 -0
  176. package/lib/WAM/index.js +1 -0
  177. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  178. package/lib/WAUSync/Protocols/USyncContactProtocol.js +43 -46
  179. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  180. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -47
  181. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  182. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -22
  183. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  184. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -30
  185. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  186. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +20 -19
  187. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  188. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +44 -53
  189. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  190. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -24
  191. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  192. package/lib/WAUSync/Protocols/index.js +1 -0
  193. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  194. package/lib/WAUSync/USyncQuery.js +88 -79
  195. package/lib/WAUSync/USyncUser.d.ts +17 -0
  196. package/lib/WAUSync/USyncUser.js +29 -28
  197. package/lib/WAUSync/index.d.ts +4 -0
  198. package/lib/WAUSync/index.js +1 -0
  199. package/lib/index.d.ts +12 -0
  200. package/lib/index.js +2 -2
  201. package/package.json +86 -22
  202. package/README.upstream.md +0 -1312
  203. package/WAProto/WAProto.json +0 -1
  204. package/WAProto/WAProto.proto +0 -6275
  205. package/WAProto/compiler.js +0 -550
  206. package/lib/Store/index.js +0 -8
  207. package/lib/Store/keyed-db.js +0 -108
  208. package/lib/Store/make-cache-manager-store.js +0 -70
  209. package/lib/Store/make-in-memory-store.js +0 -417
  210. package/lib/Store/make-ordered-dictionary.js +0 -69
  211. package/lib/Store/object-repository.js +0 -27
  212. package/lib/Utils/use-sqlite-auth-state.js +0 -162
@@ -0,0 +1,24 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { Chat, Contact, LIDMapping, WAMessage } from '../Types/index.js';
3
+ import type { ILogger } from './logger.js';
4
+ export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: RequestInit) => Promise<proto.HistorySync>;
5
+ export declare const processHistoryMessage: (item: proto.IHistorySync, logger?: ILogger) => {
6
+ chats: Chat[];
7
+ contacts: Contact[];
8
+ messages: WAMessage[];
9
+ lidPnMappings: LIDMapping[];
10
+ pastParticipants: proto.IPastParticipants[] | null | undefined;
11
+ syncType: proto.HistorySync.HistorySyncType | null | undefined;
12
+ progress: number | null | undefined;
13
+ };
14
+ export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: RequestInit, logger?: ILogger) => Promise<{
15
+ chats: Chat[];
16
+ contacts: Contact[];
17
+ messages: WAMessage[];
18
+ lidPnMappings: LIDMapping[];
19
+ pastParticipants: proto.IPastParticipants[] | null | undefined;
20
+ syncType: proto.HistorySync.HistorySyncType | null | undefined;
21
+ progress: number | null | undefined;
22
+ }>;
23
+ export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification;
24
+ //# sourceMappingURL=history.d.ts.map
@@ -1,142 +1,134 @@
1
1
  import { pipeline } from 'stream/promises';
2
2
  import { promisify } from 'util';
3
3
  import { createInflate, inflate } from 'zlib';
4
- import { proto } from '../../WAProto/compiler.js';
4
+ import { proto } from '../../WAProto/index.js';
5
5
  import { WAMessageStubType } from '../Types/index.js';
6
6
  import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary/index.js';
7
7
  import { toNumber } from './generics.js';
8
8
  import { normalizeMessageContent } from './messages.js';
9
9
  import { downloadContentFromMessage } from './messages-media.js';
10
10
  const inflatePromise = promisify(inflate);
11
- const extractPnFromMessages = messages => {
12
- for (const msgItem of messages) {
13
- const message = msgItem.message;
14
- if (!message?.key?.fromMe || !message.userReceipt?.length) {
15
- continue;
16
- }
17
- const userJid = message.userReceipt[0]?.userJid;
18
- if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
19
- return userJid;
11
+ const extractPnFromMessages = (messages) => {
12
+ for (const msgItem of messages) {
13
+ const message = msgItem.message;
14
+ // Only extract from outgoing messages (fromMe: true) in 1:1 chats
15
+ // because userReceipt.userJid is the recipient's JID
16
+ if (!message?.key?.fromMe || !message.userReceipt?.length) {
17
+ continue;
18
+ }
19
+ const userJid = message.userReceipt[0]?.userJid;
20
+ if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
21
+ return userJid;
22
+ }
20
23
  }
21
- }
22
- return undefined;
24
+ return undefined;
23
25
  };
24
26
  export const downloadHistory = async (msg, options) => {
25
- const stream = await downloadContentFromMessage(msg, 'md-msg-hist', {
26
- options
27
- });
28
- const inflater = createInflate();
29
- const chunks = [];
30
- inflater.on('data', chunk => chunks.push(chunk));
31
- await pipeline(stream, inflater);
32
- const buffer = Buffer.concat(chunks);
33
- const syncData = proto.HistorySync.decode(buffer);
34
- return syncData;
27
+ const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
28
+ // Pipe decrypted stream directly through zlib inflate
29
+ // This avoids allocating an intermediate buffer for the compressed data
30
+ const inflater = createInflate();
31
+ const chunks = [];
32
+ inflater.on('data', (chunk) => chunks.push(chunk));
33
+ await pipeline(stream, inflater);
34
+ const buffer = Buffer.concat(chunks);
35
+ const syncData = proto.HistorySync.decode(buffer);
36
+ return syncData;
35
37
  };
36
38
  export const processHistoryMessage = (item, logger) => {
37
- const messages = [];
38
- const contacts = [];
39
- const chats = [];
40
- const lidPnMappings = [];
41
- logger?.trace({
42
- progress: item.progress
43
- }, 'processing history of type ' + item.syncType?.toString());
44
- for (const m of item.phoneNumberToLidMappings || []) {
45
- if (m.lidJid && m.pnJid) {
46
- lidPnMappings.push({
47
- lid: m.lidJid,
48
- pn: m.pnJid
49
- });
50
- }
51
- }
52
- switch (item.syncType) {
53
- case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
54
- case proto.HistorySync.HistorySyncType.RECENT:
55
- case proto.HistorySync.HistorySyncType.FULL:
56
- case proto.HistorySync.HistorySyncType.ON_DEMAND:
57
- for (const chat of item.conversations) {
58
- contacts.push({
59
- id: chat.id,
60
- name: chat.displayName || chat.name || chat.username || undefined,
61
- username: chat.username || undefined,
62
- lid: chat.lidJid || chat.accountLid || undefined,
63
- phoneNumber: chat.pnJid || undefined
64
- });
65
- const chatId = chat.id;
66
- const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
67
- const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
68
- if (isLid && chat.pnJid) {
69
- lidPnMappings.push({
70
- lid: chatId,
71
- pn: chat.pnJid
72
- });
73
- } else if (isPn && chat.lidJid) {
74
- lidPnMappings.push({
75
- lid: chat.lidJid,
76
- pn: chatId
77
- });
78
- } else if (isLid && !chat.pnJid) {
79
- const pnFromReceipt = extractPnFromMessages(chat.messages || []);
80
- if (pnFromReceipt) {
81
- lidPnMappings.push({
82
- lid: chatId,
83
- pn: pnFromReceipt
84
- });
85
- }
86
- }
87
- const msgs = chat.messages || [];
88
- delete chat.messages;
89
- for (const item of msgs) {
90
- const message = item.message;
91
- messages.push(message);
92
- if (!chat.messages?.length) {
93
- chat.messages = [{
94
- message
95
- }];
96
- }
97
- if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
98
- chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
99
- }
100
- if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP || message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) && message.messageStubParameters?.[0]) {
101
- contacts.push({
102
- id: message.key.participant || message.key.remoteJid,
103
- verifiedName: message.messageStubParameters?.[0]
104
- });
105
- }
39
+ const messages = [];
40
+ const contacts = [];
41
+ const chats = [];
42
+ const lidPnMappings = [];
43
+ logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString());
44
+ // Extract LID-PN mappings for all sync types
45
+ for (const m of item.phoneNumberToLidMappings || []) {
46
+ if (m.lidJid && m.pnJid) {
47
+ lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
106
48
  }
107
- chats.push(chat);
108
- }
109
- break;
110
- case proto.HistorySync.HistorySyncType.PUSH_NAME:
111
- for (const c of item.pushnames) {
112
- contacts.push({
113
- id: c.id,
114
- notify: c.pushname
115
- });
116
- }
117
- break;
118
- }
119
- return {
120
- chats,
121
- contacts,
122
- messages,
123
- lidPnMappings,
124
- pastParticipants: item.pastParticipants,
125
- syncType: item.syncType,
126
- progress: item.progress
127
- };
49
+ }
50
+ switch (item.syncType) {
51
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
52
+ case proto.HistorySync.HistorySyncType.RECENT:
53
+ case proto.HistorySync.HistorySyncType.FULL:
54
+ case proto.HistorySync.HistorySyncType.ON_DEMAND:
55
+ for (const chat of item.conversations) {
56
+ contacts.push({
57
+ id: chat.id,
58
+ name: chat.displayName || chat.name || chat.username || undefined,
59
+ username: chat.username || undefined,
60
+ lid: chat.lidJid || chat.accountLid || undefined,
61
+ phoneNumber: chat.pnJid || undefined
62
+ });
63
+ const chatId = chat.id;
64
+ const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
65
+ const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
66
+ if (isLid && chat.pnJid) {
67
+ lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
68
+ }
69
+ else if (isPn && chat.lidJid) {
70
+ lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
71
+ }
72
+ else if (isLid && !chat.pnJid) {
73
+ // Fallback: extract PN from userReceipt in messages when pnJid is missing
74
+ const pnFromReceipt = extractPnFromMessages(chat.messages || []);
75
+ if (pnFromReceipt) {
76
+ lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
77
+ }
78
+ }
79
+ const msgs = chat.messages || [];
80
+ delete chat.messages;
81
+ for (const item of msgs) {
82
+ const message = item.message;
83
+ messages.push(message);
84
+ if (!chat.messages?.length) {
85
+ // keep only the most recent message in the chat array
86
+ chat.messages = [{ message }];
87
+ }
88
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
89
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
90
+ }
91
+ if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
92
+ message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
93
+ message.messageStubParameters?.[0]) {
94
+ contacts.push({
95
+ id: message.key.participant || message.key.remoteJid,
96
+ verifiedName: message.messageStubParameters?.[0]
97
+ });
98
+ }
99
+ }
100
+ chats.push(chat);
101
+ }
102
+ break;
103
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
104
+ for (const c of item.pushnames) {
105
+ contacts.push({ id: c.id, notify: c.pushname });
106
+ }
107
+ break;
108
+ }
109
+ return {
110
+ chats,
111
+ contacts,
112
+ messages,
113
+ lidPnMappings,
114
+ pastParticipants: item.pastParticipants,
115
+ syncType: item.syncType,
116
+ progress: item.progress
117
+ };
128
118
  };
129
119
  export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
130
- let historyMsg;
131
- if (msg.initialHistBootstrapInlinePayload) {
132
- historyMsg = proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload));
133
- } else {
134
- historyMsg = await downloadHistory(msg, options);
135
- }
136
- return processHistoryMessage(historyMsg, logger);
120
+ let historyMsg;
121
+ if (msg.initialHistBootstrapInlinePayload) {
122
+ historyMsg = proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload));
123
+ }
124
+ else {
125
+ historyMsg = await downloadHistory(msg, options);
126
+ }
127
+ return processHistoryMessage(historyMsg, logger);
137
128
  };
138
- export const getHistoryMsg = message => {
139
- const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
140
- const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
141
- return anyHistoryMsg;
129
+ export const getHistoryMsg = (message) => {
130
+ const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
131
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
132
+ return anyHistoryMsg;
142
133
  };
134
+ //# sourceMappingURL=history.js.map
@@ -0,0 +1,44 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { type BinaryNode } from '../WABinary/index.js';
3
+ import type { ILogger } from './logger.js';
4
+ export type IdentityChangeResult = {
5
+ action: 'no_identity_node';
6
+ } | {
7
+ action: 'invalid_notification';
8
+ } | {
9
+ action: 'skipped_companion_device';
10
+ device: number;
11
+ } | {
12
+ action: 'skipped_self_primary';
13
+ } | {
14
+ action: 'debounced';
15
+ } | {
16
+ action: 'skipped_offline';
17
+ } | {
18
+ action: 'skipped_no_session';
19
+ } | {
20
+ action: 'session_refreshed';
21
+ } | {
22
+ action: 'session_refresh_failed';
23
+ error: unknown;
24
+ };
25
+ export type IdentityChangeContext = {
26
+ meId: string | undefined;
27
+ meLid: string | undefined;
28
+ validateSession: (jid: string) => Promise<{
29
+ exists: boolean;
30
+ reason?: string;
31
+ }>;
32
+ assertSessions: (jids: string[], force?: boolean) => Promise<boolean>;
33
+ debounceCache: NodeCache<boolean>;
34
+ logger: ILogger;
35
+ /**
36
+ * Invoked right before `assertSessions` is called for an existing-session identity change.
37
+ * Used to kick off fire-and-forget side effects (e.g. tctoken re-issuance) in the same
38
+ * order WA Web does — i.e. before the E2E session is re-established.
39
+ * Must not throw; implementations are responsible for their own error handling.
40
+ */
41
+ onBeforeSessionRefresh?: (jid: string) => void;
42
+ };
43
+ export declare function handleIdentityChange(node: BinaryNode, ctx: IdentityChangeContext): Promise<IdentityChangeResult>;
44
+ //# sourceMappingURL=identity-change-handler.d.ts.map
@@ -0,0 +1,50 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { areJidsSameUser, getBinaryNodeChild, jidDecode } from '../WABinary/index.js';
3
+ import { isStringNullOrEmpty } from './generics.js';
4
+ export async function handleIdentityChange(node, ctx) {
5
+ const from = node.attrs.from;
6
+ if (!from) {
7
+ return { action: 'invalid_notification' };
8
+ }
9
+ const identityNode = getBinaryNodeChild(node, 'identity');
10
+ if (!identityNode) {
11
+ return { action: 'no_identity_node' };
12
+ }
13
+ ctx.logger.info({ jid: from }, 'identity changed');
14
+ const decoded = jidDecode(from);
15
+ if (decoded?.device && decoded.device !== 0) {
16
+ ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device');
17
+ return { action: 'skipped_companion_device', device: decoded.device };
18
+ }
19
+ const isSelfPrimary = ctx.meId && (areJidsSameUser(from, ctx.meId) || (ctx.meLid && areJidsSameUser(from, ctx.meLid)));
20
+ if (isSelfPrimary) {
21
+ ctx.logger.info({ jid: from }, 'self primary identity changed');
22
+ return { action: 'skipped_self_primary' };
23
+ }
24
+ if (ctx.debounceCache.get(from)) {
25
+ ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)');
26
+ return { action: 'debounced' };
27
+ }
28
+ ctx.debounceCache.set(from, true);
29
+ const isOfflineNotification = !isStringNullOrEmpty(node.attrs.offline);
30
+ const hasExistingSession = await ctx.validateSession(from);
31
+ if (!hasExistingSession.exists) {
32
+ ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh');
33
+ return { action: 'skipped_no_session' };
34
+ }
35
+ ctx.logger.debug({ jid: from }, 'old session exists, will refresh session');
36
+ if (isOfflineNotification) {
37
+ ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing');
38
+ return { action: 'skipped_offline' };
39
+ }
40
+ ctx.onBeforeSessionRefresh?.(from);
41
+ try {
42
+ await ctx.assertSessions([from], true);
43
+ return { action: 'session_refreshed' };
44
+ }
45
+ catch (error) {
46
+ ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change');
47
+ return { action: 'session_refresh_failed', error };
48
+ }
49
+ }
50
+ //# sourceMappingURL=identity-change-handler.js.map
@@ -0,0 +1,22 @@
1
+ export * from './generics.js';
2
+ export * from './decode-wa-message.js';
3
+ export * from './messages.js';
4
+ export * from './messages-media.js';
5
+ export * from './validate-connection.js';
6
+ export * from './crypto.js';
7
+ export * from './signal.js';
8
+ export * from './noise-handler.js';
9
+ export * from './history.js';
10
+ export * from './chat-utils.js';
11
+ export * from './lt-hash.js';
12
+ export * from './auth-utils.js';
13
+ export * from './use-multi-file-auth-state.js';
14
+ export * from './link-preview.js';
15
+ export * from './event-buffer.js';
16
+ export * from './process-message.js';
17
+ export * from './message-retry-manager.js';
18
+ export * from './browser-utils.js';
19
+ export * from './companion-reg-client-utils.js';
20
+ export * from './identity-change-handler.js';
21
+ export * from './stanza-ack.js';
22
+ //# sourceMappingURL=index.d.ts.map
@@ -17,5 +17,6 @@ export * from './process-message.js';
17
17
  export * from './message-retry-manager.js';
18
18
  export * from './browser-utils.js';
19
19
  export * from './companion-reg-client-utils.js';
20
+ export * from './identity-change-handler.js';
20
21
  export * from './stanza-ack.js';
21
- export * from './use-sqlite-auth-state.js';
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,21 @@
1
+ import type { WAMediaUploadFunction, WAUrlInfo } from '../Types/index.js';
2
+ import type { ILogger } from './logger.js';
3
+ export type URLGenerationOptions = {
4
+ thumbnailWidth: number;
5
+ fetchOpts: {
6
+ /** Timeout in ms */
7
+ timeout: number;
8
+ proxyUrl?: string;
9
+ headers?: HeadersInit;
10
+ };
11
+ uploadImage?: WAMediaUploadFunction;
12
+ logger?: ILogger;
13
+ };
14
+ /**
15
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
16
+ * Return undefined if the fetch failed or no URL was found
17
+ * @param text first matched URL in text
18
+ * @returns the URL info required to generate link preview
19
+ */
20
+ export declare const getUrlInfo: (text: string, opts?: URLGenerationOptions) => Promise<WAUrlInfo | undefined>;
21
+ //# sourceMappingURL=link-preview.d.ts.map
@@ -1,86 +1,85 @@
1
1
  import { prepareWAMessageMedia } from './messages.js';
2
2
  import { extractImageThumb, getHttpStream } from './messages-media.js';
3
3
  const THUMBNAIL_WIDTH_PX = 192;
4
- const getCompressedJpegThumbnail = async (url, {
5
- thumbnailWidth,
6
- fetchOpts
7
- }) => {
8
- const stream = await getHttpStream(url, fetchOpts);
9
- const result = await extractImageThumb(stream, thumbnailWidth);
10
- return result;
4
+ /** Fetches an image and generates a thumbnail for it */
5
+ const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
6
+ const stream = await getHttpStream(url, fetchOpts);
7
+ const result = await extractImageThumb(stream, thumbnailWidth);
8
+ return result;
11
9
  };
10
+ /**
11
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
12
+ * Return undefined if the fetch failed or no URL was found
13
+ * @param text first matched URL in text
14
+ * @returns the URL info required to generate link preview
15
+ */
12
16
  export const getUrlInfo = async (text, opts = {
13
- thumbnailWidth: THUMBNAIL_WIDTH_PX,
14
- fetchOpts: {
15
- timeout: 3000
16
- }
17
+ thumbnailWidth: THUMBNAIL_WIDTH_PX,
18
+ fetchOpts: { timeout: 3000 }
17
19
  }) => {
18
- try {
19
- let retries = 0;
20
- const maxRetry = 5;
21
- const {
22
- getLinkPreview
23
- } = await import('link-preview-js');
24
- let previewLink = text;
25
- if (!text.startsWith('https://') && !text.startsWith('http://')) {
26
- previewLink = 'https://' + previewLink;
27
- }
28
- const info = await getLinkPreview(previewLink, {
29
- ...opts.fetchOpts,
30
- followRedirects: 'follow',
31
- handleRedirects: (baseURL, forwardedURL) => {
32
- const urlObj = new URL(baseURL);
33
- const forwardedURLObj = new URL(forwardedURL);
34
- if (retries >= maxRetry) {
35
- return false;
20
+ try {
21
+ // retries
22
+ let retries = 0;
23
+ const maxRetry = 5;
24
+ const { getLinkPreview } = await import('link-preview-js');
25
+ let previewLink = text;
26
+ if (!text.startsWith('https://') && !text.startsWith('http://')) {
27
+ previewLink = 'https://' + previewLink;
36
28
  }
37
- if (forwardedURLObj.hostname === urlObj.hostname || forwardedURLObj.hostname === 'www.' + urlObj.hostname || 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
38
- retries += 1;
39
- return true;
40
- } else {
41
- return false;
42
- }
43
- },
44
- headers: opts.fetchOpts?.headers
45
- });
46
- if (info && 'title' in info && info.title) {
47
- const [image] = info.images;
48
- const urlInfo = {
49
- 'canonical-url': info.url,
50
- 'matched-text': text,
51
- title: info.title,
52
- description: info.description,
53
- originalThumbnailUrl: image
54
- };
55
- if (opts.uploadImage) {
56
- const {
57
- imageMessage
58
- } = await prepareWAMessageMedia({
59
- image: {
60
- url: image
61
- }
62
- }, {
63
- upload: opts.uploadImage,
64
- mediaTypeOverride: 'thumbnail-link',
65
- options: opts.fetchOpts
29
+ const info = await getLinkPreview(previewLink, {
30
+ ...opts.fetchOpts,
31
+ followRedirects: 'follow',
32
+ handleRedirects: (baseURL, forwardedURL) => {
33
+ const urlObj = new URL(baseURL);
34
+ const forwardedURLObj = new URL(forwardedURL);
35
+ if (retries >= maxRetry) {
36
+ return false;
37
+ }
38
+ if (forwardedURLObj.hostname === urlObj.hostname ||
39
+ forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
40
+ 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
41
+ retries += 1;
42
+ return true;
43
+ }
44
+ else {
45
+ return false;
46
+ }
47
+ },
48
+ headers: opts.fetchOpts?.headers
66
49
  });
67
- urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined;
68
- urlInfo.highQualityThumbnail = imageMessage || undefined;
69
- } else {
70
- try {
71
- urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined;
72
- } catch (error) {
73
- opts.logger?.debug({
74
- err: error.stack,
75
- url: previewLink
76
- }, 'error in generating thumbnail');
50
+ if (info && 'title' in info && info.title) {
51
+ const [image] = info.images;
52
+ const urlInfo = {
53
+ 'canonical-url': info.url,
54
+ 'matched-text': text,
55
+ title: info.title,
56
+ description: info.description,
57
+ originalThumbnailUrl: image
58
+ };
59
+ if (opts.uploadImage) {
60
+ const { imageMessage } = await prepareWAMessageMedia({ image: { url: image } }, {
61
+ upload: opts.uploadImage,
62
+ mediaTypeOverride: 'thumbnail-link',
63
+ options: opts.fetchOpts
64
+ });
65
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined;
66
+ urlInfo.highQualityThumbnail = imageMessage || undefined;
67
+ }
68
+ else {
69
+ try {
70
+ urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined;
71
+ }
72
+ catch (error) {
73
+ opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
74
+ }
75
+ }
76
+ return urlInfo;
77
77
  }
78
- }
79
- return urlInfo;
80
78
  }
81
- } catch (error) {
82
- if (!error.message.includes('receive a valid')) {
83
- throw error;
79
+ catch (error) {
80
+ if (!error.message.includes('receive a valid')) {
81
+ throw error;
82
+ }
84
83
  }
85
- }
86
84
  };
85
+ //# sourceMappingURL=link-preview.js.map
@@ -0,0 +1,12 @@
1
+ export interface ILogger {
2
+ level: string;
3
+ child(obj: Record<string, unknown>): ILogger;
4
+ trace(obj: unknown, msg?: string): void;
5
+ debug(obj: unknown, msg?: string): void;
6
+ info(obj: unknown, msg?: string): void;
7
+ warn(obj: unknown, msg?: string): void;
8
+ error(obj: unknown, msg?: string): void;
9
+ }
10
+ declare const _default: import("pino").Logger<never, boolean>;
11
+ export default _default;
12
+ //# sourceMappingURL=logger.d.ts.map
@@ -1,4 +1,3 @@
1
1
  import P from 'pino';
2
- export default P({
3
- timestamp: () => `,"time":"${new Date().toJSON()}"`
4
- });
2
+ export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
3
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1,8 @@
1
+ import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
2
+ /**
3
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
4
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
5
+ * if the same series of mutations was made sequentially.
6
+ */
7
+ export declare const LT_HASH_ANTI_TAMPERING: LTHashAntiTampering;
8
+ //# sourceMappingURL=lt-hash.d.ts.map
@@ -1,2 +1,8 @@
1
1
  import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
2
+ /**
3
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
4
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
5
+ * if the same series of mutations was made sequentially.
6
+ */
2
7
  export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering();
8
+ //# sourceMappingURL=lt-hash.js.map
@@ -0,0 +1,9 @@
1
+ export declare const makeMutex: () => {
2
+ mutex<T>(code: () => Promise<T> | T): Promise<T>;
3
+ };
4
+ export type Mutex = ReturnType<typeof makeMutex>;
5
+ export declare const makeKeyedMutex: () => {
6
+ mutex<T>(key: string, task: () => Promise<T> | T): Promise<T>;
7
+ };
8
+ export type KeyedMutex = ReturnType<typeof makeKeyedMutex>;
9
+ //# sourceMappingURL=make-mutex.d.ts.map