@rosyn/whats 0.0.0-stage → 0.1.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/README.md +354 -2
- package/assets/banner.jpg +0 -0
- package/dist/client/index.d.ts +96 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +224 -0
- package/dist/client/index.js.map +1 -0
- package/dist/codec/index.d.ts +8 -0
- package/dist/codec/index.d.ts.map +1 -0
- package/dist/codec/index.js +157 -0
- package/dist/codec/index.js.map +1 -0
- package/dist/compat/extensions.d.ts +219 -0
- package/dist/compat/extensions.d.ts.map +1 -0
- package/dist/compat/extensions.js +717 -0
- package/dist/compat/extensions.js.map +1 -0
- package/dist/compat/index.d.ts +41 -0
- package/dist/compat/index.d.ts.map +1 -0
- package/dist/compat/index.js +2500 -0
- package/dist/compat/index.js.map +1 -0
- package/dist/errors/index.d.ts +15 -0
- package/dist/errors/index.d.ts.map +1 -0
- package/dist/errors/index.js +26 -0
- package/dist/errors/index.js.map +1 -0
- package/dist/events/index.d.ts +12 -0
- package/dist/events/index.d.ts.map +1 -0
- package/dist/events/index.js +48 -0
- package/dist/events/index.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/media/index.d.ts +22 -0
- package/dist/media/index.d.ts.map +1 -0
- package/dist/media/index.js +88 -0
- package/dist/media/index.js.map +1 -0
- package/dist/proto/index.d.ts +401 -0
- package/dist/proto/index.d.ts.map +1 -0
- package/dist/proto/index.js +1342 -0
- package/dist/proto/index.js.map +1 -0
- package/dist/protocol/jid.d.ts +36 -0
- package/dist/protocol/jid.d.ts.map +1 -0
- package/dist/protocol/jid.js +95 -0
- package/dist/protocol/jid.js.map +1 -0
- package/dist/protocol/tokens.d.ts +3 -0
- package/dist/protocol/tokens.d.ts.map +1 -0
- package/dist/protocol/tokens.js +4 -0
- package/dist/protocol/tokens.js.map +1 -0
- package/dist/protocol/wabin.d.ts +8 -0
- package/dist/protocol/wabin.d.ts.map +1 -0
- package/dist/protocol/wabin.js +256 -0
- package/dist/protocol/wabin.js.map +1 -0
- package/dist/signal/index.d.ts +22 -0
- package/dist/signal/index.d.ts.map +1 -0
- package/dist/signal/index.js +62 -0
- package/dist/signal/index.js.map +1 -0
- package/dist/signal/protocol.d.ts +139 -0
- package/dist/signal/protocol.d.ts.map +1 -0
- package/dist/signal/protocol.js +620 -0
- package/dist/signal/protocol.js.map +1 -0
- package/dist/storage/index.d.ts +59 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +65 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/transport/websocket.d.ts +32 -0
- package/dist/transport/websocket.d.ts.map +1 -0
- package/dist/transport/websocket.js +153 -0
- package/dist/transport/websocket.js.map +1 -0
- package/dist/types/index.d.ts +111 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +2 -0
- package/dist/types/index.js.map +1 -0
- package/native/rosyn_whats_engine.node +0 -0
- package/package.json +54 -4
|
@@ -0,0 +1,2500 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createCipheriv, createDecipheriv, createHash, createHmac, pbkdf2, randomBytes } from "node:crypto";
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
4
|
+
import * as fs from "node:fs";
|
|
5
|
+
import * as path from "node:path";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { deflateRawSync, inflateRawSync } from "node:zlib";
|
|
8
|
+
import { unzipSync, zipSync } from "fflate";
|
|
9
|
+
import pb from "protobufjs/minimal.js";
|
|
10
|
+
import { RosynWhatsClient } from "../client/index.js";
|
|
11
|
+
import { downloadContentFromMessage, encryptWaMedia, toBuffer } from "../media/index.js";
|
|
12
|
+
import { proto } from "../proto/index.js";
|
|
13
|
+
import { DisconnectReason, generateMessageIDV2, jidDecode, jidNormalizedUser } from "../protocol/jid.js";
|
|
14
|
+
const pbkdf2Async = promisify(pbkdf2);
|
|
15
|
+
import { decodeWABinaryNode, encodeWABinaryNode } from "../protocol/wabin.js";
|
|
16
|
+
import { jidToSignalAddress, SignalProtocolManager, toSignalPub33, unpadRandomMax16, writeRandomPadMax16, } from "../signal/protocol.js";
|
|
17
|
+
import { loadNativeEngine } from "../storage/index.js";
|
|
18
|
+
import { WhatsAppWebSocketTransport } from "../transport/websocket.js";
|
|
19
|
+
import { createCompatExtensions } from "./extensions.js";
|
|
20
|
+
export { unzipSync, pb };
|
|
21
|
+
export const Browsers = {
|
|
22
|
+
ubuntu: (browser) => ["Ubuntu", browser, "22.04"],
|
|
23
|
+
macOS: (browser) => ["macOS", browser, "14.4"],
|
|
24
|
+
windows: (browser) => ["Windows", browser, "10.0"],
|
|
25
|
+
android: (browser = "Chrome") => ["Android", browser, "14.0"],
|
|
26
|
+
appropriate: (browser) => ["Linux", browser, "6.8"],
|
|
27
|
+
};
|
|
28
|
+
let cachedWaVersion = null;
|
|
29
|
+
export async function fetchLatestBaileysVersion() {
|
|
30
|
+
if (cachedWaVersion)
|
|
31
|
+
return cachedWaVersion;
|
|
32
|
+
try {
|
|
33
|
+
const res = await fetch("https://web.whatsapp.com/sw.js", {
|
|
34
|
+
headers: { "sec-fetch-site": "none", "user-agent": "Mozilla/5.0" },
|
|
35
|
+
signal: AbortSignal.timeout(2000),
|
|
36
|
+
});
|
|
37
|
+
if (res.ok) {
|
|
38
|
+
const text = await res.text();
|
|
39
|
+
const match = text.match(/"client_revision":(\d+)/);
|
|
40
|
+
if (match?.[1]) {
|
|
41
|
+
cachedWaVersion = { version: [2, 3000, Number(match[1])], isLatest: true };
|
|
42
|
+
return cachedWaVersion;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
}
|
|
48
|
+
return { version: [2, 3000, 1056491763], isLatest: false };
|
|
49
|
+
}
|
|
50
|
+
function reviveBuffers(val) {
|
|
51
|
+
if (!val || typeof val !== "object")
|
|
52
|
+
return val;
|
|
53
|
+
if (val.type === "Buffer" && Array.isArray(val.data)) {
|
|
54
|
+
return Buffer.from(val.data);
|
|
55
|
+
}
|
|
56
|
+
if (Array.isArray(val))
|
|
57
|
+
return val.map(reviveBuffers);
|
|
58
|
+
const out = {};
|
|
59
|
+
for (const [k, v] of Object.entries(val)) {
|
|
60
|
+
out[k] = reviveBuffers(v);
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
export async function useMultiFileAuthState(dir) {
|
|
65
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
66
|
+
const dbPath = path.join(dir, "rosyn_auth.rdb");
|
|
67
|
+
const client = new RosynWhatsClient({
|
|
68
|
+
accountId: path.basename(dir) || "default",
|
|
69
|
+
storage: { type: "rosyndb", path: dbPath },
|
|
70
|
+
session: { lazyLoad: true },
|
|
71
|
+
});
|
|
72
|
+
const native = loadNativeEngine();
|
|
73
|
+
const packAuthJson = (val) => {
|
|
74
|
+
const raw = Buffer.from(JSON.stringify(val), "utf8");
|
|
75
|
+
return Buffer.concat([Buffer.from([0x01]), deflateRawSync(raw)]);
|
|
76
|
+
};
|
|
77
|
+
const unpackAuthJson = (buf) => {
|
|
78
|
+
const data = buf[0] === 0x01 ? inflateRawSync(buf.subarray(1)) : buf;
|
|
79
|
+
return reviveBuffers(JSON.parse(Buffer.from(data).toString("utf8")));
|
|
80
|
+
};
|
|
81
|
+
let saved = {};
|
|
82
|
+
try {
|
|
83
|
+
const raw = client.getAuthRecord("__creds__");
|
|
84
|
+
if (raw && raw.length > 0) {
|
|
85
|
+
saved = unpackAuthJson(raw);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
saved = {};
|
|
90
|
+
}
|
|
91
|
+
const creds = {
|
|
92
|
+
registered: Boolean(saved.registered),
|
|
93
|
+
me: saved.me ?? undefined,
|
|
94
|
+
noiseKey: saved.noiseKey ?? JSON.parse(native.cryptoX25519Keypair()),
|
|
95
|
+
signedIdentityKey: saved.signedIdentityKey ?? JSON.parse(native.cryptoX25519Keypair()),
|
|
96
|
+
signedPreKey: saved.signedPreKey ?? JSON.parse(native.cryptoX25519Keypair()),
|
|
97
|
+
registrationId: saved.registrationId ?? Math.floor(100000 + Math.random() * 899999),
|
|
98
|
+
advSecretKey: saved.advSecretKey ?? randomBytes(32).toString("base64"),
|
|
99
|
+
account: saved.account ?? undefined,
|
|
100
|
+
platform: saved.platform ?? undefined,
|
|
101
|
+
rosynClient: client,
|
|
102
|
+
};
|
|
103
|
+
let flushTimer;
|
|
104
|
+
const scheduleFlush = () => {
|
|
105
|
+
if (flushTimer)
|
|
106
|
+
return;
|
|
107
|
+
flushTimer = setTimeout(() => {
|
|
108
|
+
flushTimer = undefined;
|
|
109
|
+
void client.flushSession().catch(() => { });
|
|
110
|
+
}, 1500);
|
|
111
|
+
flushTimer.unref();
|
|
112
|
+
};
|
|
113
|
+
return {
|
|
114
|
+
state: {
|
|
115
|
+
creds,
|
|
116
|
+
keys: {
|
|
117
|
+
get: async (type, ids) => {
|
|
118
|
+
const out = {};
|
|
119
|
+
for (const id of ids) {
|
|
120
|
+
const buf = client.getAuthRecord(`key:${type}:${id}`);
|
|
121
|
+
if (buf && buf.length > 0) {
|
|
122
|
+
try {
|
|
123
|
+
out[id] = unpackAuthJson(buf);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
out[id] = buf;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
},
|
|
132
|
+
set: async (data) => {
|
|
133
|
+
for (const [type, entries] of Object.entries(data)) {
|
|
134
|
+
for (const [id, val] of Object.entries(entries)) {
|
|
135
|
+
if (val !== undefined && val !== null) {
|
|
136
|
+
const payload = val instanceof Uint8Array ? Buffer.from(val) : packAuthJson(val);
|
|
137
|
+
client.putAuthRecord(`key:${type}:${id}`, payload);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
scheduleFlush();
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
},
|
|
145
|
+
saveCreds: async () => {
|
|
146
|
+
const toSave = {
|
|
147
|
+
registered: Boolean(creds.registered),
|
|
148
|
+
me: creds.me ?? null,
|
|
149
|
+
noiseKey: creds.noiseKey,
|
|
150
|
+
signedIdentityKey: creds.signedIdentityKey,
|
|
151
|
+
signedPreKey: creds.signedPreKey,
|
|
152
|
+
registrationId: creds.registrationId,
|
|
153
|
+
advSecretKey: creds.advSecretKey ?? null,
|
|
154
|
+
account: creds.account ?? null,
|
|
155
|
+
platform: creds.platform ?? null,
|
|
156
|
+
};
|
|
157
|
+
client.putAuthRecord("__creds__", packAuthJson(toSave));
|
|
158
|
+
await client.flushSession();
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
export function makeWASocket(config = {}) {
|
|
163
|
+
const ev = new EventEmitter();
|
|
164
|
+
const auth = config.auth?.creds;
|
|
165
|
+
const client = auth?.rosynClient ??
|
|
166
|
+
new RosynWhatsClient({
|
|
167
|
+
accountId: "bot_main",
|
|
168
|
+
storage: { type: "rosyndb", path: "./sessions/rosyn_main.rdb" },
|
|
169
|
+
session: { lazyLoad: true },
|
|
170
|
+
});
|
|
171
|
+
const authCreds = config.auth?.creds ?? {};
|
|
172
|
+
const native = loadNativeEngine();
|
|
173
|
+
const identKp = (authCreds.signedIdentityKey ?? JSON.parse(native.cryptoX25519Keypair()));
|
|
174
|
+
const spkKp = (authCreds.signedPreKey ?? JSON.parse(native.cryptoX25519Keypair()));
|
|
175
|
+
const noiseKp = (authCreds.noiseKey ?? JSON.parse(native.cryptoX25519Keypair()));
|
|
176
|
+
const ephPairingKp = JSON.parse(native.cryptoX25519Keypair());
|
|
177
|
+
const advSecretKey = authCreds.advSecretKey
|
|
178
|
+
? Buffer.from(String(authCreds.advSecretKey), "base64")
|
|
179
|
+
: randomBytes(32);
|
|
180
|
+
if (!authCreds.advSecretKey) {
|
|
181
|
+
authCreds.advSecretKey = advSecretKey.toString("base64");
|
|
182
|
+
}
|
|
183
|
+
const identPriv = Buffer.from(identKp.privateKeyHex, "hex");
|
|
184
|
+
const identPub = Buffer.from(identKp.publicKeyHex, "hex");
|
|
185
|
+
const spkPub = Buffer.from(spkKp.publicKeyHex, "hex");
|
|
186
|
+
const noisePriv = Buffer.from(noiseKp.privateKeyHex, "hex");
|
|
187
|
+
const noisePub = Buffer.from(noiseKp.publicKeyHex, "hex");
|
|
188
|
+
const pairingEphPriv = Buffer.from(ephPairingKp.privateKeyHex, "hex");
|
|
189
|
+
const pairingEphPub = Buffer.from(ephPairingKp.publicKeyHex, "hex");
|
|
190
|
+
const spkSig = native.cryptoXeddsaSign(identPriv, Buffer.concat([Buffer.from([5]), spkPub]));
|
|
191
|
+
let activePairingCode = "";
|
|
192
|
+
let activePairingJid = "";
|
|
193
|
+
const authKeys = config.auth?.keys;
|
|
194
|
+
const memKeys = new Map();
|
|
195
|
+
const getKey = async (type, id) => {
|
|
196
|
+
if (authKeys?.get) {
|
|
197
|
+
const res = await authKeys.get(type, [id]);
|
|
198
|
+
if (res && res[id] !== undefined)
|
|
199
|
+
return res[id];
|
|
200
|
+
}
|
|
201
|
+
return memKeys.get(`${type}:${id}`);
|
|
202
|
+
};
|
|
203
|
+
const setKey = async (type, id, val) => {
|
|
204
|
+
memKeys.set(`${type}:${id}`, val);
|
|
205
|
+
if (authKeys?.set) {
|
|
206
|
+
await authKeys.set({ [type]: { [id]: val } });
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
const spkPriv = Buffer.from(spkKp.privateKeyHex, "hex");
|
|
210
|
+
const signalMgr = new SignalProtocolManager(native, getKey, setKey, { priv: identPriv, pub33: toSignalPub33(identPub) }, { keyId: 1, priv: spkPriv, pub33: toSignalPub33(spkPub) }, Number(authCreds.registrationId ?? 1));
|
|
211
|
+
const groupCache = new Map();
|
|
212
|
+
const senderKeyMemory = new Map();
|
|
213
|
+
const sentMessages = new Map();
|
|
214
|
+
const ver = config.version ?? [2, 3000, 1056491763];
|
|
215
|
+
const browser = config.browser ?? Browsers.ubuntu("Chrome");
|
|
216
|
+
const buildHash = createHash("md5").update(ver.join(".")).digest();
|
|
217
|
+
const deviceProps = proto.DeviceProps.encode({
|
|
218
|
+
os: browser[0],
|
|
219
|
+
platformType: 1,
|
|
220
|
+
requireFullSync: Boolean(config.syncFullHistory),
|
|
221
|
+
version: { primary: 10, secondary: 15, tertiary: 7 },
|
|
222
|
+
});
|
|
223
|
+
const regIdBuf = Buffer.alloc(4);
|
|
224
|
+
regIdBuf.writeUInt32BE(Number(authCreds.registrationId ?? Math.floor(100000 + Math.random() * 899999)), 0);
|
|
225
|
+
const isRegistered = Boolean(authCreds.registered && authCreds.me?.id);
|
|
226
|
+
const decodedMe = isRegistered ? jidDecode(String(authCreds.me.id)) : undefined;
|
|
227
|
+
const clientPayloadBytes = Buffer.from(proto.ClientPayload.encode(isRegistered && decodedMe
|
|
228
|
+
? {
|
|
229
|
+
username: BigInt(decodedMe.user),
|
|
230
|
+
device: decodedMe.device ?? 0,
|
|
231
|
+
passive: true,
|
|
232
|
+
pull: true,
|
|
233
|
+
connectType: 1,
|
|
234
|
+
connectReason: 1,
|
|
235
|
+
userAgent: {
|
|
236
|
+
platform: 14,
|
|
237
|
+
appVersion: { primary: ver[0], secondary: ver[1], tertiary: ver[2] },
|
|
238
|
+
mcc: "000",
|
|
239
|
+
mnc: "000",
|
|
240
|
+
osVersion: "0.1",
|
|
241
|
+
device: "Desktop",
|
|
242
|
+
osBuildNumber: "0.1",
|
|
243
|
+
releaseChannel: 0,
|
|
244
|
+
localeLanguageIso6391: "en",
|
|
245
|
+
localeCountryIso31661Alpha2: "US",
|
|
246
|
+
},
|
|
247
|
+
webInfo: { webSubPlatform: 0 },
|
|
248
|
+
}
|
|
249
|
+
: {
|
|
250
|
+
passive: false,
|
|
251
|
+
pull: false,
|
|
252
|
+
connectType: 1,
|
|
253
|
+
connectReason: 1,
|
|
254
|
+
userAgent: {
|
|
255
|
+
platform: 14,
|
|
256
|
+
appVersion: { primary: ver[0], secondary: ver[1], tertiary: ver[2] },
|
|
257
|
+
mcc: "000",
|
|
258
|
+
mnc: "000",
|
|
259
|
+
osVersion: "0.1",
|
|
260
|
+
device: "Desktop",
|
|
261
|
+
osBuildNumber: "0.1",
|
|
262
|
+
releaseChannel: 0,
|
|
263
|
+
localeLanguageIso6391: "en",
|
|
264
|
+
localeCountryIso31661Alpha2: "US",
|
|
265
|
+
},
|
|
266
|
+
webInfo: { webSubPlatform: 0 },
|
|
267
|
+
devicePairingData: {
|
|
268
|
+
eRegid: regIdBuf,
|
|
269
|
+
eKeytype: Buffer.from([5]),
|
|
270
|
+
eIdent: identPub,
|
|
271
|
+
eSkeyId: Buffer.from([0, 0, 1]),
|
|
272
|
+
eSkeyVal: spkPub,
|
|
273
|
+
eSkeySig: spkSig,
|
|
274
|
+
buildHash,
|
|
275
|
+
deviceProps,
|
|
276
|
+
},
|
|
277
|
+
}));
|
|
278
|
+
const pendingQueries = new Map();
|
|
279
|
+
const pendingMediaRetries = new Map();
|
|
280
|
+
const lidToPnMap = new Map();
|
|
281
|
+
const rememberLidPn = (lid, pn) => {
|
|
282
|
+
if (lid && pn && lid.endsWith("@lid") && pn.endsWith("@s.whatsapp.net")) {
|
|
283
|
+
lidToPnMap.set(jidNormalizedUser(lid), jidNormalizedUser(pn));
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
const resolvePnJid = (jid) => {
|
|
287
|
+
if (!jid)
|
|
288
|
+
return "";
|
|
289
|
+
if (!jid.endsWith("@lid"))
|
|
290
|
+
return jid;
|
|
291
|
+
return lidToPnMap.get(jidNormalizedUser(jid)) ?? jid;
|
|
292
|
+
};
|
|
293
|
+
rememberLidPn(authCreds.me?.lid, authCreds.me?.id);
|
|
294
|
+
let msgTagCounter = 1;
|
|
295
|
+
const nextTag = () => `${Math.floor(Date.now() / 1000)}.${msgTagCounter++}`;
|
|
296
|
+
let readyResolve;
|
|
297
|
+
const transportReady = new Promise((res) => {
|
|
298
|
+
readyResolve = res;
|
|
299
|
+
});
|
|
300
|
+
let connectionClosed = false;
|
|
301
|
+
const emitClose = (err) => {
|
|
302
|
+
if (connectionClosed)
|
|
303
|
+
return;
|
|
304
|
+
connectionClosed = true;
|
|
305
|
+
sock.ws.isOpen = false;
|
|
306
|
+
try {
|
|
307
|
+
transport.close();
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
}
|
|
311
|
+
ev.emit("connection.update", {
|
|
312
|
+
connection: "close",
|
|
313
|
+
lastDisconnect: { error: err },
|
|
314
|
+
});
|
|
315
|
+
};
|
|
316
|
+
const transport = new WhatsAppWebSocketTransport({
|
|
317
|
+
onFrame: (frame) => {
|
|
318
|
+
try {
|
|
319
|
+
const node = decodeWABinaryNode(frame);
|
|
320
|
+
if (node.attrs.id && pendingQueries.has(node.attrs.id)) {
|
|
321
|
+
const p = pendingQueries.get(node.attrs.id);
|
|
322
|
+
pendingQueries.delete(node.attrs.id);
|
|
323
|
+
if (node.attrs.type === "error") {
|
|
324
|
+
p.reject(new Error(`WA IQ error on ${node.attrs.id}`));
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
p.resolve(node);
|
|
328
|
+
}
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (node.tag === "success") {
|
|
332
|
+
sock.ws.isOpen = true;
|
|
333
|
+
if (node.attrs.lid || authCreds.me?.id) {
|
|
334
|
+
sock.user = {
|
|
335
|
+
id: authCreds.me?.id ?? node.attrs.lid ?? "0@s.whatsapp.net",
|
|
336
|
+
lid: node.attrs.lid,
|
|
337
|
+
name: authCreds.me?.name ?? "RosynWhats",
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
void sendQuery({
|
|
341
|
+
tag: "iq",
|
|
342
|
+
attrs: { to: "s.whatsapp.net", type: "set", id: nextTag(), xmlns: "passive" },
|
|
343
|
+
content: [{ tag: "active", attrs: {} }],
|
|
344
|
+
})
|
|
345
|
+
.then(async () => {
|
|
346
|
+
const countRes = await sendQuery({
|
|
347
|
+
tag: "iq",
|
|
348
|
+
attrs: { to: "s.whatsapp.net", type: "get", id: nextTag(), xmlns: "encrypt" },
|
|
349
|
+
content: [{ tag: "count", attrs: {} }],
|
|
350
|
+
});
|
|
351
|
+
const countNode = Array.isArray(countRes.content)
|
|
352
|
+
? countRes.content.find((c) => c.tag === "count")
|
|
353
|
+
: undefined;
|
|
354
|
+
const serverCount = Number(countNode?.attrs?.value ?? 0);
|
|
355
|
+
if (serverCount <= 5) {
|
|
356
|
+
const startId = Number(authCreds.nextPreKeyId ?? 1);
|
|
357
|
+
const keyNodes = [];
|
|
358
|
+
const preKeyBatch = {};
|
|
359
|
+
for (let i = 0; i < 30; i++) {
|
|
360
|
+
const id = startId + i;
|
|
361
|
+
const kp = JSON.parse(native.cryptoX25519Keypair());
|
|
362
|
+
preKeyBatch[String(id)] = kp;
|
|
363
|
+
const idBuf = Buffer.alloc(3);
|
|
364
|
+
idBuf.writeUIntBE(id, 0, 3);
|
|
365
|
+
keyNodes.push({
|
|
366
|
+
tag: "key",
|
|
367
|
+
attrs: {},
|
|
368
|
+
content: [
|
|
369
|
+
{ tag: "id", attrs: {}, content: idBuf },
|
|
370
|
+
{ tag: "value", attrs: {}, content: Buffer.from(kp.publicKeyHex, "hex") },
|
|
371
|
+
],
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
if (authKeys?.set) {
|
|
375
|
+
await authKeys.set({ "pre-key": preKeyBatch });
|
|
376
|
+
}
|
|
377
|
+
else {
|
|
378
|
+
for (const [k, v] of Object.entries(preKeyBatch))
|
|
379
|
+
memKeys.set(`pre-key:${k}`, v);
|
|
380
|
+
}
|
|
381
|
+
authCreds.nextPreKeyId = startId + 30;
|
|
382
|
+
ev.emit("creds.update", authCreds);
|
|
383
|
+
const regBuf = Buffer.alloc(4);
|
|
384
|
+
regBuf.writeUInt32BE(Number(authCreds.registrationId ?? 1), 0);
|
|
385
|
+
const spkIdBuf = Buffer.alloc(3);
|
|
386
|
+
spkIdBuf.writeUIntBE(1, 0, 3);
|
|
387
|
+
await sendQuery({
|
|
388
|
+
tag: "iq",
|
|
389
|
+
attrs: { to: "s.whatsapp.net", type: "set", id: nextTag(), xmlns: "encrypt" },
|
|
390
|
+
content: [
|
|
391
|
+
{ tag: "registration", attrs: {}, content: regBuf },
|
|
392
|
+
{ tag: "type", attrs: {}, content: Buffer.from([5]) },
|
|
393
|
+
{ tag: "identity", attrs: {}, content: identPub },
|
|
394
|
+
{ tag: "list", attrs: {}, content: keyNodes },
|
|
395
|
+
{
|
|
396
|
+
tag: "skey",
|
|
397
|
+
attrs: {},
|
|
398
|
+
content: [
|
|
399
|
+
{ tag: "id", attrs: {}, content: spkIdBuf },
|
|
400
|
+
{ tag: "value", attrs: {}, content: spkPub },
|
|
401
|
+
{ tag: "signature", attrs: {}, content: spkSig },
|
|
402
|
+
],
|
|
403
|
+
},
|
|
404
|
+
],
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
})
|
|
408
|
+
.catch(() => { });
|
|
409
|
+
ev.emit("connection.update", { connection: "open" });
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (node.tag === "presence" && node.attrs.from) {
|
|
413
|
+
const from = resolvePnJid(node.attrs.from);
|
|
414
|
+
const pres = node.attrs.type === "unavailable" ? "unavailable" : "available";
|
|
415
|
+
ev.emit("presence.update", {
|
|
416
|
+
id: from,
|
|
417
|
+
presences: { [from]: { lastKnownPresence: pres, lastSeen: node.attrs.last ? Number(node.attrs.last) : undefined } },
|
|
418
|
+
});
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
if (node.tag === "chatstate" && node.attrs.from) {
|
|
422
|
+
const id = node.attrs.from;
|
|
423
|
+
const participant = resolvePnJid(node.attrs.participant || node.attrs.from);
|
|
424
|
+
const child = Array.isArray(node.content) ? node.content[0] : undefined;
|
|
425
|
+
const pres = child?.tag === "paused"
|
|
426
|
+
? "paused"
|
|
427
|
+
: child?.tag === "composing"
|
|
428
|
+
? child.attrs?.media === "audio"
|
|
429
|
+
? "recording"
|
|
430
|
+
: "composing"
|
|
431
|
+
: "available";
|
|
432
|
+
ev.emit("presence.update", { id, presences: { [participant]: { lastKnownPresence: pres } } });
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
if (node.tag === "call" && Array.isArray(node.content)) {
|
|
436
|
+
const child = node.content[0];
|
|
437
|
+
if (child?.attrs?.["call-id"]) {
|
|
438
|
+
ev.emit("call", [
|
|
439
|
+
{
|
|
440
|
+
chatId: resolvePnJid(node.attrs.from),
|
|
441
|
+
from: resolvePnJid(child.attrs["call-creator"] || node.attrs.from),
|
|
442
|
+
id: child.attrs["call-id"],
|
|
443
|
+
date: new Date(Number(node.attrs.t || Math.floor(Date.now() / 1000)) * 1000),
|
|
444
|
+
offline: Boolean(node.attrs.offline),
|
|
445
|
+
status: child.tag === "offer" ? "offer" : child.tag === "terminate" ? "terminate" : child.tag,
|
|
446
|
+
isVideo: Array.isArray(child.content) && child.content.some((c) => c.tag === "video"),
|
|
447
|
+
isGroup: Boolean(child.attrs?.["group-jid"]),
|
|
448
|
+
},
|
|
449
|
+
]);
|
|
450
|
+
}
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
if (node.tag === "stream:error") {
|
|
454
|
+
const codeNode = Array.isArray(node.content) ? node.content[0] : undefined;
|
|
455
|
+
const code = Number(node.attrs.code ||
|
|
456
|
+
(codeNode?.tag === "conflict" ? DisconnectReason.connectionReplaced : 0) ||
|
|
457
|
+
DisconnectReason.restartRequired);
|
|
458
|
+
emitClose(Object.assign(new Error(`WA stream:error (${code})`), { output: { statusCode: code } }));
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
if (node.tag === "failure") {
|
|
462
|
+
const reason = Number(node.attrs.reason || DisconnectReason.connectionClosed);
|
|
463
|
+
emitClose(Object.assign(new Error(`WA failure: ${reason}`), { output: { statusCode: reason } }));
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
if (node.tag === "notification") {
|
|
467
|
+
if (node.attrs.id) {
|
|
468
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
469
|
+
tag: "ack",
|
|
470
|
+
attrs: {
|
|
471
|
+
id: node.attrs.id,
|
|
472
|
+
class: "notification",
|
|
473
|
+
...(node.attrs.type ? { type: node.attrs.type } : {}),
|
|
474
|
+
to: node.attrs.from ?? "s.whatsapp.net",
|
|
475
|
+
...(node.attrs.participant ? { participant: node.attrs.participant } : {}),
|
|
476
|
+
},
|
|
477
|
+
}));
|
|
478
|
+
}
|
|
479
|
+
if (node.attrs.type === "mediaretry" && node.attrs.id) {
|
|
480
|
+
const waiter = pendingMediaRetries.get(node.attrs.id);
|
|
481
|
+
if (waiter) {
|
|
482
|
+
pendingMediaRetries.delete(node.attrs.id);
|
|
483
|
+
waiter.resolve(node);
|
|
484
|
+
}
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
if (node.attrs.type === "w:gp2" && node.attrs.from && Array.isArray(node.content)) {
|
|
488
|
+
const groupId = node.attrs.from;
|
|
489
|
+
rememberLidPn(node.attrs.participant, node.attrs.participant_pn);
|
|
490
|
+
const actor = resolvePnJid(node.attrs.participant_pn || node.attrs.participant);
|
|
491
|
+
for (const child of node.content) {
|
|
492
|
+
if (!child || typeof child !== "object")
|
|
493
|
+
continue;
|
|
494
|
+
const cTag = child.tag;
|
|
495
|
+
if (cTag === "add" || cTag === "remove" || cTag === "leave" || cTag === "promote" || cTag === "demote") {
|
|
496
|
+
const action = cTag === "leave" ? "remove" : cTag;
|
|
497
|
+
const childNodes = Array.isArray(child.content) ? child.content : [];
|
|
498
|
+
const participants = childNodes
|
|
499
|
+
.filter((p) => p.tag === "participant" && p.attrs?.jid)
|
|
500
|
+
.map((p) => {
|
|
501
|
+
rememberLidPn(p.attrs.jid, p.attrs.phone_number);
|
|
502
|
+
return {
|
|
503
|
+
id: resolvePnJid(p.attrs.phone_number || p.attrs.jid),
|
|
504
|
+
jid: resolvePnJid(p.attrs.phone_number || p.attrs.jid),
|
|
505
|
+
phoneNumber: p.attrs.phone_number,
|
|
506
|
+
lid: p.attrs.lid || (p.attrs.jid.endsWith("@lid") ? p.attrs.jid : undefined),
|
|
507
|
+
admin: p.attrs.type || null,
|
|
508
|
+
};
|
|
509
|
+
});
|
|
510
|
+
if (action === "add" || action === "remove") {
|
|
511
|
+
senderKeyMemory.delete(groupId);
|
|
512
|
+
}
|
|
513
|
+
groupCache.delete(groupId);
|
|
514
|
+
if (participants.length > 0) {
|
|
515
|
+
ev.emit("group-participants.update", {
|
|
516
|
+
id: groupId,
|
|
517
|
+
participants,
|
|
518
|
+
action,
|
|
519
|
+
actor,
|
|
520
|
+
author: actor,
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
else if (cTag === "subject" && child.attrs?.subject !== undefined) {
|
|
525
|
+
ev.emit("groups.update", [
|
|
526
|
+
{
|
|
527
|
+
id: groupId,
|
|
528
|
+
subject: child.attrs.subject,
|
|
529
|
+
...(actor ? { subjectOwner: actor } : {}),
|
|
530
|
+
...(node.attrs.t ? { subjectTime: Number(node.attrs.t) } : {}),
|
|
531
|
+
},
|
|
532
|
+
]);
|
|
533
|
+
}
|
|
534
|
+
else if (cTag === "description") {
|
|
535
|
+
const bodyNode = Array.isArray(child.content) ? child.content.find((x) => x.tag === "body") : undefined;
|
|
536
|
+
const desc = bodyNode?.content instanceof Uint8Array
|
|
537
|
+
? Buffer.from(bodyNode.content).toString("utf8")
|
|
538
|
+
: typeof bodyNode?.content === "string"
|
|
539
|
+
? bodyNode.content
|
|
540
|
+
: undefined;
|
|
541
|
+
ev.emit("groups.update", [
|
|
542
|
+
{
|
|
543
|
+
id: groupId,
|
|
544
|
+
...(desc !== undefined ? { desc } : {}),
|
|
545
|
+
...(child.attrs?.id ? { descId: child.attrs.id } : {}),
|
|
546
|
+
},
|
|
547
|
+
]);
|
|
548
|
+
}
|
|
549
|
+
else if (cTag === "announce" || cTag === "not_announce") {
|
|
550
|
+
ev.emit("groups.update", [{ id: groupId, announce: cTag === "announce" }]);
|
|
551
|
+
}
|
|
552
|
+
else if (cTag === "locked" || cTag === "unlocked") {
|
|
553
|
+
ev.emit("groups.update", [{ id: groupId, restrict: cTag === "locked" }]);
|
|
554
|
+
}
|
|
555
|
+
else if (cTag === "ephemeral" || cTag === "not_ephemeral") {
|
|
556
|
+
ev.emit("groups.update", [
|
|
557
|
+
{
|
|
558
|
+
id: groupId,
|
|
559
|
+
ephemeralDuration: cTag === "ephemeral" ? Number(child.attrs?.expiration || 0) : 0,
|
|
560
|
+
},
|
|
561
|
+
]);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
if (node.tag === "notification" && node.attrs.type === "link_code_companion_reg" && Array.isArray(node.content)) {
|
|
568
|
+
const reg = node.content.find((c) => c.tag === "link_code_companion_reg");
|
|
569
|
+
if (reg && Array.isArray(reg.content)) {
|
|
570
|
+
const getChildBuf = (tag) => {
|
|
571
|
+
const ch = reg.content && Array.isArray(reg.content) ? reg.content.find((x) => x.tag === tag) : undefined;
|
|
572
|
+
if (!ch?.content)
|
|
573
|
+
return Buffer.alloc(0);
|
|
574
|
+
return ch.content instanceof Uint8Array ? Buffer.from(ch.content) : Buffer.from(String(ch.content));
|
|
575
|
+
};
|
|
576
|
+
const ref = getChildBuf("link_code_pairing_ref");
|
|
577
|
+
const primaryIdentPub = getChildBuf("primary_identity_pub");
|
|
578
|
+
const wrappedPrimaryEph = getChildBuf("link_code_pairing_wrapped_primary_ephemeral_pub");
|
|
579
|
+
if (ref.length && primaryIdentPub.length === 32 && wrappedPrimaryEph.length > 48 && activePairingCode) {
|
|
580
|
+
void (async () => {
|
|
581
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
582
|
+
tag: "ack",
|
|
583
|
+
attrs: {
|
|
584
|
+
id: node.attrs.id ?? nextTag(),
|
|
585
|
+
class: "notification",
|
|
586
|
+
type: "link_code_companion_reg",
|
|
587
|
+
to: node.attrs.from ?? "s.whatsapp.net",
|
|
588
|
+
},
|
|
589
|
+
}));
|
|
590
|
+
const salt = wrappedPrimaryEph.subarray(0, 32);
|
|
591
|
+
const iv = wrappedPrimaryEph.subarray(32, 48);
|
|
592
|
+
const ct = wrappedPrimaryEph.subarray(48);
|
|
593
|
+
const decKey = await pbkdf2Async(activePairingCode, salt, 2 << 16, 32, "sha256");
|
|
594
|
+
const decipher = createDecipheriv("aes-256-ctr", decKey, iv);
|
|
595
|
+
const primaryEphPub = Buffer.concat([decipher.update(ct), decipher.final()]);
|
|
596
|
+
const companionShared = native.cryptoX25519Ecdh(pairingEphPriv, primaryEphPub);
|
|
597
|
+
const rand32 = randomBytes(32);
|
|
598
|
+
const bundleSalt = randomBytes(32);
|
|
599
|
+
const prk = createHmac("sha256", bundleSalt).update(companionShared).digest();
|
|
600
|
+
const bundleKey = createHmac("sha256", prk)
|
|
601
|
+
.update(Buffer.concat([Buffer.from("link_code_pairing_key_bundle_encryption_key"), Buffer.from([1])]))
|
|
602
|
+
.digest();
|
|
603
|
+
const bundleIv = randomBytes(12);
|
|
604
|
+
const bundlePlain = Buffer.concat([identPub, primaryIdentPub, rand32]);
|
|
605
|
+
const gcm = createCipheriv("aes-256-gcm", bundleKey, bundleIv);
|
|
606
|
+
const bundleCt = Buffer.concat([gcm.update(bundlePlain), gcm.final(), gcm.getAuthTag()]);
|
|
607
|
+
const wrappedBundle = Buffer.concat([bundleSalt, bundleIv, bundleCt]);
|
|
608
|
+
const identitySharedKey = native.cryptoX25519Ecdh(identPriv, primaryIdentPub);
|
|
609
|
+
const identityPayload = Buffer.concat([companionShared, identitySharedKey, rand32]);
|
|
610
|
+
const advPrk = createHmac("sha256", Buffer.alloc(32)).update(identityPayload).digest();
|
|
611
|
+
const advSecretBytes = createHmac("sha256", advPrk)
|
|
612
|
+
.update(Buffer.concat([Buffer.from("adv_secret"), Buffer.from([1])]))
|
|
613
|
+
.digest();
|
|
614
|
+
authCreds.advSecretKey = advSecretBytes.toString("base64");
|
|
615
|
+
await sendQuery({
|
|
616
|
+
tag: "iq",
|
|
617
|
+
attrs: { to: "s.whatsapp.net", type: "set", id: nextTag(), xmlns: "md" },
|
|
618
|
+
content: [
|
|
619
|
+
{
|
|
620
|
+
tag: "link_code_companion_reg",
|
|
621
|
+
attrs: { jid: activePairingJid, stage: "companion_finish" },
|
|
622
|
+
content: [
|
|
623
|
+
{ tag: "link_code_pairing_wrapped_key_bundle", attrs: {}, content: wrappedBundle },
|
|
624
|
+
{ tag: "companion_identity_public", attrs: {}, content: identPub },
|
|
625
|
+
{ tag: "link_code_pairing_ref", attrs: {}, content: ref },
|
|
626
|
+
],
|
|
627
|
+
},
|
|
628
|
+
],
|
|
629
|
+
});
|
|
630
|
+
authCreds.registered = true;
|
|
631
|
+
ev.emit("creds.update", authCreds);
|
|
632
|
+
})().catch((err) => {
|
|
633
|
+
emitClose(err instanceof Error
|
|
634
|
+
? Object.assign(err, {
|
|
635
|
+
output: err.output ?? { statusCode: DisconnectReason.connectionClosed },
|
|
636
|
+
})
|
|
637
|
+
: Object.assign(new Error(String(err)), { output: { statusCode: DisconnectReason.connectionClosed } }));
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
if (node.tag === "iq" && node.attrs.type === "set" && Array.isArray(node.content)) {
|
|
644
|
+
const pairSuccess = node.content.find((c) => c.tag === "pair-success");
|
|
645
|
+
if (pairSuccess && Array.isArray(pairSuccess.content)) {
|
|
646
|
+
const devNode = pairSuccess.content.find((c) => c.tag === "device");
|
|
647
|
+
const devIdentNode = pairSuccess.content.find((c) => c.tag === "device-identity");
|
|
648
|
+
const bizNode = pairSuccess.content.find((c) => c.tag === "biz");
|
|
649
|
+
const jid = devNode?.attrs?.jid;
|
|
650
|
+
const lid = devNode?.attrs?.lid;
|
|
651
|
+
const bizName = bizNode?.attrs?.name;
|
|
652
|
+
let replyContent;
|
|
653
|
+
if (devIdentNode?.content instanceof Uint8Array) {
|
|
654
|
+
const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(devIdentNode.content);
|
|
655
|
+
const hmacPrefix = accountType === 1 ? Buffer.from([6, 5]) : Buffer.alloc(0);
|
|
656
|
+
const advKey = typeof authCreds.advSecretKey === "string"
|
|
657
|
+
? Buffer.from(authCreds.advSecretKey, "base64")
|
|
658
|
+
: advSecretKey;
|
|
659
|
+
const expectedHmac = createHmac("sha256", advKey).update(Buffer.concat([hmacPrefix, details])).digest();
|
|
660
|
+
if (Buffer.compare(Buffer.from(hmac), expectedHmac) !== 0) {
|
|
661
|
+
throw new Error("Invalid account signature HMAC in pair-success");
|
|
662
|
+
}
|
|
663
|
+
const account = proto.ADVSignedDeviceIdentity.decode(details);
|
|
664
|
+
const deviceIdentity = proto.ADVDeviceIdentity.decode(account.details);
|
|
665
|
+
const deviceMsg = Buffer.concat([
|
|
666
|
+
Buffer.from([6, 1]),
|
|
667
|
+
account.details,
|
|
668
|
+
identPub,
|
|
669
|
+
account.accountSignatureKey,
|
|
670
|
+
]);
|
|
671
|
+
const deviceSignature = native.cryptoXeddsaSign(identPriv, deviceMsg);
|
|
672
|
+
const accountEnc = proto.ADVSignedDeviceIdentity.encode({
|
|
673
|
+
details: account.details,
|
|
674
|
+
accountSignature: account.accountSignature,
|
|
675
|
+
deviceSignature,
|
|
676
|
+
});
|
|
677
|
+
authCreds.account = {
|
|
678
|
+
details: Buffer.from(account.details),
|
|
679
|
+
accountSignatureKey: Buffer.from(account.accountSignatureKey),
|
|
680
|
+
accountSignature: Buffer.from(account.accountSignature),
|
|
681
|
+
deviceSignature: Buffer.from(deviceSignature),
|
|
682
|
+
};
|
|
683
|
+
replyContent = [
|
|
684
|
+
{
|
|
685
|
+
tag: "pair-device-sign",
|
|
686
|
+
attrs: {},
|
|
687
|
+
content: [
|
|
688
|
+
{
|
|
689
|
+
tag: "device-identity",
|
|
690
|
+
attrs: { "key-index": String(deviceIdentity.keyIndex ?? 0) },
|
|
691
|
+
content: accountEnc,
|
|
692
|
+
},
|
|
693
|
+
],
|
|
694
|
+
},
|
|
695
|
+
];
|
|
696
|
+
}
|
|
697
|
+
if (jid) {
|
|
698
|
+
authCreds.me = { id: jid, name: bizName, lid };
|
|
699
|
+
authCreds.registered = true;
|
|
700
|
+
sock.user = authCreds.me;
|
|
701
|
+
ev.emit("creds.update", authCreds);
|
|
702
|
+
}
|
|
703
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
704
|
+
tag: "iq",
|
|
705
|
+
attrs: { to: "s.whatsapp.net", type: "result", id: node.attrs.id ?? nextTag() },
|
|
706
|
+
content: replyContent,
|
|
707
|
+
}));
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
const companionReg = node.content.find((c) => c.tag === "link_code_companion_reg");
|
|
711
|
+
if (companionReg?.attrs?.stage === "companion_finish") {
|
|
712
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
713
|
+
tag: "iq",
|
|
714
|
+
attrs: { to: "s.whatsapp.net", type: "result", id: node.attrs.id ?? nextTag() },
|
|
715
|
+
}));
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
const pairNode = node.content.find((c) => c.tag === "pair-device");
|
|
719
|
+
if (pairNode && Array.isArray(pairNode.content)) {
|
|
720
|
+
const refNode = pairNode.content.find((c) => c.tag === "ref");
|
|
721
|
+
const refStr = refNode?.content instanceof Uint8Array
|
|
722
|
+
? Buffer.from(refNode.content).toString("utf8")
|
|
723
|
+
: typeof refNode?.content === "string"
|
|
724
|
+
? refNode.content
|
|
725
|
+
: "";
|
|
726
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
727
|
+
tag: "iq",
|
|
728
|
+
attrs: { to: "s.whatsapp.net", type: "result", id: node.attrs.id ?? nextTag() },
|
|
729
|
+
}));
|
|
730
|
+
if (refStr) {
|
|
731
|
+
const qr = [
|
|
732
|
+
refStr,
|
|
733
|
+
noisePub.toString("base64"),
|
|
734
|
+
identPub.toString("base64"),
|
|
735
|
+
advSecretKey.toString("base64"),
|
|
736
|
+
].join(",");
|
|
737
|
+
ev.emit("connection.update", { qr });
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
if (node.tag === "receipt" && node.attrs.id && node.attrs.from) {
|
|
742
|
+
const rAck = {
|
|
743
|
+
to: node.attrs.from,
|
|
744
|
+
id: node.attrs.id,
|
|
745
|
+
class: "receipt",
|
|
746
|
+
};
|
|
747
|
+
if (node.attrs.type)
|
|
748
|
+
rAck.type = node.attrs.type;
|
|
749
|
+
if (node.attrs.participant)
|
|
750
|
+
rAck.participant = node.attrs.participant;
|
|
751
|
+
transport.sendEncrypted(encodeWABinaryNode({ tag: "ack", attrs: rAck }));
|
|
752
|
+
if (node.attrs.type === "retry") {
|
|
753
|
+
console.warn(`[rosyn/whats] WA retry receipt:`, JSON.stringify(node));
|
|
754
|
+
const retryPid = node.attrs.participant || node.attrs.from;
|
|
755
|
+
const retryNode = Array.isArray(node.content)
|
|
756
|
+
? node.content.find((c) => c.tag === "retry")
|
|
757
|
+
: undefined;
|
|
758
|
+
const retryCount = retryNode?.attrs?.count ?? "1";
|
|
759
|
+
if (Number(retryCount) <= 5 && retryPid) {
|
|
760
|
+
void (async () => {
|
|
761
|
+
const cachedMsg = sentMessages.get(node.attrs.id);
|
|
762
|
+
if (!cachedMsg)
|
|
763
|
+
return;
|
|
764
|
+
const keysNode = Array.isArray(node.content)
|
|
765
|
+
? node.content.find((c) => c.tag === "keys")
|
|
766
|
+
: undefined;
|
|
767
|
+
if (keysNode && Array.isArray(keysNode.content)) {
|
|
768
|
+
const regNode = keysNode.content.find((c) => c.tag === "registration");
|
|
769
|
+
const identNode = keysNode.content.find((c) => c.tag === "identity");
|
|
770
|
+
const skeyNode = keysNode.content.find((c) => c.tag === "skey");
|
|
771
|
+
const keyNode = keysNode.content.find((c) => c.tag === "key");
|
|
772
|
+
if (regNode?.content instanceof Uint8Array &&
|
|
773
|
+
identNode?.content instanceof Uint8Array &&
|
|
774
|
+
Array.isArray(skeyNode?.content)) {
|
|
775
|
+
const skeyIdBuf = skeyNode.content.find((c) => c.tag === "id")?.content;
|
|
776
|
+
const skeyValBuf = skeyNode.content.find((c) => c.tag === "value")?.content;
|
|
777
|
+
if (skeyIdBuf instanceof Uint8Array && skeyValBuf instanceof Uint8Array) {
|
|
778
|
+
let preKey;
|
|
779
|
+
if (Array.isArray(keyNode?.content)) {
|
|
780
|
+
const pkIdBuf = keyNode.content.find((c) => c.tag === "id")?.content;
|
|
781
|
+
const pkValBuf = keyNode.content.find((c) => c.tag === "value")?.content;
|
|
782
|
+
if (pkIdBuf instanceof Uint8Array && pkValBuf instanceof Uint8Array) {
|
|
783
|
+
preKey = {
|
|
784
|
+
keyId: Buffer.from(pkIdBuf).readUIntBE(0, pkIdBuf.length),
|
|
785
|
+
publicKey: pkValBuf,
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
await signalMgr.initOutgoingSession(jidToSignalAddress(retryPid), {
|
|
790
|
+
registrationId: Buffer.from(regNode.content).readUInt32BE(0),
|
|
791
|
+
identityKey: identNode.content,
|
|
792
|
+
signedPreKey: {
|
|
793
|
+
keyId: Buffer.from(skeyIdBuf).readUIntBE(0, skeyIdBuf.length),
|
|
794
|
+
publicKey: skeyValBuf,
|
|
795
|
+
},
|
|
796
|
+
preKey,
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
let payloadToResend = { ...cachedMsg.message };
|
|
802
|
+
const meJid = authCreds.me?.id ?? sock.user?.id ?? "0@s.whatsapp.net";
|
|
803
|
+
const meLid = authCreds.me?.lid ?? sock.user?.lid;
|
|
804
|
+
let retryAddrMode;
|
|
805
|
+
if (cachedMsg.jid.endsWith("@g.us")) {
|
|
806
|
+
const meta = await sock.groupMetadata(cachedMsg.jid);
|
|
807
|
+
retryAddrMode =
|
|
808
|
+
meta.addressingMode ||
|
|
809
|
+
((meta.participants ?? []).some((p) => p.id.endsWith("@lid")) ? "lid" : "pn");
|
|
810
|
+
const groupSender = retryAddrMode === "lid" && meLid ? meLid : meJid;
|
|
811
|
+
const { distributionBytes } = await signalMgr.getOrCreateGroupDistribution(`${cachedMsg.jid}:${jidToSignalAddress(groupSender)}`);
|
|
812
|
+
payloadToResend = {
|
|
813
|
+
...cachedMsg.message,
|
|
814
|
+
senderKeyDistributionMessage: {
|
|
815
|
+
groupId: cachedMsg.jid,
|
|
816
|
+
axolotlSenderKeyDistributionMessage: distributionBytes,
|
|
817
|
+
},
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
const retryUser = jidDecode(retryPid)?.user;
|
|
821
|
+
const isMeRetry = Boolean((retryUser && jidDecode(meJid)?.user === retryUser) ||
|
|
822
|
+
(retryUser && meLid && jidDecode(meLid)?.user === retryUser));
|
|
823
|
+
if (isMeRetry) {
|
|
824
|
+
payloadToResend = {
|
|
825
|
+
deviceSentMessage: {
|
|
826
|
+
destinationJid: cachedMsg.jid,
|
|
827
|
+
message: payloadToResend,
|
|
828
|
+
},
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
const paddedRetry = writeRandomPadMax16(proto.Message.encode(payloadToResend));
|
|
832
|
+
const enc = await signalMgr.encryptMessage(jidToSignalAddress(retryPid), paddedRetry);
|
|
833
|
+
const getMediaStanzaMeta = (m) => {
|
|
834
|
+
if (!m)
|
|
835
|
+
return { stanzaType: "text" };
|
|
836
|
+
if (m.buttonsMessage)
|
|
837
|
+
return { stanzaType: "media", mediatype: "button" };
|
|
838
|
+
if (m.stickerPackMessage)
|
|
839
|
+
return { stanzaType: "media", mediatype: "sticker_pack" };
|
|
840
|
+
if (m.imageMessage)
|
|
841
|
+
return { stanzaType: "media", mediatype: "image" };
|
|
842
|
+
if (m.videoMessage)
|
|
843
|
+
return { stanzaType: "media", mediatype: m.videoMessage.gifPlayback ? "gif" : "video" };
|
|
844
|
+
if (m.audioMessage)
|
|
845
|
+
return { stanzaType: "media", mediatype: m.audioMessage.ptt ? "ptt" : "audio" };
|
|
846
|
+
if (m.documentMessage)
|
|
847
|
+
return { stanzaType: "media", mediatype: "document" };
|
|
848
|
+
if (m.stickerMessage)
|
|
849
|
+
return { stanzaType: "media", mediatype: "sticker" };
|
|
850
|
+
return { stanzaType: "text" };
|
|
851
|
+
};
|
|
852
|
+
const { stanzaType: retryStanzaType, mediatype: retryMediatype } = getMediaStanzaMeta(cachedMsg.message);
|
|
853
|
+
const isLegacyBtnRetry = Boolean(cachedMsg.message?.buttonsMessage);
|
|
854
|
+
const retryContent = [
|
|
855
|
+
{
|
|
856
|
+
tag: "enc",
|
|
857
|
+
attrs: {
|
|
858
|
+
v: "2",
|
|
859
|
+
type: enc.type,
|
|
860
|
+
count: retryCount,
|
|
861
|
+
...(retryMediatype ? { mediatype: retryMediatype } : {}),
|
|
862
|
+
},
|
|
863
|
+
content: enc.body,
|
|
864
|
+
},
|
|
865
|
+
];
|
|
866
|
+
if (cachedMsg.message?.interactiveMessage?.nativeFlowMessage ||
|
|
867
|
+
cachedMsg.message?.interactiveMessage?.carouselMessage ||
|
|
868
|
+
isLegacyBtnRetry) {
|
|
869
|
+
const firstBtn = cachedMsg.message?.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name;
|
|
870
|
+
const nfName = firstBtn === "payment_info"
|
|
871
|
+
? "payment_info"
|
|
872
|
+
: firstBtn === "review_and_pay"
|
|
873
|
+
? "order_details"
|
|
874
|
+
: firstBtn === "form_message"
|
|
875
|
+
? "form_message"
|
|
876
|
+
: "mixed";
|
|
877
|
+
retryContent.push({
|
|
878
|
+
tag: "biz",
|
|
879
|
+
attrs: {},
|
|
880
|
+
content: [
|
|
881
|
+
{
|
|
882
|
+
tag: "interactive",
|
|
883
|
+
attrs: { type: "native_flow", v: "1" },
|
|
884
|
+
content: [
|
|
885
|
+
{
|
|
886
|
+
tag: "native_flow",
|
|
887
|
+
attrs: nfName === "mixed" ? { v: "9", name: "mixed" } : { name: nfName },
|
|
888
|
+
},
|
|
889
|
+
],
|
|
890
|
+
},
|
|
891
|
+
],
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
if (enc.type === "pkmsg" && authCreds.account) {
|
|
895
|
+
const acc = reviveBuffers(authCreds.account);
|
|
896
|
+
retryContent.push({
|
|
897
|
+
tag: "device-identity",
|
|
898
|
+
attrs: {},
|
|
899
|
+
content: proto.ADVSignedDeviceIdentity.encode({
|
|
900
|
+
details: acc.details,
|
|
901
|
+
accountSignatureKey: acc.accountSignatureKey,
|
|
902
|
+
accountSignature: acc.accountSignature,
|
|
903
|
+
deviceSignature: acc.deviceSignature,
|
|
904
|
+
}),
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
908
|
+
tag: "message",
|
|
909
|
+
attrs: {
|
|
910
|
+
id: node.attrs.id,
|
|
911
|
+
to: cachedMsg.jid,
|
|
912
|
+
...(cachedMsg.jid.endsWith("@g.us") ? { participant: retryPid } : {}),
|
|
913
|
+
type: retryStanzaType,
|
|
914
|
+
},
|
|
915
|
+
content: retryContent,
|
|
916
|
+
}));
|
|
917
|
+
})().catch(() => { });
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
if (node.tag === "ack") {
|
|
923
|
+
if (node.attrs.error || node.attrs.class === "message") {
|
|
924
|
+
console.log(`[rosyn/whats] WA ack:`, node.attrs);
|
|
925
|
+
}
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
if (node.tag === "iq" && node.attrs.type === "get" && node.attrs.xmlns === "w:p") {
|
|
929
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
930
|
+
tag: "iq",
|
|
931
|
+
attrs: { to: "s.whatsapp.net", type: "result", id: node.attrs.id ?? nextTag() },
|
|
932
|
+
}));
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
if (node.tag === "message" && node.attrs.id && node.attrs.from) {
|
|
936
|
+
const msgId = node.attrs.id;
|
|
937
|
+
const from = node.attrs.from;
|
|
938
|
+
const participant = node.attrs.participant;
|
|
939
|
+
const recipient = node.attrs.recipient;
|
|
940
|
+
const isGroup = from.endsWith("@g.us");
|
|
941
|
+
const chatId = isGroup || from === "status@broadcast" ? from : recipient || from;
|
|
942
|
+
const author = isGroup || from === "status@broadcast" ? participant || from : from;
|
|
943
|
+
rememberLidPn(participant, node.attrs.participant_pn);
|
|
944
|
+
rememberLidPn(from, node.attrs.sender_pn);
|
|
945
|
+
rememberLidPn(authCreds.me?.lid, authCreds.me?.id);
|
|
946
|
+
const meId = authCreds.me?.id ?? sock.user?.id;
|
|
947
|
+
const meLid = authCreds.me?.lid ?? sock.user?.lid;
|
|
948
|
+
const fromMe = Boolean((meId && jidDecode(author)?.user === jidDecode(meId)?.user) ||
|
|
949
|
+
(meLid && jidDecode(author)?.user === jidDecode(meLid)?.user));
|
|
950
|
+
const ackAttrs = {
|
|
951
|
+
to: from,
|
|
952
|
+
id: msgId,
|
|
953
|
+
class: "message",
|
|
954
|
+
};
|
|
955
|
+
if (participant)
|
|
956
|
+
ackAttrs.participant = participant;
|
|
957
|
+
if (recipient)
|
|
958
|
+
ackAttrs.recipient = recipient;
|
|
959
|
+
transport.sendEncrypted(encodeWABinaryNode({ tag: "ack", attrs: ackAttrs }));
|
|
960
|
+
if (Array.isArray(node.content)) {
|
|
961
|
+
void (async () => {
|
|
962
|
+
for (const child of node.content) {
|
|
963
|
+
if ((child.tag !== "enc" && child.tag !== "plaintext") || !(child.content instanceof Uint8Array)) {
|
|
964
|
+
continue;
|
|
965
|
+
}
|
|
966
|
+
const encType = child.tag === "plaintext" ? "plaintext" : child.attrs.type;
|
|
967
|
+
let plainBuf;
|
|
968
|
+
if (encType === "plaintext") {
|
|
969
|
+
plainBuf = Buffer.from(child.content);
|
|
970
|
+
}
|
|
971
|
+
else if (encType === "skmsg") {
|
|
972
|
+
const groupKey = `${chatId}:${jidToSignalAddress(author)}`;
|
|
973
|
+
plainBuf = unpadRandomMax16(await signalMgr.decryptGroupMessage(groupKey, child.content));
|
|
974
|
+
}
|
|
975
|
+
else if (encType === "pkmsg" || encType === "msg") {
|
|
976
|
+
const addr = jidToSignalAddress(author);
|
|
977
|
+
plainBuf = unpadRandomMax16(await signalMgr.decryptMessage(addr, encType, child.content));
|
|
978
|
+
}
|
|
979
|
+
else {
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
982
|
+
let decoded = proto.Message.decode(plainBuf);
|
|
983
|
+
decoded = decoded.deviceSentMessage?.message ?? decoded;
|
|
984
|
+
if (decoded.senderKeyDistributionMessage?.axolotlSenderKeyDistributionMessage) {
|
|
985
|
+
const gId = decoded.senderKeyDistributionMessage.groupId ?? chatId;
|
|
986
|
+
await signalMgr.processSenderKeyDistribution(`${gId}:${jidToSignalAddress(author)}`, decoded.senderKeyDistributionMessage.axolotlSenderKeyDistributionMessage);
|
|
987
|
+
}
|
|
988
|
+
const hasDisplayContent = Boolean(decoded.conversation ||
|
|
989
|
+
decoded.extendedTextMessage?.text ||
|
|
990
|
+
decoded.buttonsResponseMessage?.selectedButtonId ||
|
|
991
|
+
decoded.interactiveResponseMessage?.nativeFlowResponseMessage ||
|
|
992
|
+
decoded.ephemeralMessage?.message ||
|
|
993
|
+
decoded.viewOnceMessage?.message ||
|
|
994
|
+
decoded.viewOnceMessageV2?.message ||
|
|
995
|
+
decoded.documentWithCaptionMessage?.message ||
|
|
996
|
+
decoded.editedMessage?.message);
|
|
997
|
+
if (hasDisplayContent) {
|
|
998
|
+
if (isGroup &&
|
|
999
|
+
participant?.endsWith("@lid") &&
|
|
1000
|
+
!node.attrs.participant_pn &&
|
|
1001
|
+
!lidToPnMap.has(jidNormalizedUser(participant))) {
|
|
1002
|
+
await sock.groupMetadata(chatId).catch(() => undefined);
|
|
1003
|
+
}
|
|
1004
|
+
ev.emit("messages.upsert", {
|
|
1005
|
+
type: "notify",
|
|
1006
|
+
messages: [
|
|
1007
|
+
{
|
|
1008
|
+
key: {
|
|
1009
|
+
remoteJid: !isGroup && chatId !== "status@broadcast" ? resolvePnJid(chatId) : chatId,
|
|
1010
|
+
remoteJidAlt: !isGroup
|
|
1011
|
+
? node.attrs.sender_pn || node.attrs.sender_lid || node.attrs.peer_recipient_pn
|
|
1012
|
+
: undefined,
|
|
1013
|
+
fromMe,
|
|
1014
|
+
id: msgId,
|
|
1015
|
+
participant: participant ? resolvePnJid(node.attrs.participant_pn || participant) : undefined,
|
|
1016
|
+
participantAlt: isGroup ? node.attrs.participant_pn || node.attrs.participant_lid : undefined,
|
|
1017
|
+
},
|
|
1018
|
+
message: decoded,
|
|
1019
|
+
messageTimestamp: Number(node.attrs.t || Math.floor(Date.now() / 1000)),
|
|
1020
|
+
pushName: node.attrs.notify,
|
|
1021
|
+
},
|
|
1022
|
+
],
|
|
1023
|
+
});
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
})().catch(() => { });
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
catch {
|
|
1031
|
+
}
|
|
1032
|
+
},
|
|
1033
|
+
onClose: (code, reason) => {
|
|
1034
|
+
emitClose(Object.assign(new Error(`WebSocket closed (${code}): ${reason}`), {
|
|
1035
|
+
output: { statusCode: DisconnectReason.connectionClosed },
|
|
1036
|
+
}));
|
|
1037
|
+
},
|
|
1038
|
+
});
|
|
1039
|
+
const sendQuery = (node, timeoutMs = 15_000) => {
|
|
1040
|
+
const id = node.attrs.id ?? nextTag();
|
|
1041
|
+
node.attrs.id = id;
|
|
1042
|
+
return new Promise((resolve, reject) => {
|
|
1043
|
+
const timer = setTimeout(() => {
|
|
1044
|
+
pendingQueries.delete(id);
|
|
1045
|
+
reject(new Error(`WA query ${id} timed out`));
|
|
1046
|
+
}, timeoutMs);
|
|
1047
|
+
pendingQueries.set(id, {
|
|
1048
|
+
resolve: (n) => {
|
|
1049
|
+
clearTimeout(timer);
|
|
1050
|
+
resolve(n);
|
|
1051
|
+
},
|
|
1052
|
+
reject: (e) => {
|
|
1053
|
+
clearTimeout(timer);
|
|
1054
|
+
reject(e);
|
|
1055
|
+
},
|
|
1056
|
+
});
|
|
1057
|
+
transport.sendEncrypted(encodeWABinaryNode(node));
|
|
1058
|
+
});
|
|
1059
|
+
};
|
|
1060
|
+
const sock = {
|
|
1061
|
+
ev,
|
|
1062
|
+
user: { id: "0@s.whatsapp.net", name: "RosynWhats" },
|
|
1063
|
+
ws: { isOpen: false },
|
|
1064
|
+
authState: config.auth,
|
|
1065
|
+
async sendMessage(jid, content, options) {
|
|
1066
|
+
const uploadWaMedia = async (plaintext, mediaType, uploadPath, mediaKey = randomBytes(32)) => {
|
|
1067
|
+
const enc = encryptWaMedia(plaintext, mediaType, mediaKey);
|
|
1068
|
+
const connRes = await sendQuery({
|
|
1069
|
+
tag: "iq",
|
|
1070
|
+
attrs: { to: "s.whatsapp.net", type: "set", id: nextTag(), xmlns: "w:m" },
|
|
1071
|
+
content: [{ tag: "media_conn", attrs: {} }],
|
|
1072
|
+
});
|
|
1073
|
+
const mcNode = Array.isArray(connRes.content) ? connRes.content.find((c) => c.tag === "media_conn") : undefined;
|
|
1074
|
+
const auth = mcNode?.attrs?.auth ?? "";
|
|
1075
|
+
const hostNode = Array.isArray(mcNode?.content) ? mcNode.content.find((c) => c.tag === "host") : undefined;
|
|
1076
|
+
const host = hostNode?.attrs?.hostname ?? "mmg.whatsapp.net";
|
|
1077
|
+
const token = enc.fileEncSha256.toString("base64url");
|
|
1078
|
+
const uploadUrl = `https://${host}${uploadPath}/${token}?auth=${encodeURIComponent(auth)}&token=${token}`;
|
|
1079
|
+
const res = await fetch(uploadUrl, {
|
|
1080
|
+
method: "POST",
|
|
1081
|
+
headers: { "Content-Type": "application/octet-stream", Origin: "https://web.whatsapp.com" },
|
|
1082
|
+
body: new Uint8Array(enc.encData),
|
|
1083
|
+
});
|
|
1084
|
+
if (!res.ok) {
|
|
1085
|
+
throw new Error(`Media upload failed (${res.status}) for ${uploadPath}`);
|
|
1086
|
+
}
|
|
1087
|
+
const json = (await res.json());
|
|
1088
|
+
return {
|
|
1089
|
+
mediaKey: enc.mediaKey,
|
|
1090
|
+
fileSha256: enc.fileSha256,
|
|
1091
|
+
fileEncSha256: enc.fileEncSha256,
|
|
1092
|
+
fileLength: plaintext.byteLength,
|
|
1093
|
+
url: json.url ?? "",
|
|
1094
|
+
directPath: json.direct_path ?? "",
|
|
1095
|
+
};
|
|
1096
|
+
};
|
|
1097
|
+
const resolveMediaBuffer = async (input) => {
|
|
1098
|
+
if (input instanceof Uint8Array)
|
|
1099
|
+
return Buffer.from(input);
|
|
1100
|
+
const urlStr = typeof input === "string" ? input : typeof input?.url === "string" ? input.url : "";
|
|
1101
|
+
if (!urlStr)
|
|
1102
|
+
return Buffer.alloc(0);
|
|
1103
|
+
if (/^https?:\/\//i.test(urlStr)) {
|
|
1104
|
+
const r = await fetch(urlStr);
|
|
1105
|
+
if (!r.ok)
|
|
1106
|
+
throw new Error(`Failed to fetch media (${r.status}): ${urlStr}`);
|
|
1107
|
+
return Buffer.from(await r.arrayBuffer());
|
|
1108
|
+
}
|
|
1109
|
+
return fs.readFileSync(urlStr);
|
|
1110
|
+
};
|
|
1111
|
+
const buildCardOrInteractiveHeader = async (src) => {
|
|
1112
|
+
if (src.video) {
|
|
1113
|
+
const buf = await resolveMediaBuffer(src.video);
|
|
1114
|
+
if (buf.length > 0) {
|
|
1115
|
+
const up = await uploadWaMedia(buf, "video", "/mms/video");
|
|
1116
|
+
return {
|
|
1117
|
+
...(src.title ? { title: String(src.title) } : {}),
|
|
1118
|
+
hasMediaAttachment: true,
|
|
1119
|
+
videoMessage: {
|
|
1120
|
+
url: up.url,
|
|
1121
|
+
directPath: up.directPath,
|
|
1122
|
+
mimetype: String(src.mimetype ?? "video/mp4"),
|
|
1123
|
+
fileSha256: up.fileSha256,
|
|
1124
|
+
fileEncSha256: up.fileEncSha256,
|
|
1125
|
+
fileLength: up.fileLength,
|
|
1126
|
+
mediaKey: up.mediaKey,
|
|
1127
|
+
mediaKeyTimestamp: Math.floor(Date.now() / 1000),
|
|
1128
|
+
},
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
if (src.image) {
|
|
1133
|
+
const buf = await resolveMediaBuffer(src.image);
|
|
1134
|
+
if (buf.length > 0) {
|
|
1135
|
+
const up = await uploadWaMedia(buf, "image", "/mms/image");
|
|
1136
|
+
return {
|
|
1137
|
+
...(src.title ? { title: String(src.title) } : {}),
|
|
1138
|
+
hasMediaAttachment: true,
|
|
1139
|
+
imageMessage: {
|
|
1140
|
+
url: up.url,
|
|
1141
|
+
directPath: up.directPath,
|
|
1142
|
+
mimetype: String(src.mimetype ?? "image/jpeg"),
|
|
1143
|
+
fileSha256: up.fileSha256,
|
|
1144
|
+
fileEncSha256: up.fileEncSha256,
|
|
1145
|
+
fileLength: up.fileLength,
|
|
1146
|
+
mediaKey: up.mediaKey,
|
|
1147
|
+
mediaKeyTimestamp: Math.floor(Date.now() / 1000),
|
|
1148
|
+
},
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
return src.title ? { title: String(src.title), hasMediaAttachment: false } : undefined;
|
|
1153
|
+
};
|
|
1154
|
+
const buildOutgoingWAMessage = async (c) => {
|
|
1155
|
+
if (c?.delete && typeof c.delete === "object") {
|
|
1156
|
+
return {
|
|
1157
|
+
protocolMessage: {
|
|
1158
|
+
key: {
|
|
1159
|
+
remoteJid: c.delete.remoteJid ?? jid,
|
|
1160
|
+
fromMe: Boolean(c.delete.fromMe),
|
|
1161
|
+
id: String(c.delete.id ?? ""),
|
|
1162
|
+
...(c.delete.participant ? { participant: String(c.delete.participant) } : {}),
|
|
1163
|
+
},
|
|
1164
|
+
type: 0,
|
|
1165
|
+
},
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
if (c?.edit && typeof c.edit === "object") {
|
|
1169
|
+
return {
|
|
1170
|
+
protocolMessage: {
|
|
1171
|
+
key: {
|
|
1172
|
+
remoteJid: c.edit.remoteJid ?? jid,
|
|
1173
|
+
fromMe: c.edit.fromMe !== undefined ? Boolean(c.edit.fromMe) : true,
|
|
1174
|
+
id: String(c.edit.id ?? ""),
|
|
1175
|
+
...(c.edit.participant ? { participant: String(c.edit.participant) } : {}),
|
|
1176
|
+
},
|
|
1177
|
+
type: 14,
|
|
1178
|
+
editedMessage: { conversation: String(c.text ?? "") },
|
|
1179
|
+
},
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
if (c?.react && typeof c.react === "object") {
|
|
1183
|
+
const rKey = c.react.key ?? {};
|
|
1184
|
+
return {
|
|
1185
|
+
reactionMessage: {
|
|
1186
|
+
key: {
|
|
1187
|
+
remoteJid: rKey.remoteJid ?? jid,
|
|
1188
|
+
fromMe: Boolean(rKey.fromMe),
|
|
1189
|
+
id: String(rKey.id ?? ""),
|
|
1190
|
+
...(rKey.participant ? { participant: String(rKey.participant) } : {}),
|
|
1191
|
+
},
|
|
1192
|
+
text: String(c.react.text ?? ""),
|
|
1193
|
+
senderTimestampMs: Date.now(),
|
|
1194
|
+
},
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
if (c?.poll && typeof c.poll === "object") {
|
|
1198
|
+
const values = Array.isArray(c.poll.values) ? c.poll.values : [];
|
|
1199
|
+
return {
|
|
1200
|
+
pollCreationMessageV3: {
|
|
1201
|
+
name: String(c.poll.name ?? ""),
|
|
1202
|
+
options: values.map((v) => ({ optionName: String(v) })),
|
|
1203
|
+
selectableOptionsCount: Number(c.poll.selectableCount ?? 0),
|
|
1204
|
+
},
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
if (c?.location && typeof c.location === "object" && !c?.buttons && !c?.interactiveButtons) {
|
|
1208
|
+
return {
|
|
1209
|
+
locationMessage: {
|
|
1210
|
+
degreesLatitude: Number(c.location.degreesLatitude ?? 0),
|
|
1211
|
+
degreesLongitude: Number(c.location.degreesLongitude ?? 0),
|
|
1212
|
+
...(c.location.name ? { name: String(c.location.name) } : {}),
|
|
1213
|
+
...(c.location.address ? { address: String(c.location.address) } : {}),
|
|
1214
|
+
...(c.location.url ? { url: String(c.location.url) } : {}),
|
|
1215
|
+
},
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
if (c?.contacts && typeof c.contacts === "object") {
|
|
1219
|
+
const list = Array.isArray(c.contacts.contacts) ? c.contacts.contacts : [];
|
|
1220
|
+
const normalized = list.map((ct) => ({
|
|
1221
|
+
displayName: ct.displayName ? String(ct.displayName) : undefined,
|
|
1222
|
+
vcard: ct.vcard ? String(ct.vcard) : "",
|
|
1223
|
+
}));
|
|
1224
|
+
if (normalized.length === 1) {
|
|
1225
|
+
return { contactMessage: normalized[0] };
|
|
1226
|
+
}
|
|
1227
|
+
return {
|
|
1228
|
+
contactsArrayMessage: {
|
|
1229
|
+
displayName: c.contacts.displayName ? String(c.contacts.displayName) : `${normalized.length} contacts`,
|
|
1230
|
+
contacts: normalized,
|
|
1231
|
+
},
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
if (c?.rawMessage && typeof c.rawMessage === "object") {
|
|
1235
|
+
return c.rawMessage;
|
|
1236
|
+
}
|
|
1237
|
+
if (c?.stickerPackMessage)
|
|
1238
|
+
return { stickerPackMessage: c.stickerPackMessage };
|
|
1239
|
+
if (c?.stickerPack && typeof c.stickerPack === "object") {
|
|
1240
|
+
const sp = c.stickerPack;
|
|
1241
|
+
const rawStickers = Array.isArray(sp.stickers) ? sp.stickers : [];
|
|
1242
|
+
const zipEntries = {};
|
|
1243
|
+
const protoStickers = [];
|
|
1244
|
+
for (let i = 0; i < rawStickers.length; i++) {
|
|
1245
|
+
const item = rawStickers[i];
|
|
1246
|
+
const buf = item instanceof Uint8Array
|
|
1247
|
+
? item
|
|
1248
|
+
: item?.sticker instanceof Uint8Array
|
|
1249
|
+
? item.sticker
|
|
1250
|
+
: item?.data instanceof Uint8Array
|
|
1251
|
+
? item.data
|
|
1252
|
+
: Buffer.alloc(0);
|
|
1253
|
+
if (buf.length === 0)
|
|
1254
|
+
continue;
|
|
1255
|
+
const fileName = String(item?.fileName ?? `sticker_${i}.webp`);
|
|
1256
|
+
const bufView = Buffer.from(buf);
|
|
1257
|
+
const detectedAnimated = bufView.subarray(0, 64).includes("ANIM");
|
|
1258
|
+
zipEntries[fileName] = new Uint8Array(buf);
|
|
1259
|
+
protoStickers.push({
|
|
1260
|
+
fileName,
|
|
1261
|
+
isAnimated: Boolean(item?.isAnimated ?? detectedAnimated),
|
|
1262
|
+
emojis: Array.isArray(item?.emojis) ? item.emojis.map(String) : ["😀"],
|
|
1263
|
+
mimetype: String(item?.mimetype ?? "image/webp"),
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
const coverBuf = sp.cover instanceof Uint8Array
|
|
1267
|
+
? Buffer.from(sp.cover)
|
|
1268
|
+
: Buffer.from(Object.values(zipEntries)[0] ?? []);
|
|
1269
|
+
const coverExt = coverBuf.subarray(0, 4).toString("ascii") === "RIFF"
|
|
1270
|
+
? "webp"
|
|
1271
|
+
: coverBuf[0] === 0xff && coverBuf[1] === 0xd8
|
|
1272
|
+
? "jpg"
|
|
1273
|
+
: "png";
|
|
1274
|
+
const trayIconFileName = String(sp.trayIconFileName ?? `tray.${coverExt}`);
|
|
1275
|
+
if (coverBuf.length > 0 && !zipEntries[trayIconFileName]) {
|
|
1276
|
+
zipEntries[trayIconFileName] = new Uint8Array(coverBuf);
|
|
1277
|
+
}
|
|
1278
|
+
const bundleBytes = zipSync(zipEntries, { level: 0 });
|
|
1279
|
+
const mediaKey = randomBytes(32);
|
|
1280
|
+
const [bundleUp, coverUp] = await Promise.all([
|
|
1281
|
+
uploadWaMedia(bundleBytes, "sticker-pack", "/mms/sticker-pack", mediaKey),
|
|
1282
|
+
uploadWaMedia(coverBuf, "thumbnail-sticker-pack", "/mms/thumbnail-sticker-pack", mediaKey),
|
|
1283
|
+
]);
|
|
1284
|
+
return {
|
|
1285
|
+
stickerPackMessage: {
|
|
1286
|
+
stickerPackId: String(sp.stickerPackId ?? generateMessageIDV2(authCreds.me?.id ?? jid)),
|
|
1287
|
+
name: String(sp.name ?? "Sticker Pack"),
|
|
1288
|
+
publisher: String(sp.publisher ?? "RosynWhats"),
|
|
1289
|
+
stickers: protoStickers,
|
|
1290
|
+
fileLength: bundleUp.fileLength,
|
|
1291
|
+
fileSha256: bundleUp.fileSha256,
|
|
1292
|
+
fileEncSha256: bundleUp.fileEncSha256,
|
|
1293
|
+
mediaKey,
|
|
1294
|
+
directPath: bundleUp.directPath,
|
|
1295
|
+
caption: sp.caption ? String(sp.caption) : undefined,
|
|
1296
|
+
packDescription: sp.description || sp.packDescription ? String(sp.description ?? sp.packDescription) : undefined,
|
|
1297
|
+
mediaKeyTimestamp: Math.floor(Date.now() / 1000),
|
|
1298
|
+
trayIconFileName,
|
|
1299
|
+
thumbnailDirectPath: coverUp.directPath,
|
|
1300
|
+
thumbnailSha256: coverUp.fileSha256,
|
|
1301
|
+
thumbnailEncSha256: coverUp.fileEncSha256,
|
|
1302
|
+
thumbnailHeight: Number(sp.thumbnailHeight ?? 252),
|
|
1303
|
+
thumbnailWidth: Number(sp.thumbnailWidth ?? 252),
|
|
1304
|
+
imageDataHash: coverUp.fileSha256.toString("base64"),
|
|
1305
|
+
stickerPackSize: bundleUp.fileLength,
|
|
1306
|
+
stickerPackOrigin: 1,
|
|
1307
|
+
},
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
if (c?.interactiveMessage)
|
|
1311
|
+
return { interactiveMessage: c.interactiveMessage };
|
|
1312
|
+
if (c?.buttonsMessage)
|
|
1313
|
+
return { buttonsMessage: c.buttonsMessage };
|
|
1314
|
+
if (Array.isArray(c?.cards) && c.cards.length > 0) {
|
|
1315
|
+
const cards = await Promise.all(c.cards.map(async (card) => {
|
|
1316
|
+
const header = await buildCardOrInteractiveHeader(card);
|
|
1317
|
+
return {
|
|
1318
|
+
...(header ? { header } : {}),
|
|
1319
|
+
body: { text: String(card.body ?? card.text ?? card.caption ?? "") },
|
|
1320
|
+
...(card.footer ? { footer: { text: String(card.footer) } } : {}),
|
|
1321
|
+
nativeFlowMessage: {
|
|
1322
|
+
buttons: (Array.isArray(card.buttons) ? card.buttons : []).map((b) => ({
|
|
1323
|
+
name: String(b.name ?? "quick_reply"),
|
|
1324
|
+
buttonParamsJson: typeof b.buttonParamsJson === "string"
|
|
1325
|
+
? b.buttonParamsJson
|
|
1326
|
+
: JSON.stringify(b.buttonParamsJson ?? {}),
|
|
1327
|
+
})),
|
|
1328
|
+
messageParamsJson: src.messageParams
|
|
1329
|
+
? typeof src.messageParams === "string"
|
|
1330
|
+
? src.messageParams
|
|
1331
|
+
: JSON.stringify(src.messageParams)
|
|
1332
|
+
: "{}",
|
|
1333
|
+
messageVersion: 1,
|
|
1334
|
+
},
|
|
1335
|
+
};
|
|
1336
|
+
}));
|
|
1337
|
+
if (cards.length === 1) {
|
|
1338
|
+
return { interactiveMessage: cards[0] };
|
|
1339
|
+
}
|
|
1340
|
+
return {
|
|
1341
|
+
interactiveMessage: {
|
|
1342
|
+
...(c.title ? { header: { title: String(c.title), hasMediaAttachment: false } } : {}),
|
|
1343
|
+
body: { text: String(c.text ?? c.body ?? c.caption ?? "") },
|
|
1344
|
+
...(c.footer ? { footer: { text: String(c.footer) } } : {}),
|
|
1345
|
+
carouselMessage: { cards, messageVersion: 1 },
|
|
1346
|
+
},
|
|
1347
|
+
};
|
|
1348
|
+
}
|
|
1349
|
+
const src = c;
|
|
1350
|
+
const rawBtns = Array.isArray(src?.interactiveButtons)
|
|
1351
|
+
? src.interactiveButtons
|
|
1352
|
+
: Array.isArray(src?.buttons)
|
|
1353
|
+
? src.buttons
|
|
1354
|
+
: undefined;
|
|
1355
|
+
if (rawBtns && rawBtns.length > 0) {
|
|
1356
|
+
const isNative = rawBtns.some((b) => typeof b?.name === "string" || (b?.nativeFlowInfo && typeof b.nativeFlowInfo?.name === "string"));
|
|
1357
|
+
if (isNative) {
|
|
1358
|
+
const header = await buildCardOrInteractiveHeader(src);
|
|
1359
|
+
return {
|
|
1360
|
+
interactiveMessage: {
|
|
1361
|
+
...(header ? { header } : {}),
|
|
1362
|
+
body: { text: String(src.body ?? src.text ?? src.caption ?? "") },
|
|
1363
|
+
...(src.footer ? { footer: { text: String(src.footer) } } : {}),
|
|
1364
|
+
nativeFlowMessage: {
|
|
1365
|
+
buttons: rawBtns.map((b) => {
|
|
1366
|
+
const nf = b?.nativeFlowInfo;
|
|
1367
|
+
const name = String(nf?.name ?? b?.name ?? "quick_reply");
|
|
1368
|
+
const rawParams = nf?.paramsJson ?? b?.buttonParamsJson ?? {};
|
|
1369
|
+
return {
|
|
1370
|
+
name,
|
|
1371
|
+
buttonParamsJson: typeof rawParams === "string" ? rawParams : JSON.stringify(rawParams),
|
|
1372
|
+
};
|
|
1373
|
+
}),
|
|
1374
|
+
messageParamsJson: src.messageParams
|
|
1375
|
+
? typeof src.messageParams === "string"
|
|
1376
|
+
? src.messageParams
|
|
1377
|
+
: JSON.stringify(src.messageParams)
|
|
1378
|
+
: "{}",
|
|
1379
|
+
messageVersion: 1,
|
|
1380
|
+
},
|
|
1381
|
+
},
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
return {
|
|
1385
|
+
buttonsMessage: {
|
|
1386
|
+
contentText: String(src.text ?? src.caption ?? src.body ?? ""),
|
|
1387
|
+
...(src.footer ? { footerText: String(src.footer) } : {}),
|
|
1388
|
+
buttons: rawBtns.map((b, idx) => ({
|
|
1389
|
+
buttonId: String(b.buttonId ?? b.id ?? `btn_${idx}`),
|
|
1390
|
+
buttonText: { displayText: String(b.buttonText?.displayText ?? b.displayText ?? b.text ?? "Button") },
|
|
1391
|
+
type: Number(b.type ?? 1),
|
|
1392
|
+
})),
|
|
1393
|
+
headerType: 1,
|
|
1394
|
+
},
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
if (c?.image) {
|
|
1398
|
+
const buf = await resolveMediaBuffer(c.image);
|
|
1399
|
+
const up = await uploadWaMedia(buf, "image", "/mms/image");
|
|
1400
|
+
return {
|
|
1401
|
+
imageMessage: {
|
|
1402
|
+
url: up.url,
|
|
1403
|
+
directPath: up.directPath,
|
|
1404
|
+
mimetype: String(c.mimetype ?? "image/jpeg"),
|
|
1405
|
+
caption: c.caption ? String(c.caption) : undefined,
|
|
1406
|
+
fileSha256: up.fileSha256,
|
|
1407
|
+
fileEncSha256: up.fileEncSha256,
|
|
1408
|
+
fileLength: up.fileLength,
|
|
1409
|
+
mediaKey: up.mediaKey,
|
|
1410
|
+
mediaKeyTimestamp: Math.floor(Date.now() / 1000),
|
|
1411
|
+
},
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
if (c?.video) {
|
|
1415
|
+
const buf = await resolveMediaBuffer(c.video);
|
|
1416
|
+
const up = await uploadWaMedia(buf, "video", "/mms/video");
|
|
1417
|
+
const videoObj = {
|
|
1418
|
+
url: up.url,
|
|
1419
|
+
directPath: up.directPath,
|
|
1420
|
+
mimetype: String(c.mimetype ?? "video/mp4"),
|
|
1421
|
+
caption: c.caption ? String(c.caption) : undefined,
|
|
1422
|
+
gifPlayback: Boolean(c.gifPlayback),
|
|
1423
|
+
fileSha256: up.fileSha256,
|
|
1424
|
+
fileEncSha256: up.fileEncSha256,
|
|
1425
|
+
fileLength: up.fileLength,
|
|
1426
|
+
mediaKey: up.mediaKey,
|
|
1427
|
+
mediaKeyTimestamp: Math.floor(Date.now() / 1000),
|
|
1428
|
+
};
|
|
1429
|
+
return c.ptv ? { ptvMessage: videoObj } : { videoMessage: videoObj };
|
|
1430
|
+
}
|
|
1431
|
+
if (c?.audio) {
|
|
1432
|
+
const buf = await resolveMediaBuffer(c.audio);
|
|
1433
|
+
const isPtt = Boolean(c.ptt);
|
|
1434
|
+
const needWaveform = isPtt && !(c.waveform instanceof Uint8Array);
|
|
1435
|
+
const needSeconds = typeof c.seconds !== "number";
|
|
1436
|
+
const audioMeta = needWaveform || needSeconds
|
|
1437
|
+
? await new Promise((resolve) => {
|
|
1438
|
+
try {
|
|
1439
|
+
const proc = spawn("ffmpeg", [
|
|
1440
|
+
"-hide_banner",
|
|
1441
|
+
"-loglevel",
|
|
1442
|
+
"error",
|
|
1443
|
+
"-i",
|
|
1444
|
+
"pipe:0",
|
|
1445
|
+
"-ac",
|
|
1446
|
+
"1",
|
|
1447
|
+
"-ar",
|
|
1448
|
+
"8000",
|
|
1449
|
+
"-f",
|
|
1450
|
+
"f32le",
|
|
1451
|
+
"pipe:1",
|
|
1452
|
+
]);
|
|
1453
|
+
const chunks = [];
|
|
1454
|
+
proc.stdout.on("data", (d) => chunks.push(d));
|
|
1455
|
+
proc.on("error", () => resolve({}));
|
|
1456
|
+
proc.on("close", (code) => {
|
|
1457
|
+
if (code !== 0 || chunks.length === 0)
|
|
1458
|
+
return resolve({});
|
|
1459
|
+
const pcm = Buffer.concat(chunks);
|
|
1460
|
+
const floats = new Float32Array(pcm.buffer, pcm.byteOffset, Math.floor(pcm.byteLength / 4));
|
|
1461
|
+
if (floats.length === 0)
|
|
1462
|
+
return resolve({});
|
|
1463
|
+
const seconds = Math.max(1, Math.round(floats.length / 8000));
|
|
1464
|
+
let waveform;
|
|
1465
|
+
if (needWaveform) {
|
|
1466
|
+
const samples = 128;
|
|
1467
|
+
const blockSize = Math.max(1, Math.floor(floats.length / samples));
|
|
1468
|
+
const filtered = [];
|
|
1469
|
+
for (let i = 0; i < samples; i++) {
|
|
1470
|
+
const start = i * blockSize;
|
|
1471
|
+
const end = Math.min(floats.length, start + blockSize);
|
|
1472
|
+
let sum = 0;
|
|
1473
|
+
for (let j = start; j < end; j++)
|
|
1474
|
+
sum += Math.abs(floats[j]);
|
|
1475
|
+
filtered.push(end > start ? sum / (end - start) : 0);
|
|
1476
|
+
}
|
|
1477
|
+
const max = Math.max(...filtered);
|
|
1478
|
+
const mult = max > 0 ? 100 / max : 0;
|
|
1479
|
+
waveform = Uint8Array.from(filtered.map((n) => Math.min(100, Math.floor(n * mult))));
|
|
1480
|
+
}
|
|
1481
|
+
resolve({ seconds, waveform });
|
|
1482
|
+
});
|
|
1483
|
+
proc.stdin.end(buf);
|
|
1484
|
+
}
|
|
1485
|
+
catch {
|
|
1486
|
+
resolve({});
|
|
1487
|
+
}
|
|
1488
|
+
})
|
|
1489
|
+
: {};
|
|
1490
|
+
const mType = isPtt ? "ptt" : "audio";
|
|
1491
|
+
const up = await uploadWaMedia(buf, mType, "/mms/audio");
|
|
1492
|
+
return {
|
|
1493
|
+
audioMessage: {
|
|
1494
|
+
url: up.url,
|
|
1495
|
+
directPath: up.directPath,
|
|
1496
|
+
mimetype: String(c.mimetype ?? (isPtt ? "audio/ogg; codecs=opus" : "audio/mpeg")),
|
|
1497
|
+
ptt: isPtt,
|
|
1498
|
+
seconds: typeof c.seconds === "number" ? c.seconds : audioMeta.seconds,
|
|
1499
|
+
waveform: c.waveform instanceof Uint8Array ? c.waveform : audioMeta.waveform,
|
|
1500
|
+
fileSha256: up.fileSha256,
|
|
1501
|
+
fileEncSha256: up.fileEncSha256,
|
|
1502
|
+
fileLength: up.fileLength,
|
|
1503
|
+
mediaKey: up.mediaKey,
|
|
1504
|
+
mediaKeyTimestamp: Math.floor(Date.now() / 1000),
|
|
1505
|
+
},
|
|
1506
|
+
};
|
|
1507
|
+
}
|
|
1508
|
+
if (c?.document) {
|
|
1509
|
+
const buf = await resolveMediaBuffer(c.document);
|
|
1510
|
+
const up = await uploadWaMedia(buf, "document", "/mms/document");
|
|
1511
|
+
return {
|
|
1512
|
+
documentMessage: {
|
|
1513
|
+
url: up.url,
|
|
1514
|
+
directPath: up.directPath,
|
|
1515
|
+
mimetype: String(c.mimetype ?? "application/octet-stream"),
|
|
1516
|
+
fileName: String(c.fileName ?? "file"),
|
|
1517
|
+
title: c.title ? String(c.title) : undefined,
|
|
1518
|
+
caption: c.caption ? String(c.caption) : undefined,
|
|
1519
|
+
fileSha256: up.fileSha256,
|
|
1520
|
+
fileEncSha256: up.fileEncSha256,
|
|
1521
|
+
fileLength: up.fileLength,
|
|
1522
|
+
mediaKey: up.mediaKey,
|
|
1523
|
+
mediaKeyTimestamp: Math.floor(Date.now() / 1000),
|
|
1524
|
+
},
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
if (c?.sticker) {
|
|
1528
|
+
const buf = await resolveMediaBuffer(c.sticker);
|
|
1529
|
+
const up = await uploadWaMedia(buf, "sticker", "/mms/image");
|
|
1530
|
+
return {
|
|
1531
|
+
stickerMessage: {
|
|
1532
|
+
url: up.url,
|
|
1533
|
+
directPath: up.directPath,
|
|
1534
|
+
mimetype: String(c.mimetype ?? "image/webp"),
|
|
1535
|
+
fileSha256: up.fileSha256,
|
|
1536
|
+
fileEncSha256: up.fileEncSha256,
|
|
1537
|
+
fileLength: up.fileLength,
|
|
1538
|
+
mediaKey: up.mediaKey,
|
|
1539
|
+
mediaKeyTimestamp: Math.floor(Date.now() / 1000),
|
|
1540
|
+
},
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
const text = typeof c?.text === "string" ? c.text : typeof c?.caption === "string" ? c.caption : "";
|
|
1544
|
+
return { conversation: text };
|
|
1545
|
+
};
|
|
1546
|
+
const waMsg = await buildOutgoingWAMessage(content);
|
|
1547
|
+
const quotedRaw = options?.quoted;
|
|
1548
|
+
const mentionedJid = Array.isArray(content?.mentions)
|
|
1549
|
+
? content.mentions
|
|
1550
|
+
: Array.isArray(content?.contextInfo?.mentionedJid)
|
|
1551
|
+
? content.contextInfo.mentionedJid
|
|
1552
|
+
: undefined;
|
|
1553
|
+
const rawCtx = content?.contextInfo && typeof content.contextInfo === "object" ? content.contextInfo : undefined;
|
|
1554
|
+
if (quotedRaw?.key?.id || mentionedJid?.length || rawCtx) {
|
|
1555
|
+
const ctx = {
|
|
1556
|
+
...(rawCtx || {}),
|
|
1557
|
+
...(quotedRaw?.key?.id
|
|
1558
|
+
? {
|
|
1559
|
+
stanzaId: quotedRaw.key.id,
|
|
1560
|
+
participant: quotedRaw.key.participant || quotedRaw.key.remoteJid || jid,
|
|
1561
|
+
quotedMessage: quotedRaw.message,
|
|
1562
|
+
...(quotedRaw.key.remoteJid && quotedRaw.key.remoteJid !== jid
|
|
1563
|
+
? { remoteJid: quotedRaw.key.remoteJid }
|
|
1564
|
+
: {}),
|
|
1565
|
+
}
|
|
1566
|
+
: {}),
|
|
1567
|
+
...(mentionedJid?.length ? { mentionedJid } : {}),
|
|
1568
|
+
};
|
|
1569
|
+
if (waMsg.conversation !== undefined && !waMsg.extendedTextMessage) {
|
|
1570
|
+
waMsg.extendedTextMessage = { text: waMsg.conversation, contextInfo: ctx };
|
|
1571
|
+
delete waMsg.conversation;
|
|
1572
|
+
}
|
|
1573
|
+
else if (waMsg.extendedTextMessage) {
|
|
1574
|
+
waMsg.extendedTextMessage.contextInfo = { ...waMsg.extendedTextMessage.contextInfo, ...ctx };
|
|
1575
|
+
}
|
|
1576
|
+
else if (waMsg.interactiveMessage) {
|
|
1577
|
+
waMsg.interactiveMessage.contextInfo = { ...waMsg.interactiveMessage.contextInfo, ...ctx };
|
|
1578
|
+
}
|
|
1579
|
+
else {
|
|
1580
|
+
for (const k of [
|
|
1581
|
+
"imageMessage",
|
|
1582
|
+
"videoMessage",
|
|
1583
|
+
"ptvMessage",
|
|
1584
|
+
"audioMessage",
|
|
1585
|
+
"documentMessage",
|
|
1586
|
+
"stickerMessage",
|
|
1587
|
+
"locationMessage",
|
|
1588
|
+
"contactMessage",
|
|
1589
|
+
"contactsArrayMessage",
|
|
1590
|
+
"pollCreationMessage",
|
|
1591
|
+
"pollCreationMessageV3",
|
|
1592
|
+
]) {
|
|
1593
|
+
if (waMsg[k]) {
|
|
1594
|
+
waMsg[k].contextInfo = { ...waMsg[k].contextInfo, ...ctx };
|
|
1595
|
+
break;
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
const isLegacyBtn = Boolean(waMsg.buttonsMessage);
|
|
1601
|
+
const isStickerPack = Boolean(waMsg.stickerPackMessage);
|
|
1602
|
+
const encMediatype = isLegacyBtn
|
|
1603
|
+
? "button"
|
|
1604
|
+
: isStickerPack
|
|
1605
|
+
? "sticker_pack"
|
|
1606
|
+
: waMsg.imageMessage
|
|
1607
|
+
? "image"
|
|
1608
|
+
: waMsg.videoMessage
|
|
1609
|
+
? waMsg.videoMessage.gifPlayback
|
|
1610
|
+
? "gif"
|
|
1611
|
+
: "video"
|
|
1612
|
+
: waMsg.ptvMessage
|
|
1613
|
+
? "ptv"
|
|
1614
|
+
: waMsg.audioMessage
|
|
1615
|
+
? waMsg.audioMessage.ptt
|
|
1616
|
+
? "ptt"
|
|
1617
|
+
: "audio"
|
|
1618
|
+
: waMsg.documentMessage
|
|
1619
|
+
? "document"
|
|
1620
|
+
: waMsg.stickerMessage
|
|
1621
|
+
? "sticker"
|
|
1622
|
+
: undefined;
|
|
1623
|
+
const stanzaType = encMediatype ? "media" : "text";
|
|
1624
|
+
const deleteEditAttr = content?.delete && typeof content.delete === "object"
|
|
1625
|
+
? jid.endsWith("@g.us") && !content.delete.fromMe
|
|
1626
|
+
? "8"
|
|
1627
|
+
: "7"
|
|
1628
|
+
: content?.edit && typeof content.edit === "object"
|
|
1629
|
+
? "1"
|
|
1630
|
+
: undefined;
|
|
1631
|
+
const isNativeFlow = Boolean(waMsg.interactiveMessage?.nativeFlowMessage || waMsg.interactiveMessage?.carouselMessage);
|
|
1632
|
+
const buildButtonAddonNodes = () => {
|
|
1633
|
+
if (!isNativeFlow && !isLegacyBtn)
|
|
1634
|
+
return [];
|
|
1635
|
+
const firstBtn = waMsg.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name;
|
|
1636
|
+
const nfName = firstBtn === "payment_info"
|
|
1637
|
+
? "payment_info"
|
|
1638
|
+
: firstBtn === "review_and_pay"
|
|
1639
|
+
? "order_details"
|
|
1640
|
+
: firstBtn === "form_message"
|
|
1641
|
+
? "form_message"
|
|
1642
|
+
: "mixed";
|
|
1643
|
+
return [
|
|
1644
|
+
{
|
|
1645
|
+
tag: "biz",
|
|
1646
|
+
attrs: {},
|
|
1647
|
+
content: [
|
|
1648
|
+
{
|
|
1649
|
+
tag: "interactive",
|
|
1650
|
+
attrs: { type: "native_flow", v: "1" },
|
|
1651
|
+
content: [
|
|
1652
|
+
{
|
|
1653
|
+
tag: "native_flow",
|
|
1654
|
+
attrs: nfName === "mixed" ? { v: "9", name: "mixed" } : { name: nfName },
|
|
1655
|
+
},
|
|
1656
|
+
],
|
|
1657
|
+
},
|
|
1658
|
+
],
|
|
1659
|
+
},
|
|
1660
|
+
];
|
|
1661
|
+
};
|
|
1662
|
+
const text = typeof waMsg.conversation === "string"
|
|
1663
|
+
? waMsg.conversation
|
|
1664
|
+
: waMsg.interactiveMessage?.body?.text ?? waMsg.buttonsMessage?.contentText ?? "";
|
|
1665
|
+
const padded = writeRandomPadMax16(proto.Message.encode(waMsg));
|
|
1666
|
+
const meJid = authCreds.me?.id ?? sock.user?.id ?? "0@s.whatsapp.net";
|
|
1667
|
+
const msgId = generateMessageIDV2(meJid);
|
|
1668
|
+
sentMessages.set(msgId, { jid, message: waMsg });
|
|
1669
|
+
setTimeout(() => sentMessages.delete(msgId), 5 * 60_000).unref();
|
|
1670
|
+
const getDevices = async (userJids) => {
|
|
1671
|
+
try {
|
|
1672
|
+
const res = await sendQuery({
|
|
1673
|
+
tag: "iq",
|
|
1674
|
+
attrs: { to: "s.whatsapp.net", type: "get", id: nextTag(), xmlns: "usync" },
|
|
1675
|
+
content: [
|
|
1676
|
+
{
|
|
1677
|
+
tag: "usync",
|
|
1678
|
+
attrs: { sid: nextTag(), mode: "query", last: "true", index: "0", context: "message" },
|
|
1679
|
+
content: [
|
|
1680
|
+
{ tag: "query", attrs: {}, content: [{ tag: "devices", attrs: { version: "2" } }] },
|
|
1681
|
+
{
|
|
1682
|
+
tag: "list",
|
|
1683
|
+
attrs: {},
|
|
1684
|
+
content: userJids.map((u) => ({ tag: "user", attrs: { jid: jidNormalizedUser(u) } })),
|
|
1685
|
+
},
|
|
1686
|
+
],
|
|
1687
|
+
},
|
|
1688
|
+
],
|
|
1689
|
+
});
|
|
1690
|
+
const out = [];
|
|
1691
|
+
const usync = Array.isArray(res.content) ? res.content.find((c) => c.tag === "usync") : undefined;
|
|
1692
|
+
const list = Array.isArray(usync?.content) ? usync.content.find((c) => c.tag === "list") : undefined;
|
|
1693
|
+
if (Array.isArray(list?.content)) {
|
|
1694
|
+
for (const u of list.content) {
|
|
1695
|
+
const uJid = u.attrs?.jid;
|
|
1696
|
+
const devs = Array.isArray(u.content) ? u.content.find((c) => c.tag === "devices") : undefined;
|
|
1697
|
+
const devList = Array.isArray(devs?.content) ? devs.content.find((c) => c.tag === "device-list") : undefined;
|
|
1698
|
+
if (uJid && Array.isArray(devList?.content)) {
|
|
1699
|
+
const dec = jidDecode(uJid);
|
|
1700
|
+
for (const d of devList.content) {
|
|
1701
|
+
if (d.tag === "device" && d.attrs?.id !== undefined && dec) {
|
|
1702
|
+
const devId = Number(d.attrs.id);
|
|
1703
|
+
out.push(devId === 0 ? `${dec.user}@${dec.server}` : `${dec.user}:${devId}@${dec.server}`);
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
if (out.length > 0)
|
|
1710
|
+
return out;
|
|
1711
|
+
}
|
|
1712
|
+
catch {
|
|
1713
|
+
}
|
|
1714
|
+
return userJids.map((u) => jidNormalizedUser(u));
|
|
1715
|
+
};
|
|
1716
|
+
const ensureSessions = async (devJids) => {
|
|
1717
|
+
const missing = [];
|
|
1718
|
+
for (const dj of devJids) {
|
|
1719
|
+
if (!(await signalMgr.hasSession(jidToSignalAddress(dj)))) {
|
|
1720
|
+
missing.push(dj);
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
if (missing.length === 0)
|
|
1724
|
+
return;
|
|
1725
|
+
const res = await sendQuery({
|
|
1726
|
+
tag: "iq",
|
|
1727
|
+
attrs: { to: "s.whatsapp.net", type: "get", id: nextTag(), xmlns: "encrypt" },
|
|
1728
|
+
content: [
|
|
1729
|
+
{
|
|
1730
|
+
tag: "key",
|
|
1731
|
+
attrs: {},
|
|
1732
|
+
content: missing.map((dj) => ({ tag: "user", attrs: { jid: dj } })),
|
|
1733
|
+
},
|
|
1734
|
+
],
|
|
1735
|
+
});
|
|
1736
|
+
const list = Array.isArray(res.content) ? res.content.find((c) => c.tag === "list") : undefined;
|
|
1737
|
+
if (!Array.isArray(list?.content))
|
|
1738
|
+
return;
|
|
1739
|
+
for (const u of list.content) {
|
|
1740
|
+
if (u.tag !== "user" || !u.attrs?.jid || !Array.isArray(u.content))
|
|
1741
|
+
continue;
|
|
1742
|
+
const regNode = u.content.find((c) => c.tag === "registration");
|
|
1743
|
+
const identNode = u.content.find((c) => c.tag === "identity");
|
|
1744
|
+
const skeyNode = u.content.find((c) => c.tag === "skey");
|
|
1745
|
+
const keyNode = u.content.find((c) => c.tag === "key");
|
|
1746
|
+
if (!(regNode?.content instanceof Uint8Array) || !(identNode?.content instanceof Uint8Array) || !Array.isArray(skeyNode?.content)) {
|
|
1747
|
+
continue;
|
|
1748
|
+
}
|
|
1749
|
+
const skeyIdBuf = skeyNode.content.find((c) => c.tag === "id")?.content;
|
|
1750
|
+
const skeyValBuf = skeyNode.content.find((c) => c.tag === "value")?.content;
|
|
1751
|
+
if (!(skeyIdBuf instanceof Uint8Array) || !(skeyValBuf instanceof Uint8Array))
|
|
1752
|
+
continue;
|
|
1753
|
+
const regId = Buffer.from(regNode.content).readUInt32BE(0);
|
|
1754
|
+
const skeyId = Buffer.from(skeyIdBuf).readUIntBE(0, skeyIdBuf.length);
|
|
1755
|
+
let preKey;
|
|
1756
|
+
if (Array.isArray(keyNode?.content)) {
|
|
1757
|
+
const pkIdBuf = keyNode.content.find((c) => c.tag === "id")?.content;
|
|
1758
|
+
const pkValBuf = keyNode.content.find((c) => c.tag === "value")?.content;
|
|
1759
|
+
if (pkIdBuf instanceof Uint8Array && pkValBuf instanceof Uint8Array) {
|
|
1760
|
+
preKey = {
|
|
1761
|
+
keyId: Buffer.from(pkIdBuf).readUIntBE(0, pkIdBuf.length),
|
|
1762
|
+
publicKey: pkValBuf,
|
|
1763
|
+
};
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
await signalMgr.initOutgoingSession(jidToSignalAddress(u.attrs.jid), {
|
|
1767
|
+
registrationId: regId,
|
|
1768
|
+
identityKey: identNode.content,
|
|
1769
|
+
signedPreKey: { keyId: skeyId, publicKey: skeyValBuf },
|
|
1770
|
+
preKey,
|
|
1771
|
+
});
|
|
1772
|
+
}
|
|
1773
|
+
};
|
|
1774
|
+
const buildDeviceIdentityNode = () => {
|
|
1775
|
+
if (!authCreds.account)
|
|
1776
|
+
return [];
|
|
1777
|
+
const acc = reviveBuffers(authCreds.account);
|
|
1778
|
+
const enc = proto.ADVSignedDeviceIdentity.encode({
|
|
1779
|
+
details: acc.details,
|
|
1780
|
+
accountSignatureKey: acc.accountSignatureKey,
|
|
1781
|
+
accountSignature: acc.accountSignature,
|
|
1782
|
+
deviceSignature: acc.deviceSignature,
|
|
1783
|
+
});
|
|
1784
|
+
return [{ tag: "device-identity", attrs: {}, content: enc }];
|
|
1785
|
+
};
|
|
1786
|
+
const computePhash = (devs) => {
|
|
1787
|
+
const sorted = [...devs].sort();
|
|
1788
|
+
const hash = createHash("sha256").update(sorted.join("")).digest("base64");
|
|
1789
|
+
return "2:" + hash.slice(0, 6);
|
|
1790
|
+
};
|
|
1791
|
+
if (jid.endsWith("@newsletter")) {
|
|
1792
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
1793
|
+
tag: "message",
|
|
1794
|
+
attrs: {
|
|
1795
|
+
id: msgId,
|
|
1796
|
+
to: jid,
|
|
1797
|
+
type: stanzaType,
|
|
1798
|
+
...(deleteEditAttr ? { edit: deleteEditAttr } : {}),
|
|
1799
|
+
},
|
|
1800
|
+
content: [
|
|
1801
|
+
{
|
|
1802
|
+
tag: "plaintext",
|
|
1803
|
+
attrs: encMediatype ? { mediatype: encMediatype } : {},
|
|
1804
|
+
content: proto.Message.encode(waMsg),
|
|
1805
|
+
},
|
|
1806
|
+
],
|
|
1807
|
+
}));
|
|
1808
|
+
}
|
|
1809
|
+
else if (jid.endsWith("@g.us")) {
|
|
1810
|
+
const meta = await sock.groupMetadata(jid);
|
|
1811
|
+
const participants = (meta.participants ?? [])
|
|
1812
|
+
.map((p) => (meta.addressingMode === "lid" && p.lid ? p.lid : p.id))
|
|
1813
|
+
.filter(Boolean);
|
|
1814
|
+
const meLid = authCreds.me?.lid ?? sock.user?.lid;
|
|
1815
|
+
const rawDevices = await getDevices(participants.length ? participants : [meJid]);
|
|
1816
|
+
const devices = rawDevices.filter((d) => d !== meJid && (!meLid || d !== meLid));
|
|
1817
|
+
const addrMode = meta.addressingMode || (participants.some((p) => p.endsWith("@lid")) ? "lid" : "pn");
|
|
1818
|
+
const groupSender = addrMode === "lid" && meLid ? meLid : meJid;
|
|
1819
|
+
const groupKey = `${jid}:${jidToSignalAddress(groupSender)}`;
|
|
1820
|
+
const { distributionBytes } = await signalMgr.getOrCreateGroupDistribution(groupKey);
|
|
1821
|
+
const skmsgBytes = await signalMgr.encryptGroupMessage(groupKey, padded);
|
|
1822
|
+
let sentTo = senderKeyMemory.get(jid);
|
|
1823
|
+
if (!sentTo) {
|
|
1824
|
+
const savedMem = (await getKey("sender-key-memory", jid));
|
|
1825
|
+
sentTo = new Set(Array.isArray(savedMem) ? savedMem : []);
|
|
1826
|
+
senderKeyMemory.set(jid, sentTo);
|
|
1827
|
+
}
|
|
1828
|
+
const pendingDevices = devices.filter((d) => !sentTo.has(d));
|
|
1829
|
+
const participantNodes = [];
|
|
1830
|
+
let hasPkmsg = false;
|
|
1831
|
+
if (pendingDevices.length > 0) {
|
|
1832
|
+
await ensureSessions(pendingDevices);
|
|
1833
|
+
const distPadded = writeRandomPadMax16(proto.Message.encode({
|
|
1834
|
+
senderKeyDistributionMessage: {
|
|
1835
|
+
groupId: jid,
|
|
1836
|
+
axolotlSenderKeyDistributionMessage: distributionBytes,
|
|
1837
|
+
},
|
|
1838
|
+
}));
|
|
1839
|
+
for (const dev of pendingDevices) {
|
|
1840
|
+
try {
|
|
1841
|
+
const enc = await signalMgr.encryptMessage(jidToSignalAddress(dev), distPadded);
|
|
1842
|
+
if (enc.type === "pkmsg")
|
|
1843
|
+
hasPkmsg = true;
|
|
1844
|
+
sentTo.add(dev);
|
|
1845
|
+
participantNodes.push({
|
|
1846
|
+
tag: "to",
|
|
1847
|
+
attrs: { jid: dev },
|
|
1848
|
+
content: [{ tag: "enc", attrs: { v: "2", type: enc.type }, content: enc.body }],
|
|
1849
|
+
});
|
|
1850
|
+
}
|
|
1851
|
+
catch {
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
await setKey("sender-key-memory", jid, Array.from(sentTo));
|
|
1855
|
+
}
|
|
1856
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
1857
|
+
tag: "message",
|
|
1858
|
+
attrs: {
|
|
1859
|
+
id: msgId,
|
|
1860
|
+
to: jid,
|
|
1861
|
+
type: stanzaType,
|
|
1862
|
+
addressing_mode: addrMode,
|
|
1863
|
+
...(deleteEditAttr ? { edit: deleteEditAttr } : {}),
|
|
1864
|
+
},
|
|
1865
|
+
content: [
|
|
1866
|
+
...(participantNodes.length ? [{ tag: "participants", attrs: {}, content: participantNodes }] : []),
|
|
1867
|
+
{
|
|
1868
|
+
tag: "enc",
|
|
1869
|
+
attrs: { v: "2", type: "skmsg", ...(encMediatype ? { mediatype: encMediatype } : {}) },
|
|
1870
|
+
content: skmsgBytes,
|
|
1871
|
+
},
|
|
1872
|
+
...(hasPkmsg ? buildDeviceIdentityNode() : []),
|
|
1873
|
+
...buildButtonAddonNodes(),
|
|
1874
|
+
],
|
|
1875
|
+
}));
|
|
1876
|
+
}
|
|
1877
|
+
else {
|
|
1878
|
+
const targetNorm = jidNormalizedUser(jid);
|
|
1879
|
+
const meLid = authCreds.me?.lid ?? sock.user?.lid;
|
|
1880
|
+
const isLid = targetNorm.endsWith("@lid");
|
|
1881
|
+
const senderIdentity = isLid && meLid ? jidNormalizedUser(meLid) : jidNormalizedUser(meJid);
|
|
1882
|
+
const rawDevices = await getDevices(senderIdentity === targetNorm ? [targetNorm] : [senderIdentity, targetNorm]);
|
|
1883
|
+
const devices = rawDevices.filter((d) => d !== meJid && (!meLid || d !== meLid));
|
|
1884
|
+
await ensureSessions(devices);
|
|
1885
|
+
const meUser = jidDecode(meJid)?.user;
|
|
1886
|
+
const meLidUser = meLid ? jidDecode(meLid)?.user : undefined;
|
|
1887
|
+
const dsmPadded = writeRandomPadMax16(proto.Message.encode({
|
|
1888
|
+
deviceSentMessage: {
|
|
1889
|
+
destinationJid: targetNorm,
|
|
1890
|
+
message: waMsg,
|
|
1891
|
+
},
|
|
1892
|
+
}));
|
|
1893
|
+
const participantNodes = [];
|
|
1894
|
+
let hasPkmsg = false;
|
|
1895
|
+
for (const dev of devices) {
|
|
1896
|
+
const devUser = jidDecode(dev)?.user;
|
|
1897
|
+
const isMeDev = Boolean((meUser && devUser === meUser) || (meLidUser && devUser === meLidUser));
|
|
1898
|
+
const enc = await signalMgr.encryptMessage(jidToSignalAddress(dev), isMeDev ? dsmPadded : padded);
|
|
1899
|
+
if (enc.type === "pkmsg")
|
|
1900
|
+
hasPkmsg = true;
|
|
1901
|
+
participantNodes.push({
|
|
1902
|
+
tag: "to",
|
|
1903
|
+
attrs: { jid: dev },
|
|
1904
|
+
content: [
|
|
1905
|
+
{
|
|
1906
|
+
tag: "enc",
|
|
1907
|
+
attrs: { v: "2", type: enc.type, ...(encMediatype ? { mediatype: encMediatype } : {}) },
|
|
1908
|
+
content: enc.body,
|
|
1909
|
+
},
|
|
1910
|
+
],
|
|
1911
|
+
});
|
|
1912
|
+
}
|
|
1913
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
1914
|
+
tag: "message",
|
|
1915
|
+
attrs: {
|
|
1916
|
+
id: msgId,
|
|
1917
|
+
to: targetNorm,
|
|
1918
|
+
type: stanzaType,
|
|
1919
|
+
...(deleteEditAttr ? { edit: deleteEditAttr } : {}),
|
|
1920
|
+
},
|
|
1921
|
+
content: [
|
|
1922
|
+
{ tag: "participants", attrs: {}, content: participantNodes },
|
|
1923
|
+
...(hasPkmsg ? buildDeviceIdentityNode() : []),
|
|
1924
|
+
...buildButtonAddonNodes(),
|
|
1925
|
+
],
|
|
1926
|
+
}));
|
|
1927
|
+
}
|
|
1928
|
+
await client.sendMessage(jidNormalizedUser(jid), { text });
|
|
1929
|
+
return { key: { remoteJid: jid, fromMe: true, id: msgId }, message: waMsg };
|
|
1930
|
+
},
|
|
1931
|
+
async sendNode(node) {
|
|
1932
|
+
transport.sendEncrypted(encodeWABinaryNode(node));
|
|
1933
|
+
},
|
|
1934
|
+
async relayMessage(jid, message, options) {
|
|
1935
|
+
const res = await sock.sendMessage(jid, { rawMessage: message }, options);
|
|
1936
|
+
return res.key.id;
|
|
1937
|
+
},
|
|
1938
|
+
async sendPresenceUpdate(presence, toJid) {
|
|
1939
|
+
if (toJid && (presence === "composing" || presence === "recording" || presence === "paused")) {
|
|
1940
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
1941
|
+
tag: "chatstate",
|
|
1942
|
+
attrs: { to: toJid },
|
|
1943
|
+
content: [
|
|
1944
|
+
presence === "paused"
|
|
1945
|
+
? { tag: "paused", attrs: {} }
|
|
1946
|
+
: { tag: "composing", attrs: presence === "recording" ? { media: "audio" } : {} },
|
|
1947
|
+
],
|
|
1948
|
+
}));
|
|
1949
|
+
return;
|
|
1950
|
+
}
|
|
1951
|
+
if (presence === "available" || presence === "unavailable") {
|
|
1952
|
+
await client.updatePresence(presence);
|
|
1953
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
1954
|
+
tag: "presence",
|
|
1955
|
+
attrs: { type: presence, ...(authCreds.me?.name ? { name: authCreds.me.name } : {}) },
|
|
1956
|
+
}));
|
|
1957
|
+
}
|
|
1958
|
+
},
|
|
1959
|
+
async readMessages(keys) {
|
|
1960
|
+
if (!Array.isArray(keys))
|
|
1961
|
+
return;
|
|
1962
|
+
const t = String(Math.floor(Date.now() / 1000));
|
|
1963
|
+
for (const k of keys) {
|
|
1964
|
+
if (!k?.remoteJid || !k?.id || k.fromMe)
|
|
1965
|
+
continue;
|
|
1966
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
1967
|
+
tag: "receipt",
|
|
1968
|
+
attrs: {
|
|
1969
|
+
type: "read",
|
|
1970
|
+
id: k.id,
|
|
1971
|
+
to: k.remoteJid,
|
|
1972
|
+
t,
|
|
1973
|
+
...(k.participant ? { participant: k.participant } : {}),
|
|
1974
|
+
},
|
|
1975
|
+
}));
|
|
1976
|
+
}
|
|
1977
|
+
},
|
|
1978
|
+
async refreshMediaConn() {
|
|
1979
|
+
const res = await sendQuery({
|
|
1980
|
+
tag: "iq",
|
|
1981
|
+
attrs: { to: "s.whatsapp.net", type: "set", id: nextTag(), xmlns: "w:m" },
|
|
1982
|
+
content: [{ tag: "media_conn", attrs: {} }],
|
|
1983
|
+
});
|
|
1984
|
+
const mc = Array.isArray(res.content) ? res.content.find((c) => c.tag === "media_conn") : undefined;
|
|
1985
|
+
const hosts = Array.isArray(mc?.content)
|
|
1986
|
+
? mc.content.filter((h) => h.tag === "host").map((h) => ({ hostname: h.attrs?.hostname ?? "mmg.whatsapp.net" }))
|
|
1987
|
+
: [{ hostname: "mmg.whatsapp.net" }];
|
|
1988
|
+
return { auth: mc?.attrs?.auth ?? "", hosts };
|
|
1989
|
+
},
|
|
1990
|
+
async waUploadToServer(stream, opts = {}) {
|
|
1991
|
+
const buf = stream instanceof Uint8Array ? stream : await toBuffer(stream);
|
|
1992
|
+
const mType = opts.mediaType ?? "document";
|
|
1993
|
+
const pathMap = {
|
|
1994
|
+
image: "/mms/image",
|
|
1995
|
+
video: "/mms/video",
|
|
1996
|
+
audio: "/mms/audio",
|
|
1997
|
+
ptt: "/mms/audio",
|
|
1998
|
+
sticker: "/mms/image",
|
|
1999
|
+
document: "/mms/document",
|
|
2000
|
+
};
|
|
2001
|
+
const enc = encryptWaMedia(buf, mType);
|
|
2002
|
+
const mc = await sock.refreshMediaConn();
|
|
2003
|
+
const host = mc.hosts[0]?.hostname ?? "mmg.whatsapp.net";
|
|
2004
|
+
const token = Buffer.from(enc.fileEncSha256).toString("base64url");
|
|
2005
|
+
const upUrl = `https://${host}${pathMap[mType] ?? "/mms/document"}/${token}?auth=${encodeURIComponent(mc.auth)}&token=${token}`;
|
|
2006
|
+
const res = await fetch(upUrl, {
|
|
2007
|
+
method: "POST",
|
|
2008
|
+
headers: { "Content-Type": "application/octet-stream", Origin: "https://web.whatsapp.com" },
|
|
2009
|
+
body: new Uint8Array(enc.encData),
|
|
2010
|
+
});
|
|
2011
|
+
if (!res.ok)
|
|
2012
|
+
throw new Error(`Media upload failed (${res.status})`);
|
|
2013
|
+
const json = (await res.json());
|
|
2014
|
+
return { mediaUrl: json.url ?? "", directPath: json.direct_path ?? "", meta_hmac: "" };
|
|
2015
|
+
},
|
|
2016
|
+
async updateMediaMessage(msg) {
|
|
2017
|
+
const inner = normalizeMessageContent(msg?.message ?? msg);
|
|
2018
|
+
const mediaKeyName = Object.keys(inner || {}).find((k) => k.endsWith("Message"));
|
|
2019
|
+
const media = mediaKeyName ? inner[mediaKeyName] : undefined;
|
|
2020
|
+
const msgId = msg?.key?.id;
|
|
2021
|
+
const remoteJid = msg?.key?.remoteJid;
|
|
2022
|
+
if (!media?.mediaKey || !msgId || !remoteJid)
|
|
2023
|
+
return msg;
|
|
2024
|
+
const mediaKeyBuf = Buffer.from(media.mediaKey);
|
|
2025
|
+
const prk = createHmac("sha256", Buffer.alloc(32)).update(mediaKeyBuf).digest();
|
|
2026
|
+
const info = Buffer.from("WhatsApp Media Retry Notification");
|
|
2027
|
+
const retryKey = createHmac("sha256", prk).update(Buffer.concat([info, Buffer.from([1])])).digest();
|
|
2028
|
+
const iv = randomBytes(12);
|
|
2029
|
+
const aad = Buffer.from(msgId, "utf8");
|
|
2030
|
+
// ServerErrorReceipt { stanzaId: field 1 }
|
|
2031
|
+
const receiptPlain = Buffer.concat([Buffer.from([0x0a, aad.length]), aad]);
|
|
2032
|
+
const gcm = createCipheriv("aes-256-gcm", retryKey, iv);
|
|
2033
|
+
gcm.setAAD(aad);
|
|
2034
|
+
const ciphertext = Buffer.concat([gcm.update(receiptPlain), gcm.final(), gcm.getAuthTag()]);
|
|
2035
|
+
const waitNode = new Promise((resolve) => {
|
|
2036
|
+
pendingMediaRetries.set(msgId, { resolve });
|
|
2037
|
+
setTimeout(() => {
|
|
2038
|
+
pendingMediaRetries.delete(msgId);
|
|
2039
|
+
resolve({ tag: "notification", attrs: {}, content: [] });
|
|
2040
|
+
}, 10_000).unref();
|
|
2041
|
+
});
|
|
2042
|
+
transport.sendEncrypted(encodeWABinaryNode({
|
|
2043
|
+
tag: "receipt",
|
|
2044
|
+
attrs: {
|
|
2045
|
+
id: msgId,
|
|
2046
|
+
to: remoteJid,
|
|
2047
|
+
type: "server-error",
|
|
2048
|
+
...(msg.key?.participant ? { participant: msg.key.participant } : {}),
|
|
2049
|
+
},
|
|
2050
|
+
content: [
|
|
2051
|
+
{
|
|
2052
|
+
tag: "encrypt",
|
|
2053
|
+
attrs: {},
|
|
2054
|
+
content: [
|
|
2055
|
+
{ tag: "enc_p", attrs: {}, content: ciphertext },
|
|
2056
|
+
{ tag: "enc_iv", attrs: {}, content: iv },
|
|
2057
|
+
],
|
|
2058
|
+
},
|
|
2059
|
+
],
|
|
2060
|
+
}));
|
|
2061
|
+
const retryNotif = await waitNode;
|
|
2062
|
+
const encNode = Array.isArray(retryNotif.content) ? retryNotif.content.find((c) => c.tag === "encrypt") : undefined;
|
|
2063
|
+
if (Array.isArray(encNode?.content)) {
|
|
2064
|
+
const encP = encNode.content.find((c) => c.tag === "enc_p")?.content;
|
|
2065
|
+
const encIv = encNode.content.find((c) => c.tag === "enc_iv")?.content;
|
|
2066
|
+
if (encP instanceof Uint8Array && encIv instanceof Uint8Array && encP.length > 16) {
|
|
2067
|
+
const dec = createDecipheriv("aes-256-gcm", retryKey, encIv);
|
|
2068
|
+
dec.setAAD(aad);
|
|
2069
|
+
dec.setAuthTag(Buffer.from(encP.subarray(encP.length - 16)));
|
|
2070
|
+
const plain = Buffer.concat([dec.update(encP.subarray(0, encP.length - 16)), dec.final()]);
|
|
2071
|
+
// MediaRetryNotification { directPath: field 2 }
|
|
2072
|
+
const dpMatch = plain.toString("utf8").match(/\/v\/[^\x00-\x1f]+/);
|
|
2073
|
+
if (dpMatch?.[0]) {
|
|
2074
|
+
media.directPath = dpMatch[0];
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
return msg;
|
|
2079
|
+
},
|
|
2080
|
+
async groupMetadata(jid) {
|
|
2081
|
+
const cached = groupCache.get(jid);
|
|
2082
|
+
if (cached && cached.participants.length > 0)
|
|
2083
|
+
return { id: jid, ...cached };
|
|
2084
|
+
const parseGroupNode = (grp) => {
|
|
2085
|
+
const subject = grp.attrs?.subject ?? "";
|
|
2086
|
+
const addressingMode = grp.attrs?.addressing_mode;
|
|
2087
|
+
const participants = [];
|
|
2088
|
+
if (Array.isArray(grp.content)) {
|
|
2089
|
+
for (const c of grp.content) {
|
|
2090
|
+
if (c.tag === "participant" && c.attrs?.jid) {
|
|
2091
|
+
rememberLidPn(c.attrs.jid, c.attrs.phone_number);
|
|
2092
|
+
const pnId = c.attrs.phone_number ? jidNormalizedUser(c.attrs.phone_number) : resolvePnJid(c.attrs.jid);
|
|
2093
|
+
const lidVal = c.attrs.lid || (c.attrs.jid.endsWith("@lid") ? c.attrs.jid : undefined);
|
|
2094
|
+
participants.push({
|
|
2095
|
+
id: pnId,
|
|
2096
|
+
...(c.attrs.phone_number ? { phoneNumber: c.attrs.phone_number } : {}),
|
|
2097
|
+
...(lidVal ? { lid: lidVal } : {}),
|
|
2098
|
+
admin: c.attrs.type,
|
|
2099
|
+
});
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
return { subject, addressingMode, participants };
|
|
2104
|
+
};
|
|
2105
|
+
try {
|
|
2106
|
+
const res = await sendQuery({
|
|
2107
|
+
tag: "iq",
|
|
2108
|
+
attrs: { to: jid, type: "get", id: nextTag(), xmlns: "w:g2" },
|
|
2109
|
+
content: [{ tag: "query", attrs: { request: "interactive" } }],
|
|
2110
|
+
});
|
|
2111
|
+
const grp = Array.isArray(res.content) ? res.content.find((c) => c.tag === "group") : undefined;
|
|
2112
|
+
if (grp) {
|
|
2113
|
+
const parsed = parseGroupNode(grp);
|
|
2114
|
+
if (parsed.participants.length > 0 || parsed.subject) {
|
|
2115
|
+
groupCache.set(jid, parsed);
|
|
2116
|
+
}
|
|
2117
|
+
return { id: jid, ...parsed };
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
catch {
|
|
2121
|
+
}
|
|
2122
|
+
try {
|
|
2123
|
+
const res = await sendQuery({
|
|
2124
|
+
tag: "iq",
|
|
2125
|
+
attrs: { to: "@g.us", type: "get", id: nextTag(), xmlns: "w:g2" },
|
|
2126
|
+
content: [
|
|
2127
|
+
{
|
|
2128
|
+
tag: "participating",
|
|
2129
|
+
attrs: {},
|
|
2130
|
+
content: [{ tag: "participants", attrs: {} }, { tag: "description", attrs: {} }],
|
|
2131
|
+
},
|
|
2132
|
+
],
|
|
2133
|
+
});
|
|
2134
|
+
const groupsNode = Array.isArray(res.content) ? res.content.find((c) => c.tag === "groups") : undefined;
|
|
2135
|
+
const targetId = jid.split("@")[0];
|
|
2136
|
+
if (Array.isArray(groupsNode?.content)) {
|
|
2137
|
+
for (const g of groupsNode.content) {
|
|
2138
|
+
if (g.tag === "group" && (g.attrs?.id === jid || g.attrs?.id === targetId)) {
|
|
2139
|
+
const parsed = parseGroupNode(g);
|
|
2140
|
+
if (parsed.participants.length > 0 || parsed.subject) {
|
|
2141
|
+
groupCache.set(jid, parsed);
|
|
2142
|
+
}
|
|
2143
|
+
return { id: jid, ...parsed };
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
catch {
|
|
2149
|
+
}
|
|
2150
|
+
return { id: jid, subject: "", participants: [] };
|
|
2151
|
+
},
|
|
2152
|
+
async sendButtons(jid, payload = {}, options = {}) {
|
|
2153
|
+
const rawBtns = Array.isArray(payload.buttons)
|
|
2154
|
+
? payload.buttons
|
|
2155
|
+
: Array.isArray(payload.interactiveButtons)
|
|
2156
|
+
? payload.interactiveButtons
|
|
2157
|
+
: [];
|
|
2158
|
+
const converted = rawBtns.map((b, idx) => {
|
|
2159
|
+
if (typeof b?.name === "string" || b?.nativeFlowInfo)
|
|
2160
|
+
return b;
|
|
2161
|
+
if (Array.isArray(b?.sections)) {
|
|
2162
|
+
return {
|
|
2163
|
+
name: "single_select",
|
|
2164
|
+
buttonParamsJson: JSON.stringify({
|
|
2165
|
+
title: b.title ?? b.displayText ?? b.text ?? "Select",
|
|
2166
|
+
sections: b.sections,
|
|
2167
|
+
...(b.icon ? { icon: b.icon } : {}),
|
|
2168
|
+
}),
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
if (typeof b?.url === "string") {
|
|
2172
|
+
return {
|
|
2173
|
+
name: "cta_url",
|
|
2174
|
+
buttonParamsJson: JSON.stringify({
|
|
2175
|
+
display_text: b.displayText ?? b.text ?? b.title ?? "Open",
|
|
2176
|
+
url: b.url,
|
|
2177
|
+
merchant_url: b.merchantUrl ?? b.url,
|
|
2178
|
+
}),
|
|
2179
|
+
};
|
|
2180
|
+
}
|
|
2181
|
+
if (b?.copyCode !== undefined || b?.copy_code !== undefined) {
|
|
2182
|
+
return {
|
|
2183
|
+
name: "cta_copy",
|
|
2184
|
+
buttonParamsJson: JSON.stringify({
|
|
2185
|
+
display_text: b.displayText ?? b.text ?? "Copy",
|
|
2186
|
+
copy_code: String(b.copyCode ?? b.copy_code),
|
|
2187
|
+
}),
|
|
2188
|
+
};
|
|
2189
|
+
}
|
|
2190
|
+
return {
|
|
2191
|
+
name: "quick_reply",
|
|
2192
|
+
buttonParamsJson: JSON.stringify({
|
|
2193
|
+
display_text: b.displayText ?? b.buttonText?.displayText ?? b.text ?? b.title ?? "Button",
|
|
2194
|
+
id: String(b.id ?? b.buttonId ?? `btn_${idx}`),
|
|
2195
|
+
}),
|
|
2196
|
+
};
|
|
2197
|
+
});
|
|
2198
|
+
const out = { ...payload, interactiveButtons: converted };
|
|
2199
|
+
delete out.buttons;
|
|
2200
|
+
return sock.sendMessage(jid, out, options);
|
|
2201
|
+
},
|
|
2202
|
+
async profilePictureUrl(jid, type = "preview") {
|
|
2203
|
+
const target = jidNormalizedUser(jid);
|
|
2204
|
+
const res = await sendQuery({
|
|
2205
|
+
tag: "iq",
|
|
2206
|
+
attrs: {
|
|
2207
|
+
target,
|
|
2208
|
+
to: "s.whatsapp.net",
|
|
2209
|
+
type: "get",
|
|
2210
|
+
id: nextTag(),
|
|
2211
|
+
xmlns: "w:profile:picture",
|
|
2212
|
+
},
|
|
2213
|
+
content: [{ tag: "picture", attrs: { type, query: "url" } }],
|
|
2214
|
+
});
|
|
2215
|
+
const pic = Array.isArray(res.content) ? res.content.find((c) => c.tag === "picture") : undefined;
|
|
2216
|
+
return pic?.attrs?.url;
|
|
2217
|
+
},
|
|
2218
|
+
async groupParticipantsUpdate(jid, participants, action) {
|
|
2219
|
+
const res = await sendQuery({
|
|
2220
|
+
tag: "iq",
|
|
2221
|
+
attrs: { to: jid, type: "set", id: nextTag(), xmlns: "w:g2" },
|
|
2222
|
+
content: [
|
|
2223
|
+
{
|
|
2224
|
+
tag: action,
|
|
2225
|
+
attrs: {},
|
|
2226
|
+
content: participants.map((p) => ({ tag: "participant", attrs: { jid: p } })),
|
|
2227
|
+
},
|
|
2228
|
+
],
|
|
2229
|
+
});
|
|
2230
|
+
groupCache.delete(jid);
|
|
2231
|
+
const node = Array.isArray(res.content) ? res.content.find((c) => c.tag === action) : undefined;
|
|
2232
|
+
const affected = Array.isArray(node?.content) ? node.content.filter((c) => c.tag === "participant") : [];
|
|
2233
|
+
return affected.map((p) => ({ status: p.attrs?.error || "200", jid: p.attrs?.jid, content: p }));
|
|
2234
|
+
},
|
|
2235
|
+
async groupSettingUpdate(jid, setting) {
|
|
2236
|
+
await sendQuery({
|
|
2237
|
+
tag: "iq",
|
|
2238
|
+
attrs: { to: jid, type: "set", id: nextTag(), xmlns: "w:g2" },
|
|
2239
|
+
content: [{ tag: setting, attrs: {} }],
|
|
2240
|
+
});
|
|
2241
|
+
groupCache.delete(jid);
|
|
2242
|
+
},
|
|
2243
|
+
async groupFetchAllParticipating() {
|
|
2244
|
+
const res = await sendQuery({
|
|
2245
|
+
tag: "iq",
|
|
2246
|
+
attrs: { to: "@g.us", type: "get", id: nextTag(), xmlns: "w:g2" },
|
|
2247
|
+
content: [
|
|
2248
|
+
{
|
|
2249
|
+
tag: "participating",
|
|
2250
|
+
attrs: {},
|
|
2251
|
+
content: [{ tag: "participants", attrs: {} }, { tag: "description", attrs: {} }],
|
|
2252
|
+
},
|
|
2253
|
+
],
|
|
2254
|
+
});
|
|
2255
|
+
const out = {};
|
|
2256
|
+
const groupsNode = Array.isArray(res.content) ? res.content.find((c) => c.tag === "groups") : undefined;
|
|
2257
|
+
if (Array.isArray(groupsNode?.content)) {
|
|
2258
|
+
for (const g of groupsNode.content) {
|
|
2259
|
+
if (g.tag !== "group" || !g.attrs?.id)
|
|
2260
|
+
continue;
|
|
2261
|
+
const gid = g.attrs.id.includes("@") ? g.attrs.id : `${g.attrs.id}@g.us`;
|
|
2262
|
+
const participants = [];
|
|
2263
|
+
if (Array.isArray(g.content)) {
|
|
2264
|
+
for (const c of g.content) {
|
|
2265
|
+
if (c.tag === "participant" && c.attrs?.jid) {
|
|
2266
|
+
rememberLidPn(c.attrs.jid, c.attrs.phone_number);
|
|
2267
|
+
const pnId = c.attrs.phone_number ? jidNormalizedUser(c.attrs.phone_number) : resolvePnJid(c.attrs.jid);
|
|
2268
|
+
const lidVal = c.attrs.lid || (c.attrs.jid.endsWith("@lid") ? c.attrs.jid : undefined);
|
|
2269
|
+
participants.push({
|
|
2270
|
+
id: pnId,
|
|
2271
|
+
...(c.attrs.phone_number ? { phoneNumber: c.attrs.phone_number } : {}),
|
|
2272
|
+
...(lidVal ? { lid: lidVal } : {}),
|
|
2273
|
+
admin: c.attrs.type,
|
|
2274
|
+
});
|
|
2275
|
+
}
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
const meta = { id: gid, subject: g.attrs.subject ?? "", addressingMode: g.attrs.addressing_mode, participants };
|
|
2279
|
+
groupCache.set(gid, { subject: meta.subject, addressingMode: meta.addressingMode, participants });
|
|
2280
|
+
out[gid] = meta;
|
|
2281
|
+
}
|
|
2282
|
+
}
|
|
2283
|
+
return out;
|
|
2284
|
+
},
|
|
2285
|
+
async requestPairingCode(phone, customPairingCode) {
|
|
2286
|
+
await transportReady;
|
|
2287
|
+
const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
2288
|
+
let code = customPairingCode;
|
|
2289
|
+
if (!code) {
|
|
2290
|
+
const rb = randomBytes(5);
|
|
2291
|
+
let val = 0n;
|
|
2292
|
+
for (const b of rb)
|
|
2293
|
+
val = (val << 8n) | BigInt(b);
|
|
2294
|
+
let chars = "";
|
|
2295
|
+
for (let i = 0; i < 8; i++) {
|
|
2296
|
+
chars = CROCKFORD[Number(val & 31n)] + chars;
|
|
2297
|
+
val >>= 5n;
|
|
2298
|
+
}
|
|
2299
|
+
code = chars;
|
|
2300
|
+
}
|
|
2301
|
+
if (code.length !== 8) {
|
|
2302
|
+
throw new Error("Custom pairing code must be exactly 8 chars");
|
|
2303
|
+
}
|
|
2304
|
+
const cleanPhone = String(phone).replace(/\D/g, "");
|
|
2305
|
+
activePairingCode = code;
|
|
2306
|
+
activePairingJid = `${cleanPhone}@s.whatsapp.net`;
|
|
2307
|
+
authCreds.me = { id: activePairingJid, name: "~" };
|
|
2308
|
+
ev.emit("creds.update", authCreds);
|
|
2309
|
+
const salt = randomBytes(32);
|
|
2310
|
+
const iv = randomBytes(16);
|
|
2311
|
+
const key = await pbkdf2Async(code, salt, 2 << 16, 32, "sha256");
|
|
2312
|
+
const cipher = createCipheriv("aes-256-ctr", key, iv);
|
|
2313
|
+
const wrapped = Buffer.concat([salt, iv, cipher.update(pairingEphPub), cipher.final()]);
|
|
2314
|
+
await sendQuery({
|
|
2315
|
+
tag: "iq",
|
|
2316
|
+
attrs: { to: "s.whatsapp.net", type: "set", id: nextTag(), xmlns: "md" },
|
|
2317
|
+
content: [
|
|
2318
|
+
{
|
|
2319
|
+
tag: "link_code_companion_reg",
|
|
2320
|
+
attrs: { jid: `${cleanPhone}@s.whatsapp.net`, stage: "companion_hello", should_show_push_notification: "true" },
|
|
2321
|
+
content: [
|
|
2322
|
+
{ tag: "link_code_pairing_wrapped_companion_ephemeral_pub", attrs: {}, content: wrapped },
|
|
2323
|
+
{ tag: "companion_server_auth_key_pub", attrs: {}, content: noisePub },
|
|
2324
|
+
{ tag: "companion_platform_id", attrs: {}, content: "1" },
|
|
2325
|
+
{ tag: "companion_platform_display", attrs: {}, content: `${browser[1]} (${browser[0]})` },
|
|
2326
|
+
{ tag: "link_code_pairing_nonce", attrs: {}, content: "0" },
|
|
2327
|
+
],
|
|
2328
|
+
},
|
|
2329
|
+
],
|
|
2330
|
+
});
|
|
2331
|
+
return code;
|
|
2332
|
+
},
|
|
2333
|
+
async logout() {
|
|
2334
|
+
await client.logout();
|
|
2335
|
+
transport.close();
|
|
2336
|
+
},
|
|
2337
|
+
end() {
|
|
2338
|
+
transport.close();
|
|
2339
|
+
void client.disconnect();
|
|
2340
|
+
},
|
|
2341
|
+
...createCompatExtensions({
|
|
2342
|
+
sendQuery,
|
|
2343
|
+
sendEncrypted: (bytes) => transport.sendEncrypted(Buffer.from(bytes)),
|
|
2344
|
+
nextTag,
|
|
2345
|
+
getAuthCreds: () => authCreds,
|
|
2346
|
+
ev,
|
|
2347
|
+
transportReady,
|
|
2348
|
+
isOpen: () => Boolean(sock.ws?.isOpen),
|
|
2349
|
+
signalMgr,
|
|
2350
|
+
groupCache,
|
|
2351
|
+
lidToPnMap,
|
|
2352
|
+
rememberLidPn,
|
|
2353
|
+
resolvePnJid,
|
|
2354
|
+
uploadPreKeys: async () => {
|
|
2355
|
+
const startId = Number(authCreds.nextPreKeyId ?? 1);
|
|
2356
|
+
const keyNodes = [];
|
|
2357
|
+
const preKeyBatch = {};
|
|
2358
|
+
for (let i = 0; i < 30; i++) {
|
|
2359
|
+
const id = startId + i;
|
|
2360
|
+
const kp = JSON.parse(native.cryptoX25519Keypair());
|
|
2361
|
+
preKeyBatch[String(id)] = kp;
|
|
2362
|
+
const idBuf = Buffer.alloc(3);
|
|
2363
|
+
idBuf.writeUIntBE(id, 0, 3);
|
|
2364
|
+
keyNodes.push({
|
|
2365
|
+
tag: "key",
|
|
2366
|
+
attrs: {},
|
|
2367
|
+
content: [
|
|
2368
|
+
{ tag: "id", attrs: {}, content: idBuf },
|
|
2369
|
+
{ tag: "value", attrs: {}, content: Buffer.from(kp.publicKeyHex, "hex") },
|
|
2370
|
+
],
|
|
2371
|
+
});
|
|
2372
|
+
}
|
|
2373
|
+
if (authKeys?.set) {
|
|
2374
|
+
await authKeys.set({ "pre-key": preKeyBatch });
|
|
2375
|
+
}
|
|
2376
|
+
else {
|
|
2377
|
+
for (const [k, v] of Object.entries(preKeyBatch))
|
|
2378
|
+
memKeys.set(`pre-key:${k}`, v);
|
|
2379
|
+
}
|
|
2380
|
+
authCreds.nextPreKeyId = startId + 30;
|
|
2381
|
+
ev.emit("creds.update", authCreds);
|
|
2382
|
+
const regBuf = Buffer.alloc(4);
|
|
2383
|
+
regBuf.writeUInt32BE(Number(authCreds.registrationId ?? 1), 0);
|
|
2384
|
+
const spkIdBuf = Buffer.alloc(3);
|
|
2385
|
+
spkIdBuf.writeUIntBE(1, 0, 3);
|
|
2386
|
+
await sendQuery({
|
|
2387
|
+
tag: "iq",
|
|
2388
|
+
attrs: { to: "s.whatsapp.net", type: "set", id: nextTag(), xmlns: "encrypt" },
|
|
2389
|
+
content: [
|
|
2390
|
+
{ tag: "registration", attrs: {}, content: regBuf },
|
|
2391
|
+
{ tag: "type", attrs: {}, content: Buffer.from([5]) },
|
|
2392
|
+
{ tag: "identity", attrs: {}, content: identPub },
|
|
2393
|
+
{ tag: "list", attrs: {}, content: keyNodes },
|
|
2394
|
+
{
|
|
2395
|
+
tag: "skey",
|
|
2396
|
+
attrs: {},
|
|
2397
|
+
content: [
|
|
2398
|
+
{ tag: "id", attrs: {}, content: spkIdBuf },
|
|
2399
|
+
{ tag: "value", attrs: {}, content: spkPub },
|
|
2400
|
+
{ tag: "signature", attrs: {}, content: spkSig },
|
|
2401
|
+
],
|
|
2402
|
+
},
|
|
2403
|
+
],
|
|
2404
|
+
});
|
|
2405
|
+
},
|
|
2406
|
+
getKey,
|
|
2407
|
+
setKey,
|
|
2408
|
+
}),
|
|
2409
|
+
};
|
|
2410
|
+
ev.emit("connection.update", { connection: "connecting" });
|
|
2411
|
+
void transport
|
|
2412
|
+
.connectWithHandshake(clientPayloadBytes, 20_000, { privateKey: noisePriv, publicKey: noisePub })
|
|
2413
|
+
.then(() => {
|
|
2414
|
+
sock.ws.isOpen = true;
|
|
2415
|
+
readyResolve();
|
|
2416
|
+
})
|
|
2417
|
+
.catch((err) => {
|
|
2418
|
+
emitClose(err instanceof Error
|
|
2419
|
+
? Object.assign(err, { output: err.output ?? { statusCode: DisconnectReason.connectionClosed } })
|
|
2420
|
+
: Object.assign(new Error(String(err)), { output: { statusCode: DisconnectReason.connectionClosed } }));
|
|
2421
|
+
});
|
|
2422
|
+
return sock;
|
|
2423
|
+
}
|
|
2424
|
+
export function normalizeMessageContent(content) {
|
|
2425
|
+
if (!content || typeof content !== "object")
|
|
2426
|
+
return content;
|
|
2427
|
+
for (const key of [
|
|
2428
|
+
"ephemeralMessage",
|
|
2429
|
+
"viewOnceMessage",
|
|
2430
|
+
"viewOnceMessageV2",
|
|
2431
|
+
"viewOnceMessageV2Extension",
|
|
2432
|
+
"documentWithCaptionMessage",
|
|
2433
|
+
"editedMessage",
|
|
2434
|
+
]) {
|
|
2435
|
+
if (content[key]?.message) {
|
|
2436
|
+
return normalizeMessageContent(content[key].message);
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2439
|
+
return content;
|
|
2440
|
+
}
|
|
2441
|
+
export function extractMessageContent(content) {
|
|
2442
|
+
return normalizeMessageContent(content);
|
|
2443
|
+
}
|
|
2444
|
+
export async function downloadMediaMessage(msg, type = "buffer") {
|
|
2445
|
+
const inner = normalizeMessageContent(msg?.message ?? msg);
|
|
2446
|
+
const mediaKey = Object.keys(inner || {}).find((k) => k.endsWith("Message")) ?? "imageMessage";
|
|
2447
|
+
const mediaType = mediaKey.replace("Message", "");
|
|
2448
|
+
const stream = await downloadContentFromMessage(inner[mediaKey], mediaType);
|
|
2449
|
+
return type === "stream" ? stream : await toBuffer(stream);
|
|
2450
|
+
}
|
|
2451
|
+
export async function prepareWAMessageMedia(media, _options) {
|
|
2452
|
+
for (const kind of ["image", "video", "audio", "document", "sticker"]) {
|
|
2453
|
+
if (media[kind]) {
|
|
2454
|
+
const buf = Buffer.isBuffer(media[kind]) ? media[kind] : Buffer.from(media[kind]);
|
|
2455
|
+
const enc = encryptWaMedia(buf, kind);
|
|
2456
|
+
return {
|
|
2457
|
+
[`${kind}Message`]: {
|
|
2458
|
+
mediaKey: enc.mediaKey,
|
|
2459
|
+
fileSha256: enc.fileSha256,
|
|
2460
|
+
fileEncSha256: enc.fileEncSha256,
|
|
2461
|
+
fileLength: buf.length,
|
|
2462
|
+
mimetype: media.mimetype,
|
|
2463
|
+
},
|
|
2464
|
+
};
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
return {};
|
|
2468
|
+
}
|
|
2469
|
+
export function generateWAMessageFromContent(jid, message, _options) {
|
|
2470
|
+
return {
|
|
2471
|
+
key: { remoteJid: jid, fromMe: true, id: generateMessageIDV2(jid) },
|
|
2472
|
+
message,
|
|
2473
|
+
messageTimestamp: Math.floor(Date.now() / 1000),
|
|
2474
|
+
};
|
|
2475
|
+
}
|
|
2476
|
+
export const MODE_OFF = 0;
|
|
2477
|
+
export const MODE_ON = 1;
|
|
2478
|
+
export const MODE_WARN = 2;
|
|
2479
|
+
let stealthDeps = {};
|
|
2480
|
+
const stealthModes = new Map();
|
|
2481
|
+
export function setStealthDeps(deps) {
|
|
2482
|
+
stealthDeps = deps;
|
|
2483
|
+
}
|
|
2484
|
+
export function setStealthMode(chat, mode) {
|
|
2485
|
+
stealthModes.set(chat, mode);
|
|
2486
|
+
}
|
|
2487
|
+
export function getStealthMode(chat) {
|
|
2488
|
+
return stealthModes.get(chat) ?? MODE_OFF;
|
|
2489
|
+
}
|
|
2490
|
+
export function getStealthConfig() {
|
|
2491
|
+
return stealthDeps;
|
|
2492
|
+
}
|
|
2493
|
+
export function getStealthRuntime() {
|
|
2494
|
+
return { attached: true, modes: stealthModes.size };
|
|
2495
|
+
}
|
|
2496
|
+
export function isStealthAttached() {
|
|
2497
|
+
return true;
|
|
2498
|
+
}
|
|
2499
|
+
export function attachStealthGuard() { }
|
|
2500
|
+
//# sourceMappingURL=index.js.map
|