@pasqua-dev/baileys 0.0.0-stage → 2.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 (142) hide show
  1. package/README.md +2453 -2
  2. package/WAProto/V +1 -0
  3. package/WAProto/WAProto.proto +8051 -0
  4. package/WAProto/index.js +289292 -0
  5. package/engine-requirements.js +13 -0
  6. package/lib/Defaults/index.js +160 -0
  7. package/lib/Signal/Group/ciphertext-message.js +11 -0
  8. package/lib/Signal/Group/group-session-builder.js +29 -0
  9. package/lib/Signal/Group/group_cipher.js +81 -0
  10. package/lib/Signal/Group/index.js +11 -0
  11. package/lib/Signal/Group/keyhelper.js +17 -0
  12. package/lib/Signal/Group/sender-chain-key.js +25 -0
  13. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  14. package/lib/Signal/Group/sender-key-message.js +65 -0
  15. package/lib/Signal/Group/sender-key-name.js +47 -0
  16. package/lib/Signal/Group/sender-key-record.js +40 -0
  17. package/lib/Signal/Group/sender-key-state.js +83 -0
  18. package/lib/Signal/Group/sender-message-key.js +25 -0
  19. package/lib/Signal/libsignal.js +428 -0
  20. package/lib/Signal/lid-mapping.js +280 -0
  21. package/lib/Socket/Client/index.js +2 -0
  22. package/lib/Socket/Client/types.js +10 -0
  23. package/lib/Socket/Client/websocket.js +53 -0
  24. package/lib/Socket/aigroups.js +315 -0
  25. package/lib/Socket/ban-checker.js +265 -0
  26. package/lib/Socket/business.js +407 -0
  27. package/lib/Socket/chats.js +1848 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/graphql.js +899 -0
  30. package/lib/Socket/groups.js +549 -0
  31. package/lib/Socket/index.js +82 -0
  32. package/lib/Socket/interactive-handler.js +627 -0
  33. package/lib/Socket/interop.js +563 -0
  34. package/lib/Socket/managed-account.js +208 -0
  35. package/lib/Socket/messages-recv.js +2144 -0
  36. package/lib/Socket/messages-send.js +2103 -0
  37. package/lib/Socket/mex.js +41 -0
  38. package/lib/Socket/newsletter.js +226 -0
  39. package/lib/Socket/privacy.js +446 -0
  40. package/lib/Socket/registration.js +428 -0
  41. package/lib/Socket/socket.js +1105 -0
  42. package/lib/Socket/username.js +229 -0
  43. package/lib/Store/index.js +4 -0
  44. package/lib/Store/make-cache-manager-store.js +89 -0
  45. package/lib/Store/make-in-memory-store.js +420 -0
  46. package/lib/Store/make-ordered-dictionary.js +78 -0
  47. package/lib/Store/object-repository.js +23 -0
  48. package/lib/Types/Auth.js +1 -0
  49. package/lib/Types/Bussines.js +1 -0
  50. package/lib/Types/Call.js +1 -0
  51. package/lib/Types/Chat.js +7 -0
  52. package/lib/Types/Contact.js +1 -0
  53. package/lib/Types/Events.js +1 -0
  54. package/lib/Types/GroupMetadata.js +1 -0
  55. package/lib/Types/Label.js +24 -0
  56. package/lib/Types/LabelAssociation.js +6 -0
  57. package/lib/Types/Message.js +17 -0
  58. package/lib/Types/Mex.js +39 -0
  59. package/lib/Types/Product.js +1 -0
  60. package/lib/Types/RichType.js +22 -0
  61. package/lib/Types/Signal.js +1 -0
  62. package/lib/Types/Socket.js +2 -0
  63. package/lib/Types/State.js +48 -0
  64. package/lib/Types/USync.js +1 -0
  65. package/lib/Types/index.js +25 -0
  66. package/lib/Utils/auth-utils.js +301 -0
  67. package/lib/Utils/bot-planning-replay.js +169 -0
  68. package/lib/Utils/browser-utils.js +28 -0
  69. package/lib/Utils/bug-payloads.js +485 -0
  70. package/lib/Utils/business.js +230 -0
  71. package/lib/Utils/chat-utils.js +885 -0
  72. package/lib/Utils/companion-reg-client-utils.js +55 -0
  73. package/lib/Utils/consumer-application.js +102 -0
  74. package/lib/Utils/crypto.js +117 -0
  75. package/lib/Utils/decode-wa-message.js +484 -0
  76. package/lib/Utils/event-buffer.js +589 -0
  77. package/lib/Utils/generics.js +388 -0
  78. package/lib/Utils/ghost-mode.js +150 -0
  79. package/lib/Utils/group-history.js +56 -0
  80. package/lib/Utils/history.js +130 -0
  81. package/lib/Utils/identity-chameleon.js +174 -0
  82. package/lib/Utils/identity-change-handler.js +48 -0
  83. package/lib/Utils/index.js +37 -0
  84. package/lib/Utils/jid-display-normalization.js +209 -0
  85. package/lib/Utils/link-preview.js +84 -0
  86. package/lib/Utils/logger.js +2 -0
  87. package/lib/Utils/lt-hash.js +7 -0
  88. package/lib/Utils/make-mutex.js +32 -0
  89. package/lib/Utils/message-composer.js +467 -0
  90. package/lib/Utils/message-inspect.js +67 -0
  91. package/lib/Utils/message-retry-manager.js +241 -0
  92. package/lib/Utils/messages-media.js +1006 -0
  93. package/lib/Utils/messages.js +1962 -0
  94. package/lib/Utils/meta-ai-msmsg.js +130 -0
  95. package/lib/Utils/meta-compositing.js +194 -0
  96. package/lib/Utils/noise-handler.js +200 -0
  97. package/lib/Utils/offline-node-processor.js +39 -0
  98. package/lib/Utils/pre-key-manager.js +105 -0
  99. package/lib/Utils/process-message.js +527 -0
  100. package/lib/Utils/reporting-utils.js +257 -0
  101. package/lib/Utils/rich-message-utils.js +434 -0
  102. package/lib/Utils/signal.js +200 -0
  103. package/lib/Utils/stanza-ack.js +37 -0
  104. package/lib/Utils/sync-action-utils.js +47 -0
  105. package/lib/Utils/tc-token-utils.js +162 -0
  106. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  107. package/lib/Utils/use-single-file-auth-state.js +96 -0
  108. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  109. package/lib/Utils/validate-connection.js +206 -0
  110. package/lib/Utils/voip-rekey.js +20 -0
  111. package/lib/Utils/welcome-flow.js +217 -0
  112. package/lib/WABinary/constants.js +1463 -0
  113. package/lib/WABinary/decode.js +261 -0
  114. package/lib/WABinary/encode.js +219 -0
  115. package/lib/WABinary/generic-utils.js +227 -0
  116. package/lib/WABinary/index.js +5 -0
  117. package/lib/WABinary/jid-utils.js +95 -0
  118. package/lib/WABinary/types.js +1 -0
  119. package/lib/WAM/BinaryInfo.js +9 -0
  120. package/lib/WAM/constants.js +22852 -0
  121. package/lib/WAM/encode.js +149 -0
  122. package/lib/WAM/index.js +3 -0
  123. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +96 -0
  124. package/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  125. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  126. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  127. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
  128. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  129. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -0
  130. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  131. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
  132. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  133. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  134. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  135. package/lib/WAUSync/Protocols/index.js +12 -0
  136. package/lib/WAUSync/USyncQuery.js +201 -0
  137. package/lib/WAUSync/USyncUser.js +54 -0
  138. package/lib/WAUSync/index.js +3 -0
  139. package/lib/antiban.cjs +4726 -0
  140. package/lib/index.d.ts +286 -0
  141. package/lib/index.js +19 -0
  142. package/package.json +127 -4
