@aldy11/baileys 2.0.6 โ†’ 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,14 +4,15 @@ WhatsApp Web API Multi-Device modern untuk Node.js dengan dukungan penuh tombol
4
4
 
5
5
  ## โœจ Fitur Utama
6
6
 
7
+ - ๐Ÿ‘๏ธ **Out-of-the-Box Android Companion & Anti View-Once (RVO PENUH)**: Default `browser` otomatis memakai **Android Companion (`Browsers.android('14')`)** sehingga server WhatsApp mengirimkan media Sekali Lihat (foto, video, voice note, video note `ptvMessage`) secara utuh beserta `mediaKey` โ€” langsung aktif tanpa konfigurasi tambahan, dilengkapi auto-deteksi **WA Biasa vs WA Business (`SMB_Android`)** dan perlindungan **zero-401** untuk sesi Web lama!
8
+ - ๐Ÿ”‘ **Universal Custom Pairing Code + Android RVO**: Mendukung kode pairing kustom 8 karakter (`sock.requestPairingCode('628123456789', 'ALDY-7111')`) **sekaligus** mempertahankan sesi sebagai Android Companion agar RVO tetap terbuka penuh (pairing handshake otomatis memakai allowlist `Chrome (Ubuntu)` yang diterima server WhatsApp).
7
9
  - ๐Ÿ”˜ **Native Flow Buttons**: Dukungan tombol interaktif WhatsApp terbaru (`quick_reply`, `cta_url`, `cta_copy`, `single_select` dropdown) dengan injeksi XML `<biz>` otomatis.
8
10
  - ๐ŸŽจ **Meta AI HTML/Canvas Primitives**: Mendukung rendering HTML/CSS interaktif di chat (`richMessage.html`), `imgv2`, `hscroll`, `footerActionV2`, `inline_entities`, dan `editrich` (mini game, widget interaktif).
9
11
  - ๐Ÿ–ผ๏ธ **Native Album**: Kirim album foto & video berkelompok langsung via `sock.sendMessage(jid, { album: [...] })`.
10
12
  - ๐Ÿ“ฆ **Sticker Pack Native**: Kirim paket stiker lengkap langsung dengan tombol simpan stiker ke WhatsApp.
11
13
  - ๐Ÿ›๏ธ **Order Status Card**: Kartu pelacakan pesanan toko e-commerce dengan status badge dan detail transaksi.
12
- - ๐Ÿ”‘ **Custom Pairing Code**: Dukungan custom pairing code 8 karakter (`sock.requestPairingCode(number, "MYCODE88")`).
13
14
  - ๐Ÿ›ก๏ธ **Anti-Corrupt Session (Mutex Lock)**: Thread-safe auth storage menggunakan `async-mutex` untuk mencegah kerusakan file kredensial saat trafik tinggi.
14
- - ๐Ÿ”„ **Message Retry & Auto Bad MAC Fix**: Manajemen otomatis untuk pengiriman ulang pesan dan perbaikan sesi enkripsi MAC rusak.
15
+ - ๐Ÿ”„ **Message Retry, PDO Fix & Auto Bad MAC Fix**: Manajemen otomatis untuk pengiriman ulang pesan, perbaikan *fallthrough* PDO resend, auto-refresh CDN pada `sock.downloadViewOnce()`, dan perbaikan sesi enkripsi MAC rusak.
15
16
  - ๐Ÿ“ž **LID to JID Auto Resolution**: Otomatis mendeteksi nomor telepon (`sender_pn`) jika pengirim menggunakan identitas `@lid`.
16
17
  - ๐Ÿงน **Bersih & Aman**: Bebas dari backdoor auto-follow channel dan bebas dari watermark banner terminal.
17
18
 
@@ -36,28 +37,41 @@ Lalu jalankan:
36
37
  npm install
37
38
  ```
38
39
 
39
- ### Cara Impor di Kode Bot:
40
+ ### Cara Impor di Kode Bot (Langsung RVO + Custom Pairing Siap Pakai!):
40
41
  ```javascript
41
- const { default: makeWASocket, useMultiFileAuthState, DisconnectReason } = require('@aldy11/baileys');
42
+ const { default: makeWASocket, useMultiFileAuthState, Browsers } = require('@aldy11/baileys');
42
43
 
