@sgintokic/baileys 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of @sgintokic/baileys might be problematic. Click here for more details.
- package/LICENSE +22 -0
- package/README.md +1097 -0
- package/WAProto/index.js +2 -0
- package/engine-requirements.js +1 -0
- package/lib/Defaults/index.js +155 -0
- package/lib/Signal/Group/ciphertext-message.js +11 -0
- package/lib/Signal/Group/group-session-builder.js +41 -0
- package/lib/Signal/Group/group_cipher.js +108 -0
- package/lib/Signal/Group/index.js +11 -0
- package/lib/Signal/Group/keyhelper.js +14 -0
- package/lib/Signal/Group/sender-chain-key.js +31 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
- package/lib/Signal/Group/sender-key-message.js +79 -0
- package/lib/Signal/Group/sender-key-name.js +49 -0
- package/lib/Signal/Group/sender-key-record.js +46 -0
- package/lib/Signal/Group/sender-key-state.js +104 -0
- package/lib/Signal/Group/sender-message-key.js +29 -0
- package/lib/Signal/libsignal.js +485 -0
- package/lib/Signal/lid-mapping.js +291 -0
- package/lib/Socket/Client/index.js +2 -0
- package/lib/Socket/Client/types.js +10 -0
- package/lib/Socket/Client/websocket.js +64 -0
- package/lib/Socket/business.js +293 -0
- package/lib/Socket/chats.js +1068 -0
- package/lib/Socket/communities.js +476 -0
- package/lib/Socket/groups.js +383 -0
- package/lib/Socket/index.js +8 -0
- package/lib/Socket/messages-recv.js +1830 -0
- package/lib/Socket/messages-send.js +1462 -0
- package/lib/Socket/mex.js +55 -0
- package/lib/Socket/newsletter.js +277 -0
- package/lib/Socket/socket.js +1087 -0
- package/lib/Store/index.js +3 -0
- package/lib/Store/make-in-memory-store.js +517 -0
- package/lib/Store/make-ordered-dictionary.js +75 -0
- package/lib/Store/object-repository.js +23 -0
- package/lib/Types/Auth.js +1 -0
- package/lib/Types/Bussines.js +1 -0
- package/lib/Types/Call.js +1 -0
- package/lib/Types/Chat.js +7 -0
- package/lib/Types/Contact.js +1 -0
- package/lib/Types/Events.js +1 -0
- package/lib/Types/GroupMetadata.js +1 -0
- package/lib/Types/Label.js +24 -0
- package/lib/Types/LabelAssociation.js +6 -0
- package/lib/Types/Message.js +18 -0
- package/lib/Types/Newsletter.js +33 -0
- package/lib/Types/Product.js +1 -0
- package/lib/Types/Signal.js +1 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.js +15 -0
- package/lib/Types/USync.js +1 -0
- package/lib/Types/index.js +31 -0
- package/lib/Utils/auth-utils.js +293 -0
- package/lib/Utils/browser-utils.js +32 -0
- package/lib/Utils/business.js +245 -0
- package/lib/Utils/chat-utils.js +959 -0
- package/lib/Utils/crypto.js +133 -0
- package/lib/Utils/decode-wa-message.js +376 -0
- package/lib/Utils/event-buffer.js +620 -0
- package/lib/Utils/generics.js +417 -0
- package/lib/Utils/history.js +150 -0
- package/lib/Utils/identity-change-handler.js +63 -0
- package/lib/Utils/index.js +21 -0
- package/lib/Utils/link-preview.js +91 -0
- package/lib/Utils/logger.js +2 -0
- package/lib/Utils/lt-hash.js +6 -0
- package/lib/Utils/make-mutex.js +31 -0
- package/lib/Utils/message-retry-manager.js +240 -0
- package/lib/Utils/messages-media.js +901 -0
- package/lib/Utils/messages.js +2052 -0
- package/lib/Utils/noise-handler.js +229 -0
- package/lib/Utils/offline-node-processor.js +50 -0
- package/lib/Utils/pre-key-manager.js +119 -0
- package/lib/Utils/process-message.js +641 -0
- package/lib/Utils/reporting-utils.js +346 -0
- package/lib/Utils/signal.js +188 -0
- package/lib/Utils/stanza-ack.js +33 -0
- package/lib/Utils/sync-action-utils.js +53 -0
- package/lib/Utils/tc-token-utils.js +15 -0
- package/lib/Utils/use-multi-file-auth-state.js +116 -0
- package/lib/Utils/use-single-file-auth-state.js +94 -0
- package/lib/Utils/validate-connection.js +235 -0
- package/lib/WABinary/constants.js +1300 -0
- package/lib/WABinary/decode.js +258 -0
- package/lib/WABinary/encode.js +219 -0
- package/lib/WABinary/generic-utils.js +203 -0
- package/lib/WABinary/index.js +5 -0
- package/lib/WABinary/jid-utils.js +93 -0
- package/lib/WABinary/types.js +1 -0
- package/lib/WAM/BinaryInfo.js +9 -0
- package/lib/WAM/constants.js +20669 -0
- package/lib/WAM/encode.js +151 -0
- package/lib/WAM/index.js +3 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +21 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +29 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +59 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +21 -0
- package/lib/WAUSync/Protocols/index.js +4 -0
- package/lib/WAUSync/USyncQuery.js +103 -0
- package/lib/WAUSync/USyncUser.js +22 -0
- package/lib/WAUSync/index.js +3 -0
- package/lib/index.js +11 -0
- package/package.json +58 -0
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
import { Boom } from "@hapi/boom";
|
|
2
|
+
import { createHash, randomBytes } from "crypto";
|
|
3
|
+
import { proto } from "../../WAProto/index.js";
|
|
4
|
+
import { DEFAULT_CONNECTION_CONFIG as config } from "../Defaults/index.js";
|
|
5
|
+
const baileysVersion = [2, 3e3, 1035194821];
|
|
6
|
+
import { DisconnectReason } from "../Types/index.js";
|
|
7
|
+
import { getAllBinaryNodeChildren, jidDecode } from "../WABinary/index.js";
|
|
8
|
+
import { sha256 } from "./crypto.js";
|
|
9
|
+
export const BufferJSON = {
|
|
10
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
11
|
+
replacer: (k, value) => {
|
|
12
|
+
if (
|
|
13
|
+
Buffer.isBuffer(value) ||
|
|
14
|
+
value instanceof Uint8Array ||
|
|
15
|
+
value?.type === "Buffer"
|
|
16
|
+
) {
|
|
17
|
+
return {
|
|
18
|
+
type: "Buffer",
|
|
19
|
+
data: Buffer.from(value?.data || value).toString("base64"),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
},
|
|
24
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
25
|
+
reviver: (_, value) => {
|
|
26
|
+
if (
|
|
27
|
+
typeof value === "object" &&
|
|
28
|
+
value !== null &&
|
|
29
|
+
value.type === "Buffer" &&
|
|
30
|
+
typeof value.data === "string"
|
|
31
|
+
) {
|
|
32
|
+
return Buffer.from(value.data, "base64");
|
|
33
|
+
}
|
|
34
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
35
|
+
const keys = Object.keys(value);
|
|
36
|
+
if (keys.length > 0 && keys.every((k) => !isNaN(parseInt(k, 10)))) {
|
|
37
|
+
const values = Object.values(value);
|
|
38
|
+
if (values.every((v) => typeof v === "number")) {
|
|
39
|
+
return Buffer.from(values);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return value;
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
export const getKeyAuthor = (key, meId = "me") =>
|
|
47
|
+
(key?.fromMe
|
|
48
|
+
? meId
|
|
49
|
+
: key?.participantAlt ||
|
|
50
|
+
key?.remoteJidAlt ||
|
|
51
|
+
key?.participant ||
|
|
52
|
+
key?.remoteJid) || "";
|
|
53
|
+
export const isStringNullOrEmpty = (value) =>
|
|
54
|
+
// eslint-disable-next-line eqeqeq
|
|
55
|
+
value == null || value === "";
|
|
56
|
+
export const writeRandomPadMax16 = (msg) => {
|
|
57
|
+
const pad = randomBytes(1);
|
|
58
|
+
const padLength = (pad[0] & 15) + 1;
|
|
59
|
+
return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
|
|
60
|
+
};
|
|
61
|
+
export const unpadRandomMax16 = (e) => {
|
|
62
|
+
const t = new Uint8Array(e);
|
|
63
|
+
if (0 === t.length) {
|
|
64
|
+
throw new Error("unpadPkcs7 given empty bytes");
|
|
65
|
+
}
|
|
66
|
+
var r = t[t.length - 1];
|
|
67
|
+
if (r > t.length) {
|
|
68
|
+
throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
|
|
69
|
+
}
|
|
70
|
+
return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
|
|
71
|
+
};
|
|
72
|
+
// code is inspired by whatsmeow
|
|
73
|
+
export const generateParticipantHashV2 = (participants) => {
|
|
74
|
+
participants.sort();
|
|
75
|
+
const sha256Hash = sha256(Buffer.from(participants.join(""))).toString(
|
|
76
|
+
"base64",
|
|
77
|
+
);
|
|
78
|
+
return "2:" + sha256Hash.slice(0, 6);
|
|
79
|
+
};
|
|
80
|
+
export const encodeWAMessage = (message) =>
|
|
81
|
+
writeRandomPadMax16(proto.Message.encode(message).finish());
|
|
82
|
+
export const generateRegistrationId = () => {
|
|
83
|
+
return Uint16Array.from(randomBytes(2))[0] & 16383;
|
|
84
|
+
};
|
|
85
|
+
export const encodeBigEndian = (e, t = 4) => {
|
|
86
|
+
let r = e;
|
|
87
|
+
const a = new Uint8Array(t);
|
|
88
|
+
for (let i = t - 1; i >= 0; i--) {
|
|
89
|
+
a[i] = 255 & r;
|
|
90
|
+
r >>>= 8;
|
|
91
|
+
}
|
|
92
|
+
return a;
|
|
93
|
+
};
|
|
94
|
+
export const toNumber = (t) =>
|
|
95
|
+
typeof t === "object" && t
|
|
96
|
+
? "toNumber" in t
|
|
97
|
+
? t.toNumber()
|
|
98
|
+
: t.low
|
|
99
|
+
: t || 0;
|
|
100
|
+
/** unix timestamp of a date in seconds */ export const unixTimestampSeconds = (
|
|
101
|
+
date = Date.now(),
|
|
102
|
+
) => (date / 1e3) | 0; // Changed from new Date → Date.now for faster operation
|
|
103
|
+
export const debouncedTimeout = (intervalMs = 1e3, task) => {
|
|
104
|
+
let timeout;
|
|
105
|
+
return {
|
|
106
|
+
start: (newIntervalMs, newTask) => {
|
|
107
|
+
task = newTask || task;
|
|
108
|
+
intervalMs = newIntervalMs || intervalMs;
|
|
109
|
+
timeout && clearTimeout(timeout);
|
|
110
|
+
timeout = setTimeout(() => task?.(), intervalMs);
|
|
111
|
+
},
|
|
112
|
+
cancel: () => {
|
|
113
|
+
timeout && clearTimeout(timeout);
|
|
114
|
+
timeout = undefined;
|
|
115
|
+
},
|
|
116
|
+
setTask: (newTask) => (task = newTask),
|
|
117
|
+
setInterval: (newInterval) => (intervalMs = newInterval),
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
export const delay = (ms) => delayCancellable(ms).delay;
|
|
121
|
+
export const delayCancellable = (ms) => {
|
|
122
|
+
const stack = new Error().stack;
|
|
123
|
+
let timeout;
|
|
124
|
+
let reject;
|
|
125
|
+
const delay = new Promise((resolve, _reject) => {
|
|
126
|
+
timeout = setTimeout(resolve, ms);
|
|
127
|
+
reject = _reject;
|
|
128
|
+
});
|
|
129
|
+
const cancel = () => {
|
|
130
|
+
clearTimeout(timeout);
|
|
131
|
+
reject(new Boom("Cancelled", { statusCode: 500, data: { stack: stack } }));
|
|
132
|
+
};
|
|
133
|
+
return { delay: delay, cancel: cancel };
|
|
134
|
+
};
|
|
135
|
+
export async function promiseTimeout(ms, promise) {
|
|
136
|
+
if (!ms) {
|
|
137
|
+
return new Promise(promise);
|
|
138
|
+
}
|
|
139
|
+
const stack = new Error().stack;
|
|
140
|
+
// Create a promise that rejects in <ms> milliseconds
|
|
141
|
+
const { delay, cancel } = delayCancellable(ms);
|
|
142
|
+
const p = new Promise((resolve, reject) => {
|
|
143
|
+
delay
|
|
144
|
+
.then(() =>
|
|
145
|
+
reject(
|
|
146
|
+
new Boom("Timed Out", {
|
|
147
|
+
statusCode: DisconnectReason.timedOut,
|
|
148
|
+
data: { stack: stack },
|
|
149
|
+
}),
|
|
150
|
+
),
|
|
151
|
+
)
|
|
152
|
+
.catch((err) => reject(err));
|
|
153
|
+
promise(resolve, reject);
|
|
154
|
+
}).finally(cancel);
|
|
155
|
+
return p;
|
|
156
|
+
}
|
|
157
|
+
// inspired from whatsmeow code
|
|
158
|
+
// https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
|
|
159
|
+
export const generateMessageIDV2 = (userId) => {
|
|
160
|
+
const idFromConfig =
|
|
161
|
+
typeof config.generateMessageIDV2 === "function"
|
|
162
|
+
? config.generateMessageIDV2(userId)
|
|
163
|
+
: null;
|
|
164
|
+
|
|
165
|
+
if (typeof idFromConfig === "string" && idFromConfig) {
|
|
166
|
+
return idFromConfig;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const data = Buffer.allocUnsafe(8 + 20 + 16);
|
|
170
|
+
data.writeBigUInt64BE(BigInt(unixTimestampSeconds()));
|
|
171
|
+
|
|
172
|
+
if (userId) {
|
|
173
|
+
const id = jidDecode(userId);
|
|
174
|
+
if (id?.user) {
|
|
175
|
+
const len = data.write(id.user, 8);
|
|
176
|
+
data.write("@c.us", 8 + len);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
randomBytes(16).copy(data, 28);
|
|
181
|
+
const hash = createHash("sha256").update(data).digest();
|
|
182
|
+
const hex = hash.toString("hex").toUpperCase();
|
|
183
|
+
return hex.substring(0, 32);
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
export const generateMessageID = () => {
|
|
187
|
+
const idFromConfig =
|
|
188
|
+
typeof config.generateMessageID === "function"
|
|
189
|
+
? config.generateMessageID()
|
|
190
|
+
: null;
|
|
191
|
+
|
|
192
|
+
if (typeof idFromConfig === "string" && idFromConfig) {
|
|
193
|
+
return idFromConfig;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return randomBytes(32).toString("hex").toUpperCase();
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
export function bindWaitForEvent(ev, event) {
|
|
200
|
+
return async (check, timeoutMs) => {
|
|
201
|
+
let listener;
|
|
202
|
+
let closeListener;
|
|
203
|
+
await promiseTimeout(timeoutMs, (resolve, reject) => {
|
|
204
|
+
closeListener = ({ connection, lastDisconnect }) => {
|
|
205
|
+
if (connection === "close") {
|
|
206
|
+
reject(
|
|
207
|
+
lastDisconnect?.error ||
|
|
208
|
+
new Boom("Connection Closed", {
|
|
209
|
+
statusCode: DisconnectReason.connectionClosed,
|
|
210
|
+
}),
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
ev.on("connection.update", closeListener);
|
|
215
|
+
listener = async (update) => {
|
|
216
|
+
if (await check(update)) {
|
|
217
|
+
resolve();
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
ev.on(event, listener);
|
|
221
|
+
}).finally(() => {
|
|
222
|
+
ev.off(event, listener);
|
|
223
|
+
ev.off("connection.update", closeListener);
|
|
224
|
+
});
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
export const bindWaitForConnectionUpdate = (ev) =>
|
|
228
|
+
bindWaitForEvent(ev, "connection.update");
|
|
229
|
+
/**
|
|
230
|
+
* utility that fetches latest baileys version from the master branch.
|
|
231
|
+
* Use to ensure your WA connection is always on the latest version
|
|
232
|
+
*/ export const fetchLatestBaileysVersion = async (options = {}) => {
|
|
233
|
+
const URL =
|
|
234
|
+
"https://raw.githubusercontent.com/whiskeysockets/baileys/master/src/Defaults/baileys-version.json";
|
|
235
|
+
try {
|
|
236
|
+
const response = await fetch(URL, {
|
|
237
|
+
dispatcher: options.dispatcher,
|
|
238
|
+
method: "GET",
|
|
239
|
+
headers: options.headers,
|
|
240
|
+
});
|
|
241
|
+
if (!response.ok) {
|
|
242
|
+
throw new Boom(
|
|
243
|
+
`Failed to fetch latest Baileys version: ${response.statusText}`,
|
|
244
|
+
{ statusCode: response.status },
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
const json = await response.json();
|
|
248
|
+
if (Array.isArray(json.version)) {
|
|
249
|
+
return { version: json.version, isLatest: true };
|
|
250
|
+
} else {
|
|
251
|
+
throw new Error("Could not get baileys version");
|
|
252
|
+
}
|
|
253
|
+
} catch (error) {
|
|
254
|
+
return { version: baileysVersion, isLatest: false, error: error };
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
/**
|
|
258
|
+
* A utility that fetches the latest web version of whatsapp.
|
|
259
|
+
* Use to ensure your WA connection is always on the latest version
|
|
260
|
+
*/ export const fetchLatestWaWebVersion = async (options = {}) => {
|
|
261
|
+
try {
|
|
262
|
+
// Absolute minimal headers required to bypass anti-bot detection
|
|
263
|
+
const defaultHeaders = {
|
|
264
|
+
"sec-fetch-site": "none",
|
|
265
|
+
"user-agent":
|
|
266
|
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
|
267
|
+
};
|
|
268
|
+
const headers = { ...defaultHeaders, ...options.headers };
|
|
269
|
+
const response = await fetch("https://web.whatsapp.com/sw.js", {
|
|
270
|
+
...options,
|
|
271
|
+
method: "GET",
|
|
272
|
+
headers: headers,
|
|
273
|
+
});
|
|
274
|
+
if (!response.ok) {
|
|
275
|
+
throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, {
|
|
276
|
+
statusCode: response.status,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
const data = await response.text();
|
|
280
|
+
const regex = /\\?"client_revision\\?":\s*(\d+)/;
|
|
281
|
+
const match = data.match(regex);
|
|
282
|
+
if (!match?.[1]) {
|
|
283
|
+
return {
|
|
284
|
+
version: baileysVersion,
|
|
285
|
+
isLatest: false,
|
|
286
|
+
error: {
|
|
287
|
+
message: "Could not find client revision in the fetched content",
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
const clientRevision = match[1];
|
|
292
|
+
return { version: [2, 3e3, +clientRevision], isLatest: true };
|
|
293
|
+
} catch (error) {
|
|
294
|
+
return { version: baileysVersion, isLatest: false, error: error };
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
/** unique message tag prefix for MD clients */ export const generateMdTagPrefix =
|
|
298
|
+
() => {
|
|
299
|
+
const bytes = randomBytes(4);
|
|
300
|
+
return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
|
|
301
|
+
};
|
|
302
|
+
const STATUS_MAP = {
|
|
303
|
+
sender: proto.WebMessageInfo.Status.SERVER_ACK,
|
|
304
|
+
played: proto.WebMessageInfo.Status.PLAYED,
|
|
305
|
+
read: proto.WebMessageInfo.Status.READ,
|
|
306
|
+
"read-self": proto.WebMessageInfo.Status.READ,
|
|
307
|
+
};
|
|
308
|
+
/**
|
|
309
|
+
* Given a type of receipt, returns what the new status of the message should be
|
|
310
|
+
* @param type type from receipt
|
|
311
|
+
*/ export const getStatusFromReceiptType = (type) => {
|
|
312
|
+
const status = STATUS_MAP[type];
|
|
313
|
+
if (typeof type === "undefined") {
|
|
314
|
+
return proto.WebMessageInfo.Status.DELIVERY_ACK;
|
|
315
|
+
}
|
|
316
|
+
return status;
|
|
317
|
+
};
|
|
318
|
+
const CODE_MAP = { conflict: DisconnectReason.connectionReplaced };
|
|
319
|
+
/**
|
|
320
|
+
* Stream errors generally provide a reason, map that to a baileys DisconnectReason
|
|
321
|
+
* @param reason the string reason given, eg. "conflict"
|
|
322
|
+
*/ export const getErrorCodeFromStreamError = (node) => {
|
|
323
|
+
const [reasonNode] = getAllBinaryNodeChildren(node);
|
|
324
|
+
let reason = reasonNode?.tag || "unknown";
|
|
325
|
+
const statusCode = +(
|
|
326
|
+
node.attrs.code ||
|
|
327
|
+
CODE_MAP[reason] ||
|
|
328
|
+
DisconnectReason.badSession
|
|
329
|
+
);
|
|
330
|
+
if (statusCode === DisconnectReason.restartRequired) {
|
|
331
|
+
reason = "restart required";
|
|
332
|
+
}
|
|
333
|
+
return { reason: reason, statusCode: statusCode };
|
|
334
|
+
};
|
|
335
|
+
export const getCallStatusFromNode = ({ tag, attrs }) => {
|
|
336
|
+
let status;
|
|
337
|
+
switch (tag) {
|
|
338
|
+
case "offer":
|
|
339
|
+
case "offer_notice":
|
|
340
|
+
status = "offer";
|
|
341
|
+
break;
|
|
342
|
+
case "terminate":
|
|
343
|
+
if (attrs.reason === "timeout") {
|
|
344
|
+
status = "timeout";
|
|
345
|
+
} else {
|
|
346
|
+
//fired when accepted/rejected/timeout/caller hangs up
|
|
347
|
+
status = "terminate";
|
|
348
|
+
}
|
|
349
|
+
break;
|
|
350
|
+
case "reject":
|
|
351
|
+
status = "reject";
|
|
352
|
+
break;
|
|
353
|
+
case "accept":
|
|
354
|
+
status = "accept";
|
|
355
|
+
break;
|
|
356
|
+
default:
|
|
357
|
+
status = "ringing";
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
return status;
|
|
361
|
+
};
|
|
362
|
+
const UNEXPECTED_SERVER_CODE_TEXT = "Unexpected server response: ";
|
|
363
|
+
export const getCodeFromWSError = (error) => {
|
|
364
|
+
let statusCode = 500;
|
|
365
|
+
if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
|
|
366
|
+
const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
|
|
367
|
+
if (!Number.isNaN(code) && code >= 400) {
|
|
368
|
+
statusCode = code;
|
|
369
|
+
}
|
|
370
|
+
} else if (
|
|
371
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
372
|
+
error?.code?.startsWith("E") ||
|
|
373
|
+
error?.message?.includes("timed out")
|
|
374
|
+
) {
|
|
375
|
+
// handle ETIMEOUT, ENOTFOUND etc
|
|
376
|
+
statusCode = 408;
|
|
377
|
+
}
|
|
378
|
+
return statusCode;
|
|
379
|
+
};
|
|
380
|
+
/**
|
|
381
|
+
* Is the given platform WA business
|
|
382
|
+
* @param platform AuthenticationCreds.platform
|
|
383
|
+
*/ export const isWABusinessPlatform = (platform) => {
|
|
384
|
+
return platform === "smbi" || platform === "smba";
|
|
385
|
+
};
|
|
386
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
387
|
+
export function trimUndefined(obj) {
|
|
388
|
+
for (const key in obj) {
|
|
389
|
+
if (typeof obj[key] === "undefined") {
|
|
390
|
+
delete obj[key];
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return obj;
|
|
394
|
+
}
|
|
395
|
+
const CROCKFORD_CHARACTERS = "123456789ABCDEFGHJKLMNPQRSTVWXYZ";
|
|
396
|
+
export function bytesToCrockford(buffer) {
|
|
397
|
+
let value = 0;
|
|
398
|
+
let bitCount = 0;
|
|
399
|
+
const crockford = [];
|
|
400
|
+
for (const element of buffer) {
|
|
401
|
+
value = (value << 8) | (element & 255);
|
|
402
|
+
bitCount += 8;
|
|
403
|
+
while (bitCount >= 5) {
|
|
404
|
+
crockford.push(
|
|
405
|
+
CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31),
|
|
406
|
+
);
|
|
407
|
+
bitCount -= 5;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
if (bitCount > 0) {
|
|
411
|
+
crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
|
|
412
|
+
}
|
|
413
|
+
return crockford.join("");
|
|
414
|
+
}
|
|
415
|
+
export function encodeNewsletterMessage(message) {
|
|
416
|
+
return proto.Message.encode(message).finish();
|
|
417
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { promisify } from "util";
|
|
2
|
+
import { inflate } from "zlib";
|
|
3
|
+
import { proto } from "../../WAProto/index.js";
|
|
4
|
+
import { WAMessageStubType } from "../Types/index.js";
|
|
5
|
+
import {
|
|
6
|
+
isHostedLidUser,
|
|
7
|
+
isHostedPnUser,
|
|
8
|
+
isLidUser,
|
|
9
|
+
isPnUser,
|
|
10
|
+
} from "../WABinary/index.js";
|
|
11
|
+
import { toNumber } from "./generics.js";
|
|
12
|
+
import { normalizeMessageContent } from "./messages.js";
|
|
13
|
+
import { downloadContentFromMessage } from "./messages-media.js";
|
|
14
|
+
const inflatePromise = promisify(inflate);
|
|
15
|
+
const extractPnFromMessages = (messages) => {
|
|
16
|
+
for (const msgItem of messages) {
|
|
17
|
+
const message = msgItem.message;
|
|
18
|
+
// Only extract from outgoing messages (fromMe: true) in 1:1 chats
|
|
19
|
+
// because userReceipt.userJid is the recipient's JID
|
|
20
|
+
if (!message?.key?.fromMe || !message.userReceipt?.length) {
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
const userJid = message.userReceipt[0]?.userJid;
|
|
24
|
+
if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
|
|
25
|
+
return userJid;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return undefined;
|
|
29
|
+
};
|
|
30
|
+
export const downloadHistory = async (msg, options) => {
|
|
31
|
+
const stream = await downloadContentFromMessage(msg, "md-msg-hist", {
|
|
32
|
+
options: options,
|
|
33
|
+
});
|
|
34
|
+
const bufferArray = [];
|
|
35
|
+
for await (const chunk of stream) {
|
|
36
|
+
bufferArray.push(chunk);
|
|
37
|
+
}
|
|
38
|
+
let buffer = Buffer.concat(bufferArray);
|
|
39
|
+
// decompress buffer
|
|
40
|
+
buffer = await inflatePromise(buffer);
|
|
41
|
+
const syncData = proto.HistorySync.decode(buffer);
|
|
42
|
+
return syncData;
|
|
43
|
+
};
|
|
44
|
+
export const processHistoryMessage = (item, logger) => {
|
|
45
|
+
const messages = [];
|
|
46
|
+
const contacts = [];
|
|
47
|
+
const chats = [];
|
|
48
|
+
const lidPnMappings = [];
|
|
49
|
+
logger?.trace(
|
|
50
|
+
{ progress: item.progress },
|
|
51
|
+
"processing history of type " + item.syncType?.toString(),
|
|
52
|
+
);
|
|
53
|
+
// Extract LID-PN mappings for all sync types
|
|
54
|
+
for (const m of item.phoneNumberToLidMappings || []) {
|
|
55
|
+
if (m.lidJid && m.pnJid) {
|
|
56
|
+
lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
switch (item.syncType) {
|
|
60
|
+
case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
|
|
61
|
+
case proto.HistorySync.HistorySyncType.RECENT:
|
|
62
|
+
case proto.HistorySync.HistorySyncType.FULL:
|
|
63
|
+
case proto.HistorySync.HistorySyncType.ON_DEMAND:
|
|
64
|
+
for (const chat of item.conversations) {
|
|
65
|
+
contacts.push({
|
|
66
|
+
id: chat.id,
|
|
67
|
+
name: chat.displayName || chat.name || chat.username || undefined,
|
|
68
|
+
lid: chat.lidJid || chat.accountLid || undefined,
|
|
69
|
+
phoneNumber: chat.pnJid || undefined,
|
|
70
|
+
});
|
|
71
|
+
const chatId = chat.id;
|
|
72
|
+
const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
|
|
73
|
+
const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
|
|
74
|
+
if (isLid && chat.pnJid) {
|
|
75
|
+
lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
|
|
76
|
+
} else if (isPn && chat.lidJid) {
|
|
77
|
+
lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
|
|
78
|
+
} else if (isLid && !chat.pnJid) {
|
|
79
|
+
// Fallback: extract PN from userReceipt in messages when pnJid is missing
|
|
80
|
+
const pnFromReceipt = extractPnFromMessages(chat.messages || []);
|
|
81
|
+
if (pnFromReceipt) {
|
|
82
|
+
lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const msgs = chat.messages || [];
|
|
86
|
+
delete chat.messages;
|
|
87
|
+
for (const item of msgs) {
|
|
88
|
+
const message = item.message;
|
|
89
|
+
messages.push(message);
|
|
90
|
+
if (!chat.messages?.length) {
|
|
91
|
+
// keep only the most recent message in the chat array
|
|
92
|
+
chat.messages = [{ message: message }];
|
|
93
|
+
}
|
|
94
|
+
if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
|
|
95
|
+
chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
|
|
96
|
+
}
|
|
97
|
+
if (
|
|
98
|
+
(message.messageStubType ===
|
|
99
|
+
WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
|
|
100
|
+
message.messageStubType ===
|
|
101
|
+
WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
|
|
102
|
+
message.messageStubParameters?.[0]
|
|
103
|
+
) {
|
|
104
|
+
contacts.push({
|
|
105
|
+
id: message.key.participant || message.key.remoteJid,
|
|
106
|
+
verifiedName: message.messageStubParameters?.[0],
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
chats.push({ ...chat });
|
|
111
|
+
}
|
|
112
|
+
break;
|
|
113
|
+
case proto.HistorySync.HistorySyncType.PUSH_NAME:
|
|
114
|
+
for (const c of item.pushnames) {
|
|
115
|
+
contacts.push({ id: c.id, notify: c.pushname });
|
|
116
|
+
}
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
chats: chats,
|
|
121
|
+
contacts: contacts,
|
|
122
|
+
messages: messages,
|
|
123
|
+
lidPnMappings: lidPnMappings,
|
|
124
|
+
syncType: item.syncType,
|
|
125
|
+
progress: item.progress,
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
export const downloadAndProcessHistorySyncNotification = async (
|
|
129
|
+
msg,
|
|
130
|
+
options,
|
|
131
|
+
logger,
|
|
132
|
+
) => {
|
|
133
|
+
let historyMsg;
|
|
134
|
+
if (msg.initialHistBootstrapInlinePayload) {
|
|
135
|
+
historyMsg = proto.HistorySync.decode(
|
|
136
|
+
await inflatePromise(msg.initialHistBootstrapInlinePayload),
|
|
137
|
+
);
|
|
138
|
+
} else {
|
|
139
|
+
historyMsg = await downloadHistory(msg, options);
|
|
140
|
+
}
|
|
141
|
+
return processHistoryMessage(historyMsg, logger);
|
|
142
|
+
};
|
|
143
|
+
export const getHistoryMsg = (message) => {
|
|
144
|
+
const normalizedContent = !!message
|
|
145
|
+
? normalizeMessageContent(message)
|
|
146
|
+
: undefined;
|
|
147
|
+
const anyHistoryMsg =
|
|
148
|
+
normalizedContent?.protocolMessage?.historySyncNotification;
|
|
149
|
+
return anyHistoryMsg;
|
|
150
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import NodeCache from "@cacheable/node-cache";
|
|
2
|
+
import {
|
|
3
|
+
areJidsSameUser,
|
|
4
|
+
getBinaryNodeChild,
|
|
5
|
+
jidDecode,
|
|
6
|
+
} from "../WABinary/index.js";
|
|
7
|
+
import { isStringNullOrEmpty } from "./generics.js";
|
|
8
|
+
export async function handleIdentityChange(node, ctx) {
|
|
9
|
+
const from = node.attrs.from;
|
|
10
|
+
if (!from) {
|
|
11
|
+
return { action: "invalid_notification" };
|
|
12
|
+
}
|
|
13
|
+
const identityNode = getBinaryNodeChild(node, "identity");
|
|
14
|
+
if (!identityNode) {
|
|
15
|
+
return { action: "no_identity_node" };
|
|
16
|
+
}
|
|
17
|
+
ctx.logger.info({ jid: from }, "identity changed");
|
|
18
|
+
const decoded = jidDecode(from);
|
|
19
|
+
if (decoded?.device && decoded.device !== 0) {
|
|
20
|
+
ctx.logger.debug(
|
|
21
|
+
{ jid: from, device: decoded.device },
|
|
22
|
+
"ignoring identity change from companion device",
|
|
23
|
+
);
|
|
24
|
+
return { action: "skipped_companion_device", device: decoded.device };
|
|
25
|
+
}
|
|
26
|
+
const isSelfPrimary =
|
|
27
|
+
ctx.meId &&
|
|
28
|
+
(areJidsSameUser(from, ctx.meId) ||
|
|
29
|
+
(ctx.meLid && areJidsSameUser(from, ctx.meLid)));
|
|
30
|
+
if (isSelfPrimary) {
|
|
31
|
+
ctx.logger.info({ jid: from }, "self primary identity changed");
|
|
32
|
+
return { action: "skipped_self_primary" };
|
|
33
|
+
}
|
|
34
|
+
if (ctx.debounceCache.get(from)) {
|
|
35
|
+
ctx.logger.debug({ jid: from }, "skipping identity assert (debounced)");
|
|
36
|
+
return { action: "debounced" };
|
|
37
|
+
}
|
|
38
|
+
ctx.debounceCache.set(from, true);
|
|
39
|
+
const isOfflineNotification = !isStringNullOrEmpty(node.attrs.offline);
|
|
40
|
+
const hasExistingSession = await ctx.validateSession(from);
|
|
41
|
+
if (!hasExistingSession.exists) {
|
|
42
|
+
ctx.logger.debug({ jid: from }, "no old session, skipping session refresh");
|
|
43
|
+
return { action: "skipped_no_session" };
|
|
44
|
+
}
|
|
45
|
+
ctx.logger.debug({ jid: from }, "old session exists, will refresh session");
|
|
46
|
+
if (isOfflineNotification) {
|
|
47
|
+
ctx.logger.debug(
|
|
48
|
+
{ jid: from },
|
|
49
|
+
"skipping session refresh during offline processing",
|
|
50
|
+
);
|
|
51
|
+
return { action: "skipped_offline" };
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
await ctx.assertSessions([from], true);
|
|
55
|
+
return { action: "session_refreshed" };
|
|
56
|
+
} catch (error) {
|
|
57
|
+
ctx.logger.warn(
|
|
58
|
+
{ error: error, jid: from },
|
|
59
|
+
"failed to assert sessions after identity change",
|
|
60
|
+
);
|
|
61
|
+
return { action: "session_refresh_failed", error: error };
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export * from "./generics.js";
|
|
2
|
+
export * from "./decode-wa-message.js";
|
|
3
|
+
export * from "./messages.js";
|
|
4
|
+
export * from "./messages-media.js";
|
|
5
|
+
export * from "./validate-connection.js";
|
|
6
|
+
export * from "./crypto.js";
|
|
7
|
+
export * from "./signal.js";
|
|
8
|
+
export * from "./noise-handler.js";
|
|
9
|
+
export * from "./history.js";
|
|
10
|
+
export * from "./chat-utils.js";
|
|
11
|
+
export * from "./lt-hash.js";
|
|
12
|
+
export * from "./auth-utils.js";
|
|
13
|
+
export * from "./use-multi-file-auth-state.js";
|
|
14
|
+
export * from "./use-single-file-auth-state.js";
|
|
15
|
+
export * from "./link-preview.js";
|
|
16
|
+
export * from "./event-buffer.js";
|
|
17
|
+
export * from "./process-message.js";
|
|
18
|
+
export * from "./message-retry-manager.js";
|
|
19
|
+
export * from "./browser-utils.js";
|
|
20
|
+
export * from "./identity-change-handler.js";
|
|
21
|
+
export * from "./stanza-ack.js";
|