@sgintokic/baileys 0.0.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.

Potentially problematic release.


This version of @sgintokic/baileys might be problematic. Click here for more details.

Files changed (106) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1097 -0
  3. package/WAProto/index.js +2 -0
  4. package/engine-requirements.js +1 -0
  5. package/lib/Defaults/index.js +155 -0
  6. package/lib/Signal/Group/ciphertext-message.js +11 -0
  7. package/lib/Signal/Group/group-session-builder.js +41 -0
  8. package/lib/Signal/Group/group_cipher.js +108 -0
  9. package/lib/Signal/Group/index.js +11 -0
  10. package/lib/Signal/Group/keyhelper.js +14 -0
  11. package/lib/Signal/Group/sender-chain-key.js +31 -0
  12. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  13. package/lib/Signal/Group/sender-key-message.js +79 -0
  14. package/lib/Signal/Group/sender-key-name.js +49 -0
  15. package/lib/Signal/Group/sender-key-record.js +46 -0
  16. package/lib/Signal/Group/sender-key-state.js +104 -0
  17. package/lib/Signal/Group/sender-message-key.js +29 -0
  18. package/lib/Signal/libsignal.js +485 -0
  19. package/lib/Signal/lid-mapping.js +291 -0
  20. package/lib/Socket/Client/index.js +2 -0
  21. package/lib/Socket/Client/types.js +10 -0
  22. package/lib/Socket/Client/websocket.js +64 -0
  23. package/lib/Socket/business.js +293 -0
  24. package/lib/Socket/chats.js +1068 -0
  25. package/lib/Socket/communities.js +476 -0
  26. package/lib/Socket/groups.js +383 -0
  27. package/lib/Socket/index.js +8 -0
  28. package/lib/Socket/messages-recv.js +1830 -0
  29. package/lib/Socket/messages-send.js +1462 -0
  30. package/lib/Socket/mex.js +55 -0
  31. package/lib/Socket/newsletter.js +277 -0
  32. package/lib/Socket/socket.js +1087 -0
  33. package/lib/Store/index.js +3 -0
  34. package/lib/Store/make-in-memory-store.js +517 -0
  35. package/lib/Store/make-ordered-dictionary.js +75 -0
  36. package/lib/Store/object-repository.js +23 -0
  37. package/lib/Types/Auth.js +1 -0
  38. package/lib/Types/Bussines.js +1 -0
  39. package/lib/Types/Call.js +1 -0
  40. package/lib/Types/Chat.js +7 -0
  41. package/lib/Types/Contact.js +1 -0
  42. package/lib/Types/Events.js +1 -0
  43. package/lib/Types/GroupMetadata.js +1 -0
  44. package/lib/Types/Label.js +24 -0
  45. package/lib/Types/LabelAssociation.js +6 -0
  46. package/lib/Types/Message.js +18 -0
  47. package/lib/Types/Newsletter.js +33 -0
  48. package/lib/Types/Product.js +1 -0
  49. package/lib/Types/Signal.js +1 -0
  50. package/lib/Types/Socket.js +2 -0
  51. package/lib/Types/State.js +15 -0
  52. package/lib/Types/USync.js +1 -0
  53. package/lib/Types/index.js +31 -0
  54. package/lib/Utils/auth-utils.js +293 -0
  55. package/lib/Utils/browser-utils.js +32 -0
  56. package/lib/Utils/business.js +245 -0
  57. package/lib/Utils/chat-utils.js +959 -0
  58. package/lib/Utils/crypto.js +133 -0
  59. package/lib/Utils/decode-wa-message.js +376 -0
  60. package/lib/Utils/event-buffer.js +620 -0
  61. package/lib/Utils/generics.js +417 -0
  62. package/lib/Utils/history.js +150 -0
  63. package/lib/Utils/identity-change-handler.js +63 -0
  64. package/lib/Utils/index.js +21 -0
  65. package/lib/Utils/link-preview.js +91 -0
  66. package/lib/Utils/logger.js +2 -0
  67. package/lib/Utils/lt-hash.js +6 -0
  68. package/lib/Utils/make-mutex.js +31 -0
  69. package/lib/Utils/message-retry-manager.js +240 -0
  70. package/lib/Utils/messages-media.js +901 -0
  71. package/lib/Utils/messages.js +2052 -0
  72. package/lib/Utils/noise-handler.js +229 -0
  73. package/lib/Utils/offline-node-processor.js +50 -0
  74. package/lib/Utils/pre-key-manager.js +119 -0
  75. package/lib/Utils/process-message.js +641 -0
  76. package/lib/Utils/reporting-utils.js +346 -0
  77. package/lib/Utils/signal.js +188 -0
  78. package/lib/Utils/stanza-ack.js +33 -0
  79. package/lib/Utils/sync-action-utils.js +53 -0
  80. package/lib/Utils/tc-token-utils.js +15 -0
  81. package/lib/Utils/use-multi-file-auth-state.js +116 -0
  82. package/lib/Utils/use-single-file-auth-state.js +94 -0
  83. package/lib/Utils/validate-connection.js +235 -0
  84. package/lib/WABinary/constants.js +1300 -0
  85. package/lib/WABinary/decode.js +258 -0
  86. package/lib/WABinary/encode.js +219 -0
  87. package/lib/WABinary/generic-utils.js +203 -0
  88. package/lib/WABinary/index.js +5 -0
  89. package/lib/WABinary/jid-utils.js +93 -0
  90. package/lib/WABinary/types.js +1 -0
  91. package/lib/WAM/BinaryInfo.js +9 -0
  92. package/lib/WAM/constants.js +20669 -0
  93. package/lib/WAM/encode.js +151 -0
  94. package/lib/WAM/index.js +3 -0
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +21 -0
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -0
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +29 -0
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +59 -0
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +21 -0
  101. package/lib/WAUSync/Protocols/index.js +4 -0
  102. package/lib/WAUSync/USyncQuery.js +103 -0
  103. package/lib/WAUSync/USyncUser.js +22 -0
  104. package/lib/WAUSync/index.js +3 -0
  105. package/lib/index.js +11 -0
  106. package/package.json +58 -0
