@skycodee/baileys 8.0.14 → 8.0.15

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.
@@ -1,123 +1,148 @@
1
- //=======================================================//
2
- import { makeLibSignalRepository } from "../Signal/libsignal.js";
3
- import { Browsers } from "../Utils/browser-utils.js";
4
- import { proto } from "../../WAProto/index.js";
5
- import logger from "../Utils/logger.js";
6
- //=======================================================//
7
- export const version = [2, 3000, 1033893291]
8
- export const DICT_VERSION = 3;
9
- //=======================================================//
10
- export const NOISE_WA_HEADER = Buffer.from([87, 65, 6, DICT_VERSION]);
11
- export const CALL_VIDEO_PREFIX = "https://call.whatsapp.com/video/";
12
- export const CALL_AUDIO_PREFIX = "https://call.whatsapp.com/voice/";
13
- export const WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX = Buffer.from([6, 5]);
14
- export const WA_ADV_HOSTED_DEVICE_SIG_PREFIX = Buffer.from([6, 6]);
15
- export const NOISE_MODE = "Noise_XX_25519_AESGCM_SHA256\0\0\0\0";
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { makeLibSignalRepository } from '../Signal/libsignal.js';
3
+ import { Browsers } from '../Utils/browser-utils.js';
4
+ import logger from '../Utils/logger.js';
5
+ const version = [2,3000,1042626022]
6
+ export const UNAUTHORIZED_CODES = [401, 403, 419];
7
+ export const BIZ_BOT_SUPPORT_PAYLOAD = '{"version":1,"is_ai_message":true,"should_upload_client_logs":false,"should_show_system_message":false,"ticket_id":"7004947587700716","citation_items":[],"ticket_locale":"us"}';
8
+ export const DEFAULT_ORIGIN = 'https://web.whatsapp.com';
9
+ export const CALL_VIDEO_PREFIX = 'https://call.whatsapp.com/video/';
10
+ export const CALL_AUDIO_PREFIX = 'https://call.whatsapp.com/voice/';
11
+ export const DEF_CALLBACK_PREFIX = 'CB:';
12
+ export const DEF_TAG_PREFIX = 'TAG:';
13
+ export const DONATE_URL = 'https://saweria.co/itsliaaa'; // Lia@Note 02-02-26 --- Apologies if this feels cheeky, just a fallback
14
+ export const LIBRARY_NAME = 'itsliaaa/baileys';
15
+ export const PHONE_CONNECTION_CB = 'CB:Pong';
16
16
  export const WA_ADV_ACCOUNT_SIG_PREFIX = Buffer.from([6, 0]);
17
17
  export const WA_ADV_DEVICE_SIG_PREFIX = Buffer.from([6, 1]);
18
- export const DEFAULT_ORIGIN = "https://web.whatsapp.com";
18
+ export const WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX = Buffer.from([6, 5]);
19
+ export const WA_ADV_HOSTED_DEVICE_SIG_PREFIX = Buffer.from([6, 6]);
19
20
  export const WA_DEFAULT_EPHEMERAL = 7 * 24 * 60 * 60;
20
- export const UNAUTHORIZED_CODES = [401, 403, 419];
21
+ /** Status messages older than 24 hours are considered expired */
22
+ export const STATUS_EXPIRY_SECONDS = 24 * 60 * 60;
23
+ /** WA Web enforces a 14-day maximum age for placeholder resend requests */
24
+ export const PLACEHOLDER_MAX_AGE_SECONDS = 14 * 24 * 60 * 60;
25
+ export const NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0';
26
+ export const DICT_VERSION = 3;
21
27
  export const KEY_BUNDLE_TYPE = Buffer.from([5]);
