kage-baileys 25.4.10 → 25.4.15

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 CHANGED
@@ -1,6 +1,14 @@
1
- MIT License
1
+ KAGE BAILEYS — MIT LICENSE
2
2
 
3
- Copyright (c) 2025 Rajeh Taher/WhiskeySockets
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
@@ -2208,7 +2208,7 @@ Los mantenedores de kage-baileys no respaldan el uso de esta librería para viol
2208
2208
 
2209
2209
  Distribuido bajo la **Licencia GPL-3.0**. Consulta [LICENSE](LICENSE) para más información.
2210
2210
 
2211
- La identidad del paquete es **Kage Baileys**. Los avisos de licencia se conservan en `LICENSE` y `licenses/`. La redistribución debe respetar las condiciones de la licencia MIT.
2211
+ 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
2212
 
2213
2213
  ### Seguridad de dependencias
2214
2214
 
@@ -2319,7 +2319,7 @@ Use `getMediaDownloadStatus(message)` to inspect ordinary media availability. It
2319
2319
  The root package and `./Utils/*` subpaths now expose additional auth-state adapters (MongoDB, MySQL, PostgreSQL, Redis, SQLite, single-file and NekoDB), TTL cache, sender-key memory helpers, group metadata validation, username validation, modern message constructors, status sticker builders, social link preview helpers, HTML-app validation/multiplayer helpers, scheduled-message helpers and newsletter status helpers. Database drivers are optional peer dependencies and must be installed only when the relevant adapter is used.
2320
2320
 
2321
2321
 
2322
- ## Kage 25.4.9: pairing and Native Flow
2322
+ ## Kage 25.4.10: pairing and Native Flow
2323
2323
 
2324
2324
  When `requestPairingCode(phoneNumber)` is called without a custom code, Kage generates `KAGE` followed by four cryptographically random digits. The actual eight-character token has no space (for example `KAGE1234`); display it as `KAGE 1234` only for readability. Kage waits for WhatsApp's `companion_hello` IQ result and returns the token only after a server-issued `link_code_pairing_ref` is received. A `rate-overlimit` response is a server-side 429 and cannot be bypassed by changing the code format; Kage does not retry automatically.
2325
2325
 
@@ -2329,5 +2329,5 @@ The Native Flow helper constructs a payment-request message only. It does not pr
2329
2329
 
2330
2330
  ## Package validation
2331
2331
 
2332
- The `test/` source folder and source maps are intentionally excluded from this clean distribution build. `npm test` runs the static package / import / WAProto validation command (`npm run check`). Offline development QA was executed before removing the test sources; see `VALIDATION-REPORT-25.4.9.md`.
2332
+ The `test/` source folder and source maps are intentionally excluded from this clean distribution build. `npm test` runs focused pairing/reconnect and Native Flow assertions. `npm run check` validates syntax, imports, exports, WAProto, and the focused assertions. See `VALIDATION-REPORT-25.4.10.md`.
2333
2333
 
@@ -49,7 +49,7 @@ export const DEFAULT_CACHE_TTLS = {
49
49
  export const DEFAULT_CACHE_MAX_KEYS = 20000;
50
50
  export const DEFAULT_CONNECTION_CONFIG = {
51
51
  version: version,
52
- browser: Browsers.androidPhone('Chrome'),
52
+ browser: Browsers.macOS('Chrome'),
53
53
  waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
54
54
  connectTimeoutMs: 20000,
55
55
  keepAliveIntervalMs: 30000,
@@ -797,89 +797,100 @@ export const makeMessagesRecvSocket = (config) => {
797
797
  }
798
798
  });
799
799
  };
800
- // Pairing-code notifications are ACKed by handleNotification after this
801
- // function returns. Start companion_finish in the background so the ACK is
802
- // sent immediately, matching the current WhatsApp Web sequence.
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
813
  logger.warn('ignored primary_hello: pairing code missing, expired, or server reference does not match');
810
- return;
814
+ return false;
811
815
  }
