whalibmob 5.40.37 → 5.40.39

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.
Files changed (53) hide show
  1. package/README.md +1 -0
  2. package/cli.js +5 -4
  3. package/docs/events-history.md +47 -0
  4. package/index.d.ts +21 -0
  5. package/index.js +6 -0
  6. package/lib/AndroidApk.js +13 -12
  7. package/lib/BinaryNode.js +2 -1
  8. package/lib/Client.js +273 -269
  9. package/lib/CompanionPairing.js +3 -1
  10. package/lib/DeviceConfig.js +10 -0
  11. package/lib/DeviceManager.js +2 -1
  12. package/lib/HistorySyncHandler.js +13 -11
  13. package/lib/MediaService.js +14 -12
  14. package/lib/OfflineNodeProcessor.js +3 -1
  15. package/lib/PairingCode.js +2 -1
  16. package/lib/PasskeyPairing.js +18 -17
  17. package/lib/PlayStore.js +15 -13
  18. package/lib/PrimaryLinkCrypto.js +2 -1
  19. package/lib/Registration.js +76 -38
  20. package/lib/Store.js +6 -5
  21. package/lib/WebSocketStream.js +3 -2
  22. package/lib/WebVersion.js +5 -3
  23. package/lib/apns-courier.js +15 -13
  24. package/lib/apns.js +6 -4
  25. package/lib/argo/ArgoDecoder.js +16 -14
  26. package/lib/auth-utils.js +10 -9
  27. package/lib/cli/linkCommands.js +5 -2
  28. package/lib/constants.js +20 -15
  29. package/lib/curve.js +5 -4
  30. package/lib/errors.js +42 -0
  31. package/lib/fcm.js +7 -5
  32. package/lib/image/JpegEncoder.js +4 -2
  33. package/lib/messages/MediaRetry.js +3 -2
  34. package/lib/messages/MessageSecret.js +9 -8
  35. package/lib/messages/MessageSender.js +30 -28
  36. package/lib/noise.js +13 -11
  37. package/lib/plist.js +18 -15
  38. package/lib/primary/HistoryExport.js +2 -1
  39. package/lib/primary/MessageStore.js +8 -2
  40. package/lib/proto/MessageProto.js +3 -1
  41. package/lib/signal/SenderKey.js +5 -4
  42. package/lib/signal/WaSignalGroup/group-session-builder.js +2 -1
  43. package/lib/signal/WaSignalGroup/group_cipher.js +10 -9
  44. package/lib/signal/WaSignalGroup/sender-key-distribution-message.js +2 -1
  45. package/lib/signal/WaSignalGroup/sender-key-message.js +2 -1
  46. package/lib/socks.js +9 -8
  47. package/lib/store/Backend.js +3 -1
  48. package/lib/store/FileBackend.js +2 -1
  49. package/lib/store/MemoryBackend.js +2 -1
  50. package/lib/store/SqliteBackend.js +6 -5
  51. package/lib/store/migrate.js +2 -1
  52. package/llms.txt +1 -0
  53. package/package.json +2 -1
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
  //registration tool//
3
+ const { Boom } = require('@hapi/boom');
4
+ const { statusFrom } = require('./errors');
3
5
  const crypto = require('crypto');
4
6
  const https = require('https');
5
7
  const tls = require('tls');
@@ -116,7 +118,7 @@ async function httpPostViaSocks(path, body, waVersion, proxyUrl, authHeader, dev
116
118
  const { status, headers: resHeaders, body: bodyBuf } = await readHttpResponse(tlsSocket, path);
117
119
  const bodyStr = decodeBody(bodyBuf, resHeaders).toString('utf8');
118
120
 
119
- if (status !== 200) throw new Error(`HTTP ${status} ${path}: ${bodyStr}`);
121
+ if (status !== 200) throw new Boom(`HTTP ${status} ${path}: ${bodyStr}`, { statusCode: statusFrom(status) });
120
122
  try { return JSON.parse(bodyStr); } catch (_) { return { raw: bodyStr }; }
121
123
  }
122
124
 
