@aldy11/baileys 2.0.1 → 2.0.2

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.
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": [2, 3000, 1043857760]
2
+ "version": [2, 3000, 1056491763]
3
3
  }
@@ -8,7 +8,7 @@ const WAProto_1 = require("../../WAProto");
8
8
  const libsignal_1 = require("../Signal/libsignal");
9
9
  const browser_utils_1 = require("../Utils/browser-utils");
10
10
  const logger_1 = __importDefault(require("../Utils/logger"));
11
- exports.version = [2, 3000, 1043857760];
11
+ exports.version = [2, 3000, 1056491763];
12
12
  exports.UNAUTHORIZED_CODES = [401, 403, 419];
13
13
  exports.DEFAULT_ORIGIN = 'https://web.whatsapp.com';
14
14
  exports.CALL_VIDEO_PREFIX = 'https://call.whatsapp.com/video/';
@@ -40,6 +40,29 @@ const makeSocket = (config) => {
40
40
  routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
41
41
  });
42
42
  const { creds } = authState;
43
+ const hasLinkedDeviceCreds = (c) => {
44
+ if (!(c && c.me && c.me.id)) {
45
+ return false;
46
+ }
47
+ if (c.account) {
48
+ return true;
49
+ }
50
+ const decoded = (0, WABinary_1.jidDecode)(c.me.id);
51
+ return Boolean(c.registered && decoded && typeof decoded.device === 'number' && decoded.device > 0);
52
+ };
53
+ let handshakeReady = false;
54
+ let resolveHandshake;
55
+ let rejectHandshake;
56
+ const handshakePromise = new Promise((resolve, reject) => {
57
+ resolveHandshake = resolve;
58
+ rejectHandshake = reject;
59
+ });
60
+ handshakePromise.catch(() => { });
61
+ let pairDeviceReady = false;
62
+ let resolvePairDevice;
63
+ const pairDevicePromise = new Promise((resolve) => {
64
+ resolvePairDevice = resolve;
65
+ });
43
66
  // add transaction capability
44
67
  const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
45
68
  const signalRepository = makeSignalRepository({ creds, keys });
@@ -132,7 +155,7 @@ const makeSocket = (config) => {
132
155
  };
133
156
  ws.on(`TAG:${msgId}`, onRecv);
134
157
  ws.on('close', onErr); // if the socket closes, you'll never receive the message
135
- ws.off('error', onErr);
158
+ ws.on('error', onErr);
136
159
  });
137
160
  return result;
138
161
  }
@@ -170,7 +193,7 @@ const makeSocket = (config) => {
170
193
  logger.trace({ handshake }, 'handshake recv from WA');
171
194
  const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
172
195
  let node;
173
- if (!creds.me) {
196
+ if (!hasLinkedDeviceCreds(creds)) {
174
197
  node = (0, Utils_1.generateRegistrationNode)(creds, config);
175
198
  logger.info({ node }, 'not logged in, attempting registration...');
176
199
  }
@@ -186,6 +209,8 @@ const makeSocket = (config) => {
186
209
  },
187
210
  }).finish());
188
211
  noise.finishInit();
212
+ handshakeReady = true;
213
+ resolveHandshake();
189
214
  startKeepAliveRequest();
190
215
  };
191
216
  const getAvailablePreKeysOnServer = async () => {
@@ -259,6 +284,13 @@ const makeSocket = (config) => {
259
284
  return;
260
285
  }
261
286
  closed = true;
287
+ if (!handshakeReady) {
288
+ rejectHandshake(error || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
289
+ }
290
+ if (!pairDeviceReady) {
291
+ pairDeviceReady = true;
292
+ resolvePairDevice();
293
+ }
262
294
  logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
263
295
  clearInterval(keepAliveReq);
264
296
  clearTimeout(qrTimer);
@@ -374,64 +406,99 @@ const makeSocket = (config) => {
374
406
  end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
375
407
  };
376
408
  const requestPairingCode = async (phoneNumber, pairKey = "") => {
377
- if (pairKey && pairKey.trim()) {
378
- authState.creds.pairingCode = pairKey.trim().toUpperCase();
379
- }
380
- else {
381
- authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
409
+ if (hasLinkedDeviceCreds(authState.creds)) {
410
+ throw new boom_1.Boom('Session is already authenticated; cannot request pairing code', { statusCode: 400 });
411
+ }
412
+ const sanitizedPhone = String(phoneNumber || '').replace(/[^0-9]/g, '');
413
+ if (!sanitizedPhone || sanitizedPhone.length < 7) {
414
+ throw new boom_1.Boom('Invalid phone number for pairing code (must contain digits with country code, e.g. 628123456789)', { statusCode: 400 });
415
+ }
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 });
421
+ }
422
+ await waitForSocketOpen();
423
+ if (!handshakeReady) {
424
+ await (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
425
+ handshakePromise.then(resolve, reject);
426
+ });
382
427
  }
