whalibmob 5.40.38 → 5.40.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +1 -0
  2. package/cli.js +5 -4
  3. package/docs/events-history.md +47 -0
  4. package/index.d.ts +19 -0
  5. package/index.js +6 -0
  6. package/lib/AndroidApk.js +13 -12
  7. package/lib/BinaryNode.js +2 -1
  8. package/lib/Client.js +273 -269
  9. package/lib/CompanionPairing.js +3 -1
  10. package/lib/DeviceManager.js +2 -1
  11. package/lib/HistorySyncHandler.js +13 -11
  12. package/lib/MediaService.js +14 -12
  13. package/lib/OfflineNodeProcessor.js +3 -1
  14. package/lib/PairingCode.js +2 -1
  15. package/lib/PasskeyPairing.js +18 -17
  16. package/lib/PlayStore.js +15 -13
  17. package/lib/PrimaryLinkCrypto.js +2 -1
  18. package/lib/Registration.js +37 -35
  19. package/lib/Store.js +6 -5
  20. package/lib/WebSocketStream.js +3 -2
  21. package/lib/WebVersion.js +5 -3
  22. package/lib/apns-courier.js +15 -13
  23. package/lib/apns.js +6 -4
  24. package/lib/argo/ArgoDecoder.js +16 -14
  25. package/lib/auth-utils.js +10 -9
  26. package/lib/cli/linkCommands.js +5 -2
  27. package/lib/curve.js +5 -4
  28. package/lib/errors.js +42 -0
  29. package/lib/fcm.js +7 -5
  30. package/lib/image/JpegEncoder.js +4 -2
  31. package/lib/messages/MediaRetry.js +3 -2
  32. package/lib/messages/MessageSecret.js +9 -8
  33. package/lib/messages/MessageSender.js +30 -28
  34. package/lib/noise.js +13 -11
  35. package/lib/plist.js +18 -15
  36. package/lib/primary/HistoryExport.js +2 -1
  37. package/lib/primary/MessageStore.js +8 -2
  38. package/lib/proto/MessageProto.js +3 -1
  39. package/lib/signal/SenderKey.js +5 -4
  40. package/lib/signal/WaSignalGroup/group-session-builder.js +2 -1
  41. package/lib/signal/WaSignalGroup/group_cipher.js +10 -9
  42. package/lib/signal/WaSignalGroup/sender-key-distribution-message.js +2 -1
  43. package/lib/signal/WaSignalGroup/sender-key-message.js +2 -1
  44. package/lib/socks.js +9 -8
  45. package/lib/store/Backend.js +3 -1
  46. package/lib/store/FileBackend.js +2 -1
  47. package/lib/store/MemoryBackend.js +2 -1
  48. package/lib/store/SqliteBackend.js +6 -5
  49. package/lib/store/migrate.js +2 -1
  50. package/llms.txt +1 -0
  51. package/package.json +2 -1
package/lib/auth-utils.js CHANGED
@@ -30,6 +30,7 @@
30
30
  //
31
31
  // ─────────────────────────────────────────────────────────────────────────────
32
32
 
33
+ const { Boom } = require('@hapi/boom');
33
34
  const { NodeCache } = require('@cacheable/node-cache');
34
35
  const { AsyncLocalStorage } = require('async_hooks');
35
36
  const { Mutex } = require('async-mutex');
