kage-baileys 25.4.13 → 25.4.18

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
 
@@ -1117,7 +1108,7 @@ await conn.sendReviewAndPay(m.chat, {
1117
1108
  })
1118
1109
  ```
1119
1110
 
1120
- `total_amount` debe coincidir con la suma de `order.items` (importe × cantidad) y usar el mismo `offset`; el constructor calcula `subtotal` y rechaza montos inconsistentes. En el ejemplo, `137` con `offset: 100` representa PEN 1.37. No envíes marcadores como `[NUMERO_PLIN]`: elimina la cuenta de prueba o reemplázala con datos válidos que estés autorizado a utilizar. Que una cuenta bancaria o billetera figure en `payment_settings` no garantiza que WhatsApp la admita como proveedor de pago. Kage construye y transmite el mensaje, pero no procesa cobros ni confirma pagos. El renderizado depende del cliente, la cuenta, la región y las funciones habilitadas por WhatsApp. Para depurar, prueba primero sin miniatura ni cuentas de pago; WhatsApp puede ignorar flujos no habilitados en esa cuenta o cliente. **Disponibilidad regional:** el Centro de ayuda de WhatsApp lista India, Brasil, México e Indonesia para pagar a empresas registradas; fuera de esos países, la función no está disponible. Baileys no puede habilitarla desde el protocolo. En países no incluidos, usa un enlace externo de tu proveedor mediante `cta_url` en vez de `review_and_pay` (consulta https://faq.whatsapp.com/1293279751500598/).
1111
+ `total_amount` se normaliza usando la suma de `order.items` (importe × cantidad), más impuestos y envío, menos descuentos; `subtotal` también se recalcula desde las líneas del pedido. Deben usarse importes válidos y un mismo `offset`. Para rechazar cualquier ajuste automático, configura `KAGE_STRICT_REVIEW_AND_PAY=1`. En el ejemplo, `137` con `offset: 100` representa PEN 1.37. No envíes marcadores como `[NUMERO_PLIN]`: elimina la cuenta de prueba o reemplázala con datos válidos que estés autorizado a utilizar. Que una cuenta bancaria o billetera figure en `payment_settings` no garantiza que WhatsApp la admita como proveedor de pago. Kage construye y transmite el mensaje, pero no procesa cobros ni confirma pagos. El renderizado depende del cliente, la cuenta, la región y las funciones habilitadas por WhatsApp. Para depurar, prueba primero sin miniatura ni cuentas de pago; WhatsApp puede ignorar flujos no habilitados en esa cuenta o cliente. **Disponibilidad regional:** el Centro de ayuda de WhatsApp lista India, Brasil, México e Indonesia para pagar a empresas registradas; fuera de esos países, la función no está disponible. Baileys no puede habilitarla desde el protocolo. En países no incluidos, usa un enlace externo de tu proveedor mediante `cta_url` en vez de `review_and_pay` (consulta https://faq.whatsapp.com/1293279751500598/).
1121
1112
 
1122
1113
  ### Helpers de fotos y perfil
1123
1114
 
@@ -2282,7 +2273,7 @@ This Kage build incorporates the compatible additions identified in the attached
2282
2273
 
2283
2274
  ### Native Flow `review_and_pay`
2284
2275
 
2285
- `buildReviewAndPayMessage()` builds the protobuf-compatible `interactiveMessage` payload. `sendReviewAndPay()` wraps it with `generateWAMessageFromContent`, adds a message ID, and supplies the payment `biz` relay node. The core `relayMessage()` path normalizes `messageParamsJson` and `messageVersion`, validates the order arithmetic, and adds the `biz` node with the `order_details` mapping for `review_and_pay`. The library does not inject a `bot` marker into ordinary private chats. `buttonParamsJson` accepts a JSON string or object and is validated before transmission. Example:
2276
+ `buildReviewAndPayMessage()` builds the protobuf-compatible `interactiveMessage` payload. `sendReviewAndPay()` wraps it with `generateWAMessageFromContent`, adds a message ID, and supplies the payment `biz` relay node. The core `relayMessage()` path normalizes `messageParamsJson` and `messageVersion`, reconciles subtotal/total against order lines and declared tax/shipping/discount, and adds the `biz` node with the `order_details` mapping for `review_and_pay`. Set `KAGE_STRICT_REVIEW_AND_PAY=1` to reject rather than reconcile mismatched totals. The library does not inject a `bot` marker into ordinary private chats. `buttonParamsJson` accepts a JSON string or object and is validated before transmission. Example:
2286
2277
 
2287
2278
  ```js
