whalibmob 5.40.37 → 5.40.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +1 -0
  2. package/cli.js +5 -4
  3. package/docs/events-history.md +47 -0
  4. package/index.d.ts +21 -0
  5. package/index.js +6 -0
  6. package/lib/AndroidApk.js +13 -12
  7. package/lib/BinaryNode.js +2 -1
  8. package/lib/Client.js +273 -269
  9. package/lib/CompanionPairing.js +3 -1
  10. package/lib/DeviceConfig.js +10 -0
  11. package/lib/DeviceManager.js +2 -1
  12. package/lib/HistorySyncHandler.js +13 -11
  13. package/lib/MediaService.js +14 -12
  14. package/lib/OfflineNodeProcessor.js +3 -1
  15. package/lib/PairingCode.js +2 -1
  16. package/lib/PasskeyPairing.js +18 -17
  17. package/lib/PlayStore.js +15 -13
  18. package/lib/PrimaryLinkCrypto.js +2 -1
  19. package/lib/Registration.js +76 -38
  20. package/lib/Store.js +6 -5
  21. package/lib/WebSocketStream.js +3 -2
  22. package/lib/WebVersion.js +5 -3
  23. package/lib/apns-courier.js +15 -13
  24. package/lib/apns.js +6 -4
  25. package/lib/argo/ArgoDecoder.js +16 -14
  26. package/lib/auth-utils.js +10 -9
  27. package/lib/cli/linkCommands.js +5 -2
  28. package/lib/constants.js +20 -15
  29. package/lib/curve.js +5 -4
  30. package/lib/errors.js +42 -0
  31. package/lib/fcm.js +7 -5
  32. package/lib/image/JpegEncoder.js +4 -2
  33. package/lib/messages/MediaRetry.js +3 -2
  34. package/lib/messages/MessageSecret.js +9 -8
  35. package/lib/messages/MessageSender.js +30 -28
  36. package/lib/noise.js +13 -11
  37. package/lib/plist.js +18 -15
  38. package/lib/primary/HistoryExport.js +2 -1
  39. package/lib/primary/MessageStore.js +8 -2
  40. package/lib/proto/MessageProto.js +3 -1
  41. package/lib/signal/SenderKey.js +5 -4
  42. package/lib/signal/WaSignalGroup/group-session-builder.js +2 -1
  43. package/lib/signal/WaSignalGroup/group_cipher.js +10 -9
  44. package/lib/signal/WaSignalGroup/sender-key-distribution-message.js +2 -1
  45. package/lib/signal/WaSignalGroup/sender-key-message.js +2 -1
  46. package/lib/socks.js +9 -8
  47. package/lib/store/Backend.js +3 -1
  48. package/lib/store/FileBackend.js +2 -1
  49. package/lib/store/MemoryBackend.js +2 -1
  50. package/lib/store/SqliteBackend.js +6 -5
  51. package/lib/store/migrate.js +2 -1
  52. package/llms.txt +1 -0
  53. package/package.json +2 -1
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
4
+ const { statusFrom } = require('../errors');
3
5
  const { dbg: _whaDbg } = require('../logger');
4
6
  //fetch all imports
5
7
  const crypto = require('crypto');
