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
@@ -17,6 +17,8 @@
17
17
  // recipient's client knows a message from device 7 of an account is genuinely
18
18
  // from that account.
19
19
 
20
+ const { Boom } = require('@hapi/boom');
21
+ const { statusFrom } = require('./errors');
20
22
  const crypto = require('crypto');
21
23
  const curveJs = require('./curve');
22
24
 
@@ -117,7 +119,7 @@ const PAIR_ERROR = {
117
119
  };
118
120
 
119
121
  function pairFailure(message, kind) {
120
- const err = new Error(message);
122
+ const err = new Boom(message, { statusCode: statusFrom(kind && kind.code, 500) });
121
123
  err.pairError = kind;
122
124
  return err;
123
125
  }
@@ -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
 
5
6
  const { BinaryNode } = require('./BinaryNode');
@@ -455,7 +456,7 @@ class DeviceManager {
455
456
  // USyncUser().withId(jid) → <user jid="...">.
456
457
  async executeUSyncQuery(usyncQuery) {
457
458
  if (!usyncQuery || usyncQuery.protocols.length === 0) {
458
- throw new Error('USyncQuery must have at least one protocol');
459
+ throw new Boom('USyncQuery must have at least one protocol', { statusCode: 400 });
459
460
  }
460
461
 
461
462
  // Convert a WAUSync element ({ tag, attrs, content }) into a BinaryNode.
@@ -25,6 +25,8 @@
25
25
  * {phone}.appStateKeys.json — app-state sync keys received from server
26
26
  */
27
27
 
28
+ const { Boom } = require('@hapi/boom');
29
+ const { statusFrom } = require('./errors');
28
30
  const crypto = require('crypto');
29
31
  const { hkdfSha256 } = require('./hkdf');
30
32
  const https = require('https');
@@ -466,7 +468,7 @@ function decryptHistoryBlob(encryptedWithMac, mediaKeyBuf) {
466
468
  .slice(0, MAC_LEN);
467
469
 
468
470
  if (!crypto.timingSafeEqual(mac, expectedMac)) {
469
- throw new Error('History blob MAC verification failed — wrong key or corrupted data');
471
+ throw new Boom('History blob MAC verification failed — wrong key or corrupted data', { statusCode: 400 });
470
472
  }
471
473
 
472
474
  const decipher = crypto.createDecipheriv('aes-256-cbc', cipherKey, iv);
@@ -496,10 +498,10 @@ function downloadUrl(url) {
496
498
  const location = res.headers['location'];
497
499
  res.resume();
498
500
  if (location) return resolve(downloadUrl(location));
499
- return reject(new Error('Redirect with no Location header'));
501
+ return reject(new Boom('Redirect with no Location header', { statusCode: 502 }));
500
502
  }
501
503
  if (res.statusCode !== 200) {
502
- reject(new Error('History CDN download failed: HTTP ' + res.statusCode));
504
+ reject(new Boom('History CDN download failed: HTTP ' + res.statusCode, { statusCode: statusFrom(res.statusCode) }));
503
505
  res.resume();
504
506
  return;
505
507
  }
@@ -509,7 +511,7 @@ function downloadUrl(url) {
509
511
  });
510
512
 
511
513
  req.on('error', reject);
512
- req.setTimeout(30000, () => req.destroy(new Error('History CDN download timed out')));
514
+ req.setTimeout(30000, () => req.destroy(new Boom('History CDN download timed out', { statusCode: 408 })));
513
515
  });
514
516
  }
515
517
 
@@ -519,7 +521,7 @@ function inflateBuffer(buf) {
519
521
  if (!err) return resolve(result);
520
522
  zlib.inflateRaw(buf, (err2, result2) => {
521
523
  if (!err2) return resolve(result2);
522
- reject(new Error('zlib inflate failed: ' + err.message));
524
+ reject(new Boom('zlib inflate failed: ' + err.message, { statusCode: 400 }));
523
525
  });
524
526
  });
525
527
  });
