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
package/lib/Client.js CHANGED
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
4
+ const { statusFrom } = require('./errors');
3
5
  const { dbg: _whaDbg, configureLogger: _whaConfigLogger } = require('./logger');
4
6
 
5
7
  const EventEmitter = require('events');
@@ -286,7 +288,7 @@ function _stripAdvField2(buf) {
286
288
  }
287
289
 
288
290
  function pairingCodeError(message, code, serverCode, serverText) {
289
- const err = new Error(message);
291
+ const err = new Boom(message, { statusCode: statusFrom(serverCode, 500) });
290
292
  err.code = code;
291
293
  if (serverCode != null) err.serverCode = serverCode;
292
294
  if (serverText != null) err.serverText = serverText;
@@ -301,7 +303,7 @@ function isServerJid(value) {
301
303
  }
302
304
 
303
305
  function passkeyError(message, code) {
304
- const err = new Error(message);
306
+ const err = new Boom(message);
305
307
  err.code = code;
306
308
  return err;
307
309
  }
@@ -793,8 +795,8 @@ const QUOTE_HOLDER = 'ContextInfo';
793
795
  const VIEW_ONCE_DEPTH = 6;
794
796
  const VIEW_ONCE_FRAMES = 64;
795
797
  const VIEW_ONCE_BYTES = 8 * 1024 * 1024;
796
- const VIEW_ONCE_BUDGET = new Error('view-once walk: byte budget spent');
797
- const VIEW_ONCE_DEEP = new Error('view-once walk: nested past the bound');
798
+ const VIEW_ONCE_BUDGET = new Boom('view-once walk: byte budget spent', { statusCode: 400 });
799
+ const VIEW_ONCE_DEEP = new Boom('view-once walk: nested past the bound', { statusCode: 400 });
798
800
  const VIEW_ONCE_TOP = { level: 1, frames: 1 };
799
801
 
800
802
  // VIEW_ONCE_SCHEMA as maps: type -> field number -> { type, repeated }.
@@ -826,7 +828,7 @@ function viewOnceStep(at, type) {
826
828
  // a message, 0 for a bool. Anything else is not the message the schema
827
829
  // describes, and does not read.
828
830
  function viewOnceWire(f, wire) {
829
- if (f.wire !== wire) throw new Error('view-once walk: wire type ' + f.wire + ' for field ' + f.number);
831
+ if (f.wire !== wire) throw new Boom('view-once walk: wire type ' + f.wire + ' for field ' + f.number, { statusCode: 400 });
830
832
  }
831
833
 
832
834
  // The fields of one protobuf message, each with where it sits in `buf`
@@ -846,7 +848,7 @@ function protoFields(buf, budget) {
846
848
  const varint = () => {
847
849
  let value = 0, scale = 1, byte;
848
850
  for (let n = 0; ; n++) {
849
- if (i >= buf.length || n >= 10) throw new Error('varint');
851
+ if (i >= buf.length || n >= 10) throw new Boom('varint', { statusCode: 400 });
850
852
  byte = buf[i++];
851
853
  value += (byte & 0x7f) * scale;
852
854
  scale *= 128;
@@ -855,14 +857,14 @@ function protoFields(buf, budget) {
855
857
  };
856
858
  const tag = () => {
857
859
  const t = varint(), number = Math.floor(t / 8);
858
- if (number < 1 || number > 0x1fffffff) throw new Error('field number');
860
+ if (number < 1 || number > 0x1fffffff) throw new Boom('field number', { statusCode: 400 });
859
861
  return { number, wire: t % 8 };
860
862
  };
861
863
  // Past the value of a field of this wire type; its length, if it has one.
862
864
  const skip = wire => {
863
865
  if (wire === 0) { varint(); return -1; }
864
866
  const length = wire === 1 ? 8 : wire === 5 ? 4 : wire === 2 ? varint() : -1;
865
- if (length < 0 || i + length > buf.length) throw new Error('wire');
867
+ if (length < 0 || i + length > buf.length) throw new Boom('wire', { statusCode: 400 });
866
868
  i += length;
867
869
  return length;
868
870
  };
@@ -876,10 +878,10 @@ function protoFields(buf, budget) {
876
878
  } else if (wire === 3) {
877
879
  const open = [number];
878
880
  while (open.length) {
879
- if (i >= buf.length) throw new Error('group left open');
881
+ if (i >= buf.length) throw new Boom('group left open', { statusCode: 400 });
880
882
  const inner = tag();
881
883
  if (inner.wire === 3) open.push(inner.number);
882
- else if (inner.wire === 4) { if (open.pop() !== inner.number) throw new Error('end-group of another number'); }
884
+ else if (inner.wire === 4) { if (open.pop() !== inner.number) throw new Boom('end-group of another number', { statusCode: 400 }); }
883
885
  else skip(inner.wire);
884
886
  }
885
887
  out.push({ number, wire, value: null, start, tagEnd, end: i });
@@ -1444,12 +1446,12 @@ class WhalibmobClient extends EventEmitter {
1444
1446
  // library has no business teaching CLI syntax either — the caller knows
1445
1447
  // which interface it is; this only has to name the state.
1446
1448
  const hasWeb = fs.existsSync(path.join(this._sessionDir, `${phoneNumber}.web.json`));
1447
- throw new Error(
1449
+ throw new Boom(
1448
1450
  hasWeb
1449
1451
  ? `No primary session for ${phoneNumber}, but it is linked as a ` +
1450
1452
  'companion device — use connectWeb() rather than init().'
1451
1453
  : `No session for ${phoneNumber} — register the number first, or ` +
1452
- 'link it to an existing account with connectWeb().'
1454
+ 'link it to an existing account with connectWeb().', { statusCode: 404 }
1453
1455
  );
1454
1456
  }
1455
1457
 
@@ -1638,7 +1640,7 @@ class WhalibmobClient extends EventEmitter {
1638
1640
  // confirmed: return false to turn it down.
1639
1641
  if (opts.prePair !== undefined) {
1640
1642
  if (opts.prePair !== null && typeof opts.prePair !== 'function') {
1641
- throw new Error('connectWeb: prePair must be a function');
1643
+ throw new Boom('connectWeb: prePair must be a function', { statusCode: 400 });
1642
1644
  }
1643
1645
  this._prePair = opts.prePair;
1644
1646
  }
@@ -1959,13 +1961,13 @@ class WhalibmobClient extends EventEmitter {
1959
1961
 
1960
1962
  async requestPairingCode(phoneNumber, customCode) {
1961
1963
  if (this._mode !== 'web') {
1962
- throw new Error('requestPairingCode is only available in web mode — call connectWeb() first');
1964
+ throw new Boom('requestPairingCode is only available in web mode — call connectWeb() first', { statusCode: 405 });
1963
1965
  }
1964
1966
  if (!this._socket || !this._socket.secured) {
1965
- throw new Error('Not connected — call connectWeb() before requesting a pairing code');
1967
+ throw new Boom('Not connected — call connectWeb() before requesting a pairing code', { statusCode: 428 });
1966
1968
  }
1967
1969
  if (this._store.registered) {
1968
- throw new Error('This session is already linked — no pairing code needed');
1970
+ throw new Boom('This session is already linked — no pairing code needed', { statusCode: 409 });
1969
1971
  }
1970
1972
 
1971
1973
  const { generatePairingCode, buildWrappedEphemeralPub, generateEphemeralKeyPair } =
@@ -1973,12 +1975,12 @@ class WhalibmobClient extends EventEmitter {
1973
1975
  const { platformTypeFor } = require('./webproto');
1974
1976
 
1975
1977
  if (customCode != null && String(customCode).length !== 8) {
1976
- throw new Error('A custom pairing code must be exactly 8 characters');
1978
+ throw new Boom('A custom pairing code must be exactly 8 characters', { statusCode: 400 });
1977
1979
  }
1978
1980
 
1979
1981
  const phone = String(phoneNumber || this._phoneNumber || this._store.phoneNumber)
1980
1982
  .replace(/\D/g, '');
1981
- if (!phone) throw new Error('requestPairingCode: a phone number is required');
1983
+ if (!phone) throw new Boom('requestPairingCode: a phone number is required', { statusCode: 400 });
1982
1984
 
1983
1985
  const code = customCode ? String(customCode).toUpperCase() : generatePairingCode();
1984
1986
 
@@ -2098,7 +2100,7 @@ class WhalibmobClient extends EventEmitter {
2098
2100
 
2099
2101
  if (!ref || !primaryIdentityPub || !wrappedEphemeral) {
2100
2102
  _whaDbg('[DBG] COMPANION_FINISH missing fields — aborting');
2101
- this.emit('error', new Error('Pairing failed: incomplete companion_finish from server'));
2103
+ this.emit('error', new Boom('Pairing failed: incomplete companion_finish from server', { statusCode: 502 }));
2102
2104
  return;
2103
2105
  }
2104
2106
  if (!this._store.pairingCode) {
@@ -2152,12 +2154,12 @@ class WhalibmobClient extends EventEmitter {
2152
2154
  if (finishResult && finishResult.attrs && finishResult.attrs.type === 'error') {
2153
2155
  const errNode = findChild(finishResult, 'error');
2154
2156
  const code = errNode && errNode.attrs && errNode.attrs.code;
2155
- throw new Error('server rejected companion_finish' + (code ? ' (' + code + ')' : ''));
2157
+ throw new Boom('server rejected companion_finish' + (code ? ' (' + code + ')' : ''), { statusCode: statusFrom(code) });
2156
2158
  }
2157
2159
  _whaDbg('[DBG] COMPANION_FINISH accepted — awaiting pair-success');
2158
2160
  } catch (err) {
2159
2161
  _whaDbg('[DBG] COMPANION_FINISH_ERR ' + (err && err.message));
2160
- this.emit('error', new Error('Pairing failed: ' + (err && err.message)));
2162
+ this.emit('error', new Boom('Pairing failed: ' + (err && err.message)));
2161
2163
  }
2162
2164
  }
2163
2165
 
@@ -2195,12 +2197,12 @@ class WhalibmobClient extends EventEmitter {
2195
2197
  platform: result.platform, businessName: result.businessName
2196
2198
  });
2197
2199
  } catch (cbErr) {
2198
- const err = new Error('pair-success: the prePair callback threw: ' + (cbErr && cbErr.message));
2200
+ const err = new Boom('pair-success: the prePair callback threw: ' + (cbErr && cbErr.message));
2199
2201
  err.pairError = PAIR_ERROR.INTERNAL;
2200
2202
  throw err;
2201
2203
  }
2202
2204
  if (allowed === false) {
2203
- const err = new Error('pair-success: rejected locally by the prePair callback');
2205
+ const err = new Boom('pair-success: rejected locally by the prePair callback', { statusCode: 403 });
2204
2206
  err.code = 'PAIR_REJECTED_LOCALLY';
2205
2207
  err.pairError = PAIR_ERROR.INTERNAL;
2206
2208
  throw err;
@@ -2715,12 +2717,12 @@ class WhalibmobClient extends EventEmitter {
2715
2717
  */
2716
2718
  async requestMediaRetry(info, mediaKey) {
2717
2719
  if (!this._socket || !this._connected) {
2718
- throw new Error('Not connected — cannot request a media retry');
2720
+ throw new Boom('Not connected — cannot request a media retry', { statusCode: 428 });
2719
2721
  }
2720
- if (!info || !info.id) throw new Error('requestMediaRetry: info.id is required');
2721
- if (!info.chatJid) throw new Error('requestMediaRetry: info.chatJid is required');
2722
+ if (!info || !info.id) throw new Boom('requestMediaRetry: info.id is required', { statusCode: 400 });
2723
+ if (!info.chatJid) throw new Boom('requestMediaRetry: info.chatJid is required', { statusCode: 400 });
2722
2724
  if (!mediaKey || !mediaKey.length) {
2723
- throw new Error('requestMediaRetry: the original message\'s mediaKey is required');
2725
+ throw new Boom('requestMediaRetry: the original message\'s mediaKey is required', { statusCode: 400 });
2724
2726
  }
2725
2727
 
2726
2728
  const { buildRetryReceiptNode } = require('./messages/MediaRetry');
@@ -2761,7 +2763,7 @@ class WhalibmobClient extends EventEmitter {
2761
2763
  * @returns {Promise<{alive: boolean, status: string|null, raw: object|null, error?: string}>}
2762
2764
  */
2763
2765
  async checkSessionAlive() {
2764
- if (!this._store) throw new Error('No session loaded');
2766
+ if (!this._store) throw new Boom('No session loaded', { statusCode: 428 });
2765
2767
  try {
2766
2768
  const res = await checkIfRegistered(this._store);
2767
2769
  const status = (res && (res.status || res.reason)) || null;
@@ -2804,7 +2806,7 @@ class WhalibmobClient extends EventEmitter {
2804
2806
  */
2805
2807
  async adoptCanonicalNumber(canonical) {
2806
2808
  canonical = String(canonical || '').replace(/\D/g, '');
2807
- if (!canonical) throw new Error('adoptCanonicalNumber: no number given');
2809
+ if (!canonical) throw new Boom('adoptCanonicalNumber: no number given', { statusCode: 400 });
2808
2810
  const current = String(this._store && this._store.phoneNumber || '');
2809
2811
  if (canonical === current) return { renamed: false, phoneNumber: current };
2810
2812
 
@@ -2824,8 +2826,8 @@ class WhalibmobClient extends EventEmitter {
2824
2826
  : path.join(this._baseDir, canonical);
2825
2827
 
2826
2828
  if (toDir !== fromDir && fs.existsSync(toDir)) {
2827
- throw new Error('Cannot rename session: ' + toDir +
2828
- ' already exists. Move it aside first.');
2829
+ throw new Boom('Cannot rename session: ' + toDir +
2830
+ ' already exists. Move it aside first.', { statusCode: 409 });
2829
2831
  }
2830
2832
 
2831
2833
  const moved = [];
@@ -2837,8 +2839,8 @@ class WhalibmobClient extends EventEmitter {
2837
2839
  const to = path.join(fromDir, canonical + suffix);
2838
2840
  if (!fs.existsSync(from)) continue;
2839
2841
  if (fs.existsSync(to)) {
2840
- throw new Error('Cannot rename session: ' + canonical + suffix +
2841
- ' already exists. Move it aside first.');
2842
+ throw new Boom('Cannot rename session: ' + canonical + suffix +
2843
+ ' already exists. Move it aside first.', { statusCode: 409 });
2842
2844
  }
2843
2845
  fs.renameSync(from, to);
2844
2846
  moved.push(suffix);
@@ -2852,14 +2854,14 @@ class WhalibmobClient extends EventEmitter {
2852
2854
  const renamed = canonical + name.slice(currentDigits.length);
2853
2855
  const to = path.join(fromDir, renamed);
2854
2856
  if (fs.existsSync(to)) {
2855
- throw new Error('Cannot rename session: ' + renamed +
2856
- ' already exists. Move it aside first.');
2857
+ throw new Boom('Cannot rename session: ' + renamed +
2858
+ ' already exists. Move it aside first.', { statusCode: 409 });
2857
2859
  }
2858
2860
  fs.renameSync(path.join(fromDir, name), to);
2859
2861
  moved.push(renamed);
2860
2862
  }
2861
2863
 
2862
- if (!moved.length) throw new Error('No session files found for ' + current);
2864
+ if (!moved.length) throw new Boom('No session files found for ' + current, { statusCode: 404 });
2863
2865
 
2864
2866
  if (toDir !== fromDir) {
2865
2867
  fs.renameSync(fromDir, toDir);
@@ -2869,7 +2871,7 @@ class WhalibmobClient extends EventEmitter {
2869
2871
  // The number is inside the store as well as in the filename.
2870
2872
  const sessionFile = path.join(this._sessionDir, canonical + '.json');
2871
2873
  const store = loadStore(sessionFile);
2872
- if (!store) throw new Error('Session file unreadable after rename');
2874
+ if (!store) throw new Boom('Session file unreadable after rename');
2873
2875
  store.phoneNumber = canonical;
2874
2876
  saveStore(store, sessionFile);
2875
2877
 
@@ -3375,8 +3377,8 @@ class WhalibmobClient extends EventEmitter {
3375
3377
  */
3376
3378
  async syncAppState(names, opts) {
3377
3379
  opts = opts || {};
3378
- if (!this._socket || !this._connected) throw new Error('Not connected');
3379
- if (!this._appState) throw new Error('No session — call init() first');
3380
+ if (!this._socket || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
3381
+ if (!this._appState) throw new Boom('No session — call init() first', { statusCode: 428 });
3380
3382
 
3381
3383
  const wanted = (names && names.length ? names : COLLECTIONS)
3382
3384
  .filter(n => COLLECTIONS.includes(n));
@@ -3410,12 +3412,12 @@ class WhalibmobClient extends EventEmitter {
3410
3412
  xmlns: 'w:sync:app:state'
3411
3413
  }, [new BinaryNode('sync', {}, nodes)]));
3412
3414
 
3413
- if (!resp) throw new Error('syncAppState: no reply from server (IQ timed out)');
3415
+ if (!resp) throw new Boom('syncAppState: no reply from server (IQ timed out)', { statusCode: 408 });
3414
3416
  if (resp.attrs && resp.attrs.type === 'error') {
3415
3417
  const errNode = findChild(resp, 'error');
3416
3418
  const code = errNode && errNode.attrs && errNode.attrs.code;
3417
- throw new Error('syncAppState: server rejected the request' +
3418
- (code ? ' (' + code + ')' : ''));
3419
+ throw new Boom('syncAppState: server rejected the request' +
3420
+ (code ? ' (' + code + ')' : ''), { statusCode: statusFrom(code) });
3419
3421
  }
3420
3422
 
3421
3423
  return this._applyAppStateResponse(resp, opts);
@@ -3621,10 +3623,10 @@ class WhalibmobClient extends EventEmitter {
3621
3623
 
3622
3624
  /** Fetch and decrypt an app-state blob the server pushed to the CDN. */
3623
3625
  async _fetchAppStateBlob(ref) {
3624
- if (!ref || !ref.mediaKey) throw new Error('app state blob reference is incomplete');
3626
+ if (!ref || !ref.mediaKey) throw new Boom('app state blob reference is incomplete', { statusCode: 400 });
3625
3627
  const { downloadMedia, resolveMediaUrl } = require('./MediaService');
3626
3628
  const url = resolveMediaUrl(null, ref.directPath);
3627
- if (!url) throw new Error('app state blob has no directPath');
3629
+ if (!url) throw new Boom('app state blob has no directPath', { statusCode: 400 });
3628
3630
  return downloadMedia(url, ref.mediaKey, 'WhatsApp App State Keys', {
3629
3631
  web: this._mode === 'web'
3630
3632
  });
@@ -3828,13 +3830,13 @@ class WhalibmobClient extends EventEmitter {
3828
3830
  * so what a caller sees immediately is what the other devices will see.
3829
3831
  */
3830
3832
  async _sendAppStatePatch(desc) {
3831
- if (!this._socket || !this._connected) throw new Error('Not connected');
3832
- if (!this._appState) throw new Error('No session — call init() first');
3833
+ if (!this._socket || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
3834
+ if (!this._appState) throw new Boom('No session — call init() first', { statusCode: 428 });
3833
3835
 
3834
3836
  const chosen = this._newestAppStateKey(this._appStateKeys());
3835
3837
  if (!chosen) {
3836
- throw new Error('cannot write app state yet: the primary device has not ' +
3837
- 'shared a sync key with this session');
3838
+ throw new Boom('cannot write app state yet: the primary device has not ' +
3839
+ 'shared a sync key with this session', { statusCode: 428 });
3838
3840
  }
3839
3841
 
3840
3842
  const state = this._appState.get(desc.name);
@@ -3856,12 +3858,12 @@ class WhalibmobClient extends EventEmitter {
3856
3858
  ])
3857
3859
  ]));
3858
3860
 
3859
- if (!resp) throw new Error('app state patch: no reply from server (IQ timed out)');
3861
+ if (!resp) throw new Boom('app state patch: no reply from server (IQ timed out)', { statusCode: 408 });
3860
3862
  if (resp.attrs && resp.attrs.type === 'error') {
3861
3863
  const errNode = findChild(resp, 'error');
3862
3864
  const code = errNode && errNode.attrs && errNode.attrs.code;
3863
3865
  // The server did not take it, so our state must not move on either.
3864
- throw new Error('app state patch rejected by server' + (code ? ' (' + code + ')' : ''));
3866
+ throw new Boom('app state patch rejected by server' + (code ? ' (' + code + ')' : ''), { statusCode: statusFrom(code) });
3865
3867
  }
3866
3868
 
3867
3869
  this._appState.set(desc.name, next);
@@ -4448,7 +4450,7 @@ class WhalibmobClient extends EventEmitter {
4448
4450
  if (!/no session found|no senderkeyrecord/i.test(String(err && err.message))) break;
4449
4451
  }
4450
4452
  }
4451
- throw firstErr || new Error('senderKeyDecrypt: no address to try');
4453
+ throw firstErr || new Boom('senderKeyDecrypt: no address to try');
4452
4454
  }
4453
4455
 
4454
4456
  // Try each address in turn and return the first plaintext.
@@ -4489,7 +4491,7 @@ class WhalibmobClient extends EventEmitter {
4489
4491
  }
4490
4492
  }
4491
4493
 
4492
- throw firstErr || new Error('decrypt: no address to try');
4494
+ throw firstErr || new Boom('decrypt: no address to try');
4493
4495
  }
4494
4496
 
4495
4497
  _decryptDMMessage({ node, from, participant, fromRaw, partRaw, senderPn, id, ts, dmEncNode }) {
@@ -6199,7 +6201,7 @@ class WhalibmobClient extends EventEmitter {
6199
6201
  this._fatal = true;
6200
6202
  this._reconnecting = false;
6201
6203
  this.emit('client_rejected', { reason, location: loc, message: detail, node });
6202
- this.emit('error', new Error(detail));
6204
+ this.emit('error', new Boom(detail, { statusCode: 405 }));
6203
6205
  this.disconnect();
6204
6206
  return;
6205
6207
  }
@@ -6268,7 +6270,7 @@ class WhalibmobClient extends EventEmitter {
6268
6270
  ? ('server returned IQ error' + (node.attrs.code ? ' ' + node.attrs.code : ''))
6269
6271
  : 'no media_conn node in server reply';
6270
6272
  _whaDbg('[DBG] media_conn failed: ' + reason);
6271
- this.emit('media_conn_error', new Error('Media connection refused: ' + reason));
6273
+ this.emit('media_conn_error', new Boom('Media connection refused: ' + reason, { statusCode: 502 }));
6272
6274
  return;
6273
6275
  }
6274
6276
  const auth = (connNode.attrs && connNode.attrs.auth) || '';
@@ -6623,9 +6625,9 @@ class WhalibmobClient extends EventEmitter {
6623
6625
  // @param {object} pdo see encodePeerDataOperationRequestMessage
6624
6626
  // @returns {Promise<string>} the id of the message that carried the request
6625
6627
  async sendPeerDataOperationMessage(pdo) {
6626
- if (!this._sender || !this._connected) throw new Error('Not connected');
6628
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
6627
6629
  const me = this._store && this._store.me && this._store.me.id;
6628
- if (!me) throw new Error('Not authenticated');
6630
+ if (!me) throw new Boom('Not authenticated', { statusCode: 401 });
6629
6631
 
6630
6632
  const {
6631
6633
  encodeMessage, encodeProtocolMessage,
@@ -6672,7 +6674,7 @@ class WhalibmobClient extends EventEmitter {
6672
6674
  async requestPlaceholderResend(messageKey, msgData) {
6673
6675
  if (!messageKey || !messageKey.id) return;
6674
6676
  const me = this._store && this._store.me && this._store.me.id;
6675
- if (!me) throw new Error('Not authenticated');
6677
+ if (!me) throw new Boom('Not authenticated', { statusCode: 401 });
6676
6678
 
6677
6679
  const cache = this._placeholderResendCache;
6678
6680
  if (cache.has(messageKey.id)) {
@@ -6776,9 +6778,9 @@ class WhalibmobClient extends EventEmitter {
6776
6778
  * @returns {Promise<object|null>} the server's IQ result, or null on timeout
6777
6779
  */
6778
6780
  async sendWAMBuffer(wamBuffer) {
6779
- if (!this._socket || !this._connected) throw new Error('Not connected');
6781
+ if (!this._socket || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
6780
6782
  if (!Buffer.isBuffer(wamBuffer)) {
6781
- throw new Error('sendWAMBuffer expects a Buffer from WAM.encodeWAM()');
6783
+ throw new Boom('sendWAMBuffer expects a Buffer from WAM.encodeWAM()', { statusCode: 400 });
6782
6784
  }
6783
6785
  return this._sendIq(new BinaryNode('iq', {
6784
6786
  id: this._genMsgId(),
@@ -6794,16 +6796,17 @@ class WhalibmobClient extends EventEmitter {
6794
6796
  _sendIq(node, opts = {}) {
6795
6797
  return new Promise((resolve, reject) => {
6796
6798
  const id = node.attrs && node.attrs.id;
6797
- if (!id) return reject(new Error('IQ node has no id'));
6799
+ if (!id) return reject(new Boom('IQ node has no id', { statusCode: 400 }));
6798
6800
 
6799
6801
  const timeoutMs = opts.timeoutMs === undefined ? 15000 : opts.timeoutMs;
6800
6802
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 120000) {
6801
- return reject(new Error('Invalid IQ response timeout'));
6803
+ return reject(new Boom('Invalid IQ response timeout', { statusCode: 400 }));
6802
6804
  }
6803
6805
  const noReply = (code) => {
6804
6806
  if (!opts.rejectOnNoReply) return resolve(null);
6805
- const error = new Error(code === 'IQ_TIMEOUT'
6806
- ? 'IQ response deadline exceeded' : 'Connection closed before IQ response');
6807
+ const error = new Boom(code === 'IQ_TIMEOUT'
6808
+ ? 'IQ response deadline exceeded' : 'Connection closed before IQ response',
6809
+ { statusCode: code === 'IQ_TIMEOUT' ? 408 : 428 });
6807
6810
  error.code = code;
6808
6811
  reject(error);
6809
6812
  };
@@ -7079,12 +7082,12 @@ class WhalibmobClient extends EventEmitter {
7079
7082
 
7080
7083
  const response = await this._sendIq(node);
7081
7084
  if (!response) {
7082
- throw new Error('fetchAllGroups: no reply from server (IQ timed out)');
7085
+ throw new Boom('fetchAllGroups: no reply from server (IQ timed out)', { statusCode: 408 });
7083
7086
  }
7084
7087
  if (response.attrs && response.attrs.type === 'error') {
7085
7088
  const errNode = findChild(response, 'error');
7086
7089
  const code = errNode && errNode.attrs && errNode.attrs.code;
7087
- throw new Error('fetchAllGroups: server returned error' + (code ? ' ' + code : ''));
7090
+ throw new Boom('fetchAllGroups: server returned error' + (code ? ' ' + code : ''), { statusCode: statusFrom(code) });
7088
7091
  }
7089
7092
 
7090
7093
  // The server wraps the list in a <groups> node: iq > groups > group[].
@@ -7832,37 +7835,37 @@ class WhalibmobClient extends EventEmitter {
7832
7835
  }
7833
7836
 
7834
7837
  async sendText(to, text, opts) {
7835
- if (!this._sender || !this._connected) throw new Error('Not connected');
7838
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
7836
7839
  return this._sender.sendText(to, text, opts);
7837
7840
  }
7838
7841
 
7839
7842
  async sendImage(to, data, opts) {
7840
- if (!this._sender || !this._connected) throw new Error('Not connected');
7843
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
7841
7844
  return this._sender.sendImage(to, data, opts);
7842
7845
  }
7843
7846
 
7844
7847
  async sendVideo(to, data, opts) {
7845
- if (!this._sender || !this._connected) throw new Error('Not connected');
7848
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
7846
7849
  return this._sender.sendVideo(to, data, opts);
7847
7850
  }
7848
7851
 
7849
7852
  async sendAudio(to, data, opts) {
7850
- if (!this._sender || !this._connected) throw new Error('Not connected');
7853
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
7851
7854
  return this._sender.sendAudio(to, data, opts);
7852
7855
  }
7853
7856
 
7854
7857
  async sendDocument(to, data, opts) {
7855
- if (!this._sender || !this._connected) throw new Error('Not connected');
7858
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
7856
7859
  return this._sender.sendDocument(to, data, opts);
7857
7860
  }
7858
7861
 
7859
7862
  async sendSticker(to, data, opts) {
7860
- if (!this._sender || !this._connected) throw new Error('Not connected');
7863
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
7861
7864
  return this._sender.sendSticker(to, data, opts);
7862
7865
  }
7863
7866
 
7864
7867
  async sendReaction(to, messageId, emoji, opts) {
7865
- if (!this._sender || !this._connected) throw new Error('Not connected');
7868
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
7866
7869
  return this._sender.sendReaction(to, messageId, emoji, opts);
7867
7870
  }
7868
7871
 
@@ -8100,8 +8103,8 @@ class WhalibmobClient extends EventEmitter {
8100
8103
  // 404 = no picture set, 401/403 = their privacy settings hide it. Neither
8101
8104
  // is a failure worth throwing over.
8102
8105
  if (code === '404' || code === '401' || code === '403') return null;
8103
- throw new Error('queryPictureInfo: server rejected the request' +
8104
- (code ? ' (' + code + ')' : ''));
8106
+ throw new Boom('queryPictureInfo: server rejected the request' +
8107
+ (code ? ' (' + code + ')' : ''), { statusCode: statusFrom(code) });
8105
8108
  }
8106
8109
 
8107
8110
  const wrapper = opts.isCommunity ? findChild(resp, 'pictures') : resp;
@@ -8153,8 +8156,8 @@ class WhalibmobClient extends EventEmitter {
8153
8156
  async downloadMedia(decoded, opts) {
8154
8157
  opts = opts || {};
8155
8158
  const d = (decoded && decoded.decoded) ? decoded.decoded : decoded;
8156
- if (!d || !d.type) throw new Error('downloadMedia: a decoded message is required');
8157
- if (!d.mediaKey) throw new Error('downloadMedia: this message carries no media');
8159
+ if (!d || !d.type) throw new Boom('downloadMedia: a decoded message is required', { statusCode: 400 });
8160
+ if (!d.mediaKey) throw new Boom('downloadMedia: this message carries no media', { statusCode: 400 });
8158
8161
 
8159
8162
 
8160
8163
  // A voice note is an audio message with PTT set, and a GIF a video with the
@@ -8165,9 +8168,9 @@ class WhalibmobClient extends EventEmitter {
8165
8168
  };
8166
8169
  const { downloadMedia, getMediaKeyName, resolveMediaUrl } = require('./MediaService');
8167
8170
  const url = resolveMediaUrl(d.url, d.directPath);
8168
- if (!url) throw new Error('downloadMedia: the message has no CDN location');
8171
+ if (!url) throw new Boom('downloadMedia: the message has no CDN location', { statusCode: 400 });
8169
8172
  const keyName = getMediaKeyName(KEY_NAME[d.type] || d.type);
8170
- if (!keyName) throw new Error('downloadMedia: unsupported media type "' + d.type + '"');
8173
+ if (!keyName) throw new Boom('downloadMedia: unsupported media type "' + d.type + '"', { statusCode: 400 });
8171
8174
 
8172
8175
  // Both digests go down by default. The message says what the file should
8173
8176
  // be; there is no reason to take the CDN's word for it. `verify: false`
@@ -8200,22 +8203,22 @@ class WhalibmobClient extends EventEmitter {
8200
8203
  async downloadThumbnail(decoded, opts) {
8201
8204
  opts = opts || {};
8202
8205
  const d = (decoded && decoded.decoded) ? decoded.decoded : decoded;
8203
- if (!d) throw new Error('downloadThumbnail: a decoded message is required');
8206
+ if (!d) throw new Boom('downloadThumbnail: a decoded message is required', { statusCode: 400 });
8204
8207
 
8205
8208
  const thumb = d.thumbnail;
8206
8209
  if (!thumb || !thumb.mediaKey) {
8207
- throw new Error('downloadThumbnail: this message carries no downloadable ' +
8208
- 'thumbnail (a link preview without one, or not a link at all)');
8210
+ throw new Boom('downloadThumbnail: this message carries no downloadable ' +
8211
+ 'thumbnail (a link preview without one, or not a link at all)', { statusCode: 400 });
8209
8212
  }
8210
8213
 
8211
8214
  const { downloadMedia, getThumbnailKeyName, resolveMediaUrl } =
8212
8215
  require('./MediaService');
8213
8216
  const keyName = getThumbnailKeyName(d.type === 'text' ? 'text' : d.type);
8214
8217
  if (!keyName) {
8215
- throw new Error('downloadThumbnail: no thumbnail key name for "' + d.type + '"');
8218
+ throw new Boom('downloadThumbnail: no thumbnail key name for "' + d.type + '"', { statusCode: 400 });
8216
8219
  }
8217
8220
  const url = resolveMediaUrl(null, thumb.directPath);
8218
- if (!url) throw new Error('downloadThumbnail: the thumbnail has no CDN location');
8221
+ if (!url) throw new Boom('downloadThumbnail: the thumbnail has no CDN location', { statusCode: 400 });
8219
8222
 
8220
8223
  return downloadMedia(url, thumb.mediaKey, keyName, {
8221
8224
  web: this._mode === 'web',
@@ -8267,10 +8270,10 @@ class WhalibmobClient extends EventEmitter {
8267
8270
  // The boolean describes that App State write only: false is not a pending
8268
8271
  // job, and true is not a readback of the account's server display_name.
8269
8272
  changeName(name) {
8270
- if (!this._socket || !this._connected) throw new Error('Not connected');
8273
+ if (!this._socket || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
8271
8274
  if (typeof name !== 'string') throw new TypeError('name must be a string');
8272
8275
  const clean = require('./Store').normalizePushName(name);
8273
- if (!clean) throw new Error('name must contain a non-placeholder display name');
8276
+ if (!clean) throw new Boom('name must contain a non-placeholder display name', { statusCode: 400 });
8274
8277
  name = clean;
8275
8278
  // Save intent before sending: a server observation or stale app-state
8276
8279
  // snapshot arriving during the request cannot overwrite the user's choice.
@@ -8332,8 +8335,8 @@ class WhalibmobClient extends EventEmitter {
8332
8335
  // The limit the apps impose. A longer one is dropped rather than refused,
8333
8336
  // so it would otherwise look exactly like this bug.
8334
8337
  if (Array.from(body).length > ABOUT_MAX_LENGTH) {
8335
- throw new Error('changeAbout: an about is limited to ' + ABOUT_MAX_LENGTH +
8336
- ' characters — the server drops a longer one instead of refusing it');
8338
+ throw new Boom('changeAbout: an about is limited to ' + ABOUT_MAX_LENGTH +
8339
+ ' characters — the server drops a longer one instead of refusing it', { statusCode: 400 });
8337
8340
  }
8338
8341
 
8339
8342
  const node = new BinaryNode('iq', {
@@ -8346,13 +8349,13 @@ class WhalibmobClient extends EventEmitter {
8346
8349
  ]);
8347
8350
 
8348
8351
  const resp = await this._sendIq(node);
8349
- if (!resp) throw new Error('changeAbout: no reply from server (IQ timed out)');
8352
+ if (!resp) throw new Boom('changeAbout: no reply from server (IQ timed out)', { statusCode: 408 });
8350
8353
  if (resp.attrs && resp.attrs.type === 'error') {
8351
8354
  const errNode = findChild(resp, 'error');
8352
8355
  const code = errNode && errNode.attrs && errNode.attrs.code;
8353
8356
  const errText = errNode && errNode.attrs && errNode.attrs.text;
8354
- throw new Error('changeAbout: server rejected the change' +
8355
- (code ? ' (' + code + (errText ? ' ' + errText : '') + ')' : ''));
8357
+ throw new Boom('changeAbout: server rejected the change' +
8358
+ (code ? ' (' + code + (errText ? ' ' + errText : '') + ')' : ''), { statusCode: statusFrom(code) });
8356
8359
  }
8357
8360
  return resp;
8358
8361
  }
@@ -8366,7 +8369,7 @@ class WhalibmobClient extends EventEmitter {
8366
8369
  async queryOwnAbout() {
8367
8370
  const me = this._store &&
8368
8371
  (this._store.phoneNumber || (this._store.me && this._store.me.id));
8369
- if (!me) throw new Error('queryOwnAbout: not connected');
8372
+ if (!me) throw new Boom('queryOwnAbout: not connected', { statusCode: 428 });
8370
8373
  return this.queryAbout(String(me));
8371
8374
  }
8372
8375
 
@@ -8391,7 +8394,7 @@ class WhalibmobClient extends EventEmitter {
8391
8394
  // account, then addressed about it. It is neither — it is addressed to the
8392
8395
  // server with nothing named at all.
8393
8396
  async changeProfilePicture(buf, opts) {
8394
- if (!this._store) throw new Error('Not connected');
8397
+ if (!this._store) throw new Boom('Not connected', { statusCode: 428 });
8395
8398
  opts = opts || {};
8396
8399
  const picture = (buf && !opts.raw) ? await prepareProfilePicture(buf, opts) : buf;
8397
8400
 
@@ -8404,21 +8407,21 @@ class WhalibmobClient extends EventEmitter {
8404
8407
 
8405
8408
  const resp = await this._sendIq(node);
8406
8409
  if (!resp) {
8407
- throw new Error('changeProfilePicture: no reply from server (IQ timed out). ' +
8410
+ throw new Boom('changeProfilePicture: no reply from server (IQ timed out). ' +
8408
8411
  'The server drops a picture it will not take rather than refusing it, so ' +
8409
8412
  'this usually means the image was not in the form it wants' +
8410
8413
  (opts.raw ? ' — this call passed { raw: true }, so nothing was re-encoded'
8411
- : '') + '.');
8414
+ : '') + '.', { statusCode: 408 });
8412
8415
  }
8413
8416
  if (resp.attrs && resp.attrs.type === 'error') {
8414
8417
  const errNode = findChild(resp, 'error');
8415
8418
  const code = errNode && errNode.attrs && errNode.attrs.code;
8416
8419
  if (String(code) === '406') {
8417
- throw new Error(_pictureRejected('changeProfilePicture', picture, buf, opts));
8420
+ throw new Boom(_pictureRejected('changeProfilePicture', picture, buf, opts), { statusCode: 406 });
8418
8421
  }
8419
- throw new Error('changeProfilePicture: ' +
8422
+ throw new Boom('changeProfilePicture: ' +
8420
8423
  (String(code) === '401' ? 'not authorised to change this picture'
8421
- : 'server rejected the request' + (code ? ' (' + code + ')' : '')));
8424
+ : 'server rejected the request' + (code ? ' (' + code + ')' : '')), { statusCode: statusFrom(code) });
8422
8425
  }
8423
8426
 
8424
8427
  if (!buf) return 'remove';
@@ -8449,12 +8452,12 @@ class WhalibmobClient extends EventEmitter {
8449
8452
  }, [new BinaryNode('privacy', {}, null)]);
8450
8453
 
8451
8454
  const resp = await this._sendIq(node);
8452
- if (!resp) throw new Error('queryPrivacySettings: no reply from server (IQ timed out)');
8455
+ if (!resp) throw new Boom('queryPrivacySettings: no reply from server (IQ timed out)', { statusCode: 408 });
8453
8456
  if (resp.attrs && resp.attrs.type === 'error') {
8454
8457
  const errNode = findChild(resp, 'error');
8455
8458
  const code = errNode && errNode.attrs && errNode.attrs.code;
8456
- throw new Error('queryPrivacySettings: server rejected the request' +
8457
- (code ? ' (' + code + ')' : ''));
8459
+ throw new Boom('queryPrivacySettings: server rejected the request' +
8460
+ (code ? ' (' + code + ')' : ''), { statusCode: statusFrom(code) });
8458
8461
  }
8459
8462
  const privacyNode = findChild(resp, 'privacy');
8460
8463
  this._privacySettings = this._parsePrivacySettings(privacyNode);
@@ -8493,8 +8496,8 @@ class WhalibmobClient extends EventEmitter {
8493
8496
  async changePrivacySetting(type, value, excluded) {
8494
8497
  const name = PRIVACY_NAME_ALIASES[String(type)];
8495
8498
  if (!name) {
8496
- throw new Error('changePrivacySetting: unknown setting "' + type + '" — one of ' +
8497
- Object.keys(PRIVACY_NAME_ALIASES).join(', '));
8499
+ throw new Boom('changePrivacySetting: unknown setting "' + type + '" — one of ' +
8500
+ Object.keys(PRIVACY_NAME_ALIASES).join(', '), { statusCode: 400 });
8498
8501
  }
8499
8502
 
8500
8503
  const wireValue = this._privacyWireValue(name, value);
@@ -8522,13 +8525,13 @@ class WhalibmobClient extends EventEmitter {
8522
8525
  ]);
8523
8526
 
8524
8527
  const resp = await this._sendIq(node);
8525
- if (!resp) throw new Error('changePrivacySetting: no reply from server (IQ timed out)');
8528
+ if (!resp) throw new Boom('changePrivacySetting: no reply from server (IQ timed out)', { statusCode: 408 });
8526
8529
  if (resp.attrs && resp.attrs.type === 'error') {
8527
8530
  const errNode = findChild(resp, 'error');
8528
8531
  const code = errNode && errNode.attrs && errNode.attrs.code;
8529
8532
  const text = errNode && errNode.attrs && errNode.attrs.text;
8530
- throw new Error('changePrivacySetting: server rejected ' + name + '=' + wireValue +
8531
- (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''));
8533
+ throw new Boom('changePrivacySetting: server rejected ' + name + '=' + wireValue +
8534
+ (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''), { statusCode: statusFrom(code) });
8532
8535
  }
8533
8536
 
8534
8537
  // The change is folded into the cached copy and the whole thing handed back
@@ -8553,9 +8556,9 @@ class WhalibmobClient extends EventEmitter {
8553
8556
  : (perName[raw] || PRIVACY_VALUE_ALIASES[raw] || raw);
8554
8557
 
8555
8558
  if (allowed && !allowed.includes(mapped)) {
8556
- throw new Error('changePrivacySetting: "' + value + '" is not a value ' +
8559
+ throw new Boom('changePrivacySetting: "' + value + '" is not a value ' +
8557
8560
  name + ' accepts — use one of ' + allowed.join(', ') +
8558
- '. The server ignores anything else without answering.');
8561
+ '. The server ignores anything else without answering.', { statusCode: 400 });
8559
8562
  }
8560
8563
  return mapped;
8561
8564
  }
@@ -8566,7 +8569,7 @@ class WhalibmobClient extends EventEmitter {
8566
8569
 
8567
8570
  // Edit a sent message
8568
8571
  async editMessage(origMsgId, chatJid, newText, opts) {
8569
- if (!this._sender || !this._connected) throw new Error('Not connected');
8572
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
8570
8573
  return this._sender.editMessage(origMsgId, chatJid, newText, opts);
8571
8574
  }
8572
8575
 
@@ -8594,7 +8597,7 @@ class WhalibmobClient extends EventEmitter {
8594
8597
  * @param {string} [opts.id] message id, generated when absent
8595
8598
  */
8596
8599
  async sendRawMessage(to, message, opts) {
8597
- if (!this._sender || !this._connected) throw new Error('Not connected');
8600
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
8598
8601
  return this._sender.sendRaw(to, message, opts);
8599
8602
  }
8600
8603
 
@@ -8612,15 +8615,15 @@ class WhalibmobClient extends EventEmitter {
8612
8615
  * @param {string[]} selected the option texts to vote for; empty clears the vote
8613
8616
  */
8614
8617
  async sendPollVote(chatJid, poll, selected, opts) {
8615
- if (!this._sender || !this._connected) throw new Error('Not connected');
8618
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
8616
8619
  const MS = require('./messages/MessageSecret');
8617
8620
  const { encodePollUpdateMessage, encodePollVoteMessage } = require('./proto/MessageProto');
8618
- if (!poll || !poll.id) throw new Error('sendPollVote: the poll\'s message id is required');
8621
+ if (!poll || !poll.id) throw new Boom('sendPollVote: the poll\'s message id is required', { statusCode: 400 });
8619
8622
  const chat = makeJid(chatJid);
8620
8623
  const isGroup = chat.endsWith('@g.us');
8621
8624
  const voter = this._addOnSenderFor(poll.sender, opts);
8622
8625
  const pollSender = poll.fromMe ? voter : poll.sender;
8623
- if (!pollSender) throw new Error('sendPollVote: poll.sender is required for a poll somebody else sent');
8626
+ if (!pollSender) throw new Boom('sendPollVote: poll.sender is required for a poll somebody else sent', { statusCode: 400 });
8624
8627
  const sealed = MS.encryptSecret({
8625
8628
  type: MS.SECRET_TYPE.POLL_VOTE,
8626
8629
  messageSecret: poll.encKey || poll.messageSecret,
@@ -8656,9 +8659,9 @@ class WhalibmobClient extends EventEmitter {
8656
8659
  * 604800 (default) or 2592000
8657
8660
  */
8658
8661
  async pinMessage(chatJid, target, opts) {
8659
- if (!this._sender || !this._connected) throw new Error('Not connected');
8662
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
8660
8663
  opts = opts || {};
8661
- if (!target || !target.id) throw new Error('pinMessage: the target message id is required');
8664
+ if (!target || !target.id) throw new Boom('pinMessage: the target message id is required', { statusCode: 400 });
8662
8665
  const { encodePinInChatMessage } = require('./proto/MessageProto');
8663
8666
  const chat = makeJid(chatJid);
8664
8667
  const key = { remoteJid: chat, fromMe: !!target.fromMe, id: target.id };
@@ -8707,19 +8710,19 @@ class WhalibmobClient extends EventEmitter {
8707
8710
  encEventResponse: MS.SECRET_TYPE.EVENT_RESPONSE
8708
8711
  };
8709
8712
  if (!d || !(d.type in LABEL || d.type === 'secretEncrypted')) {
8710
- throw new Error('decryptSecretMessage: this message is not an encrypted add-on');
8713
+ throw new Boom('decryptSecretMessage: this message is not an encrypted add-on', { statusCode: 400 });
8711
8714
  }
8712
8715
  const type = d.type === 'secretEncrypted'
8713
8716
  ? MS.SECRET_ENC_TYPE[d.secretEncType]
8714
8717
  : LABEL[d.type];
8715
- if (!type) throw new Error('decryptSecretMessage: unsupported secretEncType ' + d.secretEncType);
8718
+ if (!type) throw new Boom('decryptSecretMessage: unsupported secretEncType ' + d.secretEncType, { statusCode: 400 });
8716
8719
  const key = d.targetKey || {};
8717
- if (!key.id) throw new Error('decryptSecretMessage: the add-on does not name its target');
8720
+ if (!key.id) throw new Boom('decryptSecretMessage: the add-on does not name its target', { statusCode: 400 });
8718
8721
 
8719
8722
  const sender = toNonAdJid(String(
8720
8723
  opts.sender || (msg && msg.participant) || (msg && msg.from) || ''));
8721
8724
  if (!sender || sender.startsWith('@')) {
8722
- throw new Error('decryptSecretMessage: cannot tell who sent this — pass opts.sender');
8725
+ throw new Boom('decryptSecretMessage: cannot tell who sent this — pass opts.sender', { statusCode: 400 });
8723
8726
  }
8724
8727
  // Who sent the target. Ours: the add-on's own sender. In a direct chat:
8725
8728
  // the chat the key names. In a group: the participant the key names.
@@ -8765,21 +8768,21 @@ class WhalibmobClient extends EventEmitter {
8765
8768
  /** A reaction sent in a community announcement group. See `decryptSecretMessage`. */
8766
8769
  decryptReaction(msg, opts) {
8767
8770
  const d = (msg && msg.decoded) ? msg.decoded : msg;
8768
- if (!d || d.type !== 'encReaction') throw new Error('decryptReaction: this is not an encrypted reaction');
8771
+ if (!d || d.type !== 'encReaction') throw new Boom('decryptReaction: this is not an encrypted reaction', { statusCode: 400 });
8769
8772
  return this.decryptSecretMessage(msg, opts);
8770
8773
  }
8771
8774
 
8772
8775
  /** A comment on a community announcement. See `decryptSecretMessage`. */
8773
8776
  decryptComment(msg, opts) {
8774
8777
  const d = (msg && msg.decoded) ? msg.decoded : msg;
8775
- if (!d || d.type !== 'encComment') throw new Error('decryptComment: this is not an encrypted comment');
8778
+ if (!d || d.type !== 'encComment') throw new Boom('decryptComment: this is not an encrypted comment', { statusCode: 400 });
8776
8779
  return this.decryptSecretMessage(msg, opts);
8777
8780
  }
8778
8781
 
8779
8782
  /** A response to an event. See `decryptSecretMessage`. */
8780
8783
  decryptEventResponse(msg, opts) {
8781
8784
  const d = (msg && msg.decoded) ? msg.decoded : msg;
8782
- if (!d || d.type !== 'encEventResponse') throw new Error('decryptEventResponse: this is not an event response');
8785
+ if (!d || d.type !== 'encEventResponse') throw new Boom('decryptEventResponse: this is not an event response', { statusCode: 400 });
8783
8786
  return this.decryptSecretMessage(msg, opts);
8784
8787
  }
8785
8788
 
@@ -8787,7 +8790,7 @@ class WhalibmobClient extends EventEmitter {
8787
8790
  // fromMe: whether the message was sent by us
8788
8791
  // forEveryone: true = revoke for all, false = delete locally only
8789
8792
  async deleteMessage(origMsgId, chatJid, fromMe, forEveryone, opts) {
8790
- if (!this._sender || !this._connected) throw new Error('Not connected');
8793
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
8791
8794
  return this._sender.deleteMessage(origMsgId, chatJid, fromMe, forEveryone, opts);
8792
8795
  }
8793
8796
 
@@ -8851,12 +8854,12 @@ class WhalibmobClient extends EventEmitter {
8851
8854
  xmlns: 'abt'
8852
8855
  }, [new BinaryNode('props', propsAttrs, null)]));
8853
8856
 
8854
- if (!resp) throw new Error('queryAbProps: no reply from server (IQ timed out)');
8857
+ if (!resp) throw new Boom('queryAbProps: no reply from server (IQ timed out)', { statusCode: 408 });
8855
8858
  if (resp.attrs && resp.attrs.type === 'error') {
8856
8859
  const errNode = findChild(resp, 'error');
8857
8860
  const code = errNode && errNode.attrs && errNode.attrs.code;
8858
- throw new Error('queryAbProps: server rejected the request' +
8859
- (code ? ' (' + code + ')' : ''));
8861
+ throw new Boom('queryAbProps: server rejected the request' +
8862
+ (code ? ' (' + code + ')' : ''), { statusCode: statusFrom(code) });
8860
8863
  }
8861
8864
 
8862
8865
  const parsed = this._parseAbProps(findChild(resp, 'props'));
@@ -9005,12 +9008,12 @@ class WhalibmobClient extends EventEmitter {
9005
9008
  * `jids` maps each registered number to the JID the server gave it.
9006
9009
  */
9007
9010
  async syncContacts(phones, opts) {
9008
- if (!this._connected) throw new Error('Not connected');
9011
+ if (!this._connected) throw new Boom('Not connected', { statusCode: 428 });
9009
9012
  // _devMgr is torn down on close and rebuilt on init. Saying so beats the
9010
9013
  // null dereference a caller would otherwise get from a session that is
9011
9014
  // connected but has been through a teardown.
9012
- if (!this._devMgr) throw new Error('syncContacts: no device manager — the session is not initialised');
9013
- if (!Array.isArray(phones)) throw new Error('syncContacts: phones must be an array');
9015
+ if (!this._devMgr) throw new Boom('syncContacts: no device manager — the session is not initialised', { statusCode: 428 });
9016
+ if (!Array.isArray(phones)) throw new Boom('syncContacts: phones must be an array', { statusCode: 400 });
9014
9017
 
9015
9018
  opts = opts || {};
9016
9019
  const mode = opts.mode || 'full';
@@ -9104,10 +9107,10 @@ class WhalibmobClient extends EventEmitter {
9104
9107
  // verification replies carry verify_email/code_match, not email/do_verify.
9105
9108
 
9106
9109
  _assertEmailChannel(what) {
9107
- if (!this._connected) throw new Error(what + ': Not connected');
9110
+ if (!this._connected) throw new Boom(what + ': Not connected', { statusCode: 428 });
9108
9111
  if (this._mode === 'web') {
9109
- throw new Error(what + ': the account email is a primary-account feature — ' +
9110
- 'a companion (web) link cannot bind or verify it');
9112
+ throw new Boom(what + ': the account email is a primary-account feature — ' +
9113
+ 'a companion (web) link cannot bind or verify it', { statusCode: 405 });
9111
9114
  }
9112
9115
  }
9113
9116
 
@@ -9116,8 +9119,9 @@ class WhalibmobClient extends EventEmitter {
9116
9119
  ? 'no matching reply within 32 seconds'
9117
9120
  : code === 'IQ_DISCONNECTED' ? 'connection closed before the reply'
9118
9121
  : 'request outcome could not be confirmed';
9119
- const error = new Error(what + ': ' + reason +
9120
- '; outcome unknown. Check getEmailStatus() before repeating a change or requesting another code.');
9122
+ const error = new Boom(what + ': ' + reason +
9123
+ '; outcome unknown. Check getEmailStatus() before repeating a change or requesting another code.',
9124
+ { statusCode: code === 'IQ_TIMEOUT' ? 408 : code === 'IQ_DISCONNECTED' ? 428 : 500 });
9121
9125
  error.code = code === 'IQ_TIMEOUT' ? 'EMAIL_IQ_TIMEOUT'
9122
9126
  : code === 'IQ_DISCONNECTED' ? 'EMAIL_IQ_DISCONNECTED' : 'EMAIL_IQ_UNCERTAIN';
9123
9127
  error.operation = what;
@@ -9160,8 +9164,8 @@ class WhalibmobClient extends EventEmitter {
9160
9164
  '536': 'the code is incorrect',
9161
9165
  '537': 'too many wrong codes — request a new one'
9162
9166
  }[code];
9163
- return new Error(what + ': server rejected the request' +
9164
- (code ? ' (' + code + (text ? ' — ' + text : '') + ')' : ''));
9167
+ return new Boom(what + ': server rejected the request' +
9168
+ (code ? ' (' + code + (text ? ' — ' + text : '') + ')' : ''), { statusCode: statusFrom(code) });
9165
9169
  }
9166
9170
 
9167
9171
  _parseEmailStatus(resp) {
@@ -9210,7 +9214,7 @@ class WhalibmobClient extends EventEmitter {
9210
9214
  opts = opts || {};
9211
9215
  const addr = String(email == null ? '' : email).trim();
9212
9216
  if (!addr || addr.length > 320) {
9213
- throw new Error('setEmail: email must be between 1 and 320 characters');
9217
+ throw new Boom('setEmail: email must be between 1 and 320 characters', { statusCode: 400 });
9214
9218
  }
9215
9219
  const emailChildren = [new BinaryNode('email_address', {}, Buffer.from(addr, 'utf8'))];
9216
9220
  const resp = await this._sendEmailIq('setEmail', new BinaryNode('iq', {
@@ -9236,7 +9240,7 @@ class WhalibmobClient extends EventEmitter {
9236
9240
  const lc = String(opts.lc || opts.locale || 'US');
9237
9241
  for (const [name, val] of [['lg', lg], ['lc', lc]]) {
9238
9242
  if (val.length < 2 || val.length > 3) {
9239
- throw new Error('requestEmailCode: ' + name + ' must be 2-3 characters');
9243
+ throw new Boom('requestEmailCode: ' + name + ' must be 2-3 characters', { statusCode: 400 });
9240
9244
  }
9241
9245
  }
9242
9246
  const resp = await this._sendEmailIq('requestEmailCode', new BinaryNode('iq', {
@@ -9259,7 +9263,7 @@ class WhalibmobClient extends EventEmitter {
9259
9263
  async verifyEmailCode(code) {
9260
9264
  this._assertEmailChannel('verifyEmailCode');
9261
9265
  const digits = String(code == null ? '' : code).replace(/\D/g, '');
9262
- if (digits.length !== 6) throw new Error('verifyEmailCode: code must be exactly 6 digits');
9266
+ if (digits.length !== 6) throw new Boom('verifyEmailCode: code must be exactly 6 digits', { statusCode: 400 });
9263
9267
  const resp = await this._sendEmailIq('verifyEmailCode', new BinaryNode('iq', {
9264
9268
  id: this._genMsgId(),
9265
9269
  to: 's.whatsapp.net',
@@ -9299,7 +9303,7 @@ class WhalibmobClient extends EventEmitter {
9299
9303
  opts = opts || {};
9300
9304
  const context = opts.context === undefined ? 'settings' : opts.context;
9301
9305
  if (context !== 'settings' && context !== 'onboarding') {
9302
- throw new Error('confirmEmail: context must be settings or onboarding');
9306
+ throw new Boom('confirmEmail: context must be settings or onboarding', { statusCode: 400 });
9303
9307
  }
9304
9308
  const children = [new BinaryNode('context', {}, Buffer.from(context, 'utf8'))];
9305
9309
  const resp = await this._sendEmailIq('confirmEmail', new BinaryNode('iq', {
@@ -9358,8 +9362,8 @@ class WhalibmobClient extends EventEmitter {
9358
9362
  }
9359
9363
 
9360
9364
  async queryTosNotices(noticeIds) {
9361
- if (!this._connected) throw new Error('Not connected');
9362
- if (!Array.isArray(noticeIds)) throw new Error('queryTosNotices: noticeIds must be an array');
9365
+ if (!this._connected) throw new Boom('Not connected', { statusCode: 428 });
9366
+ if (!Array.isArray(noticeIds)) throw new Boom('queryTosNotices: noticeIds must be an array', { statusCode: 400 });
9363
9367
 
9364
9368
  const ids = noticeIds.map(id => String(id)).filter(Boolean);
9365
9369
  const resp = await this._sendIq(new BinaryNode('iq', {
@@ -9370,12 +9374,12 @@ class WhalibmobClient extends EventEmitter {
9370
9374
  }, [new BinaryNode('request', {},
9371
9375
  ids.map(id => new BinaryNode('notice', { id }, null)))]));
9372
9376
 
9373
- if (!resp) throw new Error('queryTosNotices: no reply from server (IQ timed out)');
9377
+ if (!resp) throw new Boom('queryTosNotices: no reply from server (IQ timed out)', { statusCode: 408 });
9374
9378
  if (resp.attrs && resp.attrs.type === 'error') {
9375
9379
  const errNode = findChild(resp, 'error');
9376
9380
  const code = errNode && errNode.attrs && errNode.attrs.code;
9377
- throw new Error('queryTosNotices: server rejected the request' +
9378
- (code ? ' (' + code + ')' : ''));
9381
+ throw new Boom('queryTosNotices: server rejected the request' +
9382
+ (code ? ' (' + code + ')' : ''), { statusCode: statusFrom(code) });
9379
9383
  }
9380
9384
 
9381
9385
  const parsed = this._parseTosNotices(findChild(resp, 'tos'));
@@ -9413,9 +9417,9 @@ class WhalibmobClient extends EventEmitter {
9413
9417
  * @returns {Promise<{ok: true, raw: any}>}
9414
9418
  */
9415
9419
  async acceptTosNotices(noticeIds) {
9416
- if (!this._connected) throw new Error('Not connected');
9420
+ if (!this._connected) throw new Boom('Not connected', { statusCode: 428 });
9417
9421
  if (!Array.isArray(noticeIds) || noticeIds.length === 0) {
9418
- throw new Error('acceptTosNotices: noticeIds must be a non-empty array');
9422
+ throw new Boom('acceptTosNotices: noticeIds must be a non-empty array', { statusCode: 400 });
9419
9423
  }
9420
9424
 
9421
9425
  const ids = noticeIds.map(id => String(id)).filter(Boolean);
@@ -9427,12 +9431,12 @@ class WhalibmobClient extends EventEmitter {
9427
9431
  }, [new BinaryNode('request', { type: 'session_update' },
9428
9432
  ids.map(id => new BinaryNode('notice', { id }, null)))]));
9429
9433
 
9430
- if (!resp) throw new Error('acceptTosNotices: no reply from server (IQ timed out)');
9434
+ if (!resp) throw new Boom('acceptTosNotices: no reply from server (IQ timed out)', { statusCode: 408 });
9431
9435
  if (resp.attrs && resp.attrs.type === 'error') {
9432
9436
  const errNode = findChild(resp, 'error');
9433
9437
  const code = errNode && errNode.attrs && errNode.attrs.code;
9434
- throw new Error('acceptTosNotices: server rejected the request' +
9435
- (code ? ' (' + code + ')' : ''));
9438
+ throw new Boom('acceptTosNotices: server rejected the request' +
9439
+ (code ? ' (' + code + ')' : ''), { statusCode: statusFrom(code) });
9436
9440
  }
9437
9441
 
9438
9442
  for (const id of ids) this._tosAccepted.set(id, true);
@@ -9447,9 +9451,9 @@ class WhalibmobClient extends EventEmitter {
9447
9451
  * @returns {Promise<{ok: true, raw: any}>}
9448
9452
  */
9449
9453
  async clearTosNotice(noticeId) {
9450
- if (!this._connected) throw new Error('Not connected');
9454
+ if (!this._connected) throw new Boom('Not connected', { statusCode: 428 });
9451
9455
  const id = String(noticeId || '');
9452
- if (!id) throw new Error('clearTosNotice: noticeId is required');
9456
+ if (!id) throw new Boom('clearTosNotice: noticeId is required', { statusCode: 400 });
9453
9457
 
9454
9458
  const resp = await this._sendIq(new BinaryNode('iq', {
9455
9459
  id: this._genMsgId(),
@@ -9458,12 +9462,12 @@ class WhalibmobClient extends EventEmitter {
9458
9462
  xmlns: 'tos'
9459
9463
  }, [new BinaryNode('delete', { id }, null)]));
9460
9464
 
9461
- if (!resp) throw new Error('clearTosNotice: no reply from server (IQ timed out)');
9465
+ if (!resp) throw new Boom('clearTosNotice: no reply from server (IQ timed out)', { statusCode: 408 });
9462
9466
  if (resp.attrs && resp.attrs.type === 'error') {
9463
9467
  const errNode = findChild(resp, 'error');
9464
9468
  const code = errNode && errNode.attrs && errNode.attrs.code;
9465
- throw new Error('clearTosNotice: server rejected the request' +
9466
- (code ? ' (' + code + ')' : ''));
9469
+ throw new Boom('clearTosNotice: server rejected the request' +
9470
+ (code ? ' (' + code + ')' : ''), { statusCode: statusFrom(code) });
9467
9471
  }
9468
9472
 
9469
9473
  this._tosAccepted.set(id, false);
@@ -9615,7 +9619,7 @@ class WhalibmobClient extends EventEmitter {
9615
9619
  // Text posted with a background or font becomes an ExtendedTextMessage, which
9616
9620
  // is what carries them; plain text stays a plain conversation.
9617
9621
  async sendStatus(content, opts) {
9618
- if (!this._sender || !this._connected) throw new Error('Not connected');
9622
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
9619
9623
  opts = Object.assign({},
9620
9624
  (content && typeof content === 'object') ? content : {},
9621
9625
  opts || {});
@@ -9647,7 +9651,7 @@ class WhalibmobClient extends EventEmitter {
9647
9651
  // If msg is a decoded message object (from the 'message' event), re-encode the original
9648
9652
  // media/text without re-uploading.
9649
9653
  async forwardMessage(to, msg, contextInfo) {
9650
- if (!this._sender || !this._connected) throw new Error('Not connected');
9654
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
9651
9655
  if (typeof msg === 'string') {
9652
9656
  const ctx = Object.assign({ forwardingScore: 1, isForwarded: true }, contextInfo || {});
9653
9657
  return this._sender.sendText(to, msg, { contextInfo: ctx });
@@ -9663,7 +9667,7 @@ class WhalibmobClient extends EventEmitter {
9663
9667
  // opts.id: pre-set message ID
9664
9668
  // Returns: { id, encKey } — encKey is a 32-byte Buffer needed to decrypt votes
9665
9669
  async sendPoll(to, question, options, selectableCount, opts) {
9666
- if (!this._sender || !this._connected) throw new Error('Not connected');
9670
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
9667
9671
  return this._sender.sendPoll(to, question, options, selectableCount, opts);
9668
9672
  }
9669
9673
 
@@ -9704,20 +9708,20 @@ class WhalibmobClient extends EventEmitter {
9704
9708
  opts = opts || {};
9705
9709
  const d = (vote && vote.decoded) ? vote.decoded : vote;
9706
9710
  if (!d || d.type !== 'pollVote') {
9707
- throw new Error('decryptPollVote: this is not a vote on a poll');
9711
+ throw new Boom('decryptPollVote: this is not a vote on a poll', { statusCode: 400 });
9708
9712
  }
9709
9713
  if (!d.encPayload || !d.encIv) {
9710
- throw new Error('decryptPollVote: the vote carries no encrypted ballot');
9714
+ throw new Boom('decryptPollVote: the vote carries no encrypted ballot', { statusCode: 400 });
9711
9715
  }
9712
9716
  const secret = opts.encKey || opts.messageSecret;
9713
9717
  if (!secret || secret.length !== 32) {
9714
- throw new Error('decryptPollVote: the poll\'s 32-byte encKey is required — ' +
9715
- 'it is what sendPoll returned, or decoded.encKey on a poll we received');
9718
+ throw new Boom('decryptPollVote: the poll\'s 32-byte encKey is required — ' +
9719
+ 'it is what sendPoll returned, or decoded.encKey on a poll we received', { statusCode: 400 });
9716
9720
  }
9717
9721
 
9718
9722
  const key = d.pollKey || {};
9719
9723
  const pollId = String(key.id || '');
9720
- if (!pollId) throw new Error('decryptPollVote: the vote does not name a poll');
9724
+ if (!pollId) throw new Boom('decryptPollVote: the vote does not name a poll', { statusCode: 400 });
9721
9725
 
9722
9726
  // Who voted, and who the poll belongs to. `fromMe` on the key means the
9723
9727
  // poll and the vote came from the same account, which is the one case the
@@ -9725,7 +9729,7 @@ class WhalibmobClient extends EventEmitter {
9725
9729
  const voter = toNonAdJid(String(
9726
9730
  opts.voter || (vote && vote.participant) || (vote && vote.from) || ''));
9727
9731
  if (!voter || voter.startsWith('@')) {
9728
- throw new Error('decryptPollVote: cannot tell who cast this vote — pass opts.voter');
9732
+ throw new Boom('decryptPollVote: cannot tell who cast this vote — pass opts.voter', { statusCode: 400 });
9729
9733
  }
9730
9734
  // In a group the key's remoteJid is the group; the poll's author is the
9731
9735
  // participant it names.
@@ -9758,8 +9762,8 @@ class WhalibmobClient extends EventEmitter {
9758
9762
  dec.setAuthTag(tag);
9759
9763
  plaintext = Buffer.concat([dec.update(ciphertext), dec.final()]);
9760
9764
  } catch (_) {
9761
- throw new Error('decryptPollVote: the ballot would not open — wrong encKey, ' +
9762
- 'or the wrong voter/pollSender for this poll');
9765
+ throw new Boom('decryptPollVote: the ballot would not open — wrong encKey, ' +
9766
+ 'or the wrong voter/pollSender for this poll', { statusCode: 400 });
9763
9767
  }
9764
9768
 
9765
9769
  // PollVoteMessage { selectedOptions = 1, repeated bytes } — each entry is
@@ -9803,13 +9807,13 @@ class WhalibmobClient extends EventEmitter {
9803
9807
  */
9804
9808
  async logout() {
9805
9809
  if (this._mode !== 'web') {
9806
- throw new Error('logout: only a companion can unlink itself — a session ' +
9807
- 'that registered its own number has nothing to unlink from');
9810
+ throw new Boom('logout: only a companion can unlink itself — a session ' +
9811
+ 'that registered its own number has nothing to unlink from', { statusCode: 405 });
9808
9812
  }
9809
- if (!this._socket || !this._connected) throw new Error('Not connected');
9813
+ if (!this._socket || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
9810
9814
 
9811
9815
  const ownJid = toNonAdJid(this._ownDeviceJid() || '');
9812
- if (!ownJid || ownJid.startsWith('@')) throw new Error('logout: not logged in');
9816
+ if (!ownJid || ownJid.startsWith('@')) throw new Boom('logout: not logged in', { statusCode: 401 });
9813
9817
 
9814
9818
  let accepted = false;
9815
9819
  try {
@@ -9836,7 +9840,7 @@ class WhalibmobClient extends EventEmitter {
9836
9840
  // sendLocation(to, latitude, longitude, opts)
9837
9841
  // opts: { name, address, url, id, contextInfo }
9838
9842
  async sendLocation(to, latitude, longitude, opts) {
9839
- if (!this._sender || !this._connected) throw new Error('Not connected');
9843
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
9840
9844
  return this._sender.sendLocation(to, latitude, longitude, opts);
9841
9845
  }
9842
9846
 
@@ -9844,7 +9848,7 @@ class WhalibmobClient extends EventEmitter {
9844
9848
  // sendContact(to, displayName, vcard, opts)
9845
9849
  // vcard is a vCard v3 string e.g. "BEGIN:VCARD\nVERSION:3.0\nFN:Ion Popescu\nTEL:+40712345678\nEND:VCARD"
9846
9850
  async sendContact(to, displayName, vcard, opts) {
9847
- if (!this._sender || !this._connected) throw new Error('Not connected');
9851
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
9848
9852
  return this._sender.sendContact(to, displayName, vcard, opts);
9849
9853
  }
9850
9854
 
@@ -9852,7 +9856,7 @@ class WhalibmobClient extends EventEmitter {
9852
9856
  // Sends a text message that quotes/replies to another message.
9853
9857
  // senderJid — JID of the original sender (same as `to` for DMs; member JID for groups).
9854
9858
  async sendReply(to, quotedMsgId, senderJid, text, opts) {
9855
- if (!this._sender || !this._connected) throw new Error('Not connected');
9859
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
9856
9860
  return this._sender.sendReply(to, quotedMsgId, senderJid, text, opts);
9857
9861
  }
9858
9862
 
@@ -10148,8 +10152,8 @@ class WhalibmobClient extends EventEmitter {
10148
10152
  }
10149
10153
 
10150
10154
  if (payload == null || typeof payload !== 'object') {
10151
- const err = new Error('the server answered ' + JSON.stringify(payload) +
10152
- ', which says nothing about a restriction either way');
10155
+ const err = new Boom('the server answered ' + JSON.stringify(payload) +
10156
+ ', which says nothing about a restriction either way', { statusCode: 502 });
10153
10157
  err.mexDecoded = payload;
10154
10158
  throw err;
10155
10159
  }
@@ -10228,7 +10232,7 @@ class WhalibmobClient extends EventEmitter {
10228
10232
  xmlns: 'w:mex'
10229
10233
  }, [new BinaryNode('query', { query_id: String(queryId) }, body)]));
10230
10234
 
10231
- if (!resp) throw new Error('mex query ' + queryId + ': no reply from server (IQ timed out)');
10235
+ if (!resp) throw new Boom('mex query ' + queryId + ': no reply from server (IQ timed out)', { statusCode: 408 });
10232
10236
 
10233
10237
  // An <error> child is the refusal whether or not the iq is typed as one.
10234
10238
  const errNode = (resp.attrs && resp.attrs.type === 'error')
@@ -10237,8 +10241,8 @@ class WhalibmobClient extends EventEmitter {
10237
10241
  const a = errNode.attrs || {};
10238
10242
  const code = a.code ? String(a.code) : null;
10239
10243
  const text = a.text ? String(a.text) : null;
10240
- throw new Error('mex query ' + queryId + ': server rejected the request' +
10241
- (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''));
10244
+ throw new Boom('mex query ' + queryId + ': server rejected the request' +
10245
+ (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''), { statusCode: statusFrom(code) });
10242
10246
  }
10243
10247
 
10244
10248
  // The JSON normally sits in <result>, but not every build wraps it the same
@@ -10247,8 +10251,8 @@ class WhalibmobClient extends EventEmitter {
10247
10251
  const json = this._mexJsonFrom(resp);
10248
10252
  if (json) {
10249
10253
  if (json.errors && json.errors.length) {
10250
- throw new Error('mex query ' + queryId + ': ' +
10251
- json.errors.map(e => (e && e.message) || 'unknown error').join(', '));
10254
+ throw new Boom('mex query ' + queryId + ': ' +
10255
+ json.errors.map(e => (e && e.message) || 'unknown error').join(', '), { statusCode: 502 });
10252
10256
  }
10253
10257
  return dataPath ? (json.data && json.data[dataPath]) : json.data;
10254
10258
  }
@@ -10268,9 +10272,9 @@ class WhalibmobClient extends EventEmitter {
10268
10272
  try {
10269
10273
  decoded = decodeArgo(raw);
10270
10274
  } catch (e) {
10271
- const err = new Error('mex query ' + queryId + ': the reply is ' +
10275
+ const err = new Boom('mex query ' + queryId + ': the reply is ' +
10272
10276
  (format ? '"' + format + '"' : 'binary') + ' and could not be decoded — ' +
10273
- e.message + ' (' + raw.length + ' bytes: ' + raw.toString('hex') + ')');
10277
+ e.message + ' (' + raw.length + ' bytes: ' + raw.toString('hex') + ')', { statusCode: 502 });
10274
10278
  err.mexFormat = format ? String(format) : null;
10275
10279
  err.mexPayload = raw;
10276
10280
  throw err;
@@ -10279,8 +10283,8 @@ class WhalibmobClient extends EventEmitter {
10279
10283
 
10280
10284
  if (decoded && typeof decoded === 'object') {
10281
10285
  if (decoded.errors && decoded.errors.length) {
10282
- throw new Error('mex query ' + queryId + ': ' +
10283
- decoded.errors.map(e => (e && e.message) || 'unknown error').join(', '));
10286
+ throw new Boom('mex query ' + queryId + ': ' +
10287
+ decoded.errors.map(e => (e && e.message) || 'unknown error').join(', '), { statusCode: 502 });
10284
10288
  }
10285
10289
  if (decoded.data !== undefined) {
10286
10290
  return dataPath ? (decoded.data && decoded.data[dataPath]) : decoded.data;
@@ -10295,9 +10299,9 @@ class WhalibmobClient extends EventEmitter {
10295
10299
  }
10296
10300
 
10297
10301
  if (format && String(format).toLowerCase() !== 'json') {
10298
- const err = new Error('mex query ' + queryId + ': the server answered in "' +
10302
+ const err = new Boom('mex query ' + queryId + ': the server answered in "' +
10299
10303
  format + '", which this library cannot read' +
10300
- (raw ? ' (' + raw.length + ' bytes: ' + raw.toString('hex') + ')' : ''));
10304
+ (raw ? ' (' + raw.length + ' bytes: ' + raw.toString('hex') + ')' : ''), { statusCode: 502 });
10301
10305
  err.mexFormat = String(format);
10302
10306
  err.mexPayload = raw || null;
10303
10307
  _whaDbg('[DBG] MEX_REPLY_FORMAT ' + format + ' — cannot decode');
@@ -10305,8 +10309,8 @@ class WhalibmobClient extends EventEmitter {
10305
10309
  }
10306
10310
 
10307
10311
  _whaDbg('[DBG] MEX_REPLY_UNPARSED ' + JSON.stringify(describeNodeBriefly(resp)));
10308
- throw new Error('mex query ' + queryId + ': the reply carried no JSON — ' +
10309
- describeNodeBriefly(resp));
10312
+ throw new Boom('mex query ' + queryId + ': the reply carried no JSON — ' +
10313
+ describeNodeBriefly(resp), { statusCode: 502 });
10310
10314
  }
10311
10315
 
10312
10316
  // Walk the reply for the first node whose content parses as a JSON object.
@@ -10383,8 +10387,8 @@ class WhalibmobClient extends EventEmitter {
10383
10387
  const format = resultNode && resultNode.attrs && resultNode.attrs.format;
10384
10388
  if (format && String(format).toLowerCase() !== 'json') {
10385
10389
  _whaDbg('[DBG] NEWSLETTER reply format=' + format + ' — cannot decode');
10386
- const err = new Error('the server answered in "' + format +
10387
- '" rather than JSON, which this library cannot read');
10390
+ const err = new Boom('the server answered in "' + format +
10391
+ '" rather than JSON, which this library cannot read', { statusCode: 502 });
10388
10392
  err.mexFormat = String(format);
10389
10393
  throw err;
10390
10394
  }
@@ -10411,7 +10415,7 @@ class WhalibmobClient extends EventEmitter {
10411
10415
  // The stanza differs from regular messages: no <participants> or <enc>, uses
10412
10416
  // <plaintext-body> and carries server_id + edit attributes.
10413
10417
  async sendNewsletterText(newsletterJid, text) {
10414
- if (!this._socket || !this._connected) throw new Error('Not connected');
10418
+ if (!this._socket || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
10415
10419
  const jid = makeJid(newsletterJid, 'newsletter');
10416
10420
  // A channel post is an encoded Message in <plaintext>, the same shape the
10417
10421
  // posts we receive have. This used to send the bare text in a node of
@@ -10468,15 +10472,15 @@ class WhalibmobClient extends EventEmitter {
10468
10472
 
10469
10473
  // Throws on no answer and on an <iq type="error">, naming the step.
10470
10474
  async _iqOrThrow(node, what) {
10471
- if (!this._socket || !this._connected) throw new Error('Not connected');
10475
+ if (!this._socket || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
10472
10476
  const resp = await this._sendIq(node);
10473
- if (!resp) throw new Error(what + ': no reply from the server');
10477
+ if (!resp) throw new Boom(what + ': no reply from the server', { statusCode: 408 });
10474
10478
  if (resp.attrs && resp.attrs.type === 'error') {
10475
10479
  const e = findChild(resp, 'error');
10476
10480
  const code = e && e.attrs && e.attrs.code != null ? String(e.attrs.code) : null;
10477
10481
  const text = e && e.attrs && e.attrs.text ? String(e.attrs.text) : null;
10478
- const err = new Error(what + ': refused by the server' +
10479
- (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''));
10482
+ const err = new Boom(what + ': refused by the server' +
10483
+ (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''), { statusCode: statusFrom(code) });
10480
10484
  err.code = code; err.text = text;
10481
10485
  throw err;
10482
10486
  }
@@ -10497,7 +10501,7 @@ class WhalibmobClient extends EventEmitter {
10497
10501
  id: this._genMsgId(), to: 's.whatsapp.net', type: 'get', xmlns: 'newsletter'
10498
10502
  }, [new BinaryNode('messages', attrs, null)]), 'newsletter messages');
10499
10503
  const messages = findChild(resp, 'messages');
10500
- if (!messages) throw new Error('newsletter messages: the reply carried no messages');
10504
+ if (!messages) throw new Boom('newsletter messages: the reply carried no messages', { statusCode: 502 });
10501
10505
  return this._parseNewsletterMessages(messages);
10502
10506
  }
10503
10507
 
@@ -10517,7 +10521,7 @@ class WhalibmobClient extends EventEmitter {
10517
10521
  id: this._genMsgId(), to: jid, type: 'get', xmlns: 'newsletter'
10518
10522
  }, [new BinaryNode('message_updates', attrs, null)]), 'newsletter message updates');
10519
10523
  const messages = findChild(findChild(resp, 'message_updates'), 'messages');
10520
- if (!messages) throw new Error('newsletter message updates: the reply carried no messages');
10524
+ if (!messages) throw new Boom('newsletter message updates: the reply carried no messages', { statusCode: 502 });
10521
10525
  return this._parseNewsletterMessages(messages);
10522
10526
  }
10523
10527
 
@@ -10537,10 +10541,10 @@ class WhalibmobClient extends EventEmitter {
10537
10541
 
10538
10542
  /** Count posts as viewed. `serverIds` are the posts' server ids. */
10539
10543
  async markNewsletterViewed(newsletterJid, serverIds) {
10540
- if (!this._socket || !this._connected) throw new Error('Not connected');
10544
+ if (!this._socket || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
10541
10545
  const jid = makeJid(newsletterJid, 'newsletter');
10542
10546
  const ids = (Array.isArray(serverIds) ? serverIds : [serverIds]).filter(v => v != null);
10543
- if (!ids.length) throw new Error('markNewsletterViewed: at least one server id is required');
10547
+ if (!ids.length) throw new Boom('markNewsletterViewed: at least one server id is required', { statusCode: 400 });
10544
10548
  this._socket.sendNode(new BinaryNode('receipt', {
10545
10549
  to: jid, type: 'view', id: this._genMsgId()
10546
10550
  }, [new BinaryNode('list', {}, ids.map(id => new BinaryNode('item', { server_id: String(id) }, null)))]));
@@ -10548,8 +10552,8 @@ class WhalibmobClient extends EventEmitter {
10548
10552
 
10549
10553
  /** React to a channel post. An empty `reaction` takes ours back. */
10550
10554
  async sendNewsletterReaction(newsletterJid, serverId, reaction, opts) {
10551
- if (!this._socket || !this._connected) throw new Error('Not connected');
10552
- if (serverId == null) throw new Error('sendNewsletterReaction: the post\'s server id is required');
10555
+ if (!this._socket || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
10556
+ if (serverId == null) throw new Boom('sendNewsletterReaction: the post\'s server id is required', { statusCode: 400 });
10553
10557
  const jid = makeJid(newsletterJid, 'newsletter');
10554
10558
  const id = (opts && opts.id) || this._genMsgId();
10555
10559
  const attrs = { to: jid, id, server_id: String(serverId), type: 'reaction' };
@@ -10577,7 +10581,7 @@ class WhalibmobClient extends EventEmitter {
10577
10581
  /** A channel's metadata from its invite link or the code at the end of it. */
10578
10582
  async getNewsletterInfoWithInvite(linkOrCode) {
10579
10583
  const key = String(linkOrCode || '').replace(/^https?:\/\/(www\.)?whatsapp\.com\/channel\//i, '').trim();
10580
- if (!key) throw new Error('getNewsletterInfoWithInvite: an invite link or code is required');
10584
+ if (!key) throw new Boom('getNewsletterInfoWithInvite: an invite link or code is required', { statusCode: 400 });
10581
10585
  return this._mexQuery('6563316087068696', {
10582
10586
  fetch_creation_time: true, fetch_full_image: true, fetch_viewer_metadata: false,
10583
10587
  input: { key, type: 'INVITE' }
@@ -10589,9 +10593,9 @@ class WhalibmobClient extends EventEmitter {
10589
10593
  * @param {object} [opts] `{ id, type, mediaType, mediaId, edit }`
10590
10594
  */
10591
10595
  async sendNewsletterMessage(newsletterJid, message, opts) {
10592
- if (!this._socket || !this._connected) throw new Error('Not connected');
10596
+ if (!this._socket || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
10593
10597
  if (!Buffer.isBuffer(message) || !message.length) {
10594
- throw new Error('sendNewsletterMessage: message must be a non-empty Buffer holding an encoded Message');
10598
+ throw new Boom('sendNewsletterMessage: message must be a non-empty Buffer holding an encoded Message', { statusCode: 400 });
10595
10599
  }
10596
10600
  opts = opts || {};
10597
10601
  const jid = makeJid(newsletterJid, 'newsletter');
@@ -10655,7 +10659,7 @@ class WhalibmobClient extends EventEmitter {
10655
10659
  id: this._genMsgId(), to: jid, type: 'get', xmlns: 'w:g2'
10656
10660
  }, [new BinaryNode('sub_groups', {}, null)]), 'sub groups');
10657
10661
  const holder = findChild(resp, 'sub_groups');
10658
- if (!holder) throw new Error('sub groups: the reply carried no sub_groups');
10662
+ if (!holder) throw new Boom('sub groups: the reply carried no sub_groups', { statusCode: 502 });
10659
10663
  return (Array.isArray(holder.content) ? holder.content : [])
10660
10664
  .filter(c => c && c.description === 'group' && c.attrs && c.attrs.id)
10661
10665
  .map(c => {
@@ -10678,7 +10682,7 @@ class WhalibmobClient extends EventEmitter {
10678
10682
  id: this._genMsgId(), to: jid, type: 'get', xmlns: 'w:g2'
10679
10683
  }, [new BinaryNode('linked_groups_participants', {}, null)]), 'linked groups participants');
10680
10684
  const holder = findChild(resp, 'linked_groups_participants');
10681
- if (!holder) throw new Error('linked groups participants: the reply carried none');
10685
+ if (!holder) throw new Boom('linked groups participants: the reply carried none', { statusCode: 502 });
10682
10686
  return (Array.isArray(holder.content) ? holder.content : [])
10683
10687
  .filter(c => c && c.description === 'participant' && c.attrs && c.attrs.jid)
10684
10688
  .map(c => {
@@ -10698,12 +10702,12 @@ class WhalibmobClient extends EventEmitter {
10698
10702
  async resolveBusinessMessageLink(linkOrCode) {
10699
10703
  const code = String(linkOrCode || '')
10700
10704
  .replace(/^https?:\/\/(wa\.me\/message\/|api\.whatsapp\.com\/message\/)/i, '').split(/[?#]/)[0].trim();
10701
- if (!code) throw new Error('resolveBusinessMessageLink: a link or code is required');
10705
+ if (!code) throw new Boom('resolveBusinessMessageLink: a link or code is required', { statusCode: 400 });
10702
10706
  const resp = await this._iqOrThrow(new BinaryNode('iq', {
10703
10707
  id: this._genMsgId(), to: 's.whatsapp.net', type: 'get', xmlns: 'w:qr'
10704
10708
  }, [new BinaryNode('qr', { code }, null)]), 'business message link');
10705
10709
  const qr = findChild(resp, 'qr');
10706
- if (!qr) throw new Error('business message link: the reply carried no qr');
10710
+ if (!qr) throw new Boom('business message link: the reply carried no qr', { statusCode: 502 });
10707
10711
  const a = qr.attrs || {};
10708
10712
  const msg = findChild(qr, 'message'), biz = findChild(qr, 'business');
10709
10713
  const b = (biz && biz.attrs) || {};
@@ -10725,7 +10729,7 @@ class WhalibmobClient extends EventEmitter {
10725
10729
  }, [new BinaryNode('qr', { type: 'contact', action: revoke ? 'revoke' : 'get' }, null)]), 'contact link');
10726
10730
  const qr = findChild(resp, 'qr');
10727
10731
  const code = qr && qr.attrs && qr.attrs.code != null ? String(qr.attrs.code) : null;
10728
- if (!code) throw new Error('contact link: the reply carried no code');
10732
+ if (!code) throw new Boom('contact link: the reply carried no code', { statusCode: 502 });
10729
10733
  return { code, link: 'https://wa.me/qr/' + code };
10730
10734
  }
10731
10735
 
@@ -10733,12 +10737,12 @@ class WhalibmobClient extends EventEmitter {
10733
10737
  async resolveContactQrLink(linkOrCode) {
10734
10738
  const code = String(linkOrCode || '')
10735
10739
  .replace(/^https?:\/\/(wa\.me\/qr\/|api\.whatsapp\.com\/qr\/)/i, '').split(/[?#]/)[0].trim();
10736
- if (!code) throw new Error('resolveContactQrLink: a link or code is required');
10740
+ if (!code) throw new Boom('resolveContactQrLink: a link or code is required', { statusCode: 400 });
10737
10741
  const resp = await this._iqOrThrow(new BinaryNode('iq', {
10738
10742
  id: this._genMsgId(), to: 's.whatsapp.net', type: 'get', xmlns: 'w:qr'
10739
10743
  }, [new BinaryNode('qr', { code }, null)]), 'contact link');
10740
10744
  const qr = findChild(resp, 'qr');
10741
- if (!qr) throw new Error('contact link: the reply carried no qr');
10745
+ if (!qr) throw new Boom('contact link: the reply carried no qr', { statusCode: 502 });
10742
10746
  const a = qr.attrs || {};
10743
10747
  return {
10744
10748
  jid: a.jid != null ? String(a.jid) : null,
@@ -10753,7 +10757,7 @@ class WhalibmobClient extends EventEmitter {
10753
10757
  id: this._genMsgId(), to: 's.whatsapp.net', type: 'get', xmlns: 'bot'
10754
10758
  }, [new BinaryNode('bot', { v: '2' }, null)]), 'bot list');
10755
10759
  const botNode = findChild(resp, 'bot');
10756
- if (!botNode) throw new Error('bot list: the reply carried no bot node');
10760
+ if (!botNode) throw new Boom('bot list: the reply carried no bot node', { statusCode: 502 });
10757
10761
  const out = [];
10758
10762
  for (const section of (Array.isArray(botNode.content) ? botNode.content : [])) {
10759
10763
  if (!section || section.description !== 'section' || !section.attrs || section.attrs.type !== 'all') continue;
@@ -10768,7 +10772,7 @@ class WhalibmobClient extends EventEmitter {
10768
10772
  /** Create, rename or recolour a label, or delete it with `{ deleted: true }`. */
10769
10773
  async editLabel(labelId, opts) {
10770
10774
  opts = opts || {};
10771
- if (labelId == null || labelId === '') throw new Error('editLabel: a label id is required');
10775
+ if (labelId == null || labelId === '') throw new Boom('editLabel: a label id is required', { statusCode: 400 });
10772
10776
  await this._sendAppStatePatch(AppMutations.labelEditPatch(labelId, opts.name, opts.color, opts.deleted));
10773
10777
  this.emit('label_edit', { labelId: String(labelId), name: opts.name || '', color: opts.color || 0, deleted: !!opts.deleted, synced: true });
10774
10778
  }
@@ -10783,7 +10787,7 @@ class WhalibmobClient extends EventEmitter {
10783
10787
  /** Put a label on one message, or take it off with `labeled: false`. */
10784
10788
  async labelMessage(jid, labelId, msgId, labeled) {
10785
10789
  const jidFull = makeJid(jid);
10786
- if (!msgId) throw new Error('labelMessage: a message id is required');
10790
+ if (!msgId) throw new Boom('labelMessage: a message id is required', { statusCode: 400 });
10787
10791
  await this._sendAppStatePatch(AppMutations.labelMessagePatch(jidFull, labelId, msgId, labeled !== false));
10788
10792
  this.emit('label_association', { labelId: String(labelId), jid: jidFull, msgId, labeled: labeled !== false, synced: true });
10789
10793
  }
@@ -10796,7 +10800,7 @@ class WhalibmobClient extends EventEmitter {
10796
10800
  async deleteMessageForMe(jid, msgId, fromMe, opts) {
10797
10801
  opts = opts || {};
10798
10802
  const jidFull = makeJid(jid);
10799
- if (!msgId) throw new Error('deleteMessageForMe: a message id is required');
10803
+ if (!msgId) throw new Boom('deleteMessageForMe: a message id is required', { statusCode: 400 });
10800
10804
  await this._sendAppStatePatch(AppMutations.deleteMessageForMePatch(
10801
10805
  jidFull, msgId, !!fromMe, opts.timestamp, opts.deleteMedia));
10802
10806
  this.emit('message_deleted_for_me', { jid: jidFull, msgId, fromMe: !!fromMe, deleteMedia: !!opts.deleteMedia, synced: true });
@@ -10808,30 +10812,30 @@ class WhalibmobClient extends EventEmitter {
10808
10812
  */
10809
10813
  async fetchStickerPack(packId) {
10810
10814
  const id = String(packId || '').trim();
10811
- if (!/^[A-Za-z0-9._-]+$/.test(id)) throw new Error('fetchStickerPack: a sticker pack id is required');
10815
+ if (!/^[A-Za-z0-9._-]+$/.test(id)) throw new Boom('fetchStickerPack: a sticker pack id is required', { statusCode: 400 });
10812
10816
  const url = 'https://static.whatsapp.net/sticker?lottie=1&cat=sticker_pack_data&id=' +
10813
10817
  encodeURIComponent(id) + '&lg=en';
10814
10818
  const body = await new Promise((resolve, reject) => {
10815
10819
  const req = require('https').get(url, { headers: { Origin: 'https://web.whatsapp.com' } }, (res) => {
10816
10820
  if (res.statusCode < 200 || res.statusCode >= 300) {
10817
10821
  res.resume();
10818
- return reject(new Error('fetchStickerPack: the store answered ' + res.statusCode));
10822
+ return reject(new Boom('fetchStickerPack: the store answered ' + res.statusCode, { statusCode: statusFrom(res.statusCode) }));
10819
10823
  }
10820
10824
  const chunks = []; let size = 0;
10821
10825
  res.on('data', (c) => {
10822
10826
  size += c.length;
10823
- if (size > 4 * 1024 * 1024) { req.destroy(new Error('fetchStickerPack: the listing is too large')); return; }
10827
+ if (size > 4 * 1024 * 1024) { req.destroy(new Boom('fetchStickerPack: the listing is too large', { statusCode: 413 })); return; }
10824
10828
  chunks.push(c);
10825
10829
  });
10826
10830
  res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
10827
10831
  res.on('error', reject);
10828
10832
  });
10829
- req.setTimeout(30000, () => req.destroy(new Error('fetchStickerPack: timed out')));
10833
+ req.setTimeout(30000, () => req.destroy(new Boom('fetchStickerPack: timed out', { statusCode: 408 })));
10830
10834
  req.on('error', reject);
10831
10835
  });
10832
10836
  let packs;
10833
- try { packs = JSON.parse(body); } catch (_) { throw new Error('fetchStickerPack: the store did not answer with JSON'); }
10834
- if (!Array.isArray(packs) || !packs.length) throw new Error('fetchStickerPack: no sticker pack found');
10837
+ try { packs = JSON.parse(body); } catch (_) { throw new Boom('fetchStickerPack: the store did not answer with JSON', { statusCode: 502 }); }
10838
+ if (!Array.isArray(packs) || !packs.length) throw new Boom('fetchStickerPack: no sticker pack found', { statusCode: 404 });
10835
10839
  return packs[0];
10836
10840
  }
10837
10841
 
@@ -10842,7 +10846,7 @@ class WhalibmobClient extends EventEmitter {
10842
10846
  async registerWebPush(subscription) {
10843
10847
  const sub = subscription || {};
10844
10848
  if (!sub.endpoint || !sub.auth || !sub.p256dh) {
10845
- throw new Error('registerWebPush: endpoint, auth and p256dh are required');
10849
+ throw new Boom('registerWebPush: endpoint, auth and p256dh are required', { statusCode: 400 });
10846
10850
  }
10847
10851
  const b64 = (v) => (Buffer.isBuffer(v) ? v : Buffer.from(String(v).replace(/-/g, '+').replace(/_/g, '/'), 'base64')).toString('base64');
10848
10852
  await this._iqOrThrow(new BinaryNode('iq', {
@@ -10866,7 +10870,7 @@ class WhalibmobClient extends EventEmitter {
10866
10870
  * uploads it again. `mediaKey` is the one the history notification carried.
10867
10871
  */
10868
10872
  async sendHistorySyncServerErrorReceipt(msgId, mediaKey) {
10869
- if (!this._socket || !this._connected) throw new Error('Not connected');
10873
+ if (!this._socket || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
10870
10874
  const { encryptRetryReceipt } = require('./messages/MediaRetry');
10871
10875
  const { ciphertext, iv } = encryptRetryReceipt(String(msgId), mediaKey);
10872
10876
  this._socket.sendNode(new BinaryNode('receipt', {
@@ -11001,15 +11005,15 @@ class WhalibmobClient extends EventEmitter {
11001
11005
  async _updateBlocklist(jid, action) {
11002
11006
  const { lid, pn } = await this._resolveBlockTarget(jid);
11003
11007
  if (!lid) {
11004
- throw new Error(action + 'Contact: could not resolve a LID for ' + jid +
11008
+ throw new Boom(action + 'Contact: could not resolve a LID for ' + jid +
11005
11009
  ' — the server only accepts LID-addressed block list items. ' +
11006
- 'Check the number is on WhatsApp.');
11010
+ 'Check the number is on WhatsApp.', { statusCode: 404 });
11007
11011
  }
11008
11012
  const attrs = { action, jid: jidStrToObj(lid) };
11009
11013
  if (action === 'block') {
11010
11014
  if (!pn) {
11011
- throw new Error('blockContact: no phone number known for ' + lid +
11012
- ' — a block has to carry pn_jid beside the LID.');
11015
+ throw new Boom('blockContact: no phone number known for ' + lid +
11016
+ ' — a block has to carry pn_jid beside the LID.', { statusCode: 404 });
11013
11017
  }
11014
11018
  attrs.pn_jid = jidStrToObj(pn);
11015
11019
  }
@@ -11025,14 +11029,14 @@ class WhalibmobClient extends EventEmitter {
11025
11029
 
11026
11030
  const resp = await this._sendIq(node);
11027
11031
  if (!resp) {
11028
- throw new Error(action + 'Contact: no reply from server (IQ timed out)');
11032
+ throw new Boom(action + 'Contact: no reply from server (IQ timed out)', { statusCode: 408 });
11029
11033
  }
11030
11034
  if (resp.attrs && resp.attrs.type === 'error') {
11031
11035
  const errNode = findChild(resp, 'error');
11032
11036
  const code = errNode && errNode.attrs && errNode.attrs.code;
11033
11037
  const text = errNode && errNode.attrs && errNode.attrs.text;
11034
- throw new Error(action + 'Contact: server rejected the request' +
11035
- (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''));
11038
+ throw new Boom(action + 'Contact: server rejected the request' +
11039
+ (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''), { statusCode: statusFrom(code) });
11036
11040
  }
11037
11041
  // The server answers with the whole list as it now stands.
11038
11042
  return this._parseBlocklist(findChild(resp, 'list')).jids;
@@ -11130,7 +11134,7 @@ class WhalibmobClient extends EventEmitter {
11130
11134
  }, [body]);
11131
11135
  return this._sendIq(node);
11132
11136
  } else {
11133
- if (!this._sender || !this._connected) throw new Error('Not connected');
11137
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
11134
11138
  return this._sender.sendEphemeralTimerDM(jidFull, seconds);
11135
11139
  }
11136
11140
  }
@@ -11182,16 +11186,16 @@ class WhalibmobClient extends EventEmitter {
11182
11186
  new BinaryNode('link_create', { media }, children)
11183
11187
  ]));
11184
11188
 
11185
- if (!resp) throw new Error('createCallLink: no reply from server (timed out)');
11189
+ if (!resp) throw new Boom('createCallLink: no reply from server (timed out)', { statusCode: 408 });
11186
11190
  if (resp.attrs && resp.attrs.type === 'error') {
11187
11191
  const errNode = findChild(resp, 'error');
11188
11192
  const code = errNode && errNode.attrs && errNode.attrs.code;
11189
- throw new Error('createCallLink: server rejected the request' +
11190
- (code ? ' (' + code + ')' : ''));
11193
+ throw new Boom('createCallLink: server rejected the request' +
11194
+ (code ? ' (' + code + ')' : ''), { statusCode: statusFrom(code) });
11191
11195
  }
11192
11196
  const created = findChild(resp, 'link_create');
11193
11197
  const token = created && created.attrs && created.attrs.token;
11194
- if (!token) throw new Error('createCallLink: server reply carried no token');
11198
+ if (!token) throw new Boom('createCallLink: server reply carried no token', { statusCode: 502 });
11195
11199
 
11196
11200
  const prefix = media === 'video' ? CALL_VIDEO_PREFIX : CALL_AUDIO_PREFIX;
11197
11201
  return { token: String(token), link: prefix + token, type: media };
@@ -11288,19 +11292,19 @@ class WhalibmobClient extends EventEmitter {
11288
11292
  // These used to return null indistinguishably, which surfaced to the CLI as
11289
11293
  // a bare "no response" no matter what actually went wrong.
11290
11294
  if (!resp) {
11291
- throw new Error('createGroup: no reply from server (IQ timed out)');
11295
+ throw new Boom('createGroup: no reply from server (IQ timed out)', { statusCode: 408 });
11292
11296
  }
11293
11297
  if (resp.attrs && resp.attrs.type === 'error') {
11294
11298
  const errNode = findChild(resp, 'error');
11295
11299
  const code = errNode && errNode.attrs && errNode.attrs.code;
11296
11300
  const text = errNode && errNode.attrs && errNode.attrs.text;
11297
- throw new Error('createGroup: server rejected the request' +
11298
- (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''));
11301
+ throw new Boom('createGroup: server rejected the request' +
11302
+ (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''), { statusCode: statusFrom(code) });
11299
11303
  }
11300
11304
  const createNode = findChild(resp, 'create');
11301
11305
  const groupNode = createNode ? findChild(createNode, 'group') : findChildDeep(resp, 'group');
11302
11306
  if (!groupNode) {
11303
- throw new Error('createGroup: server reply contained no <group> node');
11307
+ throw new Boom('createGroup: server reply contained no <group> node', { statusCode: 502 });
11304
11308
  }
11305
11309
  return this._parseGroupNode(groupNode);
11306
11310
  }
@@ -11379,17 +11383,17 @@ class WhalibmobClient extends EventEmitter {
11379
11383
  new BinaryNode(action, {}, participantNodes)
11380
11384
  ]);
11381
11385
  const resp = await this._sendIq(node);
11382
- if (!resp) throw new Error(action + ': no reply from server (IQ timed out)');
11386
+ if (!resp) throw new Boom(action + ': no reply from server (IQ timed out)', { statusCode: 408 });
11383
11387
  if (resp.attrs && resp.attrs.type === 'error') {
11384
11388
  const errNode = findChild(resp, 'error');
11385
11389
  const code = errNode && errNode.attrs && errNode.attrs.code;
11386
11390
  const text = errNode && errNode.attrs && errNode.attrs.text;
11387
- throw new Error(action + ': server rejected the request' +
11388
- (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''));
11391
+ throw new Boom(action + ': server rejected the request' +
11392
+ (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''), { statusCode: statusFrom(code) });
11389
11393
  }
11390
11394
  const actionNode = findChild(resp, action);
11391
11395
  if (!actionNode) {
11392
- throw new Error(action + ': server reply contained no <' + action + '> node');
11396
+ throw new Boom(action + ': server reply contained no <' + action + '> node', { statusCode: 502 });
11393
11397
  }
11394
11398
  // The membership changed, so anything we have cached about the group is now
11395
11399
  // one edit behind.
@@ -11497,13 +11501,13 @@ class WhalibmobClient extends EventEmitter {
11497
11501
  new BinaryNode(tag, {}, content === undefined ? null : content)
11498
11502
  ]);
11499
11503
  const resp = await this._sendIq(node);
11500
- if (!resp) throw new Error(tag + ': no reply from server (IQ timed out)');
11504
+ if (!resp) throw new Boom(tag + ': no reply from server (IQ timed out)', { statusCode: 408 });
11501
11505
  if (resp.attrs && resp.attrs.type === 'error') {
11502
11506
  const errNode = findChild(resp, 'error');
11503
11507
  const code = errNode && errNode.attrs && errNode.attrs.code;
11504
11508
  const text = errNode && errNode.attrs && errNode.attrs.text;
11505
- throw new Error(tag + ': server rejected the request' +
11506
- (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''));
11509
+ throw new Boom(tag + ': server rejected the request' +
11510
+ (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''), { statusCode: statusFrom(code) });
11507
11511
  }
11508
11512
  // The group's own view of these flags is now stale.
11509
11513
  this.invalidateGroupMetadata(groupJid);
@@ -11533,19 +11537,19 @@ class WhalibmobClient extends EventEmitter {
11533
11537
  }, picture ? [new BinaryNode('picture', { type: 'image' }, picture)] : null);
11534
11538
  const resp = await this._sendIq(node);
11535
11539
  if (!resp) {
11536
- throw new Error('changeGroupPicture: no reply from server (IQ timed out). ' +
11540
+ throw new Boom('changeGroupPicture: no reply from server (IQ timed out). ' +
11537
11541
  'The server drops a picture it will not take rather than refusing it, so ' +
11538
- 'this usually means the image was not in the form it wants.');
11542
+ 'this usually means the image was not in the form it wants.', { statusCode: 408 });
11539
11543
  }
11540
11544
  if (resp.attrs && resp.attrs.type === 'error') {
11541
11545
  const errNode = findChild(resp, 'error');
11542
11546
  const code = errNode && errNode.attrs && errNode.attrs.code;
11543
11547
  if (String(code) === '406') {
11544
- throw new Error(_pictureRejected('changeGroupPicture', picture, buf, opts));
11548
+ throw new Boom(_pictureRejected('changeGroupPicture', picture, buf, opts), { statusCode: 406 });
11545
11549
  }
11546
- throw new Error('changeGroupPicture: ' +
11550
+ throw new Boom('changeGroupPicture: ' +
11547
11551
  (String(code) === '403' ? 'you are not allowed to change this group picture'
11548
- : 'server rejected the request' + (code ? ' (' + code + ')' : '')));
11552
+ : 'server rejected the request' + (code ? ' (' + code + ')' : '')), { statusCode: statusFrom(code) });
11549
11553
  }
11550
11554
  if (!buf) return 'remove';
11551
11555
  const picNode = findChild(resp, 'picture');
@@ -11581,7 +11585,7 @@ class WhalibmobClient extends EventEmitter {
11581
11585
  }, [new BinaryNode('invite', { code }, null)]);
11582
11586
 
11583
11587
  const resp = await this._sendIq(node);
11584
- if (!resp) throw new Error('joinGroupWithLink: no reply from server (IQ timed out)');
11588
+ if (!resp) throw new Boom('joinGroupWithLink: no reply from server (IQ timed out)', { statusCode: 408 });
11585
11589
  if (resp.attrs && resp.attrs.type === 'error') {
11586
11590
  const errNode = findChild(resp, 'error');
11587
11591
  const codeAttr = errNode && errNode.attrs && errNode.attrs.code;
@@ -11591,7 +11595,7 @@ class WhalibmobClient extends EventEmitter {
11591
11595
  : String(codeAttr) === '406' ? 'the invite link is not valid'
11592
11596
  : 'server rejected the request' +
11593
11597
  (codeAttr ? ' (' + codeAttr + ')' : '');
11594
- throw new Error('joinGroupWithLink: ' + reason);
11598
+ throw new Boom('joinGroupWithLink: ' + reason, { statusCode: statusFrom(codeAttr) });
11595
11599
  }
11596
11600
  const pending = findChild(resp, 'membership_approval_request');
11597
11601
  if (pending && pending.attrs && pending.attrs.jid) {
@@ -11599,7 +11603,7 @@ class WhalibmobClient extends EventEmitter {
11599
11603
  }
11600
11604
  const grp = findChild(resp, 'group');
11601
11605
  if (!grp || !grp.attrs || !grp.attrs.jid) {
11602
- throw new Error('joinGroupWithLink: server reply contained no <group> node');
11606
+ throw new Boom('joinGroupWithLink: server reply contained no <group> node', { statusCode: 502 });
11603
11607
  }
11604
11608
  return { jid: String(grp.attrs.jid), pendingApproval: false };
11605
11609
  }
@@ -11686,7 +11690,7 @@ class WhalibmobClient extends EventEmitter {
11686
11690
  ]);
11687
11691
  break;
11688
11692
  default:
11689
- throw new Error('Unknown group setting: ' + setting);
11693
+ throw new Boom('Unknown group setting: ' + setting, { statusCode: 400 });
11690
11694
  }
11691
11695
  // Routed through the shared helper so a refusal from the server (not an
11692
11696
  // admin, not a member) surfaces as an error instead of resolving null, and
@@ -11741,17 +11745,17 @@ class WhalibmobClient extends EventEmitter {
11741
11745
  ])
11742
11746
  ]);
11743
11747
  const resp = await this._sendIq(node);
11744
- if (!resp) throw new Error(action + ': no reply from server (IQ timed out)');
11748
+ if (!resp) throw new Boom(action + ': no reply from server (IQ timed out)', { statusCode: 408 });
11745
11749
  if (resp.attrs && resp.attrs.type === 'error') {
11746
11750
  const errNode = findChild(resp, 'error');
11747
11751
  const code = errNode && errNode.attrs && errNode.attrs.code;
11748
11752
  const text = errNode && errNode.attrs && errNode.attrs.text;
11749
- throw new Error(action + ': server rejected the request' +
11750
- (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''));
11753
+ throw new Boom(action + ': server rejected the request' +
11754
+ (code ? ' (' + code + (text ? ' ' + text : '') + ')' : ''), { statusCode: statusFrom(code) });
11751
11755
  }
11752
11756
  const actionNode = findChildDeep(resp, action);
11753
11757
  if (!actionNode) {
11754
- throw new Error(action + ': server reply contained no <' + action + '> node');
11758
+ throw new Boom(action + ': server reply contained no <' + action + '> node', { statusCode: 502 });
11755
11759
  }
11756
11760
  this.invalidateGroupMetadata(gJid);
11757
11761
  return parseParticipantNodes(actionNode);
@@ -11773,7 +11777,7 @@ class WhalibmobClient extends EventEmitter {
11773
11777
  // The group name is filled in from the group's own metadata when the caller
11774
11778
  // does not supply one, so the bubble does not arrive nameless.
11775
11779
  async sendGroupInvite(to, groupJid, inviteCode, inviteExpiration, opts) {
11776
- if (!this._sender || !this._connected) throw new Error('Not connected');
11780
+ if (!this._sender || !this._connected) throw new Boom('Not connected', { statusCode: 428 });
11777
11781
  opts = opts || {};
11778
11782
  const gJid = makeJid(groupJid);
11779
11783
  let groupName = opts.groupName;
@@ -11807,17 +11811,17 @@ class WhalibmobClient extends EventEmitter {
11807
11811
  ])
11808
11812
  ]);
11809
11813
  const resp = await this._sendIq(node);
11810
- if (!resp) throw new Error('queryGroupInviteMessageInfo: no reply from server (IQ timed out)');
11814
+ if (!resp) throw new Boom('queryGroupInviteMessageInfo: no reply from server (IQ timed out)', { statusCode: 408 });
11811
11815
  if (resp.attrs && resp.attrs.type === 'error') {
11812
11816
  const errNode = findChild(resp, 'error');
11813
11817
  const errCode = errNode && errNode.attrs && errNode.attrs.code;
11814
- throw new Error('queryGroupInviteMessageInfo: ' +
11818
+ throw new Boom('queryGroupInviteMessageInfo: ' +
11815
11819
  (String(errCode) === '410' ? 'the invitation has expired'
11816
11820
  : String(errCode) === '406' ? 'the invitation is not valid'
11817
- : 'server rejected the request' + (errCode ? ' (' + errCode + ')' : '')));
11821
+ : 'server rejected the request' + (errCode ? ' (' + errCode + ')' : '')), { statusCode: statusFrom(errCode) });
11818
11822
  }
11819
11823
  const grp = findChild(resp, 'group');
11820
- if (!grp) throw new Error('queryGroupInviteMessageInfo: server reply contained no <group> node');
11824
+ if (!grp) throw new Boom('queryGroupInviteMessageInfo: server reply contained no <group> node', { statusCode: 502 });
11821
11825
  return this._parseGroupNode(grp);
11822
11826
  }
11823
11827
 
@@ -11837,14 +11841,14 @@ class WhalibmobClient extends EventEmitter {
11837
11841
  }, null)
11838
11842
  ]);
11839
11843
  const resp = await this._sendIq(node);
11840
- if (!resp) throw new Error('acceptGroupInviteMessage: no reply from server (IQ timed out)');
11844
+ if (!resp) throw new Boom('acceptGroupInviteMessage: no reply from server (IQ timed out)', { statusCode: 408 });
11841
11845
  if (resp.attrs && resp.attrs.type === 'error') {
11842
11846
  const errNode = findChild(resp, 'error');
11843
11847
  const errCode = errNode && errNode.attrs && errNode.attrs.code;
11844
- throw new Error('acceptGroupInviteMessage: ' +
11848
+ throw new Boom('acceptGroupInviteMessage: ' +
11845
11849
  (String(errCode) === '410' ? 'the invitation has expired'
11846
11850
  : String(errCode) === '406' ? 'the invitation is not valid'
11847
- : 'server rejected the request' + (errCode ? ' (' + errCode + ')' : '')));
11851
+ : 'server rejected the request' + (errCode ? ' (' + errCode + ')' : '')), { statusCode: statusFrom(errCode) });
11848
11852
  }
11849
11853
  this.invalidateGroupMetadata(gJid);
11850
11854
  return (resp.attrs && resp.attrs.from) ? String(resp.attrs.from) : gJid;
@@ -11863,12 +11867,12 @@ class WhalibmobClient extends EventEmitter {
11863
11867
  ])
11864
11868
  ]);
11865
11869
  const resp = await this._sendIq(node);
11866
- if (!resp) throw new Error('revokeGroupInviteForParticipant: no reply from server (IQ timed out)');
11870
+ if (!resp) throw new Boom('revokeGroupInviteForParticipant: no reply from server (IQ timed out)', { statusCode: 408 });
11867
11871
  if (resp.attrs && resp.attrs.type === 'error') {
11868
11872
  const errNode = findChild(resp, 'error');
11869
11873
  const errCode = errNode && errNode.attrs && errNode.attrs.code;
11870
- throw new Error('revokeGroupInviteForParticipant: server rejected the request' +
11871
- (errCode ? ' (' + errCode + ')' : ''));
11874
+ throw new Boom('revokeGroupInviteForParticipant: server rejected the request' +
11875
+ (errCode ? ' (' + errCode + ')' : ''), { statusCode: statusFrom(errCode) });
11872
11876
  }
11873
11877
  return true;
11874
11878
  }