@@ -141,7 +143,7 @@ function readHttpResponse(socket, label, timeoutMs) {
141
143
  let done = false;
142
144
 
143
145
  const timer = setTimeout(() => {
144
- settle(reject, new Error('SOCKS proxy timed out reading ' + label));
146
+ settle(reject, new Boom('SOCKS proxy timed out reading ' + label, { statusCode: 408 }));
145
147
  }, timeoutMs || 30000);
146
148
 
147
149
  function settle(fn, arg) {
@@ -159,7 +161,7 @@ function readHttpResponse(socket, label, timeoutMs) {
159
161
  function onData(chunk) {
160
162
  raw = raw.length ? Buffer.concat([raw, chunk]) : chunk;
161
163
  if (raw.length > MAX_RESPONSE_BYTES) {
162
- return settle(reject, new Error('response too large reading ' + label));
164
+ return settle(reject, new Boom('response too large reading ' + label, { statusCode: 413 }));
163
165
  }
164
166
  const parsed = parseHttpResponse(raw, false);
165
167
  if (parsed) settle(resolve, parsed);
@@ -170,7 +172,7 @@ function readHttpResponse(socket, label, timeoutMs) {
170
172
  function onEnd() {
171
173
  const parsed = parseHttpResponse(raw, true);
172
174
  if (parsed) return settle(resolve, parsed);
173
- settle(reject, new Error('connection closed mid-response reading ' + label));
175
+ settle(reject, new Boom('connection closed mid-response reading ' + label, { statusCode: 502 }));
174
176
  }
175
177
 
176
178
  function onError(err) { settle(reject, err); }
@@ -901,7 +903,7 @@ async function refreshSessionVersion(sessionFile, opts) {
901
903
  const { loadStore, saveStore } = require('./Store');
902
904
 
903
905
  const store = loadStore(sessionFile);
904
- if (!store) throw new Error('no session at ' + sessionFile);
906
+ if (!store) throw new Boom('no session at ' + sessionFile, { statusCode: 404 });
905
907
 
906
908
  const device = store.device || getDeviceConfig();
907
909
  const before = store.version;
@@ -1137,9 +1139,9 @@ async function ensureAndroidMaterial(opts, device) {
1137
1139
  try {
1138
1140
  apk = await PlayStore.downloadApk({ packageName, onProgress: m => say(' ' + m) });
1139
1141
  } catch (err) {
1140
- throw new Error('could not fetch the WhatsApp APK automatically: ' + err.message +
1142
+ throw new Boom('could not fetch the WhatsApp APK automatically: ' + err.message +
1141
1143
  '\nRead it out of an APK you have instead:\n' +
1142
- ' wa apk-material <base.apk> [split.apk ...]');
1144
+ ' wa apk-material <base.apk> [split.apk ...]', { statusCode: 502 });
1143
1145
  }
1144
1146
 
1145
1147
  const material = AndroidApk.extractMaterial(apk.base, apk.splits);
@@ -1165,12 +1167,12 @@ function loadAndroidMaterial(device) {
1165
1167
  try {
1166
1168
  raw = fs.readFileSync(file, 'utf8');
1167
1169
  } catch (_) {
1168
- const err = new Error('registering as Android needs the token material from a WhatsApp APK, ' +
1170
+ const err = new Boom('registering as Android needs the token material from a WhatsApp APK, ' +
1169
1171
  'and there is none at ' + file + '. Fetch it with:\n' +
1170
1172
  ' wa apk-material --download' + (variant === 'business' ? ' --business' : '') + '\n' +
1171
1173
  'or read it out of an APK you already have:\n' +
1172
1174
  ' wa apk-material <base.apk> [split.apk ...]\n' +
1173
- 'Registering as iOS needs none of this.');
1175
+ 'Registering as iOS needs none of this.', { statusCode: 404 });
1174
1176
  // Told apart from a refused repack, which must never be answered by
1175
1177
  // downloading over it.
1176
1178
  err.code = 'NO_APK_MATERIAL';
@@ -1191,12 +1193,12 @@ function loadAndroidMaterial(device) {
1191
1193
  const signer = AndroidApk.describeCertificate(material.certificates[0]);
1192
1194
  if (signer && !AndroidApk.looksLikeWhatsAppCertificate(signer) &&
1193
1195
  process.env.WA_ALLOW_FOREIGN_APK !== '1') {
1194
- throw new Error('the APK this token material came from was not signed by WhatsApp — ' +
1196
+ throw new Boom('the APK this token material came from was not signed by WhatsApp — ' +
1195
1197
  'it is signed by "' + signer.subject.replace(/\n/g, ', ') + '". Re-signing replaces ' +
1196
1198
  'the certificate the token is built from, so every attempt would come back as ' +
1197
1199
  'bad_token. Take the APK from a phone that has WhatsApp installed:\n' +
1198
1200
  ' pm path ' + (variant === 'business' ? WHATSAPP_BUSINESS_PACKAGE : WHATSAPP_PACKAGE) + '\n' +
1199
- 'then re-run wa apk-material with it. Set WA_ALLOW_FOREIGN_APK=1 to send it anyway.');
1201
+ 'then re-run wa apk-material with it. Set WA_ALLOW_FOREIGN_APK=1 to send it anyway.', { statusCode: 400 });
1200
1202
  }
1201
1203
 
1202
1204
  _androidMaterial[variant] = material;
@@ -1244,9 +1246,10 @@ function toUrlHex(buf) {
1244
1246
 
1245
1247
  // The native client inserts registration fields into a LinkedHashMap in a
1246
1248
  // fixed order; the wire sequence is that insertion order, not a sort. These are
1247
- // the live orders captured from WhatsApp Android reverse engerring: 50 fields
1249
+ // the live orders captured from WhatsApp Android reverse engerring: 51 fields
1248
1250
  // for /v2/code, 49 for /v2/register. gpia/token/vname that this build omits
1249
- // simply drop out — their slots collapse.
1251
+ // simply drop out — their slots collapse. first_api_level rides between
1252
+ // e_skey_id and feo2_query_status, the slot the native client gives it.
1250
1253
  const CODE_PARAM_ORDER = [
1251
1254
  'method', 'backup_token', '_gs', 'sim_mnc', 'id', 'mnc', '_gg',
1252
1255
  'network_radio_type', 'lg', 'rc', 'pid', '_ge', 'cellular_strength', 'gpia',
@@ -1255,7 +1258,8 @@ const CODE_PARAM_ORDER = [
1255
1258
  'mistyped', 'airplane_mode_type', 'e_ident', 'e_skey_sig', 'entrypoint',
1256
1259
  'token', 'in', 'expid', 'simnum', 'cc', 'education_screen_displayed',
1257
1260
  'e_skey_val', 'authkey', 'e_keytype', 'e_regid', 'client_metrics', '_gi',
1258
- 'e_skey_id', 'feo2_query_status', 'reason', 'fdid', 'recaptcha', '_ga', 'lc'
1261
+ 'e_skey_id', 'first_api_level', 'feo2_query_status', 'reason', 'fdid',
1262
+ 'recaptcha', '_ga', 'lc'
1259
1263
  ];
1260
1264
 
1261
1265
  const REGISTER_PARAM_ORDER = [
@@ -1388,6 +1392,39 @@ function deviceRam(device) {
1388
1392
  return Number.isFinite(n) && n > 0 ? n.toFixed(2) : DEFAULT_DEVICE_RAM;
1389
1393
  }
1390
1394
 
1395
+ // ---------- first_api_level ----------
1396
+ //
1397
+ // ro.product.first_api_level: the Android SDK the handset shipped with, which
1398
+ // registration sends as first_api_level. It is a property of the model, not of
1399
+ // the installed OS — a phone that launched on Android 13 and was updated to 14
1400
+ // still reports 33 — so it is taken from the declared profile's firstApiLevel.
1401
+ //
1402
+ // When the profile does not pin one (a custom WA_DEVICE_* build), it is derived
1403
+ // from osVersion: a phone is assumed to have shipped on the OS it now runs,
1404
+ // which is true for anything bought on its launch version. The last resort is
1405
+ // 34 (Android 14), the floor the default profiles sit on.
1406
+ const ANDROID_VERSION_TO_API = {
1407
+ '10': 29, '11': 30, '12': 31, '13': 33, '14': 34, '15': 35, '16': 36
1408
+ };
1409
+ const DEFAULT_FIRST_API_LEVEL = 34;
1410
+
1411
+ function firstApiLevel(device) {
1412
+ const pinned = device && device.firstApiLevel;
1413
+ if (pinned != null && String(pinned).trim() !== '') {
1414
+ const n = parseInt(pinned, 10);
1415
+ if (Number.isFinite(n) && n > 0) return String(n);
1416
+ }
1417
+ const osVersion = device && device.osVersion;
1418
+ if (osVersion != null) {
1419
+ // Match on the major version so '14', '14.1' and '13.0' all resolve.
1420
+ const major = String(osVersion).trim().split('.')[0];
1421
+ if (ANDROID_VERSION_TO_API[major] != null) {
1422
+ return String(ANDROID_VERSION_TO_API[major]);
1423
+ }
1424
+ }
1425
+ return String(DEFAULT_FIRST_API_LEVEL);
1426
+ }
1427
+
1391
1428
  // ---------- pid ----------
1392
1429
  //
1393
1430
  // The process id of the app making the request.
@@ -1533,6 +1570,7 @@ function getRequestVerificationCodeParameters(store, method, meta, device, attem
1533
1570
  'hasinrc', '1',
1534
1571
  'roaming_type', '0',
1535
1572
  'device_ram', deviceRam(device),
1573
+ 'first_api_level', firstApiLevel(device),
1536
1574
  'education_screen_displayed', 'false',
1537
1575
  'pid', getAppPid(store),
1538
1576
  'cellular_strength', '5',
@@ -1798,14 +1836,14 @@ function httpPost(path, body, waVersion, authHeader, device, query) {
1798
1836
  }
1799
1837
  const text = buf.toString('utf8');
1800
1838
  if (res.statusCode !== 200) {
1801
- return reject(new Error(`HTTP ${res.statusCode} ${path}: ${text}`));
1839
+ return reject(new Boom(`HTTP ${res.statusCode} ${path}: ${text}`, { statusCode: statusFrom(res.statusCode) }));
1802
1840
  }
1803
1841
  try { resolve(JSON.parse(text)); }
1804
1842
  catch (_) { resolve({ raw: text }); }
1805
1843
  });
1806
1844
  });
1807
1845
  req.on('error', reject);
1808
- req.on('timeout', () => { req.destroy(new Error(`HTTPS timeout on ${path}`)); });
1846
+ req.on('timeout', () => { req.destroy(new Boom(`HTTPS timeout on ${path}`, { statusCode: 408 })); });
1809
1847
  req.write(bodyBuf);
1810
1848
  req.end();
1811
1849
  });
@@ -2155,13 +2193,13 @@ async function handleChallenge(store, waVersion, initial, opts) {
2155
2193
  }
2156
2194
  if (!answer) {
2157
2195
  await sendFunnelLog(store, waVersion, screen, 'challenge_abandoned', 'captcha_abandoned');
2158
- const err = new Error(
2196
+ const err = new Boom(
2159
2197
  'Registration needs a CAPTCHA solved' +
2160
2198
  (typeof opts.solveCaptcha === 'function'
2161
2199
  ? ', and the solveCaptcha handler returned nothing.'
2162
2200
  : ', and no solveCaptcha handler was given.\n' +
2163
2201
  ' Pass one to verifyCode: verifyCode(store, code, { solveCaptcha: async ({ image, audio }) => "…" }).\n' +
2164
- ' image and audio are Buffers, or null when that variant was not sent.')
2202
+ ' image and audio are Buffers, or null when that variant was not sent.'), { statusCode: 403 }
2165
2203
  );
2166
2204
  err.captcha = { image, audio };
2167
2205
  err.raw = response;
@@ -2183,8 +2221,8 @@ async function handleChallenge(store, waVersion, initial, opts) {
2183
2221
  }
2184
2222
  if (is2FARequired(response)) return handle2FA(store, waVersion, opts);
2185
2223
 
2186
- const err = new Error('Registration CAPTCHA refused: ' +
2187
- (response.reason || response.status || JSON.stringify(response)));
2224
+ const err = new Boom('Registration CAPTCHA refused: ' +
2225
+ (response.reason || response.status || JSON.stringify(response)), { statusCode: 403 });
2188
2226
  err.raw = response;
2189
2227
  throw err;
2190
2228
  }
@@ -2203,13 +2241,13 @@ async function handle2FA(store, waVersion, opts) {
2203
2241
  if (typeof opts.twoFactorPin === 'function') pin = await opts.twoFactorPin();
2204
2242
  if (!pin) {
2205
2243
  await sendFunnelLog(store, waVersion, 'verify_twofac', 'twofac_abandoned', 'twofac_abandoned');
2206
- throw new Error(
2244
+ throw new Boom(
2207
2245
  'This number has two-step verification switched on and the registration ' +
2208
2246
  'needs its PIN' +
2209
2247
  (typeof opts.twoFactorPin === 'function'
2210
2248
  ? ', but the twoFactorPin handler returned nothing.'
2211
2249
  : '.\n Pass one to verifyCode: verifyCode(store, code, { twoFactorPin: async () => "123456" }).\n' +
2212
- ' It is the six-digit PIN set on the phone under Settings → Account → Two-step verification.')
2250
+ ' It is the six-digit PIN set on the phone under Settings → Account → Two-step verification.'), { statusCode: 401 }
2213
2251
  );
2214
2252
  }
2215
2253
 
@@ -2223,8 +2261,8 @@ async function handle2FA(store, waVersion, opts) {
2223
2261
  return adoptCanonicalNumber(store, response);
2224
2262
  }
2225
2263
 
2226
- const err = new Error('Two-step verification PIN refused: ' +
2227
- (response.reason || response.status || JSON.stringify(response)));
2264
+ const err = new Boom('Two-step verification PIN refused: ' +
2265
+ (response.reason || response.status || JSON.stringify(response)), { statusCode: 401 });
2228
2266
  err.raw = response;
2229
2267
  throw err;
2230
2268
  }
@@ -2408,11 +2446,11 @@ async function requestSmsCode(store, method, opts) {
2408
2446
  // nothing; letting it through spends one of the number's attempts to learn
2409
2447
  // the same thing from the server.
2410
2448
  if (method === 'flash' && !(_device && _device.os === 'android')) {
2411
- throw new Error(
2449
+ throw new Boom(
2412
2450
  'Flash call verification is Android-only — iOS has no API for reading an ' +
2413
2451
  'incoming call\'s number, so WhatsApp does not offer it there.\n' +
2414
2452
  ' Re-run as Android: WA_OS=android wa registration --request-code ' +
2415
- store.phoneNumber + ' --method flash'
2453
+ store.phoneNumber + ' --method flash', { statusCode: 405 }
2416
2454
  );
2417
2455
  }
2418
2456
 
@@ -2495,7 +2533,7 @@ async function requestSmsCode(store, method, opts) {
2495
2533
  /too_recent|too_many|too_many_guesses|too_many_all_methods/i.test(status)) {
2496
2534
  const waitSec = waitHint(result, m);
2497
2535
  const waitMsg = waitSec ? ` (wait ${Math.ceil(waitSec / 60)} min, ${waitSec}s)` : '';
2498
- throw new Error(`code already sent recently — check your phone or wait a few minutes (${reason})${waitMsg}`);
2536
+ throw new Boom(`code already sent recently — check your phone or wait a few minutes (${reason})${waitMsg}`, { statusCode: 429 });
2499
2537
  }
2500
2538
 
2501
2539
  // isRegistrationBlocked() — no_routes: signal to try alternate method
@@ -2506,14 +2544,14 @@ async function requestSmsCode(store, method, opts) {
2506
2544
  // custom_block_screen = WhatsApp security block (IP/number flagged)
2507
2545
  if (result.custom_block_screen) {
2508
2546
  const body = result.custom_block_screen.body || 'blocked by WhatsApp security';
2509
- throw new Error(`WhatsApp security block: "${body}" — use a residential IP/proxy`);
2547
+ throw new Boom(`WhatsApp security block: "${body}" — use a residential IP/proxy`, { statusCode: 403 });
2510
2548
  }
2511
2549
 
2512
2550
  // Same error twice in a row → give up. Compared even when the reason is
2513
2551
  // empty: a 200 carrying a non-JSON body leaves both status and reason
2514
2552
  // undefined, and skipping those would retry a real /code request forever.
2515
2553
  if (reason === lastReason) {
2516
- throw new Error(`Registration error (${m}): ${reason || 'no status in response'} — raw: ${JSON.stringify(result)}`);
2554
+ throw new Boom(`Registration error (${m}): ${reason || 'no status in response'} — raw: ${JSON.stringify(result)}`, { statusCode: 502 });
2517
2555
  }
2518
2556
 
2519
2557
  // First occurrence of unknown error → retry once
@@ -2523,7 +2561,7 @@ async function requestSmsCode(store, method, opts) {
2523
2561
  // A server answering with a different reason every time would otherwise
2524
2562
  // keep this loop going indefinitely.
2525
2563
  if (attemptNum > MAX_CODE_REQUEST_ATTEMPTS) {
2526
- throw new Error(`Registration error (${m}): giving up after ${MAX_CODE_REQUEST_ATTEMPTS} attempts — raw: ${JSON.stringify(result)}`);
2564
+ throw new Boom(`Registration error (${m}): giving up after ${MAX_CODE_REQUEST_ATTEMPTS} attempts — raw: ${JSON.stringify(result)}`, { statusCode: 502 });
2527
2565
  }
2528
2566
 
2529
2567
  // Nobody re-taps the button the instant the error lands.
@@ -2552,7 +2590,7 @@ async function requestSmsCode(store, method, opts) {
2552
2590
  // which is backwards — virtual numbers are among the most refused.
2553
2591
  if (result && result._noRoutes) {
2554
2592
  const tried = autoFallbackDone ? `${method}, then ${fallbackMethod}` : method;
2555
- throw new Error(
2593
+ throw new Boom(
2556
2594
  `Registration blocked (no_routes) — WhatsApp has no route to deliver the ` +
2557
2595
  `code (tried: ${tried}).\n` +
2558
2596
  ` • Most often the IP: datacenter, VPS and VPN addresses are refused. ` +
@@ -2564,7 +2602,7 @@ async function requestSmsCode(store, method, opts) {
2564
2602
  ` • wa_old only works if the number is already active on WhatsApp\n` +
2565
2603
  ` • Real SIM numbers fare better than virtual or VoIP ones\n` +
2566
2604
  ` • Leave the number alone for 24h rather than retrying — every attempt ` +
2567
- `counts against it`
2605
+ `counts against it`, { statusCode: 403 }
2568
2606
  );
2569
2607
  }
2570
2608
 
@@ -2641,16 +2679,16 @@ async function verifyCode(store, code, opts) {
2641
2679
 
2642
2680
  const reason = result.reason || '';
2643
2681
  if (reason === 'missing') {
2644
- throw new Error(
2682
+ throw new Boom(
2645
2683
  'Verification failed: code expired or already used.\n' +
2646
- ' Run /reg code <phone> again to get a new code, then immediately confirm it.'
2684
+ ' Run /reg code <phone> again to get a new code, then immediately confirm it.', { statusCode: 410 }
2647
2685
  );
2648
2686
  }
2649
2687
  if (/bad_code|code_invalid|wrong/.test(reason)) {
2650
- throw new Error('Verification failed: wrong code entered. Check the SMS and try again.');
2688
+ throw new Boom('Verification failed: wrong code entered. Check the SMS and try again.', { statusCode: 401 });
2651
2689
  }
2652
2690
  if (/too_many/.test(reason)) {
2653
- throw new Error('Verification failed: too many wrong attempts. Wait a few minutes then request a new code.');
2691
+ throw new Boom('Verification failed: too many wrong attempts. Wait a few minutes then request a new code.', { statusCode: 429 });
2654
2692
  }
2655
2693
  // Age / consent gate.
2656
2694
  //
@@ -2685,14 +2723,14 @@ async function verifyCode(store, code, opts) {
2685
2723
  ' If that is refused too, this number needs the real app once, on a phone, ' +
2686
2724
  'to clear the gate.'
2687
2725
  );
2688
- const err = new Error(lines.join('\n'));
2726
+ const err = new Boom(lines.join('\n'), { statusCode: 403 });
2689
2727
  err.reason = reason;
2690
2728
  err.pending = result.pending || null;
2691
2729
  err.canonicalPhoneNumber = canonical;
2692
2730
  err.raw = result;
2693
2731
  throw err;
2694
2732
  }
2695
- throw new Error(`Verification failed: ${reason || JSON.stringify(result)}`);
2733
+ throw new Boom(`Verification failed: ${reason || JSON.stringify(result)}`, { statusCode: 400 });
2696
2734
  }
2697
2735
 
2698
2736
  module.exports = { checkIfRegistered, checkNumberStatus, requestSmsCode, verifyCode, fetchIosVersion, fetchAndroidVersion, fetchPlayVersion, fetchAndroidVersionLive, fetchWaVersion, currentVersionFor, refreshSessionVersion, clearVersionCache, tryLoadAndroidMaterial, compareVersions, parsePhone, getCountryMeta, assertRegistrationKeys, parseSocksProxy, socksProxyUrl };
package/lib/Store.js CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
  //
3
+ const { Boom } = require('@hapi/boom');
3
4
  const { warn: _whaWarn, dbg: _whaDbg } = require('./logger');
4
5
 
5
6
  const fs = require('fs');
@@ -23,7 +24,7 @@ function prefixPubKey(raw32) {
23
24
  function stripPubKeyPrefix(pub) {
24
25
  if (pub.length === 33 && pub[0] === 0x05) return pub.slice(1);
25
26
  if (pub.length === 32) return pub;
26
- throw new Error('Invalid public key length: ' + pub.length);
27
+ throw new Boom('Invalid public key length: ' + pub.length, { statusCode: 400 });
27
28
  }
28
29
 
29
30
  // ─────────────────────────────────────────────────────────
@@ -171,7 +172,7 @@ function normaliseDevice(device) {
171
172
 
172
173
  function storeToJson(store) {
173
174
  if (!store) {
174
- throw new Error('storeToJson: store is undefined or null');
175
+ throw new Boom('storeToJson: store is undefined or null', { statusCode: 400 });
175
176
  }
176
177
 
177
178
  const normalizedPhone = store.phoneNumber
@@ -248,7 +249,7 @@ function storeToJson(store) {
248
249
 
249
250
  function storeFromJson(obj) {
250
251
  if (!obj) {
251
- throw new Error('storeFromJson: input object is undefined or null');
252
+ throw new Boom('storeFromJson: input object is undefined or null', { statusCode: 400 });
252
253
  }
253
254
 
254
255
  const name = obj.name || 'User';
@@ -335,7 +336,7 @@ function loadStore(filePath) {
335
336
 
336
337
  function toSixParts(store) {
337
338
  if (!store) {
338
- throw new Error('toSixParts: store is undefined or null');
339
+ throw new Boom('toSixParts: store is undefined or null', { statusCode: 400 });
339
340
  }
340
341
 
341
342
  const normalizedPhone = store.phoneNumber
@@ -354,7 +355,7 @@ function toSixParts(store) {
354
355
 
355
356
  function fromSixParts(sixParts) {
356
357
  const parts = sixParts.replace(/\s+/g, '').split(',');
357
- if (parts.length !== 6) throw new Error('Invalid six parts — expected 6 comma-separated values');
358
+ if (parts.length !== 6) throw new Boom('Invalid six parts — expected 6 comma-separated values', { statusCode: 400 });
358
359
 
359
360
  const phoneNumber = parts[0].replace(/^\+/, '');
360
361
  const noisePublic = Buffer.from(parts[1], 'base64');
@@ -12,6 +12,7 @@
12
12
  // still prefixes each frame with three big-endian length bytes, so the existing
13
13
  // buffer loop applies as-is.
14
14
 
15
+ const { Boom } = require('@hapi/boom');
15
16
  const EventEmitter = require('events');
16
17
  const { WEB_SOCKET_URL, WEB_ORIGIN } = require('./constants');
17
18
 
@@ -19,8 +20,8 @@ function loadWs() {
19
20
  try {
20
21
  return require('ws');
21
22
  } catch (_) {
22
- throw new Error(
23
- "The 'ws' package is required for WhatsApp Web mode. Install it with: npm install ws"
23
+ throw new Boom(
24
+ "The 'ws' package is required for WhatsApp Web mode. Install it with: npm install ws", { statusCode: 501 }
24
25
  );
25
26
  }
26
27
  }
package/lib/WebVersion.js CHANGED
@@ -16,6 +16,8 @@
16
16
  // Everything here is best-effort — a failed fetch falls back to the pinned
17
17
  // value rather than blocking a connection.
18
18
 
19
+ const { Boom } = require('@hapi/boom');
20
+ const { statusFrom } = require('./errors');
19
21
  const https = require('https');
20
22
  const { WEB_VERSION_FALLBACK } = require('./constants');
21
23
  const { proxyAgent } = require('./socks');
@@ -44,7 +46,7 @@ function fetchText(url, timeoutMs) {
44
46
  }, (res) => {
45
47
  if (res.statusCode !== 200) {
46
48
  res.resume();
47
- return reject(new Error('sw.js returned HTTP ' + res.statusCode));
49
+ return reject(new Boom('sw.js returned HTTP ' + res.statusCode, { statusCode: statusFrom(res.statusCode) }));
48
50
  }
49
51
  const chunks = [];
50
52
  res.on('data', c => chunks.push(c));
@@ -52,7 +54,7 @@ function fetchText(url, timeoutMs) {
52
54
  res.on('error', reject);
53
55
  });
54
56
  req.on('error', reject);
55
- req.setTimeout(timeoutMs || 10000, () => req.destroy(new Error('sw.js fetch timed out')));
57
+ req.setTimeout(timeoutMs || 10000, () => req.destroy(new Boom('sw.js fetch timed out', { statusCode: 408 })));
56
58
  });
57
59
  }
58
60
 
@@ -71,7 +73,7 @@ async function fetchWaWebVersion(opts) {
71
73
  try {
72
74
  const body = await fetchText(SW_URL, opts.timeoutMs);
73
75
  const match = body.match(/\\?"client_revision\\?":\s*(\d+)/);
74
- if (!match || !match[1]) throw new Error('client_revision not found in sw.js');
76
+ if (!match || !match[1]) throw new Boom('client_revision not found in sw.js', { statusCode: 502 });
75
77
 
76
78
  const version = [2, 3000, parseInt(match[1], 10)];
77
79
  _cached = version;
@@ -32,6 +32,8 @@
32
32
  // arrays on the way in. Collapsing them into a plain object would silently drop
33
33
  // every topic but the last.
34
34
 
35
+ const { Boom } = require('@hapi/boom');
36
+ const { statusFrom } = require('./errors');
35
37
  const tls = require('tls');
36
38
  const https = require('https');
37
39
  const http = require('http');
@@ -191,7 +193,7 @@ function httpGet(url) {
191
193
  res.on('error', reject);
192
194
  });
193
195
  req.on('error', reject);
194
- req.setTimeout(HTTP_TIMEOUT_MS, () => req.destroy(new Error('timed out')));
196
+ req.setTimeout(HTTP_TIMEOUT_MS, () => req.destroy(new Boom('timed out', { statusCode: 408 })));
195
197
  req.end();
196
198
  });
197
199
  }
@@ -202,7 +204,7 @@ function parseBag(body) {
202
204
  const hostCount = Number(inner.APNSCourierHostcount);
203
205
  const hostname = String(inner.APNSCourierHostname || '');
204
206
  if (!hostname || !Number.isFinite(hostCount) || hostCount < 1) {
205
- throw new Error('bag has no courier pool');
207
+ throw new Boom('bag has no courier pool', { statusCode: 502 });
206
208
  }
207
209
  return { hostCount, hostname };
208
210
  }
@@ -237,7 +239,7 @@ async function fetchBag() {
237
239
  for (const url of bagUrls()) {
238
240
  try {
239
241
  const res = await httpGet(url);
240
- if (res.status < 200 || res.status >= 300) throw new Error('HTTP ' + res.status);
242
+ if (res.status < 200 || res.status >= 300) throw new Boom('HTTP ' + res.status, { statusCode: statusFrom(res.status) });
241
243
  const bag = parseBag(res.body);
242
244
  _whaDbg('[DBG] APNs bag: ' + bag.hostCount + ' hosts at ' + bag.hostname);
243
245
  return bag;
@@ -355,7 +357,7 @@ class ApnsCourierConnection {
355
357
  this.socket = await this._dial(host);
356
358
  this.socket.on('data', chunk => this._onData(chunk));
357
359
  this.socket.on('error', err => this._fail(err));
358
- this.socket.on('close', () => this._fail(new Error('courier connection closed')));
360
+ this.socket.on('close', () => this._fail(new Boom('courier connection closed', { statusCode: 428 })));
359
361
 
360
362
  try {
361
363
  await this._handshake();
@@ -422,7 +424,7 @@ class ApnsCourierConnection {
422
424
  _whaDbg('[DBG] APNs courier certificate issued by ' + describeIssuer(this.peerIssuer));
423
425
  resolve(socket);
424
426
  });
425
- socket.setTimeout(CONNECT_TIMEOUT_MS, () => socket.destroy(new Error('courier connect timed out')));
427
+ socket.setTimeout(CONNECT_TIMEOUT_MS, () => socket.destroy(new Boom('courier connect timed out', { statusCode: 408 })));
426
428
  socket.once('error', reject);
427
429
  });
428
430
  }
@@ -447,12 +449,12 @@ class ApnsCourierConnection {
447
449
 
448
450
  const status = first(ready.fields, F_READY_STATUS);
449
451
  if (!status || status.length === 0 || status[0] !== 0) {
450
- throw new Error('courier refused CONNECT: status=' +
451
- (status && status.length ? status[0] : 'none'));
452
+ throw new Boom('courier refused CONNECT: status=' +
453
+ (status && status.length ? status[0] : 'none'), { statusCode: 502 });
452
454
  }
453
455
 
454
456
  const token = first(ready.fields, F_READY_TOKEN);
455
- if (!token) throw new Error('courier READY carried no device token');
457
+ if (!token) throw new Boom('courier READY carried no device token', { statusCode: 502 });
456
458
 
457
459
  // A reissued device token invalidates every per-topic token derived from
458
460
  // the old one, including the push_token WhatsApp may already hold. Say so,
@@ -481,7 +483,7 @@ class ApnsCourierConnection {
481
483
  const socket = this.socket;
482
484
  this.socket = null;
483
485
  if (socket) { try { socket.destroy(); } catch (_) {} }
484
- this._rejectPending(new Error('courier closed'));
486
+ this._rejectPending(new Boom('courier closed', { statusCode: 428 }));
485
487
  }
486
488
 
487
489
  // ── requests ──
@@ -504,7 +506,7 @@ class ApnsCourierConnection {
504
506
  first(p.fields, F_TOKEN_RESPONSE_TOPIC).equals(hash)));
505
507
 
506
508
  const token = first(packet.fields, F_TOKEN_RESPONSE_TOKEN);
507
- if (!token) throw new Error('courier TOKEN_RESPONSE carried no token');
509
+ if (!token) throw new Boom('courier TOKEN_RESPONSE carried no token', { statusCode: 502 });
508
510
  return token.toString('hex');
509
511
  }
510
512
 
@@ -527,7 +529,7 @@ class ApnsCourierConnection {
527
529
  // ── wire ──
528
530
 
529
531
  _send(tag, fields) {
530
- if (!this.socket) throw new Error('courier is not connected');
532
+ if (!this.socket) throw new Boom('courier is not connected', { statusCode: 428 });
531
533
  this.socket.write(encodeFrame(tag, fields));
532
534
  }
533
535
 
@@ -539,7 +541,7 @@ class ApnsCourierConnection {
539
541
  reject,
540
542
  timer: setTimeout(() => {
541
543
  this._drop(entry);
542
- reject(new Error('courier request timed out'));
544
+ reject(new Boom('courier request timed out', { statusCode: 408 }));
543
545
  }, REQUEST_TIMEOUT_MS)
544
546
  };
545
547
  if (entry.timer.unref) entry.timer.unref();
@@ -573,7 +575,7 @@ class ApnsCourierConnection {
573
575
  if (this.keepAliveTimer) clearInterval(this.keepAliveTimer);
574
576
  this.keepAliveTimer = null;
575
577
  _whaDbg('[DBG] APNs courier lost: ' + (err && err.message));
576
- const error = err instanceof Error ? err : new Error(String(err));
578
+ const error = err instanceof Error ? err : new Boom(String(err));
577
579
  this._rejectPending(error);
578
580
  // A listener waiting on a push has no other way to learn the line is gone,
579
581
  // and waiting out a three-minute timeout on a dead socket helps nobody.
package/lib/apns.js CHANGED
@@ -31,6 +31,8 @@
31
31
  // the body goes out exactly as it did before this file existed. A push token is
32
32
  // a signal that helps; it is never the reason a registration cannot be tried.
33
33
 
34
+ const { Boom } = require('@hapi/boom');
35
+ const { statusFrom } = require('./errors');
34
36
  const https = require('https');
35
37
  const crypto = require('crypto');
36
38
 
@@ -329,7 +331,7 @@ function httpPost(url, body, headers) {
329
331
  res.on('error', reject);
330
332
  });
331
333
  req.on('error', reject);
332
- req.setTimeout(HTTP_TIMEOUT_MS, () => req.destroy(new Error('timed out')));
334
+ req.setTimeout(HTTP_TIMEOUT_MS, () => req.destroy(new Boom('timed out', { statusCode: 408 })));
333
335
  req.write(body);
334
336
  req.end();
335
337
  });
@@ -349,7 +351,7 @@ const PROTOCOL_BLOCK = /<Protocol>([\s\S]+?)<\/Protocol>/;
349
351
  function parseActivationResponse(responseBody) {
350
352
  const text = Buffer.isBuffer(responseBody) ? responseBody.toString('utf8') : String(responseBody);
351
353
  const match = PROTOCOL_BLOCK.exec(text);
352
- if (!match) throw new Error('activation response carried no <Protocol> block');
354
+ if (!match) throw new Boom('activation response carried no <Protocol> block', { statusCode: 502 });
353
355
 
354
356
  const record = plist.parse(Buffer.from(match[1], 'utf8'));
355
357
  const certificate = record
@@ -358,7 +360,7 @@ function parseActivationResponse(responseBody) {
358
360
  && record['device-activation']['activation-record'].DeviceCertificate;
359
361
 
360
362
  if (!Buffer.isBuffer(certificate) || certificate.length === 0) {
361
- throw new Error('activation record carried no DeviceCertificate');
363
+ throw new Boom('activation record carried no DeviceCertificate', { statusCode: 502 });
362
364
  }
363
365
  return certificate;
364
366
  }
@@ -385,7 +387,7 @@ async function activate() {
385
387
  'Accept': '*/*'
386
388
  });
387
389
  if (res.status < 200 || res.status >= 300) {
388
- throw new Error('activation HTTP ' + res.status + ': ' + res.body.toString('utf8').slice(0, 200));
390
+ throw new Boom('activation HTTP ' + res.status + ': ' + res.body.toString('utf8').slice(0, 200), { statusCode: statusFrom(res.status) });
389
391
  }
390
392
 
391
393
  return {