my-baileys 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +1145 -0
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +8083 -0
  4. package/WAProto/fix-imports.js +85 -0
  5. package/WAProto/index.d.ts +29095 -0
  6. package/WAProto/index.js +172336 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +194 -0
  9. package/lib/Signal/Group/ciphertext-message.js +12 -0
  10. package/lib/Signal/Group/group-session-builder.js +30 -0
  11. package/lib/Signal/Group/group_cipher.js +82 -0
  12. package/lib/Signal/Group/index.js +12 -0
  13. package/lib/Signal/Group/keyhelper.js +18 -0
  14. package/lib/Signal/Group/sender-chain-key.js +26 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  16. package/lib/Signal/Group/sender-key-message.js +66 -0
  17. package/lib/Signal/Group/sender-key-name.js +48 -0
  18. package/lib/Signal/Group/sender-key-record.js +41 -0
  19. package/lib/Signal/Group/sender-key-state.js +84 -0
  20. package/lib/Signal/Group/sender-message-key.js +26 -0
  21. package/lib/Signal/libsignal.js +431 -0
  22. package/lib/Signal/lid-mapping.js +277 -0
  23. package/lib/Socket/Client/index.js +3 -0
  24. package/lib/Socket/Client/types.js +11 -0
  25. package/lib/Socket/Client/websocket.js +102 -0
  26. package/lib/Socket/aigroups.js +221 -0
  27. package/lib/Socket/business.js +379 -0
  28. package/lib/Socket/chats.js +1193 -0
  29. package/lib/Socket/communities.js +431 -0
  30. package/lib/Socket/graphql.js +524 -0
  31. package/lib/Socket/groups.js +408 -0
  32. package/lib/Socket/index.js +57 -0
  33. package/lib/Socket/interop.js +345 -0
  34. package/lib/Socket/luxu.js +510 -0
  35. package/lib/Socket/managed-account.js +99 -0
  36. package/lib/Socket/message-builder.js +523 -0
  37. package/lib/Socket/messages-recv.js +2009 -0
  38. package/lib/Socket/messages-send.js +1608 -0
  39. package/lib/Socket/mex.js +56 -0
  40. package/lib/Socket/newsletter.js +624 -0
  41. package/lib/Socket/privacy.js +128 -0
  42. package/lib/Socket/registration.js +238 -0
  43. package/lib/Socket/socket.js +1000 -0
  44. package/lib/Socket/text-router.js +67 -0
  45. package/lib/Socket/username.js +234 -0
  46. package/lib/Store/index.js +10 -0
  47. package/lib/Store/keyed-db.js +108 -0
  48. package/lib/Store/make-cache-manager-store.js +85 -0
  49. package/lib/Store/make-in-memory-store.js +198 -0
  50. package/lib/Store/make-ordered-dictionary.js +75 -0
  51. package/lib/Store/object-repository.js +32 -0
  52. package/lib/Types/Auth.js +2 -0
  53. package/lib/Types/Bussines.js +2 -0
  54. package/lib/Types/Call.js +2 -0
  55. package/lib/Types/Chat.js +8 -0
  56. package/lib/Types/Contact.js +2 -0
  57. package/lib/Types/Events.js +2 -0
  58. package/lib/Types/GroupMetadata.js +2 -0
  59. package/lib/Types/Label.js +25 -0
  60. package/lib/Types/LabelAssociation.js +7 -0
  61. package/lib/Types/Message.js +11 -0
  62. package/lib/Types/Mex.js +120 -0
  63. package/lib/Types/Product.js +2 -0
  64. package/lib/Types/Signal.js +2 -0
  65. package/lib/Types/Socket.js +3 -0
  66. package/lib/Types/State.js +56 -0
  67. package/lib/Types/USync.js +2 -0
  68. package/lib/Types/index.js +26 -0
  69. package/lib/Utils/adaptive-healing.js +53 -0
  70. package/lib/Utils/auth-utils.js +302 -0
  71. package/lib/Utils/browser-utils.js +50 -0
  72. package/lib/Utils/business.js +231 -0
  73. package/lib/Utils/chat-utils.js +872 -0
  74. package/lib/Utils/command-loader.js +108 -0
  75. package/lib/Utils/companion-reg-client-utils.js +35 -0
  76. package/lib/Utils/consumer-application.js +106 -0
  77. package/lib/Utils/crypto.js +137 -0
  78. package/lib/Utils/curve25519-js.js +262 -0
  79. package/lib/Utils/decode-wa-message.js +498 -0
  80. package/lib/Utils/event-buffer.js +622 -0
  81. package/lib/Utils/generics.js +403 -0
  82. package/lib/Utils/group-history.js +47 -0
  83. package/lib/Utils/history.js +134 -0
  84. package/lib/Utils/identity-change-handler.js +50 -0
  85. package/lib/Utils/index.js +38 -0
  86. package/lib/Utils/jid-display-normalization.js +198 -0
  87. package/lib/Utils/link-preview.js +85 -0
  88. package/lib/Utils/logger.js +3 -0
  89. package/lib/Utils/lt-hash.js +8 -0
  90. package/lib/Utils/make-mutex.js +33 -0
  91. package/lib/Utils/message-composer.js +273 -0
  92. package/lib/Utils/message-retry-manager.js +267 -0
  93. package/lib/Utils/messages-media.js +885 -0
  94. package/lib/Utils/messages.js +1405 -0
  95. package/lib/Utils/meta-ai-msmsg.js +271 -0
  96. package/lib/Utils/native-bridge.js +77 -0
  97. package/lib/Utils/noise-handler.js +201 -0
  98. package/lib/Utils/offline-node-processor.js +40 -0
  99. package/lib/Utils/optimizer.js +90 -0
  100. package/lib/Utils/pre-key-manager.js +106 -0
  101. package/lib/Utils/process-message.js +630 -0
  102. package/lib/Utils/reporting-utils.js +258 -0
  103. package/lib/Utils/session-pool.js +73 -0
  104. package/lib/Utils/signal.js +207 -0
  105. package/lib/Utils/stanza-ack.js +38 -0
  106. package/lib/Utils/sticker.js +297 -0
  107. package/lib/Utils/sync-action-utils.js +49 -0
  108. package/lib/Utils/tc-token-utils.js +163 -0
  109. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  110. package/lib/Utils/use-sqlite-auth-state.js +168 -0
  111. package/lib/Utils/validate-connection.js +203 -0
  112. package/lib/Utils/view-once-cache.js +79 -0
  113. package/lib/Utils/voip-rekey.js +25 -0
  114. package/lib/Utils/warmup.js +117 -0
  115. package/lib/WABinary/constants.js +1301 -0
  116. package/lib/WABinary/decode.js +262 -0
  117. package/lib/WABinary/encode.js +220 -0
  118. package/lib/WABinary/generic-utils.js +204 -0
  119. package/lib/WABinary/index.js +6 -0
  120. package/lib/WABinary/jid-utils.js +98 -0
  121. package/lib/WABinary/types.js +2 -0
  122. package/lib/WAM/BinaryInfo.js +10 -0
  123. package/lib/WAM/constants.js +22853 -0
  124. package/lib/WAM/encode.js +150 -0
  125. package/lib/WAM/index.js +4 -0
  126. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +41 -0
  127. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  128. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  129. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  130. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +52 -0
  131. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +31 -0
  132. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +26 -0
  133. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  134. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +35 -0
  135. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  136. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  137. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  138. package/lib/WAUSync/Protocols/index.js +13 -0
  139. package/lib/WAUSync/USyncQuery.js +127 -0
  140. package/lib/WAUSync/USyncUser.js +31 -0
  141. package/lib/WAUSync/index.js +4 -0
  142. package/lib/antiban.js +4087 -0
  143. package/lib/index.js +23 -0
  144. package/package.json +151 -0
