@mrlegendbot/baileys 1.2.4 → 1.2.6

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 (214) 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/Menu/index.d.ts +42 -0
  8. package/lib/Menu/index.js +283 -0
  9. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  10. package/lib/Signal/Group/ciphertext-message.js +10 -9
  11. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  12. package/lib/Signal/Group/group-session-builder.js +22 -21
  13. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  14. package/lib/Signal/Group/group_cipher.js +69 -75
  15. package/lib/Signal/Group/index.d.ts +12 -0
  16. package/lib/Signal/Group/index.js +1 -0
  17. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  18. package/lib/Signal/Group/keyhelper.js +10 -9
  19. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  20. package/lib/Signal/Group/sender-chain-key.js +22 -21
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.js +60 -51
  23. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  24. package/lib/Signal/Group/sender-key-message.js +62 -56
  25. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  26. package/lib/Signal/Group/sender-key-name.js +40 -38
  27. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  28. package/lib/Signal/Group/sender-key-record.js +34 -33
  29. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  30. package/lib/Signal/Group/sender-key-state.js +76 -72
  31. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  32. package/lib/Signal/Group/sender-message-key.js +23 -22
  33. package/lib/Signal/libsignal.d.ts +5 -0
  34. package/lib/Signal/libsignal.js +405 -506
  35. package/lib/Signal/lid-mapping.d.ts +23 -0
  36. package/lib/Signal/lid-mapping.js +258 -276
  37. package/lib/Socket/Client/index.d.ts +3 -0
  38. package/lib/Socket/Client/index.js +1 -0
  39. package/lib/Socket/Client/types.d.ts +16 -0
  40. package/lib/Socket/Client/types.js +7 -6
  41. package/lib/Socket/Client/websocket.d.ts +13 -0
  42. package/lib/Socket/Client/websocket.js +49 -48
  43. package/lib/Socket/business.d.ts +217 -0
  44. package/lib/Socket/business.js +369 -349
  45. package/lib/Socket/chats.d.ts +125 -0
  46. package/lib/Socket/chats.js +1148 -1172
  47. package/lib/Socket/communities.d.ts +273 -0
  48. package/lib/Socket/communities.js +413 -473
  49. package/lib/Socket/groups.d.ts +161 -0
  50. package/lib/Socket/groups.js +331 -387
  51. package/lib/Socket/index.d.ts +267 -0
  52. package/lib/Socket/index.js +19 -6
  53. package/lib/Socket/messages-recv.d.ts +203 -0
  54. package/lib/Socket/messages-recv.js +1719 -1782
  55. package/lib/Socket/messages-send.d.ts +199 -0
  56. package/lib/Socket/messages-send.js +2451 -1504
  57. package/lib/Socket/mex.d.ts +3 -0
  58. package/lib/Socket/mex.js +35 -40
  59. package/lib/Socket/newsletter.d.ts +170 -0
  60. package/lib/Socket/newsletter.js +191 -239
  61. package/lib/Socket/socket.d.ts +59 -0
  62. package/lib/Socket/socket.js +923 -992
  63. package/lib/Types/Auth.d.ts +117 -0
  64. package/lib/Types/Auth.js +1 -0
  65. package/lib/Types/Bussines.d.ts +25 -0
  66. package/lib/Types/Bussines.js +1 -0
  67. package/lib/Types/Call.d.ts +15 -0
  68. package/lib/Types/Call.js +1 -0
  69. package/lib/Types/Chat.d.ts +124 -0
  70. package/lib/Types/Chat.js +8 -1
  71. package/lib/Types/Contact.d.ts +26 -0
  72. package/lib/Types/Contact.js +1 -0
  73. package/lib/Types/Events.d.ts +256 -0
  74. package/lib/Types/Events.js +2 -1
  75. package/lib/Types/GroupMetadata.d.ts +71 -0
  76. package/lib/Types/GroupMetadata.js +1 -0
  77. package/lib/Types/Label.d.ts +47 -0
  78. package/lib/Types/Label.js +22 -20
  79. package/lib/Types/LabelAssociation.d.ts +30 -0
  80. package/lib/Types/LabelAssociation.js +4 -2
  81. package/lib/Types/Message.d.ts +320 -0
  82. package/lib/Types/Message.js +5 -3
  83. package/lib/Types/Mex.d.ts +141 -0
  84. package/lib/Types/Mex.js +31 -26
  85. package/lib/Types/Product.d.ts +79 -0
  86. package/lib/Types/Product.js +1 -0
  87. package/lib/Types/Signal.d.ts +87 -0
  88. package/lib/Types/Signal.js +2 -1
  89. package/lib/Types/Socket.d.ts +136 -0
  90. package/lib/Types/Socket.js +3 -2
  91. package/lib/Types/State.d.ts +97 -0
  92. package/lib/Types/State.js +52 -4
  93. package/lib/Types/USync.d.ts +26 -0
  94. package/lib/Types/USync.js +1 -0
  95. package/lib/Types/index.d.ts +66 -0
  96. package/lib/Types/index.js +11 -10
  97. package/lib/Utils/auth-utils.d.ts +24 -0
  98. package/lib/Utils/auth-utils.js +277 -240
  99. package/lib/Utils/browser-utils.d.ts +4 -0
  100. package/lib/Utils/browser-utils.js +23 -20
  101. package/lib/Utils/business.d.ts +23 -0
  102. package/lib/Utils/business.js +204 -200
  103. package/lib/Utils/chat-utils.d.ts +100 -0
  104. package/lib/Utils/chat-utils.js +810 -836
  105. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  106. package/lib/Utils/companion-reg-client-utils.js +25 -23
  107. package/lib/Utils/crypto.d.ts +37 -0
  108. package/lib/Utils/crypto.js +86 -70
  109. package/lib/Utils/decode-wa-message.d.ts +66 -0
  110. package/lib/Utils/decode-wa-message.js +284 -277
  111. package/lib/Utils/event-buffer.d.ts +36 -0
  112. package/lib/Utils/event-buffer.js +595 -592
  113. package/lib/Utils/generics.d.ts +92 -0
  114. package/lib/Utils/generics.js +335 -312
  115. package/lib/Utils/history.d.ts +24 -0
  116. package/lib/Utils/history.js +115 -123
  117. package/lib/Utils/identity-change-handler.d.ts +44 -0
  118. package/lib/Utils/identity-change-handler.js +50 -0
  119. package/lib/Utils/index.d.ts +22 -0
  120. package/lib/Utils/index.js +2 -1
  121. package/lib/Utils/link-preview.d.ts +21 -0
  122. package/lib/Utils/link-preview.js +73 -74
  123. package/lib/Utils/logger.d.ts +12 -0
  124. package/lib/Utils/logger.js +2 -3
  125. package/lib/Utils/lt-hash.d.ts +8 -0
  126. package/lib/Utils/lt-hash.js +6 -0
  127. package/lib/Utils/make-mutex.d.ts +9 -0
  128. package/lib/Utils/make-mutex.js +27 -27
  129. package/lib/Utils/message-retry-manager.d.ts +115 -0
  130. package/lib/Utils/message-retry-manager.js +254 -213
  131. package/lib/Utils/messages-media.d.ts +133 -0
  132. package/lib/Utils/messages-media.js +715 -741
  133. package/lib/Utils/messages.d.ts +91 -0
  134. package/lib/Utils/messages.js +827 -791
  135. package/lib/Utils/noise-handler.d.ts +20 -0
  136. package/lib/Utils/noise-handler.js +187 -215
  137. package/lib/Utils/offline-node-processor.d.ts +17 -0
  138. package/lib/Utils/offline-node-processor.js +40 -0
  139. package/lib/Utils/pre-key-manager.d.ts +28 -0
  140. package/lib/Utils/pre-key-manager.js +98 -69
  141. package/lib/Utils/process-message.d.ts +60 -0
  142. package/lib/Utils/process-message.js +586 -617
  143. package/lib/Utils/reporting-utils.d.ts +11 -0
  144. package/lib/Utils/reporting-utils.js +234 -553
  145. package/lib/Utils/signal.d.ts +47 -0
  146. package/lib/Utils/signal.js +170 -217
  147. package/lib/Utils/stanza-ack.d.ts +11 -0
  148. package/lib/Utils/stanza-ack.js +35 -27
  149. package/lib/Utils/sync-action-utils.d.ts +19 -0
  150. package/lib/Utils/sync-action-utils.js +41 -37
  151. package/lib/Utils/tc-token-utils.d.ts +37 -0
  152. package/lib/Utils/tc-token-utils.js +141 -120
  153. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  154. package/lib/Utils/use-multi-file-auth-state.js +105 -87
  155. package/lib/Utils/validate-connection.d.ts +11 -0
  156. package/lib/Utils/validate-connection.js +188 -190
  157. package/lib/WABinary/constants.d.ts +28 -0
  158. package/lib/WABinary/constants.js +1294 -28
  159. package/lib/WABinary/decode.d.ts +7 -0
  160. package/lib/WABinary/decode.js +249 -245
  161. package/lib/WABinary/encode.d.ts +3 -0
  162. package/lib/WABinary/encode.js +206 -201
  163. package/lib/WABinary/generic-utils.d.ts +15 -0
  164. package/lib/WABinary/generic-utils.js +89 -86
  165. package/lib/WABinary/index.d.ts +6 -0
  166. package/lib/WABinary/index.js +1 -0
  167. package/lib/WABinary/jid-utils.d.ts +48 -0
  168. package/lib/WABinary/jid-utils.js +77 -68
  169. package/lib/WABinary/types.d.ts +19 -0
  170. package/lib/WABinary/types.js +1 -0
  171. package/lib/WAM/BinaryInfo.d.ts +9 -0
  172. package/lib/WAM/BinaryInfo.js +8 -7
  173. package/lib/WAM/constants.d.ts +40 -0
  174. package/lib/WAM/constants.js +22853 -19892
  175. package/lib/WAM/encode.d.ts +3 -0
  176. package/lib/WAM/encode.js +132 -121
  177. package/lib/WAM/index.d.ts +4 -0
  178. package/lib/WAM/index.js +1 -0
  179. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  180. package/lib/WAUSync/Protocols/USyncContactProtocol.js +43 -46
  181. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  182. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -47
  183. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  184. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -22
  185. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  186. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -30
  187. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  188. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +20 -19
  189. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  190. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +44 -53
  191. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  192. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -24
  193. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  194. package/lib/WAUSync/Protocols/index.js +1 -0
  195. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  196. package/lib/WAUSync/USyncQuery.js +88 -79
  197. package/lib/WAUSync/USyncUser.d.ts +17 -0
  198. package/lib/WAUSync/USyncUser.js +29 -28
  199. package/lib/WAUSync/index.d.ts +4 -0
  200. package/lib/WAUSync/index.js +1 -0
  201. package/lib/index.d.ts +12 -0
  202. package/lib/index.js +2 -2
  203. package/package.json +86 -22
  204. package/README.upstream.md +0 -1312
  205. package/WAProto/WAProto.json +0 -1
  206. package/WAProto/WAProto.proto +0 -6275
  207. package/WAProto/compiler.js +0 -550
  208. package/lib/Store/index.js +0 -8
  209. package/lib/Store/keyed-db.js +0 -108
  210. package/lib/Store/make-cache-manager-store.js +0 -70
  211. package/lib/Store/make-in-memory-store.js +0 -417
  212. package/lib/Store/make-ordered-dictionary.js +0 -69
  213. package/lib/Store/object-repository.js +0 -27
  214. package/lib/Utils/use-sqlite-auth-state.js +0 -162
