@x4r1s3/baileys 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -41
- package/assets/x4r1s3-banner.svg +2 -2
- package/lib/Call/astralena-v3.mjs +96 -0
- package/lib/Call/audio-feeder.mjs +22 -0
- package/lib/Call/index.mjs +28 -1
- package/lib/Call/signaling.mjs +19 -0
- package/lib/Call/voip-resources.mjs +259 -0
- package/lib/Socket/messages-recv.js +2 -0
- package/lib/Socket/messages-send.js +38 -1
- package/lib/Socket/socket.js +71 -58
- package/lib/Utils/companion-reg-client-utils.js +61 -1
- package/lib/Utils/validate-connection.js +2 -1
- package/lib/index.d.ts +760 -150
- package/lib/index.js +11 -0
- package/package.json +4 -4
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { randomBytes } from 'node:crypto';
|
|
4
|
+
import { WebSocket } from 'ws';
|
|
5
|
+
|
|
6
|
+
export const VOIP_RESOURCE_FILES = Object.freeze({
|
|
7
|
+
wasm: 'assets/wasm/whatsapp.wasm',
|
|
8
|
+
worker: 'assets/wasm/worker-modules.js',
|
|
9
|
+
loader: 'assets/wasm/loader.js',
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
export class VoipResourceError extends Error {
|
|
13
|
+
constructor(message, options = {}) {
|
|
14
|
+
super(message, options);
|
|
15
|
+
this.name = 'VoipResourceError';
|
|
16
|
+
this.code = options.code ?? 'VOIP_RESOURCES_UNAVAILABLE';
|
|
17
|
+
this.capabilities = options.capabilities;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const pathFor = (resourcesPath, relative) => join(resolve(resourcesPath), relative);
|
|
22
|
+
const present = file => existsSync(file) && statSync(file).size > 0;
|
|
23
|
+
|
|
24
|
+
export const inspectVoipResources = (resourcesPath = 'call-resources') => {
|
|
25
|
+
const root = resolve(resourcesPath);
|
|
26
|
+
const files = {
|
|
27
|
+
wasm: pathFor(root, VOIP_RESOURCE_FILES.wasm),
|
|
28
|
+
worker: pathFor(root, VOIP_RESOURCE_FILES.worker),
|
|
29
|
+
loader: pathFor(root, VOIP_RESOURCE_FILES.loader),
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
resourcesPath: root,
|
|
33
|
+
wasm: present(files.wasm),
|
|
34
|
+
worker: present(files.worker),
|
|
35
|
+
loader: present(files.loader),
|
|
36
|
+
complete: present(files.wasm) && present(files.worker),
|
|
37
|
+
files,
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Detect whether a connected Baileys socket exposes a future/session-side
|
|
43
|
+
* resource manifest. Current Baileys sockets do not expose one; this helper
|
|
44
|
+
* makes that capability explicit for callers and future protocol adapters.
|
|
45
|
+
*/
|
|
46
|
+
export const inspectSessionVoipResources = sock => {
|
|
47
|
+
if (!sock) return { supported: false, reason: 'No Baileys socket was supplied.' };
|
|
48
|
+
if (typeof sock.fetchVoipResources === 'function') {
|
|
49
|
+
return { supported: true, method: 'fetchVoipResources' };
|
|
50
|
+
}
|
|
51
|
+
if (sock.voipResources && typeof sock.voipResources === 'object') {
|
|
52
|
+
return { supported: true, method: 'voipResources' };
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
supported: false,
|
|
56
|
+
reason: 'The current Baileys socket does not expose a VOIP resource manifest. Authentication/session state and browser runtime assets are separate.',
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const toBytes = value => {
|
|
61
|
+
if (value == null) return undefined;
|
|
62
|
+
if (Buffer.isBuffer(value)) return value;
|
|
63
|
+
if (value instanceof Uint8Array) return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
64
|
+
if (value instanceof ArrayBuffer) return Buffer.from(value);
|
|
65
|
+
if (ArrayBuffer.isView(value)) return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
66
|
+
return value;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const normalizeManifest = value => {
|
|
70
|
+
if (!value || typeof value !== 'object') return null;
|
|
71
|
+
const wasmUrl = value.wasmUrl ?? value.wasm?.url;
|
|
72
|
+
const workerUrl = value.workerUrl ?? value.worker?.url;
|
|
73
|
+
const loaderUrl = value.loaderUrl ?? value.loader?.url;
|
|
74
|
+
const wasmBinary = toBytes(value.wasmBinary ?? value.wasm?.bytes);
|
|
75
|
+
const workerModulesCode = value.workerModulesCode ?? value.worker?.code;
|
|
76
|
+
const loaderCode = value.loaderCode ?? value.loader?.code;
|
|
77
|
+
if (!wasmUrl && !workerUrl && !wasmBinary && !workerModulesCode) return null;
|
|
78
|
+
return { wasmUrl, workerUrl, loaderUrl, wasmBinary, workerModulesCode, loaderCode };
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const atomicWrite = (file, data) => {
|
|
82
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
83
|
+
const temporary = `${file}.tmp-${process.pid}-${randomBytes(5).toString('hex')}`;
|
|
84
|
+
writeFileSync(temporary, data);
|
|
85
|
+
renameSync(temporary, file);
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const fetchChecked = async url => {
|
|
89
|
+
const response = await fetch(url);
|
|
90
|
+
if (!response.ok) throw new VoipResourceError(`HTTP ${response.status} fetching VOIP resource ${url}`, { code: 'VOIP_RESOURCE_HTTP_ERROR' });
|
|
91
|
+
return response;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const downloadManifest = async manifest => {
|
|
95
|
+
const normalized = normalizeManifest(manifest);
|
|
96
|
+
if (!normalized) return null;
|
|
97
|
+
const result = { ...normalized };
|
|
98
|
+
if (!result.wasmBinary && result.wasmUrl) result.wasmBinary = Buffer.from(await (await fetchChecked(result.wasmUrl)).arrayBuffer());
|
|
99
|
+
if (!result.workerModulesCode && result.workerUrl) result.workerModulesCode = await (await fetchChecked(result.workerUrl)).text();
|
|
100
|
+
if (!result.loaderCode && result.loaderUrl) result.loaderCode = await (await fetchChecked(result.loaderUrl)).text();
|
|
101
|
+
if (!result.wasmBinary || !result.workerModulesCode) {
|
|
102
|
+
throw new VoipResourceError('VOIP resource manifest must provide wasm bytes/URL and worker code/URL.', { code: 'VOIP_RESOURCE_MANIFEST_INCOMPLETE' });
|
|
103
|
+
}
|
|
104
|
+
return result;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const cdpRequest = (ws, method, params, pending, nextId) => new Promise((resolveResult, reject) => {
|
|
108
|
+
const id = nextId.value++;
|
|
109
|
+
const timeout = setTimeout(() => {
|
|
110
|
+
pending.delete(id);
|
|
111
|
+
reject(new VoipResourceError(`Timed out waiting for Chrome DevTools method ${method}`, { code: 'VOIP_RESOURCE_CDP_TIMEOUT' }));
|
|
112
|
+
}, 15000);
|
|
113
|
+
pending.set(id, {
|
|
114
|
+
resolve: value => { clearTimeout(timeout); resolveResult(value); },
|
|
115
|
+
reject: error => { clearTimeout(timeout); reject(error); },
|
|
116
|
+
});
|
|
117
|
+
ws.send(JSON.stringify({ id, method, params }));
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
/** Fetch compatible resources from an already-open WhatsApp Web browser tab. */
|
|
121
|
+
export const fetchVoipResourcesFromBrowser = async ({
|
|
122
|
+
debuggerUrl = process.env.CALL_CHROME_DEBUGGER_JSON_URL || 'http://127.0.0.1:9222/json/list',
|
|
123
|
+
wasmId = process.env.CALL_BROWSER_WASM_ID || '32180',
|
|
124
|
+
} = {}) => {
|
|
125
|
+
const targets = await (await fetchChecked(debuggerUrl)).json();
|
|
126
|
+
const page = targets.find(target => target.type === 'page' && target.url?.includes('web.whatsapp.com'));
|
|
127
|
+
if (!page?.webSocketDebuggerUrl) {
|
|
128
|
+
throw new VoipResourceError('No WhatsApp Web page found through the configured browser debugger. The current Baileys socket does not provide browser runtime resources.', { code: 'VOIP_BROWSER_PAGE_NOT_FOUND' });
|
|
129
|
+
}
|
|
130
|
+
const ws = new WebSocket(page.webSocketDebuggerUrl);
|
|
131
|
+
const pending = new Map();
|
|
132
|
+
const nextId = { value: 1 };
|
|
133
|
+
const rejectPending = error => {
|
|
134
|
+
for (const request of pending.values()) request.reject(error);
|
|
135
|
+
pending.clear();
|
|
136
|
+
};
|
|
137
|
+
ws.on('error', error => rejectPending(new VoipResourceError(`Chrome DevTools connection failed: ${error.message}`, { code: 'VOIP_BROWSER_CONNECTION_FAILED', cause: error })));
|
|
138
|
+
ws.on('close', () => rejectPending(new VoipResourceError('Chrome DevTools connection closed while fetching VOIP resources.', { code: 'VOIP_BROWSER_CONNECTION_CLOSED' })));
|
|
139
|
+
ws.on('message', raw => {
|
|
140
|
+
let message;
|
|
141
|
+
try { message = JSON.parse(raw.toString()); } catch { return; }
|
|
142
|
+
if (!message.id || !pending.has(message.id)) return;
|
|
143
|
+
const request = pending.get(message.id);
|
|
144
|
+
pending.delete(message.id);
|
|
145
|
+
if (message.error) request.reject(new Error(message.error.message));
|
|
146
|
+
else request.resolve(message.result);
|
|
147
|
+
});
|
|
148
|
+
try {
|
|
149
|
+
await new Promise((resolveOpen, rejectOpen) => {
|
|
150
|
+
ws.once('open', resolveOpen);
|
|
151
|
+
ws.once('error', rejectOpen);
|
|
152
|
+
});
|
|
153
|
+
const expression = `(() => {
|
|
154
|
+
try {
|
|
155
|
+
const resource = require("WAWebVoipWebWasmWorkerResource");
|
|
156
|
+
const id = ${JSON.stringify(wasmId)};
|
|
157
|
+
return {
|
|
158
|
+
workerUrl: resource?.url || null,
|
|
159
|
+
wasmUrl: resource?.hsdp?.bxData?.[id]?.uri || null,
|
|
160
|
+
availableIds: Object.keys(resource?.hsdp?.bxData || {}),
|
|
161
|
+
};
|
|
162
|
+
} catch (error) { return { error: error.message }; }
|
|
163
|
+
})()`;
|
|
164
|
+
const evaluation = await cdpRequest(ws, 'Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, pending, nextId);
|
|
165
|
+
if (evaluation.exceptionDetails) throw new VoipResourceError(evaluation.exceptionDetails.text || 'Could not inspect WhatsApp Web resources', { code: 'VOIP_BROWSER_EVALUATION_FAILED' });
|
|
166
|
+
const info = evaluation.result?.value;
|
|
167
|
+
if (info?.error) throw new VoipResourceError(`Browser evaluation failed: ${info.error}`, { code: 'VOIP_BROWSER_EVALUATION_FAILED' });
|
|
168
|
+
if (!info?.workerUrl || !info?.wasmUrl) throw new VoipResourceError(`No resources found for WASM id ${wasmId}; available IDs: ${(info?.availableIds || []).join(', ')}`, { code: 'VOIP_BROWSER_RESOURCES_NOT_FOUND' });
|
|
169
|
+
return downloadManifest(info);
|
|
170
|
+
} finally {
|
|
171
|
+
ws.removeAllListeners();
|
|
172
|
+
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) ws.close();
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
/** Fetch resources from caller-supplied URLs. URLs are intentionally never used by default. */
|
|
177
|
+
export const fetchVoipResourcesFromUrls = async ({ wasmUrl, workerUrl, loaderUrl } = {}) => {
|
|
178
|
+
if (!wasmUrl || !workerUrl) {
|
|
179
|
+
throw new VoipResourceError('Remote VOIP resources require both wasmUrl and workerUrl.', { code: 'VOIP_REMOTE_URLS_INCOMPLETE' });
|
|
180
|
+
}
|
|
181
|
+
return downloadManifest({ wasmUrl, workerUrl, loaderUrl });
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
/** Load bytes/code from a trusted runtime asset package exposing a manifest. */
|
|
185
|
+
export const loadVoipResourcesFromPackage = async packageName => {
|
|
186
|
+
if (!packageName) throw new TypeError('A VOIP runtime package name is required.');
|
|
187
|
+
const module = await import(packageName);
|
|
188
|
+
const manifest = module.voipResources ?? module.default?.voipResources ?? module.default;
|
|
189
|
+
const result = await downloadManifest(manifest);
|
|
190
|
+
if (!result) throw new VoipResourceError(`Runtime package ${packageName} does not export a VOIP resource manifest.`, { code: 'VOIP_RUNTIME_PACKAGE_INVALID' });
|
|
191
|
+
return result;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const writeManifest = (resourcesPath, manifest, force = false) => {
|
|
195
|
+
const status = inspectVoipResources(resourcesPath);
|
|
196
|
+
if (!status.complete || force) {
|
|
197
|
+
atomicWrite(status.files.worker, Buffer.from(manifest.workerModulesCode));
|
|
198
|
+
atomicWrite(status.files.wasm, Buffer.from(manifest.wasmBinary));
|
|
199
|
+
if (manifest.loaderCode) atomicWrite(status.files.loader, Buffer.from(manifest.loaderCode));
|
|
200
|
+
}
|
|
201
|
+
return inspectVoipResources(resourcesPath);
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Ensure local VOIP resources exist. Resolution order:
|
|
206
|
+
* 1. Existing cache.
|
|
207
|
+
* 2. Explicit provider or a future socket-side manifest.
|
|
208
|
+
* 3. Trusted runtime asset package.
|
|
209
|
+
* 4. Optional WhatsApp Web browser debugger.
|
|
210
|
+
*
|
|
211
|
+
* A normal Baileys socket is intentionally not treated as a resource source
|
|
212
|
+
* unless it exposes an explicit fetchVoipResources()/voipResources capability.
|
|
213
|
+
*/
|
|
214
|
+
export const ensureVoipResources = async ({
|
|
215
|
+
resourcesPath = process.env.X4R1S3_VOIP_RESOURCES || process.env.PLOGME_VOIP_RESOURCES || 'call-resources',
|
|
216
|
+
sock,
|
|
217
|
+
resourceProvider,
|
|
218
|
+
runtimePackage,
|
|
219
|
+
resourceUrls,
|
|
220
|
+
debuggerUrl,
|
|
221
|
+
wasmId,
|
|
222
|
+
force = false,
|
|
223
|
+
} = {}) => {
|
|
224
|
+
const existing = inspectVoipResources(resourcesPath);
|
|
225
|
+
if (existing.complete && !force) return { ...existing, source: 'cache' };
|
|
226
|
+
|
|
227
|
+
let manifest = null;
|
|
228
|
+
let source = null;
|
|
229
|
+
if (typeof resourceProvider === 'function') {
|
|
230
|
+
manifest = await resourceProvider({ sock });
|
|
231
|
+
source = 'provider';
|
|
232
|
+
} else if (sock?.fetchVoipResources) {
|
|
233
|
+
manifest = await sock.fetchVoipResources();
|
|
234
|
+
source = 'session';
|
|
235
|
+
} else if (sock?.voipResources) {
|
|
236
|
+
manifest = sock.voipResources;
|
|
237
|
+
source = 'session';
|
|
238
|
+
} else if (runtimePackage) {
|
|
239
|
+
manifest = await loadVoipResourcesFromPackage(runtimePackage);
|
|
240
|
+
source = 'runtime-package';
|
|
241
|
+
} else if (resourceUrls) {
|
|
242
|
+
manifest = await fetchVoipResourcesFromUrls(resourceUrls);
|
|
243
|
+
source = 'remote-url';
|
|
244
|
+
} else if (debuggerUrl || process.env.CALL_CHROME_DEBUGGER_JSON_URL) {
|
|
245
|
+
manifest = await fetchVoipResourcesFromBrowser({ debuggerUrl, wasmId });
|
|
246
|
+
source = 'browser';
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (!manifest) {
|
|
250
|
+
const capabilities = inspectSessionVoipResources(sock);
|
|
251
|
+
throw new VoipResourceError(
|
|
252
|
+
'VOIP resources are missing. The current Baileys session has no resource manifest; provide a trusted runtime package, resource provider, or browser debugger endpoint.',
|
|
253
|
+
{ code: 'VOIP_RESOURCES_UNAVAILABLE', capabilities },
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
const downloaded = await downloadManifest(manifest);
|
|
257
|
+
const result = writeManifest(resourcesPath, downloaded, force);
|
|
258
|
+
return { ...result, source };
|
|
259
|
+
};
|
|
@@ -1272,6 +1272,8 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
1272
1272
|
break;
|
|
1273
1273
|
case 'link_code_companion_reg':
|
|
1274
1274
|
const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
|
|
1275
|
+
if (linkCodeCompanionReg?.attrs?.stage !== 'primary_hello')
|
|
1276
|
+
break;
|
|
1275
1277
|
const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
|
|
1276
1278
|
const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
|
|
1277
1279
|
const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
|
|
@@ -582,7 +582,9 @@ export const makeMessagesSocket = (config) => {
|
|
|
582
582
|
const binaryNodeContent = [];
|
|
583
583
|
const devices = [];
|
|
584
584
|
let reportingMessage;
|
|
585
|
-
const
|
|
585
|
+
const isRequestContactInfoMessage = message?.interactiveMessage?.nativeFlowMessage?.buttons?.some(button => button?.name === 'request_contact_info');
|
|
586
|
+
const isNativeCarouselMessage = !!message?.interactiveMessage?.carouselMessage;
|
|
587
|
+
const requiresViewOnce = !isRequestContactInfoMessage && !isNativeCarouselMessage && !!(message.buttonsMessage || message.templateMessage || message.listMessage || message.interactiveMessage);
|
|
586
588
|
if (requiresViewOnce) {
|
|
587
589
|
message = {
|
|
588
590
|
viewOnceMessage: {
|
|
@@ -2875,11 +2877,22 @@ export const makeMessagesSocket = (config) => {
|
|
|
2875
2877
|
const isEventMsg = 'event' in content && !!content.event;
|
|
2876
2878
|
const isDeleteMsg = 'delete' in content && !!content.delete;
|
|
2877
2879
|
const isEditMsg = 'edit' in content && !!content.edit;
|
|
2880
|
+
const isFakeEditMsg = content.edited === true;
|
|
2878
2881
|
const isPinMsg = 'pin' in content && !!content.pin;
|
|
2879
2882
|
const isKeepMsg = 'keep' in content && !!content.keep;
|
|
2880
2883
|
const isPollMsg = 'poll' in content && !!content.poll;
|
|
2881
2884
|
const isQuizMsg = 'poll' in content && !!content.poll.pollType;
|
|
2882
2885
|
const isAiMsg = 'ai' in content && !!content.ai;
|
|
2886
|
+
if (isFakeEditMsg && isEditMsg) {
|
|
2887
|
+
throw new Boom('Use either edited: true for an automatic fake edit or edit: key for a real edit, not both', { statusCode: 400 });
|
|
2888
|
+
}
|
|
2889
|
+
// A type-14 edit is wrapped in protocolMessage, so relayMessage
|
|
2890
|
+
// cannot infer the media type from the outer envelope. Preserve
|
|
2891
|
+
// the edited image/audio/video type on the message stanza so
|
|
2892
|
+
// cross-type edits are relayed as media rather than text.
|
|
2893
|
+
const editedMediaType = isEditMsg
|
|
2894
|
+
? getMediaType(normalizeMessageContent(fullMsg.message?.protocolMessage?.editedMessage))
|
|
2895
|
+
: undefined;
|
|
2883
2896
|
const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
|
|
2884
2897
|
delete content.secureMetaServiceLabel;
|
|
2885
2898
|
const additionalAttributes = options.additionalAttributes || {};
|
|
@@ -2944,6 +2957,7 @@ export const makeMessagesSocket = (config) => {
|
|
|
2944
2957
|
addBizAttributes: isNeedBizAttrs,
|
|
2945
2958
|
statusJidList: options.statusJidList,
|
|
2946
2959
|
statusPrivacy: options.statusPrivacy,
|
|
2960
|
+
mediaTypeOverride: editedMediaType || undefined,
|
|
2947
2961
|
additionalAttributes,
|
|
2948
2962
|
additionalNodes
|
|
2949
2963
|
});
|
|
@@ -2954,6 +2968,29 @@ export const makeMessagesSocket = (config) => {
|
|
|
2954
2968
|
});
|
|
2955
2969
|
}
|
|
2956
2970
|
|
|
2971
|
+
if (isFakeEditMsg) {
|
|
2972
|
+
// Send the original message first, then replay the same
|
|
2973
|
+
// content as a type-14 edit so callers can exercise the
|
|
2974
|
+
// edited state without manually constructing protocolMessage.
|
|
2975
|
+
const fakeEditMessage = proto.Message.fromObject({
|
|
2976
|
+
protocolMessage: {
|
|
2977
|
+
key: fullMsg.key,
|
|
2978
|
+
type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
|
|
2979
|
+
editedMessage: fullMsg.message
|
|
2980
|
+
}
|
|
2981
|
+
});
|
|
2982
|
+
await relayMessage(jid, fakeEditMessage, {
|
|
2983
|
+
messageId: generateMessageIDV2(userJid),
|
|
2984
|
+
useCachedGroupMetadata: options.useCachedGroupMetadata,
|
|
2985
|
+
addBizAttributes: isNeedBizAttrs,
|
|
2986
|
+
statusJidList: options.statusJidList,
|
|
2987
|
+
statusPrivacy: options.statusPrivacy,
|
|
2988
|
+
mediaTypeOverride: getMediaType(normalizeMessageContent(fullMsg.message)) || undefined,
|
|
2989
|
+
additionalAttributes: { ...additionalAttributes, edit: isNewsletter ? '3' : '1' },
|
|
2990
|
+
additionalNodes
|
|
2991
|
+
});
|
|
2992
|
+
}
|
|
2993
|
+
|
|
2957
2994
|
return fullMsg;
|
|
2958
2995
|
}
|
|
2959
2996
|
}
|
package/lib/Socket/socket.js
CHANGED
|
@@ -17,7 +17,7 @@ import { promisify } from 'util';
|
|
|
17
17
|
import { proto } from '../../WAProto/index.js';
|
|
18
18
|
import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, NOISE_WA_HEADER, PROCESSABLE_HISTORY_TYPES, TimeMs, UPLOAD_TIMEOUT } from '../Defaults/index.js';
|
|
19
19
|
import { DisconnectReason, QueryIds, ReachoutTimelockEnforcementType, XWAPaths } from '../Types/index.js';
|
|
20
|
-
import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, bytesToCrockford, buildPairingQRData, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCompanionPlatformId, getCodeFromWSError, getErrorCodeFromStreamError, getNextPreKeysNode, makeEventBuffer, makeNoiseHandler, promiseTimeout, signedKeyPair, xmppSignedPreKey } from '../Utils/index.js';
|
|
20
|
+
import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, bytesToCrockford, buildPairingQRData, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCompanionPlatformId, getCodeFromWSError, getErrorCodeFromStreamError, getNextPreKeysNode, getPairingCodePlatform, handleCompanionRegRefresh, makeEventBuffer, makeNoiseHandler, makePairingQRRenderer, promiseTimeout, signedKeyPair, xmppSignedPreKey } from '../Utils/index.js';
|
|
21
21
|
import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, S_WHATSAPP_NET } from '../WABinary/index.js';
|
|
22
22
|
import { BinaryInfo, encodeWAM } from '../WAM/index.js';
|
|
23
23
|
import { USyncQuery, USyncUser } from '../WAUSync/index.js';
|
|
@@ -327,7 +327,7 @@ export const makeSocket = (config) => {
|
|
|
327
327
|
logger.trace({ handshake }, 'handshake recv from WA');
|
|
328
328
|
const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
|
|
329
329
|
let node;
|
|
330
|
-
if (!creds.me) {
|
|
330
|
+
if (!creds.me || (!!creds.pairingCode && !creds.registered)) {
|
|
331
331
|
node = generateRegistrationNode(creds, config);
|
|
332
332
|
logger.info({ node }, 'not logged in, attempting registration...');
|
|
333
333
|
}
|
|
@@ -610,57 +610,61 @@ export const makeSocket = (config) => {
|
|
|
610
610
|
throw new Error('Custom pairing code must be exactly 8 chars');
|
|
611
611
|
}
|
|
612
612
|
authState.creds.pairingCode = pairingCode;
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
stage: 'companion_hello',
|
|
632
|
-
should_show_push_notification: 'true'
|
|
633
|
-
},
|
|
634
|
-
content: [
|
|
635
|
-
{
|
|
636
|
-
tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
|
|
637
|
-
attrs: {},
|
|
638
|
-
content: await generatePairingKey()
|
|
639
|
-
},
|
|
640
|
-
{
|
|
641
|
-
tag: 'companion_server_auth_key_pub',
|
|
642
|
-
attrs: {},
|
|
643
|
-
content: authState.creds.noiseKey.public
|
|
644
|
-
},
|
|
645
|
-
{
|
|
646
|
-
tag: 'companion_platform_id',
|
|
647
|
-
attrs: {},
|
|
648
|
-
content: getCompanionPlatformId(browser)
|
|
649
|
-
},
|
|
650
|
-
{
|
|
651
|
-
tag: 'companion_platform_display',
|
|
652
|
-
attrs: {},
|
|
653
|
-
content: `${browser[1]} (${browser[0]})`
|
|
613
|
+
const jid = jidEncode(phoneNumber, 's.whatsapp.net');
|
|
614
|
+
const pairingPlatform = getPairingCodePlatform(browser);
|
|
615
|
+
try {
|
|
616
|
+
await query({
|
|
617
|
+
tag: 'iq',
|
|
618
|
+
attrs: {
|
|
619
|
+
to: S_WHATSAPP_NET,
|
|
620
|
+
type: 'set',
|
|
621
|
+
id: generateMessageTag(),
|
|
622
|
+
xmlns: 'md'
|
|
623
|
+
},
|
|
624
|
+
content: [
|
|
625
|
+
{
|
|
626
|
+
tag: 'link_code_companion_reg',
|
|
627
|
+
attrs: {
|
|
628
|
+
jid,
|
|
629
|
+
stage: 'companion_hello',
|
|
630
|
+
should_show_push_notification: 'true'
|
|
654
631
|
},
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
632
|
+
content: [
|
|
633
|
+
{
|
|
634
|
+
tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
|
|
635
|
+
attrs: {},
|
|
636
|
+
content: await generatePairingKey()
|
|
637
|
+
},
|
|
638
|
+
{
|
|
639
|
+
tag: 'companion_server_auth_key_pub',
|
|
640
|
+
attrs: {},
|
|
641
|
+
content: authState.creds.noiseKey.public
|
|
642
|
+
},
|
|
643
|
+
{
|
|
644
|
+
tag: 'companion_platform_id',
|
|
645
|
+
attrs: {},
|
|
646
|
+
content: pairingPlatform.id
|
|
647
|
+
},
|
|
648
|
+
{
|
|
649
|
+
tag: 'companion_platform_display',
|
|
650
|
+
attrs: {},
|
|
651
|
+
content: pairingPlatform.display
|
|
652
|
+
},
|
|
653
|
+
{
|
|
654
|
+
tag: 'link_code_pairing_nonce',
|
|
655
|
+
attrs: {},
|
|
656
|
+
content: Buffer.alloc(1)
|
|
657
|
+
}
|
|
658
|
+
]
|
|
659
|
+
}
|
|
660
|
+
]
|
|
661
|
+
});
|
|
662
|
+
} catch (error) {
|
|
663
|
+
if (authState.creds.pairingCode === pairingCode) authState.creds.pairingCode = undefined;
|
|
664
|
+
throw error;
|
|
665
|
+
}
|
|
666
|
+
authState.creds.me = { id: jid, name: '~' };
|
|
667
|
+
ev.emit('creds.update', authState.creds);
|
|
664
668
|
return authState.creds.pairingCode;
|
|
665
669
|
};
|
|
666
670
|
async function generatePairingKey() {
|
|
@@ -729,6 +733,8 @@ export const makeSocket = (config) => {
|
|
|
729
733
|
ws.on('close', () => void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
|
|
730
734
|
// the server terminated the connection
|
|
731
735
|
ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
|
|
736
|
+
// Re-render the current pairing QR after a companion registration refresh.
|
|
737
|
+
let refreshPairingQR;
|
|
732
738
|
// QR gen
|
|
733
739
|
ws.on('CB:iq,type:set,pair-device', async (stanza) => {
|
|
734
740
|
const iq = {
|
|
@@ -744,25 +750,32 @@ export const makeSocket = (config) => {
|
|
|
744
750
|
const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
|
|
745
751
|
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
|
|
746
752
|
const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
|
|
747
|
-
const
|
|
753
|
+
const renderer = makePairingQRRenderer(refNodes.map(refNode => refNode.content.toString('utf-8')), ref => ev.emit('connection.update', {
|
|
754
|
+
qr: buildPairingQRData(ref, noiseKeyB64, identityKeyB64, creds.advSecretKey, browser)
|
|
755
|
+
}));
|
|
756
|
+
refreshPairingQR = () => void renderer.refresh();
|
|
748
757
|
let qrMs = qrTimeout || 60000; // time to let a QR live
|
|
749
758
|
const genPairQR = () => {
|
|
750
759
|
if (!ws.isOpen) {
|
|
751
760
|
return;
|
|
752
761
|
}
|
|
753
|
-
|
|
754
|
-
if (!refNode) {
|
|
762
|
+
if (!renderer.next()) {
|
|
755
763
|
void end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));
|
|
756
764
|
return;
|
|
757
765
|
}
|
|
758
|
-
const ref = refNode.content.toString('utf-8');
|
|
759
|
-
const qr = buildPairingQRData(ref, noiseKeyB64, identityKeyB64, advB64, browser);
|
|
760
|
-
ev.emit('connection.update', { qr });
|
|
761
766
|
qrTimer = setTimeout(genPairQR, qrMs);
|
|
762
767
|
qrMs = qrTimeout || 20000; // shorter subsequent qrs
|
|
763
768
|
};
|
|
764
769
|
genPairQR();
|
|
765
770
|
});
|
|
771
|
+
ws.on('CB:notification,type:companion_reg_refresh', node => {
|
|
772
|
+
handleCompanionRegRefresh(node, {
|
|
773
|
+
creds,
|
|
774
|
+
emitCredsUpdate: update => ev.emit('creds.update', update),
|
|
775
|
+
refreshQR: () => refreshPairingQR?.(),
|
|
776
|
+
logger
|
|
777
|
+
});
|
|
778
|
+
});
|
|
766
779
|
// device paired for the first time
|
|
767
780
|
// if device pairs successfully, the server asks to restart the connection
|
|
768
781
|
ws.on('CB:iq,,pair-success', async (stanza) => {
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
11
|
* from this source without explicit written permission.
|
|
12
12
|
*/
|
|
13
|
+
import { randomBytes } from 'crypto';
|
|
14
|
+
import { getBinaryNodeChild } from '../WABinary/index.js';
|
|
13
15
|
export const CompanionWebClientType = {
|
|
14
16
|
UNKNOWN: 0,
|
|
15
17
|
CHROME: 1,
|
|
@@ -30,6 +32,16 @@ const BROWSER_TO_COMPANION_WEB_CLIENT = {
|
|
|
30
32
|
Opera: CompanionWebClientType.OPERA,
|
|
31
33
|
Safari: CompanionWebClientType.SAFARI
|
|
32
34
|
};
|
|
35
|
+
const DEFAULT_PAIRING_CODE_BROWSER_PLATFORM = { id: '1', displayName: 'Chrome' };
|
|
36
|
+
const PAIRING_CODE_BROWSER_PLATFORM = {
|
|
37
|
+
Chrome: DEFAULT_PAIRING_CODE_BROWSER_PLATFORM,
|
|
38
|
+
Firefox: { id: '2', displayName: 'Firefox' },
|
|
39
|
+
IE: { id: '3', displayName: 'IE' },
|
|
40
|
+
Opera: { id: '4', displayName: 'Opera' },
|
|
41
|
+
Safari: { id: '5', displayName: 'Safari' },
|
|
42
|
+
Edge: { id: '6', displayName: 'Edge' }
|
|
43
|
+
};
|
|
44
|
+
const PAIRING_CODE_OS_DISPLAY = new Set(['Mac OS', 'Windows', 'Ubuntu']);
|
|
33
45
|
export const getCompanionWebClientType = ([os, browserName]) => {
|
|
34
46
|
if (browserName === 'Desktop') {
|
|
35
47
|
return os === 'Windows' ? CompanionWebClientType.UWP : CompanionWebClientType.ELECTRON;
|
|
@@ -39,6 +51,54 @@ export const getCompanionWebClientType = ([os, browserName]) => {
|
|
|
39
51
|
export const getCompanionPlatformId = (browser) => {
|
|
40
52
|
return getCompanionWebClientType(browser).toString();
|
|
41
53
|
};
|
|
54
|
+
export const getPairingCodePlatform = ([os, browserName]) => {
|
|
55
|
+
const browser = PAIRING_CODE_BROWSER_PLATFORM[browserName] || DEFAULT_PAIRING_CODE_BROWSER_PLATFORM;
|
|
56
|
+
const osDisplay = PAIRING_CODE_OS_DISPLAY.has(os) ? os : 'Mac OS';
|
|
57
|
+
return {
|
|
58
|
+
id: browser.id,
|
|
59
|
+
display: `${browser.displayName} (${osDisplay})`
|
|
60
|
+
};
|
|
61
|
+
};
|
|
42
62
|
export const buildPairingQRData = (ref, noiseKeyB64, identityKeyB64, advB64, browser) => {
|
|
43
63
|
return [ref, noiseKeyB64, identityKeyB64, advB64, getCompanionPlatformId(browser)].join(',');
|
|
44
|
-
};
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export const makePairingQRRenderer = (refs, render) => {
|
|
67
|
+
let index = 0;
|
|
68
|
+
let current;
|
|
69
|
+
return {
|
|
70
|
+
next() {
|
|
71
|
+
const ref = refs[index];
|
|
72
|
+
if (ref === undefined)
|
|
73
|
+
return false;
|
|
74
|
+
index += 1;
|
|
75
|
+
current = ref;
|
|
76
|
+
render(ref);
|
|
77
|
+
return true;
|
|
78
|
+
},
|
|
79
|
+
refresh() {
|
|
80
|
+
if (current === undefined)
|
|
81
|
+
return false;
|
|
82
|
+
render(current);
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const COMPANION_REG_REFRESH_CHILDREN = ['companion_reg_refresh', 'pair-device-rotate-qr'];
|
|
89
|
+
|
|
90
|
+
export const handleCompanionRegRefresh = (node, { creds, emitCredsUpdate, refreshQR, logger }) => {
|
|
91
|
+
if (!COMPANION_REG_REFRESH_CHILDREN.some(tag => getBinaryNodeChild(node, tag))) {
|
|
92
|
+
logger.warn({ node }, 'companion_reg_refresh carries neither expected child; ignoring');
|
|
93
|
+
return 'ignored_malformed';
|
|
94
|
+
}
|
|
95
|
+
if (creds.me) {
|
|
96
|
+
logger.debug({ id: node.attrs.id }, 'companion_reg_refresh on a registered session; keeping the adv secret');
|
|
97
|
+
return 'ignored_registered';
|
|
98
|
+
}
|
|
99
|
+
creds.advSecretKey = randomBytes(32).toString('base64');
|
|
100
|
+
emitCredsUpdate({ advSecretKey: creds.advSecretKey });
|
|
101
|
+
logger.info({ id: node.attrs.id }, 'rotated the adv secret; re-rendering the pairing QR');
|
|
102
|
+
refreshQR();
|
|
103
|
+
return 'rotated';
|
|
104
|
+
};
|
|
@@ -202,7 +202,8 @@ export const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentit
|
|
|
202
202
|
account,
|
|
203
203
|
me: { id: jid, name: bizName, lid },
|
|
204
204
|
signalIdentities: [...(signalIdentities || []), identity],
|
|
205
|
-
platform: platformNode?.attrs.name
|
|
205
|
+
platform: platformNode?.attrs.name,
|
|
206
|
+
registered: true
|
|
206
207
|
};
|
|
207
208
|
return {
|
|
208
209
|
creds: authUpdate,
|