whalibmob 5.40.38 → 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 (51) 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 +19 -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/DeviceManager.js +2 -1
  11. package/lib/HistorySyncHandler.js +13 -11
  12. package/lib/MediaService.js +14 -12
  13. package/lib/OfflineNodeProcessor.js +3 -1
  14. package/lib/PairingCode.js +2 -1
  15. package/lib/PasskeyPairing.js +18 -17
  16. package/lib/PlayStore.js +15 -13
  17. package/lib/PrimaryLinkCrypto.js +2 -1
  18. package/lib/Registration.js +37 -35
  19. package/lib/Store.js +6 -5
  20. package/lib/WebSocketStream.js +3 -2
  21. package/lib/WebVersion.js +5 -3
  22. package/lib/apns-courier.js +15 -13
  23. package/lib/apns.js +6 -4
  24. package/lib/argo/ArgoDecoder.js +16 -14
  25. package/lib/auth-utils.js +10 -9
  26. package/lib/cli/linkCommands.js +5 -2
  27. package/lib/curve.js +5 -4
  28. package/lib/errors.js +42 -0
  29. package/lib/fcm.js +7 -5
  30. package/lib/image/JpegEncoder.js +4 -2
  31. package/lib/messages/MediaRetry.js +3 -2
  32. package/lib/messages/MessageSecret.js +9 -8
  33. package/lib/messages/MessageSender.js +30 -28
  34. package/lib/noise.js +13 -11
  35. package/lib/plist.js +18 -15
  36. package/lib/primary/HistoryExport.js +2 -1
  37. package/lib/primary/MessageStore.js +8 -2
  38. package/lib/proto/MessageProto.js +3 -1
  39. package/lib/signal/SenderKey.js +5 -4
  40. package/lib/signal/WaSignalGroup/group-session-builder.js +2 -1
  41. package/lib/signal/WaSignalGroup/group_cipher.js +10 -9
  42. package/lib/signal/WaSignalGroup/sender-key-distribution-message.js +2 -1
  43. package/lib/signal/WaSignalGroup/sender-key-message.js +2 -1
  44. package/lib/socks.js +9 -8
  45. package/lib/store/Backend.js +3 -1
  46. package/lib/store/FileBackend.js +2 -1
  47. package/lib/store/MemoryBackend.js +2 -1
  48. package/lib/store/SqliteBackend.js +6 -5
  49. package/lib/store/migrate.js +2 -1
  50. package/llms.txt +1 -0
  51. 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;
@@ -1834,14 +1836,14 @@ function httpPost(path, body, waVersion, authHeader, device, query) {
1834
1836
  }
1835
1837
  const text = buf.toString('utf8');
1836
1838
  if (res.statusCode !== 200) {
1837
- return reject(new Error(`HTTP ${res.statusCode} ${path}: ${text}`));
1839
+ return reject(new Boom(`HTTP ${res.statusCode} ${path}: ${text}`, { statusCode: statusFrom(res.statusCode) }));
1838
1840
  }
1839
1841
  try { resolve(JSON.parse(text)); }
1840
1842
  catch (_) { resolve({ raw: text }); }
1841
1843
  });
1842
1844
  });
1843
1845
  req.on('error', reject);
1844
- 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 })); });
1845
1847
  req.write(bodyBuf);
1846
1848
  req.end();
1847
1849
  });
@@ -2191,13 +2193,13 @@ async function handleChallenge(store, waVersion, initial, opts) {
2191
2193
  }