@@ -0,0 +1,37 @@
1
+ import type { SignalKeyStoreWithTransaction } from '../Types/index.js';
2
+ import type { BinaryNode } from '../WABinary/index.js';
3
+ /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
4
+ export declare const TC_TOKEN_INDEX_KEY = "__index";
5
+ /** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
6
+ export declare function readTcTokenIndex(keys: SignalKeyStoreWithTransaction): Promise<string[]>;
7
+ /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
8
+ export declare function buildMergedTcTokenIndexWrite(keys: SignalKeyStoreWithTransaction, addedJids: Iterable<string>): Promise<{
9
+ [TC_TOKEN_INDEX_KEY]: {
10
+ token: Buffer;
11
+ };
12
+ }>;
13
+ export declare function isTcTokenExpired(timestamp: number | string | null | undefined): boolean;
14
+ export declare function shouldSendNewTcToken(senderTimestamp: number | undefined): boolean;
15
+ /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
16
+ export declare function resolveTcTokenJid(jid: string, getLIDForPN: (pn: string) => Promise<string | null>): Promise<string>;
17
+ /** Resolve target JID for issuing privacy token based on AB prop 14303 */
18
+ export declare function resolveIssuanceJid(jid: string, issueToLid: boolean, getLIDForPN: (pn: string) => Promise<string | null>, getPNForLID?: (lid: string) => Promise<string | null>): Promise<string>;
19
+ type TcTokenParams = {
20
+ jid: string;
21
+ baseContent?: BinaryNode[];
22
+ authState: {
23
+ keys: SignalKeyStoreWithTransaction;
24
+ };
25
+ getLIDForPN: (pn: string) => Promise<string | null>;
26
+ };
27
+ export declare function buildTcTokenFromJid({ authState, jid, baseContent, getLIDForPN }: TcTokenParams): Promise<BinaryNode[] | undefined>;
28
+ type StoreTcTokensParams = {
29
+ result: BinaryNode;
30
+ fallbackJid: string;
31
+ keys: SignalKeyStoreWithTransaction;
32
+ getLIDForPN: (pn: string) => Promise<string | null>;
33
+ onNewJidStored?: (jid: string) => void;
34
+ };
35
+ export declare function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }: StoreTcTokensParams): Promise<void>;
36
+ export {};
37
+ //# sourceMappingURL=tc-token-utils.d.ts.map
@@ -1,143 +1,164 @@
1
1
  import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidMetaAI, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary/index.js';
