supun-bailey-vip 1.0.6 → 1.0.7

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/lib/defaults.js CHANGED
@@ -77,8 +77,12 @@ export const DEFAULT_CONNECTION_CONFIG = {
77
77
  transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
78
78
  generateHighQualityLinkPreview: false,
79
79
  enableAutoSessionRecreation: true,
80
- enableRecentMessageCache: true,
81
- options: {},
80
+ maxMediaSize: 3 * 1024 * 1024 * 1024, // 3 GB default max media upload size
81
+ mediaUploadTimeoutMs: 30 * 60 * 1000, // 30 minutes timeout for large file uploads
82
+ options: {
83
+ maxContentLength: 3 * 1024 * 1024 * 1024,
84
+ maxBodyLength: 3 * 1024 * 1024 * 1024
85
+ },
82
86
  appStateMacVerification: { patch: false, snapshot: false },
83
87
  countryCode: 'US',
84
88
  getMessage: async () => undefined,
@@ -0,0 +1,115 @@
1
+ /**
2
+ * @license
3
+ * ============================================================================
4
+ * 🔒 SUPUN BAILEY VIP — ENCRYPTED & LOCKED LICENSE MODULE
5
+ * Protected binary wrapper. Decompilation, tampering, or modification prohibited.
6
+ * (C) 2026 Supun Fernando. All rights reserved.
7
+ * ============================================================================
8
+ */
9
+ import * as _0x2f9c from 'node:crypto';
10
+ import * as _0x5a1b from 'node:fs';
11
+
12
+ const _0x1a8e = [
13
+ '32393531656232663634653262373939326635616236383933366465623332383038346231633466306264373563306136646262373630313635343331363761',
14
+ '737570756e2d6261696c65792d7669702d6c6963656e73652d73616c742d32303236',
15
+ '736861323536',
16
+ '686578',
17
+ '6b6579',
18
+ '6c6963656e73654b6579',
19
+ '7669704b6579',
20
+ '535550554e5f4b4559',
21
+ '535550554e5f5649505f4b4559',
22
+ '5649505f4b4559',
23
+ '2e2f7669702d6b65792e6a736f6e',
24
+ '2e2f6b65792e747874',
25
+ '2e2f2e7669702d6b6579',
26
+ '75746638'
27
+ ];
28
+
29
+ (function (_0x3d0c, _0x4f82) {
30
+ const _0x1c4a = function (_0x5e19) {
31
+ while (--_0x5e19) {
32
+ _0x3d0c['push'](_0x3d0c['shift']());
33
+ }
34
+ };
35
+ _0x1c4a(++_0x4f82);
36
+ }(_0x1a8e, 0x1b));
37
+
38
+ const _0x4b7f = function (_0x21c8) {
39
+ _0x21c8 = parseInt(_0x21c8, 16);
40
+ let _0x501a = _0x1a8e[_0x21c8];
41
+ return Buffer['from'](_0x501a, 'hex')['toString']('utf8');
42
+ };
43
+
44
+ export function verifyVipAccess(_0x2d81 = {}) {
45
+ let _0x47e3 = '';
46
+ if (_0x2d81[_0x4b7f('0x5')]) _0x47e3 = String(_0x2d81[_0x4b7f('0x5')]);
47
+ else if (_0x2d81[_0x4b7f('0x6')]) _0x47e3 = String(_0x2d81[_0x4b7f('0x6')]);
48
+ else if (_0x2d81[_0x4b7f('0x7')]) _0x47e3 = String(_0x2d81[_0x4b7f('0x7')]);
49
+ else if (process['env'][_0x4b7f('0x8')]) _0x47e3 = process['env'][_0x4b7f('0x8')];
50
+ else if (process['env'][_0x4b7f('0x9')]) _0x47e3 = process['env'][_0x4b7f('0x9')];
51
+ else if (process['env'][_0x4b7f('0xa')]) _0x47e3 = process['env'][_0x4b7f('0xa')];
52
+ else {
53
+ const _0x19a0 = [_0x4b7f('0xb'), _0x4b7f('0xc'), _0x4b7f('0xd')];
54
+ for (const _0x3b2c of _0x19a0) {
55
+ try {
56
+ if (_0x5a1b['existsSync'](_0x3b2c)) {
57
+ const _0x2e61 = _0x5a1b['readFileSync'](_0x3b2c, _0x4b7f('0x0'))['trim']();
58
+ if (_0x2e61['startsWith']('{')) {
59
+ const _0x3a4f = JSON['parse'](_0x2e61);
60
+ if (_0x3a4f['key'] || _0x3a4f['licenseKey']) { _0x47e3 = String(_0x3a4f['key'] || _0x3a4f['licenseKey']); break; }
61
+ } else if (_0x2e61) {
62
+ _0x47e3 = _0x2e61;
63
+ break;
64
+ }
65
+ }
66
+ } catch {}
67
+ }
68
+ }
69
+
70
+ const _0x23f8 = String(_0x47e3 || '')['trim']();
71
+ if (!_0x23f8) {
72
+ _0x39fa();
73
+ }
74
+
75
+ const _0x48d2 = _0x4b7f('0x1');
76
+ const _0x51c7 = _0x4b7f('0x2');
77
+ const _0x140e = _0x4b7f('0x3');
78
+ const _0x27f1 = _0x4b7f('0x4');
79
+
80
+ const _0x573b = _0x2f9c['createHmac'](_0x140e, _0x51c7)['update'](_0x23f8)['digest'](_0x27f1);
81
+ const _0x17d6 = Buffer['from'](_0x573b, _0x27f1);
82
+ const _0x4c2e = Buffer['from'](_0x48d2, _0x27f1);
83
+
84
+ if (_0x17d6['length'] !== _0x4c2e['length'] || !_0x2f9c['timingSafeEqual'](_0x17d6, _0x4c2e)) {
85
+ _0x39fa();
86
+ }
87
+
88
+ return true;
89
+ }
90
+
91
+ function _0x39fa() {
92
+ const _0x3c2a = '\x1b[31;1m';
93
+ const _0x1f94 = '\x1b[33;1m';
94
+ const _0x4b31 = '\x1b[37;1m';
95
+ const _0x2e18 = '\x1b[36m';
96
+ const _0x54d2 = '\x1b[0m';
97
+
98
+ console['error']('\n' + _0x3c2a + ' ╔══════════════════════════════════════════════════════════════════╗' + _0x54d2);
99
+ console['error'](_0x3c2a + ' ║ 🔒 ACCESS DENIED — VIP LICENSE LOCKED ║' + _0x54d2);
100
+ console['error'](_0x3c2a + ' ╠══════════════════════════════════════════════════════════════════╣' + _0x54d2);
101
+ console['error'](_0x3c2a + ' ║ ║' + _0x54d2);
102
+ console['error'](_0x3c2a + ' ║ ' + _0x4b31 + 'Unauthorized Access!' + _0x1f94 + ' Invalid or Missing VIP License Key. ' + _0x3c2a + '║' + _0x54d2);
103
+ console['error'](_0x3c2a + ' ║ ' + _0x2e18 + 'This Baileys modification is private property of Supun Fernando. ' + _0x3c2a + '║' + _0x54d2);
104
+ console['error'](_0x3c2a + ' ║ ║' + _0x54d2);
105
+ console['error'](_0x3c2a + ' ║ ' + _0x4b31 + 'To unlock and run, provide the valid VIP License Key: ' + _0x3c2a + '║' + _0x54d2);
106
+ console['error'](_0x3c2a + ' ║ ' + _0x1f94 + '• Pass { key: "YOUR_KEY" } in makeWASocket(config) ' + _0x3c2a + '║' + _0x54d2);
107
+ console['error'](_0x3c2a + ' ║ ' + _0x1f94 + '• Or set in terminal: export SUPUN_KEY="YOUR_KEY" ' + _0x3c2a + '║' + _0x54d2);
108
+ console['error'](_0x3c2a + ' ║ ║' + _0x54d2);
109
+ console['error'](_0x3c2a + ' ╚══════════════════════════════════════════════════════════════════╝' + _0x54d2 + '\n');
110
+
111
+ throw new Error('[supun-bailey-vip] ACCESS DENIED: Invalid or Missing VIP License Key! Contact Supun Fernando.');
112
+ }
113
+
114
+ export const assertVipLicense = verifyVipAccess;
115
+ export default verifyVipAccess;
package/lib/index.js CHANGED
@@ -30,6 +30,10 @@ import { DEFAULT_CONNECTION_CONFIG } from './defaults.js'
30
30
  import { makeCommunitiesSocket } from './socket/business-communities.js'
31
31
  import { makeMessageBuilderSocket } from './socket/socket-builder.js'
32
32
  import { applyPerformanceMode } from './foundation/performance.js'
33
+ import { installConsoleFilter } from './utils/console-filter.js'
34
+ import { verifyVipAccess } from './foundation/vip-license.js'
35
+
36
+ installConsoleFilter()
33
37
 
34
38
  // === BANNER ASCII SMD — supun-bailey-vip (Sri Lankan flag palette) ===
35
39
  console.log('\n' + chalk.hex('#FFC72C')(' ███████╗ ███╗ ███╗ ██████╗ '))
@@ -58,6 +62,7 @@ console.log(smdLine)
58
62
  console.log(chalk.hex('#00534E').bold(' ✓ ') + chalk.greenBright.bold('Baileys Connected — Online') + '\n')
59
63
 
60
64
  const makeWASocket = config => {
65
+ verifyVipAccess(config)
61
66
  const newConfig = {
62
67
  ...DEFAULT_CONNECTION_CONFIG,
63
68
  ...config,
@@ -139,6 +144,26 @@ export * from './utils/native-flow.js'
139
144
  export { resolveNativeFlowButtons, makeWhatsAppFlowButton } from './utils/native-flow.js'
140
145
  export * from './foundation/reporting-info-store.js'
141
146
  export * from './foundation/interactive-buttons.js'
147
+ export * from './utils/button-builder.js'
148
+ export * from './utils/experimental-buttons.js'
149
+ export * from './utils/replies.js'
150
+ export * from './utils/interactive.js'
151
+ export * from './utils/sender-utils.js'
152
+ export * from './utils/vip-engine.js'
153
+ export * from './utils/message-processing.js'
154
+ export * from './utils/chat-extras.js'
155
+ export * from './utils/html-format.js'
156
+ export * from './utils/session-backup.js'
157
+ export * from './utils/pairing-utils.js'
158
+ export * from './utils/send-queue.js'
159
+ export * from './utils/group-cache.js'
160
+ export * from './utils/message-store.js'
161
+ export * from './utils/console-filter.js'
162
+ export * from './utils/pretty-log.js'
163
+ export * from './utils/live-wa-version.js'
164
+ export * from './socket/session-manager.js'
165
+ export * from './socket/connect-bot.js'
166
+ export * from './foundation/vip-license.js'
142
167
 
143
168
  export { makeWASocket }
144
169
  export default makeWASocket
@@ -0,0 +1,96 @@
1
+ /**
2
+ * lib/socket/connect-bot.js
3
+ * One-line bot starter with automatic auth directory validation, pairing code handling, and reconnection.
4
+ */
5
+
6
+ import { Boom } from '../foundation/boom.js'
7
+ import os from 'os'
8
+ import path from 'path'
9
+ import { explainLinkError, formatPairingCode, normalizePhoneNumber } from '../utils/pairing-utils.js'
10
+ import { makeSessionManager } from './session-manager.js'
11
+
12
+ const assertSafeAuthDir = (authDir) => {
13
+ if (typeof authDir !== 'string' || !authDir.trim()) {
14
+ throw new Boom('authDir is required: the folder where the session is saved (e.g. "./session")', { statusCode: 400 })
15
+ }
16
+ const resolved = path.resolve(authDir)
17
+ const unsafe = [path.parse(resolved).root, os.homedir(), process.cwd()]
18
+ if (unsafe.includes(resolved)) {
19
+ throw new Boom(`authDir "${authDir}" is not safe: use a dedicated subdirectory, like "./session"`, {
20
+ statusCode: 400
21
+ })
22
+ }
23
+ return resolved
24
+ }
25
+
26
+ /**
27
+ * Starts a complete WhatsApp bot with pairing code (or QR), session folder, and auto-reconnect.
28
+ */
29
+ export const connectBot = async (options = {}) => {
30
+ const authDir = assertSafeAuthDir(options.authDir || './session')
31
+ const number = options.number ? normalizePhoneNumber(options.number) : undefined
32
+ const log = options.log || (line => console.log(line))
33
+
34
+ const manager = makeSessionManager({
35
+ authDir,
36
+ authPath: () => authDir,
37
+ config: options.config,
38
+ setup: options.setup,
39
+ autoReconnect: options.reconnect ?? true,
40
+ pairingRetries: options.pairingRetries,
41
+ makeSocket: options.makeSocket,
42
+ sleep: options.sleep
43
+ })
44
+
45
+ let resolveReady = () => undefined
46
+ const ready = new Promise(resolve => {
47
+ resolveReady = resolve
48
+ })
49
+
50
+ manager.on('session.pairing-code', ({ code }) => {
51
+ const info = { code, formatted: formatPairingCode(code), number: number || '' }
52
+ if (options.onCode) {
53
+ options.onCode(info)
54
+ return
55
+ }
56
+ log(`🔗 WhatsApp Pairing Code: ${info.formatted}`)
57
+ log(' On phone: WhatsApp > Linked Devices > Link a Device > Link with phone number instead')
58
+ })
59
+
60
+ manager.on('session.qr', ({ qr }) => {
61
+ if (options.onQR) {
62
+ options.onQR(qr)
63
+ return
64
+ }
65
+ log('⚠️ QR Code received. Provide `number` for pairing code or `onQR` handler.')
66
+ })
67
+
68
+ manager.on('session.open', ({ id }) => {
69
+ const sock = manager.get(id)
70
+ if (!sock) return
71
+ resolveReady(sock)
72
+ options.onOpen?.(sock)
73
+ })
74
+
75
+ manager.on('session.close', ({ reason, willReconnect }) => {
76
+ options.onClose?.({ reason, willReconnect, message: explainLinkError(reason) })
77
+ })
78
+
79
+ manager.on('session.error', ({ error }) => {
80
+ const message = explainLinkError(error)
81
+ if (options.onError) options.onError(error, message)
82
+ else log(`⚠️ ${message}`)
83
+ })
84
+
85
+ await manager.start('main', { pairingNumber: number })
86
+
87
+ return {
88
+ ready,
89
+ get sock() {
90
+ return manager.get('main')
91
+ },
92
+ stop: () => manager.stop('main'),
93
+ logout: () => manager.logout('main'),
94
+ manager
95
+ }
96
+ }
@@ -53,6 +53,16 @@ import {
53
53
  } from '../binary/wa-binary.js'
54
54
  import { USyncQuery, USyncUser } from './usync.js'
55
55
  import { makeNewsletterSocket } from './newsletter.js'
56
+ import {
57
+ VipEngine,
58
+ richMenu,
59
+ sendInstaView,
60
+ sendHtml,
61
+ setLabelGroup,
62
+ sendStatusMention,
63
+ checkWhatsApp,
64
+ reqPairing
65
+ } from '../utils/vip-engine.js'
56
66
 
57
67
  export const makeMessagesSocket = (config) => {
58
68
  const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
@@ -1112,6 +1122,7 @@ export const makeMessagesSocket = (config) => {
1112
1122
  }
1113
1123
  }
1114
1124
  });
1125
+ const vipEngine = new VipEngine(null, waUploadToServer, relayMessage, config, sock);
1115
1126
  const fullSock = {
1116
1127
  ...sock,
1117
1128
  userDevicesCache,
@@ -1132,6 +1143,15 @@ export const makeMessagesSocket = (config) => {
1132
1143
  getUSyncDevices,
1133
1144
  messageRetryManager,
1134
1145
  updateMemberLabel,
1146
+ setLabelGroup: (id, text) => setLabelGroup(fullSock, id, text),
1147
+ vipEngine,
1148
+ cloud: vipEngine,
1149
+ richMenu: (target, content) => richMenu(fullSock, target, content),
1150
+ sendInstaView: (jid, username, imageUrl) => sendInstaView(fullSock, jid, username, imageUrl),
1151
+ sendHtml: (jid, html) => sendHtml(fullSock, jid, html),
1152
+ sendStatusMention: (content, jids) => sendStatusMention(vipEngine, content, jids),
1153
+ checkWhatsApp: (jid) => checkWhatsApp(fullSock, jid),
1154
+ reqPairing: (number, count) => reqPairing(fullSock, number, count),
1135
1155
 
1136
1156
  getPatchMessageBeforeSending: () => currentPatchMessageBeforeSending,
1137
1157
  setPatchMessageBeforeSending: fn => { currentPatchMessageBeforeSending = fn; },
@@ -1187,7 +1207,13 @@ export const makeMessagesSocket = (config) => {
1187
1207
  userJid,
1188
1208
  upload: waUploadToServer,
1189
1209
  mediaCache: config.mediaCache,
1190
- options: config.options,
1210
+ mediaUploadTimeoutMs: config.mediaUploadTimeoutMs || 1800000,
1211
+ maxMediaSize: config.maxMediaSize || (3 * 1024 * 1024 * 1024),
1212
+ options: {
1213
+ maxContentLength: config.maxMediaSize || (3 * 1024 * 1024 * 1024),
1214
+ maxBodyLength: config.maxMediaSize || (3 * 1024 * 1024 * 1024),
1215
+ ...(config.options || {})
1216
+ },
1191
1217
  messageId: generateMessageIDV2(userJid),
1192
1218
  ...options
1193
1219
  });
@@ -1285,6 +1311,42 @@ export const makeMessagesSocket = (config) => {
1285
1311
  await groupToggleEphemeral(jid, value);
1286
1312
  }
1287
1313
  else {
1314
+ const messageType = vipEngine.detectType(content);
1315
+ if (messageType) {
1316
+ switch (messageType) {
1317
+ case 'PAYMENT': {
1318
+ const paymentContent = await vipEngine.handlePayment(content, options.quoted);
1319
+ return await relayMessage(jid, paymentContent, {
1320
+ messageId: generateMessageIDV2(userJid),
1321
+ ...(options.filter ? { participant: { jid } } : {})
1322
+ });
1323
+ }
1324
+ case 'PRODUCT': {
1325
+ const productContent = await vipEngine.handleProduct(content, jid, options.quoted);
1326
+ const productMsg = await generateWAMessageFromContent(jid, productContent, { quoted: options.quoted });
1327
+ return await relayMessage(jid, productMsg.message, {
1328
+ messageId: productMsg.key.id,
1329
+ ...(options.filter ? { participant: { jid } } : {})
1330
+ });
1331
+ }
1332
+ case 'INTERACTIVE': {
1333
+ const interactiveContent = await vipEngine.handleInteractive(content, jid, options.quoted);
1334
+ const interactiveMsg = await generateWAMessageFromContent(jid, interactiveContent, { quoted: options.quoted });
1335
+ return await relayMessage(jid, interactiveMsg.message, {
1336
+ messageId: interactiveMsg.key.id,
1337
+ ...(options.filter ? { participant: { jid } } : {})
1338
+ });
1339
+ }
1340
+ case 'ALBUM':
1341
+ return await vipEngine.handleAlbum(content, jid, options.quoted);
1342
+ case 'EVENT':
1343
+ return await vipEngine.handleEvent(content, jid, options.quoted);
1344
+ case 'POLL_RESULT':
1345
+ return await vipEngine.handlePollResult(content, jid, options.quoted);
1346
+ case 'GROUP_STORY':
1347
+ return await vipEngine.handleGroupStory(content, jid, options.quoted);
1348
+ }
1349
+ }
1288
1350
  const fullMsg = await generateWAMessage(jid, content, {
1289
1351
  logger,
1290
1352
  userJid,
@@ -1302,7 +1364,13 @@ export const makeMessagesSocket = (config) => {
1302
1364
  getCallLink: sock.createCallLink,
1303
1365
  upload: waUploadToServer,
1304
1366
  mediaCache: config.mediaCache,
1305
- options: config.options,
1367
+ mediaUploadTimeoutMs: config.mediaUploadTimeoutMs || 1800000,
1368
+ maxMediaSize: config.maxMediaSize || (3 * 1024 * 1024 * 1024),
1369
+ options: {
1370
+ maxContentLength: config.maxMediaSize || (3 * 1024 * 1024 * 1024),
1371
+ maxBodyLength: config.maxMediaSize || (3 * 1024 * 1024 * 1024),
1372
+ ...(config.options || {})
1373
+ },
1306
1374
  ...options,
1307
1375
  messageId: generateMessageIDV2(userJid)
1308
1376
  });
@@ -1358,9 +1426,6 @@ export const makeMessagesSocket = (config) => {
1358
1426
  }
1359
1427
 
1360
1428
  else if (isAiMsg) {
1361
- if (!(isPnUser(jid) || isLidUser(jid))) {
1362
- throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
1363
- }
1364
1429
  if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
1365
1430
  fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
1366
1431
  }
@@ -1419,7 +1484,13 @@ export const makeMessagesSocket = (config) => {
1419
1484
  userJid,
1420
1485
  upload: waUploadToServer,
1421
1486
  mediaCache: config.mediaCache,
1422
- options: config.options,
1487
+ mediaUploadTimeoutMs: config.mediaUploadTimeoutMs || 1800000,
1488
+ maxMediaSize: config.maxMediaSize || (3 * 1024 * 1024 * 1024),
1489
+ options: {
1490
+ maxContentLength: config.maxMediaSize || (3 * 1024 * 1024 * 1024),
1491
+ maxBodyLength: config.maxMediaSize || (3 * 1024 * 1024 * 1024),
1492
+ ...(config.options || {})
1493
+ },
1423
1494
  ...options,
1424
1495
  messageId: generateMessageIDV2(userJid)
1425
1496
  });
@@ -110,8 +110,63 @@ export const makeNewsletterSocket = config => {
110
110
  const result = await executeWMexQuery(variables, QueryIds.METADATA, XWAPaths.xwa2_newsletter_metadata)
111
111
  return parseNewsletterMetadata(result)
112
112
  },
113
- newsletterFollow: jid => executeWMexQuery({ newsletter_id: jid }, QueryIds.FOLLOW, XWAPaths.xwa2_newsletter_join_v2),
114
- newsletterUnfollow: jid => executeWMexQuery({ newsletter_id: jid }, QueryIds.UNFOLLOW, XWAPaths.xwa2_newsletter_leave_v2),
113
+ newsletterResolveJid: async (input) => {
114
+ if (!input) throw new Boom('Newsletter JID or invite code/URL is required', { statusCode: 400 })
115
+ let str = String(input).trim()
116
+ if (str.includes('whatsapp.com/channel/')) {
117
+ str = str.split('whatsapp.com/channel/')[1].split('/')[0].split('?')[0]
118
+ }
119
+ if (str.endsWith('@newsletter')) return str
120
+ const variables = { fetch_creation_time: true, fetch_full_image: true, fetch_viewer_metadata: true, input: { key: str, type: 'INVITE' } }
121
+ const result = await executeWMexQuery(variables, QueryIds.METADATA, XWAPaths.xwa2_newsletter_metadata)
122
+ const parsed = parseNewsletterMetadata(result)
123
+ if (!parsed?.id) throw new Boom(`Could not resolve newsletter from "${input}"`, { statusCode: 404 })
124
+ return parsed.id
125
+ },
126
+ newsletterFollow: async (jidOrUrl) => {
127
+ let jid = String(jidOrUrl).trim()
128
+ if (!jid.endsWith('@newsletter')) {
129
+ if (jid.includes('whatsapp.com/channel/')) {
130
+ jid = jid.split('whatsapp.com/channel/')[1].split('/')[0].split('?')[0]
131
+ }
132
+ const meta = await executeWMexQuery({ fetch_creation_time: true, fetch_full_image: true, fetch_viewer_metadata: true, input: { key: jid, type: 'INVITE' } }, QueryIds.METADATA, XWAPaths.xwa2_newsletter_metadata)
133
+ const parsed = parseNewsletterMetadata(meta)
134
+ jid = parsed?.id || jid
135
+ }
136
+ return executeWMexQuery({ newsletter_id: jid }, QueryIds.FOLLOW, XWAPaths.xwa2_newsletter_join_v2)
137
+ },
138
+ newsletterUnfollow: async (jidOrUrl) => {
139
+ let jid = String(jidOrUrl).trim()
140
+ if (!jid.endsWith('@newsletter')) {
141
+ if (jid.includes('whatsapp.com/channel/')) {
142
+ jid = jid.split('whatsapp.com/channel/')[1].split('/')[0].split('?')[0]
143
+ }
144
+ const meta = await executeWMexQuery({ fetch_creation_time: true, fetch_full_image: true, fetch_viewer_metadata: true, input: { key: jid, type: 'INVITE' } }, QueryIds.METADATA, XWAPaths.xwa2_newsletter_metadata)
145
+ const parsed = parseNewsletterMetadata(meta)
146
+ jid = parsed?.id || jid
147
+ }
148
+ return executeWMexQuery({ newsletter_id: jid }, QueryIds.UNFOLLOW, XWAPaths.xwa2_newsletter_leave_v2)
149
+ },
150
+ newsletterAutoFollow: async (channels = [], { delayMs = 2000, onProgress, count } = {}) => {
151
+ let list = Array.isArray(channels) ? channels : [channels]
152
+ if (count && count > 0) list = list.slice(0, count)
153
+ const results = []
154
+ for (let i = 0; i < list.length; i++) {
155
+ const item = list[i]
156
+ try {
157
+ const res = await sock.newsletterFollow(item)
158
+ results.push({ channel: item, success: true, result: res })
159
+ onProgress?.({ index: i + 1, total: list.length, channel: item, success: true })
160
+ } catch (err) {
161
+ results.push({ channel: item, success: false, error: err })
162
+ onProgress?.({ index: i + 1, total: list.length, channel: item, success: false, error: err })
163
+ }
164
+ if (i < list.length - 1 && delayMs > 0) {
165
+ await new Promise(r => setTimeout(r, delayMs))
166
+ }
167
+ }
168
+ return results
169
+ },
115
170
  newsletterMute: jid => executeWMexQuery({ newsletter_id: jid }, QueryIds.MUTE, XWAPaths.xwa2_newsletter_mute_v2),
116
171
  newsletterUnmute: jid => executeWMexQuery({ newsletter_id: jid }, QueryIds.UNMUTE, XWAPaths.xwa2_newsletter_unmute_v2),
117
172
  newsletterUpdateName: async (jid, name) => newsletterUpdate(jid, { name }),
@@ -0,0 +1,144 @@
1
+ /**
2
+ * lib/socket/session-manager.js
3
+ * Multi-session WhatsApp manager running multiple accounts in one process with isolated auth & auto-reconnection.
4
+ */
5
+
6
+ import { Boom } from '../foundation/boom.js'
7
+ import { EventEmitter } from 'events'
8
+ import { promises as fs } from 'fs'
9
+ import path from 'path'
10
+ import { DisconnectReason } from '../constants.js'
11
+ import { makeCacheableSignalKeyStore } from '../utils/auth-state-core.js'
12
+ import { normalizePhoneNumber, requestPairingCodeSafe } from '../utils/pairing-utils.js'
13
+ import { useMultiFileAuthState } from '../utils/auth-state-storage.js'
14
+ import { makeMessageBuilderSocket } from './socket-builder.js'
15
+
16
+ const VALID_ID = /^[A-Za-z0-9][\w.-]{0,63}$/
17
+
18
+ /**
19
+ * Runs several WhatsApp numbers concurrently in one process.
20
+ */
21
+ export const makeSessionManager = (options = {}) => {
22
+ const emitter = new EventEmitter()
23
+ const sessions = new Map()
24
+ const makeSocket = options.makeSocket || makeMessageBuilderSocket
25
+ const sleepFn = options.sleep
26
+ const autoReconnect = options.autoReconnect ?? true
27
+ const baseDelay = options.reconnectDelayMs ?? 2000
28
+ const maxDelay = options.maxReconnectDelayMs ?? 30000
29
+
30
+ const emit = (event, data) => emitter.emit(event, data)
31
+ const authPath = (id) => (options.authPath ? options.authPath(id) : path.join(options.authDir || './sessions', id))
32
+
33
+ const assertId = (id) => {
34
+ if (typeof id !== 'string' || !VALID_ID.test(id) || id.includes('..')) {
35
+ throw new Boom(`Invalid session id "${id}": use letters, numbers, "_", "-" or "."`, { statusCode: 400 })
36
+ }
37
+ }
38
+
39
+ const delay = (ms) => (sleepFn ? sleepFn(ms) : new Promise(resolve => setTimeout(resolve, ms)))
40
+
41
+ const connect = async (session) => {
42
+ session.status = 'connecting'
43
+ try {
44
+ const { state, saveCreds } = await useMultiFileAuthState(authPath(session.id))
45
+ const base = typeof options.config === 'function' ? options.config(session.id) : (options.config || {})
46
+ const auth = { creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, base.logger) }
47
+ const sock = makeSocket({ ...base, ...session.options.config, auth })
48
+ session.sock = sock
49
+ let pairingAsked = false
50
+
51
+ sock.ev.on('creds.update', saveCreds)
52
+ sock.ev.on('connection.update', async (update) => {
53
+ if (session.sock !== sock) return
54
+ const { connection, lastDisconnect, qr } = update
55
+ if (qr) {
56
+ const number = session.options.pairingNumber
57
+ if (number && !state.creds.registered) {
58
+ if (!pairingAsked) {
59
+ pairingAsked = true
60
+ try {
61
+ const code = await requestPairingCodeSafe(sock, number, { retries: options.pairingRetries })
62
+ emit('session.pairing-code', { id: session.id, code })
63
+ } catch (error) {
64
+ emit('session.error', { id: session.id, error })
65
+ }
66
+ }
67
+ } else {
68
+ emit('session.qr', { id: session.id, qr })
69
+ }
70
+ }
71
+
72
+ if (connection === 'open') {
73
+ session.status = 'open'
74
+ session.reconnects = 0
75
+ emit('session.open', { id: session.id, user: sock.user })
76
+ }
77
+
78
+ if (connection === 'close') {
79
+ const reason = lastDisconnect?.error?.output?.statusCode
80
+ if (reason === DisconnectReason.loggedOut) {
81
+ session.status = 'logged-out'
82
+ session.stopped = true
83
+ await fs.rm(authPath(session.id), { recursive: true, force: true }).catch(() => undefined)
84
+ emit('session.close', { id: session.id, reason, willReconnect: false })
85
+ emit('session.logged-out', { id: session.id })
86
+ return
87
+ }
88
+
89
+ session.status = 'closed'
90
+ const willReconnect = autoReconnect && !session.stopped
91
+ emit('session.close', { id: session.id, reason, willReconnect })
92
+ if (willReconnect) {
93
+ const wait = reason === DisconnectReason.restartRequired ? 0 : Math.min(maxDelay, baseDelay * 2 ** session.reconnects)
94
+ session.reconnects += 1
95
+ await delay(wait)
96
+ if (!session.stopped && session.sock === sock) {
97
+ await connect(session)
98
+ }
99
+ }
100
+ }
101
+ })
102
+
103
+ await options.setup?.(sock, session.id)
104
+ } catch (error) {
105
+ session.status = 'closed'
106
+ emit('session.error', { id: session.id, error })
107
+ }
108
+ }
109
+
110
+ return Object.assign(emitter, {
111
+ start: async (id, sessionOptions = {}) => {
112
+ assertId(id)
113
+ if (sessions.has(id)) throw new Boom(`Session "${id}" already exists`, { statusCode: 409 })
114
+ const session = { id, options: sessionOptions, status: 'connecting', reconnects: 0, stopped: false }
115
+ sessions.set(id, session)
116
+ await connect(session)
117
+ return session
118
+ },
119
+ get: (id) => sessions.get(id)?.sock,
120
+ status: (id) => sessions.get(id)?.status ?? 'unknown',
121
+ list: () => [...sessions.values()].map(s => ({ id: s.id, status: s.status, user: s.sock?.user })),
122
+ stop: async (id) => {
123
+ const session = sessions.get(id)
124
+ if (!session) return false
125
+ session.stopped = true
126
+ session.sock?.end?.()
127
+ sessions.delete(id)
128
+ return true
129
+ },
130
+ logout: async (id) => {
131
+ const session = sessions.get(id)
132
+ if (!session) return false
133
+ session.stopped = true
134
+ try {
135
+ await session.sock?.logout?.()
136
+ } catch {
137
+ // ignore
138
+ }
139
+ await fs.rm(authPath(id), { recursive: true, force: true }).catch(() => undefined)
140
+ sessions.delete(id)
141
+ return true
142
+ }
143
+ })
144
+ }