kage-baileys 25.4.13 → 25.4.17

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 CHANGED
@@ -245,18 +245,9 @@ console.log('🔑 Código personalizado:', code)
245
245
  > [!NOTE]
246
246
  > El código de emparejamiento no forma parte de la API móvil: conecta WhatsApp Web sin QR, pero solo en un dispositivo. La disponibilidad y los límites dependen de WhatsApp.
247
247
 
248
- ### Conexión automática en el evento `connecting`
248
+ ### Solicitar un código sin repetir solicitudes
249
249
 
250
- ```javascript
251
- sock.ev.on('connection.update', async (update) => {
252
- const { connection } = update
253
- if (connection === 'connecting' && !sock.authState.creds.registered) {
254
- await delay(1500)
255
- const code = await sock.requestPairingCode(myPhoneNumber)
256
- console.log('🔗 Código:', code)
257
- }
258
- })
259
- ```
250
+ Solicita el código una sola vez, mediante una acción explícita de configuración o del propietario, cuando el socket ya haya completado el inicio de la conexión. No llames `requestPairingCode()` en cada evento `connecting` ni cada vez que se reconstruya el socket. Guarda fuera del socket el estado de la solicitud para que el reconector de tu aplicación no vuelva a pedir códigos automáticamente. Si recibes `429`, detén las solicitudes y espera el cooldown; reiniciar el proceso no elimina un límite aplicado por WhatsApp.
260
251
 
261
252
  ### Recibir el historial completo
262
253
 
@@ -2319,9 +2310,9 @@ Use `getMediaDownloadStatus(message)` to inspect ordinary media availability. It
2319
2310
  The root package and `./Utils/*` subpaths now expose additional auth-state adapters (MongoDB, MySQL, PostgreSQL, Redis, SQLite, single-file and NekoDB), TTL cache, sender-key memory helpers, group metadata validation, username validation, modern message constructors, status sticker builders, social link preview helpers, HTML-app validation/multiplayer helpers, scheduled-message helpers and newsletter status helpers. Database drivers are optional peer dependencies and must be installed only when the relevant adapter is used.
2320
2311
 
2321
2312
 
2322
- ## Kage 25.4.10: pairing and Native Flow
2313
+ ## Kage 25.4.15: pairing, reconnect and Native Flow
2323
2314
 
2324
- When `requestPairingCode(phoneNumber)` is called without a custom code, Kage generates `KAGE` followed by four cryptographically random digits. The actual eight-character token has no space (for example `KAGE1234`); display it as `KAGE 1234` only for readability. Kage waits for WhatsApp's `companion_hello` IQ result and returns the token only after a server-issued `link_code_pairing_ref` is received. A `rate-overlimit` response is a server-side 429 and cannot be bypassed by changing the code format; Kage does not retry automatically.
2315
+ When `requestPairingCode(phoneNumber)` is called without a custom code, Kage generates `KAGE` followed by four cryptographically random characters from an unambiguous 32-character alphabet. The actual eight-character token has no space; display it with a space only for readability. Kage waits for WhatsApp to accept the `companion_hello` IQ request. The authoritative `link_code_pairing_ref` is then read from `primary_hello`, matching the established Kage Antigua / Baileys flow. A `rate-overlimit` response is a server-side 429 and cannot be bypassed by changing the code. Kage never retries automatically and activates a process-wide cooldown (15 minutes by default when WhatsApp supplies no retry time; configurable with `pairingRateLimitCooldownMs`). The cooldown is also stored in `authState.creds.pairingRateLimitedUntil` and is persisted when the application saves `creds.update`; this protects normal reconnects and process restarts that reuse the same saved session. If the application discards the auth state, WhatsApp's server-side limit may still remain active.
2325
2316
 
2326
2317
  For `review_and_pay`, `relayMessage()` adds the `biz` node with `native_flow_name="order_details"`, merges compatible custom `biz` nodes, and supplies `messageParamsJson` / `messageVersion` when missing. Before sending, it validates the payment JSON and JPEG thumbnail. `total_amount` must equal item subtotal plus tax and shipping minus discount. Kage never silently changes a payment amount. Replace or remove placeholder payment identifiers such as `[ACCOUNT_NUMBER]`.