2192
2194
  if (!answer) {
2193
2195
  await sendFunnelLog(store, waVersion, screen, 'challenge_abandoned', 'captcha_abandoned');
2194
- const err = new Error(
2196
+ const err = new Boom(
2195
2197
  'Registration needs a CAPTCHA solved' +
2196
2198
  (typeof opts.solveCaptcha === 'function'
2197
2199
  ? ', and the solveCaptcha handler returned nothing.'
2198
2200
  : ', and no solveCaptcha handler was given.\n' +
2199
2201
  ' Pass one to verifyCode: verifyCode(store, code, { solveCaptcha: async ({ image, audio }) => "…" }).\n' +
2200
- ' 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 }
2201
2203
  );
2202
2204
  err.captcha = { image, audio };
2203
2205
  err.raw = response;
@@ -2219,8 +2221,8 @@ async function handleChallenge(store, waVersion, initial, opts) {
2219
2221
  }
2220
2222
  if (is2FARequired(response)) return handle2FA(store, waVersion, opts);
2221
2223
 
2222
- const err = new Error('Registration CAPTCHA refused: ' +
2223
- (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 });
2224
2226
  err.raw = response;
2225
2227
  throw err;
2226
2228
  }
@@ -2239,13 +2241,13 @@ async function handle2FA(store, waVersion, opts) {
2239
2241
  if (typeof opts.twoFactorPin === 'function') pin = await opts.twoFactorPin();
2240
2242
  if (!pin) {
2241
2243
  await sendFunnelLog(store, waVersion, 'verify_twofac', 'twofac_abandoned', 'twofac_abandoned');
2242
- throw new Error(
2244
+ throw new Boom(
2243
2245
  'This number has two-step verification switched on and the registration ' +
2244
2246
  'needs its PIN' +
2245
2247
  (typeof opts.twoFactorPin === 'function'
2246
2248
  ? ', but the twoFactorPin handler returned nothing.'
2247
2249
  : '.\n Pass one to verifyCode: verifyCode(store, code, { twoFactorPin: async () => "123456" }).\n' +
2248
- ' 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 }
2249
2251
  );
2250
2252
  }
2251
2253
 
@@ -2259,8 +2261,8 @@ async function handle2FA(store, waVersion, opts) {
2259
2261
  return adoptCanonicalNumber(store, response);
2260
2262
  }
2261
2263
 
2262
- const err = new Error('Two-step verification PIN refused: ' +
2263
- (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 });
2264
2266
  err.raw = response;
2265
2267
  throw err;
2266
2268
  }
@@ -2444,11 +2446,11 @@ async function requestSmsCode(store, method, opts) {
2444
2446
  // nothing; letting it through spends one of the number's attempts to learn
2445
2447
  // the same thing from the server.
2446
2448
  if (method === 'flash' && !(_device && _device.os === 'android')) {
2447
- throw new Error(
2449
+ throw new Boom(
2448
2450
  'Flash call verification is Android-only — iOS has no API for reading an ' +
2449
2451
  'incoming call\'s number, so WhatsApp does not offer it there.\n' +
2450
2452
  ' Re-run as Android: WA_OS=android wa registration --request-code ' +
2451
- store.phoneNumber + ' --method flash'
2453
+ store.phoneNumber + ' --method flash', { statusCode: 405 }
2452
2454
  );
2453
2455
  }
2454
2456
 
@@ -2531,7 +2533,7 @@ async function requestSmsCode(store, method, opts) {
2531
2533
  /too_recent|too_many|too_many_guesses|too_many_all_methods/i.test(status)) {
2532
2534
  const waitSec = waitHint(result, m);
2533
2535
  const waitMsg = waitSec ? ` (wait ${Math.ceil(waitSec / 60)} min, ${waitSec}s)` : '';
2534
- 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 });
2535
2537
  }
2536
2538
 
2537
2539
  // isRegistrationBlocked() — no_routes: signal to try alternate method
@@ -2542,14 +2544,14 @@ async function requestSmsCode(store, method, opts) {
2542
2544
  // custom_block_screen = WhatsApp security block (IP/number flagged)
2543
2545
  if (result.custom_block_screen) {
2544
2546
  const body = result.custom_block_screen.body || 'blocked by WhatsApp security';
2545
- 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 });
2546
2548
  }
2547
2549
 
2548
2550
  // Same error twice in a row → give up. Compared even when the reason is
2549
2551
  // empty: a 200 carrying a non-JSON body leaves both status and reason
2550
2552
  // undefined, and skipping those would retry a real /code request forever.
2551
2553
  if (reason === lastReason) {
2552
- 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 });
2553
2555
  }
2554
2556
 
2555
2557
  // First occurrence of unknown error → retry once
@@ -2559,7 +2561,7 @@ async function requestSmsCode(store, method, opts) {
2559
2561
  // A server answering with a different reason every time would otherwise
2560
2562
  // keep this loop going indefinitely.
2561
2563
  if (attemptNum > MAX_CODE_REQUEST_ATTEMPTS) {
2562
- 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 });
2563
2565
  }
2564
2566
 
2565
2567
  // Nobody re-taps the button the instant the error lands.
