kage-baileys 25.4.19 → 25.4.20

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,9 +245,18 @@ 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
- ### Solicitar un código sin repetir solicitudes
248
+ ### Conexión automática en el evento `connecting`
249
249
 
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.
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
+ ```
251
260
 
252
261
  ### Recibir el historial completo
253
262
 
@@ -1108,7 +1117,7 @@ await conn.sendReviewAndPay(m.chat, {
1108
1117
  })
1109
1118
  ```
1110
1119
 
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. Los marcadores de plantilla como `[NUMERO_PLIN]` se eliminan automáticamente de `payment_settings`; las cuentas reales se conservan. Configura solo datos de pago 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/).
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/).
1112
1121
 
1113
1122
  ### Helpers de fotos y perfil
1114
1123
 
@@ -2273,7 +2282,7 @@ This Kage build incorporates the compatible additions identified in the attached
2273
2282
 
2274
2283
  ### Native Flow `review_and_pay`
2275
2284
 
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:
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:
2277
2286
 
2278
2287
  ```js
2279
2288
  await conn.sendReviewAndPay(chatJid, {
@@ -2299,7 +2308,7 @@ await conn.sendReviewAndPay(chatJid, {
2299
2308
  }, {});
2300
2309
  ```
2301
2310
 
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.
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.
2303
2312
 
2304
2313
  ### Media status and view-once messages
2305
2314
 
@@ -2310,15 +2319,15 @@ Use `getMediaDownloadStatus(message)` to inspect ordinary media availability. It
2310
2319
  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.
2311
2320
 
2312
2321
 