2
+ // Same phone-number pattern as WABinary's isJidBot, applied against the user
3
+ // part so the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
2
4
  const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
5
+ /**
6
+ * Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
7
+ * storage against malformed notifications — WA Web filters server-side but we
8
+ * defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
9
+ * Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
10
+ */
3
11
  function isRegularUser(jid) {
4
- if (!jid) return false;
5
- const user = jid.split('@')[0] ?? '';
6
- if (user === '0') return false;
7
- if (BOT_PHONE_REGEX.test(user)) return false;
8
- if (isJidMetaAI(jid)) return false;
9
- return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'));
12
+ if (!jid)
13
+ return false;
14
+ const user = jid.split('@')[0] ?? '';
15
+ if (user === '0')
16
+ return false; // PSA
17
+ if (BOT_PHONE_REGEX.test(user))
18
+ return false; // Bot by phone pattern
19
+ if (isJidMetaAI(jid))
20
+ return false; // MetaAI (@bot server)
21
+ return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'));
10
22
  }
11
- const TC_TOKEN_BUCKET_DURATION = 604800;
12
- const TC_TOKEN_NUM_BUCKETS = 4;
23
+ const TC_TOKEN_BUCKET_DURATION = 604800; // 7 days
24
+ const TC_TOKEN_NUM_BUCKETS = 4; // ~28-day rolling window
25
+ /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
13
26
  export const TC_TOKEN_INDEX_KEY = '__index';
