@x4r1s3/baileys 0.0.0-stage → 1.0.1
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.
- package/LICENSE +21 -0
- package/README.md +1245 -2
- package/SECURITY.md +47 -0
- package/WAProto/V +1 -0
- package/WAProto/WAProto.proto +8892 -0
- package/WAProto/index.d.ts +104128 -0
- package/WAProto/index.js +334920 -0
- package/assets/rolling-circle.svg +133 -0
- package/assets/x4r1s3-banner.svg +32 -0
- package/engine-requirements.js +27 -0
- package/lib/Builders/A2UI.js +245 -0
- package/lib/Builders/AIRich.js +179 -0
- package/lib/Builders/Button.js +108 -0
- package/lib/Builders/CFC.js +284 -0
- package/lib/Builders/Carousel.js +81 -0
- package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
- package/lib/Call/astralena-v3.mjs +96 -0
- package/lib/Call/audio-feeder.mjs +201 -0
- package/lib/Call/audio-recorder.mjs +250 -0
- package/lib/Call/fetch-wasm-resources.mjs +104 -0
- package/lib/Call/index.mjs +707 -0
- package/lib/Call/relay-transport.mjs +563 -0
- package/lib/Call/signaling.mjs +660 -0
- package/lib/Call/types.mjs +17 -0
- package/lib/Call/video-feeder.mjs +94 -0
- package/lib/Call/voip-resources.mjs +259 -0
- package/lib/Call/wasm-engine.mjs +1372 -0
- package/lib/Call/worker-bootstrap.mjs +1042 -0
- package/lib/Defaults/ban-checker.js +56 -0
- package/lib/Defaults/index.js +170 -0
- package/lib/Signal/Group/ciphertext-message.js +23 -0
- package/lib/Signal/Group/group-session-builder.js +41 -0
- package/lib/Signal/Group/group_cipher.js +93 -0
- package/lib/Signal/Group/index.js +23 -0
- package/lib/Signal/Group/keyhelper.js +29 -0
- package/lib/Signal/Group/sender-chain-key.js +37 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
- package/lib/Signal/Group/sender-key-message.js +77 -0
- package/lib/Signal/Group/sender-key-name.js +59 -0
- package/lib/Signal/Group/sender-key-record.js +52 -0
- package/lib/Signal/Group/sender-key-state.js +95 -0
- package/lib/Signal/Group/sender-message-key.js +37 -0
- package/lib/Signal/libsignal.js +440 -0
- package/lib/Signal/lid-mapping.js +292 -0
- package/lib/Socket/Client/index.js +14 -0
- package/lib/Socket/Client/types.js +22 -0
- package/lib/Socket/Client/websocket.js +65 -0
- package/lib/Socket/aigroups.js +327 -0
- package/lib/Socket/ban-checker.js +165 -0
- package/lib/Socket/business.js +419 -0
- package/lib/Socket/chats.js +1921 -0
- package/lib/Socket/communities.js +443 -0
- package/lib/Socket/graphql.js +911 -0
- package/lib/Socket/groups.js +561 -0
- package/lib/Socket/index.js +49 -0
- package/lib/Socket/interactive-handler.js +612 -0
- package/lib/Socket/interop.js +575 -0
- package/lib/Socket/managed-account.js +220 -0
- package/lib/Socket/messages-recv.js +2193 -0
- package/lib/Socket/messages-send.js +4141 -0
- package/lib/Socket/mex.js +53 -0
- package/lib/Socket/newsletter.js +291 -0
- package/lib/Socket/privacy.js +458 -0
- package/lib/Socket/registration.js +440 -0
- package/lib/Socket/socket.js +1042 -0
- package/lib/Socket/status-actions.js +287 -0
- package/lib/Socket/username.js +241 -0
- package/lib/Store/index.js +16 -0
- package/lib/Store/make-cache-manager-store.js +101 -0
- package/lib/Store/make-in-memory-store.js +432 -0
- package/lib/Store/make-ordered-dictionary.js +90 -0
- package/lib/Store/object-repository.js +35 -0
- package/lib/Types/Auth.js +13 -0
- package/lib/Types/Bussines.js +13 -0
- package/lib/Types/Call.js +13 -0
- package/lib/Types/Chat.js +19 -0
- package/lib/Types/Contact.js +13 -0
- package/lib/Types/Events.js +13 -0
- package/lib/Types/GroupMetadata.js +13 -0
- package/lib/Types/Label.js +36 -0
- package/lib/Types/LabelAssociation.js +18 -0
- package/lib/Types/Message.js +30 -0
- package/lib/Types/Mex.js +53 -0
- package/lib/Types/Product.js +13 -0
- package/lib/Types/RichType.js +34 -0
- package/lib/Types/Signal.js +13 -0
- package/lib/Types/Socket.js +14 -0
- package/lib/Types/State.js +60 -0
- package/lib/Types/USync.js +13 -0
- package/lib/Types/index.js +37 -0
- package/lib/Utils/auth-utils.js +313 -0
- package/lib/Utils/ban-checker.js +48 -0
- package/lib/Utils/bot-capabilities.js +96 -0
- package/lib/Utils/bot-planning-replay.js +177 -0
- package/lib/Utils/browser-utils.js +40 -0
- package/lib/Utils/business.js +242 -0
- package/lib/Utils/c2582.js +147 -0
- package/lib/Utils/chat-utils.js +905 -0
- package/lib/Utils/companion-reg-client-utils.js +104 -0
- package/lib/Utils/consumer-application.js +114 -0
- package/lib/Utils/crypto.js +129 -0
- package/lib/Utils/decode-wa-message.js +496 -0
- package/lib/Utils/direct-chat-theme.js +164 -0
- package/lib/Utils/event-buffer.js +601 -0
- package/lib/Utils/experimental-proto.js +206 -0
- package/lib/Utils/games/miniapp.js +17 -0
- package/lib/Utils/games/slot-machine.js +270 -0
- package/lib/Utils/games/website-preview.js +306 -0
- package/lib/Utils/generics.js +402 -0
- package/lib/Utils/group-history.js +68 -0
- package/lib/Utils/group-wallpaper.js +168 -0
- package/lib/Utils/history.js +162 -0
- package/lib/Utils/identity-change-handler.js +60 -0
- package/lib/Utils/index.js +61 -0
- package/lib/Utils/jid-display-normalization.js +221 -0
- package/lib/Utils/link-preview.js +96 -0
- package/lib/Utils/logger.js +14 -0
- package/lib/Utils/lt-hash.js +19 -0
- package/lib/Utils/make-mutex.js +44 -0
- package/lib/Utils/message-composer.js +709 -0
- package/lib/Utils/message-inspect.js +79 -0
- package/lib/Utils/message-retry-manager.js +253 -0
- package/lib/Utils/message-security.js +167 -0
- package/lib/Utils/messages-media.js +1027 -0
- package/lib/Utils/messages.js +2467 -0
- package/lib/Utils/meta-ai-msmsg.js +215 -0
- package/lib/Utils/meta-compositing.js +239 -0
- package/lib/Utils/native-flow.js +158 -0
- package/lib/Utils/newsletter-live-update-utils.js +74 -0
- package/lib/Utils/newsletter-status-utils.js +152 -0
- package/lib/Utils/noise-handler.js +212 -0
- package/lib/Utils/offline-node-processor.js +51 -0
- package/lib/Utils/poll-manager.js +206 -0
- package/lib/Utils/portable-compat.js +12 -0
- package/lib/Utils/pre-key-manager.js +117 -0
- package/lib/Utils/process-message.js +610 -0
- package/lib/Utils/reporting-utils.js +269 -0
- package/lib/Utils/rich-message-utils.js +2841 -0
- package/lib/Utils/scheduled-message.js +107 -0
- package/lib/Utils/signal.js +212 -0
- package/lib/Utils/source-grep.js +57 -0
- package/lib/Utils/stanza-ack.js +49 -0
- package/lib/Utils/sticker-annotation.js +87 -0
- package/lib/Utils/sync-action-utils.js +59 -0
- package/lib/Utils/tc-token-utils.js +174 -0
- package/lib/Utils/use-multi-file-auth-state.js +132 -0
- package/lib/Utils/use-single-file-auth-state.js +108 -0
- package/lib/Utils/use-sqlite-auth-state.js +120 -0
- package/lib/Utils/validate-connection.js +221 -0
- package/lib/Utils/view-once-utils.js +218 -0
- package/lib/Utils/voip-rekey.js +32 -0
- package/lib/Utils/website-preview.js +27 -0
- package/lib/Utils/welcome-flow.js +228 -0
- package/lib/Utils/x4r1s3.js +144 -0
- package/lib/WABinary/constants.js +1475 -0
- package/lib/WABinary/decode.js +273 -0
- package/lib/WABinary/encode.js +231 -0
- package/lib/WABinary/generic-utils.js +242 -0
- package/lib/WABinary/index.js +17 -0
- package/lib/WABinary/jid-utils.js +107 -0
- package/lib/WABinary/types.js +13 -0
- package/lib/WAM/BinaryInfo.js +21 -0
- package/lib/WAM/constants.js +22864 -0
- package/lib/WAM/encode.js +161 -0
- package/lib/WAM/index.js +15 -0
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
- package/lib/WAUSync/Protocols/index.js +24 -0
- package/lib/WAUSync/USyncQuery.js +213 -0
- package/lib/WAUSync/USyncUser.js +66 -0
- package/lib/WAUSync/index.js +15 -0
- package/lib/antiban.cjs +4726 -0
- package/lib/index.d.ts +1895 -0
- package/lib/index.js +41 -0
- package/package.json +125 -4
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/generics.js
|
|
5
|
+
* About: Generics module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: BufferJSON, getKeyAuthor, isStringNullOrEmpty, writeRandomPadMax16, unpadRandomMax16, generateParticipantHashV2, encodeWAMessage, generateRegistrationId; …
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import { Boom } from '@hapi/boom';
|
|
14
|
+
import { createHash, randomBytes, randomFillSync } from 'crypto';
|
|
15
|
+
import { proto } from '../../WAProto/index.js';
|
|
16
|
+
// Keep resolver fallbacks aligned with Defaults/index.js. If the hosted
|
|
17
|
+
// version endpoint is unavailable, never fall back to an obsolete revision.
|
|
18
|
+
const baileysVersion = [2, 3000, 1040735178];
|
|
19
|
+
import { DisconnectReason } from '../Types/index.js';
|
|
20
|
+
import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js';
|
|
21
|
+
import { sha256 } from './crypto.js';
|
|
22
|
+
export const BufferJSON = {
|
|
23
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
24
|
+
replacer: (k, value) => {
|
|
25
|
+
if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
|
|
26
|
+
return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
|
|
27
|
+
}
|
|
28
|
+
return value;
|
|
29
|
+
},
|
|
30
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
31
|
+
reviver: (_, value) => {
|
|
32
|
+
if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
|
|
33
|
+
return Buffer.from(value.data, 'base64');
|
|
34
|
+
}
|
|
35
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
|
36
|
+
const keys = Object.keys(value);
|
|
37
|
+
if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
|
|
38
|
+
const values = Object.values(value);
|
|
39
|
+
if (values.every(v => typeof v === 'number')) {
|
|
40
|
+
return Buffer.from(values);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || '';
|
|
48
|
+
export const isStringNullOrEmpty = (value) =>
|
|
49
|
+
// eslint-disable-next-line eqeqeq
|
|
50
|
+
value == null || value === '';
|
|
51
|
+
export const writeRandomPadMax16 = (msg) => {
|
|
52
|
+
const pad = randomBytes(1);
|
|
53
|
+
const padLength = (pad[0] & 0x0f) + 1;
|
|
54
|
+
return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
|
|
55
|
+
};
|
|
56
|
+
export const unpadRandomMax16 = (e) => {
|
|
57
|
+
const t = new Uint8Array(e);
|
|
58
|
+
if (0 === t.length) {
|
|
59
|
+
throw new Error('unpadPkcs7 given empty bytes');
|
|
60
|
+
}
|
|
61
|
+
var r = t[t.length - 1];
|
|
62
|
+
if (r > t.length) {
|
|
63
|
+
throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
|
|
64
|
+
}
|
|
65
|
+
return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
|
|
66
|
+
};
|
|
67
|
+
// code is inspired by whatsmeow
|
|
68
|
+
export const generateParticipantHashV2 = (participants) => {
|
|
69
|
+
participants.sort();
|
|
70
|
+
const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
|
|
71
|
+
return '2:' + sha256Hash.slice(0, 6);
|
|
72
|
+
};
|
|
73
|
+
export const encodeWAMessage = (message) => writeRandomPadMax16(proto.Message.encode(message).finish());
|
|
74
|
+
export const generateRegistrationId = () => {
|
|
75
|
+
return Uint16Array.from(randomBytes(2))[0] & 16383;
|
|
76
|
+
};
|
|
77
|
+
export const encodeBigEndian = (e, t = 4) => {
|
|
78
|
+
let r = e;
|
|
79
|
+
const a = new Uint8Array(t);
|
|
80
|
+
for (let i = t - 1; i >= 0; i--) {
|
|
81
|
+
a[i] = 255 & r;
|
|
82
|
+
r >>>= 8;
|
|
83
|
+
}
|
|
84
|
+
return a;
|
|
85
|
+
};
|
|
86
|
+
export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
|
|
87
|
+
/** unix timestamp of a date in seconds */
|
|
88
|
+
export const unixTimestampSeconds = (date = Date.now()) => date / 1000 | 0; // Changed from new Date → Date.now for faster operation
|
|
89
|
+
export const debouncedTimeout = (intervalMs = 1000, task) => {
|
|
90
|
+
let timeout;
|
|
91
|
+
return {
|
|
92
|
+
start: (newIntervalMs, newTask) => {
|
|
93
|
+
task = newTask || task;
|
|
94
|
+
intervalMs = newIntervalMs || intervalMs;
|
|
95
|
+
timeout && clearTimeout(timeout);
|
|
96
|
+
timeout = setTimeout(() => task?.(), intervalMs);
|
|
97
|
+
},
|
|
98
|
+
cancel: () => {
|
|
99
|
+
timeout && clearTimeout(timeout);
|
|
100
|
+
timeout = undefined;
|
|
101
|
+
},
|
|
102
|
+
setTask: (newTask) => (task = newTask),
|
|
103
|
+
setInterval: (newInterval) => (intervalMs = newInterval)
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
export const delay = (ms) => delayCancellable(ms).delay;
|
|
107
|
+
export const delayCancellable = (ms) => {
|
|
108
|
+
const stack = new Error().stack;
|
|
109
|
+
let timeout;
|
|
110
|
+
let reject;
|
|
111
|
+
const delay = new Promise((resolve, _reject) => {
|
|
112
|
+
timeout = setTimeout(resolve, ms);
|
|
113
|
+
reject = _reject;
|
|
114
|
+
});
|
|
115
|
+
const cancel = () => {
|
|
116
|
+
clearTimeout(timeout);
|
|
117
|
+
reject(new Boom('Cancelled', {
|
|
118
|
+
statusCode: 500,
|
|
119
|
+
data: {
|
|
120
|
+
stack
|
|
121
|
+
}
|
|
122
|
+
}));
|
|
123
|
+
};
|
|
124
|
+
return { delay, cancel };
|
|
125
|
+
};
|
|
126
|
+
export async function promiseTimeout(ms, promise) {
|
|
127
|
+
if (!ms) {
|
|
128
|
+
return new Promise(promise);
|
|
129
|
+
}
|
|
130
|
+
const stack = new Error().stack;
|
|
131
|
+
// Create a promise that rejects in <ms> milliseconds
|
|
132
|
+
const { delay, cancel } = delayCancellable(ms);
|
|
133
|
+
const p = new Promise((resolve, reject) => {
|
|
134
|
+
delay
|
|
135
|
+
.then(() => reject(new Boom('Timed Out', {
|
|
136
|
+
statusCode: DisconnectReason.timedOut,
|
|
137
|
+
data: {
|
|
138
|
+
stack
|
|
139
|
+
}
|
|
140
|
+
})))
|
|
141
|
+
.catch(err => reject(err));
|
|
142
|
+
promise(resolve, reject);
|
|
143
|
+
}).finally(cancel);
|
|
144
|
+
return p;
|
|
145
|
+
}
|
|
146
|
+
// inspired from whatsmeow code
|
|
147
|
+
// https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
|
|
148
|
+
export const generateMessageIDV2 = (userId) => {
|
|
149
|
+
const data = Buffer.allocUnsafe(44);
|
|
150
|
+
data.writeBigUInt64BE(BigInt(Date.now() / 1000 | 0), 0);
|
|
151
|
+
if (userId) {
|
|
152
|
+
const userStr = userId.split('@')[0].split(':')[0];
|
|
153
|
+
if (userStr) {
|
|
154
|
+
const len = data.write(userStr, 8);
|
|
155
|
+
data.write('@c.us', 8 + len);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
randomFillSync(data, 28, 16);
|
|
159
|
+
const hash = createHash('sha256').update(data).digest();
|
|
160
|
+
const hex = hash.toString('hex', 0, 9).toUpperCase();
|
|
161
|
+
const baseId = '3EB0' + hex;
|
|
162
|
+
// Lia@Note 09-04-26 --- Fixed stamp position (not hash-derived) so the
|
|
163
|
+
// marker lands at the same index in every generated ID. @x4r1s3/baileys
|
|
164
|
+
// X4R1S3 is the package-owned stamp used in generated message IDs.
|
|
165
|
+
const pos = 4;
|
|
166
|
+
return baseId.slice(0, pos) + 'X4R1S3' + baseId.slice(pos);
|
|
167
|
+
};
|
|
168
|
+
// generate a random ID to attach to a message
|
|
169
|
+
export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase();
|
|
170
|
+
export function bindWaitForEvent(ev, event) {
|
|
171
|
+
return async (check, timeoutMs) => {
|
|
172
|
+
let listener;
|
|
173
|
+
let closeListener;
|
|
174
|
+
await promiseTimeout(timeoutMs, (resolve, reject) => {
|
|
175
|
+
closeListener = ({ connection, lastDisconnect }) => {
|
|
176
|
+
if (connection === 'close') {
|
|
177
|
+
reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
ev.on('connection.update', closeListener);
|
|
181
|
+
listener = async (update) => {
|
|
182
|
+
if (await check(update)) {
|
|
183
|
+
resolve();
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
ev.on(event, listener);
|
|
187
|
+
}).finally(() => {
|
|
188
|
+
ev.off(event, listener);
|
|
189
|
+
ev.off('connection.update', closeListener);
|
|
190
|
+
});
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
|
|
194
|
+
/**
|
|
195
|
+
* utility that fetches latest baileys version from the master branch.
|
|
196
|
+
* Use to ensure your WA connection is always on the latest version
|
|
197
|
+
*/
|
|
198
|
+
export const fetchLatestBaileysVersion = async (options = {}) => {
|
|
199
|
+
const URL = 'https://www.npmjs.com/package/@x4r1s3/baileys';
|
|
200
|
+
try {
|
|
201
|
+
const response = await fetch(URL, {
|
|
202
|
+
dispatcher: options.dispatcher,
|
|
203
|
+
method: 'GET',
|
|
204
|
+
headers: options.headers
|
|
205
|
+
});
|
|
206
|
+
if (!response.ok) {
|
|
207
|
+
throw new Boom(`Failed to fetch latest X4R1S3/bailey version: ${response.statusText}`, { statusCode: response.status });
|
|
208
|
+
}
|
|
209
|
+
const text = await response.text();
|
|
210
|
+
// Extract version from line 5 (const version = [...])
|
|
211
|
+
const lines = text.split('\n');
|
|
212
|
+
const versionLine = lines[4]; // Line 5 (0-indexed)
|
|
213
|
+
const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
|
|
214
|
+
if (versionMatch) {
|
|
215
|
+
const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
|
|
216
|
+
return {
|
|
217
|
+
version,
|
|
218
|
+
isLatest: true
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
throw new Error('Could not parse version from Defaults/index.ts');
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
return {
|
|
227
|
+
version: baileysVersion,
|
|
228
|
+
isLatest: false,
|
|
229
|
+
error
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
/**
|
|
234
|
+
* A utility that fetches the latest web version of whatsapp.
|
|
235
|
+
* Use to ensure your WA connection is always on the latest version
|
|
236
|
+
*/
|
|
237
|
+
export const fetchLatestWaWebVersion = async (options = {}) => {
|
|
238
|
+
try {
|
|
239
|
+
// Absolute minimal headers required to bypass anti-bot detection
|
|
240
|
+
const defaultHeaders = {
|
|
241
|
+
'sec-fetch-site': 'none',
|
|
242
|
+
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
|
|
243
|
+
};
|
|
244
|
+
const headers = { ...defaultHeaders, ...options.headers };
|
|
245
|
+
const response = await fetch('https://web.whatsapp.com/sw.js', {
|
|
246
|
+
...options,
|
|
247
|
+
method: 'GET',
|
|
248
|
+
headers
|
|
249
|
+
});
|
|
250
|
+
if (!response.ok) {
|
|
251
|
+
throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
|
|
252
|
+
}
|
|
253
|
+
const data = await response.text();
|
|
254
|
+
const regex = /\\?"client_revision\\?":\s*(\d+)/;
|
|
255
|
+
const match = data.match(regex);
|
|
256
|
+
if (!match?.[1]) {
|
|
257
|
+
return {
|
|
258
|
+
version: baileysVersion,
|
|
259
|
+
isLatest: false,
|
|
260
|
+
error: {
|
|
261
|
+
message: 'Could not find client revision in the fetched content'
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
const clientRevision = match[1];
|
|
266
|
+
return {
|
|
267
|
+
version: [2, 3000, +clientRevision],
|
|
268
|
+
isLatest: true
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
return {
|
|
273
|
+
version: baileysVersion,
|
|
274
|
+
isLatest: false,
|
|
275
|
+
error
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
/** unique message tag prefix for MD clients */
|
|
280
|
+
export const generateMdTagPrefix = () => {
|
|
281
|
+
const bytes = randomBytes(4);
|
|
282
|
+
return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
|
|
283
|
+
};
|
|
284
|
+
const STATUS_MAP = {
|
|
285
|
+
sender: proto.WebMessageInfo.Status.SERVER_ACK,
|
|
286
|
+
played: proto.WebMessageInfo.Status.PLAYED,
|
|
287
|
+
read: proto.WebMessageInfo.Status.READ,
|
|
288
|
+
'read-self': proto.WebMessageInfo.Status.READ
|
|
289
|
+
};
|
|
290
|
+
/**
|
|
291
|
+
* Given a type of receipt, returns what the new status of the message should be
|
|
292
|
+
* @param type type from receipt
|
|
293
|
+
*/
|
|
294
|
+
export const getStatusFromReceiptType = (type) => {
|
|
295
|
+
const status = STATUS_MAP[type];
|
|
296
|
+
if (typeof type === 'undefined') {
|
|
297
|
+
return proto.WebMessageInfo.Status.DELIVERY_ACK;
|
|
298
|
+
}
|
|
299
|
+
return status;
|
|
300
|
+
};
|
|
301
|
+
const CODE_MAP = {
|
|
302
|
+
conflict: DisconnectReason.connectionReplaced
|
|
303
|
+
};
|
|
304
|
+
/**
|
|
305
|
+
* Stream errors generally provide a reason, map that to a baileys DisconnectReason
|
|
306
|
+
* @param reason the string reason given, eg. "conflict"
|
|
307
|
+
*/
|
|
308
|
+
export const getErrorCodeFromStreamError = (node) => {
|
|
309
|
+
const [reasonNode] = getAllBinaryNodeChildren(node);
|
|
310
|
+
let reason = reasonNode?.tag || 'unknown';
|
|
311
|
+
const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
|
|
312
|
+
if (statusCode === DisconnectReason.restartRequired) {
|
|
313
|
+
reason = 'restart required';
|
|
314
|
+
}
|
|
315
|
+
return {
|
|
316
|
+
reason,
|
|
317
|
+
statusCode
|
|
318
|
+
};
|
|
319
|
+
};
|
|
320
|
+
export const getCallStatusFromNode = ({ tag, attrs }) => {
|
|
321
|
+
let status;
|
|
322
|
+
switch (tag) {
|
|
323
|
+
case 'offer':
|
|
324
|
+
case 'offer_notice':
|
|
325
|
+
status = 'offer';
|
|
326
|
+
break;
|
|
327
|
+
case 'terminate':
|
|
328
|
+
if (attrs.reason === 'timeout') {
|
|
329
|
+
status = 'timeout';
|
|
330
|
+
}
|
|
331
|
+
else {
|
|
332
|
+
//fired when accepted/rejected/timeout/caller hangs up
|
|
333
|
+
status = 'terminate';
|
|
334
|
+
}
|
|
335
|
+
break;
|
|
336
|
+
case 'reject':
|
|
337
|
+
status = 'reject';
|
|
338
|
+
break;
|
|
339
|
+
case 'accept':
|
|
340
|
+
status = 'accept';
|
|
341
|
+
break;
|
|
342
|
+
default:
|
|
343
|
+
status = 'ringing';
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
return status;
|
|
347
|
+
};
|
|
348
|
+
const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
|
|
349
|
+
export const getCodeFromWSError = (error) => {
|
|
350
|
+
let statusCode = 500;
|
|
351
|
+
if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
|
|
352
|
+
const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
|
|
353
|
+
if (!Number.isNaN(code) && code >= 400) {
|
|
354
|
+
statusCode = code;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
else if (
|
|
358
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
359
|
+
error?.code?.startsWith('E') ||
|
|
360
|
+
error?.message?.includes('timed out')) {
|
|
361
|
+
// handle ETIMEOUT, ENOTFOUND etc
|
|
362
|
+
statusCode = 408;
|
|
363
|
+
}
|
|
364
|
+
return statusCode;
|
|
365
|
+
};
|
|
366
|
+
/**
|
|
367
|
+
* Is the given platform WA business
|
|
368
|
+
* @param platform AuthenticationCreds.platform
|
|
369
|
+
*/
|
|
370
|
+
export const isWABusinessPlatform = (platform) => {
|
|
371
|
+
return platform === 'smbi' || platform === 'smba';
|
|
372
|
+
};
|
|
373
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
374
|
+
export function trimUndefined(obj) {
|
|
375
|
+
for (const key in obj) {
|
|
376
|
+
if (typeof obj[key] === 'undefined') {
|
|
377
|
+
delete obj[key];
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return obj;
|
|
381
|
+
}
|
|
382
|
+
const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
|
|
383
|
+
export function bytesToCrockford(buffer) {
|
|
384
|
+
let value = 0;
|
|
385
|
+
let bitCount = 0;
|
|
386
|
+
const crockford = [];
|
|
387
|
+
for (const element of buffer) {
|
|
388
|
+
value = (value << 8) | (element & 0xff);
|
|
389
|
+
bitCount += 8;
|
|
390
|
+
while (bitCount >= 5) {
|
|
391
|
+
crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
|
|
392
|
+
bitCount -= 5;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
if (bitCount > 0) {
|
|
396
|
+
crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
|
|
397
|
+
}
|
|
398
|
+
return crockford.join('');
|
|
399
|
+
}
|
|
400
|
+
export function encodeNewsletterMessage(message) {
|
|
401
|
+
return proto.Message.encode(message).finish();
|
|
402
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/group-history.js
|
|
5
|
+
* About: Group history module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: decodeGroupHistory, processGroupHistory
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import { inflateSync } from 'zlib';
|
|
14
|
+
import { proto } from '../../WAProto/index.js';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Decode a GroupHistory protobuf blob (community/group history container).
|
|
18
|
+
* @param buffer raw bytes, optionally zlib-compressed
|
|
19
|
+
* @param options.inflate try zlib.inflateSync first, falling back to raw bytes (default true)
|
|
20
|
+
* @param options.withMessageBytes decode the GroupHistoryWithMessageBytes variant,
|
|
21
|
+
* expanding each entry's messageBytes into a WebMessageInfo (default false)
|
|
22
|
+
*/
|
|
23
|
+
export const decodeGroupHistory = (buffer, options = {}) => {
|
|
24
|
+
const { inflate = true, withMessageBytes = false } = options;
|
|
25
|
+
if (!Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array)) {
|
|
26
|
+
throw new TypeError('decodeGroupHistory: buffer must be Buffer or Uint8Array');
|
|
27
|
+
}
|
|
28
|
+
let data = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
|
|
29
|
+
if (inflate) {
|
|
30
|
+
try {
|
|
31
|
+
data = inflateSync(data);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// not zlib-compressed — use raw bytes
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (withMessageBytes) {
|
|
38
|
+
const decoded = proto.GroupHistoryWithMessageBytes.decode(data);
|
|
39
|
+
const expand = list =>
|
|
40
|
+
(list || []).map(entry =>
|
|
41
|
+
entry?.messageBytes ? proto.WebMessageInfo.decode(entry.messageBytes) : { key: entry?.key }
|
|
42
|
+
);
|
|
43
|
+
return {
|
|
44
|
+
messages: expand(decoded.messages),
|
|
45
|
+
commentMessages: expand(decoded.commentMessages),
|
|
46
|
+
outOfWindowPinnedMessages: expand(decoded.outOfWindowPinnedMessages),
|
|
47
|
+
uncountedAssociatedMessageLists: (decoded.uncountedAssociatedMessageLists || []).map(l => ({
|
|
48
|
+
parentMessage: l.parentMessage,
|
|
49
|
+
messages: expand(l.messages)
|
|
50
|
+
}))
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
return proto.GroupHistory.decode(data);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Normalize a decoded GroupHistory into stable message buckets.
|
|
58
|
+
* @param groupHistory a decoded proto.GroupHistory (or the withMessageBytes shape)
|
|
59
|
+
*/
|
|
60
|
+
export const processGroupHistory = (groupHistory) => {
|
|
61
|
+
const gh = groupHistory || {};
|
|
62
|
+
return {
|
|
63
|
+
messages: gh.messages || [],
|
|
64
|
+
commentMessages: gh.commentMessages || [],
|
|
65
|
+
outOfWindowPinnedMessages: gh.outOfWindowPinnedMessages || [],
|
|
66
|
+
uncountedAssociatedMessageLists: gh.uncountedAssociatedMessageLists || []
|
|
67
|
+
};
|
|
68
|
+
};
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { unlink } from 'node:fs/promises';
|
|
2
|
+
import { proto } from '../../WAProto/index.js';
|
|
3
|
+
import { encryptedStream } from './messages-media.js';
|
|
4
|
+
import { generateMessageIDV2 } from './generics.js';
|
|
5
|
+
|
|
6
|
+
const assertGroupThemeScope = (scope = 'everyone') => {
|
|
7
|
+
if (scope === 'me') {
|
|
8
|
+
throw new Error('Client-only chat theme changes are not supported by this API. No message was sent.');
|
|
9
|
+
}
|
|
10
|
+
if (scope !== 'everyone') {
|
|
11
|
+
throw new TypeError("Chat theme scope must be 'everyone' or 'me'.");
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const relayGroupThemeSetting = async (sock, jid, setting, options = {}) => {
|
|
16
|
+
if (!sock || typeof sock.relayMessage !== 'function') {
|
|
17
|
+
throw new TypeError('Group chat theme changes require a connected socket');
|
|
18
|
+
}
|
|
19
|
+
if (typeof jid !== 'string' || !jid) {
|
|
20
|
+
throw new TypeError('Group chat theme changes require a destination JID');
|
|
21
|
+
}
|
|
22
|
+
assertGroupThemeScope(options.scope);
|
|
23
|
+
|
|
24
|
+
const message = {
|
|
25
|
+
protocolMessage: {
|
|
26
|
+
type: proto.Message.ProtocolMessage.Type.CHAT_THEME_SETTING,
|
|
27
|
+
chatThemeSetting: setting
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const messageId = options.messageId || generateMessageIDV2(sock.user?.id);
|
|
31
|
+
await sock.relayMessage(jid, message, {
|
|
32
|
+
messageId,
|
|
33
|
+
additionalAttributes: { type: 'media' }
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
key: { remoteJid: jid, fromMe: true, id: messageId },
|
|
38
|
+
message,
|
|
39
|
+
submissionStatus: 'written',
|
|
40
|
+
serverOutcome: 'unconfirmed'
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Upload and request a custom wallpaper for everyone in a group chat.
|
|
46
|
+
*
|
|
47
|
+
* This sends a group CHAT_THEME_SETTING. WhatsApp controls permissions, and a
|
|
48
|
+
* resolved relayMessage only confirms that the stanza was written to the
|
|
49
|
+
* socket. It does not confirm server acceptance or that clients applied it.
|
|
50
|
+
*
|
|
51
|
+
* @param {object} sock A connected Baileys socket.
|
|
52
|
+
* @param {string} jid The destination group JID.
|
|
53
|
+
* @param {Buffer|{ url: string }|string|null} image A buffer, URL, or local file path; null restores the default wallpaper.
|
|
54
|
+
* @param {object} [options]
|
|
55
|
+
* @param {'everyone'|'me'} [options.scope='everyone'] 'me' is rejected; Baileys has no verified per-chat local appearance operation.
|
|
56
|
+
* @param {number} [options.dimLevel=0] Wallpaper dim level.
|
|
57
|
+
* @param {number} [options.mediaUploadTimeoutMs] Upload timeout.
|
|
58
|
+
* @param {number} [options.settingTimestampMs] Protocol setting timestamp.
|
|
59
|
+
* @param {string} [options.messageId] Message ID override.
|
|
60
|
+
* @returns {Promise<{key: object, message: object, submissionStatus: 'written', serverOutcome: 'unconfirmed'}>}
|
|
61
|
+
*/
|
|
62
|
+
export const setGroupWallpaper = async (sock, jid, image, options = {}) => {
|
|
63
|
+
assertGroupThemeScope(options.scope);
|
|
64
|
+
if (image === null) {
|
|
65
|
+
return resetGroupWallpaper(sock, jid, options);
|
|
66
|
+
}
|
|
67
|
+
if (!sock || typeof sock.waUploadToServer !== 'function' || typeof sock.relayMessage !== 'function') {
|
|
68
|
+
throw new TypeError('setGroupWallpaper requires a connected socket');
|
|
69
|
+
}
|
|
70
|
+
if (typeof jid !== 'string' || !jid) {
|
|
71
|
+
throw new TypeError('setGroupWallpaper requires a destination JID');
|
|
72
|
+
}
|
|
73
|
+
if (!Buffer.isBuffer(image) && typeof image !== 'string' && !(image && typeof image.url === 'string')) {
|
|
74
|
+
throw new TypeError('setGroupWallpaper image must be a Buffer, URL, or local file path');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const media = Buffer.isBuffer(image) ? image : typeof image === 'string' ? { url: image } : image;
|
|
78
|
+
const upload = await encryptedStream(media, 'chat-wallpaper-image', { logger: sock.logger });
|
|
79
|
+
let directPath;
|
|
80
|
+
try {
|
|
81
|
+
const uploaded = await sock.waUploadToServer(upload.encFilePath, {
|
|
82
|
+
mediaType: 'chat-wallpaper-image',
|
|
83
|
+
fileEncSha256B64: upload.fileEncSha256.toString('base64'),
|
|
84
|
+
timeoutMs: options.mediaUploadTimeoutMs
|
|
85
|
+
});
|
|
86
|
+
directPath = uploaded?.directPath;
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
await unlink(upload.encFilePath).catch(() => undefined);
|
|
90
|
+
}
|
|
91
|
+
if (!directPath) {
|
|
92
|
+
throw new Error('wallpaper upload returned no directPath');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return relayGroupThemeSetting(sock, jid, {
|
|
96
|
+
settingTimestampMs: options.settingTimestampMs ?? Date.now(),
|
|
97
|
+
customImage: {
|
|
98
|
+
directPath,
|
|
99
|
+
mediaKey: upload.mediaKey,
|
|
100
|
+
fileEncSha256: upload.fileEncSha256,
|
|
101
|
+
fileSha256: upload.fileSha256,
|
|
102
|
+
dimLevel: options.dimLevel ?? 0
|
|
103
|
+
}
|
|
104
|
+
}, options);
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Request only a chat color scheme for everyone in a group.
|
|
109
|
+
*
|
|
110
|
+
* The schema represents colorSchemeId separately from the wallpaper oneof.
|
|
111
|
+
* WhatsApp's server-side behavior for omitted fields is not documented, so
|
|
112
|
+
* callers must explicitly opt in to this partial update. This is not described
|
|
113
|
+
* as a bubble-only visual change beyond the colorSchemeId field itself.
|
|
114
|
+
*
|
|
115
|
+
* @param {object} sock A connected Baileys socket.
|
|
116
|
+
* @param {string} jid The destination group JID.
|
|
117
|
+
* @param {string} colorSchemeId Complete WhatsApp color scheme ID.
|
|
118
|
+
* @param {object} options An explicit scope and partial-update acknowledgement.
|
|
119
|
+
* @param {'everyone'|'me'} options.scope Scope of the requested change; 'me' is currently unsupported.
|
|
120
|
+
* @param {true} options.allowUnverifiedPartialUpdate Acknowledge that omitted wallpaper preservation is not verified.
|
|
121
|
+
* @param {number} [options.settingTimestampMs] Protocol setting timestamp.
|
|
122
|
+
* @param {string} [options.messageId] Message ID override.
|
|
123
|
+
* @returns {Promise<{key: object, message: object, submissionStatus: 'written', serverOutcome: 'unconfirmed'}>}
|
|
124
|
+
*/
|
|
125
|
+
export const setGroupColorScheme = async (sock, jid, colorSchemeId, options = {}) => {
|
|
126
|
+
if (options.scope === 'me') {
|
|
127
|
+
assertGroupThemeScope('me');
|
|
128
|
+
}
|
|
129
|
+
if (options.scope !== 'everyone') {
|
|
130
|
+
throw new TypeError("setGroupColorScheme requires an explicit scope of 'everyone'.");
|
|
131
|
+
}
|
|
132
|
+
if (options.allowUnverifiedPartialUpdate !== true) {
|
|
133
|
+
throw new Error('A color-scheme-only update has unverified wallpaper-preservation semantics. Set allowUnverifiedPartialUpdate: true to send it.');
|
|
134
|
+
}
|
|
135
|
+
if (typeof colorSchemeId !== 'string' || !colorSchemeId.trim()) {
|
|
136
|
+
throw new TypeError('setGroupColorScheme requires a non-empty colorSchemeId');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return relayGroupThemeSetting(sock, jid, {
|
|
140
|
+
settingTimestampMs: options.settingTimestampMs ?? Date.now(),
|
|
141
|
+
colorSchemeId: colorSchemeId.trim()
|
|
142
|
+
}, options);
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Restore a group's wallpaper to WhatsApp's default design.
|
|
147
|
+
*
|
|
148
|
+
* This sends a group CHAT_THEME_SETTING, not a client-only preference update.
|
|
149
|
+
* A resolved promise confirms socket write only, not server acceptance or
|
|
150
|
+
* application on group members' clients.
|
|
151
|
+
*
|
|
152
|
+
* @param {object} sock A connected Baileys socket.
|
|
153
|
+
* @param {string} jid The destination group JID.
|
|
154
|
+
* @param {object} [options]
|
|
155
|
+
* @param {'everyone'|'me'} [options.scope='everyone'] 'me' is rejected; Baileys has no verified per-chat local appearance operation.
|
|
156
|
+
* @param {boolean} [options.isDoodleEnabled=true] Whether WhatsApp's default wallpaper doodles are enabled.
|
|
157
|
+
* @param {number} [options.settingTimestampMs] Protocol setting timestamp.
|
|
158
|
+
* @param {string} [options.messageId] Message ID override.
|
|
159
|
+
*/
|
|
160
|
+
export const resetGroupWallpaper = async (sock, jid, options = {}) => {
|
|
161
|
+
assertGroupThemeScope(options.scope);
|
|
162
|
+
return relayGroupThemeSetting(sock, jid, {
|
|
163
|
+
settingTimestampMs: options.settingTimestampMs ?? Date.now(),
|
|
164
|
+
defaultWallpaper: {
|
|
165
|
+
isDoodleEnabled: options.isDoodleEnabled ?? true
|
|
166
|
+
}
|
|
167
|
+
}, options);
|
|
168
|
+
};
|