kage-baileys 25.4.19 → 26.11.32
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 +31 -17
- package/helpers/interactive-pay.js +13 -13
- package/lib/Defaults/index.js +3 -3
- package/lib/Defaults/media.cjs +2 -2
- package/lib/Socket/messages-recv.d.ts +1 -1
- package/lib/Socket/messages-recv.js +3 -3
- package/lib/Socket/messages-send.d.ts +1 -1
- package/lib/Socket/socket.d.ts +1 -1
- package/lib/Socket/socket.js +18 -61
- package/lib/Types/Auth.d.ts +1 -3
- package/lib/Types/Message.d.ts +18 -1
- package/lib/Types/Socket.d.ts +0 -2
- package/lib/Utils/browser-utils.js +34 -6
- package/lib/Utils/companion-reg-client-utils.js +65 -5
- package/lib/Utils/interactive-compat.cjs +3 -24
- package/lib/Utils/kage-messages-media.cjs +14 -2
- package/lib/Utils/kage-messages.cjs +36 -11
- package/lib/Utils/messages-media.js +14 -2
- package/lib/Utils/messages.js +1 -1
- package/lib/Utils/native-flow.d.ts +0 -3
- package/lib/Utils/native-flow.js +98 -144
- package/lib/Utils/pairing-code.d.ts +0 -4
- package/lib/Utils/pairing-code.js +7 -45
- package/package.json +7 -6
- package/scripts/verify-pairing-flow.mjs +21 -64
- package/scripts/verify-sticker-pack.mjs +38 -0
- package/scripts/verify-native-flow-payments.mjs +0 -167
- package/scripts/verify-placeholder-payment-accounts.mjs +0 -42
package/README.md
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
# KAGE BAILEYS
|
|
6
6
|
|
|
7
|
-
**Kage Baileys —
|
|
8
|
-
|
|
7
|
+
**Kage Baileys — edición de mantenimiento del 30 de noviembre de 2026.**
|
|
8
|
+
Motor extendido de WhatsApp Web: portada de perfil (cuentas normales y Business), avatares por defecto estilo WhatsApp, botones, carruseles, Native Flows, VoIP, canales, comunidades, Meta AI, mapeo LID, álbumes, tablas, bloques de código y soporte total del protocolo. Documentación 100 % en español.
|
|
9
9
|
|
|
10
10
|
Documentación 100 % en español
|
|
11
11
|
|
|
@@ -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
|
-
###
|
|
248
|
+
### Conexión automática en el evento `connecting`
|
|
249
249
|
|
|
250
|
-
|
|
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`
|
|
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
|
|
|
@@ -1212,7 +1221,7 @@ await sock.sendMessage(jid, {
|
|
|
1212
1221
|
### Paquete de stickers
|
|
1213
1222
|
|
|
1214
1223
|
> [!IMPORTANT]
|
|
1215
|
-
>
|
|
1224
|
+
> Para convertir archivos que no sean WebP instala `sharp` o `@napi-rs/image`. Si los stickers y la portada ya son WebP, no necesitan conversión.
|
|
1216
1225
|
|
|
1217
1226
|
```javascript
|
|
1218
1227
|
await sock.sendMessage(jid, {
|
|
@@ -1220,21 +1229,26 @@ await sock.sendMessage(jid, {
|
|
|
1220
1229
|
name: 'Mi pack',
|
|
1221
1230
|
publisher: 'kage-baileys',
|
|
1222
1231
|
description: 'Descripción',
|
|
1232
|
+
packId: 'mi-pack-01', // opcional
|
|
1223
1233
|
cover: Buffer, // Buffer de imagen
|
|
1224
1234
|
stickers: [
|
|
1225
1235
|
{
|
|
1226
|
-
|
|
1227
|
-
emojis: ['❤'],
|
|
1228
|
-
accessibilityLabel: '',
|
|
1236
|
+
data: Buffer, // también se acepta la propiedad sticker
|
|
1237
|
+
emojis: ['❤'], // opcional
|
|
1238
|
+
accessibilityLabel: '', // opcional
|
|
1229
1239
|
isLottie: false, // opcional
|
|
1230
1240
|
isAnimated: false // opcional
|
|
1231
1241
|
},
|
|
1232
|
-
{ sticker:
|
|
1242
|
+
{ sticker: { url: 'https://example.com/sticker.webp' }, emojis: ['❤'] }
|
|
1233
1243
|
]
|
|
1234
1244
|
}
|
|
1235
|
-
})
|
|
1245
|
+
}, { quoted: message })
|
|
1236
1246
|
```
|
|
1237
1247
|
|
|
1248
|
+
El envío genera un único mensaje `stickerPackMessage`: crea el ZIP del paquete, cifra los datos, sube el archivo y la miniatura y después construye el protobuf de WhatsApp. Se admiten `data`, `sticker` o un `Buffer` directo en cada entrada.
|
|
1249
|
+
|
|
1250
|
+
Para ver los cambios de compatibilidad y sus límites, consulta [REPARACION-STICKER-PACK-ES.md](REPARACION-STICKER-PACK-ES.md) y [INFORME-INTEGRACION-ES.md](INFORME-INTEGRACION-ES.md).
|
|
1251
|
+
|
|
1238
1252
|
## 👁️ Opciones adicionales de mensajes
|
|
1239
1253
|
|
|
1240
1254
|
### Visualización única (view once)
|
|
@@ -2273,7 +2287,7 @@ This Kage build incorporates the compatible additions identified in the attached
|
|
|
2273
2287
|
|
|
2274
2288
|
### Native Flow `review_and_pay`
|
|
2275
2289
|
|
|
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`,
|
|
2290
|
+
`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
2291
|
|
|
2278
2292
|
```js
|
|
2279
2293
|
await conn.sendReviewAndPay(chatJid, {
|
|
@@ -2299,7 +2313,7 @@ await conn.sendReviewAndPay(chatJid, {
|
|
|
2299
2313
|
}, {});
|
|
2300
2314
|
```
|
|
2301
2315
|
|
|
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
|
|
2316
|
+
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
2317
|
|
|
2304
2318
|
### Media status and view-once messages
|
|
2305
2319
|
|
|
@@ -2310,15 +2324,15 @@ Use `getMediaDownloadStatus(message)` to inspect ordinary media availability. It
|
|
|
2310
2324
|
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
2325
|
|
|
2312
2326
|
|
|
2313
|
-
## Kage 25.4.
|
|
2327
|
+
## Kage 25.4.10: pairing and Native Flow
|
|
2314
2328
|
|
|
2315
|
-
When `requestPairingCode(phoneNumber)` is called without a custom code, Kage generates `KAGE` followed by four cryptographically random
|
|
2329
|
+
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
2330
|
|
|
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`
|
|
2331
|
+
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
2332
|
|
|
2319
2333
|
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
2334
|
|
|
2321
2335
|
## Package validation
|
|
2322
2336
|
|
|
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.
|
|
2337
|
+
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
2338
|
|
|
@@ -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 {
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
144
|
-
if (isObject(supplied.order))
|
|
142
|
+
const merged = { ...supplied, ...params };
|
|
143
|
+
if (isObject(supplied.order)) merged.order = { ...supplied.order, ...params.order };
|
|
144
|
+
return merged;
|
|
145
145
|
}
|
|
146
|
-
return
|
|
146
|
+
return params;
|
|
147
147
|
}
|
|
148
148
|
|
|
149
149
|
function getRawButtonParamsJson(options) {
|
package/lib/Defaults/index.js
CHANGED
|
@@ -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.
|
|
52
|
+
browser: Browsers.macOS('Chrome'),
|
|
53
53
|
waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
|
|
54
54
|
connectTimeoutMs: 20000,
|
|
55
55
|
keepAliveIntervalMs: 30000,
|
|
@@ -117,8 +117,8 @@ export const MEDIA_HKDF_KEY_MAPPING = {
|
|
|
117
117
|
'biz-cover-photo': 'Image'
|
|
118
118
|
};
|
|
119
119
|
Object.assign(MEDIA_PATH_MAP, {
|
|
120
|
-
'sticker-pack': '/mms/sticker',
|
|
121
|
-
'thumbnail-sticker-pack': '/mms/
|
|
120
|
+
'sticker-pack': '/mms/sticker-pack',
|
|
121
|
+
'thumbnail-sticker-pack': '/mms/thumbnail-sticker-pack',
|
|
122
122
|
'thumbnail-link': '/mms/image',
|
|
123
123
|
'thumbnail-image': '/mms/image',
|
|
124
124
|
'thumbnail-video': '/mms/video',
|
package/lib/Defaults/media.cjs
CHANGED
|
@@ -8,8 +8,8 @@ const MEDIA_PATH_MAP = {
|
|
|
8
8
|
document: '/mms/document',
|
|
9
9
|
audio: '/mms/audio',
|
|
10
10
|
sticker: '/mms/image',
|
|
11
|
-
'sticker-pack': '/mms/sticker',
|
|
12
|
-
'thumbnail-sticker-pack': '/mms/
|
|
11
|
+
'sticker-pack': '/mms/sticker-pack',
|
|
12
|
+
'thumbnail-sticker-pack': '/mms/thumbnail-sticker-pack',
|
|
13
13
|
'thumbnail-link': '/mms/image',
|
|
14
14
|
'product-catalog-image': '/product/image',
|
|
15
15
|
'md-app-state': '',
|
|
@@ -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-
|
|
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
|
|
813
|
+
logger.warn('ignored primary_hello: pairing code missing, expired, or server reference does not match');
|
|
814
814
|
return false;
|
|
815
815
|
}
|
|
816
|
-
const
|
|
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:
|
|
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-
|
|
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;
|
package/lib/Socket/socket.d.ts
CHANGED
|
@@ -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-
|
|
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;
|
package/lib/Socket/socket.js
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
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
|
|
724
|
-
//
|
|
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
|
-
|
|
747
|
-
else delete authState.creds.pairingCodeRef;
|
|
719
|
+
authState.creds.pairingCodeRef = pairingRef;
|
|
748
720
|
ev.emit('creds.update', authState.creds);
|
|
749
|
-
logger.info({ phoneNumber: normalizedNumber,
|
|
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
|
-
:
|
|
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
|
-
? `
|
|
776
|
-
: ' WhatsApp did not provide a retry time;
|
|
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
|
|
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');
|
package/lib/Types/Auth.d.ts
CHANGED
|
@@ -61,12 +61,10 @@ export type AuthenticationCreds = SignalCreds & {
|
|
|
61
61
|
accountSettings: AccountSettings;
|
|
62
62
|
registered: boolean;
|
|
63
63
|
pairingCode: string | undefined;
|
|
64
|
-
/**
|
|
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;
|
package/lib/Types/Message.d.ts
CHANGED
|
@@ -208,6 +208,22 @@ export type AnyRegularMessageContent = (({
|
|
|
208
208
|
body?: string;
|
|
209
209
|
footer?: string;
|
|
210
210
|
} | SharePhoneNumber | RequestPhoneNumber) & ViewOnce;
|
|
211
|
+
export type WAMessageStickerPackSticker = WAMediaUpload | {
|
|
212
|
+
data?: WAMediaUpload;
|
|
213
|
+
sticker?: WAMediaUpload;
|
|
214
|
+
emojis?: string[];
|
|
215
|
+
accessibilityLabel?: string;
|
|
216
|
+
isLottie?: boolean;
|
|
217
|
+
isAnimated?: boolean;
|
|
218
|
+
};
|
|
219
|
+
export type WAMessageStickerPack = {
|
|
220
|
+
name?: string;
|
|
221
|
+
publisher?: string;
|
|
222
|
+
description?: string;
|
|
223
|
+
packId?: string;
|
|
224
|
+
cover: WAMediaUpload;
|
|
225
|
+
stickers: WAMessageStickerPackSticker[];
|
|
226
|
+
};
|
|
211
227
|
export type KageMessageContent =
|
|
212
228
|
| { raw: proto.IMessage }
|
|
213
229
|
| { audioSticker: WAMediaUpload }
|
|
@@ -216,7 +232,8 @@ export type KageMessageContent =
|
|
|
216
232
|
| { links: unknown[]; title?: string }
|
|
217
233
|
| { table: unknown; title?: string }
|
|
218
234
|
| { richResponse: unknown }
|
|
219
|
-
| { stickers:
|
|
235
|
+
| ({ stickers: WAMessageStickerPackSticker[]; name?: string; publisher?: string; description?: string; packId?: string; cover: WAMediaUpload })
|
|
236
|
+
| { stickerPack: WAMessageStickerPack }
|
|
220
237
|
| { flowReply: unknown }
|
|
221
238
|
| { listReply: unknown }
|
|
222
239
|
| { orderText: string }
|
package/lib/Types/Socket.d.ts
CHANGED
|
@@ -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
|
-
|
|
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 => [
|
|
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
|
-
|
|
29
|
-
|
|
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
|