@vanzxy/baileys 1.4.0 → 1.4.2

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 (114) hide show
  1. package/cjs/WAProto/index.js +106053 -0
  2. package/cjs/lib/Defaults/index.js +168 -0
  3. package/cjs/lib/Signal/Group/ciphertext-message.js +16 -0
  4. package/cjs/lib/Signal/Group/group-session-builder.js +67 -0
  5. package/cjs/lib/Signal/Group/group_cipher.js +86 -0
  6. package/cjs/lib/Signal/Group/index.js +58 -0
  7. package/cjs/lib/Signal/Group/keyhelper.js +56 -0
  8. package/cjs/lib/Signal/Group/sender-chain-key.js +30 -0
  9. package/cjs/lib/Signal/Group/sender-key-distribution-message.js +67 -0
  10. package/cjs/lib/Signal/Group/sender-key-message.js +70 -0
  11. package/cjs/lib/Signal/Group/sender-key-name.js +52 -0
  12. package/cjs/lib/Signal/Group/sender-key-record.js +45 -0
  13. package/cjs/lib/Signal/Group/sender-key-state.js +88 -0
  14. package/cjs/lib/Signal/Group/sender-message-key.js +30 -0
  15. package/cjs/lib/Signal/libsignal.js +467 -0
  16. package/cjs/lib/Signal/lid-mapping.js +281 -0
  17. package/cjs/lib/Socket/Client/index.js +19 -0
  18. package/cjs/lib/Socket/Client/types.js +15 -0
  19. package/cjs/lib/Socket/Client/websocket.js +61 -0
  20. package/cjs/lib/Socket/business.js +384 -0
  21. package/cjs/lib/Socket/chats.js +1257 -0
  22. package/cjs/lib/Socket/communities.js +442 -0
  23. package/cjs/lib/Socket/dugong.js +753 -0
  24. package/cjs/lib/Socket/groups.js +360 -0
  25. package/cjs/lib/Socket/index.js +19 -0
  26. package/cjs/lib/Socket/messages-recv.js +1790 -0
  27. package/cjs/lib/Socket/messages-send.js +1390 -0
  28. package/cjs/lib/Socket/mex.js +46 -0
  29. package/cjs/lib/Socket/newsletter.js +340 -0
  30. package/cjs/lib/Socket/socket.js +1007 -0
  31. package/cjs/lib/Store/index.js +20 -0
  32. package/cjs/lib/Store/make-in-memory-store.js +438 -0
  33. package/cjs/lib/Store/make-ordered-dictionary.js +82 -0
  34. package/cjs/lib/Store/object-repository.js +28 -0
  35. package/cjs/lib/Types/Auth.js +3 -0
  36. package/cjs/lib/Types/Bussines.js +3 -0
  37. package/cjs/lib/Types/Call.js +3 -0
  38. package/cjs/lib/Types/Chat.js +11 -0
  39. package/cjs/lib/Types/Contact.js +3 -0
  40. package/cjs/lib/Types/Events.js +4 -0
  41. package/cjs/lib/Types/GroupMetadata.js +3 -0
  42. package/cjs/lib/Types/Label.js +26 -0
  43. package/cjs/lib/Types/LabelAssociation.js +8 -0
  44. package/cjs/lib/Types/Message.js +19 -0
  45. package/cjs/lib/Types/Mex.js +40 -0
  46. package/cjs/lib/Types/Product.js +3 -0
  47. package/cjs/lib/Types/RichType.js +24 -0
  48. package/cjs/lib/Types/Signal.js +4 -0
  49. package/cjs/lib/Types/Socket.js +4 -0
  50. package/cjs/lib/Types/State.js +54 -0
  51. package/cjs/lib/Types/USync.js +4 -0
  52. package/cjs/lib/Types/index.js +42 -0
  53. package/cjs/lib/Utils/MessageBuilder.js +2164 -0
  54. package/cjs/lib/Utils/auth-utils.js +312 -0
  55. package/cjs/lib/Utils/browser-utils.js +32 -0
  56. package/cjs/lib/Utils/business.js +245 -0
  57. package/cjs/lib/Utils/chat-utils.js +937 -0
  58. package/cjs/lib/Utils/companion-reg-client-utils.js +45 -0
  59. package/cjs/lib/Utils/crypto.js +196 -0
  60. package/cjs/lib/Utils/decode-wa-message.js +324 -0
  61. package/cjs/lib/Utils/event-buffer.js +643 -0
  62. package/cjs/lib/Utils/generics.js +429 -0
  63. package/cjs/lib/Utils/history.js +151 -0
  64. package/cjs/lib/Utils/identity-change-handler.js +56 -0
  65. package/cjs/lib/Utils/index.js +42 -0
  66. package/cjs/lib/Utils/link-preview.js +122 -0
  67. package/cjs/lib/Utils/logger.js +8 -0
  68. package/cjs/lib/Utils/lt-hash.js +62 -0
  69. package/cjs/lib/Utils/make-mutex.js +38 -0
  70. package/cjs/lib/Utils/message-retry-manager.js +267 -0
  71. package/cjs/lib/Utils/messages-media.js +933 -0
  72. package/cjs/lib/Utils/messages.js +2175 -0
  73. package/cjs/lib/Utils/noise-handler.js +205 -0
  74. package/cjs/lib/Utils/offline-node-processor.js +43 -0
  75. package/cjs/lib/Utils/pre-key-manager.js +113 -0
  76. package/cjs/lib/Utils/process-message.js +772 -0
  77. package/cjs/lib/Utils/reporting-utils.js +263 -0
  78. package/cjs/lib/Utils/rich-message-utils.js +439 -0
  79. package/cjs/lib/Utils/signal.js +214 -0
  80. package/cjs/lib/Utils/stanza-ack.js +41 -0
  81. package/cjs/lib/Utils/sync-action-utils.js +54 -0
  82. package/cjs/lib/Utils/tc-token-utils.js +174 -0
  83. package/cjs/lib/Utils/use-multi-file-auth-state.js +125 -0
  84. package/cjs/lib/Utils/use-single-file-auth-state.js +121 -0
  85. package/cjs/lib/Utils/use-sqlite-auth-state.js +182 -0
  86. package/cjs/lib/Utils/validate-connection.js +210 -0
  87. package/cjs/lib/WABinary/constants.js +1470 -0
  88. package/cjs/lib/WABinary/decode.js +301 -0
  89. package/cjs/lib/WABinary/encode.js +257 -0
  90. package/cjs/lib/WABinary/generic-utils.js +274 -0
  91. package/cjs/lib/WABinary/index.js +22 -0
  92. package/cjs/lib/WABinary/jid-utils.js +114 -0
  93. package/cjs/lib/WABinary/types.js +37 -0
  94. package/cjs/lib/WAM/BinaryInfo.js +14 -0
  95. package/cjs/lib/WAM/constants.js +22856 -0
  96. package/cjs/lib/WAM/encode.js +154 -0
  97. package/cjs/lib/WAM/index.js +20 -0
  98. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  99. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.js +67 -0
  100. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  101. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  102. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.js +29 -0
  103. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +55 -0
  104. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.js +33 -0
  105. package/cjs/lib/WAUSync/Protocols/index.js +24 -0
  106. package/cjs/lib/WAUSync/USyncQuery.js +126 -0
  107. package/cjs/lib/WAUSync/USyncUser.js +35 -0
  108. package/cjs/lib/WAUSync/index.js +20 -0
  109. package/cjs/lib/index.js +34 -0
  110. package/cjs/package.json +1 -0
  111. package/lib/Socket/messages-send.js +4 -3
  112. package/lib/Utils/messages.js +4 -1
  113. package/package.json +16 -5
  114. package/postinstall-banner.js +3 -2
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getNextPreKeysNode = exports.getNextPreKeys = exports.extractDeviceJids = exports.parseAndInjectE2ESessions = exports.extractE2ESessionFromRetryReceipt = exports.xmppPreKey = exports.xmppSignedPreKey = exports.generateOrGetPreKeys = exports.getPreKeys = exports.createSignalIdentity = void 0;
4
+ const index_js_1 = require("../Defaults/index.js");
5
+ const index_js_2 = require("../WABinary/index.js");
6
+ const crypto_js_1 = require("./crypto.js");
7
+ const generics_js_1 = require("./generics.js");
8
+ function chunk(array, size) {
9
+ const chunks = [];
10
+ for (let i = 0; i < array.length; i += size) {
11
+ chunks.push(array.slice(i, i + size));
12
+ }
13
+ return chunks;
14
+ }
15
+ const createSignalIdentity = (wid, accountSignatureKey) => {
16
+ return {
17
+ identifier: { name: wid, deviceId: 0 },
18
+ identifierKey: (0, crypto_js_1.generateSignalPubKey)(accountSignatureKey)
19
+ };
20
+ };
21
+ exports.createSignalIdentity = createSignalIdentity;
22
+ const getPreKeys = async ({ get }, min, limit) => {
23
+ const idList = [];
24
+ for (let id = min; id < limit; id++) {
25
+ idList.push(id.toString());
26
+ }
27
+ return get('pre-key', idList);
28
+ };
29
+ exports.getPreKeys = getPreKeys;
30
+ const generateOrGetPreKeys = (creds, range) => {
31
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
32
+ const remaining = range - avaliable;
33
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
34
+ const newPreKeys = {};
35
+ if (remaining > 0) {
36
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
37
+ newPreKeys[i] = crypto_js_1.Curve.generateKeyPair();
38
+ }
39
+ }
40
+ return {
41
+ newPreKeys,
42
+ lastPreKeyId,
43
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range]
44
+ };
45
+ };
46
+ exports.generateOrGetPreKeys = generateOrGetPreKeys;
47
+ const xmppSignedPreKey = (key) => ({
48
+ tag: 'skey',
49
+ attrs: {},
50
+ content: [
51
+ { tag: 'id', attrs: {}, content: (0, generics_js_1.encodeBigEndian)(key.keyId, 3) },
52
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
53
+ { tag: 'signature', attrs: {}, content: key.signature }
54
+ ]
55
+ });
56
+ exports.xmppSignedPreKey = xmppSignedPreKey;
57
+ const xmppPreKey = (pair, id) => ({
58
+ tag: 'key',
59
+ attrs: {},
60
+ content: [
61
+ { tag: 'id', attrs: {}, content: (0, generics_js_1.encodeBigEndian)(id, 3) },
62
+ { tag: 'value', attrs: {}, content: pair.public }
63
+ ]
64
+ });
65
+ exports.xmppPreKey = xmppPreKey;
66
+ const isValidUInt = (n) => typeof n === 'number' && Number.isInteger(n);
67
+ const extractE2ESessionFromRetryReceipt = (receipt) => {
68
+ const keysNode = (0, index_js_2.getBinaryNodeChild)(receipt, 'keys');
69
+ if (!keysNode)
70
+ return null;
71
+ const typeBuf = (0, index_js_2.getBinaryNodeChildBuffer)(keysNode, 'type');
72
+ if (!typeBuf || typeBuf.length !== 1 || typeBuf[0] !== index_js_1.KEY_BUNDLE_TYPE[0])
73
+ return null;
74
+ const identity = (0, index_js_2.getBinaryNodeChildBuffer)(keysNode, 'identity');
75
+ const skey = (0, index_js_2.getBinaryNodeChild)(keysNode, 'skey');
76
+ if (!identity || identity.length !== 32 || !skey)
77
+ return null;
78
+ const registrationId = (0, index_js_2.getBinaryNodeChildUInt)(receipt, 'registration', 4);
79
+ if (!isValidUInt(registrationId))
80
+ return null;
81
+ const signedPubKey = (0, index_js_2.getBinaryNodeChildBuffer)(skey, 'value');
82
+ const signedSig = (0, index_js_2.getBinaryNodeChildBuffer)(skey, 'signature');
83
+ const signedKeyId = (0, index_js_2.getBinaryNodeChildUInt)(skey, 'id', 3);
84
+ if (!signedPubKey || signedPubKey.length !== 32 || !signedSig || !isValidUInt(signedKeyId)) {
85
+ return null;
86
+ }
87
+ const preKeyNode = (0, index_js_2.getBinaryNodeChild)(keysNode, 'key');
88
+ let preKey;
89
+ if (preKeyNode) {
90
+ const preKeyPub = (0, index_js_2.getBinaryNodeChildBuffer)(preKeyNode, 'value');
91
+ const preKeyId = (0, index_js_2.getBinaryNodeChildUInt)(preKeyNode, 'id', 3);
92
+ if (!preKeyPub || preKeyPub.length !== 32 || !isValidUInt(preKeyId)) {
93
+ return null;
94
+ }
95
+ preKey = { keyId: preKeyId, publicKey: (0, crypto_js_1.generateSignalPubKey)(preKeyPub) };
96
+ }
97
+ return {
98
+ registrationId,
99
+ identityKey: (0, crypto_js_1.generateSignalPubKey)(identity),
100
+ signedPreKey: {
101
+ keyId: signedKeyId,
102
+ publicKey: (0, crypto_js_1.generateSignalPubKey)(signedPubKey),
103
+ signature: signedSig
104
+ },
105
+ preKey
106
+ };
107
+ };
108
+ exports.extractE2ESessionFromRetryReceipt = extractE2ESessionFromRetryReceipt;
109
+ const parseAndInjectE2ESessions = async (node, repository) => {
110
+ const extractKey = (key) => key
111
+ ? {
112
+ keyId: (0, index_js_2.getBinaryNodeChildUInt)(key, 'id', 3),
113
+ publicKey: (0, crypto_js_1.generateSignalPubKey)((0, index_js_2.getBinaryNodeChildBuffer)(key, 'value')),
114
+ signature: (0, index_js_2.getBinaryNodeChildBuffer)(key, 'signature')
115
+ }
116
+ : undefined;
117
+ const nodes = (0, index_js_2.getBinaryNodeChildren)((0, index_js_2.getBinaryNodeChild)(node, 'list'), 'user');
118
+ for (const node of nodes) {
119
+ (0, index_js_2.assertNodeErrorFree)(node);
120
+ }
121
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
122
+ // So Promise.all doesn't really help here,
123
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
124
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
125
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
126
+ const chunkSize = 100;
127
+ const chunks = chunk(nodes, chunkSize);
128
+ for (const nodesChunk of chunks) {
129
+ for (const node of nodesChunk) {
130
+ const signedKey = (0, index_js_2.getBinaryNodeChild)(node, 'skey');
131
+ const key = (0, index_js_2.getBinaryNodeChild)(node, 'key');
132
+ const identity = (0, index_js_2.getBinaryNodeChildBuffer)(node, 'identity');
133
+ const jid = node.attrs.jid;
134
+ const registrationId = (0, index_js_2.getBinaryNodeChildUInt)(node, 'registration', 4);
135
+ await repository.injectE2ESession({
136
+ jid,
137
+ session: {
138
+ registrationId: registrationId,
139
+ identityKey: (0, crypto_js_1.generateSignalPubKey)(identity),
140
+ signedPreKey: extractKey(signedKey),
141
+ preKey: extractKey(key)
142
+ }
143
+ });
144
+ }
145
+ }
146
+ };
147
+ exports.parseAndInjectE2ESessions = parseAndInjectE2ESessions;
148
+ const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
149
+ const { user: myUser, device: myDevice } = (0, index_js_2.jidDecode)(myJid);
150
+ const extracted = [];
151
+ for (const userResult of result) {
152
+ const { devices, id } = userResult;
153
+ const decoded = (0, index_js_2.jidDecode)(id), { user, server } = decoded;
154
+ let { domainType } = decoded;
155
+ const deviceList = devices?.deviceList;
156
+ if (!Array.isArray(deviceList))
157
+ continue;
158
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
159
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
160
+ ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
161
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
162
+ ) {
163
+ if (isHosted) {
164
+ domainType = domainType === index_js_2.WAJIDDomains.LID ? index_js_2.WAJIDDomains.HOSTED_LID : index_js_2.WAJIDDomains.HOSTED;
165
+ }
166
+ extracted.push({
167
+ user,
168
+ device,
169
+ domainType,
170
+ server: (0, index_js_2.getServerFromDomainType)(server, domainType)
171
+ });
172
+ }
173
+ }
174
+ }
175
+ return extracted;
176
+ };
177
+ exports.extractDeviceJids = extractDeviceJids;
178
+ /**
179
+ * get the next N keys for upload or processing
180
+ * @param count number of pre-keys to get or generate
181
+ */
182
+ const getNextPreKeys = async ({ creds, keys }, count) => {
183
+ const { newPreKeys, lastPreKeyId, preKeysRange } = (0, exports.generateOrGetPreKeys)(creds, count);
184
+ const update = {
185
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
186
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
187
+ };
188
+ await keys.set({ 'pre-key': newPreKeys });
189
+ const preKeys = await (0, exports.getPreKeys)(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
190
+ return { update, preKeys };
191
+ };
192
+ exports.getNextPreKeys = getNextPreKeys;
193
+ const getNextPreKeysNode = async (state, count) => {
194
+ const { creds } = state;
195
+ const { update, preKeys } = await (0, exports.getNextPreKeys)(state, count);
196
+ const node = {
197
+ tag: 'iq',
198
+ attrs: {
199
+ xmlns: 'encrypt',
200
+ type: 'set',
201
+ to: index_js_2.S_WHATSAPP_NET
202
+ },
203
+ content: [
204
+ { tag: 'registration', attrs: {}, content: (0, generics_js_1.encodeBigEndian)(creds.registrationId) },
205
+ { tag: 'type', attrs: {}, content: index_js_1.KEY_BUNDLE_TYPE },
206
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
207
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => (0, exports.xmppPreKey)(preKeys[+k], +k)) },
208
+ (0, exports.xmppSignedPreKey)(creds.signedPreKey)
209
+ ]
210
+ };
211
+ return { update, node };
212
+ };
213
+ exports.getNextPreKeysNode = getNextPreKeysNode;
214
+ //# sourceMappingURL=signal.js.map
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildAckStanza = buildAckStanza;
4
+ /**
5
+ * Builds an ACK stanza for a received node.
6
+ * Pure function -- no I/O, no side effects.
7
+ *
8
+ * Mirrors WhatsApp Web's ACK construction:
9
+ * - WAWebHandleMsgSendAck.sendAck / sendNack
10
+ * - WAWebCreateNackFromStanza.createNackFromStanza
11
+ */
12
+ function buildAckStanza(node, errorCode, meId) {
13
+ const { tag, attrs } = node;
14
+ const stanza = {
15
+ tag: 'ack',
16
+ attrs: {
17
+ id: attrs.id,
18
+ to: attrs.from,
19
+ class: tag
20
+ }
21
+ };
22
+ if (errorCode) {
23
+ stanza.attrs.error = errorCode.toString();
24
+ }
25
+ if (attrs.participant) {
26
+ stanza.attrs.participant = attrs.participant;
27
+ }
28
+ if (attrs.recipient) {
29
+ stanza.attrs.recipient = attrs.recipient;
30
+ }
31
+ // WA Web always includes type when present: `n.type || DROP_ATTR`
32
+ if (attrs.type) {
33
+ stanza.attrs.type = attrs.type;
34
+ }
35
+ // WA Web WAWebHandleMsgSendAck.sendAck/sendNack always include `from` for message-class ACKs
36
+ if (tag === 'message' && meId) {
37
+ stanza.attrs.from = meId;
38
+ }
39
+ return stanza;
40
+ }
41
+ //# sourceMappingURL=stanza-ack.js.map
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.emitSyncActionResults = exports.processContactAction = void 0;
4
+ const index_js_1 = require("../../WAProto/index.js");
5
+ const index_js_2 = require("../WABinary/index.js");
6
+ /**
7
+ * Process contactAction and return events to emit.
8
+ * Pure function - no side effects.
9
+ */
10
+ const processContactAction = (action, id, logger) => {
11
+ const results = [];
12
+ if (!id) {
13
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
14
+ return results;
15
+ }
16
+ const lidJid = action.lidJid;
17
+ const idIsPn = (0, index_js_2.isPnUser)(id);
18
+ // PN is in index[1], not in contactAction.pnJid which is usually null
19
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
20
+ // Always emit contacts.upsert
21
+ results.push({
22
+ event: 'contacts.upsert',
23
+ data: [
24
+ {
25
+ id,
26
+ name: action.fullName || action.firstName || action.username || undefined,
27
+ username: action.username || undefined,
28
+ lid: lidJid || undefined,
29
+ phoneNumber
30
+ }
31
+ ]
32
+ });
33
+ // Emit lid-mapping.update if we have valid LID-PN pair
34
+ if (lidJid && (0, index_js_2.isLidUser)(lidJid) && idIsPn) {
35
+ results.push({
36
+ event: 'lid-mapping.update',
37
+ data: { lid: lidJid, pn: id }
38
+ });
39
+ }
40
+ return results;
41
+ };
42
+ exports.processContactAction = processContactAction;
43
+ const emitSyncActionResults = (ev, results) => {
44
+ for (const result of results) {
45
+ if (result.event === 'contacts.upsert') {
46
+ ev.emit('contacts.upsert', result.data);
47
+ }
48
+ else {
49
+ ev.emit('lid-mapping.update', result.data);
50
+ }
51
+ }
52
+ };
53
+ exports.emitSyncActionResults = emitSyncActionResults;
54
+ //# sourceMappingURL=sync-action-utils.js.map
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TC_TOKEN_INDEX_KEY = void 0;
4
+ exports.readTcTokenIndex = readTcTokenIndex;
5
+ exports.buildMergedTcTokenIndexWrite = buildMergedTcTokenIndexWrite;
6
+ exports.isTcTokenExpired = isTcTokenExpired;
7
+ exports.shouldSendNewTcToken = shouldSendNewTcToken;
8
+ exports.resolveTcTokenJid = resolveTcTokenJid;
9
+ exports.resolveIssuanceJid = resolveIssuanceJid;
10
+ exports.buildTcTokenFromJid = buildTcTokenFromJid;
11
+ exports.storeTcTokensFromIqResult = storeTcTokensFromIqResult;
12
+ const index_js_1 = require("../WABinary/index.js");
13
+ // Same phone-number pattern as WABinary's isJidBot, applied against the user
14
+ // part so the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
15
+ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
16
+ /**
17
+ * Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
18
+ * storage against malformed notifications — WA Web filters server-side but we
19
+ * defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
20
+ * Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
21
+ */
22
+ function isRegularUser(jid) {
23
+ if (!jid)
24
+ return false;
25
+ const user = jid.split('@')[0] ?? '';
26
+ if (user === '0')
27
+ return false; // PSA
28
+ if (BOT_PHONE_REGEX.test(user))
29
+ return false; // Bot by phone pattern
30
+ if ((0, index_js_1.isJidMetaAI)(jid))
31
+ return false; // MetaAI (@bot server)
32
+ return !!((0, index_js_1.isPnUser)(jid) || (0, index_js_1.isLidUser)(jid) || (0, index_js_1.isHostedPnUser)(jid) || (0, index_js_1.isHostedLidUser)(jid) || jid.endsWith('@c.us'));
33
+ }
34
+ const TC_TOKEN_BUCKET_DURATION = 604800; // 7 days
35
+ const TC_TOKEN_NUM_BUCKETS = 4; // ~28-day rolling window
36
+ /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
37
+ exports.TC_TOKEN_INDEX_KEY = '__index';
38
+ /** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
39
+ async function readTcTokenIndex(keys) {
40
+ const data = await keys.get('tctoken', [exports.TC_TOKEN_INDEX_KEY]);
41
+ const entry = data[exports.TC_TOKEN_INDEX_KEY];
42
+ if (!entry?.token?.length)
43
+ return [];
44
+ try {
45
+ const parsed = JSON.parse(Buffer.from(entry.token).toString());
46
+ if (!Array.isArray(parsed))
47
+ return [];
48
+ return parsed.filter((j) => typeof j === 'string' && j.length > 0 && j !== exports.TC_TOKEN_INDEX_KEY);
49
+ }
50
+ catch {
51
+ return [];
52
+ }
53
+ }
54
+ /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
55
+ async function buildMergedTcTokenIndexWrite(keys, addedJids) {
56
+ const persisted = await readTcTokenIndex(keys);
57
+ const merged = new Set(persisted);
58
+ for (const jid of addedJids) {
59
+ if (jid && jid !== exports.TC_TOKEN_INDEX_KEY)
60
+ merged.add(jid);
61
+ }
62
+ return {
63
+ [exports.TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
64
+ };
65
+ }
66
+ // WA Web has separate sender/receiver AB props for these but they're identical today
67
+ function isTcTokenExpired(timestamp) {
68
+ if (timestamp === null || timestamp === undefined)
69
+ return true;
70
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
71
+ if (isNaN(ts))
72
+ return true;
73
+ const now = Math.floor(Date.now() / 1000);
74
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
75
+ const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
76
+ const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
77
+ return ts < cutoffTimestamp;
78
+ }
79
+ function shouldSendNewTcToken(senderTimestamp) {
80
+ if (senderTimestamp === undefined)
81
+ return true;
82
+ const now = Math.floor(Date.now() / 1000);
83
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
84
+ const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
85
+ return currentBucket > senderBucket;
86
+ }
87
+ /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
88
+ async function resolveTcTokenJid(jid, getLIDForPN) {
89
+ if ((0, index_js_1.isLidUser)(jid))
90
+ return jid;
91
+ const lid = await getLIDForPN(jid);
92
+ return lid ?? jid;
93
+ }
94
+ /** Resolve target JID for issuing privacy token based on AB prop 14303 */
95
+ async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
96
+ if (issueToLid) {
97
+ if ((0, index_js_1.isLidUser)(jid))
98
+ return jid;
99
+ const lid = await getLIDForPN(jid);
100
+ return lid ?? jid;
101
+ }
102
+ if (!(0, index_js_1.isLidUser)(jid))
103
+ return jid;
104
+ if (getPNForLID) {
105
+ const pn = await getPNForLID(jid);
106
+ return pn ?? jid;
107
+ }
108
+ return jid;
109
+ }
110
+ async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
111
+ try {
112
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
113
+ const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
114
+ const entry = tcTokenData?.[storageJid];
115
+ const tcTokenBuffer = entry?.token;
116
+ if (!tcTokenBuffer?.length || isTcTokenExpired(entry?.timestamp)) {
117
+ if (tcTokenBuffer) {
118
+ // Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
119
+ // after we drop the unusable peer token. Only wipe the record entirely when
120
+ // there's nothing worth keeping.
121
+ const cleared = entry?.senderTimestamp !== undefined
122
+ ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
123
+ : null;
124
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } });
125
+ }
126
+ return baseContent.length > 0 ? baseContent : undefined;
127
+ }
128
+ baseContent.push({
129
+ tag: 'tctoken',
130
+ attrs: {},
131
+ content: tcTokenBuffer
132
+ });
133
+ return baseContent;
134
+ }
135
+ catch (error) {
136
+ return baseContent.length > 0 ? baseContent : undefined;
137
+ }
138
+ }
139
+ async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
140
+ const tokensNode = (0, index_js_1.getBinaryNodeChild)(result, 'tokens');
141
+ if (!tokensNode)
142
+ return;
143
+ const tokenNodes = (0, index_js_1.getBinaryNodeChildren)(tokensNode, 'token');
144
+ for (const tokenNode of tokenNodes) {
145
+ if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
146
+ continue;
147
+ }
148
+ // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
149
+ const rawJid = (0, index_js_1.jidNormalizedUser)(fallbackJid || tokenNode.attrs.jid);
150
+ if (!isRegularUser(rawJid))
151
+ continue;
152
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
153
+ const existingTcData = await keys.get('tctoken', [storageJid]);
154
+ const existingEntry = existingTcData[storageJid];
155
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
156
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
157
+ // timestamp-less tokens would be immediately expired
158
+ if (!incomingTs)
159
+ continue;
160
+ if (existingTs > 0 && existingTs > incomingTs)
161
+ continue;
162
+ await keys.set({
163
+ tctoken: {
164
+ [storageJid]: {
165
+ ...existingEntry,
166
+ token: Buffer.from(tokenNode.content),
167
+ timestamp: tokenNode.attrs.t
168
+ }
169
+ }
170
+ });
171
+ onNewJidStored?.(storageJid);
172
+ }
173
+ }
174
+ //# sourceMappingURL=tc-token-utils.js.map
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useMultiFileAuthState = void 0;
4
+ const async_mutex_1 = require("async-mutex");
5
+ const promises_1 = require("fs/promises");
6
+ const path_1 = require("path");
7
+ const index_js_1 = require("../../WAProto/index.js");
8
+ const auth_utils_js_1 = require("./auth-utils.js");
9
+ const generics_js_1 = require("./generics.js");
10
+ // We need to lock files due to the fact that we are using async functions to read and write files
11
+ // https://github.com/WhiskeySockets/Baileys/issues/794
12
+ // https://github.com/nodejs/node/issues/26338
13
+ // Use a Map to store mutexes for each file path
14
+ const fileLocks = new Map();
15
+ // Get or create a mutex for a specific file path
16
+ const getFileLock = (path) => {
17
+ let mutex = fileLocks.get(path);
18
+ if (!mutex) {
19
+ mutex = new async_mutex_1.Mutex();
20
+ fileLocks.set(path, mutex);
21
+ }
22
+ return mutex;
23
+ };
24
+ /**
25
+ * stores the full authentication state in a single folder.
26
+ * Far more efficient than singlefileauthstate
27
+ *
28
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
29
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
30
+ * */
31
+ const useMultiFileAuthState = async (folder) => {
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ const writeData = async (data, file) => {
34
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
35
+ const mutex = getFileLock(filePath);
36
+ return mutex.acquire().then(async (release) => {
37
+ try {
38
+ await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_js_1.BufferJSON.replacer));
39
+ }
40
+ finally {
41
+ release();
42
+ }
43
+ });
44
+ };
45
+ const readData = async (file) => {
46
+ try {
47
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
48
+ const mutex = getFileLock(filePath);
49
+ return await mutex.acquire().then(async (release) => {
50
+ try {
51
+ const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
52
+ return JSON.parse(data, generics_js_1.BufferJSON.reviver);
53
+ }
54
+ finally {
55
+ release();
56
+ }
57
+ });
58
+ }
59
+ catch (error) {
60
+ return null;
61
+ }
62
+ };
63
+ const removeData = async (file) => {
64
+ try {
65
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
66
+ const mutex = getFileLock(filePath);
67
+ return mutex.acquire().then(async (release) => {
68
+ try {
69
+ await (0, promises_1.unlink)(filePath);
70
+ }
71
+ catch {
72
+ }
73
+ finally {
74
+ release();
75
+ }
76
+ });
77
+ }
78
+ catch { }
79
+ };
80
+ const folderInfo = await (0, promises_1.stat)(folder).catch(() => { });
81
+ if (folderInfo) {
82
+ if (!folderInfo.isDirectory()) {
83
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
84
+ }
85
+ }
86
+ else {
87
+ await (0, promises_1.mkdir)(folder, { recursive: true });
88
+ }
89
+ const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
90
+ const creds = (await readData('creds.json')) || (0, auth_utils_js_1.initAuthCreds)();
91
+ return {
92
+ state: {
93
+ creds,
94
+ keys: {
95
+ get: async (type, ids) => {
96
+ const data = {};
97
+ await Promise.all(ids.map(async (id) => {
98
+ let value = await readData(`${type}-${id}.json`);
99
+ if (type === 'app-state-sync-key' && value) {
100
+ value = index_js_1.proto.Message.AppStateSyncKeyData.fromObject(value);
101
+ }
102
+ data[id] = value;
103
+ }));
104
+ return data;
105
+ },
106
+ set: async (data) => {
107
+ const tasks = [];
108
+ for (const category in data) {
109
+ for (const id in data[category]) {
110
+ const value = data[category][id];
111
+ const file = `${category}-${id}.json`;
112
+ tasks.push(value ? writeData(value, file) : removeData(file));
113
+ }
114
+ }
115
+ await Promise.all(tasks);
116
+ }
117
+ }
118
+ },
119
+ saveCreds: async () => {
120
+ return writeData(creds, 'creds.json');
121
+ }
122
+ };
123
+ };
124
+ exports.useMultiFileAuthState = useMultiFileAuthState;
125
+ //# sourceMappingURL=use-multi-file-auth-state.js.map