@@ -0,0 +1,346 @@
1
+ import { createHmac } from "crypto";
2
+ import { proto } from "../../WAProto/index.js";
3
+ import { hkdf } from "./crypto.js";
4
+ const reportingFields = [
5
+ { f: 1 },
6
+ {
7
+ f: 3,
8
+ s: [
9
+ { f: 2 },
10
+ { f: 3 },
11
+ { f: 8 },
12
+ { f: 11 },
13
+ { f: 17, s: [{ f: 21 }, { f: 22 }] },
14
+ { f: 25 },
15
+ ],
16
+ },
17
+ { f: 4, s: [{ f: 1 }, { f: 16 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
18
+ {
19
+ f: 5,
20
+ s: [
21
+ { f: 3 },
22
+ { f: 4 },
23
+ { f: 5 },
24
+ { f: 16 },
25
+ { f: 17, s: [{ f: 21 }, { f: 22 }] },
26
+ ],
27
+ },
28
+ { f: 6, s: [{ f: 1 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 30 }] },
29
+ {
30
+ f: 7,
31
+ s: [
32
+ { f: 2 },
33
+ { f: 7 },
34
+ { f: 10 },
35
+ { f: 17, s: [{ f: 21 }, { f: 22 }] },
36
+ { f: 20 },
37
+ ],
38
+ },
39
+ {
40
+ f: 8,
41
+ s: [
42
+ { f: 2 },
43
+ { f: 7 },
44
+ { f: 9 },
45
+ { f: 17, s: [{ f: 21 }, { f: 22 }] },
46
+ { f: 21 },
47
+ ],
48
+ },
49
+ {
50
+ f: 9,
51
+ s: [
52
+ { f: 2 },
53
+ { f: 6 },
54
+ { f: 7 },
55
+ { f: 13 },
56
+ { f: 17, s: [{ f: 21 }, { f: 22 }] },
57
+ { f: 20 },
58
+ ],
59
+ },
60
+ { f: 12, s: [{ f: 1 }, { f: 2 }, { f: 14, m: true }, { f: 15 }] },
61
+ { f: 18, s: [{ f: 6 }, { f: 16 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
62
+ {
63
+ f: 26,
64
+ s: [
65
+ { f: 4 },
66
+ { f: 5 },
67
+ { f: 8 },
68
+ { f: 13 },
69
+ { f: 17, s: [{ f: 21 }, { f: 22 }] },
70
+ ],
71
+ },
72
+ {
73
+ f: 28,
74
+ s: [
75
+ { f: 1 },
76
+ { f: 2 },
77
+ { f: 4 },
78
+ { f: 5 },
79
+ { f: 6 },
80
+ { f: 7, s: [{ f: 21 }, { f: 22 }] },
81
+ ],
82
+ },
83
+ { f: 37, s: [{ f: 1, m: true }] },
84
+ {
85
+ f: 49,
86
+ s: [
87
+ { f: 2 },
88
+ { f: 3, s: [{ f: 1 }, { f: 2 }] },
89
+ { f: 5, s: [{ f: 21 }, { f: 22 }] },
90
+ { f: 8, s: [{ f: 1 }, { f: 2 }] },
91
+ ],
92
+ },
93
+ { f: 53, s: [{ f: 1, m: true }] },
94
+ { f: 55, s: [{ f: 1, m: true }] },
95
+ { f: 58, s: [{ f: 1, m: true }] },
96
+ { f: 59, s: [{ f: 1, m: true }] },
97
+ {
98
+ f: 60,
99
+ s: [
100
+ { f: 2 },
101
+ { f: 3, s: [{ f: 1 }, { f: 2 }] },
102
+ { f: 5, s: [{ f: 21 }, { f: 22 }] },
103
+ { f: 8, s: [{ f: 1 }, { f: 2 }] },
104
+ ],
105
+ },
106
+ {
107
+ f: 64,
108
+ s: [
109
+ { f: 2 },
110
+ { f: 3, s: [{ f: 1 }, { f: 2 }] },
111
+ { f: 5, s: [{ f: 21 }, { f: 22 }] },
112
+ { f: 8, s: [{ f: 1 }, { f: 2 }] },
113
+ ],
114
+ },
115
+ {
116
+ f: 66,
117
+ s: [
118
+ { f: 2 },
119
+ { f: 6 },
120
+ { f: 7 },
121
+ { f: 13 },
122
+ { f: 17, s: [{ f: 21 }, { f: 22 }] },
123
+ { f: 20 },
124
+ ],
125
+ },
126
+ { f: 74, s: [{ f: 1, m: true }] },
127
+ { f: 87, s: [{ f: 1, m: true }] },
128
+ {
129
+ f: 88,
130
+ s: [{ f: 1 }, { f: 2, s: [{ f: 1 }] }, { f: 3, s: [{ f: 21 }, { f: 22 }] }],
131
+ },
132
+ { f: 92, s: [{ f: 1, m: true }] },
133
+ { f: 93, s: [{ f: 1, m: true }] },
134
+ { f: 94, s: [{ f: 1, m: true }] },
135
+ ];
136
+ const compileReportingFields = (fields) => {
137
+ const map = new Map();
138
+ for (const f of fields) {
139
+ map.set(f.f, {
140
+ m: f.m,
141
+ children: f.s ? compileReportingFields(f.s) : undefined,
142
+ });
143
+ }
144
+ return map;
145
+ };
146
+ const compiledReportingFields = compileReportingFields(reportingFields);
147
+ const EMPTY_MAP = new Map();
148
+ const ENC_SECRET_REPORT_TOKEN = "Report Token";
149
+ const WIRE = { VARINT: 0, FIXED64: 1, BYTES: 2, FIXED32: 5 };
150
+ export const shouldIncludeReportingToken = (message) =>
151
+ !message.reactionMessage &&
152
+ !message.encReactionMessage &&
153
+ !message.encEventResponseMessage &&
154
+ !message.pollUpdateMessage;
155
+ const generateMsgSecretKey = (
156
+ modificationType,
157
+ origMsgId,
158
+ origMsgSender,
159
+ modificationSender,
160
+ origMsgSecret,
161
+ ) => {
162
+ const useCaseSecret = Buffer.concat([
163
+ Buffer.from(origMsgId, "utf8"),
164
+ Buffer.from(origMsgSender, "utf8"),
165
+ Buffer.from(modificationSender, "utf8"),
166
+ Buffer.from(modificationType, "utf8"),
167
+ ]);
168
+ return hkdf(origMsgSecret, 32, { info: useCaseSecret.toString("latin1") });
169
+ };
170
+ const extractReportingTokenContent = (data, cfg) => {
171
+ const out = [];
172
+ let i = 0;
173
+ while (i < data.length) {
174
+ const tag = decodeVarint(data, i);
175
+ if (!tag.ok) {
176
+ return null;
177
+ }
178
+ const fieldNum = tag.value >> 3;
179
+ const wireType = tag.value & 7;
180
+ const fieldStart = i;
181
+ i += tag.bytes;
182
+ const fieldCfg = cfg.get(fieldNum);
183
+ const pushSlice = (end) => {
184
+ if (end > data.length) {
185
+ return false;
186
+ }
187
+ out.push({ num: fieldNum, bytes: data.subarray(fieldStart, end) });
188
+ i = end;
189
+ return true;
190
+ };
191
+ const skip = (end) => {
192
+ if (end > data.length) {
193
+ return false;
194
+ }
195
+ i = end;
196
+ return true;
197
+ };
198
+ if (wireType === WIRE.VARINT) {
199
+ const v = decodeVarint(data, i);
200
+ if (!v.ok) {
201
+ return null;
202
+ }
203
+ const end = i + v.bytes;
204
+ if (!fieldCfg) {
205
+ if (!skip(end)) {
206
+ return null;
207
+ }
208
+ continue;
209
+ }
210
+ if (!pushSlice(end)) {
211
+ return null;
212
+ }
213
+ continue;
214
+ }
215
+ if (wireType === WIRE.FIXED64) {
216
+ const end = i + 8;
217
+ if (!fieldCfg) {
218
+ if (!skip(end)) {
219
+ return null;
220
+ }
221
+ continue;
222
+ }
223
+ if (!pushSlice(end)) {
224
+ return null;
225
+ }
226
+ continue;
227
+ }
228
+ if (wireType === WIRE.FIXED32) {
229
+ const end = i + 4;
230
+ if (!fieldCfg) {
231
+ if (!skip(end)) {
232
+ return null;
233
+ }
234
+ continue;
235
+ }
236
+ if (!pushSlice(end)) {
237
+ return null;
238
+ }
239
+ continue;
240
+ }
241
+ if (wireType === WIRE.BYTES) {
242
+ const len = decodeVarint(data, i);
243
+ if (!len.ok) {
244
+ return null;
245
+ }
246
+ const valStart = i + len.bytes;
247
+ const valEnd = valStart + len.value;
248
+ if (valEnd > data.length) {
249
+ return null;
250
+ }
251
+ if (!fieldCfg) {
252
+ i = valEnd;
253
+ continue;
254
+ }
255
+ if (fieldCfg.m || fieldCfg.children) {
256
+ const sub = extractReportingTokenContent(
257
+ data.subarray(valStart, valEnd),
258
+ fieldCfg.children ?? EMPTY_MAP,
259
+ );
260
+ if (sub === null) {
261
+ return null;
262
+ }
263
+ if (sub.length > 0) {
264
+ const newTag = encodeVarint(tag.value);
265
+ const newLen = encodeVarint(sub.length);
266
+ out.push({
267
+ num: fieldNum,
268
+ bytes: Buffer.concat([newTag, newLen, sub]),
269
+ });
270
+ }
271
+ i = valEnd;
272
+ continue;
273
+ }
274
+ out.push({ num: fieldNum, bytes: data.subarray(fieldStart, valEnd) });
275
+ i = valEnd;
276
+ continue;
277
+ }
278
+ return null;
279
+ }
280
+ if (out.length === 0) {
281
+ return Buffer.alloc(0);
282
+ }
283
+ out.sort((a, b) => a.num - b.num);
284
+ return Buffer.concat(out.map((f) => f.bytes));
285
+ };
286
+ const decodeVarint = (buffer, offset) => {
287
+ let value = 0;
288
+ let bytes = 0;
289
+ let shift = 0;
290
+ while (offset + bytes < buffer.length) {
291
+ const current = buffer[offset + bytes];
292
+ value |= (current & 127) << shift;
293
+ bytes++;
294
+ if ((current & 128) === 0) {
295
+ return { value: value, bytes: bytes, ok: true };
296
+ }
297
+ shift += 7;
298
+ if (shift > 35) {
299
+ return { value: 0, bytes: 0, ok: false };
300
+ }
301
+ }
302
+ return { value: 0, bytes: 0, ok: false };
303
+ };
304
+ const encodeVarint = (value) => {
305
+ const parts = [];
306
+ let remaining = value >>> 0;
307
+ while (remaining > 127) {
308
+ parts.push((remaining & 127) | 128);
309
+ remaining >>>= 7;
310
+ }
311
+ parts.push(remaining);
312
+ return Buffer.from(parts);
313
+ };
314
+ export const getMessageReportingToken = async (msgProtobuf, message, key) => {
315
+ const msgSecret = message.messageContextInfo?.messageSecret;
316
+ if (!msgSecret || !key.id) {
317
+ return null;
318
+ }
319
+ const from = key.fromMe ? key.remoteJid : key.participant || key.remoteJid;
320
+ const to = key.fromMe ? key.participant || key.remoteJid : key.remoteJid;
321
+ const reportingSecret = generateMsgSecretKey(
322
+ ENC_SECRET_REPORT_TOKEN,
323
+ key.id,
324
+ from,
325
+ to,
326
+ msgSecret,
327
+ );
328
+ const content = extractReportingTokenContent(
329
+ msgProtobuf,
330
+ compiledReportingFields,
331
+ );
332
+ if (!content || content.length === 0) {
333
+ return null;
334
+ }
335
+ const reportingToken = createHmac("sha256", reportingSecret)
336
+ .update(content)
337
+ .digest()
338
+ .subarray(0, 16);
339
+ return {
340
+ tag: "reporting",
341
+ attrs: {},
342
+ content: [
343
+ { tag: "reporting_token", attrs: { v: "2" }, content: reportingToken },
344
+ ],
345
+ };
346
+ };
@@ -0,0 +1,188 @@
1
+ import { KEY_BUNDLE_TYPE } from "../Defaults/index.js";
2
+ import {
3
+ assertNodeErrorFree,
4
+ getBinaryNodeChild,
5
+ getBinaryNodeChildBuffer,
6
+ getBinaryNodeChildren,
7
+ getBinaryNodeChildUInt,
8
+ getServerFromDomainType,
9
+ jidDecode,
10
+ S_WHATSAPP_NET,
11
+ WAJIDDomains,
12
+ } from "../WABinary/index.js";
13
+ import { Curve, generateSignalPubKey } from "./crypto.js";
14
+ import { encodeBigEndian } from "./generics.js";
15
+ function chunk(array, size) {
16
+ const chunks = [];
17
+ for (let i = 0; i < array.length; i += size) {
18
+ chunks.push(array.slice(i, i + size));
19
+ }
20
+ return chunks;
21
+ }
22
+ export const createSignalIdentity = (wid, accountSignatureKey) => {
23
+ return {
24
+ identifier: { name: wid, deviceId: 0 },
25
+ identifierKey: generateSignalPubKey(accountSignatureKey),
26
+ };
27
+ };
28
+ export const getPreKeys = async ({ get }, min, limit) => {
29
+ const idList = [];
30
+ for (let id = min; id < limit; id++) {
31
+ idList.push(id.toString());
32
+ }
33
+ return get("pre-key", idList);
34
+ };
35
+ export const generateOrGetPreKeys = (creds, range) => {
36
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
37
+ const remaining = range - avaliable;
38
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
39
+ const newPreKeys = {};
40
+ if (remaining > 0) {
41
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
42
+ newPreKeys[i] = Curve.generateKeyPair();
43
+ }
44
+ }
45
+ return {
46
+ newPreKeys: newPreKeys,
47
+ lastPreKeyId: lastPreKeyId,
48
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range],
49
+ };
50
+ };
51
+ export const xmppSignedPreKey = (key) => ({
52
+ tag: "skey",
53
+ attrs: {},
54
+ content: [
55
+ { tag: "id", attrs: {}, content: encodeBigEndian(key.keyId, 3) },
56
+ { tag: "value", attrs: {}, content: key.keyPair.public },
57
+ { tag: "signature", attrs: {}, content: key.signature },
58
+ ],
59
+ });
60
+ export const xmppPreKey = (pair, id) => ({
61
+ tag: "key",
62
+ attrs: {},
63
+ content: [
64
+ { tag: "id", attrs: {}, content: encodeBigEndian(id, 3) },
65
+ { tag: "value", attrs: {}, content: pair.public },
66
+ ],
67
+ });
68
+ export const parseAndInjectE2ESessions = async (node, repository) => {
69
+ const extractKey = (key) =>
70
+ key
71
+ ? {
72
+ keyId: getBinaryNodeChildUInt(key, "id", 3),
73
+ publicKey: generateSignalPubKey(
74
+ getBinaryNodeChildBuffer(key, "value"),
75
+ ),
76
+ signature: getBinaryNodeChildBuffer(key, "signature"),
77
+ }
78
+ : undefined;
79
+ const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, "list"), "user");
80
+ for (const node of nodes) {
81
+ assertNodeErrorFree(node);
82
+ }
83
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
84
+ // So Promise.all doesn't really help here,
85
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
86
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
87
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
88
+ const chunkSize = 100;
89
+ const chunks = chunk(nodes, chunkSize);
90
+ for (const nodesChunk of chunks) {
91
+ for (const node of nodesChunk) {
92
+ const signedKey = getBinaryNodeChild(node, "skey");
93
+ const key = getBinaryNodeChild(node, "key");
94
+ const identity = getBinaryNodeChildBuffer(node, "identity");
95
+ const jid = node.attrs.jid;
96
+ const registrationId = getBinaryNodeChildUInt(node, "registration", 4);
97
+ await repository.injectE2ESession({
98
+ jid: jid,
99
+ session: {
100
+ registrationId: registrationId,
101
+ identityKey: generateSignalPubKey(identity),
102
+ signedPreKey: extractKey(signedKey),
103
+ preKey: extractKey(key),
104
+ },
105
+ });
106
+ }
107
+ }
108
+ };
109
+ export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
110
+ const { user: myUser, device: myDevice } = jidDecode(myJid);
111
+ const extracted = [];
112
+ for (const userResult of result) {
113
+ const { devices, id } = userResult;
114
+ const decoded = jidDecode(id),
115
+ { user, server } = decoded;
116
+ let { domainType } = decoded;
117
+ const deviceList = devices?.deviceList;
118
+ if (!Array.isArray(deviceList)) continue;
119
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
120
+ if (
121
+ (!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
122
+ ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
123
+ (device === 0 || !!keyIndex)
124
+ ) {
125
+ if (isHosted) {
126
+ domainType =
127
+ domainType === WAJIDDomains.LID
128
+ ? WAJIDDomains.HOSTED_LID
129
+ : WAJIDDomains.HOSTED;
130
+ }
131
+ extracted.push({
132
+ user: user,
133
+ device: device,
134
+ domainType: domainType,
135
+ server: getServerFromDomainType(server, domainType),
136
+ });
137
+ }
138
+ }
139
+ }
140
+ return extracted;
141
+ };
142
+ /**
143
+ * get the next N keys for upload or processing
144
+ * @param count number of pre-keys to get or generate
145
+ */ export const getNextPreKeys = async ({ creds, keys }, count) => {
146
+ const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(
147
+ creds,
148
+ count,
149
+ );
150
+ const update = {
151
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
152
+ firstUnuploadedPreKeyId: Math.max(
153
+ creds.firstUnuploadedPreKeyId,
154
+ lastPreKeyId + 1,
155
+ ),
156
+ };
157
+ await keys.set({ "pre-key": newPreKeys });
158
+ const preKeys = await getPreKeys(
159
+ keys,
160
+ preKeysRange[0],
161
+ preKeysRange[0] + preKeysRange[1],
162
+ );
163
+ return { update: update, preKeys: preKeys };
164
+ };
165
+ export const getNextPreKeysNode = async (state, count) => {
166
+ const { creds } = state;
167
+ const { update, preKeys } = await getNextPreKeys(state, count);
168
+ const node = {
169
+ tag: "iq",
170
+ attrs: { xmlns: "encrypt", type: "set", to: S_WHATSAPP_NET },
171
+ content: [
172
+ {
173
+ tag: "registration",
174
+ attrs: {},
175
+ content: encodeBigEndian(creds.registrationId),
176
+ },
177
+ { tag: "type", attrs: {}, content: KEY_BUNDLE_TYPE },
178
+ { tag: "identity", attrs: {}, content: creds.signedIdentityKey.public },
179
+ {
180
+ tag: "list",
181
+ attrs: {},
182
+ content: Object.keys(preKeys).map((k) => xmppPreKey(preKeys[+k], +k)),
183
+ },
184
+ xmppSignedPreKey(creds.signedPreKey),
185
+ ],
186
+ };
187
+ return { update: update, node: node };
188
+ };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Builds an ACK stanza for a received node.
3
+ * Pure function -- no I/O, no side effects.
4
+ *
5
+ * Mirrors WhatsApp Web's ACK construction:
6
+ * - WAWebHandleMsgSendAck.sendAck / sendNack
7
+ * - WAWebCreateNackFromStanza.createNackFromStanza
8
+ */
9
+ export function buildAckStanza(node, errorCode, meId) {
10
+ const { tag, attrs } = node;
11
+ const stanza = {
12
+ tag: "ack",
13
+ attrs: { id: attrs.id, to: attrs.from, class: tag },
14
+ };
15
+ if (errorCode) {
16
+ stanza.attrs.error = errorCode.toString();
17
+ }
18
+ if (attrs.participant) {
19
+ stanza.attrs.participant = attrs.participant;
20
+ }
21
+ if (attrs.recipient) {
22
+ stanza.attrs.recipient = attrs.recipient;
23
+ }
24
+ // WA Web always includes type when present: `n.type || DROP_ATTR`
25
+ if (attrs.type) {
26
+ stanza.attrs.type = attrs.type;
27
+ }
28
+ // WA Web WAWebHandleMsgSendAck.sendAck/sendNack always include `from` for message-class ACKs
29
+ if (tag === "message" && meId) {
30
+ stanza.attrs.from = meId;
31
+ }
32
+ return stanza;
33
+ }
@@ -0,0 +1,53 @@
1
+ import { proto } from "../../WAProto/index.js";
2
+ import { isLidUser, isPnUser } from "../WABinary/index.js";
3
+ /**
4
+ * Process contactAction and return events to emit.
5
+ * Pure function - no side effects.
6
+ */ export const processContactAction = (action, id, logger) => {
7
+ const results = [];
8
+ if (!id) {
9
+ logger?.warn(
10
+ {
11
+ hasFullName: !!action.fullName,
12
+ hasLidJid: !!action.lidJid,
13
+ hasPnJid: !!action.pnJid,
14
+ },
15
+ "contactAction sync: missing id in index",
16
+ );
17
+ return results;
18
+ }
19
+ const lidJid = action.lidJid;
20
+ const idIsPn = isPnUser(id);
21
+ // PN is in index[1], not in contactAction.pnJid which is usually null
22
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
23
+ // Always emit contacts.upsert
24
+ results.push({
25
+ event: "contacts.upsert",
26
+ data: [
27
+ {
28
+ id: id,
29
+ name:
30
+ action.fullName || action.firstName || action.username || undefined,
31
+ lid: lidJid || undefined,
32
+ phoneNumber: phoneNumber,
33
+ },
34
+ ],
35
+ });
36
+ // Emit lid-mapping.update if we have valid LID-PN pair
37
+ if (lidJid && isLidUser(lidJid) && idIsPn) {
38
+ results.push({
39
+ event: "lid-mapping.update",
40
+ data: { lid: lidJid, pn: id },
41
+ });
42
+ }
43
+ return results;
44
+ };
45
+ export const emitSyncActionResults = (ev, results) => {
46
+ for (const result of results) {
47
+ if (result.event === "contacts.upsert") {
48
+ ev.emit("contacts.upsert", result.data);
49
+ } else {
50
+ ev.emit("lid-mapping.update", result.data);
51
+ }
52
+ }
53
+ };
@@ -0,0 +1,15 @@
1
+ export async function buildTcTokenFromJid({
2
+ authState,
3
+ jid,
4
+ baseContent = [],
5
+ }) {
6
+ try {
7
+ const tcTokenData = await authState.keys.get("tctoken", [jid]);
8
+ const tcTokenBuffer = tcTokenData?.[jid]?.token;
9
+ if (!tcTokenBuffer) return baseContent.length > 0 ? baseContent : undefined;
10
+ baseContent.push({ tag: "tctoken", attrs: {}, content: tcTokenBuffer });
11
+ return baseContent;
12
+ } catch (error) {
13
+ return baseContent.length > 0 ? baseContent : undefined;
14
+ }
15
+ }