kage-baileys 25.4.2 → 25.4.7

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.
@@ -12,6 +12,7 @@ import { BinaryInfo } from '../WAM/BinaryInfo.js';
12
12
  import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
13
  import { WebSocketClient } from './Client/index.js';
14
14
  import { executeWMexQuery } from './mex.js';
15
+ import { DEFAULT_PAIRING_CODE_TTL_MS, PAIRING_CODE_RESPONSE_GRACE_MS, buildPairingCompanionHelloNode, extractPairingReference, normalizePairingPhone } from '../Utils/pairing-code.js';
15
16
  /**
16
17
  * Connects to WA servers and performs:
17
18
  * - simple queries (no retry mechanism, wait for connection establishment)
@@ -282,6 +283,26 @@ export const makeSocket = (config) => {
282
283
  });
283
284
  connectionReady.catch(() => { });
284
285
  const socketEndHandlers = [];
286
+ const pairingCodeTimeoutMs = Math.max(30_000, Number(config.pairingCodeTimeoutMs) || DEFAULT_PAIRING_CODE_TTL_MS);
287
+ const pairingCodeMaxAgeMs = Math.min(pairingCodeTimeoutMs, DEFAULT_PAIRING_CODE_TTL_MS);
288
+ let pendingPairing;
289
+ const clearPendingPairing = ({ restore = false } = {}) => {
290
+ const pending = pendingPairing;
291
+ if (!pending) return false;
292
+ pendingPairing = undefined;
293
+ if (pending.timer) clearTimeout(pending.timer);
294
+ if (restore && !authState.creds.registered) {
295
+ const previous = pending.previous || {};
296
+ for (const key of ['me', 'pairingCode', 'pairingEphemeralKeyPair', 'pairingCodeRef', 'pairingCodeGeneratedAt']) {
297
+ if (previous[key] === undefined) delete authState.creds[key];
298
+ else authState.creds[key] = previous[key];
299
+ }
300
+ ev.emit('creds.update', authState.creds);
301
+ }
302
+ return true;
303
+ };
304
+ const cancelPairingCode = () => clearPendingPairing({ restore: true });
305
+ socketEndHandlers.push(() => clearPendingPairing({ restore: true }));
285
306
  /** log & process any unexpected errors */