22
- export const PHONE_CONNECTION_CB = "CB:Pong";
23
- export const DEF_CALLBACK_PREFIX = "CB:";
24
- export const DEF_TAG_PREFIX = "TAG:";
25
- //=======================================================//
28
+ export const NOISE_WA_HEADER = Buffer.from([87, 65, 6, DICT_VERSION]); // last is "DICT_VERSION"
29
+ export const LEXER_REGEX = /(\/\/.*|\/\*[\s\S]*?\*\/|#.*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`[\s\S]*?`)|(\b[a-zA-Z_]\w*\b)(?=\s*\()|(\b[a-zA-Z_]\w*\b)|(\b\d+(?:\.\d+)?\b)|(\s+|[^\w\s]+)/g;
30
+ /** from: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url */
26
31
  export const URL_REGEX = /https:\/\/(?![^:@\/\s]+:[^:@\/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g;
27
- //=======================================================//
28
32
  export const WA_CERT_DETAILS = {
29
- SERIAL: 0
33
+ SERIAL: 0,
34
+ ISSUER: 'WhatsAppLongTerm1',
35
+ PUBLIC_KEY: Buffer.from('142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b', 'hex')
30
36
  };
31
- //=======================================================//
32
37
  export const PROCESSABLE_HISTORY_TYPES = [
33
- proto.Message.HistorySyncNotification.HistorySyncType.INITIAL_BOOTSTRAP,
34
- proto.Message.HistorySyncNotification.HistorySyncType.PUSH_NAME,
35
- proto.Message.HistorySyncNotification.HistorySyncType.RECENT,
36
- proto.Message.HistorySyncNotification.HistorySyncType.FULL,
37
- proto.Message.HistorySyncNotification.HistorySyncType.ON_DEMAND,
38
- proto.Message.HistorySyncNotification.HistorySyncType.NON_BLOCKING_DATA,
39
- proto.Message.HistorySyncNotification.HistorySyncType.INITIAL_STATUS_V3
38
+ proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,
39
+ proto.HistorySync.HistorySyncType.PUSH_NAME,
40
+ proto.HistorySync.HistorySyncType.RECENT,
41
+ proto.HistorySync.HistorySyncType.FULL,
42
+ proto.HistorySync.HistorySyncType.ON_DEMAND,
43
+ proto.HistorySync.HistorySyncType.NON_BLOCKING_DATA,
44
+ proto.HistorySync.HistorySyncType.INITIAL_STATUS_V3
40
45
  ];
41
- //=======================================================//
42
46
  export const DEFAULT_CONNECTION_CONFIG = {
43
- "version": version,
44
- "browser": Browsers.iOS("Safari"),
45
- "waWebSocketUrl": "wss://web.whatsapp.com/ws/chat",
46
- "connectTimeoutMs": 20000,
47
- "keepAliveIntervalMs": 30000,
48
- "logger": logger.child({ "class": "baileys" }),
49
- "emitOwnEvents": true,
50
- "defaultQueryTimeoutMs": 60000,
51
- "customUploadHosts": [],
52
- "retryRequestDelayMs": 250,
53
- "maxMsgRetryCount": 5,
54
- "fireInitQueries": true,
55
- "auth": undefined,
56
- "markOnlineOnConnect": true,
57
- "syncFullHistory": true,
58
- "patchMessageBeforeSending": msg => msg,
59
- "shouldSyncHistoryMessage": () => true,
60
- "shouldIgnoreJid": () => false,
61
- "linkPreviewImageThumbnailWidth": 192,
62
- "transactionOpts": { "maxCommitRetries": 10, "delayBetweenTriesMs": 3000 },
63
- "generateHighQualityLinkPreview": false,
64
- "enableAutoSessionRecreation": true,
65
- "enableRecentMessageCache": true,
66
- "options": {},
67
- "appStateMacVerification": {
68
- "patch": false,
69
- "snapshot": false
70
- },
71
- "countryCode": "US",
72
- "getMessage": async () => undefined,
73
- "cachedGroupMetadata": async () => undefined,
74
- "makeSignalRepository": makeLibSignalRepository
47
+ version: version,
48
+ browser: Browsers.macOS('Chrome'),
49
+ waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
50
+ connectTimeoutMs: 20000,
51
+ keepAliveIntervalMs: 30000,
52
+ logger: logger.child({ class: 'baileys' }),
53
+ emitOwnEvents: true,
54
+ defaultQueryTimeoutMs: 60000,
55
+ customUploadHosts: [],
56
+ retryRequestDelayMs: 250,
57
+ maxMsgRetryCount: 3,
58
+ fireInitQueries: true,
59
+ auth: undefined,
60
+ markOnlineOnConnect: true,
61
+ syncFullHistory: true,
62
+ patchMessageBeforeSending: msg => msg,
63
+ shouldSyncHistoryMessage: ({ syncType }) => {
64
+ return syncType !== proto.HistorySync.HistorySyncType.FULL;
65
+ },
66
+ shouldIgnoreJid: () => false,
67
+ linkPreviewImageThumbnailWidth: 192,
68
+ transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
69
+ generateHighQualityLinkPreview: false,
70
+ enableAutoSessionRecreation: true,
71
+ enableRecentMessageCache: true,
72
+ options: {},
73
+ appStateMacVerification: {
74
+ patch: false,
75
+ snapshot: false
76
+ },
77
+ countryCode: 'US',
78
+ getMessage: async () => undefined,
79
+ cachedGroupMetadata: async () => undefined,
80
+ makeSignalRepository: makeLibSignalRepository
75
81
  };
76
- //=======================================================//
77
82
  export const MEDIA_PATH_MAP = {
78
- "image": "/mms/image",
79
- "video": "/mms/video",
80
- "document": "/mms/document",
81
- "audio": "/mms/audio",
82
- "sticker": "/mms/image",
83
- "thumbnail-link": "/mms/image",
84
- "product-catalog-image": "/product/image",
85
- "md-app-state": "",
86
- "md-msg-hist": "/mms/md-app-state",
87
- "biz-cover-photo": "/pps/biz-cover-photo"
83
+ image: '/mms/image',
84
+ video: '/mms/video',
85
+ document: '/mms/document',
86
+ audio: '/mms/audio',
87
+ sticker: '/mms/image',
88
+ 'sticker-pack': '/mms/sticker-pack',
89
+ 'thumbnail-sticker-pack': '/mms/thumbnail-sticker-pack',
90
+ 'thumbnail-link': '/mms/thumbnail-link',
91
+ 'product-catalog-image': '/product/image',
92
+ 'md-app-state': '',
93
+ 'md-msg-hist': '/mms/md-app-state',
94
+ 'biz-cover-photo': '/pps/biz-cover-photo'
95
+ };
96
+ // Lia@Changes 06-02-26 --- Add newsletter media path for "/m1/" instead of "/o1/" (⁠≧⁠▽⁠≦⁠)
97
+ export const NEWSLETTER_MEDIA_PATH_MAP = {
98
+ image: '/newsletter/newsletter-image',
99
+ video: '/newsletter/newsletter-video',
100
+ document: '/newsletter/newsletter-document',
101
+ audio: '/newsletter/newsletter-audio',
102
+ sticker: '/newsletter/newsletter-image',
103
+ 'thumbnail-link': '/newsletter/newsletter-thumbnail-link'
88
104
  };
89
- //=======================================================//
90
105
  export const MEDIA_HKDF_KEY_MAPPING = {
91
- "audio": "Audio",
92
- "document": "Document",
93
- "gif": "Video",
94
- "image": "Image",
95
- "ppic": "",
96
- "product": "Image",
97
- "ptt": "Audio",
98
- "sticker": "Image",
99
- "video": "Video",
100
- "thumbnail-document": "Document Thumbnail",
101
- "thumbnail-image": "Image Thumbnail",
102
- "thumbnail-video": "Video Thumbnail",
103
- "thumbnail-link": "Link Thumbnail",
104
- "md-msg-hist": "History",
105
- "md-app-state": "App State",
106
- "product-catalog-image": "",
107
- "payment-bg-image": "Payment Background",
108
- "ptv": "Video",
109
- "biz-cover-photo": "Image"
106
+ audio: 'Audio',
107
+ document: 'Document',
108
+ gif: 'Video',
109
+ image: 'Image',
110
+ ppic: '',
111
+ product: 'Image',
112
+ ptt: 'Audio',
113
+ 'sticker-pack': 'Sticker Pack',
114
+ 'thumbnail-sticker-pack': 'Sticker Pack Thumbnail',
115
+ sticker: 'Image',
116
+ video: 'Video',
117
+ 'thumbnail-document': 'Document Thumbnail',
118
+ 'thumbnail-image': 'Image Thumbnail',
119
+ 'thumbnail-video': 'Video Thumbnail',
120
+ 'thumbnail-link': 'Link Thumbnail',
121
+ 'md-msg-hist': 'History',
122
+ 'md-app-state': 'App State',
123
+ 'product-catalog-image': '',
124
+ 'payment-bg-image': 'Payment Background',
125
+ ptv: 'Video',
126
+ 'biz-cover-photo': 'Image'
110
127
  };
111
- //=======================================================//
112
128
  export const MEDIA_KEYS = Object.keys(MEDIA_PATH_MAP);
113
129
  export const MIN_PREKEY_COUNT = 5;
114
130
  export const INITIAL_PREKEY_COUNT = 812;
115
- export const UPLOAD_TIMEOUT = 30000;
116
- export const MIN_UPLOAD_INTERVAL = 5000;
131
+ export const UPLOAD_TIMEOUT = 30000; // 30 seconds
132
+ export const MIN_UPLOAD_INTERVAL = 5000; // 5 seconds minimum between uploads
117
133
  export const DEFAULT_CACHE_TTLS = {
118
- SIGNAL_STORE: 5 * 60,
119
- MSG_RETRY: 60 * 60,
120
- CALL_OFFER: 5 * 60,
121
- USER_DEVICES: 5 * 60
134
+ SIGNAL_STORE: 5 * 60, // 5 minutes
135
+ MSG_RETRY: 60 * 60, // 1 hour
136
+ CALL_OFFER: 5 * 60, // 5 minutes
137
+ USER_DEVICES: 5 * 60 // 5 minutes
138
+ };
139
+ export const TimeMs = {
140
+ Minute: 60 * 1000,
141
+ Hour: 60 * 60 * 1000,
142
+ Day: 24 * 60 * 60 * 1000,
143
+ Week: 7 * 24 * 60 * 60 * 1000
122
144
  };
123
- //=======================================================//
145
+ export const BOT_RENDERING_CONFIG_METADATA = {
146
+ bloksVersioningId: '0903aa5f7f47de66789d5f4c86d3bd6e05e4bc3ff85e454a9f907d5ed7fef97c',
147
+ pixelDensity: 2.75
148
+ };
@@ -1,355 +1,382 @@
1
- //=======================================================//
2
- import { getAllBinaryNodeChildren, jidDecode } from "../WABinary/index.js";
3
- import { DisconnectReason } from "../Types/index.js";
4
- import { createHash, randomBytes } from "crypto";
5
- import { proto } from "../../WAProto/index.js";
6
- import { version } from "../Defaults/index.js"
7
- import { sha256 } from "./crypto.js";
8
- import { Boom } from "@hapi/boom";
9
- //=======================================================//
10
- export const BufferJSON = {
11
- replacer: (k, value) => {
12
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === "Buffer") {
13
- return { type: "Buffer", data: Buffer.from(value?.data || value).toString("base64") };
14
- }
15
- return value;
16
- },
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
- //=======================================================//
34
- export const getKeyAuthor = (key, meId = "me") => (key?.fromMe ? meId : key?.participant || key?.remoteJid) || "";
35
- export const writeRandomPadMax16 = (msg) => {
36
- const pad = randomBytes(1);
37
- const padLength = (pad[0] & 0x0f) + 1;
38
- return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
39
- };
40
- //=======================================================//
41
- export const unpadRandomMax16 = (e) => {
42
- const t = new Uint8Array(e);
43
- if (0 === t.length) {
44
- throw new Error("unpadPkcs7 given empty bytes");
45
- }
46
- var r = t[t.length - 1];
47
- if (r > t.length) {
48
- throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
49
- }
50
- return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
51
- };
52
- //=======================================================//
53
- export const generateParticipantHashV2 = (participants) => {
54
- participants.sort();
55
- const sha256Hash = sha256(Buffer.from(participants.join(""))).toString("base64");
56
- return "2:" + sha256Hash.slice(0, 6);
57
- };
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
- //=======================================================//
64
- export const encodeBigEndian = (e, t = 4) => {
65
- let r = e;
66
- const a = new Uint8Array(t);
67
- for (let i = t - 1; i >= 0; i--) {
68
- a[i] = 255 & r;
69
- r >>>= 8;
70
- }
71
- return a;
72
- };
73
- export const toNumber = (t) => typeof t === "object" && t ? ("toNumber" in t ? t.toNumber() : t.low) : t || 0;
74
- //=======================================================//
75
- export const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
76
- export const debouncedTimeout = (intervalMs = 1000, task) => {
77
- let timeout;
78
- return {
79
- start: (newIntervalMs, newTask) => {
80
- task = newTask || task;
81
- intervalMs = newIntervalMs || intervalMs;
82
- timeout && clearTimeout(timeout);
83
- timeout = setTimeout(() => task?.(), intervalMs);
84
- },
85
- cancel: () => {
86
- timeout && clearTimeout(timeout);
87
- timeout = undefined;
88
- },
89
- setTask: (newTask) => (task = newTask),
90
- setInterval: (newInterval) => (intervalMs = newInterval)
91
- };
92
- };
93
- //=======================================================//
94
- export const delay = (ms) => delayCancellable(ms).delay;
95
- export const delayCancellable = (ms) => {
96
- const stack = new Error().stack;
97
- let timeout;
98
- let reject;
99
- const delay = new Promise((resolve, _reject) => {
100
- timeout = setTimeout(resolve, ms);
101
- reject = _reject;
102
- });
103
- const cancel = () => {
104
- clearTimeout(timeout);
105
- reject(new Boom("Cancelled", {
106
- statusCode: 500,
107
- data: {
108
- stack
109
- }
110
- }));
111
- };
112
- return { delay, cancel };
113
- };
114
- //=======================================================//
115
- export async function promiseTimeout(ms, promise) {
116
- return new Promise(promise);
117
- }
118
- //=======================================================//
119
- export const generateMessageIDV2 = (userId) => {
120
- const data = Buffer.alloc(8 + 20 + 16);
121
- data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
122
- if (userId) {
123
- const id = jidDecode(userId);
124
- if (id?.user) {
125
- data.write(id.user, 8);
126
- data.write("@c.us", 8 + id.user.length);
127
- }
128
- }
129
- const random = randomBytes(16);
130
- random.copy(data, 28);
131
- const hash = createHash("sha256").update(data).digest();
132
- return "3EB0" + hash.toString("hex").toUpperCase().substring(0, 18);
133
- };
134
- //=======================================================//
135
- export const generateMessageID = () => "3EB0" + randomBytes(18).toString("hex").toUpperCase();
136
- export function bindWaitForEvent(ev, event) {
137
- return async (check, timeoutMs) => {
138
- let listener;
139
- let closeListener;
140
- await promiseTimeout(timeoutMs, (resolve, reject) => {
141
- closeListener = ({ connection, lastDisconnect }) => {
142
- if (connection === "close") {
143
- reject(lastDisconnect?.error || new Boom("Connection Closed", { statusCode: DisconnectReason.connectionClosed }));
144
- }
145
- };
146
- ev.on("connection.update", closeListener);
147
- listener = async (update) => {
148
- if (await check(update)) {
149
- resolve();
150
- }
151
- };
152
- ev.on(event, listener);
153
- }).finally(() => {
154
- ev.off(event, listener);
155
- ev.off("connection.update", closeListener);
156
- });
157
- };
158
- }
159
- export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, "connection.update");
160
- //=======================================================//
161
- export const fetchLatestBaileysVersion = async (options = {}) => {
162
- const URL = "https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts";
163
- try {
164
- const response = await fetch(URL, {
165
- dispatcher: options.dispatcher,
166
- method: "GET",
167
- headers: options.headers
168
- });
169
- if (!response.ok) {
170
- throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
171
- }
172
- const text = await response.text();
173
- const lines = text.split("\n");
174
- const versionLine = lines[6];
175
- const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
176
- if (versionMatch) {
177
- const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
178
- return {
179
- version,
180
- isLatest: true
181
- };
182
- }
183
- else {
184
- throw new Error("Could not parse version from Defaults/index.ts");
185
- }
186
- }
187
- catch (error) {
188
- return {
189
- version: version,
190
- isLatest: false,
191
- error
192
- };
193
- }
194
- };
195
- //=======================================================//
196
- export const fetchLatestWaWebVersion = async (options = {}) => {
197
- try {
198
- const defaultHeaders = {
199
- "sec-fetch-site": "none",
200
- "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
201
- };
202
- const headers = { ...defaultHeaders, ...options.headers };
203
- const response = await fetch("https://web.whatsapp.com/sw.js", {
204
- ...options,
205
- method: "GET",
206
- headers
207
- });
208
- if (!response.ok) {
209
- throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
210
- }
211
- const data = await response.text();
212
- const regex = /\\?"client_revision\\?":\s*(\d+)/;
213
- const match = data.match(regex);
214
- if (!match?.[1]) {
215
- return {
216
- version: version,
217
- isLatest: false,
218
- error: {
219
- message: "Could not find client revision in the fetched content"
220
- }
221
- };
222
- }
223
- const clientRevision = match[1];
224
- return {
225
- version: [2, 3000, +clientRevision],
226
- isLatest: true
227
- };
228
- }
229
- catch (error) {
230
- return {
231
- version: version,
232
- isLatest: false,
233
- error
234
- };
235
- }
236
- };
237
- //=======================================================//
238
- export const generateMdTagPrefix = () => {
239
- const bytes = randomBytes(4);
240
- return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
241
- };
242
- //=======================================================//
243
- const STATUS_MAP = {
244
- "sender": proto.WebMessageInfo.Status.SERVER_ACK,
245
- "played": proto.WebMessageInfo.Status.PLAYED,
246
- "read": proto.WebMessageInfo.Status.READ,
247
- "read-self": proto.WebMessageInfo.Status.READ
248
- };
249
- //=======================================================//
250
- export const getStatusFromReceiptType = (type) => {
251
- const status = STATUS_MAP[type];
252
- if (typeof type === "undefined") {
253
- return proto.WebMessageInfo.Status.DELIVERY_ACK;
254
- }
255
- return status;
256
- };
257
- //=======================================================//
258
- const CODE_MAP = {
259
- conflict: DisconnectReason.connectionReplaced
260
- };
261
- //=======================================================//
262
- export const getErrorCodeFromStreamError = (node) => {
263
- const [reasonNode] = getAllBinaryNodeChildren(node);
264
- let reason = reasonNode?.tag || "unknown";
265
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
266
- if (statusCode === DisconnectReason.restartRequired) {
267
- reason = "restart required";
268
- }
269
- return {
270
- reason,
271
- statusCode
272
- };
273
- };
274
- //=======================================================//
275
- export const getCallStatusFromNode = ({ tag, attrs }) => {
276
- let status;
277
- switch (tag) {
278
- case "offer":
279
- case "offer_notice":
280
- status = "offer";
281
- break;
282
- case "terminate":
283
- if (attrs.reason === "timeout") {
284
- status = "timeout";
285
- }
286
- else {
287
- status = "terminate";
288
- }
289
- break;
290
- case "reject":
291
- status = "reject";
292
- break;
293
- case "accept":
294
- status = "accept";
295
- break;
296
- default:
297
- status = "ringing";
298
- break;
299
- }
300
- return status;
301
- };
302
- //=======================================================//
303
- const UNEXPECTED_SERVER_CODE_TEXT = "Unexpected server response: ";
304
- export const getCodeFromWSError = (error) => {
305
- let statusCode = 500;
306
- if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
307
- const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
308
- if (!Number.isNaN(code) && code >= 400) {
309
- statusCode = code;
310
- }
311
- }
312
- else if (
313
- error?.code?.startsWith("E") ||
314
- error?.message?.includes("timed out")) {
315
- statusCode = 408;
316
- }
317
- return statusCode;
318
- };
319
- //=======================================================//
320
- export const isWABusinessPlatform = (platform) => {
321
- return platform === "smbi" || platform === "smba";
322
- };
323
- //=======================================================//
324
- export function trimUndefined(obj) {
325
- for (const key in obj) {
326
- if (typeof obj[key] === "undefined") {
327
- delete obj[key];
328
- }
329
- }
330
- return obj;
331
- }
332
- //=======================================================//
333
- const CROCKFORD_CHARACTERS = "123456789ABCDEFGHJKLMNPQRSTVWXYZ";
334
- export function bytesToCrockford(buffer) {
335
- let value = 0;
336
- let bitCount = 0;
337
- const crockford = [];
338
- for (const element of buffer) {
339
- value = (value << 8) | (element & 0xff);
340
- bitCount += 8;
341
- while (bitCount >= 5) {
342
- crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
343
- bitCount -= 5;
344
- }
345
- }
346
- if (bitCount > 0) {
347
- crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
348
- }
349
- return crockford.join("");
350
- }
351
- //=======================================================//
352
- export function encodeNewsletterMessage(message) {
353
- return proto.Message.encode(message).finish();
354
- }
355
- //=======================================================//
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, 1037828507];
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
+ const pos = 4 + (hash[0] & 15);
149
+ return baseId.slice(0, pos) + 'STARFALL' + baseId.slice(pos);
150
+ };
151
+ // generate a random ID to attach to a message
152
+ export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase();
153
+ export function bindWaitForEvent(ev, event) {
154
+ return async (check, timeoutMs) => {
155
+ let listener;
156
+ let closeListener;
157
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
158
+ closeListener = ({ connection, lastDisconnect }) => {
159
+ if (connection === 'close') {
160
+ reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
161
+ }
162
+ };
163
+ ev.on('connection.update', closeListener);
164
+ listener = async (update) => {
165
+ if (await check(update)) {
166
+ resolve();
167
+ }
168
+ };
169
+ ev.on(event, listener);
170
+ }).finally(() => {
171
+ ev.off(event, listener);
172
+ ev.off('connection.update', closeListener);
173
+ });
174
+ };
175
+ }
176
+ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
177
+ /**
178
+ * utility that fetches latest baileys version from the master branch.
179
+ * Use to ensure your WA connection is always on the latest version
180
+ */
181
+ export const fetchLatestBaileysVersion = async (options = {}) => {
182
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/refs/heads/master/src/Defaults/baileys-version.json';
183
+ try {
184
+ const response = await fetch(URL, {
185
+ dispatcher: options.dispatcher,
186
+ method: 'GET',
187
+ headers: options.headers
188
+ });
189
+ if (!response.ok) {
190
+ throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
191
+ }
192
+ const text = await response.json();
193
+ const versionMatch = text.version
194
+ if (versionMatch) {
195
+ const version = versionMatch
196
+ return {
197
+ version,
198
+ isLatest: true
199
+ };
200
+ }
201
+ else {
202
+ throw new Error('Could not parse version from Defaults/index.ts');
203
+ }
204
+ }
205
+ catch (error) {
206
+ return {
207
+ version: baileysVersion,
208
+ isLatest: false,
209
+ error
210
+ };
211
+ }
212
+ };
213
+ /**
214
+ * A utility that fetches the latest web version of whatsapp.
215
+ * Use to ensure your WA connection is always on the latest version
216
+ */
217
+ export const fetchLatestWaWebVersion = async (options = {}) => {
218
+ try {
219
+ // Absolute minimal headers required to bypass anti-bot detection
220
+ const defaultHeaders = {
221
+ 'sec-fetch-site': 'none',
222
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
223
+ };
224
+ const headers = { ...defaultHeaders, ...options.headers };
225
+ const response = await fetch('https://web.whatsapp.com/sw.js', {
226
+ ...options,
227
+ method: 'GET',
228
+ headers
229
+ });
230
+ if (!response.ok) {
231
+ throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
232
+ }
233
+ const data = await response.text();
234
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
235
+ const match = data.match(regex);
236
+ if (!match?.[1]) {
237
+ return {
238
+ version: baileysVersion,
239
+ isLatest: false,
240
+ error: {
241
+ message: 'Could not find client revision in the fetched content'
242
+ }
243
+ };
244
+ }
245
+ const clientRevision = match[1];
246
+ return {
247
+ version: [2, 3000, +clientRevision],
248
+ isLatest: true
249
+ };
250
+ }
251
+ catch (error) {
252
+ return {
253
+ version: baileysVersion,
254
+ isLatest: false,
255
+ error
256
+ };
257
+ }
258
+ };
259
+ /** unique message tag prefix for MD clients */
260
+ export const generateMdTagPrefix = () => {
261
+ const bytes = randomBytes(4);
262
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
263
+ };
264
+ const STATUS_MAP = {
265
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
266
+ played: proto.WebMessageInfo.Status.PLAYED,
267
+ read: proto.WebMessageInfo.Status.READ,
268
+ 'read-self': proto.WebMessageInfo.Status.READ
269
+ };
270
+ /**
271
+ * Given a type of receipt, returns what the new status of the message should be
272
+ * @param type type from receipt
273
+ */
274
+ export const getStatusFromReceiptType = (type) => {
275
+ const status = STATUS_MAP[type];
276
+ if (typeof type === 'undefined') {
277
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
278
+ }
279
+ return status;
280
+ };
281
+ const CODE_MAP = {
282
+ conflict: DisconnectReason.connectionReplaced
283
+ };
284
+ /**
285
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
286
+ * @param reason the string reason given, eg. "conflict"
287
+ */
288
+ export const getErrorCodeFromStreamError = (node) => {
289
+ const [reasonNode] = getAllBinaryNodeChildren(node);
290
+ let reason = reasonNode?.tag || 'unknown';
291
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
292
+ if (statusCode === DisconnectReason.restartRequired) {
293
+ reason = 'restart required';
294
+ }
295
+ return {
296
+ reason,
297
+ statusCode
298
+ };
299
+ };
300
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
301
+ let status;
302
+ switch (tag) {
303
+ case 'offer':
304
+ case 'offer_notice':
305
+ status = 'offer';
306
+ break;
307
+ case 'terminate':
308
+ if (attrs.reason === 'timeout') {
309
+ status = 'timeout';
310
+ }
311
+ else {
312
+ //fired when accepted/rejected/timeout/caller hangs up
313
+ status = 'terminate';
314
+ }
315
+ break;
316
+ case 'reject':
317
+ status = 'reject';
318
+ break;
319
+ case 'accept':
320
+ status = 'accept';
321
+ break;
322
+ default:
323
+ status = 'ringing';
324
+ break;
325
+ }
326
+ return status;
327
+ };
328
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
329
+ export const getCodeFromWSError = (error) => {
330
+ let statusCode = 500;
331
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
332
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
333
+ if (!Number.isNaN(code) && code >= 400) {
334
+ statusCode = code;
335
+ }
336
+ }
337
+ else if (
338
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
339
+ error?.code?.startsWith('E') ||
340
+ error?.message?.includes('timed out')) {
341
+ // handle ETIMEOUT, ENOTFOUND etc
342
+ statusCode = 408;
343
+ }
344
+ return statusCode;
345
+ };
346
+ /**
347
+ * Is the given platform WA business
348
+ * @param platform AuthenticationCreds.platform
349
+ */
350
+ export const isWABusinessPlatform = (platform) => {
351
+ return platform === 'smbi' || platform === 'smba';
352
+ };
353
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
354
+ export function trimUndefined(obj) {
355
+ for (const key in obj) {
356
+ if (typeof obj[key] === 'undefined') {
357
+ delete obj[key];
358
+ }
359
+ }
360
+ return obj;
361
+ }
362
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
363
+ export function bytesToCrockford(buffer) {
364
+ let value = 0;
365
+ let bitCount = 0;
366
+ const crockford = [];
367
+ for (const element of buffer) {
368
+ value = (value << 8) | (element & 0xff);
369
+ bitCount += 8;
370
+ while (bitCount >= 5) {
371
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
372
+ bitCount -= 5;
373
+ }
374
+ }
375
+ if (bitCount > 0) {
376
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
377
+ }
378
+ return crockford.join('');
379
+ }
380
+ export function encodeNewsletterMessage(message) {
381
+ return proto.Message.encode(message).finish();
382
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skycodee/baileys",
3
- "version": "8.0.14",
3
+ "version": "8.0.15",
4
4
  "description": "Websocket Whatsapp API for Node.js",
5
5
  "keywords": [
6
6
  "whatsapp",