kage-baileys 25.4.17 → 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
@@ -1108,7 +1108,7 @@ await conn.sendReviewAndPay(m.chat, {
1108
1108
  })
1109
1109
  ```
1110
1110
 
1111
- `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/).
1112
1112
 
1113
1113
  ### Helpers de fotos y perfil
1114
1114
 
@@ -2273,7 +2273,7 @@ This Kage build incorporates the compatible additions identified in the attached
2273
2273
 
2274
2274
  ### Native Flow `review_and_pay`
2275
2275
 
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`, 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:
2277
2277
 
2278
2278
  ```js
2279
2279
  await conn.sendReviewAndPay(chatJid, {
@@ -2299,7 +2299,7 @@ await conn.sendReviewAndPay(chatJid, {
2299
2299
  }, {});
2300
2300
  ```
2301
2301
 
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 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.
2303
2303
 
2304
2304
  ### Media status and view-once messages
2305
2305
 
@@ -2310,15 +2310,15 @@ Use `getMediaDownloadStatus(message)` to inspect ordinary media availability. It
2310
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.
2311
2311
 
2312
2312
 
2313
- ## Kage 25.4.15: pairing, reconnect and Native Flow
2313
+ ## Kage 25.4.16: payment amount normalization
2314
2314
 
2315
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.
2316
2316
 
2317
- For `review_and_pay`, `relayMessage()` adds the `biz` node with `native_flow_name="order_details"`, merges compatible custom `biz` nodes, and supplies `messageParamsJson` / `messageVersion` when missing. Before sending, it validates the payment JSON and JPEG thumbnail. `total_amount` must equal item subtotal plus tax and shipping minus discount. Kage never silently changes a payment amount. Replace or remove placeholder payment identifiers such as `[ACCOUNT_NUMBER]`.
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]`.
2318
2318
 
2319
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).
2320
2320
 
2321
2321
  ## Package validation
2322
2322
 
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.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`.
2324
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) {
@@ -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');
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "kage-baileys",
3
3
  "type": "module",
4
- "version": "25.4.17",
5
- "description": "Kage Baileys with hardened pairing-code validation, WhatsApp 429 cooldown, resilient reconnect classification, Native Flow validation, and expanded WAProto compatibility",
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.15.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.`);
@@ -74,8 +74,8 @@ assert.match(send, /getBizBinaryNode\(relayContent\)/,
74
74
  'Native Flow relay must attach the biz companion node');
75
75
  assert.match(send, /native_flow_name|order_details/,
76
76
  'Native Flow relay must support order_details mapping');
77
- assert.match(pay, /total_amount must equal the sum of order\.items/,
78
- 'review_and_pay must reject mismatched total/item values');
77
+ assert.match(pay, /normalizeReviewAndPayAmounts\(result\)/,
78
+ 'review_and_pay helper must reconcile total/subtotal against order lines');
79
79
  assert.match(pay, /placeholder/,
80
80
  'review_and_pay must reject placeholder payment identifiers');
81
81