@@ -276,9 +277,9 @@ function makeCacheableSignalKeyStore(store, logger, _cache) {
276
277
  */
277
278
  transaction(work, key) {
278
279
  if (typeof store.transaction !== 'function') {
279
- throw new Error(
280
+ throw new Boom(
280
281
  'transaction() is only available when the underlying store was wrapped ' +
281
- 'with addTransactionCapability()'
282
+ 'with addTransactionCapability()', { statusCode: 501 }
282
283
  );
283
284
  }
284
285
  return (async () => {
@@ -610,21 +611,21 @@ function addTransactionCapability(state, logger, opts) {
610
611
  */
611
612
  function assertMeId(store) {
612
613
  if (!store) {
613
- throw new Error(
614
- 'Cannot proceed: no store was given — call createNewStore() first'
614
+ throw new Boom(
615
+ 'Cannot proceed: no store was given — call createNewStore() first', { statusCode: 400 }
615
616
  );
616
617
  }
617
618
  if (!store.phoneNumber) {
618
- throw new Error(
619
- 'Cannot proceed: store has no phoneNumber — call createNewStore() first'
619
+ throw new Boom(
620
+ 'Cannot proceed: store has no phoneNumber — call createNewStore() first', { statusCode: 400 }
620
621
  );
621
622
  }
622
623
  if (!store.registered) {
623
- throw new Error(
624
+ throw new Boom(
624
625
  'Cannot proceed: device is not registered yet — ' +
625
626
  (store.mode === 'web'
626
627
  ? 'link this device first, with a pairing code or by scanning the QR'
627
- : 'complete SMS verification with verifyCode() before sending messages')
628
+ : 'complete SMS verification with verifyCode() before sending messages'), { statusCode: 401 }
628
629
  );
629
630
  }
630
631
 
@@ -662,7 +663,7 @@ function assertMeId(store) {
662
663
  * @returns {object} fresh store / credential object
663
664
  */
664
665
  function initAuthCreds(phoneNumber, options) {
665
- if (!phoneNumber) throw new Error('initAuthCreds: phoneNumber is required');
666
+ if (!phoneNumber) throw new Boom('initAuthCreds: phoneNumber is required', { statusCode: 400 });
666
667
  options = options || {};
667
668
 
668
669
  // The library's own key generation — curve25519, with the right prefixes.
@@ -1,4 +1,7 @@
1
1
  'use strict';
2
+
3
+ const { Boom } = require('@hapi/boom');
4
+
2
5
  // The logic behind the CLI's link commands, with no terminal in it.
3
6
  //
4
7
  // A primary approves a separate companion (WhatsApp Web) and then hands it the
@@ -78,7 +81,7 @@ function size(bytes) {
78
81
  const clock = now => (typeof now === 'function' ? now() : isNum(now) ? now : Date.now());
79
82
 
80
83
  function coded(code, message) {
81
- const error = new Error(message || code);
84
+ const error = new Boom(message || code);
82
85
  error.code = code;
83
86
  return error;
84
87
  }
@@ -821,7 +824,7 @@ async function checkReady(client) {
821
824
  const readiness = await client.getPrimaryLinkReadiness();
822
825
  const blockers = readiness && Array.isArray(readiness.blockers) ? readiness.blockers : [];
823
826
  if (!readiness || readiness.ready !== true) {
824
- if (!blockers.length) throw new Error('the readiness check gave no verdict');
827
+ if (!blockers.length) throw new Boom('the readiness check gave no verdict');
825
828
  const error = coded(blockers[0].code);
826
829
  error.blockers = blockers;
827
830
  error.readiness = readiness;
package/lib/curve.js CHANGED
@@ -31,6 +31,7 @@
31
31
  //
32
32
  // The API is curve25519-js's, unchanged, so this is a drop-in for it.
33
33
 
34
+ const { Boom } = require('@hapi/boom');
34
35
  const crypto = require('crypto');
35
36
  const curveJs = require('curve25519-js');
36
37
 
@@ -93,8 +94,8 @@ function clamp(seed) {
93
94
  */
94
95
  function generateKeyPair(seed) {
95
96
  if (!seed || seed.length !== 32) {
96
- throw new Error('generateKeyPair: seed must be 32 bytes, got ' +
97
- (seed ? seed.length : 'nothing'));
97
+ throw new Boom('generateKeyPair: seed must be 32 bytes, got ' +
98
+ (seed ? seed.length : 'nothing'), { statusCode: 400 });
98
99
  }
99
100
  if (!NATIVE) {
100
101
  const kp = curveJs.generateKeyPair(seed);
@@ -115,8 +116,8 @@ function generateKeyPair(seed) {
115
116
  * @returns {Buffer} 32 bytes
116
117
  */
117
118
  function sharedKey(priv, pub) {
118
- if (!priv || priv.length !== 32) throw new Error('sharedKey: private key must be 32 bytes');
119
- if (!pub || pub.length !== 32) throw new Error('sharedKey: public key must be 32 bytes');
119
+ if (!priv || priv.length !== 32) throw new Boom('sharedKey: private key must be 32 bytes', { statusCode: 400 });
120
+ if (!pub || pub.length !== 32) throw new Boom('sharedKey: public key must be 32 bytes', { statusCode: 400 });
120
121
  if (!NATIVE) return Buffer.from(curveJs.sharedKey(priv, pub));
121
122
  return crypto.diffieHellman({
122
123
  privateKey: _importPrivate(Buffer.from(priv)),
package/lib/errors.js ADDED
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+
3
+ // Every error this library raises itself is a Boom (https://hapi.dev/module/boom)
4
+ // rather than a bare Error. A Boom is still an Error — message, stack and
5
+ // `instanceof Error` are untouched, and so are the string `code`s some errors
6
+ // carry — with an HTTP-style status on top, so a caller can branch on what kind
7
+ // of failure it was instead of matching message text:
8
+ //
9
+ // err.isBoom true for anything raised here
10
+ // err.output.statusCode the status, see below
11
+ // err.data extra detail when there is any, else null
12
+ //
13
+ // The statuses mean the same thing everywhere in the library:
14
+ //
15
+ // 400 the caller passed something unusable, or data would not parse
16
+ // 401 not authenticated — logged out, wrong code or PIN
17
+ // 403 the server refuses this client or account outright
18
+ // 404 something that had to exist does not — a session, a key, a file
19
+ // 405 the call does not apply to this kind of session
20
+ // 408 no answer in time
21
+ // 409 it is already there, or already done
22
+ // 413 something is larger than it is allowed to be
23
+ // 428 not connected, or no session loaded yet
24
+ // 429 too many attempts, wait
25
+ // 500 unexpected — a bug, or a failure that fits nothing above
26
+ // 501 an optional piece (a package, a driver) is not available
27
+ // 502 a server answered, but not with what was asked for
28
+ //
29
+ // When the WhatsApp server or an HTTP endpoint names its own error status, that
30
+ // status is passed through as it came (a 403 stays a 403, a 406 a 406).
31
+
32
+ const { Boom } = require('@hapi/boom');
33
+
34
+ // The status a server gave, when it is one Boom accepts (an integer from 400 to
35
+ // 599); otherwise the fallback. Server codes arrive as strings, numbers, or not
36
+ // at all, and Boom throws on anything below 400.
37
+ function statusFrom(code, fallback = 502) {
38
+ const n = typeof code === 'string' && code.trim() !== '' ? Number(code) : code;
39
+ return Number.isInteger(n) && n >= 400 && n <= 599 ? n : fallback;
40
+ }
41
+
42
+ module.exports = { Boom, statusFrom };
package/lib/fcm.js CHANGED
@@ -33,6 +33,8 @@
33
33
  // registration step would mint a new device each time, which is itself a
34
34
  // pattern no real phone produces.
35
35
 
36
+ const { Boom } = require('@hapi/boom');
37
+ const { statusFrom } = require('./errors');
36
38
  const https = require('https');
37
39
  const zlib = require('zlib');
38
40
  const crypto = require('crypto');
@@ -225,7 +227,7 @@ function httpPost(url, body, headers) {
225
227
  res.on('error', reject);
226
228
  });
227
229
  req.on('error', reject);
228
- req.setTimeout(HTTP_TIMEOUT_MS, () => req.destroy(new Error('timed out')));
230
+ req.setTimeout(HTTP_TIMEOUT_MS, () => req.destroy(new Boom('timed out', { statusCode: 408 })));
229
231
  req.write(body);
230
232
  req.end();
231
233
  });
@@ -242,11 +244,11 @@ async function checkin() {
242
244
  'User-Agent': 'Android-Checkin/2.0 (generic JLS36G); gzip'
243
245
  });
244
246
  if (res.status < 200 || res.status >= 300) {
245
- throw new Error('checkin HTTP ' + res.status);
247
+ throw new Boom('checkin HTTP ' + res.status, { statusCode: statusFrom(res.status) });
246
248
  }
247
249
  const { androidId, securityToken } = decodeCheckinResponse(res.body);
248
250
  if (!androidId || !securityToken) {
249
- throw new Error('checkin returned no android id (' + res.body.length + ' B)');
251
+ throw new Boom('checkin returned no android id (' + res.body.length + ' B)', { statusCode: 502 });
250
252
  }
251
253
  return { androidId: androidId.toString(), securityToken: securityToken.toString() };
252
254
  }
@@ -277,12 +279,12 @@ async function fisInstall(config, existingFid) {
277
279
  'X-Android-Cert': config.certSha1.replace(/:/g, '').toUpperCase()
278
280
  });
279
281
  if (res.status < 200 || res.status >= 300) {
280
- throw new Error('FIS install HTTP ' + res.status + ': ' + res.body.toString('utf8').slice(0, 200));
282
+ throw new Boom('FIS install HTTP ' + res.status + ': ' + res.body.toString('utf8').slice(0, 200), { statusCode: statusFrom(res.status) });
281
283
  }
282
284
 
283
285
  let parsed;
284
286
  try { parsed = JSON.parse(res.body.toString('utf8')); }
285
- catch (_) { throw new Error('FIS install returned non-JSON'); }
287
+ catch (_) { throw new Boom('FIS install returned non-JSON', { statusCode: 502 }); }
286
288
 
287
289
  const auth = parsed.authToken || {};
288
290
  return {
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
4
+
3
5
  // RGBA → baseline JPEG, with nothing installed.
4
6
  //
5
7
  // The forward path of the decoder next door: convert to YCbCr, transform each
@@ -245,8 +247,8 @@ function huffmanSegment(id, bits, values) {
245
247
  * transparent areas come out as whatever colour is underneath them.
246
248
  */
247
249
  function encodeJpeg(data, width, height, quality) {
248
- if (!width || !height) throw new Error('jpeg: cannot encode a picture with no size');
249
- if (data.length < width * height * 4) throw new Error('jpeg: not enough pixel data');
250
+ if (!width || !height) throw new Boom('jpeg: cannot encode a picture with no size', { statusCode: 400 });
251
+ if (data.length < width * height * 4) throw new Boom('jpeg: not enough pixel data', { statusCode: 400 });
250
252
 
251
253
  const q = quality || 50;
252
254
  const lumaQ = scaleQuant(STD_LUMA_QUANT, q);
@@ -27,6 +27,7 @@
27
27
  // The notification comes back under the same key, with the same message id as
28
28
  // the additional data.
29
29
 
30
+ const { Boom } = require('@hapi/boom');
30
31
  const crypto = require('crypto');
31
32
  const { hkdfSha256 } = require('../hkdf');
32
33
 
@@ -52,7 +53,7 @@ function varint(n) {
52
53
  function readVarint(buf, pos) {
53
54
  let result = 0, shift = 0, byte;
54
55
  do {
55
- if (pos >= buf.length) throw new Error('truncated varint');
56
+ if (pos >= buf.length) throw new Boom('truncated varint', { statusCode: 400 });
56
57
  byte = buf[pos++];
57
58
  result |= (byte & 0x7f) << shift;
58
59
  shift += 7;
@@ -126,7 +127,7 @@ function encryptRetryReceipt(msgId, mediaKey) {
126
127
  */
127
128
  function decryptRetryNotification(notif, mediaKey) {
128
129
  const { messageId, ciphertext, iv } = notif;
129
- if (!ciphertext || !iv) throw new Error('media retry notification carried no payload');
130
+ if (!ciphertext || !iv) throw new Boom('media retry notification carried no payload', { statusCode: 502 });
130
131
 
131
132
  const key = mediaRetryKey(mediaKey);
132
133
  const tag = ciphertext.slice(ciphertext.length - 16);
@@ -17,6 +17,7 @@
17
17
  // targetId | 0x00 | addOnSender; the others use none. Both JIDs go in without
18
18
  // a device: an add-on belongs to an account.
19
19
 
20
+ const { Boom } = require('@hapi/boom');
20
21
  const crypto = require('crypto');
21
22
  const { hkdfSha256 } = require('../hkdf');
22
23
 
@@ -52,21 +53,21 @@ function nonAd(jid) {
52
53
  function deriveSecretKey(opts) {
53
54
  const type = opts.type;
54
55
  if (!Object.values(SECRET_TYPE).includes(type)) {
55
- throw new Error('message secret: unknown use case ' + JSON.stringify(type));
56
+ throw new Boom('message secret: unknown use case ' + JSON.stringify(type), { statusCode: 400 });
56
57
  }
57
58
  const secret = opts.messageSecret;
58
59
  if (!secret || secret.length !== 32) {
59
- throw new Error('message secret: the target message\'s 32-byte secret is required');
60
+ throw new Boom('message secret: the target message\'s 32-byte secret is required', { statusCode: 400 });
60
61
  }
61
62
  const targetId = String(opts.targetId || '');
62
- if (!targetId) throw new Error('message secret: the target message id is required');
63
+ if (!targetId) throw new Boom('message secret: the target message id is required', { statusCode: 400 });
63
64
  const targetSender = nonAd(opts.targetSender);
64
65
  const sender = nonAd(opts.sender);
65
66
  if (!targetSender || targetSender.startsWith('@')) {
66
- throw new Error('message secret: who sent the target message is required');
67
+ throw new Boom('message secret: who sent the target message is required', { statusCode: 400 });
67
68
  }
68
69
  if (!sender || sender.startsWith('@')) {
69
- throw new Error('message secret: who sent the add-on is required');
70
+ throw new Boom('message secret: who sent the add-on is required', { statusCode: 400 });
70
71
  }
71
72
  const info = Buffer.from(targetId + targetSender + sender + type, 'utf8');
72
73
  const key = hkdfSha256(Buffer.from(secret), Buffer.alloc(0), info, 32);
@@ -82,7 +83,7 @@ function decryptSecret(opts) {
82
83
  const payload = Buffer.from(opts.encPayload || []);
83
84
  const iv = Buffer.from(opts.encIv || []);
84
85
  if (payload.length < 16 || iv.length !== 12) {
85
- throw new Error('message secret: the add-on carries no usable ciphertext');
86
+ throw new Boom('message secret: the add-on carries no usable ciphertext', { statusCode: 400 });
86
87
  }
87
88
  try {
88
89
  const dec = crypto.createDecipheriv('aes-256-gcm', key, iv);
@@ -90,8 +91,8 @@ function decryptSecret(opts) {
90
91
  dec.setAuthTag(payload.subarray(payload.length - 16));
91
92
  return Buffer.concat([dec.update(payload.subarray(0, payload.length - 16)), dec.final()]);
92
93
  } catch (_) {
93
- throw new Error('message secret: the add-on would not open — wrong secret, ' +
94
- 'or the wrong sender for this target');
94
+ throw new Boom('message secret: the add-on would not open — wrong secret, ' +
95
+ 'or the wrong sender for this target', { statusCode: 400 });
95
96
  }
96
97
  }
97
98
 
@@ -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
  }