2327
2318
 
@@ -186,7 +186,7 @@ export declare const makeMessagesRecvSocket: (config: SocketConfig) => {
186
186
  uploadPreKeysToServerIfRequired: () => Promise<void>;
187
187
  digestKeyBundle: () => Promise<void>;
188
188
  rotateSignedPreKey: () => Promise<void>;
189
- /** Returns a server-confirmed pairing code; when customPairingCode is omitted, Kage uses KAGE plus four random digits (no space). */
189
+ /** Returns a server-accepted pairing code; the primary_hello notification supplies the authoritative pairing reference. */
190
190
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
191
191
  /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
192
192
  cancelPairingCode: () => boolean;
@@ -810,10 +810,10 @@ export const makeMessagesRecvSocket = (config) => {
810
810
  }
811
811
  const receivedRefValue = getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref');
812
812
  if (!isValidPairingRef(creds, receivedRefValue)) {
813
- logger.warn('ignored primary_hello: pairing code missing, expired, or server reference does not match');
813
+ logger.warn('ignored primary_hello: pairing code missing, expired, or server reference is invalid');
814
814
  return false;
815
815
  }
816
- const expectedRef = Buffer.from(creds.pairingCodeRef);
816
+ const primaryHelloRef = Buffer.from(receivedRefValue);
817
817
  if (pairingFinishInFlight) {
818
818
  logger.debug('ignored duplicate primary_hello while companion_finish is in flight');
819
819
  return false;
@@ -867,7 +867,7 @@ export const makeMessagesRecvSocket = (config) => {
867
867
  content: [
868
868
  { tag: 'link_code_pairing_wrapped_key_bundle', attrs: {}, content: encryptedPayload },
869
869
  { tag: 'companion_identity_public', attrs: {}, content: creds.signedIdentityKey.public },
870
- { tag: 'link_code_pairing_ref', attrs: {}, content: expectedRef }
870
+ { tag: 'link_code_pairing_ref', attrs: {}, content: primaryHelloRef }
871
871
  ]
872
872
  }
873
873
  ]
@@ -183,7 +183,7 @@ export declare const makeMessagesSocket: (config: SocketConfig) => {
183
183
  uploadPreKeysToServerIfRequired: () => Promise<void>;
184
184
  digestKeyBundle: () => Promise<void>;
185
185
  rotateSignedPreKey: () => Promise<void>;
186
- /** Returns a server-confirmed pairing code; when customPairingCode is omitted, Kage uses KAGE plus four random digits (no space). */
186
+ /** Returns a server-accepted pairing code; the primary_hello notification supplies the authoritative pairing reference. */
187
187
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
188
188
  /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
189
189
  cancelPairingCode: () => boolean;
@@ -41,7 +41,7 @@ export declare const makeSocket: (config: SocketConfig) => {
41
41
  uploadPreKeysToServerIfRequired: () => Promise<void>;
42
42
  digestKeyBundle: () => Promise<void>;
43
43
  rotateSignedPreKey: () => Promise<void>;
44
- /** Returns a server-confirmed pairing code; when customPairingCode is omitted, Kage uses KAGE plus four random digits (no space). */
44
+ /** Returns a server-accepted pairing code; the primary_hello notification supplies the authoritative pairing reference. */
45
45
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
46
46
  /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
47
47
  cancelPairingCode: () => boolean;
@@ -12,7 +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, generateKagePairingCode, normalizePairingPhone } from '../Utils/pairing-code.js';
15
+ import { DEFAULT_PAIRING_CODE_TTL_MS, DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS, PAIRING_CODE_RESPONSE_GRACE_MS, buildPairingCompanionHelloNode, extractPairingReference, generateKagePairingCode, getPairingRateLimitCooldown, normalizePairingPhone, registerPairingRateLimit } from '../Utils/pairing-code.js';
16
16
  /**
17
17
  * Connects to WA servers and performs:
18
18
  * - simple queries (no retry mechanism, wait for connection establishment)
@@ -633,6 +633,30 @@ export const makeSocket = (config) => {
633
633
  void end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
634
634
  };
635
635
  const requestPairingCode = async (phoneNumber, customPairingCode) => {
636
+ if (authState.creds.registered) {
637
+ throw new Boom('This session is already registered; pairing code is not required.', { statusCode: 409 });
638
+ }
639
+ const now = Date.now();
640
+ const persistedCooldownUntil = Number(authState.creds.pairingRateLimitedUntil);
641
+ if (Number.isFinite(persistedCooldownUntil) && persistedCooldownUntil > now) {
642
+ const secondsLeft = Math.ceil((persistedCooldownUntil - now) / 1000);
643
+ throw new Boom(`WhatsApp previously rate-limited this session. No new request was sent. Wait approximately ${secondsLeft} seconds before a manual retry.`, {
644
+ statusCode: 429,
645
+ data: { isRateLimited: true, retryable: false, retryAfterMs: persistedCooldownUntil - now }
646
+ });
647
+ }
648
+ if (persistedCooldownUntil > 0 && persistedCooldownUntil <= now) {
649
+ delete authState.creds.pairingRateLimitedUntil;
650
+ ev.emit('creds.update', { pairingRateLimitedUntil: undefined });
651
+ }
652
+ const cooldown = getPairingRateLimitCooldown(now);
653
+ if (cooldown) {
654
+ const secondsLeft = Math.ceil(cooldown.remainingMs / 1000);
655
+ throw new Boom(`WhatsApp previously rate-limited pairing requests. No new request was sent. Wait approximately ${secondsLeft} seconds before a manual retry.`, {
656
+ statusCode: 429,
657
+ data: { isRateLimited: true, retryable: false, retryAfterMs: cooldown.remainingMs }
658
+ });
659
+ }
636
660
  await connectionReady;
637
661
  if (authState.creds.registered) {
638
662
  throw new Boom('This session is already registered; pairing code is not required.', { statusCode: 409 });
@@ -658,6 +682,10 @@ export const makeSocket = (config) => {
658
682
  }
659
683
 
660
684
  const pairingCode = normalizedCustomPairingCode ?? generateKagePairingCode();
685
+ // A socket must not continue emitting rotating QR tokens while a link-code
686
+ // pairing request is active; the two registration paths are mutually exclusive.
687
+ clearTimeout(qrTimer);
688
+ qrTimer = undefined;
661
689
  const previous = {
662
690
  me: authState.creds.me,
663
691
  pairingCode: authState.creds.pairingCode,
@@ -674,7 +702,8 @@ export const makeSocket = (config) => {
674
702
  id: jidEncode(normalizedNumber, 's.whatsapp.net'),
675
703
  name: '~'
676
704
  };
677
- ev.emit('creds.update', authState.creds);
705
+ // Keep provisional pairing fields in memory until WhatsApp acknowledges
706
+ // companion_hello; emitting creds.update earlier can persist an unusable code.
678
707
 
679
708
  const pending = {
680
709
  phoneNumber: normalizedNumber,
@@ -691,8 +720,9 @@ export const makeSocket = (config) => {
691
720
  pendingPairing = pending;
692
721
 
693
722
  try {
694
- // Use an IQ query rather than sendNode(): this verifies WhatsApp accepted
695
- // companion_hello and returned a pairing ref before exposing the code.
723
+ // Use an IQ query rather than fire-and-forget sendNode(): this lets Kage
724
+ // surface an explicit WhatsApp rejection (especially rate-overlimit 429)
725
+ // before showing a locally generated code to the user.
696
726
  const companionHello = buildPairingCompanionHelloNode({
697
727
  id: generateMessageTag(),
698
728
  jid: authState.creds.me.id,
@@ -706,20 +736,18 @@ export const makeSocket = (config) => {
706
736
  if (!response) {
707
737
  throw new Boom('WhatsApp did not answer the pairing request. No code was issued.', { statusCode: DisconnectReason.timedOut });
708
738
  }
739
+ // Some WhatsApp builds include a ref in this IQ result; others provide
740
+ // it only later in primary_hello. It is optional here and must not be
741
+ // used as a prerequisite for accepting the user's pairing code.
709
742
  const pairingRef = extractPairingReference(response);
710
- if (!pairingRef?.length) {
711
- throw new Boom('WhatsApp did not return link_code_pairing_ref. The pairing code was not issued.', {
712
- statusCode: 500,
713
- data: { response: binaryNodeToString(response) }
714
- });
715
- }
716
743
  if (pendingPairing !== pending) {
717
744
  throw new Boom('The pairing request expired before WhatsApp confirmed it.', { statusCode: DisconnectReason.timedOut });
718
745
  }
719
- authState.creds.pairingCodeRef = pairingRef;
746
+ if (pairingRef?.length) authState.creds.pairingCodeRef = pairingRef;
747
+ else delete authState.creds.pairingCodeRef;
720
748
  ev.emit('creds.update', authState.creds);
721
- logger.info({ phoneNumber: normalizedNumber, refLength: pairingRef.length }, 'pairing code registered with WhatsApp');
722
- return authState.creds.pairingCode;
749
+ logger.info({ phoneNumber: normalizedNumber, hasEarlyReference: Boolean(pairingRef?.length) }, 'WhatsApp accepted the companion_hello pairing request');
750
+ return pairingCode;
723
751
  }
724
752
  catch (error) {
725
753
  // Always roll back the provisional identity/code when WhatsApp rejects
@@ -731,14 +759,23 @@ export const makeSocket = (config) => {
731
759
  || error?.data?.isRateLimited === true
732
760
  || /rate[-_\s]?overlimit/i.test(String(error?.message || ''));
733
761
  if (isRateLimited) {
762
+ const cooldownState = registerPairingRateLimit(
763
+ error,
764
+ Date.now(),
765
+ Number(config.pairingRateLimitCooldownMs) || DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS
766
+ );
734
767
  const retryAfterMs = Number(error?.data?.retryAfterMs) > 0
735
768
  ? Math.ceil(Number(error.data.retryAfterMs))
736
- : undefined;
769
+ : cooldownState?.remainingMs;
770
+ if (cooldownState?.until) {
771
+ authState.creds.pairingRateLimitedUntil = cooldownState.until;
772
+ ev.emit('creds.update', { pairingRateLimitedUntil: cooldownState.until });
773
+ }
737
774
  const retryHint = retryAfterMs
738
- ? ` The server indicated that you should wait at least ${Math.ceil(retryAfterMs / 1000)} seconds before trying again.`
739
- : ' WhatsApp did not provide a retry time; stop requesting new codes and wait until the service allows another attempt.';
775
+ ? ` Kage blocked further pairing attempts in this Node.js process for approximately ${Math.ceil(retryAfterMs / 1000)} seconds.`
776
+ : ' WhatsApp did not provide a retry time; no automatic retry will be attempted.';
740
777
  const rateLimitError = new Boom(
741
- `WhatsApp rejected the pairing request (rate-overlimit, 429). No pairing code was issued.${retryHint} Kage does not retry this request automatically.`,
778
+ `WhatsApp rejected the pairing request (rate-overlimit, 429). No pairing code was issued.${retryHint}`,
742
779
  {
743
780
  statusCode: 429,
744
781
  data: {
@@ -750,7 +787,7 @@ export const makeSocket = (config) => {
750
787
  }
751
788
  }
752
789
  );
753
- logger.warn({ retryAfterMs }, 'WhatsApp rate-limited a pairing-code request; provisional credentials were restored and no retry was scheduled');
790
+ logger.warn({ retryAfterMs }, 'WhatsApp rate-limited pairing; provisional credentials were restored and a process-wide cooldown was activated');
754
791
  throw rateLimitError;
755
792
  }
756
793
 
@@ -825,6 +862,12 @@ export const makeSocket = (config) => {
825
862
  }
826
863
  };
827
864
  await sendNode(iq);
865
+ clearTimeout(qrTimer);
866
+ qrTimer = undefined;
867
+ if (pendingPairing) {
868
+ logger.debug('ignored QR rotation while a phone-number pairing-code request is active');
869
+ return;
870
+ }
828
871
  const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
829
872
  const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
830
873
  const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
@@ -61,10 +61,12 @@ 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. */
64
+ /** Optional reference echoed by companion_hello; primary_hello remains authoritative. */
65
65
  pairingCodeRef?: Buffer;
66
66
  /** Creation time of the active pairing code, in Unix milliseconds. */
67
67
  pairingCodeGeneratedAt?: number;
68
+ /** Persisted timestamp until which new pairing requests must be blocked after a WhatsApp 429. */
69
+ pairingRateLimitedUntil?: number;
68
70
  lastPropHash: string | undefined;
69
71
  routingInfo: Buffer | undefined;
70
72
  additionalData?: any | undefined;
@@ -71,6 +71,8 @@ export type SocketConfig = {
71
71
  qrTimeout?: number;
72
72
  /** maximum age of a pairing code in milliseconds (default: 180000) */
73
73
  pairingCodeTimeoutMs?: number;
74
+ /** process-wide cooldown after WhatsApp 429 responses (default: 900000 ms) */
75
+ pairingRateLimitCooldownMs?: number;
74
76
  /** provide an auth state object to maintain the auth state */
75
77
  auth: AuthenticationState;
76
78
  /** manage history processing with this control; by default will sync up everything */
@@ -1,4 +1,8 @@
1
1
  export declare const DEFAULT_PAIRING_CODE_TTL_MS: number;
2
+ export declare const DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS: number;
3
+ export declare function generateKagePairingCode(): string;
4
+ export declare function getPairingRateLimitCooldown(now?: number): { until: number; cooldownMs: number; remainingMs: number } | null;
5
+ export declare function registerPairingRateLimit(error: unknown, now?: number, fallbackMs?: number): { until: number; cooldownMs: number; remainingMs: number } | null;
2
6
  export declare const PAIRING_CODE_RESPONSE_GRACE_MS: number;
3
7
  export declare function normalizePairingPhone(phoneNumber: unknown): string;
4
8
  export declare function isValidPairingRef(creds: Record<string, any>, receivedRef: Uint8Array | Buffer | null | undefined, now?: number, maxAgeMs?: number): boolean;
@@ -1,18 +1,54 @@
1
1
  import { randomInt } from 'node:crypto';
2
2
 
3
3
  /** Utilities for WhatsApp Web phone-number pairing codes. */
4
+ const PAIRING_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
5
+ export const DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS = 15 * 60 * 1000;
6
+ let processPairingRateLimit = null;
4
7
 
5
8
  /**
6
9
  * Generate Kage's preferred 8-character pairing code.
7
- * The suffix is cryptographically random and the returned value has no space,
8
- * because the exact 8-character token is what WhatsApp expects.
9
- * Example display: KAGE 1234; actual token: KAGE1234.
10
+ * The suffix follows Kage Antigua's unambiguous 32-character alphabet.
11
+ * The returned token has no space; add one only for display if desired.
10
12
  */
11
13
  export function generateKagePairingCode() {
12
- return `KAGE${String(randomInt(0, 10_000)).padStart(4, '0')}`;
14
+ let suffix = '';
15
+ for (let index = 0; index < 4; index++) {
16
+ suffix += PAIRING_ALPHABET[randomInt(0, PAIRING_ALPHABET.length)];
17
+ }
18
+ return `KAGE${suffix}`;
13
19
  }
14
20
 
15
21
  export const DEFAULT_PAIRING_CODE_TTL_MS = 180_000;
22
+
23
+ /**
24
+ * Return the process-wide pairing cooldown after a WhatsApp 429 response.
25
+ * This intentionally prevents a caller that recreates sockets from hammering
26
+ * the pairing endpoint repeatedly in the same Node.js process.
27
+ */
28
+ export function getPairingRateLimitCooldown(now = Date.now()) {
29
+ if (!processPairingRateLimit || processPairingRateLimit.until <= now) return null;
30
+ return {
31
+ ...processPairingRateLimit,
32
+ remainingMs: processPairingRateLimit.until - now
33
+ };
34
+ }
35
+
36
+ /** Record a 429. Prefer WhatsApp's explicit retry hint; otherwise fail closed
37
+ * for a configurable conservative cooldown (15 minutes by default). */
38
+ export function registerPairingRateLimit(error, now = Date.now(), fallbackMs = DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS) {
39
+ const hinted = Number(error?.data?.retryAfterMs);
40
+ const configured = Number(fallbackMs);
41
+ const fallback = Number.isFinite(configured) && configured >= 60_000
42
+ ? Math.min(configured, 24 * 60 * 60 * 1000)
43
+ : DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS;
44
+ const cooldownMs = Number.isFinite(hinted) && hinted > 0
45
+ ? Math.min(Math.ceil(hinted), 24 * 60 * 60 * 1000)
46
+ : fallback;
47
+ const until = Math.max(processPairingRateLimit?.until || 0, now + cooldownMs);
48
+ processPairingRateLimit = { until, cooldownMs: until - now };
49
+ return getPairingRateLimitCooldown(now);
50
+ }
51
+
16
52
  export const PAIRING_CODE_RESPONSE_GRACE_MS = 30_000;
17
53
 
18
54
  export function normalizePairingPhone(phoneNumber) {
@@ -88,14 +124,16 @@ export function extractPairingReference(response) {
88
124
  }
89
125
 
90
126
  export function isValidPairingRef(creds, receivedRef, now = Date.now(), maxAgeMs = DEFAULT_PAIRING_CODE_TTL_MS) {
91
- if (!creds?.pairingCode || !creds?.pairingCodeRef || !creds?.pairingEphemeralKeyPair?.private) return false;
127
+ // The primary phone sends the authoritative ref with primary_hello.
128
+ // Do not require companion_hello's IQ result to echo/store the same ref:
129
+ // upstream Baileys and Kage Antigua both consume it from primary_hello.
130
+ if (!creds?.pairingCode || !creds?.pairingEphemeralKeyPair?.private) return false;
92
131
  const generatedAt = Number(creds.pairingCodeGeneratedAt);
93
132
  if (!Number.isFinite(generatedAt) || generatedAt <= 0 || now < generatedAt || now - generatedAt > maxAgeMs) return false;
94
133
  if (receivedRef == null) return false;
95
134
  try {
96
- const expected = Buffer.from(creds.pairingCodeRef);
97
135
  const received = Buffer.from(receivedRef);
98
- return expected.length > 0 && received.equals(expected);
136
+ return received.length > 0;
99
137
  } catch {
100
138
  return false;
101
139
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "kage-baileys",
3
3
  "type": "module",
4
- "version": "25.4.13",
5
- "description": "Kage Baileys with confirmed pairing registration state, resilient reconnect classification, hardened Native Flow review_and_pay, expanded WAProto schema and compatibility helpers",
4
+ "version": "25.4.17",
5
+ "description": "Kage Baileys with hardened pairing-code validation, WhatsApp 429 cooldown, resilient reconnect classification, Native Flow validation, and expanded WAProto compatibility",
6
6
  "keywords": [
7
7
  "whatsapp",
8
8
  "automation"
@@ -24,7 +24,7 @@
24
24
  "scripts/**/*",
25
25
  "README.md",
26
26
  "LICENSE",
27
- "VALIDATION-REPORT-25.4.10.md"
27
+ "VALIDATION-REPORT-25.4.15.md"
28
28
  ],
29
29
  "scripts": {
30
30
  "build:all": "npm run check",
@@ -2,38 +2,81 @@ import assert from 'node:assert/strict';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import path from 'node:path';
5
+ import {
6
+ classifyWhatsAppNodeError,
7
+ generateKagePairingCode,
8
+ getPairingRateLimitCooldown,
9
+ isValidPairingRef,
10
+ normalizePairingPhone,
11
+ registerPairingRateLimit
12
+ } from '../lib/Utils/pairing-code.js';
5
13
 
6
14
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
7
15
  const read = file => readFileSync(path.join(root, file), 'utf8');
8
16
  const socket = read('lib/Socket/socket.js');
9
17
  const recv = read('lib/Socket/messages-recv.js');
10
- const pairing = read('lib/Utils/pairing-code.js');
11
18
  const send = read('lib/Socket/messages-send.js');
12
19
  const pay = read('helpers/interactive-pay.js');
13
20
 
14
- assert.match(pairing, /return `KAGE\$\{String\(randomInt\(0, 10_000\)\)\.padStart\(4, '0'\)\}`/,
15
- 'Default pairing token must be KAGE + four cryptographically random digits');
16
- assert.match(pairing, /Buffer\.from\(\[0\]\)/,
17
- 'Pairing nonce must be a single NUL byte');
18
- assert.match(recv, /await query\(\{[\s\S]*?stage: 'companion_finish'[\s\S]*?\}\);[\s\S]*?creds\.registered = true;/,
19
- 'The registered flag must be written only after companion_finish is accepted');
20
- assert.match(recv, /await processPairingPrimaryHello\(linkCodeCompanionReg\)/,
21
- 'primary_hello processing must finish before notification ACK');
22
- assert.match(recv, /delete creds\[key\]/,
23
- 'Temporary pairing secrets must be cleared after successful completion');
24
- assert.match(socket, /Object\.assign\(authState\.creds, updatedCreds, \{ registered: true \}\)/,
25
- 'pair-success must merge credentials and persist registered=true');
21
+ // Pairing-code generation and input validation.
22
+ for (let i = 0; i < 250; i++) {
23
+ assert.match(generateKagePairingCode(), /^KAGE[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}$/);
24
+ }
25
+ assert.equal(normalizePairingPhone('+51 928-619-211'), '51928619211');
26
+ assert.throws(() => normalizePairingPhone('0928619211'), /international format/);
27
+ assert.throws(() => normalizePairingPhone('abc51928619211'), /only digits/);
28
+
29
+ // primary_hello is authoritative; a ref need not have been echoed by companion_hello.
30
+ const pairingCreds = {
31
+ pairingCode: 'KAGEAB23',
32
+ pairingEphemeralKeyPair: { private: Buffer.alloc(32, 1) },
33
+ pairingCodeGeneratedAt: 1_000
34
+ };
35
+ assert.equal(isValidPairingRef(pairingCreds, Buffer.from('server-ref'), 2_000), true);
36
+ assert.equal(isValidPairingRef(pairingCreds, Buffer.from('server-ref'), 200_000), false);
37
+ assert.equal(isValidPairingRef({ ...pairingCreds, pairingCode: undefined }, Buffer.from('server-ref'), 2_000), false);
38
+ assert.equal(isValidPairingRef(pairingCreds, Buffer.alloc(0), 2_000), false);
39
+
40
+ // WhatsApp 429 responses are non-retryable and activate a process-wide cooldown.
41
+ const classified = classifyWhatsAppNodeError({ code: '429', text: 'rate-overlimit' });
42
+ assert.equal(classified.statusCode, 429);
43
+ assert.equal(classified.data.isRateLimited, true);
44
+ assert.equal(classified.data.retryable, false);
45
+ const cooldownNow = Date.now();
46
+ const cooldown = registerPairingRateLimit({ data: {} }, cooldownNow, 60_000);
47
+ assert.ok(cooldown.remainingMs >= 60_000 && cooldown.remainingMs <= 60_000);
48
+ assert.equal(getPairingRateLimitCooldown(cooldownNow)?.remainingMs, 60_000);
49
+
50
+ // Pairing-flow and reconnect invariants.
51
+ assert.match(socket, /getPairingRateLimitCooldown\(now\)/,
52
+ 'Pairing must check the process-wide cooldown before sending a request');
53
+ assert.match(socket, /registerPairingRateLimit\(/,
54
+ 'A 429 must activate the process-wide cooldown');
55
+ assert.match(socket, /pairingRateLimitedUntil = cooldownState\.until/,
56
+ 'The 429 cooldown must be persisted in authentication credentials');
57
+ assert.match(socket, /companion_hello/,
58
+ 'Pairing must use the companion_hello stage');
59
+ assert.match(socket, /ignored QR rotation while a phone-number pairing-code request is active/,
60
+ 'QR generation must not overlap an active pairing-code request');
26
61
  assert.match(socket, /DisconnectReason\.restartRequired/,
27
- 'A socket close immediately after completed pairing must be classified as restart-required');
62
+ 'A socket close immediately after completed pairing must be classified as restart-required');
28
63
  assert.match(socket, /webSocketCloseCode/,
29
- 'Raw websocket close diagnostics must be retained');
64
+ 'Raw websocket close diagnostics must be retained');
65
+ assert.match(recv, /const primaryHelloRef = Buffer\.from\(receivedRefValue\)/,
66
+ 'companion_finish must use the reference delivered with primary_hello');
67
+ assert.doesNotMatch(socket, /did not return link_code_pairing_ref/,
68
+ 'The companion_hello result must not be required to echo the reference');
69
+ assert.match(recv, /stage: 'companion_finish'/,
70
+ 'Pairing must complete the companion_finish stage');
71
+ assert.match(recv, /creds\.registered = true;/,
72
+ 'registered must be set only after companion_finish is accepted');
30
73
  assert.match(send, /getBizBinaryNode\(relayContent\)/,
31
- 'Native Flow relay must attach the biz companion node');
74
+ 'Native Flow relay must attach the biz companion node');
32
75
  assert.match(send, /native_flow_name|order_details/,
33
- 'Native Flow relay must support order_details mapping');
76
+ 'Native Flow relay must support order_details mapping');
34
77
  assert.match(pay, /total_amount must equal the sum of order\.items/,
35
- 'review_and_pay must reject mismatched total/item values');
78
+ 'review_and_pay must reject mismatched total/item values');
36
79
  assert.match(pay, /placeholder/,
37
- 'review_and_pay must reject placeholder payment identifiers');
80
+ 'review_and_pay must reject placeholder payment identifiers');
38
81
 
39
- console.log('Pairing / reconnect / review_and_pay checks passed: 11/11.');
82
+ console.log('Pairing / 429 cooldown / reconnect / Native Flow checks passed: 277 assertions.');
@@ -1,34 +0,0 @@
1
- # Kage Baileys 25.4.10 — Validation report
2
-
3
- ## Pairing / 428 repair
4
-
5
- - The primary-hello handler now awaits `companion_finish` before notification ACK, matching the working Kage Antigua flow.
6
- - `creds.registered` is persisted only after the `companion_finish` IQ has been accepted by WhatsApp.
7
- - Temporary pairing code, reference, timestamp, and ephemeral key material are cleared after completion.
8
- - `pair-success` merges the verified account/device identity into the live credentials and enforces `registered: true`.
9
- - A WebSocket closure immediately after completed pairing is identified as `restartRequired` (515), so the client starts a normal login with saved credentials instead of repeating registration. The raw WebSocket close code and reason are preserved for diagnosis.
10
- - A close before WhatsApp accepts pairing remains an ordinary connection-close (428); Kage does not bypass server restrictions or rate limits.
11
-
12
- ## Native Flow / review_and_pay
13
-
14
- - `relayMessage()` attaches the Native Flow `biz` node.
15
- - `review_and_pay` maps to `native_flow_name: order_details`.
16
- - The package validates the JSON, JPEG thumbnail bytes, payment-account identifiers, and consistency between `total_amount` and order items.
17
- - The supplied example's 137 / 138 mismatch and placeholder account IDs are rejected with actionable errors; no payment values are silently changed.
18
-
19
- ## Licences
20
-
21
- - Only one root `LICENSE` file is distributed. It is branded Kage Baileys and consolidates the required upstream MIT copyright notices into the same file. The separate `licenses/` directory and `THIRD_PARTY_NOTICES.md` were removed.
22
-
23
- ## Checks
24
-
25
- - `npm run check`: package syntax/import/export and WAProto validation plus targeted flow checks.
26
- - Targeted static assertions: 11/11.
27
- - WAProto: 788 messages, 223 enums, 3,660 fields.
28
- - `npm pack --dry-run`: package file list checked.
29
-
30
- ## Limits
31
-
32
- - No live WhatsApp account was linked in this environment. A server-side 428 before `primary_hello` completion can still be caused by an unsupported browser identity, stale protocol version, or temporary WhatsApp-side restriction.
33
- - Recent upstream reports show Desktop browser tuples can be rejected with 428 while a Chrome browser tuple succeeds; Mahiru's configured `Browsers.macOS('Chrome')` is not the rejected `Desktop` tuple. Some new-device 428 cases continued even with a fresh protocol version and may be server-side restrictions.
34
- - The `review_and_pay` structure is validated; WhatsApp client rendering and payment availability depend on supported region, account type and provider.