812
816
  const expectedRef = Buffer.from(creds.pairingCodeRef);
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
- void (async () => {
825
- try {
826
- const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
827
- const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
828
- if (primaryEphemeralPublicKeyWrapped.length !== 80) {
829
- throw new Boom('Invalid wrapped primary ephemeral public key length.', { statusCode: 400 });
830
- }
831
- const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
832
- const companionSharedKey = Curve.sharedKey(creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
833
- const random = randomBytes(32);
834
- const linkCodeSalt = randomBytes(32);
835
- const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
836
- salt: linkCodeSalt,
837
- info: 'link_code_pairing_key_bundle_encryption_key'
838
- });
839
- const encryptPayload = Buffer.concat([
840
- Buffer.from(creds.signedIdentityKey.public),
841
- primaryIdentityPublicKey,
842
- random
843
- ]);
844
- const encryptIv = randomBytes(12);
845
- const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
846
- const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
847
- const identitySharedKey = Curve.sharedKey(creds.signedIdentityKey.private, primaryIdentityPublicKey);
848
- const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
849
- creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
850
- // Use the ref returned by companion_hello, never a ref echoed by
851
- // the phone notification. A successful IQ alone does not mark
852
- // the account registered; pair-success performs that transition.
853
- await query({
854
- tag: 'iq',
855
- attrs: {
856
- to: S_WHATSAPP_NET,
857
- type: 'set',
858
- id: sock.generateMessageTag(),
859
- xmlns: 'md'
860
- },
861
- content: [
862
- {
863
- tag: 'link_code_companion_reg',
864
- attrs: { jid: creds.me.id, stage: 'companion_finish' },
865
- content: [
866
- { tag: 'link_code_pairing_wrapped_key_bundle', attrs: {}, content: encryptedPayload },
867
- { tag: 'companion_identity_public', attrs: {}, content: creds.signedIdentityKey.public },
868
- { tag: 'link_code_pairing_ref', attrs: {}, content: expectedRef }
869
- ]
870
- }
871
- ]
872
- });
873
- ev.emit('creds.update', creds);
874
- logger.info({ attempt: pairingPrimaryHelloAttempts }, 'companion_finish accepted; awaiting pair-success');
875
- }
876
- catch (error) {
877
- logger.error({ error }, 'failed to complete pairing-code companion_finish');
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
- finally {
880
- pairingFinishInFlight = false;
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: expectedRef }
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');
@@ -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;
@@ -791,7 +792,26 @@ export const makeSocket = (config) => {
791
792
  }
792
793
  });
793
794
  ws.on('error', mapWebSocketError(end));