286
307
  const onUnexpectedError = (err, msg) => {
287
308
  logger.error({ err }, `unexpected error in '${msg}'`);
@@ -324,9 +345,12 @@ export const makeSocket = (config) => {
324
345
  logger.trace({ handshake }, 'handshake recv from WA');
325
346
  const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
326
347
  let node;
327
- if (!creds.me) {
348
+ // A pairing-code request temporarily writes creds.me before the account is
349
+ // actually registered. Such a state must continue through registration,
350
+ // never through the normal login path on reconnect.
351
+ if (!creds.me || (!!creds.pairingCode && !creds.registered)) {
328
352
  node = generateRegistrationNode(creds, config);
329
- logger.info({ node }, 'not logged in, attempting registration...');
353
+ logger.info({ node }, 'not logged in or pairing is pending, attempting registration...');
330
354
  }
331
355
  else {
332
356
  node = generateLoginNode(creds.me.id, config);
@@ -609,63 +633,94 @@ export const makeSocket = (config) => {
609
633
  };
610
634
  const requestPairingCode = async (phoneNumber, customPairingCode) => {
611
635
  await connectionReady;
612
- const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
613
- if (customPairingCode && customPairingCode?.length !== 8) {
614
- throw new Error('Custom pairing code must be exactly 8 chars');
636
+ if (authState.creds.registered) {
637
+ throw new Boom('This session is already registered; pairing code is not required.', { statusCode: 409 });
638
+ }
639
+ if (pendingPairing) {
640
+ const secondsLeft = Math.max(0, Math.ceil((pendingPairing.expiresAt - Date.now()) / 1000));
641
+ throw new Boom('A pairing code is already pending. Complete it, wait for it to expire, or call cancelPairingCode().', {
642
+ statusCode: 409,
643
+ data: { phoneNumber: pendingPairing.phoneNumber, secondsLeft }
644
+ });
645
+ }
646
+ let normalizedNumber;
647
+ try {
648
+ normalizedNumber = normalizePairingPhone(phoneNumber);
649
+ } catch (error) {
650
+ throw new Boom(error.message, { statusCode: error.statusCode || 400, data: { phoneNumber } });
651
+ }
652
+ if (customPairingCode != null && !/^[A-Z0-9]{8}$/i.test(String(customPairingCode))) {
653
+ throw new Boom('Custom pairing code must be exactly 8 alphanumeric characters.', { statusCode: 400 });
615
654
  }
655
+
656
+ const pairingCode = customPairingCode ? String(customPairingCode).toUpperCase() : bytesToCrockford(randomBytes(5));
657
+ const previous = {
658
+ me: authState.creds.me,
659
+ pairingCode: authState.creds.pairingCode,
660
+ pairingEphemeralKeyPair: authState.creds.pairingEphemeralKeyPair,
661
+ pairingCodeRef: authState.creds.pairingCodeRef,
662
+ pairingCodeGeneratedAt: authState.creds.pairingCodeGeneratedAt
663
+ };
664
+ const generatedAt = Date.now();
665
+ authState.creds.pairingEphemeralKeyPair = Curve.generateKeyPair();
616
666
  authState.creds.pairingCode = pairingCode;
667
+ authState.creds.pairingCodeGeneratedAt = generatedAt;
668
+ delete authState.creds.pairingCodeRef;
617
669
  authState.creds.me = {
618
- id: jidEncode(phoneNumber, 's.whatsapp.net'),
670
+ id: jidEncode(normalizedNumber, 's.whatsapp.net'),
619
671
  name: '~'
620
672
  };
621
673
  ev.emit('creds.update', authState.creds);
622
- await sendNode({
623
- tag: 'iq',
624
- attrs: {
625
- to: S_WHATSAPP_NET,
626
- type: 'set',
674
+
675
+ const pending = {
676
+ phoneNumber: normalizedNumber,
677
+ expiresAt: generatedAt + pairingCodeMaxAgeMs,
678
+ previous,
679
+ timer: undefined
680
+ };
681
+ pending.timer = setTimeout(() => {
682
+ if (pendingPairing !== pending) return;
683
+ logger.info({ phoneNumber: normalizedNumber }, 'pairing code expired without being used');
684
+ clearPendingPairing({ restore: true });
685
+ }, pairingCodeMaxAgeMs + PAIRING_CODE_RESPONSE_GRACE_MS);
686
+ pending.timer.unref?.();
687
+ pendingPairing = pending;
688
+
689
+ try {
690
+ // Use an IQ query rather than sendNode(): this verifies WhatsApp accepted
691
+ // companion_hello and returned a pairing ref before exposing the code.
692
+ const companionHello = buildPairingCompanionHelloNode({
627
693
  id: generateMessageTag(),
628
- xmlns: 'md'
629
- },
630
- content: [
631
- {
632
- tag: 'link_code_companion_reg',
633
- attrs: {
634
- jid: authState.creds.me.id,
635
- stage: 'companion_hello',
636
- should_show_push_notification: 'true'
637
- },
638
- content: [
639
- {
640
- tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
641
- attrs: {},
642
- content: await generatePairingKey()
643
- },
644
- {
645
- tag: 'companion_server_auth_key_pub',
646
- attrs: {},
647
- content: authState.creds.noiseKey.public
648
- },
649
- {
650
- tag: 'companion_platform_id',
651
- attrs: {},
652
- content: getCompanionPlatformId(browser)
653
- },
654
- {
655
- tag: 'companion_platform_display',
656
- attrs: {},
657
- content: `${browser[1]} (${browser[0]})`
658
- },
659
- {
660
- tag: 'link_code_pairing_nonce',
661
- attrs: {},
662
- content: '0'
663
- }
664
- ]
665
- }
666
- ]
667
- });
668
- return authState.creds.pairingCode;
694
+ jid: authState.creds.me.id,
695
+ wrappedEphemeralPublicKey: await generatePairingKey(),
696
+ noisePublicKey: authState.creds.noiseKey.public,
697
+ platformId: getCompanionPlatformId(browser),
698
+ platformDisplay: `${browser[1]} (${browser[0]})`
699
+ });
700
+ const response = await query(companionHello, config.defaultQueryTimeoutMs ?? 60_000);
701
+
702
+ if (!response) {
703
+ throw new Boom('WhatsApp did not answer the pairing request. No code was issued.', { statusCode: DisconnectReason.timedOut });
704
+ }
705
+ const pairingRef = extractPairingReference(response);
706
+ if (!pairingRef?.length) {
707
+ throw new Boom('WhatsApp did not return link_code_pairing_ref. The pairing code was not issued.', {
708
+ statusCode: 500,
709
+ data: { response: binaryNodeToString(response) }
710
+ });
711
+ }
712
+ if (pendingPairing !== pending) {
713
+ throw new Boom('The pairing request expired before WhatsApp confirmed it.', { statusCode: DisconnectReason.timedOut });
714
+ }
715
+ authState.creds.pairingCodeRef = pairingRef;
716
+ ev.emit('creds.update', authState.creds);
717
+ logger.info({ phoneNumber: normalizedNumber, refLength: pairingRef.length }, 'pairing code registered with WhatsApp');
718
+ return authState.creds.pairingCode;
719
+ }
720
+ catch (error) {
721
+ clearPendingPairing({ restore: true });
722
+ throw error;
723
+ }
669
724
  };
670
725
  async function generatePairingKey() {
671
726
  const salt = randomBytes(32);
@@ -745,7 +800,11 @@ export const makeSocket = (config) => {
745
800
  logger.debug('pair success recv');
746
801
  try {
747
802
  updateServerTimeOffset(stanza);
803
+ clearPendingPairing();
748
804
  const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
805
+ delete updatedCreds.pairingCode;
806
+ delete updatedCreds.pairingCodeRef;
807
+ delete updatedCreds.pairingCodeGeneratedAt;
749
808
  logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
750
809
  ev.emit('creds.update', updatedCreds);
751
810
  ev.emit('connection.update', { isNewLogin: true, qr: undefined });
@@ -961,6 +1020,7 @@ export const makeSocket = (config) => {
961
1020
  digestKeyBundle,
962
1021
  rotateSignedPreKey,
963
1022
  requestPairingCode,
1023
+ cancelPairingCode,
964
1024
  updateServerTimeOffset,
965
1025
  sendUnifiedSession,
966
1026
  wamBuffer: publicWAMBuffer,
@@ -45,7 +45,7 @@ export type AccountSettings = {
45
45
  };
46
46
  export type AuthenticationCreds = SignalCreds & {
47
47
  readonly noiseKey: KeyPair;
48
- readonly pairingEphemeralKeyPair: KeyPair;
48
+ pairingEphemeralKeyPair: KeyPair;
49
49
  advSecretKey: string;
50
50
  me?: Contact;
51
51
  account?: proto.IADVSignedDeviceIdentity;
@@ -61,6 +61,10 @@ export type AuthenticationCreds = SignalCreds & {
61
61
  accountSettings: AccountSettings;
62
62
  registered: boolean;
63
63
  pairingCode: string | undefined;
64
+ /** Server-confirmed reference for the active pairing-code request. */
65
+ pairingCodeRef?: Buffer;
66
+ /** Creation time of the active pairing code, in Unix milliseconds. */
67
+ pairingCodeGeneratedAt?: number;
64
68
  lastPropHash: string | undefined;
65
69
  routingInfo: Buffer | undefined;
66
70
  additionalData?: any | undefined;
@@ -69,6 +69,8 @@ export type SocketConfig = {
69
69
  maxMsgRetryCount: number;
70
70
  /** time to wait for the generation of the next QR in ms */
71
71
  qrTimeout?: number;
72
+ /** maximum age of a pairing code in milliseconds (default: 180000) */
73
+ pairingCodeTimeoutMs?: number;
72
74
  /** provide an auth state object to maintain the auth state */
73
75
  auth: AuthenticationState;
74
76
  /** manage history processing with this control; by default will sync up everything */
@@ -50,3 +50,4 @@ export * from './html-multiplayer.js';
50
50
  export * from './newsletter-status.js';
51
51
  export * from './scheduled-message.js';
52
52
  export * from './username-validation.js';
53
+ export * from './pairing-code.js';
@@ -51,3 +51,4 @@ export * from './html-multiplayer.js';
51
51
  export * from './newsletter-status.js';
52
52
  export * from './scheduled-message.js';
53
53
  export * from './username-validation.js';
54
+ export * from './pairing-code.js';
@@ -12,3 +12,5 @@ export declare function checkNativeFlowButtons(buttons?: Array<{ name?: string }
12
12
  export declare function nativeFlowButtonsViolateConstraints(buttons?: Array<{ name?: string } | string>): boolean;
13
13
  export declare function createNativeFlowButton(name: string, params?: Record<string, unknown> | string): { name: string; buttonParamsJson: string };
14
14
  export declare function parseNativeFlowButton(button: { name?: string; buttonParamsJson: string }): Record<string, unknown>;
15
+
16
+ export declare function prepareNativeFlowMessageForRelay<T>(input: T): T;
@@ -120,6 +120,148 @@ export const checkNativeFlowButtons = buttons => {
120
120
 
121
121
  export const nativeFlowButtonsViolateConstraints = buttons => !checkNativeFlowButtons(buttons).ok;
122
122
 
123
+
124
+ /**
125
+ * Normalizes and validates Native Flow data immediately before relay.
126
+ * WhatsApp examples include messageParamsJson/messageVersion; omitting them
127
+ * may result in a message that is delivered without rendering its controls.
128
+ */
129
+ export function prepareNativeFlowMessageForRelay(input) {
130
+ let message = input?.message ?? input;
131
+ const wrapperKeys = [
132
+ 'ephemeralMessage', 'viewOnceMessage', 'viewOnceMessageV2',
133
+ 'viewOnceMessageV2Extension', 'documentWithCaptionMessage'
134
+ ];
135
+ const seen = new Set();
136
+ while (message && typeof message === 'object') {
137
+ if (seen.has(message)) throw new TypeError('Circular message wrapper in Native Flow payload');
138
+ seen.add(message);
139
+ const key = wrapperKeys.find(name => message[name]?.message);
140
+ if (!key) break;
141
+ message = message[key].message;
142
+ }
143
+
144
+ const flow = message?.interactiveMessage?.nativeFlowMessage;
145
+ if (!flow) return input;
146
+ if (!Array.isArray(flow.buttons) || flow.buttons.length === 0) {
147
+ throw new TypeError('interactiveMessage.nativeFlowMessage.buttons must contain at least one button');
148
+ }
149
+
150
+ if (typeof flow.messageParamsJson !== 'string' || !flow.messageParamsJson.trim()) {
151
+ flow.messageParamsJson = '{}';
152
+ } else {
153
+ try { JSON.parse(flow.messageParamsJson); }
154
+ catch (error) { throw new TypeError(`nativeFlowMessage.messageParamsJson is invalid JSON: ${error.message}`); }
155
+ }
156
+ if (!Number.isInteger(flow.messageVersion) || flow.messageVersion < 1) {
157
+ flow.messageVersion = 1;
158
+ }
159
+
160
+ for (const [index, button] of flow.buttons.entries()) {
161
+ if (!button || typeof button !== 'object' || typeof button.name !== 'string' || !button.name.trim()) {
162
+ throw new TypeError(`nativeFlowMessage.buttons[${index}].name is required`);
163
+ }
164
+ if (typeof button.buttonParamsJson !== 'string') {
165
+ if (button.buttonParamsJson && typeof button.buttonParamsJson === 'object' && !Array.isArray(button.buttonParamsJson)) {
166
+ button.buttonParamsJson = JSON.stringify(button.buttonParamsJson);
167
+ } else {
168
+ throw new TypeError(`nativeFlowMessage.buttons[${index}].buttonParamsJson must be a JSON string or object`);
169
+ }
170
+ }
171
+ if (Buffer.byteLength(button.buttonParamsJson, 'utf8') > 64_000) {
172
+ throw new RangeError(`nativeFlowMessage.buttons[${index}].buttonParamsJson exceeds 64 KB`);
173
+ }
174
+ let params;
175
+ try { params = JSON.parse(button.buttonParamsJson); }
176
+ catch (error) { throw new TypeError(`nativeFlowMessage.buttons[${index}].buttonParamsJson is invalid JSON: ${error.message}`); }
177
+ if (!params || typeof params !== 'object' || Array.isArray(params)) {
178
+ throw new TypeError(`nativeFlowMessage.buttons[${index}].buttonParamsJson must encode an object`);
179
+ }
180
+
181
+ if (button.name === 'review_and_pay') {
182
+ if (flow.buttons.length !== 1) {
183
+ throw new TypeError('review_and_pay must be the only button in its Native Flow message');
184
+ }
185
+ const currency = String(params.currency ?? '').toUpperCase();
186
+ if (!/^[A-Z]{3}$/.test(currency)) throw new TypeError('review_and_pay requires a three-letter currency code');
187
+ if (typeof params.reference_id !== 'string' || !params.reference_id.trim()) {
188
+ throw new TypeError('review_and_pay requires reference_id');
189
+ }
190
+ if (!['physical-goods', 'digital-goods'].includes(params.type)) {
191
+ throw new TypeError('review_and_pay type must be physical-goods or digital-goods');
192
+ }
193
+ if (!params.order || !Array.isArray(params.order.items) || params.order.items.length === 0) {
194
+ throw new TypeError('review_and_pay requires at least one order.items entry');
195
+ }
196
+
197
+ const readAmount = (amount, label, commonOffset, allowZero = false) => {
198
+ if (!amount || typeof amount !== 'object') throw new TypeError(`${label} must contain value and offset`);
199
+ const value = Number(amount.value);
200
+ const offset = Number(amount.offset);
201
+ if (!Number.isSafeInteger(value) || value < (allowZero ? 0 : 1)) {
202
+ throw new TypeError(`${label}.value must be a ${allowZero ? 'non-negative' : 'positive'} safe integer`);
203
+ }
204
+ if (!Number.isSafeInteger(offset) || offset <= 0) throw new TypeError(`${label}.offset must be a positive safe integer`);
205
+ if (commonOffset != null && offset !== commonOffset) throw new TypeError(`${label}.offset must match the order offset`);
206
+ return { value: BigInt(value), offset };
207
+ };
208
+
209
+ const total = readAmount(params.total_amount, 'total_amount');
210
+ const offset = total.offset;
211
+ let itemSum = 0n;
212
+ for (const [itemIndex, item] of params.order.items.entries()) {
213
+ if (!item || typeof item !== 'object' || typeof item.name !== 'string' || !item.name.trim()) {
214
+ throw new TypeError(`order.items[${itemIndex}].name is required`);
215
+ }
216
+ const amount = readAmount(item.amount, `order.items[${itemIndex}].amount`, offset);
217
+ const quantity = Number(item.quantity);
218
+ if (!Number.isSafeInteger(quantity) || quantity <= 0) {
219
+ throw new TypeError(`order.items[${itemIndex}].quantity must be a positive safe integer`);
220
+ }
221
+ itemSum += amount.value * BigInt(quantity);
222
+ }
223
+ if (itemSum > BigInt(Number.MAX_SAFE_INTEGER)) throw new RangeError('review_and_pay item total exceeds the safe integer range');
224
+
225
+ let subtotal;
226
+ if (params.order.subtotal == null) {
227
+ subtotal = { value: Number(itemSum), offset };
228
+ params.order.subtotal = subtotal;
229
+ } else {
230
+ const parsed = readAmount(params.order.subtotal, 'order.subtotal', offset, true);
231
+ subtotal = { value: Number(parsed.value), offset };
232
+ if (parsed.value !== itemSum) throw new TypeError('order.subtotal must equal the sum of order.items (amount × quantity)');
233
+ }
234
+
235
+ const optionalOrderAmount = (key) => {
236
+ if (params.order[key] == null) return 0n;
237
+ return readAmount(params.order[key], `order.${key}`, offset, true).value;
238
+ };
239
+ const expectedTotal = itemSum + optionalOrderAmount('tax') + optionalOrderAmount('shipping') - optionalOrderAmount('discount');
240
+ if (expectedTotal < 0n || expectedTotal !== total.value) {
241
+ throw new TypeError(`review_and_pay total_amount (${total.value}) must equal subtotal + tax + shipping - discount (${expectedTotal})`);
242
+ }
243
+
244
+ if (params.payment_settings != null && !Array.isArray(params.payment_settings)) {
245
+ throw new TypeError('review_and_pay payment_settings must be an array');
246
+ }
247
+ for (const [accountIndex, entry] of (params.payment_settings ?? []).entries()) {
248
+ const account = entry?.payment_account ?? entry?.paymentAccount;
249
+ const identifier = account?.identifier_value ?? account?.identifierValue;
250
+ if (typeof identifier !== 'string' || !identifier.trim()) {
251
+ throw new TypeError(`payment_settings[${accountIndex}] requires payment_account.identifier_value`);
252
+ }
253
+ if (/^\[[^\]]+\]$/.test(identifier.trim())) {
254
+ throw new TypeError(`payment_settings[${accountIndex}] still contains a placeholder identifier; remove it or replace it with a valid provider value`);
255
+ }
256
+ }
257
+
258
+ const normalized = JSON.stringify(params);
259
+ if (normalized !== button.buttonParamsJson) button.buttonParamsJson = normalized;
260
+ }
261
+ }
262
+ return input;
263
+ }
264
+
123
265
  export const createNativeFlowButton = (name, params = {}) => {
124
266
  if (typeof name !== 'string' || !name.trim()) throw new TypeError('Native Flow button name is required');
125
267
  if (typeof params === 'string') {
@@ -0,0 +1,14 @@
1
+ export declare const DEFAULT_PAIRING_CODE_TTL_MS: number;
2
+ export declare const PAIRING_CODE_RESPONSE_GRACE_MS: number;
3
+ export declare function normalizePairingPhone(phoneNumber: unknown): string;
4
+ export declare function isValidPairingRef(creds: Record<string, any>, receivedRef: Uint8Array | Buffer | null | undefined, now?: number, maxAgeMs?: number): boolean;
5
+
6
+ export declare function buildPairingCompanionHelloNode(options: {
7
+ id: string;
8
+ jid: string;
9
+ wrappedEphemeralPublicKey: Buffer | Uint8Array;
10
+ noisePublicKey: Buffer | Uint8Array;
11
+ platformId: string;
12
+ platformDisplay: string;
13
+ }): { tag: string; attrs: Record<string, string>; content: Array<Record<string, unknown>> };
14
+ export declare function extractPairingReference(response: unknown): Buffer | null;
@@ -0,0 +1,89 @@
1
+ /** Utilities for WhatsApp Web phone-number pairing codes. */
2
+ export const DEFAULT_PAIRING_CODE_TTL_MS = 180_000;
3
+ export const PAIRING_CODE_RESPONSE_GRACE_MS = 30_000;
4
+
5
+ export function normalizePairingPhone(phoneNumber) {
6
+ const raw = String(phoneNumber ?? '').trim();
7
+ if (!/^\+?[0-9\s().-]+$/.test(raw)) {
8
+ const error = new Error('phoneNumber must contain only digits and standard phone formatting characters.');
9
+ error.statusCode = 400;
10
+ throw error;
11
+ }
12
+ const normalized = raw.replace(/\D/g, '');
13
+ if (normalized.startsWith('0') || normalized.length < 6 || normalized.length > 15) {
14
+ const error = new Error('phoneNumber must contain 6–15 digits in international format, including country code and without +, spaces or punctuation.');
15
+ error.statusCode = 400;
16
+ throw error;
17
+ }
18
+ return normalized;
19
+ }
20
+
21
+
22
+ /** Build the exact link-code companion_hello IQ request sent after Noise is ready. */
23
+ export function buildPairingCompanionHelloNode({
24
+ id,
25
+ jid,
26
+ wrappedEphemeralPublicKey,
27
+ noisePublicKey,
28
+ platformId,
29
+ platformDisplay
30
+ } = {}) {
31
+ if (!id || typeof id !== 'string') throw new TypeError('Pairing IQ id is required.');
32
+ if (!jid || typeof jid !== 'string' || !/^[1-9]\d{5,14}@s\.whatsapp\.net$/.test(jid)) {
33
+ throw new TypeError('Pairing JID must be a valid WhatsApp phone JID in international format.');
34
+ }
35
+ const toBuffer = (value, name) => {
36
+ if (!Buffer.isBuffer(value) && !(value instanceof Uint8Array)) {
37
+ throw new TypeError(`${name} must be a Buffer or Uint8Array.`);
38
+ }
39
+ const output = Buffer.from(value);
40
+ if (!output.length) throw new TypeError(`${name} cannot be empty.`);
41
+ return output;
42
+ };
43
+ if (!platformId || typeof platformId !== 'string') throw new TypeError('Companion platform id is required.');
44
+ if (!platformDisplay || typeof platformDisplay !== 'string') throw new TypeError('Companion platform display is required.');
45
+
46
+ return {
47
+ tag: 'iq',
48
+ attrs: { to: 's.whatsapp.net', type: 'set', id, xmlns: 'md' },
49
+ content: [{
50
+ tag: 'link_code_companion_reg',
51
+ attrs: { jid, stage: 'companion_hello', should_show_push_notification: 'true' },
52
+ content: [
53
+ { tag: 'link_code_pairing_wrapped_companion_ephemeral_pub', attrs: {}, content: toBuffer(wrappedEphemeralPublicKey, 'wrappedEphemeralPublicKey') },
54
+ { tag: 'companion_server_auth_key_pub', attrs: {}, content: toBuffer(noisePublicKey, 'noisePublicKey') },
55
+ { tag: 'companion_platform_id', attrs: {}, content: platformId },
56
+ { tag: 'companion_platform_display', attrs: {}, content: platformDisplay },
57
+ // The protocol value is a single NUL byte, not ASCII '0'.
58
+ { tag: 'link_code_pairing_nonce', attrs: {}, content: Buffer.from([0]) }
59
+ ]
60
+ }]
61
+ };
62
+ }
63
+
64
+ /** Return the server-issued pairing reference, or null for an incomplete response. */
65
+ export function extractPairingReference(response) {
66
+ const registration = Array.isArray(response?.content)
67
+ ? response.content.find(child => child?.tag === 'link_code_companion_reg')
68
+ : undefined;
69
+ const reference = Array.isArray(registration?.content)
70
+ ? registration.content.find(child => child?.tag === 'link_code_pairing_ref')
71
+ : undefined;
72
+ const value = reference?.content;
73
+ if (!(Buffer.isBuffer(value) || value instanceof Uint8Array) || value.length === 0) return null;
74
+ return Buffer.from(value);
75
+ }
76
+
77
+ export function isValidPairingRef(creds, receivedRef, now = Date.now(), maxAgeMs = DEFAULT_PAIRING_CODE_TTL_MS) {
78
+ if (!creds?.pairingCode || !creds?.pairingCodeRef || !creds?.pairingEphemeralKeyPair?.private) return false;
79
+ const generatedAt = Number(creds.pairingCodeGeneratedAt);
80
+ if (!Number.isFinite(generatedAt) || generatedAt <= 0 || now < generatedAt || now - generatedAt > maxAgeMs) return false;
81
+ if (receivedRef == null) return false;
82
+ try {
83
+ const expected = Buffer.from(creds.pairingCodeRef);
84
+ const received = Buffer.from(receivedRef);
85
+ return expected.length > 0 && received.equals(expected);
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "kage-baileys",
3
3
  "type": "module",
4
- "version": "25.4.2",
5
- "description": "Kage Baileys with additive cross-fork helpers, expanded WAProto schema, Native Flow review_and_pay and guarded media diagnostics",
4
+ "version": "25.4.7",
5
+ "description": "Kage Baileys with pairing logger ReferenceError fix, validated WhatsApp pairing-code flow, Native Flow review_and_pay relay fixes, expanded WAProto schema and guarded media diagnostics",
6
6
  "keywords": [
7
7
  "whatsapp",
8
8
  "automation"
@@ -29,7 +29,10 @@
29
29
  "TEST-REPORT.md",
30
30
  "VIEWONCE-FIX-REPORT.md",
31
31
  "PROTO-SCHEMA-FIX-REPORT.md",
32
- "THIRD_PARTY_NOTICES.md"
32
+ "THIRD_PARTY_NOTICES.md",
33
+ "PAIRING-CODE-FIX-REPORT.md",
34
+ "INTEGRATION-REPORT.md",
35
+ "TEST-REPORT-25.4.6.txt"
33
36
  ],
34
37
  "scripts": {
35
38
  "build:all": "npm run check",
@@ -42,7 +45,8 @@
42
45
  "lint": "npm run check",
43
46
  "release": "release-it",
44
47
  "test": "node --test",
45
- "test:viewonce": "node --test test/media-message-guards.test.js"
48
+ "test:viewonce": "node --test test/media-message-guards.test.js",
49
+ "test:offline": "node --test test/cross-fork-helpers.test.js test/media-message-guards.test.js test/newsletter-utils.test.js test/offline-node-processor.test.js test/pairing-code.test.mjs test/proto-schema.test.js"
46
50
  },
47
51
  "dependencies": {
48
52
  "@adiwajshing/keyed-db": "^0.2.4",