27
+ /** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
14
28
  export async function readTcTokenIndex(keys) {
15
- const data = await keys.get('tctoken', [TC_TOKEN_INDEX_KEY]);
16
- const entry = data[TC_TOKEN_INDEX_KEY];
17
- if (!entry?.token?.length) return [];
18
- try {
19
- const parsed = JSON.parse(Buffer.from(entry.token).toString());
20
- if (!Array.isArray(parsed)) return [];
21
- return parsed.filter(j => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY);
22
- } catch {
23
- return [];
24
- }
29
+ const data = await keys.get('tctoken', [TC_TOKEN_INDEX_KEY]);
30
+ const entry = data[TC_TOKEN_INDEX_KEY];
31
+ if (!entry?.token?.length)
32
+ return [];
33
+ try {
34
+ const parsed = JSON.parse(Buffer.from(entry.token).toString());
35
+ if (!Array.isArray(parsed))
36
+ return [];
37
+ return parsed.filter((j) => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY);
38
+ }
39
+ catch {
40
+ return [];
41
+ }
25
42
  }
43
+ /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
26
44
  export async function buildMergedTcTokenIndexWrite(keys, addedJids) {
27
- const persisted = await readTcTokenIndex(keys);
28
- const merged = new Set(persisted);
29
- for (const jid of addedJids) {
30
- if (jid && jid !== TC_TOKEN_INDEX_KEY) merged.add(jid);
31
- }
32
- return {
33
- [TC_TOKEN_INDEX_KEY]: {
34
- token: Buffer.from(JSON.stringify([...merged]))
45
+ const persisted = await readTcTokenIndex(keys);
46
+ const merged = new Set(persisted);
47
+ for (const jid of addedJids) {
48
+ if (jid && jid !== TC_TOKEN_INDEX_KEY)
49
+ merged.add(jid);
35
50
  }
36
- };
51
+ return {
52
+ [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
53
+ };
37
54
  }
55
+ // WA Web has separate sender/receiver AB props for these but they're identical today
38
56
  export function isTcTokenExpired(timestamp) {
39
- if (timestamp === null || timestamp === undefined) return true;
40
- const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
41
- if (isNaN(ts)) return true;
42
- const now = Math.floor(Date.now() / 1000);
43
- const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
44
- const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
45
- const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
46
- return ts < cutoffTimestamp;
57
+ if (timestamp === null || timestamp === undefined)
58
+ return true;
59
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
60
+ if (isNaN(ts))
61
+ return true;
62
+ const now = Math.floor(Date.now() / 1000);
63
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
64
+ const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
65
+ const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
66
+ return ts < cutoffTimestamp;
47
67
  }
48
68
  export function shouldSendNewTcToken(senderTimestamp) {
49
- if (senderTimestamp === undefined) return true;
50
- const now = Math.floor(Date.now() / 1000);
51
- const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
52
- const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
53
- return currentBucket > senderBucket;
69
+ if (senderTimestamp === undefined)
70
+ return true;
71
+ const now = Math.floor(Date.now() / 1000);
72
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
73
+ const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
74
+ return currentBucket > senderBucket;
54
75
  }
76
+ /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
55
77
  export async function resolveTcTokenJid(jid, getLIDForPN) {
56
- if (isLidUser(jid)) return jid;
57
- const lid = await getLIDForPN(jid);
58
- return lid ?? jid;
59
- }
60
- export async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
61
- if (issueToLid) {
62
- if (isLidUser(jid)) return jid;
78
+ if (isLidUser(jid))
79
+ return jid;
63
80
  const lid = await getLIDForPN(jid);
64
81
  return lid ?? jid;
65
- }
66
- if (!isLidUser(jid)) return jid;
67
- if (getPNForLID) {
68
- const pn = await getPNForLID(jid);
69
- return pn ?? jid;
70
- }
71
- return jid;
72
82
  }
73
- export async function buildTcTokenFromJid({
74
- authState,
75
- jid,
76
- baseContent = [],
77
- getLIDForPN
78
- }) {
79
- try {
80
- const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
81
- const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
82
- const entry = tcTokenData?.[storageJid];
83
- const tcTokenBuffer = entry?.token;
84
- const timestamp = entry?.timestamp;
85
- if (!tcTokenBuffer?.length || timestamp === undefined || isTcTokenExpired(timestamp)) {
86
- if (tcTokenBuffer) {
87
- const cleared = entry?.senderTimestamp !== undefined ? {
88
- token: Buffer.alloc(0),
89
- senderTimestamp: entry.senderTimestamp
90
- } : null;
91
- await authState.keys.set({
92
- tctoken: {
93
- [storageJid]: cleared
94
- }
95
- });
96
- }
97
- return baseContent.length > 0 ? baseContent : undefined;
83
+ /** Resolve target JID for issuing privacy token based on AB prop 14303 */
84
+ export async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
85
+ if (issueToLid) {
86
+ if (isLidUser(jid))
87
+ return jid;
88
+ const lid = await getLIDForPN(jid);
89
+ return lid ?? jid;
90
+ }
91
+ if (!isLidUser(jid))
92
+ return jid;
93
+ if (getPNForLID) {
94
+ const pn = await getPNForLID(jid);
95
+ return pn ?? jid;
98
96
  }
