kage-baileys 25.4.2 → 25.4.6

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
@@ -1076,68 +1076,48 @@ await sock.sendMessage(jid, {
1076
1076
  })
1077
1077
  ```
1078
1078
 
1079
- ### `review_and_pay` Native Flow con miniatura JPEG
1079
+ ### `review_and_pay` Native Flow
1080
1080
 
1081
- Kage incluye un constructor para el formato `interactiveMessage` + `nativeFlowMessage` que se transmite mediante `relayMessage`. La miniatura acepta un `Buffer`, una imagen en base64, un `data:image/...` o una URL HTTP(S); las imágenes PNG/WebP/GIF se convierten a JPEG mediante `sharp` sin truncar bytes.
1081
+ El flujo necesita el mensaje protobuf y el nodo auxiliar `biz` con `native_flow_name: 'order_details'`. Kage 25.4.3 agrega ese nodo automáticamente en `relayMessage()`, normaliza `messageParamsJson: '{}'` y `messageVersion: 1`, valida el JSON y comprueba que los importes del pedido coincidan. No añade automáticamente el nodo `bot` a chats privados normales; solo debe enviarse cuando el destino sea un bot admitido. `sendReviewAndPay()` prepara el `WebMessageInfo` y el nodo `biz` para otros sockets.
1082
1082
 
1083
- ```javascript
1084
- import { buildReviewAndPayMessage } from 'kage-baileys'
1083
+ Empieza probando sin miniatura ni cuentas de pago para separar el problema de renderizado del proveedor de pagos:
1085
1084
 