@@ -2588,7 +2590,7 @@ async function requestSmsCode(store, method, opts) {
2588
2590
  // which is backwards — virtual numbers are among the most refused.
2589
2591
  if (result && result._noRoutes) {
2590
2592
  const tried = autoFallbackDone ? `${method}, then ${fallbackMethod}` : method;
2591
- throw new Error(
2593
+ throw new Boom(
2592
2594
  `Registration blocked (no_routes) — WhatsApp has no route to deliver the ` +
2593
2595
  `code (tried: ${tried}).\n` +
2594
2596
  ` • Most often the IP: datacenter, VPS and VPN addresses are refused. ` +
@@ -2600,7 +2602,7 @@ async function requestSmsCode(store, method, opts) {
2600
2602
  ` • wa_old only works if the number is already active on WhatsApp\n` +
2601
2603
  ` • Real SIM numbers fare better than virtual or VoIP ones\n` +
2602
2604
  ` • Leave the number alone for 24h rather than retrying — every attempt ` +
2603
- `counts against it`
2605
+ `counts against it`, { statusCode: 403 }
2604
2606
  );
2605
2607
  }
2606
2608
 
@@ -2677,16 +2679,16 @@ async function verifyCode(store, code, opts) {
2677
2679
 
2678
2680
  const reason = result.reason || '';
2679
2681
  if (reason === 'missing') {
2680
- throw new Error(
2682
+ throw new Boom(
2681
2683
  'Verification failed: code expired or already used.\n' +
2682
- ' 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 }
2683
2685
  );
2684
2686
  }
2685
2687
  if (/bad_code|code_invalid|wrong/.test(reason)) {
2686
- 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 });
2687
2689
  }
2688
2690
  if (/too_many/.test(reason)) {
2689
- 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 });
2690
2692
  }
2691
2693
  // Age / consent gate.
2692
2694
  //
@@ -2721,14 +2723,14 @@ async function verifyCode(store, code, opts) {
2721
2723
  ' If that is refused too, this number needs the real app once, on a phone, ' +
2722
2724
  'to clear the gate.'
2723
2725
  );
2724
- const err = new Error(lines.join('\n'));
2726
+ const err = new Boom(lines.join('\n'), { statusCode: 403 });
2725
2727
  err.reason = reason;
2726
2728
  err.pending = result.pending || null;
2727
2729
  err.canonicalPhoneNumber = canonical;
2728
2730
  err.raw = result;
2729
2731
  throw err;
2730
2732
  }
2731
- throw new Error(`Verification failed: ${reason || JSON.stringify(result)}`);
2733
+ throw new Boom(`Verification failed: ${reason || JSON.stringify(result)}`, { statusCode: 400 });
2732
2734
  }
2733
2735
 
