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
+
3
5
  // Argo — the binary encoding WhatsApp's GraphQL transport answers in.
4
6
  //
5
7
  // A w:mex reply can come back as JSON or as Argo; the <result> node says which.
@@ -52,14 +54,14 @@ class Reader {
52
54
  }
53
55
  get done() { return this.pos >= this.buf.length; }
54
56
  byte() {
55
- if (this.pos >= this.buf.length) throw new Error('argo: ran off the end of the message');
57
+ if (this.pos >= this.buf.length) throw new Boom('argo: ran off the end of the message', { statusCode: 400 });
56
58
  return this.buf[this.pos++];
57
59
  }
58
60
  peek() { return this.buf[this.pos]; }
59
61
  take(n) {
60
62
  if (n < 0 || this.pos + n > this.buf.length) {
61
- throw new Error('argo: asked for ' + n + ' bytes with ' +
62
- (this.buf.length - this.pos) + ' left');
63
+ throw new Boom('argo: asked for ' + n + ' bytes with ' +
64
+ (this.buf.length - this.pos) + ' left', { statusCode: 400 });
63
65
  }
64
66
  const out = this.buf.slice(this.pos, this.pos + n);
65
67
  this.pos += n;
@@ -73,7 +75,7 @@ class Reader {
73
75
  value |= BigInt(b & 0x7f) << shift;
74
76
  if (!(b & 0x80)) break;
75
77
  shift += 7n;
76
- if (shift > 63n) throw new Error('argo: label is too long to be a number');
78
+ if (shift > 63n) throw new Boom('argo: label is too long to be a number', { statusCode: 400 });
77
79
  }
78
80
  const signed = (value >> 1n) ^ -(value & 1n);
79
81
  return Number(signed);
@@ -115,7 +117,7 @@ class BlockQueue {
115
117
  if (this.inline) return this.inlineBlock;
116
118
  if (!this.byKey.has(key)) {
117
119
  const buf = this.blocks[this.next++];
118
- if (buf === undefined) throw new Error('argo: message is missing a block for ' + key);
120
+ if (buf === undefined) throw new Boom('argo: message is missing a block for ' + key, { statusCode: 400 });
119
121
  this.byKey.set(key, { reader: new Reader(buf), seen: [] });
120
122
  }
121
123
  return this.byKey.get(key);
@@ -128,8 +130,8 @@ function decodeArgo(bytes) {
128
130
  const header = readHeader(reader);
129
131
 
130
132
  if (!header.selfDescribing) {
131
- const err = new Error('argo: this message is encoded against a GraphQL schema ' +
132
- 'rather than describing itself, so it cannot be read without that schema');
133
+ const err = new Boom('argo: this message is encoded against a GraphQL schema ' +
134
+ 'rather than describing itself, so it cannot be read without that schema', { statusCode: 400 });
133
135
  err.needsSchema = true;
134
136
  throw err;
135
137
  }
@@ -140,11 +142,11 @@ function decodeArgo(bytes) {
140
142
  } else {
141
143
  while (!reader.done) {
142
144
  const len = reader.label();
143
- if (len < 0) throw new Error('argo: block length cannot be ' + len);
145
+ if (len < 0) throw new Boom('argo: block length cannot be ' + len, { statusCode: 400 });
144
146
  blocks.push(reader.take(len));
145
147
  }
146
148
  }
147
- if (!blocks.length) throw new Error('argo: message has no core');
149
+ if (!blocks.length) throw new Boom('argo: message has no core', { statusCode: 400 });
148
150
 
149
151
  // The core is the last block, and every other block feeds it.
150
152
  const core = new Reader(blocks[blocks.length - 1]);
@@ -164,11 +166,11 @@ function readBlockValue(core, queue, key, convert) {
164
166
  if (label <= BACKREF_BASE) {
165
167
  const idx = -label + BACKREF_BASE;
166
168
  if (idx < 0 || idx >= block.seen.length) {
167
- throw new Error('argo: backreference ' + label + ' points outside ' + key);
169
+ throw new Boom('argo: backreference ' + label + ' points outside ' + key, { statusCode: 400 });
168
170
  }
169
171
  return block.seen[idx];
170
172
  }
171
- if (label < 0) throw new Error('argo: ' + key + ' cannot have label ' + label);
173
+ if (label < 0) throw new Boom('argo: ' + key + ' cannot have label ' + label, { statusCode: 400 });
172
174
  const value = convert(block.reader.take(label));
173
175
  block.seen.push(value);
174
176
  return value;
@@ -184,7 +186,7 @@ function readValue(core, queue) {
184
186
 
185
187
  case MARKER.OBJECT: {
186
188
  const count = core.label();
187
- if (count < 0) throw new Error('argo: object cannot have ' + count + ' fields');
189
+ if (count < 0) throw new Boom('argo: object cannot have ' + count + ' fields', { statusCode: 400 });
188
190
  const out = {};
189
191
  for (let i = 0; i < count; i++) {
190
192
  const name = readBlockValue(core, queue, 'String', b => b.toString('utf8'));
@@ -195,7 +197,7 @@ function readValue(core, queue) {
195
197
 
196
198
  case MARKER.LIST: {
197
199
  const count = core.label();
198
- if (count < 0) throw new Error('argo: list cannot have ' + count + ' items');
200
+ if (count < 0) throw new Boom('argo: list cannot have ' + count + ' items', { statusCode: 400 });
199
201
  const out = [];
200
202
  for (let i = 0; i < count; i++) out.push(readValue(core, queue));
201
203
  return out;
@@ -218,7 +220,7 @@ function readValue(core, queue) {
218
220
  default:
219
221
  if (marker === LABEL_ABSENT) return undefined;
220
222
  if (marker === LABEL_ERROR) return readValue(core, queue);
221
- throw new Error('argo: unknown type marker ' + marker);
223
+ throw new Boom('argo: unknown type marker ' + marker, { statusCode: 400 });
222
224
  }
223
225
  }
224
226
 
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/constants.js CHANGED
@@ -164,96 +164,101 @@ const IOS_DEVICE_PROFILES = {
164
164
 
165
165
  // ─── Android device profiles ───────────────────────────────────────────────
166
166
  // Set WA_OS=android WA_DEVICE=<key> in .env to select one.
167
+ // firstApiLevel is the Android API level the handset *shipped* with
168
+ // (ro.product.first_api_level), which registration sends as first_api_level. It
169
+ // is not the current OS: a phone launched on Android 13 (API 33) and updated to
170
+ // 14 still reports 33, so the value is pinned per model to the SDK it left the
171
+ // factory on, not derived from osVersion.
167
172
  const ANDROID_DEVICE_PROFILES = {
168
173
  'samsung-s24-ultra': {
169
174
  os: 'android', platform: PLATFORM.ANDROID,
170
175
  model: 'Samsung Galaxy S24 Ultra', manufacturer: 'Samsung',
171
176
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
172
- modelId: 'SM-S928B', deviceModelType: 2, ram: '11.55'
177
+ modelId: 'SM-S928B', deviceModelType: 2, ram: '11.55', firstApiLevel: 34
173
178
  },
174
179
  'samsung-s24': {
175
180
  os: 'android', platform: PLATFORM.ANDROID,
176
181
  model: 'Samsung Galaxy S24', manufacturer: 'Samsung',
177
182
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
178
- modelId: 'SM-S921B', deviceModelType: 2, ram: '7.63'
183
+ modelId: 'SM-S921B', deviceModelType: 2, ram: '7.63', firstApiLevel: 34
179
184
  },
180
185
  'samsung-s23': {
181
186
  os: 'android', platform: PLATFORM.ANDROID,
182
187
  model: 'Samsung Galaxy S23', manufacturer: 'Samsung',
183
188
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
184
- modelId: 'SM-S911B', deviceModelType: 2, ram: '7.63'
189
+ modelId: 'SM-S911B', deviceModelType: 2, ram: '7.63', firstApiLevel: 33
185
190
  },
186
191
  'samsung-s23-ultra': {
187
192
  os: 'android', platform: PLATFORM.ANDROID,
188
193
  model: 'Samsung Galaxy S23 Ultra', manufacturer: 'Samsung',
189
194
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
190
- modelId: 'SM-S918B', deviceModelType: 2, ram: '11.55'
195
+ modelId: 'SM-S918B', deviceModelType: 2, ram: '11.55', firstApiLevel: 33
191
196
  },
192
197
  'samsung-a55': {
193
198
  os: 'android', platform: PLATFORM.ANDROID,
194
199
  model: 'Samsung Galaxy A55', manufacturer: 'Samsung',
195
200
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
196
- modelId: 'SM-A556B', deviceModelType: 1, ram: '7.44'
201
+ modelId: 'SM-A556B', deviceModelType: 1, ram: '7.44', firstApiLevel: 34
197
202
  },
198
203
  'pixel8pro': {
199
204
  os: 'android', platform: PLATFORM.ANDROID,
200
205
  model: 'Pixel 8 Pro', manufacturer: 'Google',
201
206
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
202
- modelId: 'Pixel 8 Pro', deviceModelType: 2, ram: '11.44'
207
+ modelId: 'Pixel 8 Pro', deviceModelType: 2, ram: '11.44', firstApiLevel: 34
203
208
  },
204
209
  'pixel8': {
205
210
  os: 'android', platform: PLATFORM.ANDROID,
206
211
  model: 'Pixel 8', manufacturer: 'Google',
207
212
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
208
- modelId: 'Pixel 8', deviceModelType: 2, ram: '7.53'
213
+ modelId: 'Pixel 8', deviceModelType: 2, ram: '7.53', firstApiLevel: 34
209
214
  },
210
215
  'pixel7': {
211
216
  os: 'android', platform: PLATFORM.ANDROID,
212
217
  model: 'Pixel 7', manufacturer: 'Google',
213
218
  osVersion: '14', osBuildNumber: 'TP1A.221005.002',
214
- modelId: 'Pixel 7', deviceModelType: 2, ram: '7.53'
219
+ modelId: 'Pixel 7', deviceModelType: 2, ram: '7.53', firstApiLevel: 33
215
220
  },
216
221
  'pixel7a': {
217
222
  os: 'android', platform: PLATFORM.ANDROID,
218
223
  model: 'Pixel 7a', manufacturer: 'Google',
219
224
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
220
- modelId: 'Pixel 7a', deviceModelType: 1, ram: '7.44'
225
+ modelId: 'Pixel 7a', deviceModelType: 1, ram: '7.44', firstApiLevel: 33
221
226
  },
222
227
  'xiaomi14': {
223
228
  os: 'android', platform: PLATFORM.ANDROID,
224
229
  model: 'Xiaomi 14', manufacturer: 'Xiaomi',
225
230
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
226
- modelId: '23127PN0CG', deviceModelType: 2, ram: '11.36'
231
+ modelId: '23127PN0CG', deviceModelType: 2, ram: '11.36', firstApiLevel: 34
227
232
  },
228
233
  'xiaomi13': {
229
234
  os: 'android', platform: PLATFORM.ANDROID,
230
235
  model: 'Xiaomi 13', manufacturer: 'Xiaomi',
231
236
  osVersion: '13', osBuildNumber: 'TQ3A.230901.001',
232
- modelId: '2211133G', deviceModelType: 2, ram: '7.51'
237
+ modelId: '2211133G', deviceModelType: 2, ram: '7.51', firstApiLevel: 33
233
238
  },
234
239
  'oneplus12': {
235
240
  os: 'android', platform: PLATFORM.ANDROID,
236
241
  model: 'OnePlus 12', manufacturer: 'OnePlus',
237
242
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
238
- modelId: 'CPH2573', deviceModelType: 2, ram: '11.48'
243
+ modelId: 'CPH2573', deviceModelType: 2, ram: '11.48', firstApiLevel: 34
239
244
  },
240
245
  'oneplus11': {
241
246
  os: 'android', platform: PLATFORM.ANDROID,
242
247
  model: 'OnePlus 11', manufacturer: 'OnePlus',
243
248
  osVersion: '13', osBuildNumber: 'TQ3A.230901.001',
244
- modelId: 'CPH2449', deviceModelType: 2, ram: '15.32'
249
+ modelId: 'CPH2449', deviceModelType: 2, ram: '15.32', firstApiLevel: 33
245
250
  },
246
251
  'oppo-find-x7': {
247
252
  os: 'android', platform: PLATFORM.ANDROID,
248
253
  model: 'OPPO Find X7', manufacturer: 'OPPO',
249
254
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
250
- modelId: 'CPH2599', deviceModelType: 2, ram: '11.40'
255
+ modelId: 'CPH2599', deviceModelType: 2, ram: '11.40', firstApiLevel: 34
251
256
  },
252
257
  'realme-gt5': {
253
258
  os: 'android', platform: PLATFORM.ANDROID,
254
259
  model: 'realme GT 5 Pro', manufacturer: 'realme',
255
260
  osVersion: '14', osBuildNumber: 'UP1A.231005.007',
256
- modelId: 'RMX3888', deviceModelType: 2, ram: '15.28'
261
+ modelId: 'RMX3888', deviceModelType: 2, ram: '15.28', firstApiLevel: 34
257
262
  }
258
263
  };
259
264
 
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