1086
- const content = await buildReviewAndPayMessage({
1085
+ ```javascript
1086
+ await conn.sendReviewAndPay(m.chat, {
1087
1087
  header: { title: '', subtitle: '' },
1088
1088
  body: 'Texto',
1089
1089
  footer: 'Footer',
1090
- thumbnail: 'https://cdn.example.com/producto.jpg',
1091
- paymentParams: {
1092
- currency: 'PEN',
1093
- payment_configuration: '',
1094
- payment_type: 'upr',
1095
- total_amount: { value: 137, offset: 100 },
1096
- reference_id: 'KFG_001',
1097
- type: 'physical-goods',
1098
- order: {
1099
- status: 'pending',
1100
- description: 'Pequeña descripción',
1101
- order_type: 'PAYMENT_REQUEST',
1102
- items: [{
1103
- name: 'Título principal',
1104
- amount: { value: 138, offset: 100 },
1105
- quantity: 1
1106
- }]
1107
- },
1108
- payment_settings: [
1109
- {
1110
- type: 'payment_account',
1111
- payment_account: {
1112
- account_type: 'digital_wallet',
1113
- identifier_type: 'phone_number',
1114
- identifier_value: '51900000000',
1115
- institution_name: 'Yape',
1116
- beneficiary_name: 'Nombre del beneficiario'
1117
- }
1118
- }
1119
- ],
1120
- additional_note: 'Descripción principal',
1121
- share_payment_status: false,
1122
- is_soft_deleted: false
1123
- }
1090
+ currency: 'PEN',
1091
+ totalValue: 137,
1092
+ itemValue: 137,
1093
+ offset: 100,
1094
+ referenceId: 'KFG_001',
1095
+ type: 'physical-goods',
1096
+ itemName: 'Título principal',
1097
+ orderDescription: 'Pequeña descripción',
1098
+ paymentAccounts: [],
1099
+ additionalNote: 'Descripción principal'
1124
1100
  })
1125
-
1126
- await conn.relayMessage(m.chat, content, {})
1127
1101
  ```
1128
1102
 
1129
- También se puede usar el método instalado automáticamente en el socket:
1103
+ Cuando el mensaje de texto se muestre, añade una miniatura JPEG válida y menor de 64 KB:
1130
1104
 
1131
1105
  ```javascript
1132
1106
  await conn.sendReviewAndPay(m.chat, {
1133
1107
  body: 'Texto',
1134
1108
  footer: 'Footer',
1135
1109
  thumbnail: 'https://cdn.example.com/producto.jpg',
1136
- paymentParams: datosDelPago
1110
+ currency: 'PEN',
1111
+ totalValue: 137,
1112
+ itemValue: 137,
1113
+ offset: 100,
1114
+ referenceId: 'KFG_001',
1115
+ itemName: 'Título principal',
1116
+ paymentAccounts: []
1137
1117
  })
1138
1118
  ```
1139
1119
 
1140
- `payment_settings` admite varias cuentas (Yape, Plin, bancos y otros métodos) y conserva los identificadores proporcionados. Reemplaza todos los datos de ejemplo o marcadores por datos reales y autorizados; Kage solo construye y transmite el mensaje, no procesa cobros ni confirma pagos. El cliente, la cuenta, la región y las capacidades habilitadas por WhatsApp determinan si el botón se muestra y puede utilizarse. `review_and_pay` puede no renderizarse en WhatsApp Web/iOS.
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/).
1141
1121
 
1142
1122
  ### Helpers de fotos y perfil
1143
1123
 
@@ -2296,13 +2276,13 @@ This Kage build incorporates selected fixes reviewed from RedX Baileys 7.0.0-rc1
2296
2276
  - WMex response parsing accepts JSON bodies with a binary prefix and safely handles partial newsletter metadata responses.
2297
2277
  - Compact binary newsletter metadata is accepted only when exactly one channel JID can be identified; ambiguous payloads are rejected instead of guessed.
2298
2278
 
2299
- ## Kage cross-fork integration (25.4.1)
2279
+ ## Kage cross-fork integration (25.4.3)
2300
2280
 
2301
2281
  This Kage build incorporates the compatible additions identified in the attached Kage Antigua, Dnuzi, ItsLiaaa, and Elaina/Rexx distributions. It keeps Kage's ESM socket, Signal, transport and media core as the single implementation. The additive WAProto schema is loaded by the existing merged-protocol runtime.
2302
2282
 
2303
2283
  ### Native Flow `review_and_pay`
2304
2284
 
2305
- `buildReviewAndPayMessage()` builds the protobuf-compatible `interactiveMessage` payload and `sendReviewAndPay()` relays it directly through the authenticated socket. `buttonParamsJson` accepts either a JSON string or an object; strings are validated and preserved exactly. 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:
2306
2286
 
2307
2287
  ```js
2308
2288
  await conn.sendReviewAndPay(chatJid, {
@@ -2312,7 +2292,6 @@ await conn.sendReviewAndPay(chatJid, {
2312
2292
  buttonParamsJson: JSON.stringify({
2313
2293
  currency: 'PEN',
2314
2294
  payment_configuration: '',
2315
- payment_type: 'upr',
2316
2295
  total_amount: { value: 1000, offset: 100 },
2317
2296
  reference_id: 'ORDER_001',
2318
2297
  type: 'physical-goods',
@@ -2320,14 +2299,16 @@ await conn.sendReviewAndPay(chatJid, {
2320
2299
  status: 'pending',
2321
2300
  description: 'Pedido de prueba',
2322
2301
  order_type: 'PAYMENT_REQUEST',
2302
+ subtotal: { value: 1000, offset: 100 },
2323
2303
  items: [{ name: 'Producto', amount: { value: 1000, offset: 100 }, quantity: 1 }]
2324
2304
  },
2325
- payment_settings: []
2305
+ payment_settings: [],
2306
+ native_payment_methods: []
2326
2307
  })
2327
2308
  }, {});
2328
2309
  ```
2329
2310
 
2330
- This sends a WhatsApp Native Flow payment-request UI payload only. It does not charge, settle or verify a payment, and rendering depends on WhatsApp client/account support and valid payment-provider data. The generic helper deliberately does not embed personal payment accounts.
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.
2331
2312
 
2332
2313
  ### Media status and view-once messages
2333
2314
 
@@ -2337,3 +2318,7 @@ Use `getMediaDownloadStatus(message)` to inspect ordinary media availability. It
2337
2318
 
2338
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.
2339
2320
 
2321
+
2322
+ ## Integrated validation suite
2323
+
2324
+ Run `npm install` before the full suite. `npm test` executes every Kage test, including the Native Flow and protobuf runtime tests that require declared runtime dependencies. `npm run test:offline` executes the isolated offline suite that does not need those external packages. Pairing request construction is tested in `test/pairing-code.test.mjs`, including the single-byte NUL nonce and extraction of the server-issued pairing reference.
@@ -34,7 +34,7 @@ export interface ReviewAndPayOptions {
34
34
  paymentAccounts?: PaymentAccount[];
35
35
  paymentSettings?: PaymentAccount[];
36
36
  paymentParams?: Record<string, unknown> | string;
37
- /** Pre-serialized Native Flow button JSON; forwarded unchanged after JSON validation. */
37
+ /** Pre-serialized Native Flow JSON; structurally validated before relay. */
38
38
  buttonParamsJson?: Record<string, unknown> | string;
39
39
  button_params_json?: Record<string, unknown> | string;
40
40
  messageParamsJson?: string;
@@ -48,6 +48,6 @@ export interface ReviewAndPayOptions {
48
48
  }
49
49
 
50
50
  export function buildReviewAndPayMessage(options?: ReviewAndPayOptions): Promise<proto.IMessage>;
51
- export function sendReviewAndPay(conn: { relayMessage(jid: string, content: proto.IMessage, options?: Record<string, unknown>): Promise<unknown> }, jid: string, options?: ReviewAndPayOptions, relayOptions?: Record<string, unknown>): Promise<unknown>;
51
+ export function sendReviewAndPay(conn: { user?: { id?: string; lid?: string }; authState?: { creds?: { me?: { id?: string; lid?: string } } }; relayMessage(jid: string, content: proto.IMessage, options?: Record<string, unknown>): Promise<unknown> }, jid: string, options?: ReviewAndPayOptions, relayOptions?: Record<string, unknown>): Promise<unknown>;
52
52
  declare const _default: { buildReviewAndPayMessage: typeof buildReviewAndPayMessage; sendReviewAndPay: typeof sendReviewAndPay };
53
53
  export default _default;
@@ -4,6 +4,9 @@
4
4
  * this function does not collect, validate or process actual payments.
5
5
  */
6
6
  import { normalizeThumbnail } from './media-thumb.js';
7
+ import { generateWAMessageFromContent } from '../lib/Utils/messages.js';
8
+ import { getBizBinaryNode } from '../lib/WABinary/index.js';
9
+ import { prepareNativeFlowMessageForRelay } from '../lib/Utils/native-flow.js';
7
10
 
8
11
  const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
9
12
  const positiveInteger = (value, name) => {
@@ -32,6 +35,9 @@ function normalizePaymentAccounts(accounts) {
32
35
  if (typeof identifier !== 'string' || !identifier.trim()) {
33
36
  throw new TypeError(`paymentAccounts[${index}] needs a nonempty identifier_value`);
34
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
+ }
35
41
  const result = { ...entry, type: entry.type || 'payment_account', payment_account: { ...paymentAccount } };
36
42
  delete result.paymentAccount;
37
43
  if (result.payment_account.identifierValue !== undefined && result.payment_account.identifier_value === undefined) {
@@ -72,7 +78,7 @@ function normalizePaymentParams(options) {
72
78
  const totalAmount = options.totalAmount ?? supplied?.total_amount ?? supplied?.totalAmount;
73
79
  const orderItems = options.items ?? supplied?.order?.items ?? [{
74
80
  name: options.itemName ?? 'Producto',
75
- amount: amountObject(options.itemValue ?? 138, options.offset ?? 100, 'item.amount'),
81
+ amount: amountObject(options.itemValue ?? options.totalValue ?? 137, options.offset ?? 100, 'item.amount'),
76
82
  quantity: positiveInteger(options.quantity ?? 1, 'quantity')
77
83
  }];
78
84
  if (!Array.isArray(orderItems) || orderItems.length === 0) throw new TypeError('order.items must contain at least one item');
@@ -81,7 +87,7 @@ function normalizePaymentParams(options) {
81
87
  if (!isObject(item)) throw new TypeError(`order.items[${index}] must be an object`);
82
88
  const name = item.name ?? item.title;
83
89
  if (typeof name !== 'string' || !name.trim()) throw new TypeError(`order.items[${index}].name is required`);
84
- const itemAmount = item.amount ?? { value: options.itemValue ?? 138, offset: options.offset ?? 100 };
90
+ const itemAmount = item.amount ?? { value: options.itemValue ?? options.totalValue ?? 137, offset: options.offset ?? 100 };
85
91
  return {
86
92
  ...item,
87
93
  name: name.trim(),
@@ -91,21 +97,41 @@ function normalizePaymentParams(options) {
91
97
  });
92
98
 
93
99
  const accounts = options.paymentAccounts ?? options.paymentSettings ?? options.payment_settings ?? supplied?.payment_settings ?? [];
100
+ const offset = normalizedItems[0].amount.offset;
101
+ if (normalizedItems.some(item => item.amount.offset !== offset)) {
102
+ throw new TypeError('All order item amounts must use the same offset');
103
+ }
104
+ const itemTotal = normalizedItems.reduce((sum, item) => {
105
+ return sum + BigInt(item.amount.value) * BigInt(item.quantity);
106
+ }, 0n);
107
+ if (itemTotal > BigInt(Number.MAX_SAFE_INTEGER)) throw new RangeError('Order item total exceeds the safe integer range');
108
+ const normalizedTotal = amountObject(
109
+ totalAmount ?? options.totalValue ?? { value: Number(itemTotal), offset },
110
+ offset,
111
+ 'total_amount'
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');
115
+ }
94
116
  const params = {
95
117
  currency,
96
118
  payment_configuration: options.paymentConfiguration ?? supplied?.payment_configuration ?? '',
97
- payment_type: options.paymentType ?? supplied?.payment_type ?? 'upr',
98
- total_amount: amountObject(totalAmount ?? { value: options.totalValue ?? 137, offset: options.offset ?? 100 }, options.offset ?? 100, 'total_amount'),
119
+ ...(options.paymentType ?? supplied?.payment_type
120
+ ? { payment_type: options.paymentType ?? supplied.payment_type }
121
+ : {}),
122
+ total_amount: normalizedTotal,
99
123
  reference_id: String(options.referenceId ?? options.reference_id ?? supplied?.reference_id ?? `KAGE_${Date.now()}`),
100
124
  type: options.type ?? supplied?.type ?? 'physical-goods',
101
125
  order: {
102
126
  ...(isObject(supplied?.order) ? supplied.order : {}),
103
127
  status: options.orderStatus ?? supplied?.order?.status ?? 'pending',
104
128
  description: options.orderDescription ?? supplied?.order?.description ?? 'Descripción',
129
+ subtotal: { value: Number(itemTotal), offset },
105
130
  order_type: options.orderType ?? supplied?.order?.order_type ?? 'PAYMENT_REQUEST',
106
131
  items: normalizedItems
107
132
  },
108
133
  payment_settings: normalizePaymentAccounts(accounts),
134
+ native_payment_methods: options.nativePaymentMethods ?? supplied?.native_payment_methods ?? [],
109
135
  additional_note: options.additionalNote ?? options.additional_note ?? supplied?.additional_note ?? '',
110
136
  share_payment_status: options.sharePaymentStatus ?? supplied?.share_payment_status ?? false,
111
137
  is_soft_deleted: options.isSoftDeleted ?? supplied?.is_soft_deleted ?? false
@@ -178,7 +204,7 @@ export async function buildReviewAndPayMessage(options = {}) {
178
204
  };
179
205
  if (!thumbnail) delete header.jpegThumbnail;
180
206
 
181
- return {
207
+ const payload = {
182
208
  interactiveMessage: {
183
209
  header,
184
210
  body: { text: body },
@@ -191,6 +217,8 @@ export async function buildReviewAndPayMessage(options = {}) {
191
217
  contextInfo: options.contextInfo ? { ...options.contextInfo } : {}
192
218
  }
193
219
  };
220
+ prepareNativeFlowMessageForRelay(payload);
221
+ return payload;
194
222
  }
195
223
 
196
224
  /** Build and relay the Native Flow payment request through an authenticated Baileys socket. */
@@ -198,7 +226,24 @@ export async function sendReviewAndPay(conn, jid, options = {}, relayOptions = {
198
226
  if (!conn || typeof conn.relayMessage !== 'function') throw new TypeError('A connected Baileys socket with relayMessage is required');
199
227
  if (typeof jid !== 'string' || !jid.trim()) throw new TypeError('A destination JID is required');
200
228
  const payload = await buildReviewAndPayMessage(options);
201
- return conn.relayMessage(jid, payload, relayOptions ?? {});
229
+ const userJid = conn.user?.id || conn.authState?.creds?.me?.id;
230
+ const userJidLid = conn.user?.lid || conn.authState?.creds?.me?.lid;
231
+ if (!userJid) throw new Error('Socket is not authenticated: user JID is unavailable');
232
+
233
+ // Build a real WebMessageInfo first, then relay it with the business node
234
+ // required for Native Flow rendering. This also supplies a stable message ID.
235
+ const waMessage = generateWAMessageFromContent(jid, payload, { userJid, userJidLid });
236
+ const additionalNodes = Array.isArray(relayOptions?.additionalNodes)
237
+ ? [...relayOptions.additionalNodes]
238
+ : [];
239
+ const hasBizNode = additionalNodes.some(node => node?.tag === 'biz');
240
+ if (!hasBizNode) additionalNodes.push(getBizBinaryNode(waMessage.message));
241
+
242
+ return conn.relayMessage(jid, waMessage.message, {
243
+ ...(relayOptions || {}),
244
+ messageId: relayOptions?.messageId || waMessage.key.id,
245
+ additionalNodes
246
+ });
202
247
  }
203
248
 
204
249
  export default { buildReviewAndPayMessage, sendReviewAndPay };
@@ -201,6 +201,8 @@ export declare const makeBusinessSocket: (config: SocketConfig) => {
201
201
  digestKeyBundle: () => Promise<void>;
202
202
  rotateSignedPreKey: () => Promise<void>;
203
203
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
204
+ /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
205
+ cancelPairingCode: () => boolean;
204
206
  updateServerTimeOffset: ({ attrs }: BinaryNode) => void;
205
207
  sendUnifiedSession: () => Promise<void>;
206
208
  wamBuffer: import("../index.js").BinaryInfo;
@@ -109,6 +109,8 @@ export declare const makeChatsSocket: (config: SocketConfig) => {
109
109
  digestKeyBundle: () => Promise<void>;
110
110
  rotateSignedPreKey: () => Promise<void>;
111
111
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
112
+ /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
113
+ cancelPairingCode: () => boolean;
112
114
  updateServerTimeOffset: ({ attrs }: BinaryNode) => void;
113
115
  sendUnifiedSession: () => Promise<void>;
114
116
  wamBuffer: import("../index.js").BinaryInfo;
@@ -256,6 +256,8 @@ export declare const makeCommunitiesSocket: (config: SocketConfig) => {
256
256
  digestKeyBundle: () => Promise<void>;
257
257
  rotateSignedPreKey: () => Promise<void>;
258
258
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
259
+ /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
260
+ cancelPairingCode: () => boolean;
259
261
  updateServerTimeOffset: ({ attrs }: BinaryNode) => void;
260
262
  sendUnifiedSession: () => Promise<void>;
261
263
  wamBuffer: import("../index.js").BinaryInfo;
@@ -143,6 +143,8 @@ export declare const makeGroupsSocket: (config: SocketConfig) => {
143
143
  digestKeyBundle: () => Promise<void>;
144
144
  rotateSignedPreKey: () => Promise<void>;
145
145
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
146
+ /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
147
+ cancelPairingCode: () => boolean;
146
148
  updateServerTimeOffset: ({ attrs }: BinaryNode) => void;
147
149
  sendUnifiedSession: () => Promise<void>;
148
150
  wamBuffer: import("../index.js").BinaryInfo;
@@ -245,6 +245,8 @@ declare const makeWASocket: (config: UserFacingSocketConfig) => {
245
245
  digestKeyBundle: () => Promise<void>;
246
246
  rotateSignedPreKey: () => Promise<void>;
247
247
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
248
+ /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
249
+ cancelPairingCode: () => boolean;
248
250
  updateServerTimeOffset: ({ attrs }: import("../index.js").BinaryNode) => void;
249
251
  sendUnifiedSession: () => Promise<void>;
250
252
  wamBuffer: import("../index.js").BinaryInfo;
@@ -187,6 +187,8 @@ export declare const makeMessagesRecvSocket: (config: SocketConfig) => {
187
187
  digestKeyBundle: () => Promise<void>;
188
188
  rotateSignedPreKey: () => Promise<void>;
189
189
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
190
+ /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
191
+ cancelPairingCode: () => boolean;
190
192
  updateServerTimeOffset: ({ attrs }: BinaryNode) => void;
191
193
  sendUnifiedSession: () => Promise<void>;
192
194
  wamBuffer: import("../index.js").BinaryInfo;
@@ -13,6 +13,7 @@ import viewOnceStub from '../Utils/media-message-guards.cjs';
13
13
  const { markViewOnceUnavailable } = viewOnceStub;
14
14
  import { buildAckStanza } from '../Utils/stanza-ack.js';
15
15
  import { buildMergedTcTokenIndexWrite, isTcTokenExpired, readTcTokenIndex, resolveIssuanceJid, resolveTcTokenJid, storeTcTokensFromIqResult, TC_TOKEN_INDEX_KEY } from '../Utils/tc-token-utils.js';
16
+ import { isValidPairingRef } from '../Utils/pairing-code.js';
16
17
  import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, getBinaryNodeChildUInt, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
17
18
  import { extractGroupMetadata } from './groups.js';
18
19
  import { makeMessagesSocket } from './messages-send.js';
@@ -796,6 +797,91 @@ export const makeMessagesRecvSocket = (config) => {
796
797
  }
797
798
  });
798
799
  };
800
+ // Pairing-code notifications are ACKed by handleNotification after this
801
+ // function returns. Start companion_finish in the background so the ACK is
802
+ // sent immediately, matching the current WhatsApp Web sequence.
803
+ let pairingPrimaryHelloAttempts = 0;
804
+ let pairingFinishInFlight = false;
805
+ const processPairingPrimaryHello = (linkCodeCompanionReg) => {
806
+ const creds = authState.creds;
807
+ const receivedRefValue = getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref');
808
+ if (!isValidPairingRef(creds, receivedRefValue)) {
809
+ logger.warn('ignored primary_hello: pairing code missing, expired, or server reference does not match');
810
+ return;
811
+ }
812
+ const expectedRef = Buffer.from(creds.pairingCodeRef);
813
+ if (pairingFinishInFlight) {
814
+ logger.debug('ignored duplicate primary_hello while companion_finish is in flight');
815
+ return;
816
+ }
817
+ if (pairingPrimaryHelloAttempts >= 3) {
818
+ logger.warn('ignored primary_hello after the three-attempt pairing limit');
819
+ return;
820
+ }
821
+ pairingPrimaryHelloAttempts += 1;
822
+ pairingFinishInFlight = true;
823
+
824
+ void (async () => {
825
+ try {
826
+ const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
827
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
828
+ if (primaryEphemeralPublicKeyWrapped.length !== 80) {
829
+ throw new Boom('Invalid wrapped primary ephemeral public key length.', { statusCode: 400 });
830
+ }
831
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
832
+ const companionSharedKey = Curve.sharedKey(creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
833
+ const random = randomBytes(32);
834
+ const linkCodeSalt = randomBytes(32);
835
+ const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
836
+ salt: linkCodeSalt,
837
+ info: 'link_code_pairing_key_bundle_encryption_key'
838
+ });
839
+ const encryptPayload = Buffer.concat([
840
+ Buffer.from(creds.signedIdentityKey.public),
841
+ primaryIdentityPublicKey,
842
+ random
843
+ ]);
844
+ const encryptIv = randomBytes(12);
845
+ const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
846
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
847
+ const identitySharedKey = Curve.sharedKey(creds.signedIdentityKey.private, primaryIdentityPublicKey);
848
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
849
+ creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
850
+ // Use the ref returned by companion_hello, never a ref echoed by
851
+ // the phone notification. A successful IQ alone does not mark
852
+ // the account registered; pair-success performs that transition.
853
+ await query({
854
+ tag: 'iq',
855
+ attrs: {
856
+ to: S_WHATSAPP_NET,
857
+ type: 'set',
858
+ id: sock.generateMessageTag(),
859
+ xmlns: 'md'
860
+ },
861
+ content: [
862
+ {
863
+ tag: 'link_code_companion_reg',
864
+ attrs: { jid: creds.me.id, stage: 'companion_finish' },
865
+ content: [
866
+ { tag: 'link_code_pairing_wrapped_key_bundle', attrs: {}, content: encryptedPayload },
867
+ { tag: 'companion_identity_public', attrs: {}, content: creds.signedIdentityKey.public },
868
+ { tag: 'link_code_pairing_ref', attrs: {}, content: expectedRef }
869
+ ]
870
+ }
871
+ ]
872
+ });
873
+ ev.emit('creds.update', creds);
874
+ logger.info({ attempt: pairingPrimaryHelloAttempts }, 'companion_finish accepted; awaiting pair-success');
875
+ }
876
+ catch (error) {
877
+ logger.error({ error }, 'failed to complete pairing-code companion_finish');
878
+ }
879
+ finally {
880
+ pairingFinishInFlight = false;
881
+ }
882
+ })();
883
+ };
884
+
799
885
  const processNotification = async (node) => {
800
886
  const result = {};
801
887
  const [child] = getAllBinaryNodeChildren(node);
@@ -881,68 +967,18 @@ export const makeMessagesRecvSocket = (config) => {
881
967
  }
882
968
  }
883
969
  break;
884
- case 'link_code_companion_reg':
970
+ case 'link_code_companion_reg': {
885
971
  const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
886
- const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
887
- const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
888
- const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
889
- const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
890
- const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
891
- const random = randomBytes(32);
892
- const linkCodeSalt = randomBytes(32);
893
- const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
894
- salt: linkCodeSalt,
895
- info: 'link_code_pairing_key_bundle_encryption_key'
896
- });
897
- const encryptPayload = Buffer.concat([
898
- Buffer.from(authState.creds.signedIdentityKey.public),
899
- primaryIdentityPublicKey,
900
- random
901
- ]);
902
- const encryptIv = randomBytes(12);
903
- const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
904
- const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
905
- const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
906
- const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
907
- authState.creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
908
- await query({
909
- tag: 'iq',
910
- attrs: {
911
- to: S_WHATSAPP_NET,
912
- type: 'set',
913
- id: sock.generateMessageTag(),
914
- xmlns: 'md'
915
- },
916
- content: [
917
- {
918
- tag: 'link_code_companion_reg',
919
- attrs: {
920
- jid: authState.creds.me.id,
921
- stage: 'companion_finish'
922
- },
923
- content: [
924
- {
925
- tag: 'link_code_pairing_wrapped_key_bundle',
926
- attrs: {},
927
- content: encryptedPayload
928
- },
929
- {
930
- tag: 'companion_identity_public',
931
- attrs: {},
932
- content: authState.creds.signedIdentityKey.public
933
- },
934
- {
935
- tag: 'link_code_pairing_ref',
936
- attrs: {},
937
- content: ref
938
- }
939
- ]
940
- }
941
- ]
942
- });
943
- authState.creds.registered = true;
944
- ev.emit('creds.update', authState.creds);
972
+ // companion_hello responses are IQ results, not notifications.
973
+ // Only primary_hello starts the companion_finish crypto exchange.
974
+ if (linkCodeCompanionReg?.attrs?.stage === 'primary_hello') {
975
+ processPairingPrimaryHello(linkCodeCompanionReg);
976
+ }
977
+ else {
978
+ logger.debug({ stage: linkCodeCompanionReg?.attrs?.stage }, 'ignored non-primary pairing notification');
979
+ }
945
980
  break;
981
+ }
946
982
  case 'privacy_token':
947
983
  await handlePrivacyTokenNotification(node);
948
984
  break;
@@ -184,6 +184,8 @@ export declare const makeMessagesSocket: (config: SocketConfig) => {
184
184
  digestKeyBundle: () => Promise<void>;
185
185
  rotateSignedPreKey: () => Promise<void>;
186
186
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
187
+ /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
188
+ cancelPairingCode: () => boolean;
187
189
  updateServerTimeOffset: ({ attrs }: BinaryNode) => void;
188
190
  sendUnifiedSession: () => Promise<void>;
189
191
  wamBuffer: import("../index.js").BinaryInfo;
@@ -4,10 +4,11 @@ import { proto } from '../../WAProto/index.js';
4
4
  import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
5
  import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
6
6
  import { getUrlInfo } from '../Utils/link-preview.js';
7
+ import { prepareNativeFlowMessageForRelay } from '../Utils/native-flow.js';
7
8
  import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
8
9
  import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
9
10
  import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
10
- import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
11
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, getBizBinaryNode, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
11
12
  import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
13
  import { makeNewsletterSocket } from './newsletter.js';
13
14
  export const makeMessagesSocket = (config) => {
@@ -454,6 +455,8 @@ export const makeMessagesSocket = (config) => {
454
455
  useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
455
456
  const participants = [];
456
457
  const destinationJid = !isStatus ? finalJid : statusJid;
458
+ const relayContent = normalizeMessageContent(message) || message;
459
+ prepareNativeFlowMessageForRelay(relayContent);
457
460
  const binaryNodeContent = [];
458
461
  const devices = [];
459
462
  let reportingMessage;
@@ -839,9 +842,44 @@ export const makeMessagesSocket = (config) => {
839
842
  });
840
843
  }
841
844
  if (additionalNodes && additionalNodes.length > 0) {
842
- ;
843
845
  stanza.content.push(...additionalNodes);
844
846
  }
847
+
848
+ // Kage Antigua adds a companion <biz> node for Native Flow. For
849
+ // review_and_pay, getBizBinaryNode maps the button to
850
+ // native_flow_name="order_details". Do not add <bot> to ordinary
851
+ // private chats: recent Baileys forks guard that marker because
852
+ // unqualified bot markers can cause user messages to be rejected.
853
+ const relayInteractive = relayContent?.interactiveMessage;
854
+ const needsBizNode = Boolean(
855
+ relayContent?.buttonsMessage ||
856
+ relayContent?.listMessage ||
857
+ relayContent?.templateMessage ||
858
+ relayInteractive?.nativeFlowMessage ||
859
+ relayInteractive?.carouselMessage
860
+ );
861
+ if (needsBizNode && !isNewsletter && !isRetryResend) {
862
+ const generatedBizNode = getBizBinaryNode(relayContent);
863
+ const existingBizIndex = stanza.content.findIndex(node => node?.tag === 'biz');
864
+ if (existingBizIndex < 0) {
865
+ stanza.content.push(generatedBizNode);
866
+ }
867
+ else {
868
+ const existingBizNode = stanza.content[existingBizIndex];
869
+ const mergedContent = [...(generatedBizNode.content || [])];
870
+ for (const child of (existingBizNode.content || [])) {
871
+ if (!mergedContent.some(item => item?.tag === child?.tag)) mergedContent.push(child);
872
+ }
873
+ stanza.content[existingBizIndex] = {
874
+ ...existingBizNode,
875
+ ...generatedBizNode,
876
+ attrs: { ...(existingBizNode.attrs || {}), ...(generatedBizNode.attrs || {}) },
877
+ ...(mergedContent.length ? { content: mergedContent } : {})
878
+ };
879
+ }
880
+ logger.debug({ msgId, flow: relayInteractive?.nativeFlowMessage?.buttons?.[0]?.name },
881
+ 'added Native Flow biz companion node');
882
+ }
845
883
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
846
884
  await sendNode(stanza);
847
885
  // Fire-and-forget: issue our token to the contact AFTER message send.
@@ -154,6 +154,8 @@ export declare const makeNewsletterSocket: (config: SocketConfig) => {
154
154
  digestKeyBundle: () => Promise<void>;
155
155
  rotateSignedPreKey: () => Promise<void>;
156
156
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
157
+ /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
158
+ cancelPairingCode: () => boolean;
157
159
  updateServerTimeOffset: ({ attrs }: import("../index.js").BinaryNode) => void;
158
160
  sendUnifiedSession: () => Promise<void>;
159
161
  wamBuffer: import("../index.js").BinaryInfo;
@@ -42,6 +42,8 @@ export declare const makeSocket: (config: SocketConfig) => {
42
42
  digestKeyBundle: () => Promise<void>;
43
43
  rotateSignedPreKey: () => Promise<void>;
44
44
  requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
45
+ /** Cancel the active pairing-code request and restore the previous temporary auth fields. */
46
+ cancelPairingCode: () => boolean;
45
47
  updateServerTimeOffset: ({ attrs }: BinaryNode) => void;
46
48
  sendUnifiedSession: () => Promise<void>;
47
49
  wamBuffer: BinaryInfo;