kage-baileys 25.4.10 → 25.4.17
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/LICENSE +10 -2
- package/README.md +6 -15
- package/lib/Socket/messages-recv.d.ts +1 -1
- package/lib/Socket/messages-recv.js +78 -67
- package/lib/Socket/messages-send.d.ts +1 -1
- package/lib/Socket/socket.d.ts +1 -1
- package/lib/Socket/socket.js +92 -25
- package/lib/Types/Auth.d.ts +3 -1
- package/lib/Types/Socket.d.ts +2 -0
- package/lib/Utils/pairing-code.d.ts +4 -0
- package/lib/Utils/pairing-code.js +45 -7
- package/package.json +7 -9
- package/scripts/verify-pairing-flow.mjs +82 -0
- package/licenses/dnuzi-MIT.txt +0 -21
- package/licenses/elaina-native-flow-MIT.txt +0 -22
- package/licenses/itsliaaa-MIT.txt +0 -22
- package/licenses/kage-antigua-MIT.txt +0 -21
- package/licenses/rexxhayanasi-MIT.txt +0 -22
- package/licenses/upstream-MIT.txt +0 -21
- package/licenses/whiskeysockets-MIT.txt +0 -21
package/LICENSE
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
|
-
MIT
|
|
1
|
+
KAGE BAILEYS — MIT LICENSE
|
|
2
2
|
|
|
3
|
-
Copyright (c) 2025
|
|
3
|
+
Copyright (c) 2025-2026 Kage Baileys
|
|
4
|
+
|
|
5
|
+
Third-party MIT components and compatibility portions included in this distribution
|
|
6
|
+
retain the following original copyright attributions:
|
|
7
|
+
- Copyright (c) 2025 Rajeh Taher / WhiskeySockets
|
|
8
|
+
- Copyright (c) 2026 Lia Wynn (itsliaaa/baileys)
|
|
9
|
+
- Copyright (c) 2026 DanuZz Lk (dnuzi/baileys)
|
|
10
|
+
- Copyright (c) 2026 rexxhayanasi (Elaina Baileys)
|
|
11
|
+
- Copyright (c) 2025-2026 Kage Baileys (Kage Antigua)
|
|
4
12
|
|
|
5
13
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
14
|
of this software and associated documentation files (the "Software"), to deal
|
package/README.md
CHANGED
|
@@ -245,18 +245,9 @@ console.log('🔑 Código personalizado:', code)
|
|
|
245
245
|
> [!NOTE]
|
|
246
246
|
> El código de emparejamiento no forma parte de la API móvil: conecta WhatsApp Web sin QR, pero solo en un dispositivo. La disponibilidad y los límites dependen de WhatsApp.
|
|
247
247
|
|
|
248
|
-
###
|
|
248
|
+
### Solicitar un código sin repetir solicitudes
|
|
249
249
|
|
|
250
|
-
|
|
251
|
-
sock.ev.on('connection.update', async (update) => {
|
|
252
|
-
const { connection } = update
|
|
253
|
-
if (connection === 'connecting' && !sock.authState.creds.registered) {
|
|
254
|
-
await delay(1500)
|
|
255
|
-
const code = await sock.requestPairingCode(myPhoneNumber)
|
|
256
|
-
console.log('🔗 Código:', code)
|
|
257
|
-
}
|
|
258
|
-
})
|
|
259
|
-
```
|
|
250
|
+
Solicita el código una sola vez, mediante una acción explícita de configuración o del propietario, cuando el socket ya haya completado el inicio de la conexión. No llames `requestPairingCode()` en cada evento `connecting` ni cada vez que se reconstruya el socket. Guarda fuera del socket el estado de la solicitud para que el reconector de tu aplicación no vuelva a pedir códigos automáticamente. Si recibes `429`, detén las solicitudes y espera el cooldown; reiniciar el proceso no elimina un límite aplicado por WhatsApp.
|
|
260
251
|
|
|
261
252
|
### Recibir el historial completo
|
|
262
253
|
|
|
@@ -2208,7 +2199,7 @@ Los mantenedores de kage-baileys no respaldan el uso de esta librería para viol
|
|
|
2208
2199
|
|
|
2209
2200
|
Distribuido bajo la **Licencia GPL-3.0**. Consulta [LICENSE](LICENSE) para más información.
|
|
2210
2201
|
|
|
2211
|
-
La identidad del paquete es **Kage Baileys**.
|
|
2202
|
+
La identidad del paquete es **Kage Baileys**. Se distribuye un único archivo raíz `LICENSE`, que consolida la licencia MIT de Kage y las atribuciones de copyright de los fragmentos compatibles de terceros. La redistribución debe respetar sus condiciones.
|
|
2212
2203
|
|
|
2213
2204
|
### Seguridad de dependencias
|
|
2214
2205
|
|
|
@@ -2319,9 +2310,9 @@ Use `getMediaDownloadStatus(message)` to inspect ordinary media availability. It
|
|
|
2319
2310
|
The root package and `./Utils/*` subpaths now expose additional auth-state adapters (MongoDB, MySQL, PostgreSQL, Redis, SQLite, single-file and NekoDB), TTL cache, sender-key memory helpers, group metadata validation, username validation, modern message constructors, status sticker builders, social link preview helpers, HTML-app validation/multiplayer helpers, scheduled-message helpers and newsletter status helpers. Database drivers are optional peer dependencies and must be installed only when the relevant adapter is used.
|
|
2320
2311
|
|
|
2321
2312
|
|
|
2322
|
-
## Kage 25.4.
|
|
2313
|
+
## Kage 25.4.15: pairing, reconnect and Native Flow
|
|
2323
2314
|
|
|
2324
|
-
When `requestPairingCode(phoneNumber)` is called without a custom code, Kage generates `KAGE` followed by four cryptographically random
|
|
2315
|
+
When `requestPairingCode(phoneNumber)` is called without a custom code, Kage generates `KAGE` followed by four cryptographically random characters from an unambiguous 32-character alphabet. The actual eight-character token has no space; display it with a space only for readability. Kage waits for WhatsApp to accept the `companion_hello` IQ request. The authoritative `link_code_pairing_ref` is then read from `primary_hello`, matching the established Kage Antigua / Baileys flow. A `rate-overlimit` response is a server-side 429 and cannot be bypassed by changing the code. Kage never retries automatically and activates a process-wide cooldown (15 minutes by default when WhatsApp supplies no retry time; configurable with `pairingRateLimitCooldownMs`). The cooldown is also stored in `authState.creds.pairingRateLimitedUntil` and is persisted when the application saves `creds.update`; this protects normal reconnects and process restarts that reuse the same saved session. If the application discards the auth state, WhatsApp's server-side limit may still remain active.
|
|
2325
2316
|
|
|
2326
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]`.
|
|
2327
2318
|
|
|
@@ -2329,5 +2320,5 @@ The Native Flow helper constructs a payment-request message only. It does not pr
|
|
|
2329
2320
|
|
|
2330
2321
|
## Package validation
|
|
2331
2322
|
|
|
2332
|
-
The `test/` source folder and source maps are intentionally excluded from this clean distribution build. `npm test` runs
|
|
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`.
|
|
2333
2324
|
|
|
@@ -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-accepted pairing code; the primary_hello notification supplies the authoritative pairing reference. */
|
|
190
190
|
requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
|
|
191
191
|
/** Cancel the active pairing-code request and restore the previous temporary auth fields. */
|
|
192
192
|
cancelPairingCode: () => boolean;
|
|
@@ -797,89 +797,100 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
797
797
|
}
|
|
798
798
|
});
|
|
799
799
|
};
|
|
800
|
-
//
|
|
801
|
-
//
|
|
802
|
-
//
|
|
800
|
+
// Match Kage Antigua's confirmed link-code sequence: complete companion_finish
|
|
801
|
+
// before ACKing primary_hello, then persist registered=true. Without this flag,
|
|
802
|
+
// a reconnect can incorrectly send a fresh registration payload and loop on 428.
|
|
803
803
|
let pairingPrimaryHelloAttempts = 0;
|
|
804
804
|
let pairingFinishInFlight = false;
|
|
805
|
-
const processPairingPrimaryHello = (linkCodeCompanionReg) => {
|
|
805
|
+
const processPairingPrimaryHello = async (linkCodeCompanionReg) => {
|
|
806
806
|
const creds = authState.creds;
|
|
807
|
+
if (creds.registered) {
|
|
808
|
+
logger.debug('ignored duplicate primary_hello: account is already registered');
|
|
809
|
+
return false;
|
|
810
|
+
}
|
|
807
811
|
const receivedRefValue = getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref');
|
|
808
812
|
if (!isValidPairingRef(creds, receivedRefValue)) {
|
|
809
|
-
logger.warn('ignored primary_hello: pairing code missing, expired, or server reference
|
|
810
|
-
return;
|
|
813
|
+
logger.warn('ignored primary_hello: pairing code missing, expired, or server reference is invalid');
|
|
814
|
+
return false;
|
|
811
815
|
}
|
|
812
|
-
const
|
|
816
|
+
const primaryHelloRef = Buffer.from(receivedRefValue);
|
|
813
817
|
if (pairingFinishInFlight) {
|
|
814
818
|
logger.debug('ignored duplicate primary_hello while companion_finish is in flight');
|
|
815
|
-
return;
|
|
819
|
+
return false;
|
|
816
820
|
}
|
|
817
821
|
if (pairingPrimaryHelloAttempts >= 3) {
|
|
818
822
|
logger.warn('ignored primary_hello after the three-attempt pairing limit');
|
|
819
|
-
return;
|
|
823
|
+
return false;
|
|
820
824
|
}
|
|
821
825
|
pairingPrimaryHelloAttempts += 1;
|
|
822
826
|
pairingFinishInFlight = true;
|
|
823
827
|
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
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');
|
|
828
|
+
try {
|
|
829
|
+
const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
|
|
830
|
+
const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
|
|
831
|
+
if (primaryEphemeralPublicKeyWrapped.length !== 80) {
|
|
832
|
+
throw new Boom('Invalid wrapped primary ephemeral public key length.', { statusCode: 400 });
|
|
878
833
|
}
|
|
879
|
-
|
|
880
|
-
|
|
834
|
+
const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
|
|
835
|
+
const companionSharedKey = Curve.sharedKey(creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
|
|
836
|
+
const random = randomBytes(32);
|
|
837
|
+
const linkCodeSalt = randomBytes(32);
|
|
838
|
+
const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
|
|
839
|
+
salt: linkCodeSalt,
|
|
840
|
+
info: 'link_code_pairing_key_bundle_encryption_key'
|
|
841
|
+
});
|
|
842
|
+
const encryptPayload = Buffer.concat([
|
|
843
|
+
Buffer.from(creds.signedIdentityKey.public),
|
|
844
|
+
primaryIdentityPublicKey,
|
|
845
|
+
random
|
|
846
|
+
]);
|
|
847
|
+
const encryptIv = randomBytes(12);
|
|
848
|
+
const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
|
|
849
|
+
const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
|
|
850
|
+
const identitySharedKey = Curve.sharedKey(creds.signedIdentityKey.private, primaryIdentityPublicKey);
|
|
851
|
+
const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
|
|
852
|
+
creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
|
|
853
|
+
|
|
854
|
+
// The server-issued companion_hello reference is authoritative.
|
|
855
|
+
await query({
|
|
856
|
+
tag: 'iq',
|
|
857
|
+
attrs: {
|
|
858
|
+
to: S_WHATSAPP_NET,
|
|
859
|
+
type: 'set',
|
|
860
|
+
id: sock.generateMessageTag(),
|
|
861
|
+
xmlns: 'md'
|
|
862
|
+
},
|
|
863
|
+
content: [
|
|
864
|
+
{
|
|
865
|
+
tag: 'link_code_companion_reg',
|
|
866
|
+
attrs: { jid: creds.me.id, stage: 'companion_finish' },
|
|
867
|
+
content: [
|
|
868
|
+
{ tag: 'link_code_pairing_wrapped_key_bundle', attrs: {}, content: encryptedPayload },
|
|
869
|
+
{ tag: 'companion_identity_public', attrs: {}, content: creds.signedIdentityKey.public },
|
|
870
|
+
{ tag: 'link_code_pairing_ref', attrs: {}, content: primaryHelloRef }
|
|
871
|
+
]
|
|
872
|
+
}
|
|
873
|
+
]
|
|
874
|
+
});
|
|
875
|
+
|
|
876
|
+
// Kage Antigua sets this only after the server accepts companion_finish.
|
|
877
|
+
// Persisting it makes the next socket use generateLoginNode(), not
|
|
878
|
+
// generateRegistrationNode(), after WhatsApp restarts the transport.
|
|
879
|
+
creds.registered = true;
|
|
880
|
+
for (const key of ['pairingCode', 'pairingCodeRef', 'pairingCodeGeneratedAt', 'pairingEphemeralKeyPair']) {
|
|
881
|
+
delete creds[key];
|
|
881
882
|
}
|
|
882
|
-
|
|
883
|
+
ev.emit('creds.update', creds);
|
|
884
|
+
logger.info({ attempt: pairingPrimaryHelloAttempts }, 'companion_finish accepted; credentials marked registered for reconnect');
|
|
885
|
+
return true;
|
|
886
|
+
}
|
|
887
|
+
catch (error) {
|
|
888
|
+
logger.error({ error }, 'failed to complete pairing-code companion_finish');
|
|
889
|
+
throw error;
|
|
890
|
+
}
|
|
891
|
+
finally {
|
|
892
|
+
pairingFinishInFlight = false;
|
|
893
|
+
}
|
|
883
894
|
};
|
|
884
895
|
|
|
885
896
|
const processNotification = async (node) => {
|
|
@@ -972,7 +983,7 @@ export const makeMessagesRecvSocket = (config) => {
|
|
|
972
983
|
// companion_hello responses are IQ results, not notifications.
|
|
973
984
|
// Only primary_hello starts the companion_finish crypto exchange.
|
|
974
985
|
if (linkCodeCompanionReg?.attrs?.stage === 'primary_hello') {
|
|
975
|
-
processPairingPrimaryHello(linkCodeCompanionReg);
|
|
986
|
+
await processPairingPrimaryHello(linkCodeCompanionReg);
|
|
976
987
|
}
|
|
977
988
|
else {
|
|
978
989
|
logger.debug({ stage: linkCodeCompanionReg?.attrs?.stage }, 'ignored non-primary pairing notification');
|
|
@@ -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-accepted pairing code; the primary_hello notification supplies the authoritative pairing reference. */
|
|
187
187
|
requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
|
|
188
188
|
/** Cancel the active pairing-code request and restore the previous temporary auth fields. */
|
|
189
189
|
cancelPairingCode: () => boolean;
|
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-accepted pairing code; the primary_hello notification supplies the authoritative pairing reference. */
|
|
45
45
|
requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
|
|
46
46
|
/** Cancel the active pairing-code request and restore the previous temporary auth fields. */
|
|
47
47
|
cancelPairingCode: () => boolean;
|
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, PAIRING_CODE_RESPONSE_GRACE_MS, buildPairingCompanionHelloNode, extractPairingReference, generateKagePairingCode, normalizePairingPhone } from '../Utils/pairing-code.js';
|
|
15
|
+
import { DEFAULT_PAIRING_CODE_TTL_MS, DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS, PAIRING_CODE_RESPONSE_GRACE_MS, buildPairingCompanionHelloNode, extractPairingReference, generateKagePairingCode, getPairingRateLimitCooldown, normalizePairingPhone, registerPairingRateLimit } from '../Utils/pairing-code.js';
|
|
16
16
|
/**
|
|
17
17
|
* Connects to WA servers and performs:
|
|
18
18
|
* - simple queries (no retry mechanism, wait for connection establishment)
|
|
@@ -286,6 +286,7 @@ export const makeSocket = (config) => {
|
|
|
286
286
|
const pairingCodeTimeoutMs = Math.max(30_000, Number(config.pairingCodeTimeoutMs) || DEFAULT_PAIRING_CODE_TTL_MS);
|
|
287
287
|
const pairingCodeMaxAgeMs = Math.min(pairingCodeTimeoutMs, DEFAULT_PAIRING_CODE_TTL_MS);
|
|
288
288
|
let pendingPairing;
|
|
289
|
+
let pairingRestartExpected = false;
|
|
289
290
|
const clearPendingPairing = ({ restore = false } = {}) => {
|
|
290
291
|
const pending = pendingPairing;
|
|
291
292
|
if (!pending) return false;
|
|
@@ -632,6 +633,30 @@ export const makeSocket = (config) => {
|
|
|
632
633
|
void end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
|
|
633
634
|
};
|
|
634
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
|
+
}
|
|
635
660
|
await connectionReady;
|
|
636
661
|
if (authState.creds.registered) {
|
|
637
662
|
throw new Boom('This session is already registered; pairing code is not required.', { statusCode: 409 });
|
|
@@ -657,6 +682,10 @@ export const makeSocket = (config) => {
|
|
|
657
682
|
}
|
|
658
683
|
|
|
659
684
|
const pairingCode = normalizedCustomPairingCode ?? generateKagePairingCode();
|
|
685
|
+
// A socket must not continue emitting rotating QR tokens while a link-code
|
|
686
|
+
// pairing request is active; the two registration paths are mutually exclusive.
|
|
687
|
+
clearTimeout(qrTimer);
|
|
688
|
+
qrTimer = undefined;
|
|
660
689
|
const previous = {
|
|
661
690
|
me: authState.creds.me,
|
|
662
691
|
pairingCode: authState.creds.pairingCode,
|
|
@@ -673,7 +702,8 @@ export const makeSocket = (config) => {
|
|
|
673
702
|
id: jidEncode(normalizedNumber, 's.whatsapp.net'),
|
|
674
703
|
name: '~'
|
|
675
704
|
};
|
|
676
|
-
|
|
705
|
+
// Keep provisional pairing fields in memory until WhatsApp acknowledges
|
|
706
|
+
// companion_hello; emitting creds.update earlier can persist an unusable code.
|
|
677
707
|
|
|
678
708
|
const pending = {
|
|
679
709
|
phoneNumber: normalizedNumber,
|
|
@@ -690,8 +720,9 @@ export const makeSocket = (config) => {
|
|
|
690
720
|
pendingPairing = pending;
|
|
691
721
|
|
|
692
722
|
try {
|
|
693
|
-
// Use an IQ query rather than sendNode(): this
|
|
694
|
-
//
|
|
723
|
+
// Use an IQ query rather than fire-and-forget sendNode(): this lets Kage
|
|
724
|
+
// surface an explicit WhatsApp rejection (especially rate-overlimit 429)
|
|
725
|
+
// before showing a locally generated code to the user.
|
|
695
726
|
const companionHello = buildPairingCompanionHelloNode({
|
|
696
727
|
id: generateMessageTag(),
|
|
697
728
|
jid: authState.creds.me.id,
|
|
@@ -705,20 +736,18 @@ export const makeSocket = (config) => {
|
|
|
705
736
|
if (!response) {
|
|
706
737
|
throw new Boom('WhatsApp did not answer the pairing request. No code was issued.', { statusCode: DisconnectReason.timedOut });
|
|
707
738
|
}
|
|
739
|
+
// Some WhatsApp builds include a ref in this IQ result; others provide
|
|
740
|
+
// it only later in primary_hello. It is optional here and must not be
|
|
741
|
+
// used as a prerequisite for accepting the user's pairing code.
|
|
708
742
|
const pairingRef = extractPairingReference(response);
|
|
709
|
-
if (!pairingRef?.length) {
|
|
710
|
-
throw new Boom('WhatsApp did not return link_code_pairing_ref. The pairing code was not issued.', {
|
|
711
|
-
statusCode: 500,
|
|
712
|
-
data: { response: binaryNodeToString(response) }
|
|
713
|
-
});
|
|
714
|
-
}
|
|
715
743
|
if (pendingPairing !== pending) {
|
|
716
744
|
throw new Boom('The pairing request expired before WhatsApp confirmed it.', { statusCode: DisconnectReason.timedOut });
|
|
717
745
|
}
|
|
718
|
-
authState.creds.pairingCodeRef = pairingRef;
|
|
746
|
+
if (pairingRef?.length) authState.creds.pairingCodeRef = pairingRef;
|
|
747
|
+
else delete authState.creds.pairingCodeRef;
|
|
719
748
|
ev.emit('creds.update', authState.creds);
|
|
720
|
-
logger.info({ phoneNumber: normalizedNumber,
|
|
721
|
-
return
|
|
749
|
+
logger.info({ phoneNumber: normalizedNumber, hasEarlyReference: Boolean(pairingRef?.length) }, 'WhatsApp accepted the companion_hello pairing request');
|
|
750
|
+
return pairingCode;
|
|
722
751
|
}
|
|
723
752
|
catch (error) {
|
|
724
753
|
// Always roll back the provisional identity/code when WhatsApp rejects
|
|
@@ -730,14 +759,23 @@ export const makeSocket = (config) => {
|
|
|
730
759
|
|| error?.data?.isRateLimited === true
|
|
731
760
|
|| /rate[-_\s]?overlimit/i.test(String(error?.message || ''));
|
|
732
761
|
if (isRateLimited) {
|
|
762
|
+
const cooldownState = registerPairingRateLimit(
|
|
763
|
+
error,
|
|
764
|
+
Date.now(),
|
|
765
|
+
Number(config.pairingRateLimitCooldownMs) || DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS
|
|
766
|
+
);
|
|
733
767
|
const retryAfterMs = Number(error?.data?.retryAfterMs) > 0
|
|
734
768
|
? Math.ceil(Number(error.data.retryAfterMs))
|
|
735
|
-
:
|
|
769
|
+
: cooldownState?.remainingMs;
|
|
770
|
+
if (cooldownState?.until) {
|
|
771
|
+
authState.creds.pairingRateLimitedUntil = cooldownState.until;
|
|
772
|
+
ev.emit('creds.update', { pairingRateLimitedUntil: cooldownState.until });
|
|
773
|
+
}
|
|
736
774
|
const retryHint = retryAfterMs
|
|
737
|
-
? `
|
|
738
|
-
: ' WhatsApp did not provide a retry time;
|
|
775
|
+
? ` Kage blocked further pairing attempts in this Node.js process for approximately ${Math.ceil(retryAfterMs / 1000)} seconds.`
|
|
776
|
+
: ' WhatsApp did not provide a retry time; no automatic retry will be attempted.';
|
|
739
777
|
const rateLimitError = new Boom(
|
|
740
|
-
`WhatsApp rejected the pairing request (rate-overlimit, 429). No pairing code was issued.${retryHint}
|
|
778
|
+
`WhatsApp rejected the pairing request (rate-overlimit, 429). No pairing code was issued.${retryHint}`,
|
|
741
779
|
{
|
|
742
780
|
statusCode: 429,
|
|
743
781
|
data: {
|
|
@@ -749,7 +787,7 @@ export const makeSocket = (config) => {
|
|
|
749
787
|
}
|
|
750
788
|
}
|
|
751
789
|
);
|
|
752
|
-
logger.warn({ retryAfterMs }, 'WhatsApp rate-limited
|
|
790
|
+
logger.warn({ retryAfterMs }, 'WhatsApp rate-limited pairing; provisional credentials were restored and a process-wide cooldown was activated');
|
|
753
791
|
throw rateLimitError;
|
|
754
792
|
}
|
|
755
793
|
|
|
@@ -791,7 +829,26 @@ export const makeSocket = (config) => {
|
|
|
791
829
|
}
|
|
792
830
|
});
|
|
793
831
|
ws.on('error', mapWebSocketError(end));
|
|
794
|
-
ws.on('close', () =>
|
|
832
|
+
ws.on('close', (webSocketCode, webSocketReason) => {
|
|
833
|
+
const reasonText = Buffer.isBuffer(webSocketReason)
|
|
834
|
+
? webSocketReason.toString('utf8').slice(0, 200)
|
|
835
|
+
: String(webSocketReason || '').slice(0, 200);
|
|
836
|
+
const isPairingRestart = pairingRestartExpected
|
|
837
|
+
|| Boolean(pendingPairing && authState.creds.registered && authState.creds.me?.id);
|
|
838
|
+
if (isPairingRestart) {
|
|
839
|
+
pairingRestartExpected = false;
|
|
840
|
+
clearPendingPairing();
|
|
841
|
+
void end(new Boom('Pairing completed; WhatsApp closed the setup socket to restart the linked session.', {
|
|
842
|
+
statusCode: DisconnectReason.restartRequired,
|
|
843
|
+
data: { pairingCompleted: true, webSocketCloseCode: Number(webSocketCode), webSocketReason: reasonText }
|
|
844
|
+
}));
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
void end(new Boom('Connection Terminated', {
|
|
848
|
+
statusCode: DisconnectReason.connectionClosed,
|
|
849
|
+
data: { webSocketCloseCode: Number(webSocketCode), webSocketReason: reasonText }
|
|
850
|
+
}));
|
|
851
|
+
});
|
|
795
852
|
// the server terminated the connection
|
|
796
853
|
ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
|
|
797
854
|
// QR gen
|
|
@@ -805,6 +862,12 @@ export const makeSocket = (config) => {
|
|
|
805
862
|
}
|
|
806
863
|
};
|
|
807
864
|
await sendNode(iq);
|
|
865
|
+
clearTimeout(qrTimer);
|
|
866
|
+
qrTimer = undefined;
|
|
867
|
+
if (pendingPairing) {
|
|
868
|
+
logger.debug('ignored QR rotation while a phone-number pairing-code request is active');
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
808
871
|
const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
|
|
809
872
|
const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
|
|
810
873
|
const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
|
|
@@ -836,14 +899,17 @@ export const makeSocket = (config) => {
|
|
|
836
899
|
updateServerTimeOffset(stanza);
|
|
837
900
|
clearPendingPairing();
|
|
838
901
|
const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
902
|
+
Object.assign(authState.creds, updatedCreds, { registered: true });
|
|
903
|
+
for (const key of ['pairingCode', 'pairingCodeRef', 'pairingCodeGeneratedAt', 'pairingEphemeralKeyPair']) {
|
|
904
|
+
delete authState.creds[key];
|
|
905
|
+
}
|
|
906
|
+
clearPendingPairing();
|
|
907
|
+
pairingRestartExpected = true;
|
|
908
|
+
logger.info({ me: authState.creds.me, platform: authState.creds.platform }, 'pairing configured successfully; credentials saved and WhatsApp restart expected');
|
|
909
|
+
ev.emit('creds.update', authState.creds);
|
|
844
910
|
ev.emit('connection.update', { isNewLogin: true, qr: undefined });
|
|
845
911
|
await sendNode(reply);
|
|
846
|
-
|
|
912
|
+
await sendUnifiedSession();
|
|
847
913
|
}
|
|
848
914
|
catch (error) {
|
|
849
915
|
logger.info({ trace: error.stack }, 'error in pairing');
|
|
@@ -852,6 +918,7 @@ export const makeSocket = (config) => {
|
|
|
852
918
|
});
|
|
853
919
|
// login complete
|
|
854
920
|
ws.on('CB:success', async (node) => {
|
|
921
|
+
pairingRestartExpected = false;
|
|
855
922
|
try {
|
|
856
923
|
updateServerTimeOffset(node);
|
|
857
924
|
await uploadPreKeysToServerIfRequired();
|
package/lib/Types/Auth.d.ts
CHANGED
|
@@ -61,10 +61,12 @@ export type AuthenticationCreds = SignalCreds & {
|
|
|
61
61
|
accountSettings: AccountSettings;
|
|
62
62
|
registered: boolean;
|
|
63
63
|
pairingCode: string | undefined;
|
|
64
|
-
/**
|
|
64
|
+
/** Optional reference echoed by companion_hello; primary_hello remains authoritative. */
|
|
65
65
|
pairingCodeRef?: Buffer;
|
|
66
66
|
/** Creation time of the active pairing code, in Unix milliseconds. */
|
|
67
67
|
pairingCodeGeneratedAt?: number;
|
|
68
|
+
/** Persisted timestamp until which new pairing requests must be blocked after a WhatsApp 429. */
|
|
69
|
+
pairingRateLimitedUntil?: number;
|
|
68
70
|
lastPropHash: string | undefined;
|
|
69
71
|
routingInfo: Buffer | undefined;
|
|
70
72
|
additionalData?: any | undefined;
|
package/lib/Types/Socket.d.ts
CHANGED
|
@@ -71,6 +71,8 @@ export type SocketConfig = {
|
|
|
71
71
|
qrTimeout?: number;
|
|
72
72
|
/** maximum age of a pairing code in milliseconds (default: 180000) */
|
|
73
73
|
pairingCodeTimeoutMs?: number;
|
|
74
|
+
/** process-wide cooldown after WhatsApp 429 responses (default: 900000 ms) */
|
|
75
|
+
pairingRateLimitCooldownMs?: number;
|
|
74
76
|
/** provide an auth state object to maintain the auth state */
|
|
75
77
|
auth: AuthenticationState;
|
|
76
78
|
/** manage history processing with this control; by default will sync up everything */
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
export declare const DEFAULT_PAIRING_CODE_TTL_MS: number;
|
|
2
|
+
export declare const DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS: number;
|
|
3
|
+
export declare function generateKagePairingCode(): string;
|
|
4
|
+
export declare function getPairingRateLimitCooldown(now?: number): { until: number; cooldownMs: number; remainingMs: number } | null;
|
|
5
|
+
export declare function registerPairingRateLimit(error: unknown, now?: number, fallbackMs?: number): { until: number; cooldownMs: number; remainingMs: number } | null;
|
|
2
6
|
export declare const PAIRING_CODE_RESPONSE_GRACE_MS: number;
|
|
3
7
|
export declare function normalizePairingPhone(phoneNumber: unknown): string;
|
|
4
8
|
export declare function isValidPairingRef(creds: Record<string, any>, receivedRef: Uint8Array | Buffer | null | undefined, now?: number, maxAgeMs?: number): boolean;
|
|
@@ -1,18 +1,54 @@
|
|
|
1
1
|
import { randomInt } from 'node:crypto';
|
|
2
2
|
|
|
3
3
|
/** Utilities for WhatsApp Web phone-number pairing codes. */
|
|
4
|
+
const PAIRING_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
|
5
|
+
export const DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS = 15 * 60 * 1000;
|
|
6
|
+
let processPairingRateLimit = null;
|
|
4
7
|
|
|
5
8
|
/**
|
|
6
9
|
* Generate Kage's preferred 8-character pairing code.
|
|
7
|
-
* The suffix
|
|
8
|
-
*
|
|
9
|
-
* Example display: KAGE 1234; actual token: KAGE1234.
|
|
10
|
+
* The suffix follows Kage Antigua's unambiguous 32-character alphabet.
|
|
11
|
+
* The returned token has no space; add one only for display if desired.
|
|
10
12
|
*/
|
|
11
13
|
export function generateKagePairingCode() {
|
|
12
|
-
|
|
14
|
+
let suffix = '';
|
|
15
|
+
for (let index = 0; index < 4; index++) {
|
|
16
|
+
suffix += PAIRING_ALPHABET[randomInt(0, PAIRING_ALPHABET.length)];
|
|
17
|
+
}
|
|
18
|
+
return `KAGE${suffix}`;
|
|
13
19
|
}
|
|
14
20
|
|
|
15
21
|
export const DEFAULT_PAIRING_CODE_TTL_MS = 180_000;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Return the process-wide pairing cooldown after a WhatsApp 429 response.
|
|
25
|
+
* This intentionally prevents a caller that recreates sockets from hammering
|
|
26
|
+
* the pairing endpoint repeatedly in the same Node.js process.
|
|
27
|
+
*/
|
|
28
|
+
export function getPairingRateLimitCooldown(now = Date.now()) {
|
|
29
|
+
if (!processPairingRateLimit || processPairingRateLimit.until <= now) return null;
|
|
30
|
+
return {
|
|
31
|
+
...processPairingRateLimit,
|
|
32
|
+
remainingMs: processPairingRateLimit.until - now
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Record a 429. Prefer WhatsApp's explicit retry hint; otherwise fail closed
|
|
37
|
+
* for a configurable conservative cooldown (15 minutes by default). */
|
|
38
|
+
export function registerPairingRateLimit(error, now = Date.now(), fallbackMs = DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS) {
|
|
39
|
+
const hinted = Number(error?.data?.retryAfterMs);
|
|
40
|
+
const configured = Number(fallbackMs);
|
|
41
|
+
const fallback = Number.isFinite(configured) && configured >= 60_000
|
|
42
|
+
? Math.min(configured, 24 * 60 * 60 * 1000)
|
|
43
|
+
: DEFAULT_PAIRING_RATE_LIMIT_COOLDOWN_MS;
|
|
44
|
+
const cooldownMs = Number.isFinite(hinted) && hinted > 0
|
|
45
|
+
? Math.min(Math.ceil(hinted), 24 * 60 * 60 * 1000)
|
|
46
|
+
: fallback;
|
|
47
|
+
const until = Math.max(processPairingRateLimit?.until || 0, now + cooldownMs);
|
|
48
|
+
processPairingRateLimit = { until, cooldownMs: until - now };
|
|
49
|
+
return getPairingRateLimitCooldown(now);
|
|
50
|
+
}
|
|
51
|
+
|
|
16
52
|
export const PAIRING_CODE_RESPONSE_GRACE_MS = 30_000;
|
|
17
53
|
|
|
18
54
|
export function normalizePairingPhone(phoneNumber) {
|
|
@@ -88,14 +124,16 @@ export function extractPairingReference(response) {
|
|
|
88
124
|
}
|
|
89
125
|
|
|
90
126
|
export function isValidPairingRef(creds, receivedRef, now = Date.now(), maxAgeMs = DEFAULT_PAIRING_CODE_TTL_MS) {
|
|
91
|
-
|
|
127
|
+
// The primary phone sends the authoritative ref with primary_hello.
|
|
128
|
+
// Do not require companion_hello's IQ result to echo/store the same ref:
|
|
129
|
+
// upstream Baileys and Kage Antigua both consume it from primary_hello.
|
|
130
|
+
if (!creds?.pairingCode || !creds?.pairingEphemeralKeyPair?.private) return false;
|
|
92
131
|
const generatedAt = Number(creds.pairingCodeGeneratedAt);
|
|
93
132
|
if (!Number.isFinite(generatedAt) || generatedAt <= 0 || now < generatedAt || now - generatedAt > maxAgeMs) return false;
|
|
94
133
|
if (receivedRef == null) return false;
|
|
95
134
|
try {
|
|
96
|
-
const expected = Buffer.from(creds.pairingCodeRef);
|
|
97
135
|
const received = Buffer.from(receivedRef);
|
|
98
|
-
return
|
|
136
|
+
return received.length > 0;
|
|
99
137
|
} catch {
|
|
100
138
|
return false;
|
|
101
139
|
}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kage-baileys",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "25.4.
|
|
5
|
-
"description": "Kage Baileys with
|
|
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",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"whatsapp",
|
|
8
8
|
"automation"
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"url": "git@github.com:xrljosedv/kage-baileys.git"
|
|
13
13
|
},
|
|
14
14
|
"license": "MIT",
|
|
15
|
-
"author": "
|
|
15
|
+
"author": "Kage Baileys",
|
|
16
16
|
"main": "lib/index.js",
|
|
17
17
|
"types": "lib/index.d.ts",
|
|
18
18
|
"files": [
|
|
@@ -21,24 +21,22 @@
|
|
|
21
21
|
"engine-requirements.js",
|
|
22
22
|
"extras/**/*",
|
|
23
23
|
"helpers/**/*",
|
|
24
|
-
"licenses/**/*",
|
|
25
24
|
"scripts/**/*",
|
|
26
25
|
"README.md",
|
|
27
26
|
"LICENSE",
|
|
28
|
-
"
|
|
29
|
-
"VALIDATION-REPORT-25.4.9.md"
|
|
27
|
+
"VALIDATION-REPORT-25.4.15.md"
|
|
30
28
|
],
|
|
31
29
|
"scripts": {
|
|
32
30
|
"build:all": "npm run check",
|
|
33
31
|
"build": "npm run check",
|
|
34
|
-
"check": "node ./scripts/verify-package.mjs",
|
|
32
|
+
"check": "node ./scripts/verify-package.mjs && npm test",
|
|
35
33
|
"changelog:last": "conventional-changelog -p angular -r 2",
|
|
36
34
|
"changelog:preview": "conventional-changelog -p angular -u",
|
|
37
35
|
"changelog:update": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
|
|
38
36
|
"gen:protobuf": "sh WAProto/GenerateStatics.sh",
|
|
39
|
-
"lint": "
|
|
37
|
+
"lint": "node ./scripts/verify-package.mjs",
|
|
40
38
|
"release": "release-it",
|
|
41
|
-
"test": "
|
|
39
|
+
"test": "node ./scripts/verify-pairing-flow.mjs"
|
|
42
40
|
},
|
|
43
41
|
"dependencies": {
|
|
44
42
|
"@adiwajshing/keyed-db": "^0.2.4",
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {
|
|
6
|
+
classifyWhatsAppNodeError,
|
|
7
|
+
generateKagePairingCode,
|
|
8
|
+
getPairingRateLimitCooldown,
|
|
9
|
+
isValidPairingRef,
|
|
10
|
+
normalizePairingPhone,
|
|
11
|
+
registerPairingRateLimit
|
|
12
|
+
} from '../lib/Utils/pairing-code.js';
|
|
13
|
+
|
|
14
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
15
|
+
const read = file => readFileSync(path.join(root, file), 'utf8');
|
|
16
|
+
const socket = read('lib/Socket/socket.js');
|
|
17
|
+
const recv = read('lib/Socket/messages-recv.js');
|
|
18
|
+
const send = read('lib/Socket/messages-send.js');
|
|
19
|
+
const pay = read('helpers/interactive-pay.js');
|
|
20
|
+
|
|
21
|
+
// Pairing-code generation and input validation.
|
|
22
|
+
for (let i = 0; i < 250; i++) {
|
|
23
|
+
assert.match(generateKagePairingCode(), /^KAGE[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}$/);
|
|
24
|
+
}
|
|
25
|
+
assert.equal(normalizePairingPhone('+51 928-619-211'), '51928619211');
|
|
26
|
+
assert.throws(() => normalizePairingPhone('0928619211'), /international format/);
|
|
27
|
+
assert.throws(() => normalizePairingPhone('abc51928619211'), /only digits/);
|
|
28
|
+
|
|
29
|
+
// primary_hello is authoritative; a ref need not have been echoed by companion_hello.
|
|
30
|
+
const pairingCreds = {
|
|
31
|
+
pairingCode: 'KAGEAB23',
|
|
32
|
+
pairingEphemeralKeyPair: { private: Buffer.alloc(32, 1) },
|
|
33
|
+
pairingCodeGeneratedAt: 1_000
|
|
34
|
+
};
|
|
35
|
+
assert.equal(isValidPairingRef(pairingCreds, Buffer.from('server-ref'), 2_000), true);
|
|
36
|
+
assert.equal(isValidPairingRef(pairingCreds, Buffer.from('server-ref'), 200_000), false);
|
|
37
|
+
assert.equal(isValidPairingRef({ ...pairingCreds, pairingCode: undefined }, Buffer.from('server-ref'), 2_000), false);
|
|
38
|
+
assert.equal(isValidPairingRef(pairingCreds, Buffer.alloc(0), 2_000), false);
|
|
39
|
+
|
|
40
|
+
// WhatsApp 429 responses are non-retryable and activate a process-wide cooldown.
|
|
41
|
+
const classified = classifyWhatsAppNodeError({ code: '429', text: 'rate-overlimit' });
|
|
42
|
+
assert.equal(classified.statusCode, 429);
|
|
43
|
+
assert.equal(classified.data.isRateLimited, true);
|
|
44
|
+
assert.equal(classified.data.retryable, false);
|
|
45
|
+
const cooldownNow = Date.now();
|
|
46
|
+
const cooldown = registerPairingRateLimit({ data: {} }, cooldownNow, 60_000);
|
|
47
|
+
assert.ok(cooldown.remainingMs >= 60_000 && cooldown.remainingMs <= 60_000);
|
|
48
|
+
assert.equal(getPairingRateLimitCooldown(cooldownNow)?.remainingMs, 60_000);
|
|
49
|
+
|
|
50
|
+
// Pairing-flow and reconnect invariants.
|
|
51
|
+
assert.match(socket, /getPairingRateLimitCooldown\(now\)/,
|
|
52
|
+
'Pairing must check the process-wide cooldown before sending a request');
|
|
53
|
+
assert.match(socket, /registerPairingRateLimit\(/,
|
|
54
|
+
'A 429 must activate the process-wide cooldown');
|
|
55
|
+
assert.match(socket, /pairingRateLimitedUntil = cooldownState\.until/,
|
|
56
|
+
'The 429 cooldown must be persisted in authentication credentials');
|
|
57
|
+
assert.match(socket, /companion_hello/,
|
|
58
|
+
'Pairing must use the companion_hello stage');
|
|
59
|
+
assert.match(socket, /ignored QR rotation while a phone-number pairing-code request is active/,
|
|
60
|
+
'QR generation must not overlap an active pairing-code request');
|
|
61
|
+
assert.match(socket, /DisconnectReason\.restartRequired/,
|
|
62
|
+
'A socket close immediately after completed pairing must be classified as restart-required');
|
|
63
|
+
assert.match(socket, /webSocketCloseCode/,
|
|
64
|
+
'Raw websocket close diagnostics must be retained');
|
|
65
|
+
assert.match(recv, /const primaryHelloRef = Buffer\.from\(receivedRefValue\)/,
|
|
66
|
+
'companion_finish must use the reference delivered with primary_hello');
|
|
67
|
+
assert.doesNotMatch(socket, /did not return link_code_pairing_ref/,
|
|
68
|
+
'The companion_hello result must not be required to echo the reference');
|
|
69
|
+
assert.match(recv, /stage: 'companion_finish'/,
|
|
70
|
+
'Pairing must complete the companion_finish stage');
|
|
71
|
+
assert.match(recv, /creds\.registered = true;/,
|
|
72
|
+
'registered must be set only after companion_finish is accepted');
|
|
73
|
+
assert.match(send, /getBizBinaryNode\(relayContent\)/,
|
|
74
|
+
'Native Flow relay must attach the biz companion node');
|
|
75
|
+
assert.match(send, /native_flow_name|order_details/,
|
|
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');
|
|
79
|
+
assert.match(pay, /placeholder/,
|
|
80
|
+
'review_and_pay must reject placeholder payment identifiers');
|
|
81
|
+
|
|
82
|
+
console.log('Pairing / 429 cooldown / reconnect / Native Flow checks passed: 277 assertions.');
|
package/licenses/dnuzi-MIT.txt
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 DanuZz ?
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 Rajeh Taher/WhiskeySockets
|
|
4
|
-
Copyright (c) 2026 rexxhayanasi
|
|
5
|
-
|
|
6
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
-
in the Software without restriction, including without limitation the rights
|
|
9
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
-
furnished to do so, subject to the following conditions:
|
|
12
|
-
|
|
13
|
-
The above copyright notice and this permission notice shall be included in all
|
|
14
|
-
copies or substantial portions of the Software.
|
|
15
|
-
|
|
16
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
-
SOFTWARE.
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 Rajeh Taher/WhiskeySockets
|
|
4
|
-
Copyright (c) 2026 Lia Wynn
|
|
5
|
-
|
|
6
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
-
in the Software without restriction, including without limitation the rights
|
|
9
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
-
furnished to do so, subject to the following conditions:
|
|
12
|
-
|
|
13
|
-
The above copyright notice and this permission notice shall be included in all
|
|
14
|
-
copies or substantial portions of the Software.
|
|
15
|
-
|
|
16
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
-
SOFTWARE.
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025-2026 Kage Baileys
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 Rajeh Taher/WhiskeySockets
|
|
4
|
-
Copyright (c) 2026 rexxhayanasi
|
|
5
|
-
|
|
6
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
-
in the Software without restriction, including without limitation the rights
|
|
9
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
-
furnished to do so, subject to the following conditions:
|
|
12
|
-
|
|
13
|
-
The above copyright notice and this permission notice shall be included in all
|
|
14
|
-
copies or substantial portions of the Software.
|
|
15
|
-
|
|
16
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
-
SOFTWARE.
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025-2026 Kage Baileys
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 Rajeh Taher/WhiskeySockets
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|