428
+ if (!pairDeviceReady && !closed) {
429
+ await Promise.race([
430
+ pairDevicePromise,
431
+ (0, Utils_1.delay)(1500)
432
+ ]);
433
+ }
434
+ if (closed || !ws.isOpen) {
435
+ throw new boom_1.Boom('Connection Closed before pairing code request', { statusCode: Types_1.DisconnectReason.connectionClosed });
436
+ }
437
+ const prevPairingCode = authState.creds.pairingCode;
438
+ const prevMe = authState.creds.me;
439
+ const pairingCode = cleanedPairKey || (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
440
+ const pairingPlatform = (0, Utils_1.resolvePairingBrowser)(browser);
441
+ authState.creds.pairingCode = pairingCode;
442
+ authState.creds.registered = false;
383
443
  authState.creds.me = {
384
- id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
444
+ id: (0, WABinary_1.jidEncode)(sanitizedPhone, 's.whatsapp.net'),
385
445
  name: '~'
386
446
  };
387
- ev.emit('creds.update', authState.creds);
388
- await sendNode({
389
- tag: 'iq',
390
- attrs: {
391
- to: WABinary_1.S_WHATSAPP_NET,
392
- type: 'set',
393
- id: generateMessageTag(),
394
- xmlns: 'md'
395
- },
396
- content: [
397
- {
398
- tag: 'link_code_companion_reg',
399
- attrs: {
400
- jid: authState.creds.me.id,
401
- stage: 'companion_hello',
402
- // eslint-disable-next-line camelcase
403
- should_show_push_notification: 'true'
404
- },
405
- content: [
406
- {
407
- tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
408
- attrs: {},
409
- content: await generatePairingKey()
410
- },
411
- {
412
- tag: 'companion_server_auth_key_pub',
413
- attrs: {},
414
- content: authState.creds.noiseKey.public
415
- },
416
- {
417
- tag: 'companion_platform_id',
418
- attrs: {},
419
- content: (0, Utils_1.getPlatformId)(browser[1])
420
- },
421
- {
422
- tag: 'companion_platform_display',
423
- attrs: {},
424
- content: `${browser[1]} (${browser[0]})`
447
+ try {
448
+ await query({
449
+ tag: 'iq',
450
+ attrs: {
451
+ to: WABinary_1.S_WHATSAPP_NET,
452
+ type: 'set',
453
+ id: generateMessageTag(),
454
+ xmlns: 'md'
455
+ },
456
+ content: [
457
+ {
458
+ tag: 'link_code_companion_reg',
459
+ attrs: {
460
+ jid: authState.creds.me.id,
461
+ stage: 'companion_hello',
462
+ // eslint-disable-next-line camelcase
463
+ should_show_push_notification: 'true'
425
464
  },
426
- {
427
- tag: 'link_code_pairing_nonce',
428
- attrs: {},
429
- content: '0'
430
- }
431
- ]
432
- }
433
- ]
434
- });
465
+ content: [
466
+ {
467
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
468
+ attrs: {},
469
+ content: await generatePairingKey()
470
+ },
471
+ {
472
+ tag: 'companion_server_auth_key_pub',
473
+ attrs: {},
474
+ content: authState.creds.noiseKey.public
475
+ },
476
+ {
477
+ tag: 'companion_platform_id',
478
+ attrs: {},
479
+ content: pairingPlatform.platformId
480
+ },
481
+ {
482
+ tag: 'companion_platform_display',
483
+ attrs: {},
484
+ content: pairingPlatform.platformDisplay
485
+ },
486
+ {
487
+ tag: 'link_code_pairing_nonce',
488
+ attrs: {},
489
+ content: '0'
490
+ }
491
+ ]
492
+ }
493
+ ]
494
+ }, 20000);
495
+ }
496
+ catch (err) {
497
+ authState.creds.pairingCode = prevPairingCode;
498
+ authState.creds.me = prevMe;
499
+ throw err;
500
+ }
501
+ ev.emit('creds.update', authState.creds);
435
502
  return authState.creds.pairingCode;
436
503
  };
437
504
  async function generatePairingKey() {
@@ -483,6 +550,10 @@ const makeSocket = (config) => {
483
550
  }
484
551
  };
485
552
  await sendNode(iq);
553
+ if (!pairDeviceReady) {
554
+ pairDeviceReady = true;
555
+ resolvePairDevice();
556
+ }
486
557
  const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
487
558
  const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
488
559
  const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
@@ -529,7 +600,7 @@ const makeSocket = (config) => {
529
600
  await sendPassiveIq('active');
530
601
  logger.info('opened connection to WA');
531
602
  clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
532
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
603
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid }, registered: true });
533
604
  ev.emit('connection.update', { connection: 'open' });
534
605
  }