2734
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 {
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
4
+
3
5
  // Argo — the binary encoding WhatsApp's GraphQL transport answers in.
4
6
  //
5
7
  // A w:mex reply can come back as JSON or as Argo; the <result> node says which.
@@ -52,14 +54,14 @@ class Reader {
52
54
  }
53
55
  get done() { return this.pos >= this.buf.length; }
54
56
  byte() {
55
- if (this.pos >= this.buf.length) throw new Error('argo: ran off the end of the message');
57
+ if (this.pos >= this.buf.length) throw new Boom('argo: ran off the end of the message', { statusCode: 400 });
56
58
  return this.buf[this.pos++];
57
59
  }
58
60
  peek() { return this.buf[this.pos]; }
59
61
  take(n) {
60
62
  if (n < 0 || this.pos + n > this.buf.length) {
61
- throw new Error('argo: asked for ' + n + ' bytes with ' +
62
- (this.buf.length - this.pos) + ' left');
63
+ throw new Boom('argo: asked for ' + n + ' bytes with ' +
64
+ (this.buf.length - this.pos) + ' left', { statusCode: 400 });
63
65
  }
64
66
  const out = this.buf.slice(this.pos, this.pos + n);
65
67
  this.pos += n;
@@ -73,7 +75,7 @@ class Reader {
73
75
  value |= BigInt(b & 0x7f) << shift;
74
76
  if (!(b & 0x80)) break;
75
77
  shift += 7n;
76
- if (shift > 63n) throw new Error('argo: label is too long to be a number');
78
+ if (shift > 63n) throw new Boom('argo: label is too long to be a number', { statusCode: 400 });
77
79
  }
78
80
  const signed = (value >> 1n) ^ -(value & 1n);
79
81
  return Number(signed);
@@ -115,7 +117,7 @@ class BlockQueue {
115
117
  if (this.inline) return this.inlineBlock;
116
118
  if (!this.byKey.has(key)) {
117
119
  const buf = this.blocks[this.next++];
118
- if (buf === undefined) throw new Error('argo: message is missing a block for ' + key);
120
+ if (buf === undefined) throw new Boom('argo: message is missing a block for ' + key, { statusCode: 400 });
119
121
  this.byKey.set(key, { reader: new Reader(buf), seen: [] });
120
122
  }
121
123
  return this.byKey.get(key);
@@ -128,8 +130,8 @@ function decodeArgo(bytes) {
128
130
  const header = readHeader(reader);
129
131
 
130
132
  if (!header.selfDescribing) {
131
- const err = new Error('argo: this message is encoded against a GraphQL schema ' +
132
- 'rather than describing itself, so it cannot be read without that schema');
133
+ const err = new Boom('argo: this message is encoded against a GraphQL schema ' +
134
+ 'rather than describing itself, so it cannot be read without that schema', { statusCode: 400 });
133
135
  err.needsSchema = true;
134
136
  throw err;
135
137
  }
@@ -140,11 +142,11 @@ function decodeArgo(bytes) {
140
142
  } else {
141
143
  while (!reader.done) {
142
144
  const len = reader.label();
143
- if (len < 0) throw new Error('argo: block length cannot be ' + len);
145
+ if (len < 0) throw new Boom('argo: block length cannot be ' + len, { statusCode: 400 });
144
146
  blocks.push(reader.take(len));
145
147
  }
146
148
  }
147
- if (!blocks.length) throw new Error('argo: message has no core');
149
+ if (!blocks.length) throw new Boom('argo: message has no core', { statusCode: 400 });
148
150
 
149
151
  // The core is the last block, and every other block feeds it.
150
152
  const core = new Reader(blocks[blocks.length - 1]);
@@ -164,11 +166,11 @@ function readBlockValue(core, queue, key, convert) {
164
166
  if (label <= BACKREF_BASE) {
165
167
  const idx = -label + BACKREF_BASE;
166
168
  if (idx < 0 || idx >= block.seen.length) {
167
- throw new Error('argo: backreference ' + label + ' points outside ' + key);
169
+ throw new Boom('argo: backreference ' + label + ' points outside ' + key, { statusCode: 400 });
168
170
  }
169
171
  return block.seen[idx];
170
172
  }
171
- if (label < 0) throw new Error('argo: ' + key + ' cannot have label ' + label);
173
+ if (label < 0) throw new Boom('argo: ' + key + ' cannot have label ' + label, { statusCode: 400 });
172
174
  const value = convert(block.reader.take(label));
173
175
  block.seen.push(value);
174
176
  return value;
@@ -184,7 +186,7 @@ function readValue(core, queue) {
184
186
 
185
187
  case MARKER.OBJECT: {
186
188
  const count = core.label();
187
- if (count < 0) throw new Error('argo: object cannot have ' + count + ' fields');
189
+ if (count < 0) throw new Boom('argo: object cannot have ' + count + ' fields', { statusCode: 400 });
188
190
  const out = {};
189
191
  for (let i = 0; i < count; i++) {
190
192
  const name = readBlockValue(core, queue, 'String', b => b.toString('utf8'));
@@ -195,7 +197,7 @@ function readValue(core, queue) {
195
197
 
196
198
  case MARKER.LIST: {
197
199
  const count = core.label();
198
- if (count < 0) throw new Error('argo: list cannot have ' + count + ' items');
200
+ if (count < 0) throw new Boom('argo: list cannot have ' + count + ' items', { statusCode: 400 });
199
201
  const out = [];
200
202
  for (let i = 0; i < count; i++) out.push(readValue(core, queue));
201
203
  return out;
@@ -218,7 +220,7 @@ function readValue(core, queue) {
218
220
  default:
219
221
  if (marker === LABEL_ABSENT) return undefined;
220
222
  if (marker === LABEL_ERROR) return readValue(core, queue);
221
- throw new Error('argo: unknown type marker ' + marker);
223
+ throw new Boom('argo: unknown type marker ' + marker, { statusCode: 400 });
222
224
  }
223
225
  }
224
226