99
- baseContent.push({
100
- tag: 'tctoken',
101
- attrs: { t: String(timestamp) },
102
- content: tcTokenBuffer
103
- });
104
- return baseContent;
105
- } catch (error) {
106
- return baseContent.length > 0 ? baseContent : undefined;
107
- }
97
+ return jid;
108
98
  }
109
- export async function storeTcTokensFromIqResult({
110
- result,
111
- fallbackJid,
112
- keys,
113
- getLIDForPN,
114
- onNewJidStored
115
- }) {
116
- const tokensNode = getBinaryNodeChild(result, 'tokens');
117
- if (!tokensNode) return;
118
- const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
119
- for (const tokenNode of tokenNodes) {
120
- if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
121
- continue;
99
+ export async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
100
+ try {
101
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
102
+ const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
103
+ const entry = tcTokenData?.[storageJid];
104
+ const tcTokenBuffer = entry?.token;
105
+ const timestamp = entry?.timestamp;
106
+ if (!tcTokenBuffer?.length || timestamp === undefined || isTcTokenExpired(timestamp)) {
107
+ if (tcTokenBuffer) {
108
+ // Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
109
+ // after we drop the unusable peer token. Only wipe the record entirely when
110
+ // there's nothing worth keeping.
111
+ const cleared = entry?.senderTimestamp !== undefined
112
+ ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
113
+ : null;
114
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } });
115
+ }
116
+ return baseContent.length > 0 ? baseContent : undefined;
117
+ }
118
+ baseContent.push({
119
+ tag: 'tctoken',
120
+ attrs: { t: String(timestamp) },
121
+ content: tcTokenBuffer
122
+ });
123
+ return baseContent;
124
+ }
125
+ catch (error) {
126
+ return baseContent.length > 0 ? baseContent : undefined;
122
127
  }