@@ -709,7 +711,7 @@ function mergeHistoryToStore(sessionDir, phone, syncData) {
709
711
  * @returns {Promise<object>} Result object emitted in 'history_sync' event
710
712
  */
711
713
  async function processHistorySyncNotification(notification, sessionDir, phone) {
712
- if (!notification) throw new Error('processHistorySyncNotification: missing notification');
714
+ if (!notification) throw new Boom('processHistorySyncNotification: missing notification', { statusCode: 400 });
713
715
 
714
716
  const typeName = HistorySyncTypeName[notification.syncType] || String(notification.syncType);
715
717
 
@@ -732,8 +734,8 @@ async function processHistorySyncNotification(notification, sessionDir, phone) {
732
734
  };
733
735
  } else {
734
736
  if (!notification.directPath || !notification.mediaKey) {
735
- throw new Error('HistorySyncNotification missing directPath or mediaKey' +
736
- ' (syncType=' + typeName + ')');
737
+ throw new Boom('HistorySyncNotification missing directPath or mediaKey' +
738
+ ' (syncType=' + typeName + ')', { statusCode: 400 });
737
739
  }
738
740
 
739
741
  const cdnUrl = 'https://' + CDN_HOST + notification.directPath;
@@ -743,7 +745,7 @@ async function processHistorySyncNotification(notification, sessionDir, phone) {
743
745
  if (notification.fileEncSha256 && notification.fileEncSha256.length > 0) {
744
746
  const actualSha = crypto.createHash('sha256').update(encryptedBlob).digest();
745
747
  if (!actualSha.equals(notification.fileEncSha256)) {
746
- throw new Error('History blob fileEncSha256 mismatch — data corrupted or wrong key');
748
+ throw new Boom('History blob fileEncSha256 mismatch — data corrupted or wrong key', { statusCode: 400 });
747
749
  }
748
750
  }
749
751
 
@@ -753,7 +755,7 @@ async function processHistorySyncNotification(notification, sessionDir, phone) {
753
755
  if (notification.fileSha256 && notification.fileSha256.length > 0) {
754
756
  const actualSha = crypto.createHash('sha256').update(plaintext).digest();
755
757
  if (!actualSha.equals(notification.fileSha256)) {
756
- throw new Error('History blob fileSha256 mismatch after decryption');
758
+ throw new Boom('History blob fileSha256 mismatch after decryption', { statusCode: 400 });
757
759
  }
758
760
  }
759
761
 
@@ -761,7 +763,7 @@ async function processHistorySyncNotification(notification, sessionDir, phone) {
761
763
  }
762
764
 
763
765
  const syncData = decodeHistorySync(decompressed);
764
- if (!syncData) throw new Error('Failed to decode HistorySync protobuf');
766
+ if (!syncData) throw new Boom('Failed to decode HistorySync protobuf', { statusCode: 400 });
765
767
 
766
768
  const merged = mergeHistoryToStore(sessionDir, phone, syncData);
767
769
 
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
4
+ const { statusFrom } = require('./errors');
3
5
  const crypto = require('crypto');
4
6
  const { hkdfSha256 } = require('./hkdf');
5
7
  const https = require('https');
@@ -114,7 +116,7 @@ function decryptMedia(encryptedWithMac, mediaKey, keyName) {
114
116
  .slice(0, MAC_LEN);
115
117
 
116
118
  if (!crypto.timingSafeEqual(mac, expectedMac)) {
117
- throw new Error('Media MAC verification failed');
119
+ throw new Boom('Media MAC verification failed', { statusCode: 400 });
118
120
  }
119
121
 
120
122
  const decipher = crypto.createDecipheriv('aes-256-cbc', cipherKey, iv);
@@ -131,7 +133,7 @@ function decryptMedia(encryptedWithMac, mediaKey, keyName) {
131
133
  // ("connection expired"), because each retry reuses the same stale auth.
132
134
  async function uploadMedia(mediaType, data, hosts, auth, refreshAuth, opts) {
133
135
  const typeInfo = MEDIA_PATH[mediaType];
134
- if (!typeInfo) throw new Error('Unknown media type: ' + mediaType);
136
+ if (!typeInfo) throw new Boom('Unknown media type: ' + mediaType, { statusCode: 400 });
135
137
  const web = !!(opts && opts.web);
136
138
  const uploadPath = mediaPathFor(mediaType, web);
137
139
 
@@ -189,7 +191,7 @@ async function uploadMedia(mediaType, data, hosts, auth, refreshAuth, opts) {
189
191
  refreshed = true;
190
192
  }
191
193
 
192
- throw new Error('Failed to upload media to all available hosts');
194
+ throw new Boom('Failed to upload media to all available hosts', { statusCode: 502 });
193
195
  }
194
196
 
195
197
  // Resolves { status, body } — status 0 marks a transport-level failure, so the
@@ -293,8 +295,8 @@ async function downloadMedia(url, mediaKey, keyName, opts) {
293
295
  crypto.createHash('sha256').update(encrypted).digest(),
294
296
  opts.fileEncSha256, 'fileEncSha256');
295
297
  if (bad) {
296
- throw new Error('downloadMedia: the downloaded file does not match the ' +
297
- 'message (' + bad + ')');
298
+ throw new Boom('downloadMedia: the downloaded file does not match the ' +
299
+ 'message (' + bad + ')', { statusCode: 400 });
298
300
  }
299
301
  }
300
302
 
@@ -305,8 +307,8 @@ async function downloadMedia(url, mediaKey, keyName, opts) {
305
307
  crypto.createHash('sha256').update(plaintext).digest(),
306
308
  opts.fileSha256, 'fileSha256');
307
309
  if (bad) {
308
- throw new Error('downloadMedia: the decrypted file is not the one the ' +
309
- 'message described (' + bad + ')');
310
+ throw new Boom('downloadMedia: the decrypted file is not the one the ' +
311
+ 'message described (' + bad + ')', { statusCode: 400 });
310
312
  }
311
313
  }
312
314
 
@@ -338,19 +340,19 @@ function _httpGet(url, opts, depth) {
338
340
  res.resume(); // drop the redirect body
339
341
  const location = res.headers && res.headers.location;
340
342
  if (!location) {
341
- return reject(new Error('httpGet: the server answered ' + status +
342
- ' without a Location header'));
343
+ return reject(new Boom('httpGet: the server answered ' + status +
344
+ ' without a Location header', { statusCode: 502 }));
343
345
  }
344
346
  const hops = (depth || 0) + 1;
345
347
  if (hops > MAX_REDIRECTS) {
346
- return reject(new Error('httpGet: more than ' + MAX_REDIRECTS +
347
- ' redirects'));
348
+ return reject(new Boom('httpGet: more than ' + MAX_REDIRECTS +
349
+ ' redirects', { statusCode: 502 }));
348
350
  }
349
351
  return _httpGet(location, opts, hops).then(resolve, reject);
350
352
  }
351
353
  if (status < 200 || status > 299) {
352
354
  res.resume(); // an error page, not media
353
- return reject(new Error('httpGet: the server answered ' + status));
355
+ return reject(new Boom('httpGet: the server answered ' + status, { statusCode: statusFrom(status) }));
354
356
  }
355
357
  const chunks = [];
356
358
  res.on('data', c => chunks.push(c));
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
4
+
3
5
  // The backlog the server flushes on reconnect, processed at a pace that leaves
4
6
  // the process usable.
5
7
  //
@@ -55,7 +57,7 @@ function makeOfflineNodeProcessor(handlers, deps, batchSize) {
55
57
  const handler = handlers.get(tag);
56
58
 
57
59
  if (!handler) {
58
- deps.onError(new Error('unknown offline stanza: ' + tag), 'offline ' + tag);
60
+ deps.onError(new Boom('unknown offline stanza: ' + tag, { statusCode: 501 }), 'offline ' + tag);
59
61
  continue;
60
62
  }
61
63
 
@@ -24,6 +24,7 @@
24
24
  // After that the server drops the connection with a 515 and the next one logs
25
25
  // in normally.
26
26
 
27
+ const { Boom } = require('@hapi/boom');
27
28
  const crypto = require('crypto');
28
29
  const { hkdfSha256 } = require('./hkdf');
29
30
  const curveJs = require('./curve');
@@ -126,7 +127,7 @@ async function buildWrappedEphemeralPub(pairingCode, ephemeralPublicKey) {
126
127
  async function decipherLinkPublicKey(data, pairingCode) {
127
128
  const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
128
129
  if (buf.length < 80) {
129
- throw new Error('link_code_pairing_wrapped_primary_ephemeral_pub too short: ' + buf.length);
130
+ throw new Boom('link_code_pairing_wrapped_primary_ephemeral_pub too short: ' + buf.length, { statusCode: 400 });
130
131
  }
131
132
  const salt = buf.slice(0, 32);
132
133
  const iv = buf.slice(32, 48);
@@ -32,6 +32,7 @@
32
32
  // Nothing here talks to the network or to an authenticator. These are the
33
33
  // encodings and derivations; the client drives them.
34
34
 
35
+ const { Boom } = require('@hapi/boom');
35
36
  const crypto = require('crypto');
36
37
  const { hkdfSha256 } = require('./hkdf');
37
38
  const curveJs = require('./curve');
@@ -75,7 +76,7 @@ function readFields(buf) {
75
76
  const readVarint = () => {
76
77
  let v = 0, shift = 0;
77
78
  for (;;) {
78
- if (pos >= buf.length) throw new Error('truncated protobuf');
79
+ if (pos >= buf.length) throw new Boom('truncated protobuf', { statusCode: 400 });
79
80
  const b = buf[pos++];
80
81
  v += (b & 0x7f) * Math.pow(2, shift);
81
82
  if (!(b & 0x80)) return v;
@@ -90,7 +91,7 @@ function readFields(buf) {
90
91
  fields[num] = readVarint();
91
92
  } else if (wire === 2) {
92
93
  const len = readVarint();
93
- if (pos + len > buf.length) throw new Error('truncated protobuf');
94
+ if (pos + len > buf.length) throw new Boom('truncated protobuf', { statusCode: 400 });
94
95
  fields[num] = buf.slice(pos, pos + len);
95
96
  pos += len;
96
97
  } else if (wire === 5) {
@@ -98,7 +99,7 @@ function readFields(buf) {
98
99
  } else if (wire === 1) {
99
100
  pos += 8;
100
101
  } else {
101
- throw new Error('unsupported protobuf wire type ' + wire);
102
+ throw new Boom('unsupported protobuf wire type ' + wire, { statusCode: 400 });
102
103
  }
103
104
  }
104
105
  return fields;
@@ -126,12 +127,12 @@ function decodePrimaryEphemeralIdentity(buf) {
126
127
  const f = readFields(Buffer.from(buf));
127
128
  const publicKey = f[1], nonce = f[2];
128
129
  if (!Buffer.isBuffer(publicKey) || publicKey.length !== 32) {
129
- throw new Error('primary ephemeral identity: unexpected public key length ' +
130
- (Buffer.isBuffer(publicKey) ? publicKey.length : 0));
130
+ throw new Boom('primary ephemeral identity: unexpected public key length ' +
131
+ (Buffer.isBuffer(publicKey) ? publicKey.length : 0), { statusCode: 400 });
131
132
  }
132
133
  if (!Buffer.isBuffer(nonce) || nonce.length !== 32) {
133
- throw new Error('primary ephemeral identity: unexpected nonce length ' +
134
- (Buffer.isBuffer(nonce) ? nonce.length : 0));
134
+ throw new Boom('primary ephemeral identity: unexpected nonce length ' +
135
+ (Buffer.isBuffer(nonce) ? nonce.length : 0), { statusCode: 400 });
135
136
  }
136
137
  return { publicKey, nonce };
137
138
  }
@@ -158,17 +159,17 @@ function encodeEncryptedPairingRequest(encryptedPayload, iv) {
158
159
  // base64url or plain base64, and it is normalised on the way out.
159
160
 
160
161
  function toBytes(value, what) {
161
- if (value == null) throw new Error('passkey response: ' + what + ' is missing');
162
+ if (value == null) throw new Boom('passkey response: ' + what + ' is missing', { statusCode: 400 });
162
163
  if (Buffer.isBuffer(value)) return value;
163
164
  if (value instanceof ArrayBuffer) return Buffer.from(value);
164
165
  if (ArrayBuffer.isView(value)) return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
165
166
  if (typeof value === 'string') {
166
167
  if (!/^[A-Za-z0-9+/_-]*={0,2}$/.test(value)) {
167
- throw new Error('passkey response: ' + what + ' is not base64');
168
+ throw new Boom('passkey response: ' + what + ' is not base64', { statusCode: 400 });
168
169
  }
169
170
  return Buffer.from(value.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
170
171
  }
171
- throw new Error('passkey response: ' + what + ' must be bytes or a base64 string');
172
+ throw new Boom('passkey response: ' + what + ' must be bytes or a base64 string', { statusCode: 400 });
172
173
  }
173
174
 
174
175
  const b64url = (buf) => Buffer.from(buf).toString('base64url');
@@ -182,14 +183,14 @@ const b64url = (buf) => Buffer.from(buf).toString('base64url');
182
183
  */
183
184
  function encodeWebAuthnResponse(response) {
184
185
  if (!response || typeof response !== 'object') {
185
- throw new Error('passkey response: an assertion object is required');
186
+ throw new Boom('passkey response: an assertion object is required', { statusCode: 400 });
186
187
  }
187
188
  const inner = response.response;
188
189
  if (!inner || typeof inner !== 'object') {
189
- throw new Error('passkey response: response.response is missing');
190
+ throw new Boom('passkey response: response.response is missing', { statusCode: 400 });
190
191
  }
191
192
  const rawId = toBytes(response.rawId != null ? response.rawId : response.id, 'rawId');
192
- if (!rawId.length) throw new Error('passkey response: rawId is empty');
193
+ if (!rawId.length) throw new Boom('passkey response: rawId is empty', { statusCode: 400 });
193
194
 
194
195
  const body = {
195
196
  id: typeof response.id === 'string' && response.id ? response.id : b64url(rawId),
@@ -211,16 +212,16 @@ function encodeWebAuthnResponse(response) {
211
212
  * is what PublicKeyCredential.parseRequestOptionsFromJSON() takes.
212
213
  */
213
214
  function parseRequestOptions(content) {
214
- if (content == null) throw new Error('passkey request: options are missing');
215
+ if (content == null) throw new Boom('passkey request: options are missing', { statusCode: 400 });
215
216
  const text = Buffer.isBuffer(content) ? content.toString('utf8') : String(content);
216
217
  let parsed;
217
218
  try { parsed = JSON.parse(text); }
218
- catch (_) { throw new Error('passkey request: options are not valid JSON'); }
219
+ catch (_) { throw new Boom('passkey request: options are not valid JSON', { statusCode: 400 }); }
219
220
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
220
- throw new Error('passkey request: options are not an object');
221
+ throw new Boom('passkey request: options are not an object', { statusCode: 400 });
221
222
  }
222
223
  if (typeof parsed.challenge !== 'string' || !parsed.challenge) {
223
- throw new Error('passkey request: options carry no challenge');
224
+ throw new Boom('passkey request: options carry no challenge', { statusCode: 400 });
224
225
  }
225
226
  return parsed;
226
227
  }
package/lib/PlayStore.js CHANGED
@@ -22,6 +22,8 @@
22
22
  // download on a phone connection; only the density splits are actually needed
23
23
  // for the token, so this fetches only those.
24
24
 
25
+ const { Boom } = require('@hapi/boom');
26
+ const { statusFrom } = require('./errors');
25
27
  const https = require('https');
26
28
  const { URL } = require('url');
27
29
  const DEVICE_PROFILE = require('./playstore-device');
@@ -62,7 +64,7 @@ const PERSONAL_PACKAGE = 'com.whatsapp';
62
64
  function _readVarint(buf, pos) {
63
65
  let result = 0, shift = 0, byte;
64
66
  do {
65
- if (pos >= buf.length) throw new Error('truncated varint');
67
+ if (pos >= buf.length) throw new Boom('truncated varint', { statusCode: 400 });
66
68
  byte = buf[pos++];
67
69
  result += (byte & 0x7f) * Math.pow(2, shift);
68
70
  shift += 7;
@@ -150,7 +152,7 @@ function _request(url, opts) {
150
152
  res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks) }));
151
153
  });
152
154
  req.on('error', reject);
153
- req.on('timeout', () => req.destroy(new Error('timeout on ' + url)));
155
+ req.on('timeout', () => req.destroy(new Boom('timeout on ' + url, { statusCode: 408 })));
154
156
  if (opts.body) req.write(opts.body);
155
157
  req.end();
156
158
  });
@@ -218,18 +220,18 @@ async function fetchAnonymousAuth() {
218
220
  if (lastErr) throw lastErr;
219
221
 
220
222
  if (res.status !== 200) {
221
- throw new Error('the Aurora token dispenser answered HTTP ' + res.status +
223
+ throw new Boom('the Aurora token dispenser answered HTTP ' + res.status +
222
224
  ' after ' + DISPENSER_ATTEMPTS + ' attempts' +
223
225
  ' — it is a free third-party service and this is what it does when it is ' +
224
226
  'down or rate limiting. Nothing is wrong with your setup; either try again ' +
225
- 'later or pass an APK path instead.');
227
+ 'later or pass an APK path instead.', { statusCode: statusFrom(res.status) });
226
228
  }
227
229
 
228
230
  let json;
229
231
  try { json = JSON.parse(res.body.toString('utf8')); }
230
- catch (_) { throw new Error('the Aurora token dispenser returned something that is not JSON'); }
232
+ catch (_) { throw new Boom('the Aurora token dispenser returned something that is not JSON', { statusCode: 502 }); }
231
233
  if (!json || !json.authToken) {
232
- throw new Error('the Aurora token dispenser returned no authToken');
234
+ throw new Boom('the Aurora token dispenser returned no authToken', { statusCode: 502 });
233
235
  }
234
236
 
235
237
  const provider = json.deviceInfoProvider || {};
@@ -274,7 +276,7 @@ async function _protoGet(url, headers) {
274
276
  'Accept': 'application/x-protobuf'
275
277
  }, headers)
276
278
  });
277
- if (res.status !== 200) throw new Error('GET ' + url + ' returned HTTP ' + res.status);
279
+ if (res.status !== 200) throw new Boom('GET ' + url + ' returned HTTP ' + res.status, { statusCode: statusFrom(res.status) });
278
280
  return res.body;
279
281
  }
280
282
 
@@ -285,11 +287,11 @@ async function fetchVersion(packageName, headers) {
285
287
  const raw = await _protoGet(DETAILS_URL + '?doc=' + encodeURIComponent(packageName), headers);
286
288
  // ResponseWrapper(1).Payload → detailsResponse(2).docV2(4).docDetails(13).appDetails(1)
287
289
  const details = _walk(raw, [1, 2, 4, 13, 1]);
288
- if (!details) throw new Error('the Play details response carried no AppDetails for ' + packageName);
290
+ if (!details) throw new Boom('the Play details response carried no AppDetails for ' + packageName, { statusCode: 502 });
289
291
  const fields = decodeFields(details);
290
292
  const code = _one(fields, 3);
291
293
  const name = _one(fields, 4);
292
- if (code === null) throw new Error('the Play details response carried no versionCode for ' + packageName);
294
+ if (code === null) throw new Boom('the Play details response carried no versionCode for ' + packageName, { statusCode: 502 });
293
295
  return { versionCode: code, versionName: name ? name.toString('utf8') : '' };
294
296
  }
295
297
 
@@ -316,13 +318,13 @@ async function fetchDelivery(packageName, versionCode, headers) {
316
318
  headers);
317
319
  // ResponseWrapper(1).Payload → deliveryResponse(21).appDeliveryData(2)
318
320
  const data = _walk(raw, [1, 21, 2]);
319
- if (!data) throw new Error('the Play delivery response carried no AppDeliveryData for ' + packageName);
321
+ if (!data) throw new Boom('the Play delivery response carried no AppDeliveryData for ' + packageName, { statusCode: 502 });
320
322
 
321
323
  const fields = decodeFields(data);
322
324
  const baseUrl = _one(fields, 3);
323
325
  if (!baseUrl || !baseUrl.length) {
324
- throw new Error('Play issued no download URL for ' + packageName +
325
- ' — the app is unavailable for this synthetic device profile');
326
+ throw new Boom('Play issued no download URL for ' + packageName +
327
+ ' — the app is unavailable for this synthetic device profile', { statusCode: 502 });
326
328
  }
327
329
 
328
330
  const splits = [];
@@ -359,7 +361,7 @@ async function _download(url, cookies) {
359
361
  if (pairs.length) headers.Cookie = pairs.join('; ');
360
362
  const res = await _request(url, { headers });
361
363
  if (res.status < 200 || res.status >= 300) {
362
- throw new Error('APK download failed with HTTP ' + res.status);
364
+ throw new Boom('APK download failed with HTTP ' + res.status, { statusCode: statusFrom(res.status) });
363
365
  }
364
366
  return res.body;
365
367
  }
@@ -1,13 +1,14 @@
1
1
  'use strict';
2
2
  // Primary-role consumer E2EE linking. This module is pure: no socket, store,
3
3
  // device verification, registration or provider credentials.
4
+ const { Boom } = require('@hapi/boom');
4
5
  const crypto = require('node:crypto');
5
6
  const { Reader, Writer } = require('protobufjs/minimal');
6
7
  const curve = require('./curve');
7
8
  const pairing = require('./PairingCode');
8
9
  const { BinaryNode } = require('./BinaryNode');
9
10
  function failure(code = 'PRIMARY_LINK_INVALID') {
10
- const error = new Error(code);
11
+ const error = new Boom(code, { statusCode: 400 });
11
12
  error.code = code;
12
13
  return error;
13
14
  }