@@ -476,14 +478,14 @@ class MessageSender {
476
478
  async sendRaw(to, message, options) {
477
479
  options = options || {};
478
480
  if (!Buffer.isBuffer(message) || !message.length) {
479
- throw new Error('sendRawMessage: message must be a non-empty Buffer holding an encoded Message');
481
+ throw new Boom('sendRawMessage: message must be a non-empty Buffer holding an encoded Message', { statusCode: 400 });
480
482
  }
481
483
  const type = options.type || 'text';
482
484
  if (!['text', 'media', 'poll', 'reaction'].includes(type)) {
483
- throw new Error('sendRawMessage: type must be text, media, poll or reaction');
485
+ throw new Boom('sendRawMessage: type must be text, media, poll or reaction', { statusCode: 400 });
484
486
  }
485
487
  if (type === 'media' && !options.mediaType) {
486
- throw new Error('sendRawMessage: a media message needs opts.mediaType (image, video, audio, …)');
488
+ throw new Boom('sendRawMessage: a media message needs opts.mediaType (image, video, audio, …)', { statusCode: 400 });
487
489
  }
488
490
  const msgId = options.id || generateMessageId();
489
491
  const toJid = makeJid(to);
@@ -633,7 +635,7 @@ class MessageSender {
633
635
  async forwardDecodedMessage(to, msg, opts) {
634
636
  opts = opts || {};
635
637
  const d = (msg && msg.decoded) ? msg.decoded : msg;
636
- if (!d || !d.type) throw new Error('forwardDecodedMessage: msg.decoded is required');
638
+ if (!d || !d.type) throw new Boom('forwardDecodedMessage: msg.decoded is required', { statusCode: 400 });
637
639
  const ctx = Object.assign({ forwardingScore: 1, isForwarded: true }, opts.contextInfo || {});
638
640
  const o = Object.assign({}, opts, { contextInfo: ctx });
639
641
  switch (d.type) {
@@ -641,7 +643,7 @@ class MessageSender {
641
643
  return this.sendText(to, d.text || '', o);
642
644
 
643
645
  case 'image':
644
- if (!d.url && !d.directPath) throw new Error('forwardDecodedMessage: image has no CDN data');
646
+ if (!d.url && !d.directPath) throw new Boom('forwardDecodedMessage: image has no CDN data', { statusCode: 400 });
645
647
  return this.sendImage(to, null, Object.assign({}, o, {
646
648
  _cdnForward: {
647
649
  url: d.url, directPath: d.directPath, mediaKey: d.mediaKey,
@@ -655,7 +657,7 @@ class MessageSender {
655
657
  }));
656
658
 
657
659
  case 'video':
658
- if (!d.url && !d.directPath) throw new Error('forwardDecodedMessage: video has no CDN data');
660
+ if (!d.url && !d.directPath) throw new Boom('forwardDecodedMessage: video has no CDN data', { statusCode: 400 });
659
661
  return this.sendVideo(to, null, Object.assign({}, o, {
660
662
  _cdnForward: {
661
663
  url: d.url, directPath: d.directPath, mediaKey: d.mediaKey,
@@ -669,7 +671,7 @@ class MessageSender {
669
671
 
670
672
  case 'audio':
671
673
  case 'voice':
672
- if (!d.url && !d.directPath) throw new Error('forwardDecodedMessage: audio has no CDN data');
674
+ if (!d.url && !d.directPath) throw new Boom('forwardDecodedMessage: audio has no CDN data', { statusCode: 400 });
673
675
  return this.sendAudio(to, null, Object.assign({}, o, {
674
676
  ptt: d.type === 'voice',
675
677
  _cdnForward: {
@@ -681,7 +683,7 @@ class MessageSender {
681
683
  }));
682
684
 
683
685
  case 'document':
684
- if (!d.url && !d.directPath) throw new Error('forwardDecodedMessage: document has no CDN data');
686
+ if (!d.url && !d.directPath) throw new Boom('forwardDecodedMessage: document has no CDN data', { statusCode: 400 });
685
687
  return this.sendDocument(to, null, Object.assign({}, o, {
686
688
  fileName: d.fileName || 'file',
687
689
  _cdnForward: {
@@ -694,7 +696,7 @@ class MessageSender {
694
696
  }));
695
697
 
696
698
  case 'sticker':
697
- if (!d.url && !d.directPath) throw new Error('forwardDecodedMessage: sticker has no CDN data');
699
+ if (!d.url && !d.directPath) throw new Boom('forwardDecodedMessage: sticker has no CDN data', { statusCode: 400 });
698
700
  return this.sendSticker(to, null, Object.assign({}, o, {
699
701
  _cdnForward: {
700
702
  url: d.url, directPath: d.directPath, mediaKey: d.mediaKey,
@@ -1041,10 +1043,10 @@ class MessageSender {
1041
1043
  const ownLidUser = this._client._myLid ? phoneFromJid(this._client._myLid) : null;
1042
1044
 
1043
1045
  if (isLidTarget && !ownLidUser) {
1044
- throw new Error(
1046
+ throw new Boom(
1045
1047
  'Cannot send to ' + toJid + ': the recipient is LID-addressed but our own LID ' +
1046
1048
  'is unknown (the server did not supply lid= on <success>). Reconnect so the ' +
1047
- 'LID is re-issued.'
1049
+ 'LID is re-issued.', { statusCode: 428 }
1048
1050
  );
1049
1051
  }
1050
1052
 
@@ -1135,7 +1137,7 @@ class MessageSender {
1135
1137
 
1136
1138
  let msgContent;
1137
1139
  if (encryptedList.length === 0) {
1138
- throw new Error('NO_OPEN_SESSION: no encrypted recipients — need a fresh pkmsg to establish session');
1140
+ throw new Boom('NO_OPEN_SESSION: no encrypted recipients — need a fresh pkmsg to establish session', { statusCode: 404 });
1139
1141
  } else {
1140
1142
  // Always use <participants><to jid=...><enc> structure — required by MD protocol.
1141
1143
  // Old iOS non-MD used direct <enc> in <message>, but the WhatsApp server now
@@ -1337,9 +1339,9 @@ class MessageSender {
1337
1339
  // the server answers with ack 479.
1338
1340
  const others = members.filter(jid => !this._client._isOwnUser(jid));
1339
1341
  if (others.length === 0) {
1340
- throw new Error(
1342
+ throw new Boom(
1341
1343
  'Cannot post a Status: it would reach nobody. The contact list is ' +
1342
- 'empty — sync history first, or pass { recipients: [...] }.'
1344
+ 'empty — sync history first, or pass { recipients: [...] }.', { statusCode: 400 }
1343
1345
  );
1344
1346
  }
1345
1347
  }
@@ -1362,11 +1364,11 @@ class MessageSender {
1362
1364
  // server rejects exactly that shape with ack error 479. Fail here with a
1363
1365
  // reason the caller can act on instead of emitting a doomed stanza.
1364
1366
  if (members.length === 0) {
1365
- throw new Error(
1367
+ throw new Boom(
1366
1368
  'Cannot send to ' + groupJid + ': group metadata unavailable' +
1367
1369
  (metaErr ? ' (' + metaErr.message + ')' : '') +
1368
1370
  ' — no Signal session can be established with the members. ' +
1369
- 'Check that the account is still a participant of this group.'
1371
+ 'Check that the account is still a participant of this group.', { statusCode: 502 }
1370
1372
  );
1371
1373
  }
1372
1374
  }
@@ -1383,10 +1385,10 @@ class MessageSender {
1383
1385
  // DeviceManager warns about, and the server answers it with ack 479.
1384
1386
  const useLid = groupAddressingMode === 'lid';
1385
1387
  if (useLid && !this._client._myLid) {
1386
- throw new Error(
1388
+ throw new Boom(
1387
1389
  'Cannot send to ' + groupJid + ': group is LID-addressed but our own LID ' +
1388
1390
  'is unknown (the server did not supply lid= on <success>). ' +
1389
- 'Reconnect so the LID is re-issued.'
1391
+ 'Reconnect so the LID is re-issued.', { statusCode: 428 }
1390
1392
  );
1391
1393
  }
1392
1394
  // Derived whenever the server has given us a LID, not only in LID mode: it
@@ -1508,7 +1510,7 @@ class MessageSender {
1508
1510
  // is no one to hand the SenderKey to and the skmsg below is undeliverable.
1509
1511
  // Better to say so than to emit it and read the 479 back.
1510
1512
  if (isStatus && allTargets.length === 0) {
1511
- throw new Error(
1513
+ throw new Boom(
1512
1514
  'Cannot post a Status: no Signal session could be opened with any ' +
1513
1515
  'recipient, so the post would reach nobody.'
1514
1516
  );
@@ -1740,9 +1742,9 @@ class MessageSender {
1740
1742
  if (!hasToken) {
1741
1743
  _whaDbg('[DBG] ACK_463 IQ timeout or server refused — no token bytes stored for ' +
1742
1744
  tcJid + ', giving up (account may be restricted)\n');
1743
- throw new Error(
1745
+ throw new Boom(
1744
1746
  'Send error 463: server did not issue a tctoken for ' + tcJid +
1745
- ' (IQ timeout or account restricted)'
1747
+ ' (IQ timeout or account restricted)', { statusCode: 463 }
1746
1748
  );
1747
1749
  }
1748
1750
  _whaDbg('[DBG] ACK_463 token stored for ' + tcJid + ' — retrying send\n');
@@ -1758,7 +1760,7 @@ class MessageSender {
1758
1760
  .then(r => resolve(r))
1759
1761
  .catch(err => {
1760
1762
  _whaDbg('[DBG] ACK_463 recovery failed: ' + (err && err.message));
1761
- reject(new Error('Send error 463: tctoken recovery failed — ' + (err && err.message)));
1763
+ reject(new Boom('Send error 463: tctoken recovery failed — ' + (err && err.message), { statusCode: 463 }));
1762
1764
  })
1763
1765
  .finally(() => client._inFlight463Recoveries.delete(tcJid));
1764
1766
  return;
@@ -1766,7 +1768,7 @@ class MessageSender {
1766
1768
  // ─────────────────────────────────────────────────────────────
1767
1769
 
1768
1770
  if (error) {
1769
- reject(new Error('Send error ' + error + ' for ' + id));
1771
+ reject(new Boom('Send error ' + error + ' for ' + id, { statusCode: statusFrom(error, 500) }));
1770
1772
  } else {
1771
1773
  resolve({
1772
1774
  id,
@@ -1894,7 +1896,7 @@ class MessageSender {
1894
1896
  _toMediaBuffer(data) {
1895
1897
  if (Buffer.isBuffer(data)) return data;
1896
1898
  if (typeof data === 'string') return fs.readFileSync(data);
1897
- throw new Error('Media must be a Buffer or file path');
1899
+ throw new Boom('Media must be a Buffer or file path', { statusCode: 400 });
1898
1900
  }
1899
1901
 
1900
1902
  async _uploadMedia(mediaType, data) {
@@ -1917,7 +1919,7 @@ class MessageSender {
1917
1919
 
1918
1920
  async _fetchMediaConn() {
1919
1921
  if (!this._client || !this._client._connected) {
1920
- throw new Error('Cannot fetch media connection: not connected');
1922
+ throw new Boom('Cannot fetch media connection: not connected', { statusCode: 428 });
1921
1923
  }
1922
1924
  return new Promise((resolve, reject) => {
1923
1925
  const cleanup = () => {
@@ -1927,19 +1929,19 @@ class MessageSender {
1927
1929
  };
1928
1930
  const timeout = setTimeout(() => {
1929
1931
  cleanup();
1930
- reject(new Error('Timeout waiting for media connection'));
1932
+ reject(new Boom('Timeout waiting for media connection', { statusCode: 408 }));
1931
1933
  }, 15000);
1932
1934
  const onConn = ({ hosts, auth, ttl }) => {
1933
1935
  cleanup();
1934
1936
  if (!hosts || !hosts.length) {
1935
- return reject(new Error('Media connection returned no upload hosts'));
1937
+ return reject(new Boom('Media connection returned no upload hosts', { statusCode: 502 }));
1936
1938
  }
1937
1939
  this.setMediaConnection(hosts, auth, ttl, Date.now());
1938
1940
  resolve();
1939
1941
  };
1940
1942
  const onErr = (err) => {
1941
1943
  cleanup();
1942
- reject(err instanceof Error ? err : new Error(String(err)));
1944
+ reject(err instanceof Error ? err : new Boom(String(err)));
1943
1945
  };
1944
1946
  this._client.once('media_conn', onConn);
1945
1947
  this._client.once('media_conn_error', onErr);
package/lib/noise.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 net = require('net');
4
6
  const { hkdfSha256 } = require('./hkdf');
5
7
  const crypto = require('crypto');
@@ -80,7 +82,7 @@ function _pbReadFields(buf) {
80
82
  }
81
83
 
82
84
  function _certFail(what) {
83
- throw new Error('WA server cert validation failed: ' + what);
85
+ throw new Boom('WA server cert validation failed: ' + what, { statusCode: 502 });
84
86
  }
85
87
 
86
88
  function _certBytes(value, what) {
@@ -218,7 +220,7 @@ function memClassFromRam(ramGiB) {
218
220
  function stripKeyPrefix(pub) {
219
221
  if (pub.length === 33 && pub[0] === 0x05) return pub.slice(1);
220
222
  if (pub.length === 32) return pub;
221
- throw new Error('Invalid DH public key length: ' + pub.length);
223
+ throw new Boom('Invalid DH public key length: ' + pub.length, { statusCode: 400 });
222
224
  }
223
225
 
224
226
  function dhShared(privKey32, pubKey) {
@@ -318,7 +320,7 @@ function makeFrame(payload) {
318
320
  const len = payload.length;
319
321
  if (len > MAX_FRAME_LENGTH) {
320
322
  // Silently truncating the length here would desync the stream for good.
321
- throw new Error('Frame length ' + len + ' exceeds ' + MAX_FRAME_LENGTH);
323
+ throw new Boom('Frame length ' + len + ' exceeds ' + MAX_FRAME_LENGTH, { statusCode: 413 });
322
324
  }
323
325
  const header = Buffer.alloc(FRAME_HEADER_SIZE);
324
326
  header[0] = (len >>> 16) & 0xff;
@@ -405,7 +407,7 @@ class NoiseSocket extends EventEmitter {
405
407
  // never completes, not just a TCP one.
406
408
  this._connectTimeoutTimer = setTimeout(() => {
407
409
  if (this._connectReject) {
408
- const err = new Error('WA TCP connect timeout (20s)');
410
+ const err = new Boom('WA TCP connect timeout (20s)', { statusCode: 408 });
409
411
  this._connectReject(err);
410
412
  this._connectResolve = null;
411
413
  this._connectReject = null;
@@ -520,7 +522,7 @@ class NoiseSocket extends EventEmitter {
520
522
  _whaDbg('[DBG] NOISE ◀── ServerHello ephemeral=' + _hsSize(serverHello.ephemeral) +
521
523
  ' static=' + _hsSize(serverHello.staticEnc) + ' encrypted' +
522
524
  ' certificate=' + _hsSize(serverHello.payload) + ' encrypted');
523
- if (!serverHello.ephemeral) throw new Error('No server ephemeral in ServerHello');
525
+ if (!serverHello.ephemeral) throw new Boom('No server ephemeral in ServerHello', { statusCode: 502 });
524
526
  _whaDbg('[DBG] NOISE ◀── server ephemeral=' + _hsKey(serverHello.ephemeral));
525
527
 
526
528
  this.noiseState.hash(serverHello.ephemeral);
@@ -538,7 +540,7 @@ class NoiseSocket extends EventEmitter {
538
540
  // static key and payload. A ServerHello without a certificate leaves
539
541
  // nothing to authenticate it with, so it does not get that far.
540
542
  if (!serverHello.payload) {
541
- throw new Error('WA server cert validation failed: the server sent no certificate');
543
+ throw new Boom('WA server cert validation failed: the server sent no certificate', { statusCode: 502 });
542
544
  }
543
545
  const certPlain = this.noiseState.decryptWithAd(serverHello.payload);
544
546
  _whaDbg('[DBG] NOISE ◀── certificate decrypted=' + certPlain.length + 'B — verifying');
@@ -828,8 +830,8 @@ class NoiseSocket extends EventEmitter {
828
830
  'to re-register.';
829
831
  }
830
832
 
831
- const err = new Error('WhatsApp auth failure ' + reason +
832
- (detail ? ' — ' + detail : ''));
833
+ const err = new Boom('WhatsApp auth failure ' + reason +
834
+ (detail ? ' — ' + detail : ''), { statusCode: statusFrom(reason, 401) });
833
835
  err.code = reason;
834
836
  // A temporary ban says which kind and for how long.
835
837
  if (reason === '402') {
@@ -850,7 +852,7 @@ class NoiseSocket extends EventEmitter {
850
852
  }
851
853
 
852
854
  // Unexpected first node — log it as an error but try to continue
853
- const err = new Error('Unexpected first server node after handshake: ' + tag);
855
+ const err = new Boom('Unexpected first server node after handshake: ' + tag, { statusCode: 502 });
854
856
  if (this._connectReject) {
855
857
  this._connectReject(err);
856
858
  this._connectResolve = null;
@@ -876,7 +878,7 @@ class NoiseSocket extends EventEmitter {
876
878
  }
877
879
 
878
880
  sendNode(node) {
879
- if (!this.secured) throw new Error('Channel not secured — handshake incomplete');
881
+ if (!this.secured) throw new Boom('Channel not secured — handshake incomplete', { statusCode: 428 });
880
882
  const { encodeNode } = require('./BinaryNode');
881
883
  const plain = encodeNode(node);
882
884
  const ciphertext = aesgcmEncrypt(this.writeKey, this.writeCounter++, plain, null);
@@ -902,7 +904,7 @@ class NoiseSocket extends EventEmitter {
902
904
  // If the TCP connection closed while the WA handshake was still in progress,
903
905
  // the Promise returned by connect() would hang forever — reject it now.
904
906
  if (this._connectReject) {
905
- this._connectReject(new Error('WA TCP closed during handshake'));
907
+ this._connectReject(new Boom('WA TCP closed during handshake', { statusCode: 428 }));
906
908
  this._connectResolve = null;
907
909
  this._connectReject = null;
908
910
  }
package/lib/plist.js CHANGED
@@ -1,4 +1,7 @@
1
1
  'use strict';
2
+
3
+ const { Boom } = require('@hapi/boom');
4
+
2
5
  //
3
6
  // ─── Property lists ───────────────────────────────────────────────────────────
4
7
  //
@@ -194,7 +197,7 @@ class XmlScanner {
194
197
  expectClose(name) {
195
198
  const tag = this.nextTag();
196
199
  if (!tag || !tag.closing || tag.name !== name) {
197
- throw new Error('plist: expected </' + name + '>');
200
+ throw new Boom('plist: expected </' + name + '>', { statusCode: 400 });
198
201
  }
199
202
  }
200
203
  }
@@ -245,7 +248,7 @@ function parseXmlValue(scanner, tag) {
245
248
  if (tag.selfClosing) return items;
246
249
  for (;;) {
247
250
  const next = scanner.nextTag();
248
- if (!next) throw new Error('plist: unterminated <array>');
251
+ if (!next) throw new Boom('plist: unterminated <array>', { statusCode: 400 });
249
252
  if (next.closing && next.name === 'array') return items;
250
253
  items.push(parseXmlValue(scanner, next));
251
254
  }
@@ -255,17 +258,17 @@ function parseXmlValue(scanner, tag) {
255
258
  if (tag.selfClosing) return dict;
256
259
  for (;;) {
257
260
  const keyTag = scanner.nextTag();
258
- if (!keyTag) throw new Error('plist: unterminated <dict>');
261
+ if (!keyTag) throw new Boom('plist: unterminated <dict>', { statusCode: 400 });
259
262
  if (keyTag.closing && keyTag.name === 'dict') return dict;
260
- if (keyTag.name !== 'key') throw new Error('plist: expected <key>, saw <' + keyTag.name + '>');
263
+ if (keyTag.name !== 'key') throw new Boom('plist: expected <key>, saw <' + keyTag.name + '>', { statusCode: 400 });
261
264
  const key = parseXmlValue(scanner, keyTag);
262
265
  const valueTag = scanner.nextTag();
263
- if (!valueTag) throw new Error('plist: <key>' + key + '</key> has no value');
266
+ if (!valueTag) throw new Boom('plist: <key>' + key + '</key> has no value', { statusCode: 400 });
264
267
  dict[key] = parseXmlValue(scanner, valueTag);
265
268
  }
266
269
  }
267
270
  default:
268
- throw new Error('plist: unsupported element <' + tag.name + '>');
271
+ throw new Boom('plist: unsupported element <' + tag.name + '>', { statusCode: 400 });
269
272
  }
270
273
  }
271
274
 
@@ -273,7 +276,7 @@ function parseXml(buf) {
273
276
  const scanner = new XmlScanner(buf.toString('utf8'));
274
277
  for (;;) {
275
278
  const tag = scanner.nextTag();
276
- if (!tag) throw new Error('plist: no root element');
279
+ if (!tag) throw new Boom('plist: no root element', { statusCode: 400 });
277
280
  // <plist> is a container, not a value; step through it to its single child.
278
281
  if (tag.name === 'plist' && !tag.closing) continue;
279
282
  if (tag.closing) continue;
@@ -294,7 +297,7 @@ function isBinary(buf) {
294
297
 
295
298
  class BinaryPlistReader {
296
299
  constructor(buf) {
297
- if (buf.length < MAGIC.length + 32) throw new Error('plist: binary plist too short');
300
+ if (buf.length < MAGIC.length + 32) throw new Boom('plist: binary plist too short', { statusCode: 400 });
298
301
  const trailer = buf.length - 32;
299
302
  this.buf = buf;
300
303
  this.offsetSize = buf[trailer + 6];
@@ -304,10 +307,10 @@ class BinaryPlistReader {
304
307
  this.tableOffset = Number(buf.readBigUInt64BE(trailer + 24));
305
308
 
306
309
  if (this.offsetSize < 1 || this.offsetSize > 8 || this.refSize < 1 || this.refSize > 8) {
307
- throw new Error('plist: implausible binary plist trailer');
310
+ throw new Boom('plist: implausible binary plist trailer', { statusCode: 400 });
308
311
  }
309
312
  if (this.tableOffset + this.count * this.offsetSize > trailer) {
310
- throw new Error('plist: binary plist offset table out of range');
313
+ throw new Boom('plist: binary plist offset table out of range', { statusCode: 400 });
311
314
  }
312
315
  }
313
316
 
@@ -318,7 +321,7 @@ class BinaryPlistReader {
318
321
  }
319
322
 
320
323
  offsetOf(index) {
321
- if (index < 0 || index >= this.count) throw new Error('plist: object index out of range');
324
+ if (index < 0 || index >= this.count) throw new Boom('plist: object index out of range', { statusCode: 400 });
322
325
  return Number(this.uint(this.tableOffset + index * this.offsetSize, this.offsetSize));
323
326
  }
324
327
 
@@ -328,7 +331,7 @@ class BinaryPlistReader {
328
331
  sizeAt(offset, info) {
329
332
  if (info !== 0x0f) return { count: info, start: offset + 1 };
330
333
  const marker = this.buf[offset + 1];
331
- if ((marker & 0xf0) !== 0x10) throw new Error('plist: bad extended length marker');
334
+ if ((marker & 0xf0) !== 0x10) throw new Boom('plist: bad extended length marker', { statusCode: 400 });
332
335
  const width = 1 << (marker & 0x0f);
333
336
  return {
334
337
  count: Number(this.uint(offset + 2, width)),
@@ -347,7 +350,7 @@ class BinaryPlistReader {
347
350
  if (info === 0x00) return null;
348
351
  if (info === 0x08) return false;
349
352
  if (info === 0x09) return true;
350
- throw new Error('plist: unsupported singleton 0x0' + info.toString(16));
353
+ throw new Boom('plist: unsupported singleton 0x0' + info.toString(16), { statusCode: 400 });
351
354
 
352
355
  case 0x1: {
353
356
  const width = 1 << info;
@@ -362,7 +365,7 @@ class BinaryPlistReader {
362
365
  case 0x2:
363
366
  if (info === 2) return this.buf.readFloatBE(offset + 1);
364
367
  if (info === 3) return this.buf.readDoubleBE(offset + 1);
365
- throw new Error('plist: unsupported real width');
368
+ throw new Boom('plist: unsupported real width', { statusCode: 400 });
366
369
 
367
370
  case 0x3:
368
371
  return new Date(this.buf.readDoubleBE(offset + 1) * 1000 + APPLE_EPOCH_OFFSET_MS);
@@ -412,7 +415,7 @@ class BinaryPlistReader {
412
415
  }
413
416
 
414
417
  default:
415
- throw new Error('plist: unsupported marker 0x' + marker.toString(16));
418
+ throw new Boom('plist: unsupported marker 0x' + marker.toString(16), { statusCode: 400 });
416
419
  }
417
420
  }
418
421
  }
@@ -16,6 +16,7 @@
16
16
  // than exported with a quiet hole in it. A contact the store kept under both
17
17
  // their phone number and their lid goes over as one conversation, as the
18
18
  // phone shows them.
19
+ const { Boom } = require('@hapi/boom');
19
20
  const zlib = require('node:zlib');
20
21
  const { Writer } = require('protobufjs/minimal');
21
22
 
@@ -32,7 +33,7 @@ const isUint = (v, max) => Number.isInteger(v) && v >= 0 && v <= max;
32
33
 
33
34
  function failure(code, detail) {
34
35
  const full = 'PRIMARY_HISTORY_EXPORT_' + code;
35
- const error = new Error(detail ? full + ': ' + detail : full);
36
+ const error = new Boom(detail ? full + ': ' + detail : full);
36
37
  error.code = full;
37
38
  return error;
38
39
  }
@@ -25,6 +25,7 @@
25
25
  // refused to write all end up in `losses`. Revoked, expired and view-once
26
26
  // content is dropped the moment it is known, never handed out, and taken off
27
27
  // the disk at the next turn of the event loop.
28
+ const { Boom } = require('@hapi/boom');
28
29
  const fs = require('node:fs');
29
30
  const path = require('node:path');
30
31
  const crypto = require('node:crypto');
@@ -72,7 +73,12 @@ const isGroup = jid => jid.endsWith('@g.us');
72
73
 
73
74
  function failure(code, detail, cause) {
74
75
  const full = 'PRIMARY_MESSAGE_STORE_' + code;
75
- const error = new Error(detail ? full + ': ' + detail : full, cause ? { cause } : undefined);
76
+ const error = new Boom(detail ? full + ': ' + detail : full);
77
+ // Boom takes no `cause`; set it the way Error's own option does.
78
+ if (cause) {
79
+ Object.defineProperty(error, 'cause',
80
+ { value: cause, writable: true, configurable: true, enumerable: false });
81
+ }
76
82
  error.code = full;
77
83
  return error;
78
84
  }
@@ -215,7 +221,7 @@ function setCorruptAside(files, at) {
215
221
  const moved = [];
216
222
  try {
217
223
  for (const file of files.filter(exists)) {
218
- if (exists(file + suffix)) throw new Error(file + suffix + ' already exists');
224
+ if (exists(file + suffix)) throw new Boom(file + suffix + ' already exists', { statusCode: 409 });
219
225
  fs.renameSync(file, file + suffix);
220
226
  moved.push(file);
221
227
  }
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
4
+
3
5
  const WIRE_VARINT = 0;
4
6
  const WIRE_64 = 1;
5
7
  const WIRE_LEN = 2;
@@ -366,7 +368,7 @@ function encodePinInChatMessage(opts) {
366
368
  const ENC_ADDON_FIELD = { encReaction: 56, encComment: 71, encEventResponse: 76 };
367
369
  function encodeEncAddOnMessage(type, opts) {
368
370
  const num = ENC_ADDON_FIELD[type];
369
- if (!num) throw new Error('unknown encrypted add-on ' + type);
371
+ if (!num) throw new Boom('unknown encrypted add-on ' + type, { statusCode: 400 });
370
372
  return field(num, WIRE_LEN, Buffer.concat([
371
373
  field(1, WIRE_LEN, encodeMessageKey(opts.key)),
372
374
  field(2, WIRE_LEN, bytes(opts.encPayload)),
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
3
4
  const { dbg: _whaDbg } = require('../logger');
4
5
  const { hkdfSha256 } = require('../hkdf');
5
6
 
@@ -411,10 +412,10 @@ class SenderKeyCrypto {
411
412
  }
412
413
  const currentIter = state.iteration;
413
414
  if (iteration < currentIter) {
414
- throw new Error('SenderKey: old message key not found for iteration ' + iteration);
415
+ throw new Boom('SenderKey: old message key not found for iteration ' + iteration, { statusCode: 404 });
415
416
  }
416
417
  if (iteration - currentIter > 2000) {
417
- throw new Error('SenderKey: message too far ahead (over 2000 iterations)');
418
+ throw new Boom('SenderKey: message too far ahead (over 2000 iterations)', { statusCode: 400 });
418
419
  }
419
420
  // Advance chain, caching skipped keys
420
421
  let chainKey = state.chainKey;
@@ -470,7 +471,7 @@ class SenderKeyCrypto {
470
471
 
471
472
  const version = ciphertext[0];
472
473
  if ((version & 0xf) !== 3) {
473
- throw new Error('Unknown SenderKeyMessage version: ' + version);
474
+ throw new Boom('Unknown SenderKeyMessage version: ' + version, { statusCode: 400 });
474
475
  }
475
476
 
476
477
  const SIG_LEN = 64;
@@ -487,7 +488,7 @@ class SenderKeyCrypto {
487
488
  const sigPub = senderKeyState.signingKey.pub;
488
489
 
489
490
  const ok = curveJs.verify(sigPub, forVerify, sig);
490
- if (!ok) throw new Error('SenderKeyMessage signature verification failed');
491
+ if (!ok) throw new Boom('SenderKeyMessage signature verification failed', { statusCode: 400 });
491
492
 
492
493
  const messageKey = this._getMessageKeyAtIteration(senderKeyState, iteration);
493
494
  const { iv, cipherKey } = deriveMessageKeys(messageKey);
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
3
4
  const keyhelper = require('./keyhelper');
4
5
  const { SenderKeyDistributionMessage } = require('./sender-key-distribution-message');
5
6
  const { SenderKeyRecord } = require('./sender-key-record');
@@ -31,7 +32,7 @@ class GroupSessionBuilder {
31
32
  }
32
33
  const state = senderKeyRecord.getSenderKeyState();
33
34
  if (!state) {
34
- throw new Error('No session state available');
35
+ throw new Boom('No session state available', { statusCode: 404 });
35
36
  }
36
37
  return new SenderKeyDistributionMessage(
37
38
  state.getKeyId(),
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
3
4
  const { decrypt, encrypt } = require('../libsignal/crypto');
4
5
  const { SenderKeyMessage } = require('./sender-key-message');
5
6
  const { SenderKeyRecord } = require('./sender-key-record');
@@ -13,11 +14,11 @@ class GroupCipher {
13
14
  async encrypt(paddedPlaintext) {
14
15
  const record = await this.senderKeyStore.loadSenderKey(this.senderKeyName);
15
16
  if (!record) {
16
- throw new Error('No SenderKeyRecord found for encryption');
17
+ throw new Boom('No SenderKeyRecord found for encryption', { statusCode: 404 });
17
18
  }
18
19
  const senderKeyState = record.getSenderKeyState();
19
20
  if (!senderKeyState) {
20
- throw new Error('No session to encrypt message');
21
+ throw new Boom('No session to encrypt message', { statusCode: 404 });
21
22
  }
22
23
  const iteration = senderKeyState.getSenderChainKey().getIteration();
23
24
  const senderKey = this.getSenderKey(senderKeyState, iteration === 0 ? 0 : iteration + 1);
@@ -35,12 +36,12 @@ class GroupCipher {
35
36
  async decrypt(senderKeyMessageBytes) {
36
37
  const record = await this.senderKeyStore.loadSenderKey(this.senderKeyName);
37
38
  if (!record) {
38
- throw new Error('No SenderKeyRecord found for decryption');
39
+ throw new Boom('No SenderKeyRecord found for decryption', { statusCode: 404 });
39
40
  }
40
41
  const senderKeyMessage = new SenderKeyMessage(null, null, null, null, senderKeyMessageBytes);
41
42
  const senderKeyState = record.getSenderKeyState(senderKeyMessage.getKeyId());
42
43
  if (!senderKeyState) {
43
- throw new Error('No session found to decrypt message');
44
+ throw new Boom('No session found to decrypt message', { statusCode: 404 });
44
45
  }
45
46
  senderKeyMessage.verifySignature(senderKeyState.getSigningKeyPublic());
46
47
  const senderKey = this.getSenderKey(senderKeyState, senderKeyMessage.getIteration());
@@ -55,14 +56,14 @@ class GroupCipher {
55
56
  if (senderKeyState.hasSenderMessageKey(iteration)) {
56
57
  const messageKey = senderKeyState.removeSenderMessageKey(iteration);
57
58
  if (!messageKey) {
58
- throw new Error('No sender message key found for iteration');
59
+ throw new Boom('No sender message key found for iteration', { statusCode: 404 });
59
60
  }
60
61
  return messageKey;
61
62
  }
62
- throw new Error(`Received message with old counter: ${senderChainKey.getIteration()}, ${iteration}`);
63
+ throw new Boom(`Received message with old counter: ${senderChainKey.getIteration()}, ${iteration}`, { statusCode: 400 });
63
64
  }
64
65
  if (iteration - senderChainKey.getIteration() > 2000) {
65
- throw new Error('Over 2000 messages into the future!');
66
+ throw new Boom('Over 2000 messages into the future!', { statusCode: 400 });
66
67
  }
67
68
  while (senderChainKey.getIteration() < iteration) {
68
69
  senderKeyState.addSenderMessageKey(senderChainKey.getSenderMessageKey());
@@ -76,7 +77,7 @@ class GroupCipher {
76
77
  try {
77
78
  return decrypt(key, ciphertext, iv);
78
79
  } catch (e) {
79
- throw new Error('InvalidMessageException');
80
+ throw new Boom('InvalidMessageException', { statusCode: 400 });
80
81
  }
81
82
  }
82
83
 
@@ -84,7 +85,7 @@ class GroupCipher {
84
85
  try {
85
86
  return encrypt(key, plaintext, iv);
86
87
  } catch (e) {
87
- throw new Error('InvalidMessageException');
88
+ throw new Boom('InvalidMessageException', { statusCode: 400 });
88
89
  }
89
90
  }
90
91
  }
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
3
4
  const { CiphertextMessage } = require('./ciphertext-message');
4
5
 
5
6
  // ─── Minimal protobuf encode/decode for SenderKeyDistributionMessage ──────────
@@ -91,7 +92,7 @@ class SenderKeyDistributionMessage extends CiphertextMessage {
91
92
  ? decoded.signingKey
92
93
  : Buffer.from(decoded.signingKey);
93
94
  } catch (e) {
94
- throw new Error(String(e));
95
+ throw new Boom(String(e));
95
96
  }
96
97
  } else {
97
98
  const version = this.intsToByteHighAndLow(this.CURRENT_VERSION, this.CURRENT_VERSION);
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
3
4
  const { calculateSignature, verifySignature } = require('../libsignal/curve');
4
5
  const { CiphertextMessage } = require('./ciphertext-message');
5
6
 
@@ -120,7 +121,7 @@ class SenderKeyMessage extends CiphertextMessage {
120
121
  const part1 = this.serialized.slice(0, this.serialized.length - this.SIGNATURE_LENGTH);
121
122
  const part2 = this.serialized.slice(-1 * this.SIGNATURE_LENGTH);
122
123
  const res = verifySignature(signatureKey, part1, part2);
123
- if (!res) throw new Error('Invalid signature!');
124
+ if (!res) throw new Boom('Invalid signature!', { statusCode: 400 });
124
125
  }
125
126
 
126
127
  getSignature(signatureKey, serialized) {