whalibmob 5.40.34 → 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.
@@ -0,0 +1,331 @@
1
+ 'use strict';
2
+
3
+ // Linking with a passkey, the third way in beside the QR and the 8-character
4
+ // code.
5
+ //
6
+ // An account that has a passkey can ask a new companion to prove the owner is
7
+ // present with it instead of having them scan or type anything. The server
8
+ // starts it: an unpaired companion receives a WebAuthn challenge, the caller
9
+ // has an authenticator sign it, and from there the two devices agree on a key
10
+ // the same way the other paths do, with one extra check a human can read.
11
+ //
12
+ // The exchange, in order:
13
+ //
14
+ // 1. passkey_prologue_request the server pushes WebAuthn request options.
15
+ // 2. passkey_prologue we send the signed assertion, and with it a
16
+ // commitment to an ephemeral public key and a
17
+ // nonce we keep to ourselves for now.
18
+ // 3. crsc_continuation the primary answers with its own ephemeral
19
+ // key and nonce.
20
+ // 4. companion_nonce we reveal the nonce, so the primary can check
21
+ // it against the commitment from step 2. Both
22
+ // sides now derive the same short code, which
23
+ // the owner compares by eye.
24
+ // 5. encrypted_pairing_request our noise key, identity key and adv secret,
25
+ // encrypted under the key from the exchange.
26
+ // 6. pair-success as on every other path.
27
+ //
28
+ // The commitment is what makes the code worth comparing: neither side can pick
29
+ // its nonce after seeing the other's, so a matching code means nobody sat in
30
+ // the middle swapping keys.
31
+ //
32
+ // Nothing here talks to the network or to an authenticator. These are the
33
+ // encodings and derivations; the client drives them.
34
+
35
+ const crypto = require('crypto');
36
+ const { hkdfSha256 } = require('./hkdf');
37
+ const curveJs = require('./curve');
38
+ const { CROCKFORD_CHARACTERS, bytesToCrockford, stripKeyPrefix } = require('./PairingCode');
39
+
40
+ const HANDOFF_INFO = 'shortcake-passkey-handoff-v1';
41
+ const ENCRYPTION_INFO = 'Pairing Information Encryption Key';
42
+ // A handoff key proves this client was the one showing the QR a moment ago.
43
+ // It is only honoured for a short while after the request that minted it.
44
+ const HANDOFF_TTL_MS = 5 * 60 * 1000;
45
+
46
+ // ─── minimal protobuf ────────────────────────────────────────────────────────
47
+ //
48
+ // Six messages, each two or three fields wide. A reader and a writer are
49
+ // cheaper than a schema runtime, as everywhere else in the library.
50
+
51
+ function varint(n) {
52
+ const out = [];
53
+ let v = n;
54
+ do {
55
+ let b = v % 128;
56
+ v = Math.floor(v / 128);
57
+ if (v) b |= 0x80;
58
+ out.push(b);
59
+ } while (v);
60
+ return Buffer.from(out);
61
+ }
62
+
63
+ function bytesField(num, buf) {
64
+ const b = Buffer.isBuffer(buf) ? buf : Buffer.from(buf);
65
+ return Buffer.concat([varint((num << 3) | 2), varint(b.length), b]);
66
+ }
67
+
68
+ function varintField(num, value) {
69
+ return Buffer.concat([varint((num << 3) | 0), varint(value)]);
70
+ }
71
+
72
+ function readFields(buf) {
73
+ const fields = {};
74
+ let pos = 0;
75
+ const readVarint = () => {
76
+ let v = 0, shift = 0;
77
+ for (;;) {
78
+ if (pos >= buf.length) throw new Error('truncated protobuf');
79
+ const b = buf[pos++];
80
+ v += (b & 0x7f) * Math.pow(2, shift);
81
+ if (!(b & 0x80)) return v;
82
+ shift += 7;
83
+ }
84
+ };
85
+ while (pos < buf.length) {
86
+ const tag = readVarint();
87
+ const num = Math.floor(tag / 8);
88
+ const wire = tag & 7;
89
+ if (wire === 0) {
90
+ fields[num] = readVarint();
91
+ } else if (wire === 2) {
92
+ const len = readVarint();
93
+ if (pos + len > buf.length) throw new Error('truncated protobuf');
94
+ fields[num] = buf.slice(pos, pos + len);
95
+ pos += len;
96
+ } else if (wire === 5) {
97
+ pos += 4;
98
+ } else if (wire === 1) {
99
+ pos += 8;
100
+ } else {
101
+ throw new Error('unsupported protobuf wire type ' + wire);
102
+ }
103
+ }
104
+ return fields;
105
+ }
106
+
107
+ // CompanionEphemeralIdentity { publicKey = 1, deviceType = 2, ref = 3 }
108
+ function encodeCompanionEphemeralIdentity(o) {
109
+ return Buffer.concat([
110
+ bytesField(1, o.publicKey),
111
+ varintField(2, o.deviceType || 0),
112
+ bytesField(3, Buffer.from(String(o.ref), 'utf8'))
113
+ ]);
114
+ }
115
+
116
+ // ProloguePayload { companionEphemeralIdentity = 1, commitment = 2 { hash = 1 } }
117
+ function encodeProloguePayload(identity, commitmentHash) {
118
+ return Buffer.concat([
119
+ bytesField(1, identity),
120
+ bytesField(2, bytesField(1, commitmentHash))
121
+ ]);
122
+ }
123
+
124
+ // PrimaryEphemeralIdentity { publicKey = 1, nonce = 2 }
125
+ function decodePrimaryEphemeralIdentity(buf) {
126
+ const f = readFields(Buffer.from(buf));
127
+ const publicKey = f[1], nonce = f[2];
128
+ if (!Buffer.isBuffer(publicKey) || publicKey.length !== 32) {
129
+ throw new Error('primary ephemeral identity: unexpected public key length ' +
130
+ (Buffer.isBuffer(publicKey) ? publicKey.length : 0));
131
+ }
132
+ if (!Buffer.isBuffer(nonce) || nonce.length !== 32) {
133
+ throw new Error('primary ephemeral identity: unexpected nonce length ' +
134
+ (Buffer.isBuffer(nonce) ? nonce.length : 0));
135
+ }
136
+ return { publicKey, nonce };
137
+ }
138
+
139
+ // PairingRequest { companionPublicKey = 1, companionIdentityKey = 2, advSecret = 3 }
140
+ function encodePairingRequest(o) {
141
+ return Buffer.concat([
142
+ bytesField(1, o.companionPublicKey),
143
+ bytesField(2, o.companionIdentityKey),
144
+ bytesField(3, o.advSecret)
145
+ ]);
146
+ }
147
+
148
+ // EncryptedPairingRequest { encryptedPayload = 1, IV = 2 }
149
+ function encodeEncryptedPairingRequest(encryptedPayload, iv) {
150
+ return Buffer.concat([bytesField(1, encryptedPayload), bytesField(2, iv)]);
151
+ }
152
+
153
+ // ─── WebAuthn JSON ───────────────────────────────────────────────────────────
154
+ //
155
+ // The server speaks the JSON form of WebAuthn: binary members are base64url
156
+ // without padding, the shape PublicKeyCredential.toJSON() produces in a
157
+ // browser. Callers hand in whatever their authenticator gave them, bytes or
158
+ // base64url or plain base64, and it is normalised on the way out.
159
+
160
+ function toBytes(value, what) {
161
+ if (value == null) throw new Error('passkey response: ' + what + ' is missing');
162
+ if (Buffer.isBuffer(value)) return value;
163
+ if (value instanceof ArrayBuffer) return Buffer.from(value);
164
+ if (ArrayBuffer.isView(value)) return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
165
+ if (typeof value === 'string') {
166
+ if (!/^[A-Za-z0-9+/_-]*={0,2}$/.test(value)) {
167
+ throw new Error('passkey response: ' + what + ' is not base64');
168
+ }
169
+ return Buffer.from(value.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
170
+ }
171
+ throw new Error('passkey response: ' + what + ' must be bytes or a base64 string');
172
+ }
173
+
174
+ const b64url = (buf) => Buffer.from(buf).toString('base64url');
175
+
176
+ /**
177
+ * Normalise an authenticator's assertion into what goes on the wire.
178
+ *
179
+ * @param {object} response { id, rawId, type, response: { clientDataJSON,
180
+ * authenticatorData, signature, userHandle? } }
181
+ * @returns {{credentialId: Buffer, json: Buffer}}
182
+ */
183
+ function encodeWebAuthnResponse(response) {
184
+ if (!response || typeof response !== 'object') {
185
+ throw new Error('passkey response: an assertion object is required');
186
+ }
187
+ const inner = response.response;
188
+ if (!inner || typeof inner !== 'object') {
189
+ throw new Error('passkey response: response.response is missing');
190
+ }
191
+ const rawId = toBytes(response.rawId != null ? response.rawId : response.id, 'rawId');
192
+ if (!rawId.length) throw new Error('passkey response: rawId is empty');
193
+
194
+ const body = {
195
+ id: typeof response.id === 'string' && response.id ? response.id : b64url(rawId),
196
+ rawId: b64url(rawId),
197
+ type: response.type || 'public-key',
198
+ response: {
199
+ clientDataJSON: b64url(toBytes(inner.clientDataJSON, 'clientDataJSON')),
200
+ authenticatorData: b64url(toBytes(inner.authenticatorData, 'authenticatorData')),
201
+ signature: b64url(toBytes(inner.signature, 'signature')),
202
+ userHandle: inner.userHandle == null ? null : b64url(toBytes(inner.userHandle, 'userHandle'))
203
+ }
204
+ };
205
+ return { credentialId: rawId, json: Buffer.from(JSON.stringify(body), 'utf8') };
206
+ }
207
+
208
+ /**
209
+ * Read the request options the server pushed. They are WebAuthn request
210
+ * options in their JSON form and are handed to the caller as they came, which
211
+ * is what PublicKeyCredential.parseRequestOptionsFromJSON() takes.
212
+ */
213
+ function parseRequestOptions(content) {
214
+ if (content == null) throw new Error('passkey request: options are missing');
215
+ const text = Buffer.isBuffer(content) ? content.toString('utf8') : String(content);
216
+ let parsed;
217
+ try { parsed = JSON.parse(text); }
218
+ catch (_) { throw new Error('passkey request: options are not valid JSON'); }
219
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
220
+ throw new Error('passkey request: options are not an object');
221
+ }
222
+ if (typeof parsed.challenge !== 'string' || !parsed.challenge) {
223
+ throw new Error('passkey request: options carry no challenge');
224
+ }
225
+ return parsed;
226
+ }
227
+
228
+ // ─── derivations ─────────────────────────────────────────────────────────────
229
+
230
+ /**
231
+ * The key that ties a passkey response to the QR this client was showing.
232
+ *
233
+ * Derived from the adv secret that was in that QR, just before the secret is
234
+ * replaced. A proof under it lets the phone skip the code comparison: the owner
235
+ * already had this exact client in front of their camera.
236
+ */
237
+ function deriveHandoffKey(advSecret) {
238
+ return hkdfSha256(Buffer.from(advSecret), Buffer.alloc(32), Buffer.from(HANDOFF_INFO, 'utf8'), 32);
239
+ }
240
+
241
+ function handoffProof(handoffKey, prologuePayload) {
242
+ return crypto.createHmac('sha256', handoffKey).update(prologuePayload).digest();
243
+ }
244
+
245
+ /**
246
+ * Step 2. An ephemeral key pair, a nonce, and the payload that commits to both.
247
+ *
248
+ * The commitment is SHA-256 over the encoded identity followed by the nonce.
249
+ * The nonce stays here until the primary has answered.
250
+ *
251
+ * @param {object} o { ref, deviceType, keyPair?, nonce? } — the last two are
252
+ * for tests; real use generates them.
253
+ */
254
+ function buildPrologue(o) {
255
+ const kp = o.keyPair || (() => {
256
+ const pair = curveJs.generateKeyPair(crypto.randomBytes(32));
257
+ return { private: Buffer.from(pair.private), public: Buffer.from(pair.public) };
258
+ })();
259
+ const companionNonce = o.nonce || crypto.randomBytes(32);
260
+ const identity = encodeCompanionEphemeralIdentity({
261
+ publicKey: stripKeyPrefix(kp.public),
262
+ deviceType: o.deviceType,
263
+ ref: o.ref
264
+ });
265
+ const commitment = crypto.createHash('sha256')
266
+ .update(Buffer.concat([identity, companionNonce])).digest();
267
+ return {
268
+ keyPair: kp,
269
+ companionNonce,
270
+ prologuePayload: encodeProloguePayload(identity, commitment)
271
+ };
272
+ }
273
+
274
+ /**
275
+ * Step 4. From the primary's answer, the key the pairing request is encrypted
276
+ * under and the code both screens show.
277
+ *
278
+ * The code is five bytes: the primary's nonce XORed with a digest of our nonce
279
+ * and its public key, in the same alphabet the 8-character pairing code uses.
280
+ *
281
+ * @returns {{encryptionKey: Buffer, code: string}} code is "XXXX-XXXX"
282
+ */
283
+ function deriveContinuation(o) {
284
+ const primaryPub = Buffer.from(o.primaryPublicKey);
285
+ const sharedSecret = Buffer.from(curveJs.sharedKey(
286
+ stripKeyPrefix(o.ephemeralPrivate), stripKeyPrefix(primaryPub)));
287
+ const salt = 'Companion Pairing ' + (o.deviceType || 0) + ' with ref ' + o.ref;
288
+ const encryptionKey = hkdfSha256(
289
+ sharedSecret, Buffer.from(salt, 'utf8'), Buffer.from(ENCRYPTION_INFO, 'utf8'), 32);
290
+
291
+ const digest = crypto.createHash('sha256')
292
+ .update(Buffer.concat([Buffer.from(o.companionNonce), primaryPub])).digest();
293
+ const codeBytes = Buffer.alloc(5);
294
+ for (let i = 0; i < 5; i++) codeBytes[i] = o.primaryNonce[i] ^ digest[i];
295
+ const encoded = bytesToCrockford(codeBytes);
296
+ return { encryptionKey, code: encoded.slice(0, 4) + '-' + encoded.slice(4) };
297
+ }
298
+
299
+ /**
300
+ * Step 5. The keys the primary needs to issue our device identity, sealed with
301
+ * AES-256-GCM under the key from the exchange.
302
+ */
303
+ function buildEncryptedPairingRequest(o) {
304
+ const iv = o.iv || crypto.randomBytes(12);
305
+ const plain = encodePairingRequest({
306
+ companionPublicKey: stripKeyPrefix(o.noisePublicKey),
307
+ companionIdentityKey: stripKeyPrefix(o.identityPublicKey),
308
+ advSecret: Buffer.from(o.advSecret)
309
+ });
310
+ const cipher = crypto.createCipheriv('aes-256-gcm', o.encryptionKey, iv);
311
+ const sealed = Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()]);
312
+ return encodeEncryptedPairingRequest(sealed, iv);
313
+ }
314
+
315
+ module.exports = {
316
+ HANDOFF_TTL_MS,
317
+ CROCKFORD_CHARACTERS,
318
+ encodeCompanionEphemeralIdentity,
319
+ encodeProloguePayload,
320
+ decodePrimaryEphemeralIdentity,
321
+ encodePairingRequest,
322
+ encodeEncryptedPairingRequest,
323
+ encodeWebAuthnResponse,
324
+ parseRequestOptions,
325
+ deriveHandoffKey,
326
+ handoffProof,
327
+ buildPrologue,
328
+ deriveContinuation,
329
+ buildEncryptedPairingRequest,
330
+ readFields
331
+ };
package/lib/WebStore.js CHANGED
@@ -37,6 +37,8 @@ function createNewWebStore(phoneNumber) {
37
37
  store.registered = false;
38
38
  store.advSecretKey = null;
39
39
  store.pairingCode = null;
40
+ store.pairingRef = null;
41
+ store.lidDbMigrated = true;
40
42
  store.pairingEphemeralKeyPair = generateEphemeralKeyPair();
41
43
  store.me = null;
42
44
  store.deviceIndex = 0;
@@ -54,6 +56,10 @@ function webStoreToJson(store) {
54
56
  mode: 'web',
55
57
  advSecretKey: store.advSecretKey || null,
56
58
  pairingCode: store.pairingCode || null,
59
+ // The ref the server issued for the pending code; the notification that
60
+ // completes the exchange has to name the same one.
61
+ pairingRef: store.pairingRef || null,
62
+ lidDbMigrated: store.lidDbMigrated !== false,
57
63
  pairingEphemeralKeyPair: store.pairingEphemeralKeyPair ? {
58
64
  private: store.pairingEphemeralKeyPair.private.toString('base64'),
59
65
  public: store.pairingEphemeralKeyPair.public.toString('base64')
@@ -75,6 +81,8 @@ function webStoreFromJson(obj) {
75
81
  store.mode = 'web';
76
82
  store.advSecretKey = obj.advSecretKey || null;
77
83
  store.pairingCode = obj.pairingCode || null;
84
+ store.pairingRef = obj.pairingRef || null;
85
+ store.lidDbMigrated = obj.lidDbMigrated !== false;
78
86
  store.pairingEphemeralKeyPair = obj.pairingEphemeralKeyPair
79
87
  ? {
80
88
  private: Buffer.from(obj.pairingEphemeralKeyPair.private, 'base64'),
package/lib/webproto.js CHANGED
@@ -96,7 +96,7 @@ function encodeHistorySyncConfig(opts) {
96
96
  const parts = [
97
97
  varintField(3, opts.storageQuotaMb != null ? opts.storageQuotaMb : 10240),
98
98
  boolField(4, opts.inlineInitialPayloadInE2EeMsg !== false),
99
- boolField(6, !!opts.supportCallLogHistory),
99
+ boolField(6, opts.supportCallLogHistory !== false),
100
100
  boolField(7, opts.supportBotUserAgentChatHistory !== false),
101
101
  boolField(8, opts.supportCagReactionsAndPolls !== false),
102
102
  boolField(9, opts.supportBizHostedMsg !== false),
@@ -104,7 +104,11 @@ function encodeHistorySyncConfig(opts) {
104
104
  boolField(11, opts.supportHostedGroupMsg !== false),
105
105
  boolField(12, opts.supportFbidBotChatHistory !== false),
106
106
  boolField(14, opts.supportMessageAssociation !== false),
107
- boolField(15, !!opts.supportGroupHistory)
107
+ boolField(15, opts.supportGroupHistory !== false),
108
+ // How far back the primary sends thumbnails with the messages it syncs.
109
+ varintField(19, opts.thumbnailSyncDaysLimit != null ? opts.thumbnailSyncDaysLimit : 60),
110
+ boolField(21, opts.supportManusHistory !== false),
111
+ boolField(22, opts.supportHatchHistory !== false)
108
112
  ];
109
113
  if (opts.fullSyncDaysLimit) parts.unshift(varintField(1, opts.fullSyncDaysLimit));
110
114
  if (opts.fullSyncSizeMbLimit) parts.unshift(varintField(2, opts.fullSyncSizeMbLimit));
@@ -200,7 +204,7 @@ function encodeDevicePairingData(o) {
200
204
  // Field numbers, straight off the schema:
201
205
  // 1 username · 3 passive · 5 userAgent · 6 webInfo · 7 pushName
202
206
  // 12 connectType · 13 connectReason · 18 device · 19 devicePairingData
203
- // 33 pull
207
+ // 24 lc · 33 pull · 41 lidDbMigrated
204
208
 
205
209
  const CONNECT_TYPE_WIFI_UNKNOWN = 1;
206
210
  const CONNECT_REASON_USER_ACTIVATED = 1;
@@ -263,7 +267,12 @@ function encodeCompanionLoginPayload(opts) {
263
267
  ...commonWebPayload(opts),
264
268
  boolField(3, true), // passive
265
269
  boolField(33, true), // pull
266
- varintField(18, opts.device || 0)
270
+ varintField(18, opts.device || 0),
271
+ varintField(24, 1), // lc
272
+ // Tells the server this client keeps its chats by LID, which is how the
273
+ // account's own devices are addressed now. A caller whose storage is still
274
+ // keyed by phone number can say so with lidDbMigrated: false.
275
+ boolField(41, opts.lidDbMigrated !== false)
267
276
  ]);
268
277
  }
269
278
 
package/llms.txt CHANGED
@@ -101,7 +101,8 @@ async function main() {
101
101
  client.on('message', (msg) => console.log(msg.from, msg.decoded && msg.decoded.text));
102
102
 
103
103
  await client.connectWeb('40712345678', { syncFullHistory: true });
104
- await client.requestPairingCode('40712345678'); // first run only; or listen for 'qr'
104
+ await client.requestPairingCode('40712345678'); // first run only; or listen for 'qr',
105
+ // or 'passkey_request' on an account with a passkey
105
106
  }
106
107
 
107
108
  main().catch((err) => { console.error(err.message || err); process.exit(1); });
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "whalibmob",
3
- "version": "5.40.34",
3
+ "version": "5.40.35",
4
4
  "description": "Node.js library for WhatsApp — register a number over SMS, or link as a companion by QR. Signal E2E encryption, media, groups, channels.",
5
5
  "author": "Kunboruto20",
6
6
  "main": "index.js",
7
7
  "types": "index.d.ts",
8
8
  "bin": {
9
- "wa": "cli.js"
9
+ "wa": "./cli.js"
10
10
  },
11
11
  "files": [
12
12
  "index.js",
@@ -58,7 +58,7 @@
58
58
  ],
59
59
  "repository": {
60
60
  "type": "git",
61
- "url": "git+https://github.com/Kunboruto20/whalibmob.git"
61
+ "url": "https://github.com/Kunboruto20/whalibmob.git"
62
62
  },
63
63
  "homepage": "https://github.com/Kunboruto20/whalibmob#readme",
64
64
  "bugs": {
@@ -78,8 +78,8 @@
78
78
  },
79
79
  "optionalDependencies": {
80
80
  "jimp": "^1.6.0",
81
- "qrcode-terminal": "^0.12.0",
82
- "socks": "^2.8.9"
81
+ "socks": "^2.8.9",
82
+ "qrcode-terminal": "^0.12.0"
83
83
  },
84
84
  "devDependencies": {
85
85
  "@types/node": "^22.0.0",