123
- const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid);
124
- if (!isRegularUser(rawJid)) continue;
125
- const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
126
- const existingTcData = await keys.get('tctoken', [storageJid]);
127
- const existingEntry = existingTcData[storageJid];
128
- const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
129
- const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
130
- if (!incomingTs) continue;
131
- if (existingTs > 0 && existingTs > incomingTs) continue;
132
- await keys.set({
133
- tctoken: {
134
- [storageJid]: {
135
- ...existingEntry,
136
- token: Buffer.from(tokenNode.content),
137
- timestamp: tokenNode.attrs.t
128
+ }
129
+ export async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
130
+ const tokensNode = getBinaryNodeChild(result, 'tokens');
131
+ if (!tokensNode)
132
+ return;
133
+ const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
134
+ for (const tokenNode of tokenNodes) {
135
+ if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
136
+ continue;
138
137
  }
139
- }
140
- });
141
- onNewJidStored?.(storageJid);
142
- }
138
+ // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
139
+ const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid);
140
+ if (!isRegularUser(rawJid))
141
+ continue;
142
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
143
+ const existingTcData = await keys.get('tctoken', [storageJid]);
144
+ const existingEntry = existingTcData[storageJid];
145
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
146
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
147
+ // timestamp-less tokens would be immediately expired
148
+ if (!incomingTs)
149
+ continue;
150
+ if (existingTs > 0 && existingTs > incomingTs)
151
+ continue;
152
+ await keys.set({
153
+ tctoken: {
154
+ [storageJid]: {
155
+ ...existingEntry,
156
+ token: Buffer.from(tokenNode.content),
157
+ timestamp: tokenNode.attrs.t
158
+ }
159
+ }
160
+ });
161
+ onNewJidStored?.(storageJid);
162
+ }
143
163
  }