2313
- ## Kage 25.4.17: payment account placeholder cleanup
2322
+ ## Kage 25.4.10: pairing and Native Flow
2314
2323
 
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.
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.
2316
2325
 
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. Placeholder payment identifiers such as `[NUMERO_PLIN]` or `[ACCOUNT_NUMBER]` are filtered out automatically before relay; valid payment accounts are preserved.
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]`.
2318
2327
 
2319
2328
  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).
2320
2329
 
2321
2330
  ## Package validation
2322
2331
 
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.17.md`.
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`.
2324
2333
 
@@ -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 { isPlaceholderPaymentIdentifier, normalizeReviewAndPayAmounts, prepareNativeFlowMessageForRelay } from '../lib/Utils/native-flow.js';
9
+ import { 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) => {
@@ -27,16 +27,17 @@ const amountObject = (value, offset, name) => {
27
27
  function normalizePaymentAccounts(accounts) {
28
28
  if (accounts == null) return [];
29
29
  if (!Array.isArray(accounts)) throw new TypeError('paymentAccounts must be an array');
30
- const normalized = [];
31
- for (const [index, entry] of accounts.entries()) {
30
+ return accounts.map((entry, index) => {
32
31
  if (!isObject(entry)) throw new TypeError(`paymentAccounts[${index}] must be an object`);
33
32
  const paymentAccount = entry.payment_account ?? entry.paymentAccount;
34
33
  if (!isObject(paymentAccount)) throw new TypeError(`paymentAccounts[${index}].payment_account is required`);
35
34
  const identifier = paymentAccount.identifier_value ?? paymentAccount.identifierValue;
36
- if (isPlaceholderPaymentIdentifier(identifier)) continue;
37
35
  if (typeof identifier !== 'string' || !identifier.trim()) {
38
36
  throw new TypeError(`paymentAccounts[${index}] needs a nonempty identifier_value`);
39
37
  }
38
+ if (/^\[[^\]]+\]$/.test(identifier.trim())) {
39
+ throw new TypeError(`paymentAccounts[${index}].identifier_value is still a placeholder; replace it with a real value or omit that account`);
40
+ }
40
41
  const result = { ...entry, type: entry.type || 'payment_account', payment_account: { ...paymentAccount } };
41
42
  delete result.paymentAccount;
42
43
  if (result.payment_account.identifierValue !== undefined && result.payment_account.identifier_value === undefined) {
@@ -59,9 +60,8 @@ function normalizePaymentAccounts(accounts) {
59
60
  delete result.payment_account.identifierType;
60
61
  delete result.payment_account.institutionName;
61
62
  delete result.payment_account.beneficiaryName;
62
- normalized.push(result);
63
- }
64
- return normalized;
63
+ return result;
64
+ });
65
65
  }
66
66
 
67
67
  function normalizePaymentParams(options) {
@@ -110,8 +110,8 @@ function normalizePaymentParams(options) {
110
110
  offset,
111
111
  'total_amount'
112
112
  );
113
- if (normalizedTotal.offset !== offset) {
114
- throw new TypeError('total_amount.offset must match the order item offset');
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');
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;
142
141
  if (supplied) {
143
- result = { ...supplied, ...params };
144
- if (isObject(supplied.order)) result.order = { ...supplied.order, ...params.order };
142
+ const merged = { ...supplied, ...params };
143
+ if (isObject(supplied.order)) merged.order = { ...supplied.order, ...params.order };
144
+ return merged;
145
145
  }
146
- return normalizeReviewAndPayAmounts(result);
146
+ return params;
147
147
  }
148
148
 
149
149
  function getRawButtonParamsJson(options) {
@@ -49,7 +49,7 @@ export const DEFAULT_CACHE_TTLS = {
49
49
  export const DEFAULT_CACHE_MAX_KEYS = 20000;
50
50
  export const DEFAULT_CONNECTION_CONFIG = {
51
51
  version: version,
52
- browser: Browsers.androidPhone('Chrome'),
52
+ browser: Browsers.macOS('Chrome'),
53
53
  waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
54
54
  connectTimeoutMs: 20000,
55
55
  keepAliveIntervalMs: 30000,
@@ -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-accepted pairing code; the primary_hello notification supplies the authoritative pairing reference. */
189
+ /** Returns a server-confirmed pairing code; when customPairingCode is omitted, Kage uses KAGE plus four random digits (no space). */
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 is invalid');
813
+ logger.warn('ignored primary_hello: pairing code missing, expired, or server reference does not match');
814
814
  return false;
815
815
  }
816
- const primaryHelloRef = Buffer.from(receivedRefValue);
816
+ const expectedRef = Buffer.from(creds.pairingCodeRef);
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: primaryHelloRef }
870
+ { tag: 'link_code_pairing_ref', attrs: {}, content: expectedRef }
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-accepted pairing code; the primary_hello notification supplies the authoritative pairing reference. */
186
+ /** Returns a server-confirmed pairing code; when customPairingCode is omitted, Kage uses KAGE plus four random digits (no space). */
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-accepted pairing code; the primary_hello notification supplies the authoritative pairing reference. */
44
+ /** Returns a server-confirmed pairing code; when customPairingCode is omitted, Kage uses KAGE plus four random digits (no space). */
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, DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS, PAIRING_CODE_RESPONSE_GRACE_MS, buildPairingCompanionHelloNode, extractPairingReference, generateKagePairingCode, getPairingRateLimitCooldown, normalizePairingPhone, registerPairingRateLimit } from '../Utils/pairing-code.js';
15
+ import { DEFAULT_PAIRING_CODE_TTL_MS, PAIRING_CODE_RESPONSE_GRACE_MS, buildPairingCompanionHelloNode, extractPairingReference, generateKagePairingCode, normalizePairingPhone } 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,30 +633,6 @@ 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
- }
660
636
  await connectionReady;
661
637
  if (authState.creds.registered) {
662
638
  throw new Boom('This session is already registered; pairing code is not required.', { statusCode: 409 });
@@ -682,10 +658,6 @@ export const makeSocket = (config) => {
682
658
  }
683
659
 
684
660
  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;
689
661
  const previous = {
690
662
  me: authState.creds.me,
691
663
  pairingCode: authState.creds.pairingCode,
@@ -702,8 +674,7 @@ export const makeSocket = (config) => {
702
674
  id: jidEncode(normalizedNumber, 's.whatsapp.net'),
703
675
  name: '~'
704
676
  };
705
- // Keep provisional pairing fields in memory until WhatsApp acknowledges
706
- // companion_hello; emitting creds.update earlier can persist an unusable code.
677
+ ev.emit('creds.update', authState.creds);
707
678
 
708
679
  const pending = {
709
680
  phoneNumber: normalizedNumber,
@@ -720,9 +691,8 @@ export const makeSocket = (config) => {
720
691
  pendingPairing = pending;
721
692
 
722
693
  try {
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.
694
+ // Use an IQ query rather than sendNode(): this verifies WhatsApp accepted
695
+ // companion_hello and returned a pairing ref before exposing the code.
726
696
  const companionHello = buildPairingCompanionHelloNode({
727
697
  id: generateMessageTag(),
728
698
  jid: authState.creds.me.id,
@@ -736,18 +706,20 @@ export const makeSocket = (config) => {
736
706
  if (!response) {
737
707
  throw new Boom('WhatsApp did not answer the pairing request. No code was issued.', { statusCode: DisconnectReason.timedOut });
738
708
  }
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.
742
709
  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
+ }
743
716
  if (pendingPairing !== pending) {
744
717
  throw new Boom('The pairing request expired before WhatsApp confirmed it.', { statusCode: DisconnectReason.timedOut });
745
718
  }
746
- if (pairingRef?.length) authState.creds.pairingCodeRef = pairingRef;
747
- else delete authState.creds.pairingCodeRef;
719
+ authState.creds.pairingCodeRef = pairingRef;
748
720
  ev.emit('creds.update', authState.creds);
749
- logger.info({ phoneNumber: normalizedNumber, hasEarlyReference: Boolean(pairingRef?.length) }, 'WhatsApp accepted the companion_hello pairing request');
750
- return pairingCode;
721
+ logger.info({ phoneNumber: normalizedNumber, refLength: pairingRef.length }, 'pairing code registered with WhatsApp');
722
+ return authState.creds.pairingCode;
751
723
  }
752
724
  catch (error) {
753
725
  // Always roll back the provisional identity/code when WhatsApp rejects
@@ -759,23 +731,14 @@ export const makeSocket = (config) => {
759
731
  || error?.data?.isRateLimited === true
760
732
  || /rate[-_\s]?overlimit/i.test(String(error?.message || ''));
761
733
  if (isRateLimited) {
762
- const cooldownState = registerPairingRateLimit(
763
- error,
764
- Date.now(),
765
- Number(config.pairingRateLimitCooldownMs) || DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS
766
- );
767
734
  const retryAfterMs = Number(error?.data?.retryAfterMs) > 0
768
735
  ? Math.ceil(Number(error.data.retryAfterMs))
769
- : cooldownState?.remainingMs;
770
- if (cooldownState?.until) {
771
- authState.creds.pairingRateLimitedUntil = cooldownState.until;
772
- ev.emit('creds.update', { pairingRateLimitedUntil: cooldownState.until });
773
- }
736
+ : undefined;
774
737
  const retryHint = retryAfterMs
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.';
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.';
777
740
  const rateLimitError = new Boom(
778
- `WhatsApp rejected the pairing request (rate-overlimit, 429). No pairing code was issued.${retryHint}`,
741
+ `WhatsApp rejected the pairing request (rate-overlimit, 429). No pairing code was issued.${retryHint} Kage does not retry this request automatically.`,
779
742
  {
780
743
  statusCode: 429,
781
744
  data: {
@@ -787,7 +750,7 @@ export const makeSocket = (config) => {
787
750
  }
788
751
  }
789
752
  );
790
- logger.warn({ retryAfterMs }, 'WhatsApp rate-limited pairing; provisional credentials were restored and a process-wide cooldown was activated');
753
+ logger.warn({ retryAfterMs }, 'WhatsApp rate-limited a pairing-code request; provisional credentials were restored and no retry was scheduled');
791
754
  throw rateLimitError;
792
755
  }
793
756
 
@@ -862,12 +825,6 @@ export const makeSocket = (config) => {
862
825
  }
863
826
  };
864
827
  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
- }
871
828
  const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
872
829
  const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
873
830
  const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
@@ -61,12 +61,10 @@ export type AuthenticationCreds = SignalCreds & {
61
61
  accountSettings: AccountSettings;
62
62
  registered: boolean;
63
63
  pairingCode: string | undefined;
64
- /** Optional reference echoed by companion_hello; primary_hello remains authoritative. */
64
+ /** Server-confirmed reference for the active pairing-code request. */
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;
70
68
  lastPropHash: string | undefined;
71
69
  routingInfo: Buffer | undefined;
72
70
  additionalData?: any | undefined;
@@ -71,8 +71,6 @@ 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;
76
74
  /** provide an auth state object to maintain the auth state */
77
75
  auth: AuthenticationState;
78
76
  /** manage history processing with this control; by default will sync up everything */
@@ -1,5 +1,6 @@
1
1
  import { platform, release } from 'os';
2
2
  import { proto } from '../../WAProto/index.js';
3
+
3
4
  const PLATFORM_MAP = {
4
5
  aix: 'AIX',
5
6
  darwin: 'Mac OS',
@@ -13,19 +14,46 @@ const PLATFORM_MAP = {
13
14
  cygwin: undefined,
14
15
  netbsd: undefined
15
16
  };
17
+
18
+ /**
19
+ * Standard browser descriptors used by Baileys / Kage.
20
+ * Format is always [OS, BrowserName, Version] so platform detection is consistent
21
+ * for every browser (Chrome, Firefox, Safari, Edge, Brave, Opera, etc.).
22
+ */
16
23
  export const Browsers = {
17
24
  ubuntu: browser => ['Ubuntu', browser, '22.04.4'],
18
25
  macOS: browser => ['Mac OS', browser, '14.4.1'],
19
26
  baileys: browser => ['Baileys', browser, '6.5.0'],
20
27
  windows: browser => ['Windows', browser, '10.0.22631'],
21
- android: browser => [browser, 'Android', ''],
28
+ // Fixed order: OS first so getCompanionPlatformId correctly sees the browser name
29
+ android: browser => ['Android', browser, ''],
22
30
  /** Android phone mode — use for view-once message compatibility */
23
- androidPhone: browser => [browser, 'Android', '15'],
31
+ androidPhone: browser => ['Android', browser, '15'],
24
32
  /** The appropriate browser based on your OS & release */
25
- appropriate: browser => [PLATFORM_MAP[platform()] || 'Ubuntu', browser, release()]
33
+ appropriate: browser => [PLATFORM_MAP[platform()] || 'Ubuntu', browser, release()],
34
+ // Extra convenience aliases so any browser string works without errors
35
+ chrome: () => ['Windows', 'Chrome', '10.0.22631'],
36
+ firefox: () => ['Windows', 'Firefox', '10.0.22631'],
37
+ edge: () => ['Windows', 'Edge', '10.0.22631'],
38
+ safari: () => ['Mac OS', 'Safari', '14.4.1'],
39
+ brave: () => ['Windows', 'Chrome', '10.0.22631'], // Brave reports as Chrome-compatible
40
+ opera: () => ['Windows', 'Opera', '10.0.22631'],
41
+ desktop: () => ['Windows', 'Desktop', '10.0.22631']
26
42
  };
43
+
44
+ /**
45
+ * Resolve a companion platform id that WhatsApp accepts.
46
+ * Always returns a known numeric string so pairing never fails with bad-request
47
+ * because of an unknown browser name.
48
+ */
27
49
  export const getPlatformId = (browser) => {
28
- const platformType = proto.DeviceProps.PlatformType[browser.toUpperCase()];
29
- return platformType ? platformType.toString() : '1'; //chrome
50
+ // browser can be a string (legacy) or the [OS, Name, Ver] tuple
51
+ const name = Array.isArray(browser)
52
+ ? String(browser[1] || browser[0] || 'Chrome')
53
+ : String(browser || 'Chrome');
54
+ const upper = name.toUpperCase().replace(/\s+/g, '');
55
+ const platformType = proto.DeviceProps.PlatformType[upper]
56
+ || proto.DeviceProps.PlatformType.CHROME
57
+ || 1;
58
+ return String(platformType);
30
59
  };
31
- //# sourceMappingURL=browser-utils.js.map
@@ -11,25 +11,85 @@ export var CompanionWebClientType;
11
11
  CompanionWebClientType[CompanionWebClientType["UWP"] = 8] = "UWP";
12
12
  CompanionWebClientType[CompanionWebClientType["OTHER_WEB_CLIENT"] = 9] = "OTHER_WEB_CLIENT";
13
13
  })(CompanionWebClientType || (CompanionWebClientType = {}));
14
+
14
15
  const BROWSER_TO_COMPANION_WEB_CLIENT = {
15
16
  Chrome: CompanionWebClientType.CHROME,
17
+ Chromium: CompanionWebClientType.CHROME,
18
+ Brave: CompanionWebClientType.CHROME,
19
+ Vivaldi: CompanionWebClientType.CHROME,
16
20
  Edge: CompanionWebClientType.EDGE,
21
+ 'Microsoft Edge': CompanionWebClientType.EDGE,
17
22
  Firefox: CompanionWebClientType.FIREFOX,
18
23
  IE: CompanionWebClientType.IE,
24
+ 'Internet Explorer': CompanionWebClientType.IE,
19
25
  Opera: CompanionWebClientType.OPERA,
20
- Safari: CompanionWebClientType.SAFARI
26
+ Safari: CompanionWebClientType.SAFARI,
27
+ Desktop: CompanionWebClientType.ELECTRON,
28
+ Electron: CompanionWebClientType.ELECTRON,
29
+ Baileys: CompanionWebClientType.CHROME,
30
+ Android: CompanionWebClientType.CHROME, // treat Android web clients as Chrome
31
+ Ubuntu: CompanionWebClientType.CHROME,
32
+ Windows: CompanionWebClientType.CHROME,
33
+ 'Mac OS': CompanionWebClientType.CHROME
21
34
  };
22
- export const getCompanionWebClientType = ([os, browserName]) => {
35
+
36
+ /**
37
+ * Robustly detect the web client type from any browser descriptor.
38
+ * Accepts:
39
+ * - ['OS', 'BrowserName', 'Version'] (standard)
40
+ * - ['BrowserName', 'OS', 'Version'] (old androidPhone style)
41
+ * - plain string
42
+ * Always returns a known value so WhatsApp never answers "bad-request".
43
+ */
44
+ export const getCompanionWebClientType = (browser) => {
45
+ let os = '';
46
+ let browserName = '';
47
+
48
+ if (Array.isArray(browser)) {
49
+ // Detect which element is the browser name
50
+ const knownBrowsers = Object.keys(BROWSER_TO_COMPANION_WEB_CLIENT);
51
+ const first = String(browser[0] || '');
52
+ const second = String(browser[1] || '');
53
+ if (knownBrowsers.some(k => k.toLowerCase() === first.toLowerCase())) {
54
+ browserName = first;
55
+ os = second;
56
+ } else if (knownBrowsers.some(k => k.toLowerCase() === second.toLowerCase())) {
57
+ browserName = second;
58
+ os = first;
59
+ } else {
60
+ // Fallback: assume classic [OS, Browser]
61
+ os = first;
62
+ browserName = second || first || 'Chrome';
63
+ }
64
+ } else if (typeof browser === 'string') {
65
+ browserName = browser;
66
+ } else {
67
+ browserName = 'Chrome';
68
+ }
69
+
23
70
  if (browserName === 'Desktop') {
24
71
  return os === 'Windows' ? CompanionWebClientType.UWP : CompanionWebClientType.ELECTRON;
25
72
  }
26
- return BROWSER_TO_COMPANION_WEB_CLIENT[browserName] || CompanionWebClientType.OTHER_WEB_CLIENT;
73
+
74
+ // Case-insensitive lookup
75
+ const key = Object.keys(BROWSER_TO_COMPANION_WEB_CLIENT).find(
76
+ k => k.toLowerCase() === browserName.toLowerCase()
77
+ );
78
+ return key ? BROWSER_TO_COMPANION_WEB_CLIENT[key] : CompanionWebClientType.CHROME;
27
79
  };
80
+
81
+ /**
82
+ * Always returns a valid platform id string (never fails).
83
+ */
28
84
  export const getCompanionPlatformId = (browser) => {
29
- return getCompanionWebClientType(browser).toString();
85
+ try {
86
+ return getCompanionWebClientType(browser).toString();
87
+ } catch {
88
+ return CompanionWebClientType.CHROME.toString();
89
+ }
30
90
  };
91
+
31
92
  export const buildPairingQRData = (ref, noiseKeyB64, identityKeyB64, advB64, browser) => {
32
93
  return ('https://wa.me/settings/linked_devices#' +
33
94
  [ref, noiseKeyB64, identityKeyB64, advB64, getCompanionPlatformId(browser)].join(','));
34
95
  };
35
- //# sourceMappingURL=companion-reg-client-utils.js.map
@@ -198,33 +198,12 @@ function createKageOrderDetails(parameters) {
198
198
  if (p.order.subtotal == null) {
199
199
  p.order.subtotal = { value: Number(sum), offset };
200
200
  }
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
- }
201
+ const subtotal = amount(p.order.subtotal,'order.subtotal');
202
+ if (sum !== subtotal) throw new TypeError('El subtotal no coincide con los productos');
208
203
  const tax = p.order.tax ? amount(p.order.tax,'tax') : 0n;
209
204
  const shipping = p.order.shipping ? amount(p.order.shipping,'shipping') : 0n;
210
205
  const discount = p.order.discount ? amount(p.order.discount,'discount') : 0n;
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);
215
- // Remove only instructional placeholder identifiers such as [NUMERO_PLIN].
216
- // Keep configured accounts and let the relay validator reject malformed entries.
217
- if (Array.isArray(p.payment_settings)) {
218
- p.payment_settings = p.payment_settings.filter(entry => {
219
- const account = entry?.payment_account ?? entry?.paymentAccount;
220
- const identifier = account?.identifier_value ?? account?.identifierValue;
221
- if (typeof identifier !== 'string') return true;
222
- const value = identifier.trim();
223
- return !(/^\[[^\]]+\]$/.test(value) || /^<[^>]+>$/.test(value) || /^\{\{?[^{}]+\}\}?$/.test(value)
224
- || /^(?:NUMERO|NÚMERO|PHONE|TELEFONO|TELÉFONO|ACCOUNT|CUENTA|YOUR|REPLACE|PLACEHOLDER|INSERT|ENTER|CAMBIAR|PONER|EJEMPLO|EXAMPLE)(?:[\s_-]|$)/i.test(value)
225
- || /^(?:X{4,}|0{6,}|9{6,})$/i.test(value));
226
- });
227
- }
206
+ if (subtotal + tax + shipping - discount !== total) throw new TypeError('El total no coincide con subtotal + impuestos + envío - descuento');
228
207
  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');
229
208
  // Defaults útiles para review_and_pay
230
209
  if (!p.payment_type) p.payment_type = 'upi';
@@ -13,7 +13,4 @@ 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;
17
16
  export declare function prepareNativeFlowMessageForRelay<T>(input: T): T;
18
-
19
- export declare function isPlaceholderPaymentIdentifier(value: unknown): boolean;