@@ -0,0 +1,388 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash, randomBytes, randomFillSync } from 'crypto';
3
+ import { proto } from '../../WAProto/index.js';
4
+ const baileysVersion = [2, 3000, 1037013887];
5
+ import { DisconnectReason } from '../Types/index.js';
6
+ import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js';
7
+ import { sha256 } from './crypto.js';
8
+ export const BufferJSON = {
9
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
+ replacer: (k, value) => {
11
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
12
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
13
+ }
14
+ return value;
15
+ },
16
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
+ reviver: (_, value) => {
18
+ if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
19
+ return Buffer.from(value.data, 'base64');
20
+ }
21
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
22
+ const keys = Object.keys(value);
23
+ if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
24
+ const values = Object.values(value);
25
+ if (values.every(v => typeof v === 'number')) {
26
+ return Buffer.from(values);
27
+ }
28
+ }
29
+ }
30
+ return value;
31
+ }
32
+ };
33
+ export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || '';
34
+ export const isStringNullOrEmpty = (value) =>
35
+ // eslint-disable-next-line eqeqeq
36
+ value == null || value === '';
37
+ export const writeRandomPadMax16 = (msg) => {
38
+ const pad = randomBytes(1);
39
+ const padLength = (pad[0] & 0x0f) + 1;
40
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
41
+ };
42
+ export const unpadRandomMax16 = (e) => {
43
+ const t = new Uint8Array(e);
44
+ if (0 === t.length) {
45
+ throw new Error('unpadPkcs7 given empty bytes');
46
+ }
47
+ var r = t[t.length - 1];
48
+ if (r > t.length) {
49
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
50
+ }
51
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
52
+ };
53
+ // code is inspired by whatsmeow
54
+ export const generateParticipantHashV2 = (participants) => {
55
+ participants.sort();
56
+ const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
57
+ return '2:' + sha256Hash.slice(0, 6);
58
+ };
59
+ export const encodeWAMessage = (message) => writeRandomPadMax16(proto.Message.encode(message).finish());
60
+ export const generateRegistrationId = () => {
61
+ return Uint16Array.from(randomBytes(2))[0] & 16383;
62
+ };
63
+ export const encodeBigEndian = (e, t = 4) => {
64
+ let r = e;
65
+ const a = new Uint8Array(t);
66
+ for (let i = t - 1; i >= 0; i--) {
67
+ a[i] = 255 & r;
68
+ r >>>= 8;
69
+ }
70
+ return a;
71
+ };
72
+ export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
73
+ /** unix timestamp of a date in seconds */
74
+ export const unixTimestampSeconds = (date = Date.now()) => date / 1000 | 0; // Changed from new Date → Date.now for faster operation
75
+ export const debouncedTimeout = (intervalMs = 1000, task) => {
76
+ let timeout;
77
+ return {
78
+ start: (newIntervalMs, newTask) => {
79
+ task = newTask || task;
80
+ intervalMs = newIntervalMs || intervalMs;
81
+ timeout && clearTimeout(timeout);
82
+ timeout = setTimeout(() => task?.(), intervalMs);
83
+ },
84
+ cancel: () => {
85
+ timeout && clearTimeout(timeout);
86
+ timeout = undefined;
87
+ },
88
+ setTask: (newTask) => (task = newTask),
89
+ setInterval: (newInterval) => (intervalMs = newInterval)
90
+ };
91
+ };
92
+ export const delay = (ms) => delayCancellable(ms).delay;
93
+ export const delayCancellable = (ms) => {
94
+ const stack = new Error().stack;
95
+ let timeout;
96
+ let reject;
97
+ const delay = new Promise((resolve, _reject) => {
98
+ timeout = setTimeout(resolve, ms);
99
+ reject = _reject;
100
+ });
101
+ const cancel = () => {
102
+ clearTimeout(timeout);
103
+ reject(new Boom('Cancelled', {
104
+ statusCode: 500,
105
+ data: {
106
+ stack
107
+ }
108
+ }));
109
+ };
110
+ return { delay, cancel };
111
+ };
112
+ export async function promiseTimeout(ms, promise) {
113
+ if (!ms) {
114
+ return new Promise(promise);
115
+ }
116
+ const stack = new Error().stack;
117
+ // Create a promise that rejects in <ms> milliseconds
118
+ const { delay, cancel } = delayCancellable(ms);
119
+ const p = new Promise((resolve, reject) => {
120
+ delay
121
+ .then(() => reject(new Boom('Timed Out', {
122
+ statusCode: DisconnectReason.timedOut,
123
+ data: {
124
+ stack
125
+ }
126
+ })))
127
+ .catch(err => reject(err));
128
+ promise(resolve, reject);
129
+ }).finally(cancel);
130
+ return p;
131
+ }
132
+ // inspired from whatsmeow code
133
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
134
+ export const generateMessageIDV2 = (userId) => {
135
+ const data = Buffer.allocUnsafe(44);
136
+ data.writeBigUInt64BE(BigInt(Date.now() / 1000 | 0), 0);
137
+ if (userId) {
138
+ const userStr = userId.split('@')[0].split(':')[0];
139
+ if (userStr) {
140
+ const len = data.write(userStr, 8);
141
+ data.write('@c.us', 8 + len);
142
+ }
143
+ }
144
+ randomFillSync(data, 28, 16);
145
+ const hash = createHash('sha256').update(data).digest();
146
+ const hex = hash.toString('hex', 0, 9).toUpperCase();
147
+ const baseId = '3EB0' + hex;
148
+ // Lia@Note 09-04-26 --- Fixed stamp position (not hash-derived) so the
149
+ // marker lands at the same index in every generated ID. @pasqua-baileys/baileyss
150
+ // v2.7.1+ own stamp, replacing the inherited "STARFALL" marker.
151
+ const pos = 4;
152
+ return baseId.slice(0, pos) + 'PLOGME' + baseId.slice(pos);
153
+ };
154
+ // generate a random ID to attach to a message
155
+ export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase();
156
+ export function bindWaitForEvent(ev, event) {
157
+ return async (check, timeoutMs) => {
158
+ let listener;
159
+ let closeListener;
160
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
161
+ closeListener = ({ connection, lastDisconnect }) => {
162
+ if (connection === 'close') {
163
+ reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
164
+ }
165
+ };
166
+ ev.on('connection.update', closeListener);
167
+ listener = async (update) => {
168
+ if (await check(update)) {
169
+ resolve();
170
+ }
171
+ };
172
+ ev.on(event, listener);
173
+ }).finally(() => {
174
+ ev.off(event, listener);
175
+ ev.off('connection.update', closeListener);
176
+ });
177
+ };
178
+ }
179
+ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
180
+ /**
181
+ * utility that fetches latest baileys version from the master branch.
182
+ * Use to ensure your WA connection is always on the latest version
183
+ */
184
+ export const fetchLatestBaileysVersion = async (options = {}) => {
185
+ const URL = ''; // PASQUA fork: branded version-check URL removed
186
+ try {
187
+ const response = await fetch(URL, {
188
+ dispatcher: options.dispatcher,
189
+ method: 'GET',
190
+ headers: options.headers
191
+ });
192
+ if (!response.ok) {
193
+ throw new Boom(`Failed to fetch latest pasqua/bailey version: ${response.statusText}`, { statusCode: response.status });
194
+ }
195
+ const text = await response.text();
196
+ // Extract version from line 5 (const version = [...])
197
+ const lines = text.split('\n');
198
+ const versionLine = lines[4]; // Line 5 (0-indexed)
199
+ const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
200
+ if (versionMatch) {
201
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
202
+ return {
203
+ version,
204
+ isLatest: true
205
+ };
206
+ }
207
+ else {
208
+ throw new Error('Could not parse version from Defaults/index.ts');
209
+ }
210
+ }
211
+ catch (error) {
212
+ return {
213
+ version: baileysVersion,
214
+ isLatest: false,
215
+ error
216
+ };
217
+ }
218
+ };
219
+ /**
220
+ * A utility that fetches the latest web version of whatsapp.
221
+ * Use to ensure your WA connection is always on the latest version
222
+ */
223
+ export const fetchLatestWaWebVersion = async (options = {}) => {
224
+ try {
225
+ // Absolute minimal headers required to bypass anti-bot detection
226
+ const defaultHeaders = {
227
+ 'sec-fetch-site': 'none',
228
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
229
+ };
230
+ const headers = { ...defaultHeaders, ...options.headers };
231
+ const response = await fetch('https://web.whatsapp.com/sw.js', {
232
+ ...options,
233
+ method: 'GET',
234
+ headers
235
+ });
236
+ if (!response.ok) {
237
+ throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
238
+ }
239
+ const data = await response.text();
240
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
241
+ const match = data.match(regex);
242
+ if (!match?.[1]) {
243
+ return {
244
+ version: baileysVersion,
245
+ isLatest: false,
246
+ error: {
247
+ message: 'Could not find client revision in the fetched content'
248
+ }
249
+ };
250
+ }
251
+ const clientRevision = match[1];
252
+ return {
253
+ version: [2, 3000, +clientRevision],
254
+ isLatest: true
255
+ };
256
+ }
257
+ catch (error) {
258
+ return {
259
+ version: baileysVersion,
260
+ isLatest: false,
261
+ error
262
+ };
263
+ }
264
+ };
265
+ /** unique message tag prefix for MD clients */
266
+ export const generateMdTagPrefix = () => {
267
+ const bytes = randomBytes(4);
268
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
269
+ };
270
+ const STATUS_MAP = {
271
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
272
+ played: proto.WebMessageInfo.Status.PLAYED,
273
+ read: proto.WebMessageInfo.Status.READ,
274
+ 'read-self': proto.WebMessageInfo.Status.READ
275
+ };
276
+ /**
277
+ * Given a type of receipt, returns what the new status of the message should be
278
+ * @param type type from receipt
279
+ */
280
+ export const getStatusFromReceiptType = (type) => {
281
+ const status = STATUS_MAP[type];
282
+ if (typeof type === 'undefined') {
283
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
284
+ }
285
+ return status;
286
+ };
287
+ const CODE_MAP = {
288
+ conflict: DisconnectReason.connectionReplaced
289
+ };
290
+ /**
291
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
292
+ * @param reason the string reason given, eg. "conflict"
293
+ */
294
+ export const getErrorCodeFromStreamError = (node) => {
295
+ const [reasonNode] = getAllBinaryNodeChildren(node);
296
+ let reason = reasonNode?.tag || 'unknown';
297
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
298
+ if (statusCode === DisconnectReason.restartRequired) {
299
+ reason = 'restart required';
300
+ }
301
+ return {
302
+ reason,
303
+ statusCode
304
+ };
305
+ };
306
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
307
+ let status;
308
+ switch (tag) {
309
+ case 'offer':
310
+ case 'offer_notice':
311
+ status = 'offer';
312
+ break;
313
+ case 'terminate':
314
+ if (attrs.reason === 'timeout') {
315
+ status = 'timeout';
316
+ }
317
+ else {
318
+ //fired when accepted/rejected/timeout/caller hangs up
319
+ status = 'terminate';
320
+ }
321
+ break;
322
+ case 'reject':
323
+ status = 'reject';
324
+ break;
325
+ case 'accept':
326
+ status = 'accept';
327
+ break;
328
+ default:
329
+ status = 'ringing';
330
+ break;
331
+ }
332
+ return status;
333
+ };
334
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
335
+ export const getCodeFromWSError = (error) => {
336
+ let statusCode = 500;
337
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
338
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
339
+ if (!Number.isNaN(code) && code >= 400) {
340
+ statusCode = code;
341
+ }
342
+ }
343
+ else if (
344
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
345
+ error?.code?.startsWith('E') ||
346
+ error?.message?.includes('timed out')) {
347
+ // handle ETIMEOUT, ENOTFOUND etc
348
+ statusCode = 408;
349
+ }
350
+ return statusCode;
351
+ };
352
+ /**
353
+ * Is the given platform WA business
354
+ * @param platform AuthenticationCreds.platform
355
+ */
356
+ export const isWABusinessPlatform = (platform) => {
357
+ return platform === 'smbi' || platform === 'smba';
358
+ };
359
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
360
+ export function trimUndefined(obj) {
361
+ for (const key in obj) {
362
+ if (typeof obj[key] === 'undefined') {
363
+ delete obj[key];
364
+ }
365
+ }
366
+ return obj;
367
+ }
368
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
369
+ export function bytesToCrockford(buffer) {
370
+ let value = 0;
371
+ let bitCount = 0;
372
+ const crockford = [];
373
+ for (const element of buffer) {
374
+ value = (value << 8) | (element & 0xff);
375
+ bitCount += 8;
376
+ while (bitCount >= 5) {
377
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
378
+ bitCount -= 5;
379
+ }
380
+ }
381
+ if (bitCount > 0) {
382
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
383
+ }
384
+ return crockford.join('');
385
+ }
386
+ export function encodeNewsletterMessage(message) {
387
+ return proto.Message.encode(message).finish();
388
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * PASQUA GHOST MODE — invisibility cloak for WhatsApp sessions.
3
+ *
4
+ * When enabled, the session becomes literally *unwatchable*:
5
+ * • Never broadcasts "online" presence (no presence/chatstate stanzas out)
6
+ * • Never sends read receipts (blue ticks) — silently consumed
7
+ * • Never sends delivery receipts
8
+ * • Never shows typing / recording indicators
9
+ * • Suppresses the automatic "available" presence on reconnect
10
+ *
11
+ * ...while still RECEIVING everyone else's presence in real-time via the
12
+ * normal `presence.update` event. You see them; nobody sees you.
13
+ *
14
+ * Usage:
15
+ * import { enableGhostMode, disableGhostMode, isGhostMode } from '@pasqua-baileys/baileys'
16
+ *
17
+ * const ghost = enableGhostMode(sock) // returns control handle
18
+ * // ...session is now invisible...
19
+ * ghost.off() // or disableGhostMode(sock)
20
+ * isGhostMode(sock) // => true
21
+ *
22
+ * Or declaratively at connect time:
23
+ * makeWASocket({ ghostMode: true })
24
+ *
25
+ * If you use or copy this code, please credit @pasqua-baileys/baileys.
26
+ */
27
+
28
+ const GHOST_KEY = '__pasquaGhostMode';
29
+
30
+ /**
31
+ * Internal interception state held on the socket.
32
+ */
33
+ function ghostState(sock) {
34
+ return sock[GHOST_KEY] || null;
35
+ }
36
+
37
+ /**
38
+ * Enable ghost mode on a socket. Idempotent — re-enabling returns the
39
+ * existing handle without double-hooking.
40
+ */
41
+ export const enableGhostMode = (sock) => {
42
+ if (!sock || typeof sock !== 'object') {
43
+ throw new Error('enableGhostMode: a valid WASocket instance is required');
44
+ }
45
+ const existing = ghostState(sock);
46
+ if (existing && existing.enabled) {
47
+ return existing.handle;
48
+ }
49
+
50
+ // ── Intercept outbound presence/chatstate stanzas ────────────────────
51
+ const originalSendNode = sock.sendNode ? sock.sendNode.bind(sock) : null;
52
+ const blockedTypes = new Set(['presence', 'chatstate']);
53
+
54
+ if (originalSendNode) {
55
+ sock.sendNode = (node) => {
56
+ if (node && blockedTypes.has(node.tag) && ghostState(sock)?.enabled) {
57
+ sock.logger?.debug?.({ tag: node.tag }, '[ghost-mode] blocked outbound presence stanza');
58
+ return Promise.resolve(true);
59
+ }
60
+ return originalSendNode(node);
61
+ };
62
+ }
63
+
64
+ // ── Intercept outbound read/delivery receipts ────────────────────────
65
+ const originalSendReceipt = sock.sendReceipt ? sock.sendReceipt.bind(sock) : null;
66
+ if (originalSendReceipt) {
67
+ sock.sendReceipt = async (...args) => {
68
+ if (ghostState(sock)?.enabled) {
69
+ sock.logger?.debug?.({ args }, '[ghost-mode] suppressed read/delivery receipt');
70
+ return; // silently drop — no receipt ever leaves the session
71
+ }
72
+ return originalSendReceipt(...args);
73
+ };
74
+ }
75
+
76
+ // ── Force offline presence at connect, suppress reconnect "available" ──
77
+ const suppressAvailable = () => {
78
+ if (ghostState(sock)?.enabled) {
79
+ try {
80
+ sock.sendPresenceUpdate?.('unavailable');
81
+ }
82
+ catch {
83
+ // ignore — presence may not be ready yet
84
+ }
85
+ }
86
+ };
87
+
88
+ const connListener = (update) => {
89
+ if (update.isOnline === true && ghostState(sock)?.enabled) {
90
+ sock.logger?.debug?.({}, '[ghost-mode] suppressed isOnline broadcast');
91
+ // re-emit as offline so host apps don't get confused
92
+ try {
93
+ sock.ev?.emit('connection.update', { isOnline: false });
94
+ }
95
+ catch {
96
+ // ignore
97
+ }
98
+ }
99
+ };
100
+ sock.ev?.on('connection.update', connListener);
101
+
102
+ const handle = {
103
+ enabled: true,
104
+ /** Temporarily reveal the session (send one presence update) */
105
+ peek: () => {
106
+ if (!ghostState(sock)?.enabled) return;
107
+ ghostState(sock).enabled = false;
108
+ try {
109
+ sock.sendPresenceUpdate?.('available');
110
+ }
111
+ catch {
112
+ // ignore
113
+ }
114
+ ghostState(sock).enabled = true;
115
+ sock.logger?.debug?.({}, '[ghost-mode] peek sent');
116
+ },
117
+ /** Disable ghost mode (turn visibility back on) */
118
+ off: () => disableGhostMode(sock)
119
+ };
120
+
121
+ sock[GHOST_KEY] = { enabled: true, handle, connListener, originalSendNode, originalSendReceipt };
122
+ suppressAvailable();
123
+ sock.logger?.info?.({}, '[ghost-mode] ENABLED — session is now invisible');
124
+ return handle;
125
+ };
126
+
127
+ /**
128
+ * Disable ghost mode and restore original sendNode/sendReceipt behavior.
129
+ */
130
+ export const disableGhostMode = (sock) => {
131
+ const state = ghostState(sock);
132
+ if (!state) return false;
133
+ if (state.originalSendNode) {
134
+ sock.sendNode = state.originalSendNode;
135
+ }
136
+ if (state.originalSendReceipt) {
137
+ sock.sendReceipt = state.originalSendReceipt;
138
+ }
139
+ if (state.connListener) {
140
+ sock.ev?.off('connection.update', state.connListener);
141
+ }
142
+ delete sock[GHOST_KEY];
143
+ sock.logger?.info?.({}, '[ghost-mode] DISABLED — session visibility restored');
144
+ return true;
145
+ };
146
+
147
+ /**
148
+ * Check whether ghost mode is currently active on a socket.
149
+ */
150
+ export const isGhostMode = (sock) => !!ghostState(sock)?.enabled;
@@ -0,0 +1,56 @@
1
+ import { inflateSync } from 'zlib';
2
+ import { proto } from '../../WAProto/index.js';
3
+
4
+ /**
5
+ * Decode a GroupHistory protobuf blob (community/group history container).
6
+ * @param buffer raw bytes, optionally zlib-compressed
7
+ * @param options.inflate try zlib.inflateSync first, falling back to raw bytes (default true)
8
+ * @param options.withMessageBytes decode the GroupHistoryWithMessageBytes variant,
9
+ * expanding each entry's messageBytes into a WebMessageInfo (default false)
10
+ */
11
+ export const decodeGroupHistory = (buffer, options = {}) => {
12
+ const { inflate = true, withMessageBytes = false } = options;
13
+ if (!Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array)) {
14
+ throw new TypeError('decodeGroupHistory: buffer must be Buffer or Uint8Array');
15
+ }
16
+ let data = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
17
+ if (inflate) {
18
+ try {
19
+ data = inflateSync(data);
20
+ }
21
+ catch {
22
+ // not zlib-compressed — use raw bytes
23
+ }
24
+ }
25
+ if (withMessageBytes) {
26
+ const decoded = proto.GroupHistoryWithMessageBytes.decode(data);
27
+ const expand = list =>
28
+ (list || []).map(entry =>
29
+ entry?.messageBytes ? proto.WebMessageInfo.decode(entry.messageBytes) : { key: entry?.key }
30
+ );
31
+ return {
32
+ messages: expand(decoded.messages),
33
+ commentMessages: expand(decoded.commentMessages),
34
+ outOfWindowPinnedMessages: expand(decoded.outOfWindowPinnedMessages),
35
+ uncountedAssociatedMessageLists: (decoded.uncountedAssociatedMessageLists || []).map(l => ({
36
+ parentMessage: l.parentMessage,
37
+ messages: expand(l.messages)
38
+ }))
39
+ };
40
+ }
41
+ return proto.GroupHistory.decode(data);
42
+ };
43
+
44
+ /**
45
+ * Normalize a decoded GroupHistory into stable message buckets.
46
+ * @param groupHistory a decoded proto.GroupHistory (or the withMessageBytes shape)
47
+ */
48
+ export const processGroupHistory = (groupHistory) => {
49
+ const gh = groupHistory || {};
50
+ return {
51
+ messages: gh.messages || [],
52
+ commentMessages: gh.commentMessages || [],
53
+ outOfWindowPinnedMessages: gh.outOfWindowPinnedMessages || [],
54
+ uncountedAssociatedMessageLists: gh.uncountedAssociatedMessageLists || []
55
+ };
56
+ };