164
+ //# sourceMappingURL=tc-token-utils.js.map
@@ -0,0 +1,13 @@
1
+ import type { AuthenticationState } from '../Types/index.js';
2
+ /**
3
+ * stores the full authentication state in a single folder.
4
+ * Far more efficient than singlefileauthstate
5
+ *
6
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
7
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
8
+ * */
9
+ export declare const useMultiFileAuthState: (folder: string) => Promise<{
10
+ state: AuthenticationState;
11
+ saveCreds: () => Promise<void>;
12
+ }>;
13
+ //# sourceMappingURL=use-multi-file-auth-state.d.ts.map
@@ -1,103 +1,121 @@
1
1
  import { Mutex } from 'async-mutex';
2
2
  import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises';
3
3
  import { join } from 'path';
4
- import { proto } from '../../WAProto/compiler.js';
4
+ import { proto } from '../../WAProto/index.js';
5
5
  import { initAuthCreds } from './auth-utils.js';
6
6
  import { BufferJSON } from './generics.js';
7
+ // We need to lock files due to the fact that we are using async functions to read and write files
8
+ // https://github.com/WhiskeySockets/Baileys/issues/794
9
+ // https://github.com/nodejs/node/issues/26338
10
+ // Use a Map to store mutexes for each file path
7
11
  const fileLocks = new Map();