43
44
  async function startBot() {
44
45
  const { state, saveCreds } = await useMultiFileAuthState('auth_info');
46
+ // Tanpa konfigurasi browser tambahan: otomatis Android Companion (View-Once / RVO penuh!)
47
+ // Otomatis mendeteksi WA Business (SMB_Android) setelah pairing & aman untuk sesi Web lama!
45
48
  const sock = makeWASocket({
46
49
  auth: state,
47
50
  printQRInTerminal: true
48
51
  });
49
-
52
+
53
+ // Opsional: login dengan Custom Pairing Code 8 karakter (tetap Android Companion + RVO penuh!)
54
+ if (!state.creds.registered) {
55
+ const code = await sock.requestPairingCode('628123456789', 'MYCODE88', { formatted: true });
56
+ console.log('Kode Pairing:', code); // -> MYCO-DE88
57
+ }
58
+
50
59
  sock.ev.on('creds.update', saveCreds);
51
60
  sock.ev.on('connection.update', (update) => {
52
- const { connection, lastDisconnect } = update;
53
- if (connection === 'open') {
54
- console.log('โœ… Bot WhatsApp Terhubung!');
61
+ if (update.connection === 'open') {
62
+ console.log('โœ… Terhubung! Mode:', sock.companionPlatformMode, '| RVO:', sock.isViewOnceSupported);
55
63
  }
56
64
  });
57
65
  }
58
66
  startBot();
59
67
  ```
60
68
 
69
+ > **Catatan Mode Perangkat (`browser`):**
70
+ > - Default sesi baru: `Browsers.android('14')` โ€” **RVO/View-Once penuh** (QR & Custom Pairing Code keduanya didukung).
71
+ > - Akun WhatsApp Business: otomatis terdeteksi & disimpan ke `creds.registeredPlatformMode = 'android-business'` setelah pairing (atau bisa dipaksa eksplisit dengan `browser: Browsers.androidBusiness('14')`).
72
+ > - Sesi lama (Web/Chrome sebelum v2.1.0): otomatis dideteksi sebagai `'web'` sehingga tidak terkena logout 401 saat upgrade; hapus folder sesi & tautkan ulang sekali untuk mengaktifkan RVO penuh.
73
+ > - Jika ingin memaksa mode Web klasik: `browser: Browsers.ubuntu('Chrome')`.
74
+
61
75
  ---
62
76
 
63
77
  ## ๐Ÿ’ก Contoh Penggunaan Fitur Unggulan
package/index.d.ts CHANGED
@@ -11,11 +11,14 @@ export interface AuthenticationState {
11
11
  };
12
12
  }
13
13
 
14
+ export type CompanionPlatformMode = 'android' | 'android-business' | 'web';
15
+
14
16
  export interface UserFacingSocketConfig {
15
17
  auth?: AuthenticationState;
16
18
  logger?: any;
17
19
  printQRInTerminal?: boolean;
18
20
  browser?: [string, string, string];
21
+ autoDetectCompanionPlatform?: boolean;
19
22
  markOnlineOnConnect?: boolean;
20
23
  syncFullHistory?: boolean;
21
24
  defaultQueryTimeoutMs?: number;
@@ -28,9 +31,20 @@ export interface UserFacingSocketConfig {
28
31
  [key: string]: any;
29
32
  }
30
33
 
34
+ export interface PairingCodeOptions {
35
+ customCode?: string;
36
+ pairKey?: string;
37
+ formatted?: boolean;
38
+ showPushNotification?: boolean;
39
+ }
40
+
31
41
  export interface WASocket {
32
42
  user?: { id: string; name?: string };
33
43
  authState: AuthenticationState;
44
+ readonly companionPlatformMode: CompanionPlatformMode;
45
+ readonly isViewOnceSupported: boolean;
46
+ getCompanionPlatformMode: () => CompanionPlatformMode;
47
+ getEffectiveBrowser: () => [string, string, string];
34
48
  ev: {
35
49
  on: (event: string, listener: (...args: any[]) => void) => void;
36
50
  off: (event: string, listener: (...args: any[]) => void) => void;
@@ -38,7 +52,7 @@ export interface WASocket {
38
52
  emit: (event: string, ...args: any[]) => boolean;
39
53
  };
40
54
  ws: any;
41
- requestPairingCode: (phoneNumber: string, pairKey?: string) => Promise<string>;
55
+ requestPairingCode: (phoneNumber: string, pairKey?: string | PairingCodeOptions, options?: PairingCodeOptions) => Promise<string>;
42
56
  sendMessage: (jid: string, content: any, options?: any) => Promise<any>;
43
57
  relayMessage: (jid: string, message: any, options?: any) => Promise<any>;
44
58
  sendReceipt: (jid: string, participant: string | undefined, messageIds: string[], type?: any) => Promise<void>;
@@ -94,13 +108,40 @@ export declare function useMultiFileAuthState(folder: string): Promise<{
94
108
  }>;
95
109
 
96
110
  export declare const Browsers: {
97
- (browser: string): [string, string, string];
98
- ubuntu: (browser: string) => [string, string, string];
99
- macOS: (browser: string) => [string, string, string];
100
- windows: (browser: string) => [string, string, string];
111
+ (browser?: string): [string, string, string];
112
+ ubuntu: (browser?: string) => [string, string, string];
113
+ macOS: (browser?: string) => [string, string, string];
114
+ windows: (browser?: string) => [string, string, string];
115
+ baileys: (browser?: string) => [string, string, string];
116
+ android: (version?: string) => [string, string, string];
117
+ androidBusiness: (version?: string) => [string, string, string];
118
+ appropriate: (browser?: string) => [string, string, string];
101
119
  };
102
120
 
103
121
  export declare function getPlatformId(browser: string): string;
122
+ export declare function isAndroidCompanionBrowser(browser?: [string, string, string]): boolean;
123
+ export declare function isSmbAndroidCompanionBrowser(browser?: [string, string, string]): boolean;
124
+ export declare function getCompanionBrowserMode(browser?: [string, string, string]): CompanionPlatformMode;
125
+ export declare function resolveEffectiveBrowser(config?: UserFacingSocketConfig, creds?: any): {
126
+ browser: [string, string, string];
127
+ mode: CompanionPlatformMode;
128
+ isViewOnceSupported: boolean;
129
+ isLegacyWebFallback: boolean;
130
+ };
131
+ export declare function resolvePairingBrowser(browserTuple?: [string, string, string]): {
132
+ osName: string;
133
+ browserName: string;
134
+ platformId: string;
135
+ platformDisplay: string;
136
+ };
137
+ export declare function formatPairingCode(code: string): string;
138
+ export declare function normalizePairingCode(pairKey?: string): {
139
+ valid: boolean;
140
+ code: string;
141
+ formatted: string;
142
+ warnings: string[];
143
+ error: string | null;
144
+ };
104
145
  export declare function fetchLatestBaileysVersion(options?: any): Promise<{ version: [number, number, number]; isLatest: boolean; error?: any }>;
105
146
  export declare function fetchLatestWaWebVersion(options?: any): Promise<{ version: [number, number, number]; isLatest: boolean; error?: any }>;
106
147
  export declare function generateWAMessage(jid: string, content: any, options: any): Promise<any>;
@@ -40,7 +40,10 @@ exports.PROCESSABLE_HISTORY_TYPES = [
40
40
  ];
41
41
  exports.DEFAULT_CONNECTION_CONFIG = {
42
42
  version: exports.version,
43
- browser: (0, browser_utils_1.Browsers)('Chrome'),
43
+ // Default ke Android Companion agar View-Once (RVO) terbuka penuh secara bawaan
44
+ // dan tetap 100% kompatibel dengan QR maupun Custom Pairing Code (auto-safe untuk sesi Web lama).
45
+ browser: browser_utils_1.Browsers.android('14'),
46
+ autoDetectCompanionPlatform: true,
44
47
  waWebSocketUrl: 'wss://web.whatsapp.com/ws/chat',
45
48
  connectTimeoutMs: 20_000,
46
49
  keepAliveIntervalMs: 30_000,
@@ -3,8 +3,27 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const Defaults_1 = require("../Defaults");
4
4
  const business_1 = require("./business");
5
5
  // export the last socket layer
6
- const makeWASocket = (config) => ((0, business_1.makeBusinessSocket)({
7
- ...Defaults_1.DEFAULT_CONNECTION_CONFIG,
8
- ...config
9
- }));
6
+ const makeWASocket = (config = {}) => {
7
+ const explicitBrowser = Boolean(config && Array.isArray(config.browser) && config.browser.length >= 2);
8
+ const sock = (0, business_1.makeBusinessSocket)({
9
+ ...Defaults_1.DEFAULT_CONNECTION_CONFIG,
10
+ ...config,
11
+ explicitBrowser,
12
+ });
13
+ if (typeof sock.getCompanionPlatformMode === 'function') {
14
+ Object.defineProperties(sock, {
15
+ companionPlatformMode: {
16
+ enumerable: true,
17
+ configurable: true,
18
+ get: () => sock.getCompanionPlatformMode(),
19
+ },
20
+ isViewOnceSupported: {
21
+ enumerable: true,
22
+ configurable: true,
23
+ get: () => sock.getCompanionPlatformMode() !== 'web',
24
+ },
25
+ });
26
+ }
27
+ return sock;
28
+ };
10
29
  exports.default = makeWASocket;
@@ -1066,7 +1066,20 @@ const makeMessagesSocket = (config) => {
1066
1066
  };
1067
1067
  // Power features (WhatsApp bypass & advanced capabilities)
1068
1068
  fullSocket.extractViewOnce = (msg) => (0, Utils_1.extractViewOnce)(msg);
1069
- fullSocket.downloadViewOnce = (msg, options) => (0, Utils_1.downloadViewOnce)(msg, options);
1069
+ fullSocket.downloadViewOnce = async (msg, options) => {
1070
+ try {
1071
+ return await (0, Utils_1.downloadViewOnce)(msg, options);
1072
+ }
1073
+ catch (err) {
1074
+ const errStr = String((err && err.message) || err || '');
1075
+ const isExpiredCdn = /403|404|410|expired|not found|forbidden/i.test(errStr);
1076
+ if (isExpiredCdn && msg && msg.key && msg.message && typeof fullSocket.updateMediaMessage === 'function') {
1077
+ const refreshed = await fullSocket.updateMediaMessage(msg);
1078
+ return await (0, Utils_1.downloadViewOnce)(refreshed, options);
1079
+ }
1080
+ throw err;
1081
+ }
1082
+ };
1070
1083
  fullSocket.sendGhostMention = (jid, text, mentions, options) => (0, Utils_1.sendGhostMention)(fullSocket, jid, text, mentions, options);
1071
1084
  fullSocket.tagAll = (groupId, text, options) => (0, Utils_1.tagAll)(fullSocket, groupId, text, options);
1072
1085
  fullSocket.sendFakeQuote = (jid, text, fakeOpts, options) => (0, Utils_1.sendFakeQuote)(fullSocket, jid, text, fakeOpts, options);
@@ -50,6 +50,17 @@ const makeSocket = (config) => {
50
50
  const decoded = (0, WABinary_1.jidDecode)(c.me.id);
51
51
  return Boolean(c.registered && decoded && typeof decoded.device === 'number' && decoded.device > 0);
52
52
  };
53
+ const getEffectiveConnectionState = () => (0, Utils_1.resolveEffectiveBrowser)(config, creds);
54
+ const getEffectiveConfig = () => {
55
+ const effective = getEffectiveConnectionState();
56
+ return {
57
+ effective,
58
+ effectiveConfig: {
59
+ ...config,
60
+ browser: effective.browser
61
+ }
62
+ };
63
+ };
53
64
  let handshakeReady = false;
54
65
  let resolveHandshake;
55
66
  let rejectHandshake;
@@ -182,11 +193,12 @@ const makeSocket = (config) => {
182
193
  };
183
194
  /** connection handshake */
184
195
  const validateConnection = async () => {
196
+ const { effective, effectiveConfig } = getEffectiveConfig();
185
197
  let helloMsg = {
186
198
  clientHello: { ephemeral: ephemeralKeyPair.public }
187
199
  };
188
200
  helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
189
- logger.info({ browser, helloMsg }, 'connected to WA');
201
+ logger.info({ browser: effective.browser, companionMode: effective.mode, helloMsg }, 'connected to WA');
190
202
  const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
191
203
  const result = await awaitNextMessage(init);
192
204
  const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
@@ -194,12 +206,12 @@ const makeSocket = (config) => {
194
206
  const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
195
207
  let node;
196
208
  if (!hasLinkedDeviceCreds(creds)) {
197
- node = (0, Utils_1.generateRegistrationNode)(creds, config);
198
- logger.info({ node }, 'not logged in, attempting registration...');
209
+ node = (0, Utils_1.generateRegistrationNode)(creds, effectiveConfig);
210
+ logger.info({ node, companionMode: effective.mode }, 'not logged in, attempting registration...');
199
211
  }
200
212
  else {
201
- node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
202
- logger.info({ node }, 'logging in...');
213
+ node = (0, Utils_1.generateLoginNode)(creds.me.id, effectiveConfig, creds);
214
+ logger.info({ node, companionMode: effective.mode }, 'logging in...');
203
215
  }
204
216
  const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
205
217
  await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
@@ -405,20 +417,25 @@ const makeSocket = (config) => {
405
417
  }
406
418
  end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
407
419
  };
408
- const requestPairingCode = async (phoneNumber, pairKey = "") => {
420
+ const requestPairingCode = async (phoneNumber, pairKey = "", options = {}) => {
409
421
  if (hasLinkedDeviceCreds(authState.creds)) {
410
422
  throw new boom_1.Boom('Session is already authenticated; cannot request pairing code', { statusCode: 400 });
411
423
  }
424
+ let rawPairKey = pairKey;
425
+ let opts = options && typeof options === 'object' ? options : {};
426
+ if (pairKey && typeof pairKey === 'object') {
427
+ opts = pairKey;
428
+ rawPairKey = opts.customCode || opts.pairKey || '';
429
+ }
412
430
  const sanitizedPhone = String(phoneNumber || '').replace(/[^0-9]/g, '');
413
431
  if (!sanitizedPhone || sanitizedPhone.length < 7) {
414
432
  throw new boom_1.Boom('Invalid phone number for pairing code (must contain digits with country code, e.g. 628123456789)', { statusCode: 400 });
415
433
  }
416
- const cleanedPairKey = typeof pairKey === 'string'
417
- ? pairKey.replace(/[^a-zA-Z0-9]/g, '').toUpperCase()
418
- : '';
419
- if (cleanedPairKey && cleanedPairKey.length !== 8) {
420
- throw new boom_1.Boom('Custom pairing code must be exactly 8 alphanumeric characters', { statusCode: 400 });
434
+ const parsedPairKey = (0, Utils_1.normalizePairingCode)(typeof rawPairKey === 'string' ? rawPairKey : '');
435
+ if (!parsedPairKey.valid) {
436
+ throw new boom_1.Boom(parsedPairKey.error || 'Custom pairing code must be exactly 8 alphanumeric characters', { statusCode: 400 });
421
437
  }
438
+ const cleanedPairKey = parsedPairKey.code;
422
439
  await waitForSocketOpen();
423
440
  if (!handshakeReady) {
424
441
  await (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
@@ -437,7 +454,8 @@ const makeSocket = (config) => {
437
454
  const prevPairingCode = authState.creds.pairingCode;
438
455
  const prevMe = authState.creds.me;
439
456
  const pairingCode = cleanedPairKey || (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
440
- const pairingPlatform = (0, Utils_1.resolvePairingBrowser)(browser);
457
+ const { effective } = getEffectiveConfig();
458
+ const pairingPlatform = (0, Utils_1.resolvePairingBrowser)(effective.browser);
441
459
  authState.creds.pairingCode = pairingCode;
442
460
  authState.creds.registered = false;
443
461
  authState.creds.me = {
@@ -460,7 +478,7 @@ const makeSocket = (config) => {
460
478
  jid: authState.creds.me.id,
461
479
  stage: 'companion_hello',
462
480
  // eslint-disable-next-line camelcase
463
- should_show_push_notification: 'true'
481
+ should_show_push_notification: opts.showPushNotification === false ? 'false' : 'true'
464
482
  },
465
483
  content: [
466
484
  {
@@ -499,7 +517,9 @@ const makeSocket = (config) => {
499
517
  throw err;
500
518
  }
501
519
  ev.emit('creds.update', authState.creds);
502
- return authState.creds.pairingCode;
520
+ return opts.formatted
521
+ ? (0, Utils_1.formatPairingCode)(authState.creds.pairingCode)
522
+ : authState.creds.pairingCode;
503
523
  };
504
524
  async function generatePairingKey() {
505
525
  const salt = (0, crypto_1.randomBytes)(32);
@@ -582,8 +602,9 @@ const makeSocket = (config) => {
582
602
  ws.on('CB:iq,,pair-success', async (stanza) => {
583
603
  logger.debug('pair success recv');
584
604
  try {
585
- const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
586
- logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
605
+ const { effectiveConfig } = getEffectiveConfig();
606
+ const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds, effectiveConfig);
607
+ logger.info({ me: updatedCreds.me, platform: updatedCreds.platform, registeredPlatformMode: updatedCreds.registeredPlatformMode }, 'pairing configured successfully, expect to restart the connection...');
587
608
  ev.emit('creds.update', updatedCreds);
588
609
  ev.emit('connection.update', { isNewLogin: true, qr: undefined });
589
610
  await sendNode(reply);
@@ -600,7 +621,14 @@ const makeSocket = (config) => {
600
621
  await sendPassiveIq('active');
601
622
  logger.info('opened connection to WA');
602
623
  clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
603
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid }, registered: true });
624
+ const { effective } = getEffectiveConfig();
625
+ const credsUpdate = { me: { ...authState.creds.me, lid: node.attrs.lid }, registered: true };
626
+ if (!authState.creds.registeredPlatformMode) {
627
+ credsUpdate.registeredPlatformMode = (effective.mode === 'android' && (0, Utils_1.isWABusinessPlatform)(authState.creds.platform))
628
+ ? 'android-business'
629
+ : effective.mode;
630
+ }
631
+ ev.emit('creds.update', credsUpdate);
604
632
  ev.emit('connection.update', { connection: 'open' });
605
633
  }
606
634
  catch (err) {
@@ -699,6 +727,8 @@ const makeSocket = (config) => {
699
727
  uploadPreKeys,
700
728
  uploadPreKeysToServerIfRequired,
701
729
  requestPairingCode,
730
+ getCompanionPlatformMode: () => getEffectiveConnectionState().mode,
731
+ getEffectiveBrowser: () => getEffectiveConnectionState().browser,
702
732
  /** Waits for the connection to WA to reach a state */
703
733
  waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
704
734
  sendWAMBuffer,
@@ -191,6 +191,7 @@ const initAuthCreds = () => {
191
191
  unarchiveChats: false
192
192
  },
193
193
  registered: false,
194
+ registeredPlatformMode: undefined,
194
195
  pairingCode: undefined,
195
196
  lastPropHash: undefined,
196
197
  routingInfo: undefined,
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolvePairingBrowser = exports.getPlatformId = exports.Browsers = void 0;
3
+ exports.formatPairingCode = exports.normalizePairingCode = exports.resolveEffectiveBrowser = exports.getCompanionBrowserMode = exports.isAndroidCompanionBrowser = exports.isSmbAndroidCompanionBrowser = exports.resolvePairingBrowser = exports.getPlatformId = exports.Browsers = void 0;
4
4
 
5
5
  const os = require("os");
6
6
  const { proto } = require("../../WAProto/index.js");
@@ -50,6 +50,144 @@ Browsers.appropriate = (browser = 'Chrome') => [PLATFORM_MAP[os.platform()] || '
50
50
 
51
51
  exports.Browsers = Browsers;
52
52
 
53
+ const isSmbAndroidCompanionBrowser = (browser) => {
54
+ const name = Array.isArray(browser) ? String(browser[1] || '').toLowerCase() : '';
55
+ return name.includes('smb_android') || name === 'smba';
56
+ };
57
+ exports.isSmbAndroidCompanionBrowser = isSmbAndroidCompanionBrowser;
58
+
59
+ const isAndroidCompanionBrowser = (browser) => {
60
+ const name = Array.isArray(browser) ? String(browser[1] || '').toLowerCase() : '';
61
+ return name.includes('android') || name === 'smba';
62
+ };
63
+ exports.isAndroidCompanionBrowser = isAndroidCompanionBrowser;
64
+
65
+ const getCompanionBrowserMode = (browser) => {
66
+ if (isSmbAndroidCompanionBrowser(browser)) {
67
+ return 'android-business';
68
+ }
69
+ if (isAndroidCompanionBrowser(browser)) {
70
+ return 'android';
71
+ }
72
+ return 'web';
73
+ };
74
+ exports.getCompanionBrowserMode = getCompanionBrowserMode;
75
+
76
+ const isBusinessPlatformName = (platform) => {
77
+ const normalized = String(platform || '').toLowerCase();
78
+ return normalized === 'smba' || normalized === 'smbi';
79
+ };
80
+
81
+ const hasLinkedSessionCreds = (creds) => {
82
+ if (!(creds && creds.me && creds.me.id)) {
83
+ return false;
84
+ }
85
+ if (creds.account) {
86
+ return true;
87
+ }
88
+ return Boolean(creds.registered && /:\d+@/.test(String(creds.me.id)));
89
+ };
90
+
91
+ /**
92
+ * Menentukan tuple browser dan mode companion yang paling akurat untuk sesi baru maupun sesi tertaut:
93
+ * - Sesi baru (default): memakai Android Companion (`Browsers.android('14')`) agar View-Once (RVO)
94
+ * terbuka penuh sekaligus tetap kompatibel dengan QR & Custom Pairing Code.
95
+ * - Sesi tertaut baru (punya `creds.registeredPlatformMode`): otomatis menyelaraskan `android`,
96
+ * `android-business` (deteksi WA Business `smba`/`smbi`), atau `web` tanpa konfigurasi tambahan.
97
+ * - Sesi legacy lama (tertaut sebelum v2.1.0 tanpa `registeredPlatformMode` & tanpa `browser` eksplisit):
98
+ * otomatis memakai `Browsers.ubuntu('Chrome')` (mode `web`) agar tidak memicu logout 401 saat upgrade.
99
+ */
100
+ const resolveEffectiveBrowser = (config = {}, creds = undefined) => {
101
+ const configuredBrowser = Array.isArray(config.browser) && config.browser.length >= 2
102
+ ? config.browser
103
+ : Browsers.android('14');
104
+ const explicitBrowser = Boolean(config.explicitBrowser);
105
+ const autoDetect = config.autoDetectCompanionPlatform !== false;
106
+ const isLinked = hasLinkedSessionCreds(creds);
107
+
108
+ if (!isLinked || !autoDetect) {
109
+ const mode = getCompanionBrowserMode(configuredBrowser);
110
+ return {
111
+ browser: configuredBrowser,
112
+ mode,
113
+ isViewOnceSupported: mode !== 'web',
114
+ isLegacyWebFallback: false,
115
+ };
116
+ }
117
+
118
+ const savedMode = typeof creds?.registeredPlatformMode === 'string'
119
+ ? creds.registeredPlatformMode.trim().toLowerCase()
120
+ : '';
121
+ const isBizAccount = isBusinessPlatformName(creds?.platform);
122
+
123
+ if (savedMode === 'android-business' || (savedMode === 'android' && isBizAccount)) {
124
+ const browser = isSmbAndroidCompanionBrowser(configuredBrowser)
125
+ ? configuredBrowser
126
+ : Browsers.androidBusiness('14');
127
+ return {
128
+ browser,
129
+ mode: 'android-business',
130
+ isViewOnceSupported: true,
131
+ isLegacyWebFallback: false,
132
+ };
133
+ }
134
+
135
+ if (savedMode === 'android') {
136
+ const browser = (isAndroidCompanionBrowser(configuredBrowser) && !isSmbAndroidCompanionBrowser(configuredBrowser))
137
+ ? configuredBrowser
138
+ : Browsers.android('14');
139
+ return {
140
+ browser,
141
+ mode: 'android',
142
+ isViewOnceSupported: true,
143
+ isLegacyWebFallback: false,
144
+ };
145
+ }
146
+
147
+ if (savedMode === 'web') {
148
+ const browser = (explicitBrowser && !isAndroidCompanionBrowser(configuredBrowser))
149
+ ? configuredBrowser
150
+ : Browsers.ubuntu('Chrome');
151
+ return {
152
+ browser,
153
+ mode: 'web',
154
+ isViewOnceSupported: false,
155
+ isLegacyWebFallback: false,
156
+ };
157
+ }
158
+
159
+ // Sesi legacy (sebelum v2.1.0, belum memiliki registeredPlatformMode di creds.json)
160
+ if (explicitBrowser) {
161
+ if (isAndroidCompanionBrowser(configuredBrowser) && isBizAccount) {
162
+ const browser = isSmbAndroidCompanionBrowser(configuredBrowser)
163
+ ? configuredBrowser
164
+ : Browsers.androidBusiness('14');
165
+ return {
166
+ browser,
167
+ mode: 'android-business',
168
+ isViewOnceSupported: true,
169
+ isLegacyWebFallback: false,
170
+ };
171
+ }
172
+ const mode = getCompanionBrowserMode(configuredBrowser);
173
+ return {
174
+ browser: configuredBrowser,
175
+ mode,
176
+ isViewOnceSupported: mode !== 'web',
177
+ isLegacyWebFallback: false,
178
+ };
179
+ }
180
+
181
+ // Default aman untuk sesi legacy tanpa explicit browser: pertahankan mode Web (hindari 401)
182
+ return {
183
+ browser: Browsers.ubuntu('Chrome'),
184
+ mode: 'web',
185
+ isViewOnceSupported: false,
186
+ isLegacyWebFallback: true,
187
+ };
188
+ };
189
+ exports.resolveEffectiveBrowser = resolveEffectiveBrowser;
190
+
53
191
  const getPlatformId = (browser) => {
54
192
  const key = String(browser || '').toUpperCase();
55
193
  if (key === 'ANDROID' || key === 'SMB_ANDROID') {
@@ -81,4 +219,55 @@ const resolvePairingBrowser = (browserTuple) => {
81
219
  };
82
220
  };
83
221
 
84
- exports.resolvePairingBrowser = resolvePairingBrowser;
222
+ exports.resolvePairingBrowser = resolvePairingBrowser;
223
+
224
+ /**
225
+ * Memformat kode pairing 8 karakter menjadi XXXX-XXXX agar mudah dibaca & diketik di WhatsApp HP.
226
+ */
227
+ const formatPairingCode = (code) => {
228
+ const clean = String(code || '').replace(/[^a-zA-Z0-9]/g, '').toUpperCase();
229
+ if (clean.length === 8) {
230
+ return `${clean.slice(0, 4)}-${clean.slice(4)}`;
231
+ }
232
+ return clean;
233
+ };
234
+ exports.formatPairingCode = formatPairingCode;
235
+
236
+ /**
237
+ * Menormalisasi & memvalidasi custom pairing code (8 karakter alfanumerik, otomatis hapus strip/spasi).
238
+ */
239
+ const normalizePairingCode = (pairKey) => {
240
+ const raw = typeof pairKey === 'string' ? pairKey : '';
241
+ const cleaned = raw.replace(/[^a-zA-Z0-9]/g, '').toUpperCase();
242
+ if (!cleaned) {
243
+ return {
244
+ valid: true,
245
+ code: '',
246
+ formatted: '',
247
+ warnings: [],
248
+ error: null,
249
+ };
250
+ }
251
+ if (cleaned.length !== 8) {
252
+ return {
253
+ valid: false,
254
+ code: '',
255
+ formatted: '',
256
+ warnings: [],
257
+ error: `Custom pairing code must be exactly 8 alphanumeric characters (got ${cleaned.length}: "${cleaned}")`,
258
+ };
259
+ }
260
+ const warnings = [];
261
+ const ambiguous = [...new Set(cleaned.split('').filter((ch) => '0ILOU'.includes(ch)))];
262
+ if (ambiguous.length > 0) {
263
+ warnings.push(`Code "${cleaned}" contains potentially ambiguous characters (${ambiguous.join(', ')}) on some WhatsApp clients; prefer 1-9 and A-Z excluding I, L, O, U.`);
264
+ }
265
+ return {
266
+ valid: true,
267
+ code: cleaned,
268
+ formatted: formatPairingCode(cleaned),
269
+ warnings,
270
+ error: null,
271
+ };
272
+ };
273
+ exports.normalizePairingCode = normalizePairingCode;
@@ -9,16 +9,10 @@ const WABinary_1 = require("../WABinary");
9
9
  const crypto_2 = require("./crypto");
10
10
  const generics_1 = require("./generics");
11
11
  const signal_1 = require("./signal");
12
+ const browser_utils_1 = require("./browser-utils");
12
13
 
13
- const isSmbAndroidBrowser = (browser) => {
14
- const name = Array.isArray(browser) ? String(browser[1] || '').toLowerCase() : '';
15
- return name.includes('smb_android') || name === 'smba';
16
- };
17
-
18
- const isAndroidBrowser = (browser) => {
19
- const name = Array.isArray(browser) ? String(browser[1] || '').toLowerCase() : '';
20
- return name.includes('android') || name === 'smba';
21
- };
14
+ const isSmbAndroidBrowser = browser_utils_1.isSmbAndroidCompanionBrowser;
15
+ const isAndroidBrowser = browser_utils_1.isAndroidCompanionBrowser;
22
16
 
23
17
  const getUserAgent = (config) => {
24
18
  const userAgentPlatform = isSmbAndroidBrowser(config.browser)
@@ -69,10 +63,16 @@ const getClientPayload = (config) => {
69
63
  return payload;
70
64
  };
71
65
 
72
- const generateLoginNode = (userJid, config) => {
66
+ const generateLoginNode = (userJid, config, creds) => {
73
67
  const { user, device } = (0, WABinary_1.jidDecode)(userJid);
68
+ const effectiveConfig = creds
69
+ ? {
70
+ ...config,
71
+ browser: (0, browser_utils_1.resolveEffectiveBrowser)(config, creds).browser
72
+ }
73
+ : config;
74
74
  const payload = {
75
- ...getClientPayload(config),
75
+ ...getClientPayload(effectiveConfig),
76
76
  passive: true,
77
77
  pull: true,
78
78
  username: +user,
@@ -149,7 +149,7 @@ const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentity
149
149
  };
150
150
  exports.generateRegistrationNode = generateRegistrationNode;
151
151
 
152
- const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
152
+ const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }, config) => {
153
153
  const msgId = stanza.attrs.id;
154
154
  const pairSuccessNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-success');
155
155
  const deviceIdentityNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'device-identity');
@@ -224,6 +224,19 @@ const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, s
224
224
  ]
225
225
  };
226
226
 
227
+ const platformName = platformNode?.attrs.name;
228
+ let registeredPlatformMode;
229
+ if (config && Array.isArray(config.browser)) {
230
+ if (isAndroidBrowser(config.browser)) {
231
+ registeredPlatformMode = (isSmbAndroidBrowser(config.browser) || (0, generics_1.isWABusinessPlatform)(platformName))
232
+ ? 'android-business'
233
+ : 'android';
234
+ }
235
+ else {
236
+ registeredPlatformMode = 'web';
237
+ }
238
+ }
239
+
227
240
  const authUpdate = {
228
241
  account,
229
242
  me: { id: jid, name: bizName, lid },
@@ -231,8 +244,9 @@ const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, s
231
244
  ...(signalIdentities || []),
232
245
  identity
233
246
  ],
234
- platform: platformNode?.attrs.name,
235
- registered: true
247
+ platform: platformName,
248
+ registered: true,
249
+ ...(registeredPlatformMode ? { registeredPlatformMode } : {})
236
250
  };
237
251
 
238
252
  return {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aldy11/baileys",
3
- "version": "2.0.6",
4
- "description": "WhatsApp Multi-Device API Library with Native Flow Buttons, Meta AI Primitives, and Session Protection",
3
+ "version": "2.1.0",
4
+ "description": "WhatsApp Multi-Device API Library with Out-of-the-Box Android Companion View-Once (RVO), Universal Custom Pairing Code, Native Flow Buttons, and Meta AI Primitives",
5
5
  "author": "aldy11",
6
6
  "main": "lib/index.js",
7
7
  "types": "index.d.ts",
@@ -18,6 +18,9 @@
18
18
  "whatsapp-api",
19
19
  "whatsapp-bot",
20
20
  "multi-device",
21
+ "view-once",
22
+ "rvo",
23
+ "pairing-code",
21
24
  "interactive-buttons",
22
25
  "meta-ai"
23
26
  ],