535
606
  catch (err) {
@@ -568,8 +639,7 @@ const makeSocket = (config) => {
568
639
  });
569
640
  let didStartBuffer = false;
570
641
  process.nextTick(() => {
571
- var _a;
572
- if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
642
+ if (hasLinkedDeviceCreds(creds)) {
573
643
  // start buffering important events
574
644
  // if we're logged in
575
645
  ev.buffer();
@@ -593,7 +663,7 @@ const makeSocket = (config) => {
593
663
  var _a, _b;
594
664
  const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
595
665
  // if name has just been received
596
- if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
666
+ if (name && ((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name && hasLinkedDeviceCreds(creds)) {
597
667
  logger.debug({ name }, 'updated pushName');
598
668
  sendNode({
599
669
  tag: 'presence',
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPlatformId = exports.Browsers = void 0;
3
+ exports.resolvePairingBrowser = exports.getPlatformId = exports.Browsers = void 0;
4
4
 
5
5
  const os = require("os");
6
6
  const { proto } = require("../../WAProto/index.js");
@@ -19,6 +19,14 @@ const PLATFORM_MAP = {
19
19
  'netbsd': undefined
20
20
  };
21
21
 
22
+ const VALID_PAIRING_BROWSERS = {
23
+ CHROME: 'Chrome',
24
+ FIREFOX: 'Firefox',
25
+ SAFARI: 'Safari',
26
+ EDGE: 'Edge',
27
+ OPERA: 'Opera',
28
+ };
29
+
22
30
  const Browsers = (browser = 'Chrome') => {
23
31
  const osName = PLATFORM_MAP[os.platform()] || 'Ubuntu';
24
32
  const osRelease = os.release();
@@ -33,8 +41,27 @@ Browsers.appropriate = (browser = 'Chrome') => [PLATFORM_MAP[os.platform()] || '
33
41
  exports.Browsers = Browsers;
34
42
 
35
43
  const getPlatformId = (browser) => {
36
- const platformType = proto.DeviceProps.PlatformType[browser.toUpperCase()];
44
+ const platformType = proto.DeviceProps.PlatformType[String(browser || '').toUpperCase()];
37
45
  return platformType ? platformType.toString() : '1'; // Default Chrome
38
46
  };
39
47
 
40
- exports.getPlatformId = getPlatformId;
48
+ exports.getPlatformId = getPlatformId;
49
+
50
+ /**
51
+ * Resolves a safe Web Browser identity for WhatsApp Link-with-Phone-Number pairing.
52
+ * WhatsApp pairing rejects non-browser platforms such as "Desktop" (PlatformType 7).
53
+ */
54
+ const resolvePairingBrowser = (browserTuple) => {
55
+ const rawOs = Array.isArray(browserTuple) && browserTuple[0] ? String(browserTuple[0]).trim() : 'Ubuntu';
56
+ const rawBrowser = Array.isArray(browserTuple) && browserTuple[1] ? String(browserTuple[1]).trim() : 'Chrome';
57
+ const canonicalBrowser = VALID_PAIRING_BROWSERS[rawBrowser.toUpperCase()] || 'Chrome';
58
+ const canonicalOs = rawOs && rawOs.toLowerCase() !== 'baileys' ? rawOs : 'Ubuntu';
59
+ return {
60
+ osName: canonicalOs,
61
+ browserName: canonicalBrowser,
62
+ platformId: getPlatformId(canonicalBrowser),
63
+ platformDisplay: `${canonicalBrowser} (${canonicalOs})`,
64
+ };
65
+ };
66
+
67
+ exports.resolvePairingBrowser = resolvePairingBrowser;
@@ -76,9 +76,13 @@ const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentity
76
76
  .update(config.version.join('.'))
77
77
  .digest();
78
78
 
79
+ const effectiveBrowserPlatform = (!config.syncFullHistory && String(config.browser[1] || '').toUpperCase() === 'DESKTOP')
80
+ ? 'Chrome'
81
+ : config.browser[1];
82
+
79
83
  const companion = {
80
84
  os: config.browser[0],
81
- platformType: getPlatformType(config.browser[1]),
85
+ platformType: getPlatformType(effectiveBrowserPlatform),
82
86
  requireFullSync: config.syncFullHistory,
83
87
  historySyncConfig: {
84
88
  storageQuotaMb: 10240,
@@ -207,7 +211,8 @@ const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, s
207
211
  ...(signalIdentities || []),
208
212
  identity
209
213
  ],
210
- platform: platformNode?.attrs.name
214
+ platform: platformNode?.attrs.name,
215
+ registered: true
211
216
  };
212
217
 
213
218
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aldy11/baileys",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "WhatsApp Multi-Device API Library with Native Flow Buttons, Meta AI Primitives, and Session Protection",
5
5
  "author": "aldy11",
6
6
  "main": "lib/index.js",