8
- const getFileLock = path => {
9
- let mutex = fileLocks.get(path);
10
- if (!mutex) {
11
- mutex = new Mutex();
12
- fileLocks.set(path, mutex);
13
- }
14
- return mutex;
12
+ // Get or create a mutex for a specific file path
13
+ const getFileLock = (path) => {
14
+ let mutex = fileLocks.get(path);
15
+ if (!mutex) {
16
+ mutex = new Mutex();
17
+ fileLocks.set(path, mutex);
18
+ }
19
+ return mutex;
15
20
  };
16
- export const useMultiFileAuthState = async folder => {
17
- const writeData = async (data, file) => {
18
- const filePath = join(folder, fixFileName(file));
19
- const mutex = getFileLock(filePath);
20
- return mutex.acquire().then(async release => {
21
- try {
22
- await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer));
23
- } finally {
24
- release();
25
- }
26
- });
27
- };
28
- const readData = async file => {
29
- try {
30
- const filePath = join(folder, fixFileName(file));
31
- const mutex = getFileLock(filePath);
32
- return await mutex.acquire().then(async release => {
21
+ /**
22
+ * stores the full authentication state in a single folder.
23
+ * Far more efficient than singlefileauthstate
24
+ *
25
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
26
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
27
+ * */
28
+ export const useMultiFileAuthState = async (folder) => {
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ const writeData = async (data, file) => {
31
+ const filePath = join(folder, fixFileName(file));
32
+ const mutex = getFileLock(filePath);
33
+ return mutex.acquire().then(async (release) => {
34
+ try {
35
+ await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer));
36
+ }
37
+ finally {
38
+ release();
39
+ }
40
+ });
41
+ };
42
+ const readData = async (file) => {
33
43
  try {
34
- const data = await readFile(filePath, {
35
- encoding: 'utf-8'
36
- });
37
- return JSON.parse(data, BufferJSON.reviver);
38
- } finally {
39
- release();
44
+ const filePath = join(folder, fixFileName(file));
45
+ const mutex = getFileLock(filePath);
46
+ return await mutex.acquire().then(async (release) => {
47
+ try {
48
+ const data = await readFile(filePath, { encoding: 'utf-8' });
49
+ return JSON.parse(data, BufferJSON.reviver);
50
+ }
51
+ finally {
52
+ release();
53
+ }
54
+ });
40
55
  }
41
- });
42
- } catch (error) {
43
- return null;
44
- }
45
- };
46
- const removeData = async file => {
47
- try {
48
- const filePath = join(folder, fixFileName(file));
49
- const mutex = getFileLock(filePath);
50
- return mutex.acquire().then(async release => {
56
+ catch (error) {
57
+ return null;
58
+ }
59
+ };
60
+ const removeData = async (file) => {
51
61
  try {
52
- await unlink(filePath);
53
- } catch {} finally {
54
- release();
62
+ const filePath = join(folder, fixFileName(file));
63
+ const mutex = getFileLock(filePath);
64
+ return mutex.acquire().then(async (release) => {
65
+ try {
66
+ await unlink(filePath);
67
+ }
68
+ catch {
69
+ }
70
+ finally {
71
+ release();
72
+ }
73
+ });
55
74
  }
56
- });
57
- } catch {}
58
- };
59
- const folderInfo = await stat(folder).catch(() => {});
60
- if (folderInfo) {
61
- if (!folderInfo.isDirectory()) {
62
- throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
75
+ catch { }
76
+ };
77
+ const folderInfo = await stat(folder).catch(() => { });
78
+ if (folderInfo) {
79
+ if (!folderInfo.isDirectory()) {
80
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
81
+ }
82
+ }
83
+ else {
84
+ await mkdir(folder, { recursive: true });
63
85
  }
64
- } else {
65
- await mkdir(folder, {
66
- recursive: true
67
- });
68
- }
69
- const fixFileName = file => file?.replace(/\//g, '__')?.replace(/:/g, '-');
70
- const creds = (await readData('creds.json')) || initAuthCreds();
71
- return {
72
- state: {
73
- creds,
74
- keys: {
75
- get: async (type, ids) => {
76
- const data = {};
77
- await Promise.all(ids.map(async id => {
78
- let value = await readData(`${type}-${id}.json`);
79
- if (type === 'app-state-sync-key' && value) {
80
- value = proto.Message.AppStateSyncKeyData.fromObject(value);
86
+ const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
87
+ const creds = (await readData('creds.json')) || initAuthCreds();
88
+ return {
89
+ state: {
90
+ creds,
91
+ keys: {
92
+ get: async (type, ids) => {
93
+ const data = {};
94
+ await Promise.all(ids.map(async (id) => {
95
+ let value = await readData(`${type}-${id}.json`);
96
+ if (type === 'app-state-sync-key' && value) {
97
+ value = proto.Message.AppStateSyncKeyData.fromObject(value);
98
+ }
99
+ data[id] = value;
100
+ }));
101
+ return data;
102
+ },
103
+ set: async (data) => {
104
+ const tasks = [];
105
+ for (const category in data) {
106
+ for (const id in data[category]) {
107
+ const value = data[category][id];
108
+ const file = `${category}-${id}.json`;
109
+ tasks.push(value ? writeData(value, file) : removeData(file));
110
+ }
111
+ }
112
+ await Promise.all(tasks);
113
+ }
81
114
  }
82
- data[id] = value;
83
- }));
84
- return data;
85
115
  },
86
- set: async data => {
87
- const tasks = [];
88
- for (const category in data) {
89
- for (const id in data[category]) {
90
- const value = data[category][id];
91
- const file = `${category}-${id}.json`;
92
- tasks.push(value ? writeData(value, file) : removeData(file));
93
- }
94
- }
95
- await Promise.all(tasks);
116
+ saveCreds: async () => {
117
+ return writeData(creds, 'creds.json');
96
118
  }
97
- }
98
- },
99
- saveCreds: async () => {
100
- return writeData(creds, 'creds.json');
101
- }
102
- };
119
+ };
103
120
  };
121
+ //# sourceMappingURL=use-multi-file-auth-state.js.map
@@ -0,0 +1,11 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { AuthenticationCreds, SignalCreds, SocketConfig } from '../Types/index.js';
3
+ import { type BinaryNode } from '../WABinary/index.js';
4
+ export declare const generateLoginNode: (userJid: string, config: SocketConfig) => proto.IClientPayload;
5
+ export declare const generateRegistrationNode: ({ registrationId, signedPreKey, signedIdentityKey }: SignalCreds, config: SocketConfig) => proto.ClientPayload;
6
+ export declare const configureSuccessfulPairing: (stanza: BinaryNode, { advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, "advSecretKey" | "signedIdentityKey" | "signalIdentities">) => {
7
+ creds: Partial<AuthenticationCreds>;
8
+ reply: BinaryNode;
9
+ };
10
+ export declare const encodeSignedDeviceIdentity: (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => Uint8Array<ArrayBufferLike>;
11
+ //# sourceMappingURL=validate-connection.d.ts.map