@@ -0,0 +1,297 @@
1
+ /**
2
+ * lib/Utils/sticker.js — image/video -> WhatsApp WebP sticker conversion,
3
+ * plus writing the sticker-pack EXIF metadata WhatsApp reads for the pack
4
+ * name/publisher/emoji. Requires the optional "sharp" dependency; video
5
+ * conversion additionally shells out to a locally-installed `ffmpeg`.
6
+ *
7
+ * Note on the ffmpeg call: options.fps/seconds are strictly validated and
8
+ * coerced to bounded integers, and the process is spawned with an argv
9
+ * array (execFile), never a shell string — so there's no way for a caller
10
+ * (or attacker-controlled option) to inject extra shell commands here.
11
+ */
12
+ import os from 'os';
13
+ import path from 'path';
14
+ import fs from 'fs';
15
+ import crypto from 'crypto';
16
+ import { execFile, spawn } from 'child_process';
17
+ import { Boom } from '@hapi/boom';
18
+
19
+ export const addExifToWebp = async (webpBuffer, { packName = '', packPublisher = '', categories = [] } = {}) => {
20
+ const json = {
21
+ 'sticker-pack-id': crypto.randomBytes(16).toString('hex'),
22
+ 'sticker-pack-name': packName,
23
+ 'sticker-pack-publisher': packPublisher,
24
+ emojis: categories.length ? categories : ['😀']
25
+ };
26
+ const jsonBuffer = Buffer.from(JSON.stringify(json), 'utf-8');
27
+ const exifAttr = Buffer.from([
28
+ 0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16,
29
+ 0x00, 0x00, 0x00
30
+ ]);
31
+ exifAttr.writeUIntLE(jsonBuffer.length, 14, 4);
32
+ const exifPayload = Buffer.concat([exifAttr, jsonBuffer]);
33
+ const pad = (buf) => (buf.length % 2 === 1 ? Buffer.concat([buf, Buffer.from([0x00])]) : buf);
34
+ const makeChunk = (tag, data) => {
35
+ const sizeField = Buffer.alloc(4);
36
+ sizeField.writeUInt32LE(data.length, 0);
37
+ return Buffer.concat([Buffer.from(tag, 'ascii'), sizeField, pad(data)]);
38
+ };
39
+ const exifChunk = makeChunk('EXIF', exifPayload);
40
+ if (webpBuffer.slice(0, 4).toString('ascii') !== 'RIFF' || webpBuffer.slice(8, 12).toString('ascii') !== 'WEBP') {
41
+ throw new Error('addExifToWebp expects a valid WebP buffer');
42
+ }
43
+ let offset = 12;
44
+ let vp8xChunk = null;
45
+ const otherChunks = [];
46
+ while (offset < webpBuffer.length) {
47
+ const tag = webpBuffer.slice(offset, offset + 4).toString('ascii');
48
+ const size = webpBuffer.readUInt32LE(offset + 4);
49
+ const chunkTotal = 8 + size + (size % 2);
50
+ if (tag === 'VP8X') {
51
+ vp8xChunk = webpBuffer.slice(offset, offset + chunkTotal);
52
+ }
53
+ else if (tag !== 'EXIF') {
54
+ otherChunks.push(webpBuffer.slice(offset, offset + chunkTotal));
55
+ }
56
+ offset += chunkTotal;
57
+ }
58
+ let flags;
59
+ let canvasWidth;
60
+ let canvasHeight;
61
+ if (vp8xChunk) {
62
+ flags = vp8xChunk.readUInt8(8);
63
+ canvasWidth = vp8xChunk.readUIntLE(12, 3) + 1;
64
+ canvasHeight = vp8xChunk.readUIntLE(15, 3) + 1;
65
+ }
66
+ else {
67
+ flags = 0;
68
+ let sharp;
69
+ try {
70
+ sharp = (await import('sharp')).default;
71
+ }
72
+ catch (error) {
73
+ throw new Error('addExifToWebp needs the optional "sharp" dependency to read image dimensions');
74
+ }
75
+ const meta = await sharp(webpBuffer).metadata();
76
+ canvasWidth = meta.width;
77
+ canvasHeight = meta.height;
78
+ }
79
+ flags |= 0x08;
80
+ const vp8xData = Buffer.alloc(10);
81
+ vp8xData.writeUInt8(flags, 0);
82
+ vp8xData.writeUIntLE(canvasWidth - 1, 4, 3);
83
+ vp8xData.writeUIntLE(canvasHeight - 1, 7, 3);
84
+ const newVp8xChunk = makeChunk('VP8X', vp8xData);
85
+ const body = Buffer.concat([newVp8xChunk, ...otherChunks, exifChunk]);
86
+ const fileSize = Buffer.alloc(4);
87
+ fileSize.writeUInt32LE(4 + body.length, 0);
88
+ return Buffer.concat([Buffer.from('RIFF', 'ascii'), fileSize, Buffer.from('WEBP', 'ascii'), body]);
89
+ };
90
+
91
+ export const imageToWebpSticker = async (imageBuffer, options = {}) => {
92
+ let sharp;
93
+ try {
94
+ sharp = (await import('sharp')).default;
95
+ }
96
+ catch (error) {
97
+ throw new Error('imageToWebpSticker requires the optional "sharp" dependency to be installed');
98
+ }
99
+ const webp = await sharp(imageBuffer)
100
+ .resize(512, 512, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
101
+ .webp({ quality: options.quality ?? 80 })
102
+ .toBuffer();
103
+ return addExifToWebp(webp, options);
104
+ };
105
+
106
+ /** Clamp a user-supplied numeric option to a safe integer range, with a default if invalid. */
107
+ const boundedInt = (value, { min, max, fallback }) => {
108
+ const n = Number(value);
109
+ if (!Number.isFinite(n)) {
110
+ return fallback;
111
+ }
112
+ return Math.min(max, Math.max(min, Math.round(n)));
113
+ };
114
+
115
+ export const videoToWebpSticker = async (videoBuffer, options = {}) => {
116
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xayz-baileys-sticker-'));
117
+ const inputPath = path.join(tmpDir, 'input.mp4');
118
+ const outputPath = path.join(tmpDir, 'output.webp');
119
+ fs.writeFileSync(inputPath, videoBuffer);
120
+ // Validated/clamped, not interpolated into a shell string — see execFile call below.
121
+ const fps = boundedInt(options.fps, { min: 1, max: 30, fallback: 10 });
122
+ const seconds = boundedInt(options.seconds, { min: 1, max: 10, fallback: 5 });
123
+ const vf = `fps=${fps},scale=512:512:force_original_aspect_ratio=decrease,` +
124
+ `pad=512:512:(ow-iw)/2:(oh-ih)/2:color=0x00000000,split[a][b];` +
125
+ `[a]palettegen=reserve_transparent=1[p];[b][p]paletteuse`;
126
+ const args = ['-y', '-i', inputPath, '-t', String(seconds), '-vf', vf, '-loop', '0', '-preset', 'default', '-an', '-vsync', '0', outputPath];
127
+ try {
128
+ await new Promise((resolve, reject) => {
129
+ // execFile with an argv array — ffmpeg is invoked directly, no shell is
130
+ // spawned, so nothing in `args` (all of which are numbers/paths we built
131
+ // ourselves) can be interpreted as a shell command.
132
+ execFile('ffmpeg', args, (err) => (err ? reject(err) : resolve()));
133
+ });
134
+ const webp = fs.readFileSync(outputPath);
135
+ return await addExifToWebp(webp, options);
136
+ }
137
+ finally {
138
+ fs.rmSync(tmpDir, { recursive: true, force: true });
139
+ }
140
+ };
141
+
142
+ // --- Added from baileys@6.2.7: a second, independent sticker-conversion path.
143
+ // Unlike imageToWebpSticker/videoToWebpSticker above (which need the optional
144
+ // "sharp" dependency and write video input/output to temp files), everything
145
+ // below goes straight through `ffmpeg` via piped stdin/stdout — no temp files,
146
+ // no "sharp" dependency, and it auto-detects image vs. video input. `spawn()`
147
+ // is called with an argv array (no `shell: true`), same "no shell involved"
148
+ // safety property as the execFile call above. Kept as separate exports (no
149
+ // name overlap with addExifToWebp/imageToWebpSticker/videoToWebpSticker) so
150
+ // both paths remain available — use whichever fits: the sharp-based path if
151
+ // you already depend on sharp elsewhere, this one if you'd rather not.
152
+
153
+ const runFfmpeg = (input, args) => new Promise((resolve, reject) => {
154
+ const proc = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', 'pipe:0', ...args, 'pipe:1'], { stdio: ['pipe', 'pipe', 'pipe'] });
155
+ const outChunks = [];
156
+ const errChunks = [];
157
+ proc.stdout.on('data', chunk => outChunks.push(chunk));
158
+ proc.stderr.on('data', chunk => errChunks.push(chunk));
159
+ proc.on('error', err => reject(new Boom(`ffmpeg failed to start: ${err.message}`, { statusCode: 500 })));
160
+ proc.on('close', code => {
161
+ if (code !== 0) {
162
+ reject(new Boom(`ffmpeg exited with code ${code}: ${Buffer.concat(errChunks).toString('utf8').slice(0, 500)}`, { statusCode: 500 }));
163
+ return;
164
+ }
165
+ resolve(Buffer.concat(outChunks));
166
+ });
167
+ proc.stdin.on('error', () => { });
168
+ proc.stdin.end(input);
169
+ });
170
+
171
+ /** Best-effort sniff of whether `buffer` looks like a video (vs. a still image), by container magic bytes. */
172
+ export const isLikelyVideoBuffer = (buffer) => {
173
+ if (!Buffer.isBuffer(buffer) || buffer.length < 4) {
174
+ return false;
175
+ }
176
+ const header = buffer.subarray(0, 16).toString('ascii');
177
+ if (header.startsWith('RIFF') && /AVI|WEBM/.test(header)) {
178
+ return true;
179
+ }
180
+ if (buffer.subarray(0, 4).toString('hex') === '1a45dfa3') {
181
+ return true;
182
+ }
183
+ const ftyp = buffer.toString('ascii', 4, 12);
184
+ if (buffer.toString('ascii', 0, 4) === 'ftyp' || /^(ftyp)/.test(buffer.toString('ascii', 0, 8))) {
185
+ return /mp4|isom|M4V|M4A|qt\s/.test(ftyp);
186
+ }
187
+ return false;
188
+ };
189
+
190
+ /** Image or video Buffer -> 512x512 WebP Buffer (no EXIF yet), entirely via piped ffmpeg. */
191
+ export const convertToWebp = async (buffer, { animated = false, quality = 60 } = {}) => {
192
+ const scalePad = "scale='min(512,iw)':'min(512,ih)':force_original_aspect_ratio=decrease,format=rgba,pad=512:512:-1:-1:color=#00000000";
193
+ const args = animated
194
+ ? ['-vf', `${scalePad},fps=15`, '-loop', '0', '-preset', 'default', '-an', '-vsync', '0', '-vcodec', 'libwebp', '-q:v', String(quality), '-f', 'webp']
195
+ : ['-vf', `${scalePad}`, '-vframes', '1', '-vcodec', 'libwebp', '-q:v', String(quality), '-f', 'webp'];
196
+ return runFfmpeg(buffer, args);
197
+ };
198
+
199
+ /** Image or video Buffer -> 96x96 PNG Buffer, for a sticker pack's tray icon. */
200
+ export const convertToTrayIcon = async (buffer) => {
201
+ const scalePad = "scale='min(96,iw)':'min(96,ih)':force_original_aspect_ratio=decrease,format=rgba,pad=96:96:-1:-1:color=#00000000";
202
+ const args = ['-vf', scalePad, '-vframes', '1', '-vcodec', 'png', '-f', 'image2'];
203
+ return runFfmpeg(buffer, args);
204
+ };
205
+
206
+ const readWebpChunks = (buf) => {
207
+ const chunks = [];
208
+ let offset = 12;
209
+ while (offset + 8 <= buf.length) {
210
+ const fourCC = buf.toString('ascii', offset, offset + 4);
211
+ const size = buf.readUInt32LE(offset + 4);
212
+ const dataStart = offset + 8;
213
+ const data = buf.subarray(dataStart, dataStart + size);
214
+ chunks.push({ fourCC, data });
215
+ offset = dataStart + size + (size % 2);
216
+ }
217
+ return chunks;
218
+ };
219
+ const buildWebpChunk = (fourCC, data) => {
220
+ const header = Buffer.alloc(8);
221
+ header.write(fourCC, 0, 4, 'ascii');
222
+ header.writeUInt32LE(data.length, 4);
223
+ const pad = data.length % 2 === 1 ? Buffer.from([0]) : Buffer.alloc(0);
224
+ return Buffer.concat([header, data, pad]);
225
+ };
226
+ const buildExifChunkData = (json) => {
227
+ const header = Buffer.from([0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00]);
228
+ const payload = Buffer.from(JSON.stringify(json), 'utf8');
229
+ header.writeUInt32LE(payload.length, 14);
230
+ return Buffer.concat([header, payload]);
231
+ };
232
+
233
+ /**
234
+ * Writes WhatsApp's sticker-pack EXIF metadata into a WebP buffer.
235
+ * Same job as addExifToWebp() above, independent implementation (adds an
236
+ * `is-avatar-sticker` field and reads canvas dimensions from the VP8/VP8L
237
+ * frame instead of falling back to `sharp` when there's no VP8X chunk).
238
+ */
239
+ export const writeExifToWebp = (webpBuffer, { packId, packName = '', publisher = '', emojis = [], isAvatar = false } = {}) => {
240
+ if (webpBuffer.toString('ascii', 0, 4) !== 'RIFF' || webpBuffer.toString('ascii', 8, 12) !== 'WEBP') {
241
+ throw new Boom('writeExifToWebp: not a valid webp buffer', { statusCode: 400 });
242
+ }
243
+ const chunks = readWebpChunks(webpBuffer);
244
+ const exifData = buildExifChunkData({
245
+ 'sticker-pack-id': packId || crypto.randomUUID(),
246
+ 'sticker-pack-name': packName,
247
+ 'sticker-pack-publisher': publisher,
248
+ emojis: emojis.length ? emojis : ['🤖'],
249
+ 'is-avatar-sticker': isAvatar ? 1 : 0
250
+ });
251
+ let vp8x = chunks.find(c => c.fourCC === 'VP8X');
252
+ const otherChunks = chunks.filter(c => c.fourCC !== 'VP8X' && c.fourCC !== 'EXIF');
253
+ if (!vp8x) {
254
+ const img = otherChunks.find(c => c.fourCC === 'VP8 ' || c.fourCC === 'VP8L');
255
+ if (!img) {
256
+ throw new Boom('writeExifToWebp: no VP8/VP8L image data found', { statusCode: 400 });
257
+ }
258
+ let width;
259
+ let height;
260
+ if (img.fourCC === 'VP8 ') {
261
+ width = (img.data.readUInt16LE(6) & 0x3fff);
262
+ height = (img.data.readUInt16LE(8) & 0x3fff);
263
+ }
264
+ else {
265
+ const b = img.data;
266
+ width = 1 + (((b[2] & 0x3f) << 8) | b[1]);
267
+ height = 1 + (((b[4] & 0xf) << 10) | (b[3] << 2) | ((b[2] & 0xc0) >> 6));
268
+ }
269
+ const flags = Buffer.alloc(4);
270
+ flags[0] = 0x08;
271
+ const dims = Buffer.alloc(6);
272
+ dims.writeUIntLE(width - 1, 0, 3);
273
+ dims.writeUIntLE(height - 1, 3, 3);
274
+ vp8x = { fourCC: 'VP8X', data: Buffer.concat([flags, dims]) };
275
+ }
276
+ else {
277
+ const flagsByte = vp8x.data[0] | 0x08;
278
+ vp8x = { fourCC: 'VP8X', data: Buffer.concat([Buffer.from([flagsByte]), vp8x.data.subarray(1)]) };
279
+ }
280
+ const rebuilt = [vp8x, ...otherChunks, { fourCC: 'EXIF', data: exifData }];
281
+ const chunkBuffers = rebuilt.map(c => buildWebpChunk(c.fourCC, c.data));
282
+ const payload = Buffer.concat(chunkBuffers);
283
+ const riffSize = 4 + payload.length;
284
+ const out = Buffer.alloc(8 + 4 + payload.length);
285
+ out.write('RIFF', 0, 4, 'ascii');
286
+ out.writeUInt32LE(riffSize, 4);
287
+ out.write('WEBP', 8, 4, 'ascii');
288
+ payload.copy(out, 12);
289
+ return out;
290
+ };
291
+
292
+ /** One-call image/video Buffer -> finished sticker WebP Buffer (auto-detects video, converts, writes EXIF). */
293
+ export const makeSticker = async (buffer, { pack = '', author = '', emojis = [], isPrivate = false, animated = false, quality = 60 } = {}) => {
294
+ const shouldAnimate = animated || isLikelyVideoBuffer(buffer);
295
+ const webp = await convertToWebp(buffer, { animated: shouldAnimate, quality });
296
+ return writeExifToWebp(webp, { packName: pack, publisher: author, emojis, isAvatar: isPrivate });
297
+ };
@@ -0,0 +1,49 @@
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
+ */
7
+ export const processContactAction = (action, id, logger) => {
8
+ const results = [];
9
+ if (!id) {
10
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
11
+ return results;
12
+ }
13
+ const lidJid = action.lidJid;
14
+ const idIsPn = isPnUser(id);
15
+ // PN is in index[1], not in contactAction.pnJid which is usually null
16
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
17
+ // Always emit contacts.upsert
18
+ results.push({
19
+ event: 'contacts.upsert',
20
+ data: [
21
+ {
22
+ id,
23
+ name: action.fullName || action.firstName || action.username || undefined,
24
+ username: action.username || undefined,
25
+ lid: lidJid || undefined,
26
+ phoneNumber
27
+ }
28
+ ]
29
+ });
30
+ // Emit lid-mapping.update if we have valid LID-PN pair
31
+ if (lidJid && isLidUser(lidJid) && idIsPn) {
32
+ results.push({
33
+ event: 'lid-mapping.update',
34
+ data: { lid: lidJid, pn: id }
35
+ });
36
+ }
37
+ return results;
38
+ };
39
+ export const emitSyncActionResults = (ev, results) => {
40
+ for (const result of results) {
41
+ if (result.event === 'contacts.upsert') {
42
+ ev.emit('contacts.upsert', result.data);
43
+ }
44
+ else {
45
+ ev.emit('lid-mapping.update', result.data);
46
+ }
47
+ }
48
+ };
49
+ //# sourceMappingURL=sync-action-utils.js.map
@@ -0,0 +1,163 @@
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.
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
+ */
11
+ function isRegularUser(jid) {
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'));
22
+ }
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. */
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). */
28
+ export async function readTcTokenIndex(keys) {
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
+ }
42
+ }
43
+ /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
44
+ export async function buildMergedTcTokenIndexWrite(keys, addedJids) {
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);
50
+ }
51
+ return {
52
+ [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
53
+ };
54
+ }
55
+ // WA Web has separate sender/receiver AB props for these but they're identical today
56
+ export function isTcTokenExpired(timestamp) {
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;
67
+ }
68
+ export function shouldSendNewTcToken(senderTimestamp) {
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;
75
+ }
76
+ /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
77
+ export async function resolveTcTokenJid(jid, getLIDForPN) {
78
+ if (isLidUser(jid))
79
+ return jid;
80
+ const lid = await getLIDForPN(jid);
81
+ return lid ?? jid;
82
+ }
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;
96
+ }
97
+ return jid;
98
+ }
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
+ if (!tcTokenBuffer?.length || isTcTokenExpired(entry?.timestamp)) {
106
+ if (tcTokenBuffer) {
107
+ // Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
108
+ // after we drop the unusable peer token. Only wipe the record entirely when
109
+ // there's nothing worth keeping.
110
+ const cleared = entry?.senderTimestamp !== undefined
111
+ ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
112
+ : null;
113
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } });
114
+ }
115
+ return baseContent.length > 0 ? baseContent : undefined;
116
+ }
117
+ baseContent.push({
118
+ tag: 'tctoken',
119
+ attrs: {},
120
+ content: tcTokenBuffer
121
+ });
122
+ return baseContent;
123
+ }
124
+ catch (error) {
125
+ return baseContent.length > 0 ? baseContent : undefined;
126
+ }
127
+ }
128
+ export async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
129
+ const tokensNode = getBinaryNodeChild(result, 'tokens');
130
+ if (!tokensNode)
131
+ return;
132
+ const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
133
+ for (const tokenNode of tokenNodes) {
134
+ if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
135
+ continue;
136
+ }
137
+ // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
138
+ const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid);
139
+ if (!isRegularUser(rawJid))
140
+ continue;
141
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
142
+ const existingTcData = await keys.get('tctoken', [storageJid]);
143
+ const existingEntry = existingTcData[storageJid];
144
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
145
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
146
+ // timestamp-less tokens would be immediately expired
147
+ if (!incomingTs)
148
+ continue;
149
+ if (existingTs > 0 && existingTs > incomingTs)
150
+ continue;
151
+ await keys.set({
152
+ tctoken: {
153
+ [storageJid]: {
154
+ ...existingEntry,
155
+ token: Buffer.from(tokenNode.content),
156
+ timestamp: tokenNode.attrs.t
157
+ }
158
+ }
159
+ });
160
+ onNewJidStored?.(storageJid);
161
+ }
162
+ }
163
+ //# sourceMappingURL=tc-token-utils.js.map
@@ -0,0 +1,121 @@
1
+ import { Mutex } from 'async-mutex';
2
+ import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { initAuthCreds } from './auth-utils.js';
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
11
+ const fileLocks = new Map();
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;
20
+ };
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) => {
43
+ try {
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
+ });
55
+ }
56
+ catch (error) {
57
+ return null;
58
+ }
59
+ };
60
+ const removeData = async (file) => {
61
+ try {
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
+ });
74
+ }
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 });
85
+ }
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
+ }
114
+ }
115
+ },
116
+ saveCreds: async () => {
117
+ return writeData(creds, 'creds.json');
118
+ }
119
+ };
120
+ };
121
+ //# sourceMappingURL=use-multi-file-auth-state.js.map