whalibmob 5.40.33 → 5.40.35
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 +5 -4
- package/cli.js +7 -0
- package/docs/linking.md +79 -9
- package/index.d.ts +73 -1
- package/index.js +2 -0
- package/lib/Client.js +398 -9
- package/lib/CompanionPairing.js +47 -8
- package/lib/PasskeyPairing.js +331 -0
- package/lib/WebStore.js +8 -0
- package/lib/webproto.js +13 -4
- package/llms.txt +2 -1
- package/package.json +5 -5
package/lib/Client.js
CHANGED
|
@@ -283,6 +283,27 @@ function _stripAdvField2(buf) {
|
|
|
283
283
|
return Buffer.from(out);
|
|
284
284
|
}
|
|
285
285
|
|
|
286
|
+
function pairingCodeError(message, code, serverCode, serverText) {
|
|
287
|
+
const err = new Error(message);
|
|
288
|
+
err.code = code;
|
|
289
|
+
if (serverCode != null) err.serverCode = serverCode;
|
|
290
|
+
if (serverText != null) err.serverText = serverText;
|
|
291
|
+
return err;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// The server's own address, whichever way the decoder handed it over.
|
|
295
|
+
function isServerJid(value) {
|
|
296
|
+
if (typeof value === 'string') return value === 's.whatsapp.net';
|
|
297
|
+
return !!value && typeof value === 'object' && value.server === 's.whatsapp.net' &&
|
|
298
|
+
!value.user && !value.device;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function passkeyError(message, code) {
|
|
302
|
+
const err = new Error(message);
|
|
303
|
+
err.code = code;
|
|
304
|
+
return err;
|
|
305
|
+
}
|
|
306
|
+
|
|
286
307
|
function findChild(node, desc) {
|
|
287
308
|
if (!node || !Array.isArray(node.content)) return null;
|
|
288
309
|
return node.content.find(c => c && c.description === desc) || null;
|
|
@@ -1607,6 +1628,16 @@ class WhalibmobClient extends EventEmitter {
|
|
|
1607
1628
|
// comma-joined fields. Off by default — the bare form is what WhatsApp Web
|
|
1608
1629
|
// itself renders and the most widely scannable.
|
|
1609
1630
|
if (opts.qrWrapUrl) this._qrWrapUrl = true;
|
|
1631
|
+
// Asked once the phone has authorised this device and before the link is
|
|
1632
|
+
// confirmed: return false to turn it down.
|
|
1633
|
+
if (opts.prePair !== undefined) {
|
|
1634
|
+
if (opts.prePair !== null && typeof opts.prePair !== 'function') {
|
|
1635
|
+
throw new Error('connectWeb: prePair must be a function');
|
|
1636
|
+
}
|
|
1637
|
+
this._prePair = opts.prePair;
|
|
1638
|
+
}
|
|
1639
|
+
if (opts.passkeyAutoConfirm !== undefined) this._passkeyAutoConfirm = !!opts.passkeyAutoConfirm;
|
|
1640
|
+
if (opts.lidDbMigrated !== undefined) this._store.lidDbMigrated = !!opts.lidDbMigrated;
|
|
1610
1641
|
|
|
1611
1642
|
// Announce the revision the web client is actually on.
|
|
1612
1643
|
//
|
|
@@ -1688,6 +1719,7 @@ class WhalibmobClient extends EventEmitter {
|
|
|
1688
1719
|
countryCode: 'US',
|
|
1689
1720
|
pushName: store.name && store.name !== 'User' ? store.name : undefined,
|
|
1690
1721
|
syncFullHistory: store.syncFullHistory !== false,
|
|
1722
|
+
lidDbMigrated: store.lidDbMigrated !== false,
|
|
1691
1723
|
registrationId: store.registrationId,
|
|
1692
1724
|
identityKeyPair: store.identityKeyPair,
|
|
1693
1725
|
signedPreKey: store.signedPreKey
|
|
@@ -1939,6 +1971,7 @@ class WhalibmobClient extends EventEmitter {
|
|
|
1939
1971
|
// used must not be able to complete a later exchange.
|
|
1940
1972
|
this._store.pairingEphemeralKeyPair = generateEphemeralKeyPair();
|
|
1941
1973
|
this._store.pairingCode = code;
|
|
1974
|
+
this._store.pairingRef = null;
|
|
1942
1975
|
this._store.phoneNumber = phone;
|
|
1943
1976
|
this._store.me = { id: phone + '@s.whatsapp.net', name: '~', lid: null };
|
|
1944
1977
|
this._saveWebStore();
|
|
@@ -1977,7 +2010,41 @@ class WhalibmobClient extends EventEmitter {
|
|
|
1977
2010
|
]);
|
|
1978
2011
|
|
|
1979
2012
|
_whaDbg('[DBG] REQUEST_PAIRING_CODE phone=' + phone + ' code=' + code);
|
|
1980
|
-
|
|
2013
|
+
|
|
2014
|
+
// Wait for the answer before handing the code out. The server validates the
|
|
2015
|
+
// request (the display name, the number, how often it has been asked) and a
|
|
2016
|
+
// refusal used to go unseen: the code was returned and shown, and typing it
|
|
2017
|
+
// into the phone could never work.
|
|
2018
|
+
const response = await this._sendIq(node);
|
|
2019
|
+
const clearPending = () => {
|
|
2020
|
+
this._store.pairingCode = null;
|
|
2021
|
+
this._store.pairingRef = null;
|
|
2022
|
+
this._saveWebStore();
|
|
2023
|
+
};
|
|
2024
|
+
if (!response) {
|
|
2025
|
+
clearPending();
|
|
2026
|
+
throw pairingCodeError('The server did not answer the pairing code request', 'PAIRING_CODE_NO_RESPONSE');
|
|
2027
|
+
}
|
|
2028
|
+
if (response.attrs && response.attrs.type === 'error') {
|
|
2029
|
+
clearPending();
|
|
2030
|
+
const errNode = findChild(response, 'error');
|
|
2031
|
+
const errCode = errNode && errNode.attrs && errNode.attrs.code != null ? String(errNode.attrs.code) : null;
|
|
2032
|
+
const errText = errNode && errNode.attrs && errNode.attrs.text ? String(errNode.attrs.text) : null;
|
|
2033
|
+
const why = errCode === '400' ? 'the request was not accepted (check the number and the browser name)'
|
|
2034
|
+
: errCode === '429' ? 'too many pairing codes were requested, wait before asking again'
|
|
2035
|
+
: (errText || 'refused');
|
|
2036
|
+
throw pairingCodeError(
|
|
2037
|
+
'The server refused the pairing code request' + (errCode ? ' (' + errCode + ')' : '') + ': ' + why,
|
|
2038
|
+
'PAIRING_CODE_REFUSED', errCode, errText);
|
|
2039
|
+
}
|
|
2040
|
+
const refBuf = getNodeContent(findChild(findChild(response, 'link_code_companion_reg'), 'link_code_pairing_ref'));
|
|
2041
|
+
if (!refBuf || !refBuf.length) {
|
|
2042
|
+
clearPending();
|
|
2043
|
+
throw pairingCodeError('The pairing code response carried no pairing ref', 'PAIRING_CODE_NO_REF');
|
|
2044
|
+
}
|
|
2045
|
+
this._store.pairingRef = refBuf.toString('utf8');
|
|
2046
|
+
this._saveWebStore();
|
|
2047
|
+
|
|
1981
2048
|
this.emit('pairing_code', { code, phoneNumber: phone });
|
|
1982
2049
|
return code;
|
|
1983
2050
|
}
|
|
@@ -2019,6 +2086,20 @@ class WhalibmobClient extends EventEmitter {
|
|
|
2019
2086
|
this.emit('error', new Error('Pairing failed: incomplete companion_finish from server'));
|
|
2020
2087
|
return;
|
|
2021
2088
|
}
|
|
2089
|
+
if (!this._store.pairingCode) {
|
|
2090
|
+
_whaDbg('[DBG] COMPANION_FINISH without a pending pairing code — ignored');
|
|
2091
|
+
return;
|
|
2092
|
+
}
|
|
2093
|
+
// The notification has to be the answer to the code we asked for. One that
|
|
2094
|
+
// names another ref belongs to an earlier request, or to nobody; deriving
|
|
2095
|
+
// adv_secret from it would replace the one the pending code is tied to.
|
|
2096
|
+
if (this._store.pairingRef && ref.toString('utf8') !== this._store.pairingRef) {
|
|
2097
|
+
// Not an error for the caller: the pending code is untouched and still
|
|
2098
|
+
// good, and a stray notification must not be able to stop a program
|
|
2099
|
+
// that has no error listener.
|
|
2100
|
+
_whaDbg('[DBG] COMPANION_FINISH pairing ref mismatch — ignored');
|
|
2101
|
+
return;
|
|
2102
|
+
}
|
|
2022
2103
|
|
|
2023
2104
|
try {
|
|
2024
2105
|
const { advSecretKey, wrappedKeyBundle } = await buildCompanionFinishBundle({
|
|
@@ -2072,16 +2153,45 @@ class WhalibmobClient extends EventEmitter {
|
|
|
2072
2153
|
* the connection right after with a 515; the reconnect logs in normally and
|
|
2073
2154
|
* that is when history starts arriving.
|
|
2074
2155
|
*/
|
|
2075
|
-
_handlePairSuccess(node) {
|
|
2156
|
+
async _handlePairSuccess(node) {
|
|
2076
2157
|
// The phone accepted a scan (or a code) — no more QRs to show.
|
|
2077
2158
|
this._stopQrRotation();
|
|
2078
|
-
const { configureSuccessfulPairing } = require('./CompanionPairing');
|
|
2159
|
+
const { configureSuccessfulPairing, buildPairErrorReply, PAIR_ERROR } = require('./CompanionPairing');
|
|
2160
|
+
const msgId = node && node.attrs && node.attrs.id;
|
|
2161
|
+
// Tell the server why, so the phone stops waiting instead of timing out.
|
|
2162
|
+
const refuse = (kind) => {
|
|
2163
|
+
if (!msgId || !this._socket) return;
|
|
2164
|
+
try { this._socket.sendNode(buildPairErrorReply(msgId, kind, BinaryNode)); }
|
|
2165
|
+
catch (e) { _whaDbg('[DBG] PAIR_ERROR reply failed: ' + (e && e.message)); }
|
|
2166
|
+
};
|
|
2167
|
+
let result = null;
|
|
2079
2168
|
try {
|
|
2080
|
-
|
|
2169
|
+
this._updateServerTimeOffset(node);
|
|
2170
|
+
result = configureSuccessfulPairing(node, {
|
|
2081
2171
|
advSecretKey: this._store.advSecretKey,
|
|
2082
2172
|
identityKeyPair: this._store.identityKeyPair
|
|
2083
2173
|
}, BinaryNode);
|
|
2084
2174
|
|
|
2175
|
+
if (typeof this._prePair === 'function') {
|
|
2176
|
+
let allowed;
|
|
2177
|
+
try {
|
|
2178
|
+
allowed = await this._prePair({
|
|
2179
|
+
jid: result.me.id, lid: result.me.lid,
|
|
2180
|
+
platform: result.platform, businessName: result.businessName
|
|
2181
|
+
});
|
|
2182
|
+
} catch (cbErr) {
|
|
2183
|
+
const err = new Error('pair-success: the prePair callback threw: ' + (cbErr && cbErr.message));
|
|
2184
|
+
err.pairError = PAIR_ERROR.INTERNAL;
|
|
2185
|
+
throw err;
|
|
2186
|
+
}
|
|
2187
|
+
if (allowed === false) {
|
|
2188
|
+
const err = new Error('pair-success: rejected locally by the prePair callback');
|
|
2189
|
+
err.code = 'PAIR_REJECTED_LOCALLY';
|
|
2190
|
+
err.pairError = PAIR_ERROR.INTERNAL;
|
|
2191
|
+
throw err;
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
|
|
2085
2195
|
this._store.me = result.me;
|
|
2086
2196
|
this._store.deviceIndex = result.deviceIndex;
|
|
2087
2197
|
this._store.platform = result.platform;
|
|
@@ -2090,8 +2200,10 @@ class WhalibmobClient extends EventEmitter {
|
|
|
2090
2200
|
this._store.advIdentity = result.accountEnc;
|
|
2091
2201
|
this._store.registered = true;
|
|
2092
2202
|
this._store.pairingCode = null;
|
|
2203
|
+
this._store.pairingRef = null;
|
|
2093
2204
|
if (result.me && result.me.name) this._store.name = result.me.name;
|
|
2094
2205
|
this._saveWebStore();
|
|
2206
|
+
this._clearPasskeyState();
|
|
2095
2207
|
|
|
2096
2208
|
if (result.me && result.me.lid) {
|
|
2097
2209
|
this._myLid = result.me.lid;
|
|
@@ -2099,6 +2211,7 @@ class WhalibmobClient extends EventEmitter {
|
|
|
2099
2211
|
const pnUser = String(result.me.id).split('@')[0].split(':')[0];
|
|
2100
2212
|
this._lidToPn.set(lidUser, pnUser);
|
|
2101
2213
|
this._pnToLid.set(pnUser, lidUser);
|
|
2214
|
+
await this._trustPrimaryIdentity(lidUser, result);
|
|
2102
2215
|
}
|
|
2103
2216
|
|
|
2104
2217
|
this._socket.sendNode(result.reply);
|
|
@@ -2113,10 +2226,35 @@ class WhalibmobClient extends EventEmitter {
|
|
|
2113
2226
|
});
|
|
2114
2227
|
} catch (err) {
|
|
2115
2228
|
_whaDbg('[DBG] PAIR_SUCCESS_ERR ' + (err && err.message));
|
|
2229
|
+
refuse(err && err.pairError);
|
|
2230
|
+
this.emit('pair_error', {
|
|
2231
|
+
jid: result && result.me ? result.me.id : null,
|
|
2232
|
+
lid: result && result.me ? result.me.lid : null,
|
|
2233
|
+
platform: result ? result.platform : null,
|
|
2234
|
+
err
|
|
2235
|
+
});
|
|
2116
2236
|
this.emit('error', err);
|
|
2117
2237
|
}
|
|
2118
2238
|
}
|
|
2119
2239
|
|
|
2240
|
+
// The account signature key in a pair-success is the phone's own identity
|
|
2241
|
+
// key. Recording it as the identity of the account's device 0 means the first
|
|
2242
|
+
// session the phone opens with us is checked against the key that authorised
|
|
2243
|
+
// the link, rather than accepted from whoever answers for that address.
|
|
2244
|
+
//
|
|
2245
|
+
// Not done for a hosted account: the key that signs there is the host's.
|
|
2246
|
+
async _trustPrimaryIdentity(lidUser, result) {
|
|
2247
|
+
try {
|
|
2248
|
+
if (!lidUser || !result || result.hosted) return;
|
|
2249
|
+
const key = result.account && result.account.accountSignatureKey;
|
|
2250
|
+
const store = this._signal && this._signal.store;
|
|
2251
|
+
if (!key || key.length !== 32 || !store || typeof store.saveIdentity !== 'function') return;
|
|
2252
|
+
await store.saveIdentity(lidUser + '.0', Buffer.concat([Buffer.from([0x05]), Buffer.from(key)]));
|
|
2253
|
+
} catch (err) {
|
|
2254
|
+
_whaDbg('[DBG] PRIMARY_IDENTITY save failed: ' + (err && err.message));
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
|
|
2120
2258
|
/**
|
|
2121
2259
|
* <iq><pair-device> — the QR path.
|
|
2122
2260
|
*
|
|
@@ -2174,12 +2312,20 @@ class WhalibmobClient extends EventEmitter {
|
|
|
2174
2312
|
const { WEB_BROWSER } = require('./constants');
|
|
2175
2313
|
const noiseB64 = stripKeyPrefix(this._store.noiseKeyPair.public).toString('base64');
|
|
2176
2314
|
const identityB64 = stripKeyPrefix(this._store.identityKeyPair.public).toString('base64');
|
|
2177
|
-
const advB64 = this._store.advSecretKey;
|
|
2178
2315
|
const browser = this._store.browser || WEB_BROWSER;
|
|
2179
2316
|
const wrap = !!this._qrWrapUrl;
|
|
2180
2317
|
|
|
2181
2318
|
const queue = refs.slice();
|
|
2182
2319
|
let first = true;
|
|
2320
|
+
let current = null;
|
|
2321
|
+
|
|
2322
|
+
// The adv secret is read at the moment a QR is built, not once up front:
|
|
2323
|
+
// the server can ask for it to be replaced while the QRs are on screen.
|
|
2324
|
+
const emitQr = (ref, ttlMs) => {
|
|
2325
|
+
const qr = buildQrData(ref, noiseB64, identityB64, this._store.advSecretKey, browser, { wrap });
|
|
2326
|
+
_whaDbg('[DBG] QR emitted (ref …' + ref.slice(-6) + ', ' + queue.length + ' left)');
|
|
2327
|
+
this.emit('qr', { qr, ref, ttlMs, remaining: queue.length });
|
|
2328
|
+
};
|
|
2183
2329
|
|
|
2184
2330
|
const showNext = () => {
|
|
2185
2331
|
const ref = queue.shift();
|
|
@@ -2189,20 +2335,239 @@ class WhalibmobClient extends EventEmitter {
|
|
|
2189
2335
|
this.emit('qr_timeout');
|
|
2190
2336
|
return;
|
|
2191
2337
|
}
|
|
2192
|
-
const qr = buildQrData(ref, noiseB64, identityB64, advB64, browser, { wrap });
|
|
2193
2338
|
// 60s for the first, 20s for each after — the reference client's cadence.
|
|
2194
2339
|
const ttlMs = first ? 60000 : 20000;
|
|
2195
2340
|
first = false;
|
|
2196
|
-
|
|
2197
|
-
|
|
2341
|
+
current = { ref, ttlMs, until: Date.now() + ttlMs };
|
|
2342
|
+
emitQr(ref, ttlMs);
|
|
2198
2343
|
this._qrTimer = setTimeout(showNext, ttlMs);
|
|
2199
2344
|
};
|
|
2200
2345
|
|
|
2346
|
+
// The QR on screen again, with the secret as it is now and the time it has
|
|
2347
|
+
// left. Its timer is not touched: the ref expires when it was going to.
|
|
2348
|
+
this._qrRefresh = () => {
|
|
2349
|
+
if (!current || !this._qrTimer) return;
|
|
2350
|
+
emitQr(current.ref, Math.max(0, current.until - Date.now()));
|
|
2351
|
+
};
|
|
2352
|
+
|
|
2201
2353
|
showNext();
|
|
2202
2354
|
}
|
|
2203
2355
|
|
|
2204
2356
|
_stopQrRotation() {
|
|
2205
2357
|
if (this._qrTimer) { clearTimeout(this._qrTimer); this._qrTimer = null; }
|
|
2358
|
+
this._qrRefresh = null;
|
|
2359
|
+
}
|
|
2360
|
+
|
|
2361
|
+
// Replace the adv secret with a fresh one.
|
|
2362
|
+
//
|
|
2363
|
+
// The secret rides in every QR and authenticates the pair-success that
|
|
2364
|
+
// follows a scan. The server asks for a new one with a companion_reg_refresh
|
|
2365
|
+
// notification; a QR built from the old one would be scanned, accepted by
|
|
2366
|
+
// the phone, and then fail here.
|
|
2367
|
+
_rotateAdvSecret(opts) {
|
|
2368
|
+
if (this._mode !== 'web' || !this._store || this._store.registered) return false;
|
|
2369
|
+
this._store.advSecretKey = crypto.randomBytes(32).toString('base64');
|
|
2370
|
+
this._saveWebStore();
|
|
2371
|
+
_whaDbg('[DBG] ADV_SECRET rotated');
|
|
2372
|
+
if (!(opts && opts.silent) && typeof this._qrRefresh === 'function') this._qrRefresh();
|
|
2373
|
+
return true;
|
|
2374
|
+
}
|
|
2375
|
+
|
|
2376
|
+
// ─── Passkey linking ──────────────────────────────────────────────────────
|
|
2377
|
+
//
|
|
2378
|
+
// See PasskeyPairing.js for the exchange. The server opens it; the caller
|
|
2379
|
+
// supplies the authenticator.
|
|
2380
|
+
|
|
2381
|
+
_clearPasskeyState() {
|
|
2382
|
+
this._passkeyLinking = null;
|
|
2383
|
+
this._passkeyHandoff = null;
|
|
2384
|
+
this._passkeySkipHandoffUx = false;
|
|
2385
|
+
}
|
|
2386
|
+
|
|
2387
|
+
// An <iq xmlns="md"> to the server that has to be answered. No answer and an
|
|
2388
|
+
// error answer both throw; `what` names the step in the message.
|
|
2389
|
+
async _mdIq(type, children, what) {
|
|
2390
|
+
if (!this._socket) throw passkeyError(what + ': not connected', 'PASSKEY_NOT_CONNECTED');
|
|
2391
|
+
const response = await this._sendIq(new BinaryNode('iq', {
|
|
2392
|
+
id: this._genMsgId(), to: 's.whatsapp.net', type, xmlns: 'md'
|
|
2393
|
+
}, children));
|
|
2394
|
+
if (!response) throw passkeyError(what + ': the server did not answer', 'PASSKEY_NO_RESPONSE');
|
|
2395
|
+
if (response.attrs && response.attrs.type === 'error') {
|
|
2396
|
+
const errNode = findChild(response, 'error');
|
|
2397
|
+
const code = errNode && errNode.attrs && errNode.attrs.code != null ? String(errNode.attrs.code) : null;
|
|
2398
|
+
const text = errNode && errNode.attrs && errNode.attrs.text ? String(errNode.attrs.text) : null;
|
|
2399
|
+
const err = passkeyError(what + ': refused by the server' +
|
|
2400
|
+
(code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''), 'PASSKEY_REFUSED');
|
|
2401
|
+
err.serverCode = code;
|
|
2402
|
+
err.serverText = text;
|
|
2403
|
+
throw err;
|
|
2404
|
+
}
|
|
2405
|
+
return response;
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
/**
|
|
2409
|
+
* <notification type="passkey_prologue_request"> — the account can be linked
|
|
2410
|
+
* with a passkey, and the server is asking for an assertion.
|
|
2411
|
+
*/
|
|
2412
|
+
async _handlePasskeyRequest(node) {
|
|
2413
|
+
const Passkey = require('./PasskeyPairing');
|
|
2414
|
+
let publicKey;
|
|
2415
|
+
try {
|
|
2416
|
+
try {
|
|
2417
|
+
publicKey = Passkey.parseRequestOptions(getNodeContent(findChild(node, 'passkey_request_options')));
|
|
2418
|
+
} catch (parseErr) {
|
|
2419
|
+
// The push did not carry usable options; they can be asked for.
|
|
2420
|
+
_whaDbg('[DBG] PASSKEY request unreadable (' + parseErr.message + ') — fetching options');
|
|
2421
|
+
const resp = await this._mdIq('get', [new BinaryNode('passkey_request_options', {}, null)],
|
|
2422
|
+
'passkey request options');
|
|
2423
|
+
publicKey = Passkey.parseRequestOptions(getNodeContent(findChild(resp, 'passkey_request_options')));
|
|
2424
|
+
}
|
|
2425
|
+
} catch (err) {
|
|
2426
|
+
_whaDbg('[DBG] PASSKEY request failed: ' + (err && err.message));
|
|
2427
|
+
this.emit('passkey_error', { err, continuation: false });
|
|
2428
|
+
return;
|
|
2429
|
+
}
|
|
2430
|
+
if (this._store.registered) return;
|
|
2431
|
+
|
|
2432
|
+
// Keep a key derived from the secret the QR was showing, then replace the
|
|
2433
|
+
// secret. The first proves to the phone that the passkey answer comes from
|
|
2434
|
+
// the client it was looking at; the second is what pair-success will be
|
|
2435
|
+
// verified under.
|
|
2436
|
+
if (this._store.advSecretKey) {
|
|
2437
|
+
this._passkeyHandoff = {
|
|
2438
|
+
key: Passkey.deriveHandoffKey(Buffer.from(this._store.advSecretKey, 'base64')),
|
|
2439
|
+
at: Date.now()
|
|
2440
|
+
};
|
|
2441
|
+
}
|
|
2442
|
+
// Not silently: a QR still on screen carries the old secret, and scanning
|
|
2443
|
+
// it would be accepted by the phone and fail here. It is drawn again with
|
|
2444
|
+
// the new one, so the owner can still choose to scan.
|
|
2445
|
+
this._rotateAdvSecret();
|
|
2446
|
+
_whaDbg('[DBG] PASSKEY request received');
|
|
2447
|
+
this.emit('passkey_request', { publicKey });
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
/**
|
|
2451
|
+
* Answer a `passkey_request` with the assertion an authenticator produced.
|
|
2452
|
+
*
|
|
2453
|
+
* `response` is a WebAuthn assertion: `{ id, rawId, type, response: {
|
|
2454
|
+
* clientDataJSON, authenticatorData, signature, userHandle? } }`, with the
|
|
2455
|
+
* binary members as bytes or base64url — what `credential.toJSON()` returns
|
|
2456
|
+
* in a browser. Resolves once the server has taken it; `passkey_confirmation`
|
|
2457
|
+
* follows.
|
|
2458
|
+
*/
|
|
2459
|
+
async sendPasskeyResponse(response) {
|
|
2460
|
+
if (this._mode !== 'web') {
|
|
2461
|
+
throw passkeyError('sendPasskeyResponse is only available in web mode — call connectWeb() first', 'PASSKEY_WRONG_MODE');
|
|
2462
|
+
}
|
|
2463
|
+
if (!this._socket || !this._socket.secured) {
|
|
2464
|
+
throw passkeyError('Not connected — call connectWeb() before answering a passkey request', 'PASSKEY_NOT_CONNECTED');
|
|
2465
|
+
}
|
|
2466
|
+
if (this._store.registered) {
|
|
2467
|
+
throw passkeyError('This session is already linked', 'PASSKEY_ALREADY_LINKED');
|
|
2468
|
+
}
|
|
2469
|
+
const Passkey = require('./PasskeyPairing');
|
|
2470
|
+
const { platformTypeFor } = require('./webproto');
|
|
2471
|
+
const { credentialId, json } = Passkey.encodeWebAuthnResponse(response);
|
|
2472
|
+
|
|
2473
|
+
const refResp = await this._mdIq('get', [new BinaryNode('ref', {}, null)], 'passkey companion ref');
|
|
2474
|
+
const refBuf = getNodeContent(findChild(refResp, 'ref'));
|
|
2475
|
+
if (!refBuf || !refBuf.length) {
|
|
2476
|
+
throw passkeyError('passkey companion ref: the answer carried no ref', 'PASSKEY_NO_REF');
|
|
2477
|
+
}
|
|
2478
|
+
const ref = refBuf.toString('utf8');
|
|
2479
|
+
const deviceType = platformTypeFor((this._store.browser || [])[1]);
|
|
2480
|
+
const prologue = Passkey.buildPrologue({ ref, deviceType });
|
|
2481
|
+
|
|
2482
|
+
this._passkeyLinking = {
|
|
2483
|
+
keyPair: prologue.keyPair,
|
|
2484
|
+
companionNonce: prologue.companionNonce,
|
|
2485
|
+
ref,
|
|
2486
|
+
deviceType,
|
|
2487
|
+
encryptionKey: null
|
|
2488
|
+
};
|
|
2489
|
+
|
|
2490
|
+
const children = [
|
|
2491
|
+
new BinaryNode('credential_id', {}, credentialId),
|
|
2492
|
+
new BinaryNode('webauthn_assertion', {}, json),
|
|
2493
|
+
new BinaryNode('prologue_payload', {}, prologue.prologuePayload)
|
|
2494
|
+
];
|
|
2495
|
+
const handoff = this._passkeyHandoff;
|
|
2496
|
+
if (handoff && Date.now() - handoff.at < Passkey.HANDOFF_TTL_MS) {
|
|
2497
|
+
children.push(new BinaryNode('pairing_handoff_proof', {},
|
|
2498
|
+
Passkey.handoffProof(handoff.key, prologue.prologuePayload)));
|
|
2499
|
+
this._passkeySkipHandoffUx = true;
|
|
2500
|
+
} else {
|
|
2501
|
+
this._passkeySkipHandoffUx = false;
|
|
2502
|
+
}
|
|
2503
|
+
|
|
2504
|
+
await this._mdIq('set', [new BinaryNode('passkey_prologue', {}, children)], 'passkey prologue');
|
|
2505
|
+
this._passkeyHandoff = null;
|
|
2506
|
+
_whaDbg('[DBG] PASSKEY prologue accepted');
|
|
2507
|
+
}
|
|
2508
|
+
|
|
2509
|
+
/**
|
|
2510
|
+
* <notification type="crsc_continuation"> — the primary's half of the
|
|
2511
|
+
* exchange. Reveal our nonce, derive the key and the code.
|
|
2512
|
+
*/
|
|
2513
|
+
async _handlePasskeyContinuation(node) {
|
|
2514
|
+
const Passkey = require('./PasskeyPairing');
|
|
2515
|
+
try {
|
|
2516
|
+
const cache = this._passkeyLinking;
|
|
2517
|
+
if (!cache) throw passkeyError('passkey continuation without a pending passkey response', 'PASSKEY_NOT_PENDING');
|
|
2518
|
+
const identityBuf = getNodeContent(findChild(node, 'primary_ephemeral_identity'));
|
|
2519
|
+
if (!identityBuf) throw passkeyError('passkey continuation carries no primary identity', 'PASSKEY_BAD_CONTINUATION');
|
|
2520
|
+
const primary = Passkey.decodePrimaryEphemeralIdentity(identityBuf);
|
|
2521
|
+
|
|
2522
|
+
await this._mdIq('set', [new BinaryNode('companion_nonce', {}, cache.companionNonce)],
|
|
2523
|
+
'passkey companion nonce');
|
|
2524
|
+
|
|
2525
|
+
const derived = Passkey.deriveContinuation({
|
|
2526
|
+
ephemeralPrivate: cache.keyPair.private,
|
|
2527
|
+
primaryPublicKey: primary.publicKey,
|
|
2528
|
+
primaryNonce: primary.nonce,
|
|
2529
|
+
companionNonce: cache.companionNonce,
|
|
2530
|
+
deviceType: cache.deviceType,
|
|
2531
|
+
ref: cache.ref
|
|
2532
|
+
});
|
|
2533
|
+
// The cache can have been dropped while the nonce was on its way.
|
|
2534
|
+
if (this._passkeyLinking !== cache) return;
|
|
2535
|
+
cache.encryptionKey = derived.encryptionKey;
|
|
2536
|
+
|
|
2537
|
+
const skipHandoffUx = !!this._passkeySkipHandoffUx;
|
|
2538
|
+
const auto = skipHandoffUx && this._passkeyAutoConfirm !== false;
|
|
2539
|
+
_whaDbg('[DBG] PASSKEY confirmation ready (skipHandoffUx=' + skipHandoffUx + ')');
|
|
2540
|
+
this.emit('passkey_confirmation', { code: derived.code, skipHandoffUx, autoConfirmed: auto });
|
|
2541
|
+
// The phone already saw this client's QR, so there is nothing for the
|
|
2542
|
+
// owner to compare.
|
|
2543
|
+
if (auto) await this.sendPasskeyConfirmation();
|
|
2544
|
+
} catch (err) {
|
|
2545
|
+
_whaDbg('[DBG] PASSKEY continuation failed: ' + (err && err.message));
|
|
2546
|
+
this.emit('passkey_error', { err, continuation: true });
|
|
2547
|
+
}
|
|
2548
|
+
}
|
|
2549
|
+
|
|
2550
|
+
/**
|
|
2551
|
+
* Finish a passkey link, once the owner has confirmed that the code from
|
|
2552
|
+
* `passkey_confirmation` matches the one on their phone. `paired` follows.
|
|
2553
|
+
*/
|
|
2554
|
+
async sendPasskeyConfirmation() {
|
|
2555
|
+
const cache = this._passkeyLinking;
|
|
2556
|
+
if (!cache) throw passkeyError('No passkey link is in progress', 'PASSKEY_NOT_PENDING');
|
|
2557
|
+
if (!cache.encryptionKey) {
|
|
2558
|
+
throw passkeyError('The passkey link has no encryption key yet — wait for passkey_confirmation', 'PASSKEY_NOT_READY');
|
|
2559
|
+
}
|
|
2560
|
+
const Passkey = require('./PasskeyPairing');
|
|
2561
|
+
const request = Passkey.buildEncryptedPairingRequest({
|
|
2562
|
+
encryptionKey: cache.encryptionKey,
|
|
2563
|
+
noisePublicKey: this._store.noiseKeyPair.public,
|
|
2564
|
+
identityPublicKey: this._store.identityKeyPair.public,
|
|
2565
|
+
advSecret: Buffer.from(this._store.advSecretKey, 'base64')
|
|
2566
|
+
});
|
|
2567
|
+
await this._mdIq('set', [new BinaryNode('encrypted_pairing_request', {}, request)],
|
|
2568
|
+
'passkey pairing request');
|
|
2569
|
+
this._passkeyLinking = null;
|
|
2570
|
+
_whaDbg('[DBG] PASSKEY pairing request accepted — awaiting pair-success');
|
|
2206
2571
|
}
|
|
2207
2572
|
|
|
2208
2573
|
/**
|
|
@@ -2290,6 +2655,7 @@ class WhalibmobClient extends EventEmitter {
|
|
|
2290
2655
|
this._reconnecting = false;
|
|
2291
2656
|
this._reconnectTry = 0;
|
|
2292
2657
|
this._stopQrRotation();
|
|
2658
|
+
this._clearPasskeyState();
|
|
2293
2659
|
this._stopTimers();
|
|
2294
2660
|
if (this._socket) {
|
|
2295
2661
|
try { this._socket.close(); } catch (_) {}
|
|
@@ -3646,7 +4012,11 @@ class WhalibmobClient extends EventEmitter {
|
|
|
3646
4012
|
// the link.
|
|
3647
4013
|
if (this._mode === 'web') {
|
|
3648
4014
|
if (type === 'set' && findChild(node, 'pair-device')) { this._handlePairDevice(node); return; }
|
|
3649
|
-
if (findChild(node, 'pair-success'))
|
|
4015
|
+
if (findChild(node, 'pair-success')) {
|
|
4016
|
+
this._handlePairSuccess(node).catch(e =>
|
|
4017
|
+
_whaDbg('[DBG] PAIR_SUCCESS handler failed: ' + (e && e.message)));
|
|
4018
|
+
return;
|
|
4019
|
+
}
|
|
3650
4020
|
}
|
|
3651
4021
|
|
|
3652
4022
|
// Resolve pending IQ
|
|
@@ -5210,6 +5580,25 @@ class WhalibmobClient extends EventEmitter {
|
|
|
5210
5580
|
}
|
|
5211
5581
|
}
|
|
5212
5582
|
|
|
5583
|
+
// The three below only mean anything to a companion that is not linked
|
|
5584
|
+
// yet, and only when they come from the server itself.
|
|
5585
|
+
if (this._mode === 'web' && this._store && !this._store.registered &&
|
|
5586
|
+
isServerJid(attrs.from)) {
|
|
5587
|
+
if (type === 'passkey_prologue_request') {
|
|
5588
|
+
this._handlePasskeyRequest(node).catch(e =>
|
|
5589
|
+
_whaDbg('[DBG] PASSKEY request handler failed: ' + (e && e.message)));
|
|
5590
|
+
} else if (type === 'crsc_continuation') {
|
|
5591
|
+
this._handlePasskeyContinuation(node).catch(e =>
|
|
5592
|
+
_whaDbg('[DBG] PASSKEY continuation handler failed: ' + (e && e.message)));
|
|
5593
|
+
} else if (type === 'companion_reg_refresh') {
|
|
5594
|
+
if (findChild(node, 'companion_reg_refresh') || findChild(node, 'pair-device-rotate-qr')) {
|
|
5595
|
+
this._rotateAdvSecret();
|
|
5596
|
+
} else {
|
|
5597
|
+
_whaDbg('[DBG] companion_reg_refresh not recognised — ignored');
|
|
5598
|
+
}
|
|
5599
|
+
}
|
|
5600
|
+
}
|
|
5601
|
+
|
|
5213
5602
|
if (type === 'md-msg-hist') {
|
|
5214
5603
|
// Server signals that history sync data is available.
|
|
5215
5604
|
// The actual encrypted notification may arrive as:
|
package/lib/CompanionPairing.js
CHANGED
|
@@ -107,6 +107,31 @@ function stripKeyPrefix(pub) {
|
|
|
107
107
|
return pub;
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
+
// What the server is told when a pair-success is turned down. It hears the
|
|
111
|
+
// reason as a code and a short word, the same pair the reference client sends,
|
|
112
|
+
// so the phone can stop waiting instead of timing out.
|
|
113
|
+
const PAIR_ERROR = {
|
|
114
|
+
HMAC: { code: 401, text: 'hmac-mismatch' },
|
|
115
|
+
SIGNATURE: { code: 401, text: 'signature-mismatch' },
|
|
116
|
+
INTERNAL: { code: 500, text: 'internal-error' }
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
function pairFailure(message, kind) {
|
|
120
|
+
const err = new Error(message);
|
|
121
|
+
err.pairError = kind;
|
|
122
|
+
return err;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The <iq type="error"> that answers a pair-success we could not accept.
|
|
127
|
+
*/
|
|
128
|
+
function buildPairErrorReply(id, kind, BinaryNode) {
|
|
129
|
+
const k = kind || PAIR_ERROR.INTERNAL;
|
|
130
|
+
return new BinaryNode('iq', { to: 's.whatsapp.net', type: 'error', id }, [
|
|
131
|
+
new BinaryNode('error', { code: String(k.code), text: k.text }, null)
|
|
132
|
+
]);
|
|
133
|
+
}
|
|
134
|
+
|
|
110
135
|
function findChild(node, desc) {
|
|
111
136
|
if (!node || !Array.isArray(node.content)) return null;
|
|
112
137
|
return node.content.find(c => c && c.description === desc) || null;
|
|
@@ -134,7 +159,7 @@ function configureSuccessfulPairing(stanza, creds, BinaryNode) {
|
|
|
134
159
|
const msgId = stanza.attrs && stanza.attrs.id;
|
|
135
160
|
|
|
136
161
|
const pairSuccess = findChild(stanza, 'pair-success');
|
|
137
|
-
if (!pairSuccess) throw
|
|
162
|
+
if (!pairSuccess) throw pairFailure('pair-success: node missing from stanza', PAIR_ERROR.INTERNAL);
|
|
138
163
|
|
|
139
164
|
const deviceIdentityNode = findChild(pairSuccess, 'device-identity');
|
|
140
165
|
const platformNode = findChild(pairSuccess, 'platform');
|
|
@@ -142,14 +167,18 @@ function configureSuccessfulPairing(stanza, creds, BinaryNode) {
|
|
|
142
167
|
const businessNode = findChild(pairSuccess, 'biz');
|
|
143
168
|
|
|
144
169
|
if (!deviceIdentityNode || !deviceNode) {
|
|
145
|
-
throw
|
|
170
|
+
throw pairFailure('pair-success: missing device-identity or device', PAIR_ERROR.INTERNAL);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (!creds || !creds.advSecretKey) {
|
|
174
|
+
throw pairFailure('pair-success: no adv secret to verify against', PAIR_ERROR.INTERNAL);
|
|
146
175
|
}
|
|
147
176
|
|
|
148
177
|
const hmacMsg = readFields(Buffer.from(deviceIdentityNode.content));
|
|
149
178
|
const details = hmacMsg[1];
|
|
150
179
|
const hmac = hmacMsg[2];
|
|
151
180
|
const accountType = hmacMsg[3];
|
|
152
|
-
if (!details || !hmac) throw
|
|
181
|
+
if (!details || !hmac) throw pairFailure('pair-success: malformed ADVSignedDeviceIdentityHMAC', PAIR_ERROR.INTERNAL);
|
|
153
182
|
|
|
154
183
|
// 1. HMAC — proves the record came from a holder of adv_secret.
|
|
155
184
|
const hmacPrefix = accountType === ADV_ENCRYPTION_TYPE_HOSTED
|
|
@@ -158,8 +187,8 @@ function configureSuccessfulPairing(stanza, creds, BinaryNode) {
|
|
|
158
187
|
const advSign = crypto.createHmac('sha256', Buffer.from(creds.advSecretKey, 'base64'))
|
|
159
188
|
.update(Buffer.concat([hmacPrefix, details]))
|
|
160
189
|
.digest();
|
|
161
|
-
if (
|
|
162
|
-
throw
|
|
190
|
+
if (hmac.length !== advSign.length || !crypto.timingSafeEqual(hmac, advSign)) {
|
|
191
|
+
throw pairFailure('pair-success: invalid account signature HMAC — pairing code mismatch', PAIR_ERROR.HMAC);
|
|
163
192
|
}
|
|
164
193
|
|
|
165
194
|
const account = readFields(details);
|
|
@@ -167,7 +196,7 @@ function configureSuccessfulPairing(stanza, creds, BinaryNode) {
|
|
|
167
196
|
const accountSignature = account[3];
|
|
168
197
|
const deviceDetails = account[1];
|
|
169
198
|
if (!accountSignatureKey || !accountSignature || !deviceDetails) {
|
|
170
|
-
throw
|
|
199
|
+
throw pairFailure('pair-success: malformed ADVSignedDeviceIdentity', PAIR_ERROR.INTERNAL);
|
|
171
200
|
}
|
|
172
201
|
|
|
173
202
|
const deviceIdentity = readFields(deviceDetails);
|
|
@@ -181,8 +210,13 @@ function configureSuccessfulPairing(stanza, creds, BinaryNode) {
|
|
|
181
210
|
? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
|
|
182
211
|
: WA_ADV_ACCOUNT_SIG_PREFIX;
|
|
183
212
|
const accountMsg = Buffer.concat([accountSigPrefix, deviceDetails, ourIdentityPub]);
|
|
184
|
-
|
|
185
|
-
|
|
213
|
+
let signatureOk = false;
|
|
214
|
+
try {
|
|
215
|
+
signatureOk = stripKeyPrefix(accountSignatureKey).length === 32 && accountSignature.length === 64 &&
|
|
216
|
+
!!curveJs.verify(stripKeyPrefix(accountSignatureKey), accountMsg, accountSignature);
|
|
217
|
+
} catch (_) { signatureOk = false; }
|
|
218
|
+
if (!signatureOk) {
|
|
219
|
+
throw pairFailure('pair-success: failed to verify account signature', PAIR_ERROR.SIGNATURE);
|
|
186
220
|
}
|
|
187
221
|
|
|
188
222
|
// 3. Counter-sign. This is the signature recipients check on our pkmsgs.
|
|
@@ -232,6 +266,9 @@ function configureSuccessfulPairing(stanza, creds, BinaryNode) {
|
|
|
232
266
|
// account signature key, since recipients need it to check our signature.
|
|
233
267
|
accountEnc: encodeSignedDeviceIdentity(signedAccount, true),
|
|
234
268
|
platform: (platformNode && platformNode.attrs && platformNode.attrs.name) || null,
|
|
269
|
+
businessName: (businessNode && businessNode.attrs && businessNode.attrs.name) || null,
|
|
270
|
+
// A hosted account's signature key is the host's, not a phone's identity.
|
|
271
|
+
hosted: deviceType === ADV_ENCRYPTION_TYPE_HOSTED || accountType === ADV_ENCRYPTION_TYPE_HOSTED,
|
|
235
272
|
deviceIndex,
|
|
236
273
|
keyIndex
|
|
237
274
|
};
|
|
@@ -239,6 +276,8 @@ function configureSuccessfulPairing(stanza, creds, BinaryNode) {
|
|
|
239
276
|
|
|
240
277
|
module.exports = {
|
|
241
278
|
configureSuccessfulPairing,
|
|
279
|
+
buildPairErrorReply,
|
|
280
|
+
PAIR_ERROR,
|
|
242
281
|
encodeSignedDeviceIdentity,
|
|
243
282
|
readFields,
|
|
244
283
|
WA_ADV_ACCOUNT_SIG_PREFIX,
|