2288
2279
  await conn.sendReviewAndPay(chatJid, {
@@ -2308,7 +2299,7 @@ await conn.sendReviewAndPay(chatJid, {
2308
2299
  }, {});
2309
2300
  ```
2310
2301
 
2311
- This sends a WhatsApp Native Flow payment-request payload only. It does not charge, settle or verify a payment, and rendering depends on WhatsApp client/account/region support and a payment provider activated for that business. The generic helper deliberately does not embed personal payment accounts. The total must match the line-item sum (plus tax/shipping minus discount); Kage calculates a missing subtotal and rejects inconsistent amounts. The core relay automatically attaches the required `biz` companion node even when the caller uses `conn.relayMessage()` directly. WhatsApp Help Center lists India, Brazil, Mexico and Indonesia as markets where customers can pay registered businesses; outside those markets the native payment feature is unavailable. For other countries, use a provider-hosted payment link with a regular `cta_url` button instead.
2302
+ This sends a WhatsApp Native Flow payment-request payload only. It does not charge, settle or verify a payment, and rendering depends on WhatsApp client/account/region support and a payment provider activated for that business. The generic helper deliberately does not embed personal payment accounts. The subtotal is derived from the line items and `total_amount` is normalized to subtotal plus tax and shipping minus discount. Set `KAGE_STRICT_REVIEW_AND_PAY=1` to reject mismatches instead of reconciling them. The core relay automatically attaches the required `biz` companion node even when the caller uses `conn.relayMessage()` directly. WhatsApp Help Center lists India, Brazil, Mexico and Indonesia as markets where customers can pay registered businesses; outside those markets the native payment feature is unavailable. For other countries, use a provider-hosted payment link with a regular `cta_url` button instead.
2312
2303
 
2313
2304
  ### Media status and view-once messages
2314
2305
 
@@ -2319,15 +2310,15 @@ 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.16: payment amount normalization
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
- 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]`.
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` is normalized to item subtotal plus tax and shipping minus discount. The subtotal is derived from the actual order lines. Set `KAGE_STRICT_REVIEW_AND_PAY=1` to reject mismatched amounts instead of normalizing them. Kage builds the UI payload; it does not process or confirm payments. Replace or remove placeholder payment identifiers such as `[ACCOUNT_NUMBER]`.
2327
2318
 
2328
2319
  The Native Flow helper constructs a payment-request message only. It does not process or verify transactions. WhatsApp's current Help Center lists registered-business payments in India, Brazil, Mexico and Indonesia; outside those countries, its in-app business-payment feature is not available. Use a legitimate hosted payment link for other regions. See [WhatsApp Help Center: participating countries](https://faq.whatsapp.com/1293279751500598/?locale=es_LA).
2329
2320
 
2330
2321
  ## Package validation
2331
2322
 
2332
- The `test/` source folder and source maps are intentionally excluded from this clean distribution build. `npm test` runs focused pairing/reconnect and Native Flow assertions. `npm run check` validates syntax, imports, exports, WAProto, and the focused assertions. See `VALIDATION-REPORT-25.4.10.md`.
2323
+ The `test/` source folder and source maps are intentionally excluded from this clean distribution build. `npm test` runs focused pairing/reconnect and Native Flow assertions. `npm run check` validates syntax, imports, exports, WAProto, and the focused assertions. See `VALIDATION-REPORT-25.4.16.md`.
2333
2324
 
@@ -6,7 +6,7 @@
6
6
  import { normalizeThumbnail } from './media-thumb.js';
7
7
  import { generateWAMessageFromContent } from '../lib/Utils/messages.js';
8
8
  import { getBizBinaryNode } from '../lib/WABinary/index.js';
9
- import { prepareNativeFlowMessageForRelay } from '../lib/Utils/native-flow.js';
9
+ import { normalizeReviewAndPayAmounts, prepareNativeFlowMessageForRelay } from '../lib/Utils/native-flow.js';
10
10
 
11
11
  const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
12
12
  const positiveInteger = (value, name) => {
@@ -110,8 +110,8 @@ function normalizePaymentParams(options) {
110
110
  offset,
111
111
  'total_amount'
112
112
  );
113
- if (normalizedTotal.offset !== offset || BigInt(normalizedTotal.value) !== itemTotal) {
114
- throw new TypeError('total_amount must equal the sum of order.items (value × quantity) and use the same offset');
113
+ if (normalizedTotal.offset !== offset) {
114
+ throw new TypeError('total_amount.offset must match the order item offset');
115
115
  }
116
116
  const params = {
117
117
  currency,
@@ -138,12 +138,12 @@ function normalizePaymentParams(options) {
138
138
  };
139
139
 
140
140
  if (!params.reference_id.trim()) throw new TypeError('referenceId cannot be empty');
141
+ let result = params;
141
142
  if (supplied) {
142
- const merged = { ...supplied, ...params };
143
- if (isObject(supplied.order)) merged.order = { ...supplied.order, ...params.order };
144
- return merged;
143
+ result = { ...supplied, ...params };
144
+ if (isObject(supplied.order)) result.order = { ...supplied.order, ...params.order };
145
145
  }
146
- return params;
146
+ return normalizeReviewAndPayAmounts(result);
147
147
  }
148
148
 
149
149
  function getRawButtonParamsJson(options) {
@@ -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 */
@@ -198,12 +198,20 @@ function createKageOrderDetails(parameters) {
198
198
  if (p.order.subtotal == null) {
199
199
  p.order.subtotal = { value: Number(sum), offset };
200
200
  }
201
- const subtotal = amount(p.order.subtotal,'order.subtotal');
202
- if (sum !== subtotal) throw new TypeError('El subtotal no coincide con los productos');
201
+ let subtotal = amount(p.order.subtotal,'order.subtotal');
202
+ const strict = process.env.KAGE_STRICT_REVIEW_AND_PAY === '1';
203
+ if (sum !== subtotal && strict) throw new TypeError('El subtotal no coincide con los productos');
204
+ if (sum !== subtotal) {
205
+ p.order.subtotal.value = Number(sum);
206
+ subtotal = sum;
207
+ }
203
208
  const tax = p.order.tax ? amount(p.order.tax,'tax') : 0n;
204
209
  const shipping = p.order.shipping ? amount(p.order.shipping,'shipping') : 0n;
205
210
  const discount = p.order.discount ? amount(p.order.discount,'discount') : 0n;
206
- if (subtotal + tax + shipping - discount !== total) throw new TypeError('El total no coincide con subtotal + impuestos + envío - descuento');
211
+ const expectedTotal = subtotal + tax + shipping - discount;
212
+ if (expectedTotal <= 0n || expectedTotal > BigInt(Number.MAX_SAFE_INTEGER)) throw new RangeError('El total calculado está fuera del rango permitido');
213
+ if (total !== expectedTotal && strict) throw new TypeError('El total no coincide con subtotal + impuestos + envío - descuento');
214
+ if (total !== expectedTotal) p.total_amount.value = Number(expectedTotal);
207
215
  if (!p.payment_settings?.length && !p.native_payment_methods?.length && !p.payment_configuration) throw new TypeError('Falta una configuración de pago real; usa cta_url para enlaces externos');
208
216
  // Defaults útiles para review_and_pay
209
217
  if (!p.payment_type) p.payment_type = 'upi';
@@ -13,4 +13,5 @@ export declare function nativeFlowButtonsViolateConstraints(buttons?: Array<{ na
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
15
 
16
+ export declare function normalizeReviewAndPayAmounts<T extends Record<string, unknown>>(params: T, options?: { strict?: boolean }): T;
16
17
  export declare function prepareNativeFlowMessageForRelay<T>(input: T): T;
@@ -120,6 +120,104 @@ export const checkNativeFlowButtons = buttons => {
120
120
 
121
121
  export const nativeFlowButtonsViolateConstraints = buttons => !checkNativeFlowButtons(buttons).ok;
122
122
 
123
+ /**
124
+ * Reconciles review_and_pay arithmetic against the actual order lines.
125
+ *
126
+ * WhatsApp expects total_amount = item subtotal + tax + shipping - discount.
127
+ * Older Kage forks did not validate this, which allowed malformed payloads to
128
+ * reach the relay layer. The safe default is to recompute subtotal/total from
129
+ * the line items and declared adjustments instead of crashing on a stale total.
130
+ * Set KAGE_STRICT_REVIEW_AND_PAY=1 to reject mismatches instead.
131
+ */
132
+ export function normalizeReviewAndPayAmounts(params, options = {}) {
133
+ if (!params || typeof params !== 'object' || Array.isArray(params)) {
134
+ throw new TypeError('review_and_pay parameters must be an object');
135
+ }
136
+ if (!params.order || typeof params.order !== 'object' || !Array.isArray(params.order.items) || !params.order.items.length) {
137
+ throw new TypeError('review_and_pay requires at least one order.items entry');
138
+ }
139
+
140
+ const strict = options.strict ?? process.env.KAGE_STRICT_REVIEW_AND_PAY === '1';
141
+ const firstAmount = params.order.items[0]?.amount;
142
+ const offset = Number(params.total_amount?.offset ?? firstAmount?.offset);
143
+ if (!Number.isSafeInteger(offset) || offset <= 0) {
144
+ throw new TypeError('review_and_pay requires a positive safe integer amount offset');
145
+ }
146
+
147
+ const readAmount = (amount, label, allowZero = false) => {
148
+ if (!amount || typeof amount !== 'object' || Array.isArray(amount)) {
149
+ throw new TypeError(`${label} must contain value and offset`);
150
+ }
151
+ const value = Number(amount.value);
152
+ const amountOffset = Number(amount.offset);
153
+ if (!Number.isSafeInteger(value) || value < (allowZero ? 0 : 1)) {
154
+ throw new TypeError(`${label}.value must be a ${allowZero ? 'non-negative' : 'positive'} safe integer`);
155
+ }
156
+ if (!Number.isSafeInteger(amountOffset) || amountOffset <= 0) {
157
+ throw new TypeError(`${label}.offset must be a positive safe integer`);
158
+ }
159
+ if (amountOffset !== offset) {
160
+ throw new TypeError(`${label}.offset must match the order offset (${offset})`);
161
+ }
162
+ return BigInt(value);
163
+ };
164
+
165
+ const writeAmount = (current, value) => ({
166
+ ...(current && typeof current === 'object' && !Array.isArray(current) ? current : {}),
167
+ value: typeof current?.value === 'string' ? value.toString() : Number(value),
168
+ offset: typeof current?.offset === 'string' ? String(offset) : offset
169
+ });
170
+
171
+ let itemSum = 0n;
172
+ for (const [itemIndex, item] of params.order.items.entries()) {
173
+ if (!item || typeof item !== 'object' || typeof item.name !== 'string' || !item.name.trim()) {
174
+ throw new TypeError(`order.items[${itemIndex}].name is required`);
175
+ }
176
+ const amount = readAmount(item.amount, `order.items[${itemIndex}].amount`);
177
+ const quantity = Number(item.quantity);
178
+ if (!Number.isSafeInteger(quantity) || quantity <= 0) {
179
+ throw new TypeError(`order.items[${itemIndex}].quantity must be a positive safe integer`);
180
+ }
181
+ itemSum += amount * BigInt(quantity);
182
+ }
183
+ if (itemSum > BigInt(Number.MAX_SAFE_INTEGER)) {
184
+ throw new RangeError('review_and_pay item total exceeds the safe integer range');
185
+ }
186
+
187
+ if (params.order.subtotal != null) {
188
+ const suppliedSubtotal = readAmount(params.order.subtotal, 'order.subtotal', true);
189
+ if (suppliedSubtotal !== itemSum && strict) {
190
+ throw new TypeError('order.subtotal must equal the sum of order.items (amount × quantity)');
191
+ }
192
+ }
193
+ params.order.subtotal = writeAmount(params.order.subtotal, itemSum);
194
+
195
+ const optionalOrderAmount = key => {
196
+ if (params.order[key] == null) return 0n;
197
+ return readAmount(params.order[key], `order.${key}`, true);
198
+ };
199
+ const expectedTotal = itemSum
200
+ + optionalOrderAmount('tax')
201
+ + optionalOrderAmount('shipping')
202
+ - optionalOrderAmount('discount');
203
+
204
+ if (expectedTotal <= 0n) {
205
+ throw new RangeError('review_and_pay calculated total must be greater than zero');
206
+ }
207
+ if (expectedTotal > BigInt(Number.MAX_SAFE_INTEGER)) {
208
+ throw new RangeError('review_and_pay calculated total exceeds the safe integer range');
209
+ }
210
+
211
+ if (params.total_amount != null) {
212
+ const suppliedTotal = readAmount(params.total_amount, 'total_amount');
213
+ if (suppliedTotal !== expectedTotal && strict) {
214
+ throw new TypeError(`review_and_pay total_amount (${suppliedTotal}) must equal subtotal + tax + shipping - discount (${expectedTotal})`);
215
+ }
216
+ }
217
+ params.total_amount = writeAmount(params.total_amount, expectedTotal);
218
+ return params;
219
+ }
220
+
123
221
 
124
222
  /**
125
223
  * Normalizes and validates Native Flow data immediately before relay.
@@ -211,52 +309,7 @@ export function prepareNativeFlowMessageForRelay(input) {
211
309
  throw new TypeError('review_and_pay requires at least one order.items entry');
212
310
  }
213
311
 
214
- const readAmount = (amount, label, commonOffset, allowZero = false) => {
215
- if (!amount || typeof amount !== 'object') throw new TypeError(`${label} must contain value and offset`);
216
- const value = Number(amount.value);
217
- const offset = Number(amount.offset);
218
- if (!Number.isSafeInteger(value) || value < (allowZero ? 0 : 1)) {
219
- throw new TypeError(`${label}.value must be a ${allowZero ? 'non-negative' : 'positive'} safe integer`);
220
- }
221
- if (!Number.isSafeInteger(offset) || offset <= 0) throw new TypeError(`${label}.offset must be a positive safe integer`);
222
- if (commonOffset != null && offset !== commonOffset) throw new TypeError(`${label}.offset must match the order offset`);
223
- return { value: BigInt(value), offset };
224
- };
225
-
226
- const total = readAmount(params.total_amount, 'total_amount');
227
- const offset = total.offset;
228
- let itemSum = 0n;
229
- for (const [itemIndex, item] of params.order.items.entries()) {
230
- if (!item || typeof item !== 'object' || typeof item.name !== 'string' || !item.name.trim()) {
231
- throw new TypeError(`order.items[${itemIndex}].name is required`);
232
- }
233
- const amount = readAmount(item.amount, `order.items[${itemIndex}].amount`, offset);
234
- const quantity = Number(item.quantity);
235
- if (!Number.isSafeInteger(quantity) || quantity <= 0) {
236
- throw new TypeError(`order.items[${itemIndex}].quantity must be a positive safe integer`);
237
- }
238
- itemSum += amount.value * BigInt(quantity);
239
- }
240
- if (itemSum > BigInt(Number.MAX_SAFE_INTEGER)) throw new RangeError('review_and_pay item total exceeds the safe integer range');
241
-
242
- let subtotal;
243
- if (params.order.subtotal == null) {
244
- subtotal = { value: Number(itemSum), offset };
245
- params.order.subtotal = subtotal;
246
- } else {
247
- const parsed = readAmount(params.order.subtotal, 'order.subtotal', offset, true);
248
- subtotal = { value: Number(parsed.value), offset };
249
- if (parsed.value !== itemSum) throw new TypeError('order.subtotal must equal the sum of order.items (amount × quantity)');
250
- }
251
-
252
- const optionalOrderAmount = (key) => {
253
- if (params.order[key] == null) return 0n;
254
- return readAmount(params.order[key], `order.${key}`, offset, true).value;
255
- };
256
- const expectedTotal = itemSum + optionalOrderAmount('tax') + optionalOrderAmount('shipping') - optionalOrderAmount('discount');
257
- if (expectedTotal < 0n || expectedTotal !== total.value) {
258
- throw new TypeError(`review_and_pay total_amount (${total.value}) must equal subtotal + tax + shipping - discount (${expectedTotal})`);
259
- }
312
+ normalizeReviewAndPayAmounts(params);
260
313
 
261
314
  if (params.payment_settings != null && !Array.isArray(params.payment_settings)) {
262
315
  throw new TypeError('review_and_pay payment_settings must be an array');
@@ -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.18",
5
+ "description": "Kage Baileys with hardened pairing-code validation, WhatsApp 429 cooldown, resilient reconnect classification, normalized Native Flow payment totals, and expanded WAProto compatibility",
6
6
  "keywords": [
7
7
  "whatsapp",
8
8
  "automation"
@@ -24,7 +24,8 @@
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
+ "VALIDATION-REPORT-25.4.16.md"
28
29
  ],
29
30
  "scripts": {
30
31
  "build:all": "npm run check",
@@ -36,7 +37,7 @@
36
37
  "gen:protobuf": "sh WAProto/GenerateStatics.sh",
37
38
  "lint": "node ./scripts/verify-package.mjs",
38
39
  "release": "release-it",
39
- "test": "node ./scripts/verify-pairing-flow.mjs"
40
+ "test": "node ./scripts/verify-pairing-flow.mjs && node ./scripts/verify-native-flow-payments.mjs"
40
41
  },
41
42
  "dependencies": {
42
43
  "@adiwajshing/keyed-db": "^0.2.4",
@@ -0,0 +1,125 @@
1
+ import assert from 'node:assert/strict';
2
+ import { createRequire } from 'node:module';
3
+ import {
4
+ normalizeReviewAndPayAmounts,
5
+ prepareNativeFlowMessageForRelay
6
+ } from '../lib/Utils/native-flow.js';
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const { createKageOrderDetails } = require('../lib/Utils/interactive-compat.cjs');
10
+
11
+ let checks = 0;
12
+ const check = (condition, message) => {
13
+ assert.ok(condition, message);
14
+ checks += 1;
15
+ };
16
+
17
+ const makeMessage = ({
18
+ total = 137,
19
+ item = 138,
20
+ quantity = 1,
21
+ subtotal = 137,
22
+ offset = 100,
23
+ tax,
24
+ shipping,
25
+ discount,
26
+ stringValues = false
27
+ } = {}) => {
28
+ const money = value => ({
29
+ value: stringValues ? String(value) : value,
30
+ offset: stringValues ? String(offset) : offset
31
+ });
32
+ const order = {
33
+ items: [{ name: 'Producto de prueba', amount: money(item), quantity }],
34
+ subtotal: money(subtotal)
35
+ };
36
+ if (tax !== undefined) order.tax = money(tax);
37
+ if (shipping !== undefined) order.shipping = money(shipping);
38
+ if (discount !== undefined) order.discount = money(discount);
39
+
40
+ const params = {
41
+ currency: 'PEN',
42
+ reference_id: 'KAGE_TEST_001',
43
+ type: 'physical-goods',
44
+ total_amount: money(total),
45
+ order
46
+ };
47
+ return {
48
+ interactiveMessage: {
49
+ nativeFlowMessage: {
50
+ buttons: [{ name: 'review_and_pay', buttonParamsJson: JSON.stringify(params) }]
51
+ }
52
+ }
53
+ };
54
+ };
55
+
56
+ // Regression for the user's exact exception: total 137 vs calculated 138.
57
+ const mismatched = makeMessage();
58
+ prepareNativeFlowMessageForRelay(mismatched);
59
+ let params = JSON.parse(mismatched.interactiveMessage.nativeFlowMessage.buttons[0].buttonParamsJson);
60
+ check(params.total_amount.value === 138, 'total_amount should be normalized from 137 to 138');
61
+ check(params.order.subtotal.value === 138, 'subtotal should match the item sum');
62
+
63
+ // String amounts are supported and keep their original JSON representation.
64
+ const stringPayload = makeMessage({ total: 137, item: 138, subtotal: 137, stringValues: true });
65
+ prepareNativeFlowMessageForRelay(stringPayload);
66
+ params = JSON.parse(stringPayload.interactiveMessage.nativeFlowMessage.buttons[0].buttonParamsJson);
67
+ check(params.total_amount.value === '138', 'string total_amount should remain a string after normalization');
68
+ check(params.order.subtotal.value === '138', 'string subtotal should remain a string after normalization');
69
+
70
+ // Tax, shipping and discount are included in the canonical total calculation.
71
+ const adjustments = makeMessage({ total: 144, item: 138, subtotal: 138, tax: 4, shipping: 5, discount: 2 });
72
+ prepareNativeFlowMessageForRelay(adjustments);
73
+ params = JSON.parse(adjustments.interactiveMessage.nativeFlowMessage.buttons[0].buttonParamsJson);
74
+ check(params.total_amount.value === 145, 'total should include tax + shipping - discount');
75
+
76
+ // A missing total is calculated from the order lines and adjustments.
77
+ const noTotal = makeMessage({ total: 137, item: 138 });
78
+ let missingParams = JSON.parse(noTotal.interactiveMessage.nativeFlowMessage.buttons[0].buttonParamsJson);
79
+ delete missingParams.total_amount;
80
+ noTotal.interactiveMessage.nativeFlowMessage.buttons[0].buttonParamsJson = JSON.stringify(missingParams);
81
+ prepareNativeFlowMessageForRelay(noTotal);
82
+ missingParams = JSON.parse(noTotal.interactiveMessage.nativeFlowMessage.buttons[0].buttonParamsJson);
83
+ check(missingParams.total_amount.value === 138, 'missing total_amount should be derived from order items');
84
+
85
+ // Strict mode remains available to deployments that prefer rejection.
86
+ assert.throws(() => normalizeReviewAndPayAmounts({
87
+ total_amount: { value: 137, offset: 100 },
88
+ order: {
89
+ items: [{ name: 'Producto', amount: { value: 138, offset: 100 }, quantity: 1 }],
90
+ subtotal: { value: 138, offset: 100 }
91
+ }
92
+ }, { strict: true }), /total_amount/);
93
+ checks += 1;
94
+
95
+ // Structural and currency-offset errors must still be rejected.
96
+ const malformed = makeMessage();
97
+ let malformedParams = JSON.parse(malformed.interactiveMessage.nativeFlowMessage.buttons[0].buttonParamsJson);
98
+ malformedParams.order.items[0].name = '';
99
+ malformed.interactiveMessage.nativeFlowMessage.buttons[0].buttonParamsJson = JSON.stringify(malformedParams);
100
+ assert.throws(() => prepareNativeFlowMessageForRelay(malformed), /name is required/);
101
+ checks += 1;
102
+ const wrongOffset = makeMessage({ total: 137, item: 138 });
103
+ let wrongParams = JSON.parse(wrongOffset.interactiveMessage.nativeFlowMessage.buttons[0].buttonParamsJson);
104
+ wrongParams.order.items[0].amount.offset = 10;
105
+ wrongOffset.interactiveMessage.nativeFlowMessage.buttons[0].buttonParamsJson = JSON.stringify(wrongParams);
106
+ assert.throws(() => prepareNativeFlowMessageForRelay(wrongOffset), /offset must match/);
107
+ checks += 1;
108
+
109
+ // The CommonJS compatibility builder uses the same arithmetic policy.
110
+ const legacy = createKageOrderDetails({
111
+ currency: 'PEN',
112
+ reference_id: 'KAGE_TEST_CJS',
113
+ type: 'physical-goods',
114
+ payment_configuration: 'merchant_account',
115
+ total_amount: { value: 137, offset: 100 },
116
+ order: {
117
+ subtotal: { value: 137, offset: 100 },
118
+ items: [{ name: 'Producto', amount: { value: 138, offset: 100 }, quantity: 1 }]
119
+ }
120
+ });
121
+ const legacyParams = JSON.parse(legacy.buttonParamsJson);
122
+ check(legacyParams.total_amount.value === 138, 'CJS compatibility builder should normalize total_amount');
123
+ check(legacyParams.order.subtotal.value === 138, 'CJS compatibility builder should normalize subtotal');
124
+
125
+ console.log(`Native Flow payment validation: ${checks} checks passed.`);
@@ -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');
34
- assert.match(pay, /total_amount must equal the sum of order\.items/,
35
- 'review_and_pay must reject mismatched total/item values');
76
+ 'Native Flow relay must support order_details mapping');
77
+ assert.match(pay, /normalizeReviewAndPayAmounts\(result\)/,
78
+ 'review_and_pay helper must reconcile total/subtotal against order lines');
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.