794
- ws.on('close', () => void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
795
+ ws.on('close', (webSocketCode, webSocketReason) => {
796
+ const reasonText = Buffer.isBuffer(webSocketReason)
797
+ ? webSocketReason.toString('utf8').slice(0, 200)
798
+ : String(webSocketReason || '').slice(0, 200);
799
+ const isPairingRestart = pairingRestartExpected
800
+ || Boolean(pendingPairing && authState.creds.registered && authState.creds.me?.id);
801
+ if (isPairingRestart) {
802
+ pairingRestartExpected = false;
803
+ clearPendingPairing();
804
+ void end(new Boom('Pairing completed; WhatsApp closed the setup socket to restart the linked session.', {
805
+ statusCode: DisconnectReason.restartRequired,
806
+ data: { pairingCompleted: true, webSocketCloseCode: Number(webSocketCode), webSocketReason: reasonText }
807
+ }));
808
+ return;
809
+ }
810
+ void end(new Boom('Connection Terminated', {
811
+ statusCode: DisconnectReason.connectionClosed,
812
+ data: { webSocketCloseCode: Number(webSocketCode), webSocketReason: reasonText }
813
+ }));
814
+ });
795
815
  // the server terminated the connection
796
816
  ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
797
817
  // QR gen
@@ -836,14 +856,17 @@ export const makeSocket = (config) => {
836
856
  updateServerTimeOffset(stanza);
837
857
  clearPendingPairing();
838
858
  const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
839
- delete updatedCreds.pairingCode;
840
- delete updatedCreds.pairingCodeRef;
841
- delete updatedCreds.pairingCodeGeneratedAt;
842
- logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
843
- ev.emit('creds.update', updatedCreds);
859
+ Object.assign(authState.creds, updatedCreds, { registered: true });
860
+ for (const key of ['pairingCode', 'pairingCodeRef', 'pairingCodeGeneratedAt', 'pairingEphemeralKeyPair']) {
861
+ delete authState.creds[key];
862
+ }
863
+ clearPendingPairing();
864
+ pairingRestartExpected = true;
865
+ logger.info({ me: authState.creds.me, platform: authState.creds.platform }, 'pairing configured successfully; credentials saved and WhatsApp restart expected');
866
+ ev.emit('creds.update', authState.creds);
844
867
  ev.emit('connection.update', { isNewLogin: true, qr: undefined });
845
868
  await sendNode(reply);
846
- void sendUnifiedSession();
869
+ await sendUnifiedSession();
847
870
  }
848
871
  catch (error) {
849
872
  logger.info({ trace: error.stack }, 'error in pairing');
@@ -852,6 +875,7 @@ export const makeSocket = (config) => {
852
875
  });
853
876
  // login complete
854
877
  ws.on('CB:success', async (node) => {
878
+ pairingRestartExpected = false;
855
879
  try {
856
880
  updateServerTimeOffset(node);
857
881
  await uploadPreKeysToServerIfRequired();
@@ -1,5 +1,6 @@
1
1
  import { platform, release } from 'os';
2
2
  import { proto } from '../../WAProto/index.js';
3
+
3
4
  const PLATFORM_MAP = {
4
5
  aix: 'AIX',
5
6
  darwin: 'Mac OS',
@@ -13,19 +14,46 @@ const PLATFORM_MAP = {
13
14
  cygwin: undefined,
14
15
  netbsd: undefined
15
16
  };
17
+
18
+ /**
19
+ * Standard browser descriptors used by Baileys / Kage.
20
+ * Format is always [OS, BrowserName, Version] so platform detection is consistent
21
+ * for every browser (Chrome, Firefox, Safari, Edge, Brave, Opera, etc.).
22
+ */
16
23
  export const Browsers = {
17
24
  ubuntu: browser => ['Ubuntu', browser, '22.04.4'],
18
25
  macOS: browser => ['Mac OS', browser, '14.4.1'],
19
26
  baileys: browser => ['Baileys', browser, '6.5.0'],
20
27
  windows: browser => ['Windows', browser, '10.0.22631'],
21
- android: browser => [browser, 'Android', ''],
28
+ // Fixed order: OS first so getCompanionPlatformId correctly sees the browser name
29
+ android: browser => ['Android', browser, ''],
22
30
  /** Android phone mode — use for view-once message compatibility */
23
- androidPhone: browser => [browser, 'Android', '15'],
31
+ androidPhone: browser => ['Android', browser, '15'],
24
32
  /** The appropriate browser based on your OS & release */
25
- appropriate: browser => [PLATFORM_MAP[platform()] || 'Ubuntu', browser, release()]
33
+ appropriate: browser => [PLATFORM_MAP[platform()] || 'Ubuntu', browser, release()],
34
+ // Extra convenience aliases so any browser string works without errors
35
+ chrome: () => ['Windows', 'Chrome', '10.0.22631'],
36
+ firefox: () => ['Windows', 'Firefox', '10.0.22631'],
37
+ edge: () => ['Windows', 'Edge', '10.0.22631'],
38
+ safari: () => ['Mac OS', 'Safari', '14.4.1'],
39
+ brave: () => ['Windows', 'Chrome', '10.0.22631'], // Brave reports as Chrome-compatible
40
+ opera: () => ['Windows', 'Opera', '10.0.22631'],
41
+ desktop: () => ['Windows', 'Desktop', '10.0.22631']
26
42
  };
43
+
44
+ /**
45
+ * Resolve a companion platform id that WhatsApp accepts.
46
+ * Always returns a known numeric string so pairing never fails with bad-request
47
+ * because of an unknown browser name.
48
+ */
27
49
  export const getPlatformId = (browser) => {
28
- const platformType = proto.DeviceProps.PlatformType[browser.toUpperCase()];
29
- return platformType ? platformType.toString() : '1'; //chrome
50
+ // browser can be a string (legacy) or the [OS, Name, Ver] tuple
51
+ const name = Array.isArray(browser)
52
+ ? String(browser[1] || browser[0] || 'Chrome')
53
+ : String(browser || 'Chrome');
54
+ const upper = name.toUpperCase().replace(/\s+/g, '');
55
+ const platformType = proto.DeviceProps.PlatformType[upper]
56
+ || proto.DeviceProps.PlatformType.CHROME
57
+ || 1;
58
+ return String(platformType);
30
59
  };
31
- //# sourceMappingURL=browser-utils.js.map
@@ -11,25 +11,85 @@ export var CompanionWebClientType;
11
11
  CompanionWebClientType[CompanionWebClientType["UWP"] = 8] = "UWP";
12
12
  CompanionWebClientType[CompanionWebClientType["OTHER_WEB_CLIENT"] = 9] = "OTHER_WEB_CLIENT";
13
13
  })(CompanionWebClientType || (CompanionWebClientType = {}));
14
+
14
15
  const BROWSER_TO_COMPANION_WEB_CLIENT = {
15
16
  Chrome: CompanionWebClientType.CHROME,
17
+ Chromium: CompanionWebClientType.CHROME,
18
+ Brave: CompanionWebClientType.CHROME,
19
+ Vivaldi: CompanionWebClientType.CHROME,
16
20
  Edge: CompanionWebClientType.EDGE,
21
+ 'Microsoft Edge': CompanionWebClientType.EDGE,
17
22
  Firefox: CompanionWebClientType.FIREFOX,
18
23
  IE: CompanionWebClientType.IE,
24
+ 'Internet Explorer': CompanionWebClientType.IE,
19
25
  Opera: CompanionWebClientType.OPERA,
20
- Safari: CompanionWebClientType.SAFARI
26
+ Safari: CompanionWebClientType.SAFARI,
27
+ Desktop: CompanionWebClientType.ELECTRON,
28
+ Electron: CompanionWebClientType.ELECTRON,
29
+ Baileys: CompanionWebClientType.CHROME,
30
+ Android: CompanionWebClientType.CHROME, // treat Android web clients as Chrome
31
+ Ubuntu: CompanionWebClientType.CHROME,
32
+ Windows: CompanionWebClientType.CHROME,
33
+ 'Mac OS': CompanionWebClientType.CHROME
21
34
  };
22
- export const getCompanionWebClientType = ([os, browserName]) => {
35
+
36
+ /**
37
+ * Robustly detect the web client type from any browser descriptor.
38
+ * Accepts:
39
+ * - ['OS', 'BrowserName', 'Version'] (standard)
40
+ * - ['BrowserName', 'OS', 'Version'] (old androidPhone style)
41
+ * - plain string
42
+ * Always returns a known value so WhatsApp never answers "bad-request".
43
+ */
44
+ export const getCompanionWebClientType = (browser) => {
45
+ let os = '';
46
+ let browserName = '';
47
+
48
+ if (Array.isArray(browser)) {
49
+ // Detect which element is the browser name
50
+ const knownBrowsers = Object.keys(BROWSER_TO_COMPANION_WEB_CLIENT);
51
+ const first = String(browser[0] || '');
52
+ const second = String(browser[1] || '');
53
+ if (knownBrowsers.some(k => k.toLowerCase() === first.toLowerCase())) {
54
+ browserName = first;
55
+ os = second;
56
+ } else if (knownBrowsers.some(k => k.toLowerCase() === second.toLowerCase())) {
57
+ browserName = second;
58
+ os = first;
59
+ } else {
60
+ // Fallback: assume classic [OS, Browser]
61
+ os = first;
62
+ browserName = second || first || 'Chrome';
63
+ }
64
+ } else if (typeof browser === 'string') {
65
+ browserName = browser;
66
+ } else {
67
+ browserName = 'Chrome';
68
+ }
69
+
23
70
  if (browserName === 'Desktop') {
24
71
  return os === 'Windows' ? CompanionWebClientType.UWP : CompanionWebClientType.ELECTRON;
25
72
  }
26
- return BROWSER_TO_COMPANION_WEB_CLIENT[browserName] || CompanionWebClientType.OTHER_WEB_CLIENT;
73
+
74
+ // Case-insensitive lookup
75
+ const key = Object.keys(BROWSER_TO_COMPANION_WEB_CLIENT).find(
76
+ k => k.toLowerCase() === browserName.toLowerCase()
77
+ );
78
+ return key ? BROWSER_TO_COMPANION_WEB_CLIENT[key] : CompanionWebClientType.CHROME;
27
79
  };
80
+
81
+ /**
82
+ * Always returns a valid platform id string (never fails).
83
+ */
28
84
  export const getCompanionPlatformId = (browser) => {
29
- return getCompanionWebClientType(browser).toString();
85
+ try {
86
+ return getCompanionWebClientType(browser).toString();
87
+ } catch {
88
+ return CompanionWebClientType.CHROME.toString();
89
+ }
30
90
  };
91
+
31
92
  export const buildPairingQRData = (ref, noiseKeyB64, identityKeyB64, advB64, browser) => {
32
93
  return ('https://wa.me/settings/linked_devices#' +
33
94
  [ref, noiseKeyB64, identityKeyB64, advB64, getCompanionPlatformId(browser)].join(','));
34
95
  };
35
- //# sourceMappingURL=companion-reg-client-utils.js.map
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "kage-baileys",
3
3
  "type": "module",
4
- "version": "25.4.10",
5
- "description": "Kage Baileys with KAGE-prefixed confirmed pairing codes, hardened Native Flow review_and_pay validation, expanded WAProto schema and maintained compatibility helpers",
4
+ "version": "25.4.15",
5
+ "description": "Kage Baileys with confirmed pairing registration state, resilient reconnect classification, hardened Native Flow review_and_pay, expanded WAProto schema and compatibility helpers",
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": "Rajeh Taher",
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
- "THIRD_PARTY_NOTICES.md",
29
- "VALIDATION-REPORT-25.4.9.md"
27
+ "VALIDATION-REPORT-25.4.10.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": "npm run check",
37
+ "lint": "node ./scripts/verify-package.mjs",
40
38
  "release": "release-it",
41
- "test": "npm run check"
39
+ "test": "node ./scripts/verify-pairing-flow.mjs"
42
40
  },
43
41
  "dependencies": {
44
42
  "@adiwajshing/keyed-db": "^0.2.4",
@@ -0,0 +1,39 @@
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
+
6
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
7
+ const read = file => readFileSync(path.join(root, file), 'utf8');
8
+ const socket = read('lib/Socket/socket.js');
9
+ const recv = read('lib/Socket/messages-recv.js');
10
+ const pairing = read('lib/Utils/pairing-code.js');
11
+ const send = read('lib/Socket/messages-send.js');
12
+ const pay = read('helpers/interactive-pay.js');
13
+
14
+ assert.match(pairing, /return `KAGE\$\{String\(randomInt\(0, 10_000\)\)\.padStart\(4, '0'\)\}`/,
15
+ 'Default pairing token must be KAGE + four cryptographically random digits');
16
+ assert.match(pairing, /Buffer\.from\(\[0\]\)/,
17
+ 'Pairing nonce must be a single NUL byte');
18
+ assert.match(recv, /await query\(\{[\s\S]*?stage: 'companion_finish'[\s\S]*?\}\);[\s\S]*?creds\.registered = true;/,
19
+ 'The registered flag must be written only after companion_finish is accepted');
20
+ assert.match(recv, /await processPairingPrimaryHello\(linkCodeCompanionReg\)/,
21
+ 'primary_hello processing must finish before notification ACK');
22
+ assert.match(recv, /delete creds\[key\]/,
23
+ 'Temporary pairing secrets must be cleared after successful completion');
24
+ assert.match(socket, /Object\.assign\(authState\.creds, updatedCreds, \{ registered: true \}\)/,
25
+ 'pair-success must merge credentials and persist registered=true');
26
+ assert.match(socket, /DisconnectReason\.restartRequired/,
27
+ 'A socket close immediately after completed pairing must be classified as restart-required');
28
+ assert.match(socket, /webSocketCloseCode/,
29
+ 'Raw websocket close diagnostics must be retained');
30
+ assert.match(send, /getBizBinaryNode\(relayContent\)/,
31
+ 'Native Flow relay must attach the biz companion node');
32
+ assert.match(send, /native_flow_name|order_details/,
33
+ 'Native Flow relay must support order_details mapping');
34
+ assert.match(pay, /total_amount must equal the sum of order\.items/,
35
+ 'review_and_pay must reject mismatched total/item values');
36
+ assert.match(pay, /placeholder/,
37
+ 'review_and_pay must reject placeholder payment identifiers');
38
+
39
+ console.log('Pairing / reconnect / review_and_pay checks passed: 11/11.');
@@ -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.