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/README.md CHANGED
@@ -276,6 +276,7 @@ Where a session is kept, saving and restoring it, database backends, and the Sig
276
276
 
277
277
  - [Handling Events](https://github.com/Kunboruto20/whalibmob/blob/main/docs/events-history.md#handling-events)
278
278
  - [Connection Health, Sync and Account Events](https://github.com/Kunboruto20/whalibmob/blob/main/docs/events-history.md#connection-health-sync-and-account-events)
279
+ - [Handling Errors](https://github.com/Kunboruto20/whalibmob/blob/main/docs/events-history.md#handling-errors)
279
280
  - [History Sync](https://github.com/Kunboruto20/whalibmob/blob/main/docs/events-history.md#history-sync)
280
281
 
281
282
  ### [Sending & Receiving Messages](https://github.com/Kunboruto20/whalibmob/blob/main/docs/messaging.md)
package/cli.js CHANGED
@@ -41,6 +41,7 @@ function installDbgSuppression() {
41
41
  }
42
42
  installDbgSuppression();
43
43
 
44
+ const { Boom } = require('@hapi/boom');
44
45
  const path = require('path');
45
46
  const fs = require('fs');
46
47
  const readline = require('readline');
@@ -607,7 +608,7 @@ function setEarlierStoreAside(dir, who) {
607
608
  const moved = [];
608
609
  try {
609
610
  for (const file of present) {
610
- if (fs.existsSync(file + suffix)) throw new Error(file + suffix + ' already exists');
611
+ if (fs.existsSync(file + suffix)) throw new Boom(file + suffix + ' already exists', { statusCode: 409 });
611
612
  fs.renameSync(file, file + suffix);
612
613
  moved.push(file);
613
614
  }
@@ -1481,7 +1482,7 @@ function notConnected() {
1481
1482
  // ─── guard ────────────────────────────────────────────────────────────────────
1482
1483
 
1483
1484
  function requireConn() {
1484
- if (!_client || !_client.connected) throw new Error('not connected — use /connect <phone>');
1485
+ if (!_client || !_client.connected) throw new Boom('not connected — use /connect <phone>', { statusCode: 428 });
1485
1486
  }
1486
1487
 
1487
1488
  // ─── tokenizer ────────────────────────────────────────────────────────────────
@@ -1543,7 +1544,7 @@ function linkUsage(usage, ...more) {
1543
1544
  function requirePrimary() {
1544
1545
  requireConn();
1545
1546
  if (_client._mode !== 'mobile') {
1546
- const e = new Error('PRIMARY_LINK_PRIMARY_REQUIRED');
1547
+ const e = new Boom('PRIMARY_LINK_PRIMARY_REQUIRED');
1547
1548
  e.code = 'PRIMARY_LINK_PRIMARY_REQUIRED';
1548
1549
  throw e;
1549
1550
  }
@@ -1714,7 +1715,7 @@ async function linkCommand(cmd, p, line) {
1714
1715
  // No connection needed: the lock is a file, and a session that cannot
1715
1716
  // link because of it is still able to connect. Who holds it is shown
1716
1717
  // first, and it is broken only on a y; Enter is no.
1717
- if (!_client) throw new Error('not connected — use /connect <phone>');
1718
+ if (!_client) throw new Boom('not connected — use /connect <phone>', { statusCode: 428 });
1718
1719
  await LinkCli.runLinkUnlock({ client: _client, confirm: (question) => askYesNo(question + ' [y/N] '), print: out });
1719
1720
  return;
1720
1721
  }
@@ -196,6 +196,53 @@ client.on('keepalive_timeout', ({ errorCount }) => {
196
196
 
197
197
  ---
198
198
 
199
+ ## Handling Errors
200
+
201
+ Every error the library raises itself is a [Boom](https://hapi.dev/module/boom/). A Boom is still an `Error`: `err.message`, `err.stack` and `instanceof Error` work as they always did, and the string `err.code` some errors carry (`PAIRING_CODE_REFUSED`, `IQ_TIMEOUT`, …) is untouched. What it adds is an HTTP-style status, so you can branch on the kind of failure instead of matching message text:
202
+
203
+ ```js
204
+ const { Boom } = require('whalibmob') // or require('@hapi/boom')
205
+
206
+ try {
207
+ await client.createGroup('Team', members)
208
+ } catch (err) {
209
+ if (!(err instanceof Boom)) throw err // not ours: a Node or dependency error
210
+
211
+ switch (err.output.statusCode) {
212
+ case 428: await reconnect(); break // not connected
213
+ case 408: await retryLater(); break // the server did not answer in time
214
+ case 403: console.log('not allowed'); break // the server's own refusal, passed through
215
+ default: console.error(err.message)
216
+ }
217
+ }
218
+ ```
219
+
220
+ | Status | Meaning |
221
+ |---|---|
222
+ | `400` | You passed something unusable, or data would not parse |
223
+ | `401` | Not authenticated — logged out, wrong code or PIN |
224
+ | `403` | The server refuses this client or account outright |
225
+ | `404` | Something that had to exist does not — a session, a key, a file |
226
+ | `405` | The call does not apply to this kind of session (e.g. a primary-only call on a companion) |
227
+ | `408` | No answer in time |
228
+ | `409` | It is already there, or already done |
229
+ | `413` | Something is larger than it is allowed to be |
230
+ | `428` | Not connected, or no session loaded yet |
231
+ | `429` | Too many attempts — wait |
232
+ | `500` | Unexpected: a bug, or a failure that fits nothing above |
233
+ | `501` | An optional piece (a package, a driver) is not available |
234
+ | `502` | A server answered, but not with what was asked for |
235
+
236
+ When the WhatsApp server or an HTTP endpoint names its own error status, that status is passed through as it came: a group action refused with `403` is a Boom with `statusCode` 403, an invite that expired is a `410`, a picture the server would not take is a `406`.
237
+
238
+ Three things to know:
239
+
240
+ - **`err.isBoom` is the cheap test.** Errors that come from Node (`ECONNRESET`, `ENOENT`) or from a dependency reach you as they are, so check `err.isBoom` (or `err instanceof Boom`) before reading `err.output`.
241
+ - **The same goes for the `error` event** and for every event that hands you an error (`decrypt_error`, `pair_error`, `history_sync_error`, …).
242
+ - **The Signal protocol layer keeps its own classes.** `SessionError`, `PreKeyError`, `UntrustedIdentityKeyError` and `MessageCounterError` (under `Signal.libsignal`) are unchanged; tell them apart by `err.name`.
243
+
244
+ ---
245
+
199
246
  ## History Sync
200
247
 
201
248
  ### How History Sync Works
package/index.d.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  /// <reference types="node" />
10
10
 
11
11
  import { EventEmitter } from 'events';
12
+ import { Boom as HapiBoom } from '@hapi/boom';
12
13
 
13
14
  // ────────────────────────────────────────────────────────────────────────────
14
15
  // Core aliases
@@ -2485,6 +2486,24 @@ export declare const Socks: LibModule;
2485
2486
  export declare const OfflineNodeProcessor: LibModule;
2486
2487
  export declare const Constants: LibModule;
2487
2488
  export declare const Logger: LibModule;
2489
+ /**
2490
+ * `whalibmob/lib/errors.js` — what the library's own errors are made of.
2491
+ *
2492
+ * Every error whalibmob raises itself is a Boom: still an `Error`, with an
2493
+ * HTTP-style status on `err.output.statusCode` (400 bad input, 401 not
2494
+ * authenticated, 404 missing, 408 timed out, 428 not connected, 500 unexpected,
2495
+ * 502 a server answered wrongly, or the server's own status passed through).
2496
+ * Errors that come from Node or a dependency reach the caller as they are, so
2497
+ * test `err.isBoom` before reading `err.output`.
2498
+ */
2499
+ export declare const Errors: {
2500
+ Boom: typeof HapiBoom;
2501
+ /** `code` when it is an integer status from 400 to 599, else `fallback` (502). */
2502
+ statusFrom(code: unknown, fallback?: number): number;
2503
+ };
2504
+ /** `@hapi/boom`'s `Boom`, re-exported: the class the library's errors are instances of. */
2505
+ export declare const Boom: typeof HapiBoom;
2506
+ export type Boom<Data = any> = HapiBoom<Data>;
2488
2507
  /**
2489
2508
  * `whalibmob/lib/proto.js` — the handshake payloads. The message protobufs are
2490
2509
  * the directory of the same name, and are `MessageProto`.
package/index.js CHANGED
@@ -158,6 +158,10 @@ const Socks = require('./lib/socks');
158
158
  const OfflineNodeProcessor = require('./lib/OfflineNodeProcessor');
159
159
  const Constants = require('./lib/constants');
160
160
  const Logger = require('./lib/logger');
161
+ // lib/errors.js — what every error this library raises is made of. Boom is
162
+ // @hapi/boom's class, the same one a caller would get from requiring it.
163
+ const Errors = require('./lib/errors');
164
+ const Boom = Errors.Boom;
161
165
  // lib/proto.js — the handshake payloads. The message protobufs are the
162
166
  // directory of the same name, and are MessageProto.
163
167
  const Proto = require('./lib/proto.js');
@@ -432,6 +436,8 @@ module.exports = {
432
436
  OfflineNodeProcessor,
433
437
  Constants,
434
438
  Logger,
439
+ Errors,
440
+ Boom,
435
441
  Proto,
436
442
 
437
443
  // Messages and media
package/lib/AndroidApk.js CHANGED
@@ -22,6 +22,7 @@
22
22
  // apk-material command drives it and writes the result where computeToken
23
23
  // looks for it.
24
24
 
25
+ const { Boom } = require('@hapi/boom');
25
26
  const crypto = require('crypto');
26
27
  const zlib = require('zlib');
27
28
 
@@ -67,7 +68,7 @@ function _findEndOfCentralDirectory(buf) {
67
68
  // directory order.
68
69
  function readZipDirectory(buf) {
69
70
  const eocd = _findEndOfCentralDirectory(buf);
70
- if (eocd < 0) throw new Error('not a zip archive: no end-of-central-directory record');
71
+ if (eocd < 0) throw new Boom('not a zip archive: no end-of-central-directory record', { statusCode: 400 });
71
72
 
72
73
  let count = buf.readUInt16LE(eocd + 10);
73
74
  let offset = buf.readUInt32LE(eocd + 16);
@@ -78,10 +79,10 @@ function readZipDirectory(buf) {
78
79
  if (count === 0xffff || offset === 0xffffffff) {
79
80
  const loc = eocd - 20;
80
81
  if (loc < 0 || buf.readUInt32LE(loc) !== 0x07064b50) {
81
- throw new Error('zip needs ZIP64 but carries no ZIP64 locator');
82
+ throw new Boom('zip needs ZIP64 but carries no ZIP64 locator', { statusCode: 400 });
82
83
  }
83
84
  const z64 = Number(buf.readBigUInt64LE(loc + 8));
84
- if (buf.readUInt32LE(z64) !== 0x06064b50) throw new Error('bad ZIP64 end-of-central-directory');
85
+ if (buf.readUInt32LE(z64) !== 0x06064b50) throw new Boom('bad ZIP64 end-of-central-directory', { statusCode: 400 });
85
86
  count = Number(buf.readBigUInt64LE(z64 + 32));
86
87
  offset = Number(buf.readBigUInt64LE(z64 + 48));
87
88
  }
@@ -108,7 +109,7 @@ function readZipEntry(buf, entries, name) {
108
109
  const e = entries.get(name);
109
110
  if (!e) return null;
110
111
  const lh = e.localHeaderOffset;
111
- if (buf.readUInt32LE(lh) !== 0x04034b50) throw new Error('bad local header for ' + name);
112
+ if (buf.readUInt32LE(lh) !== 0x04034b50) throw new Boom('bad local header for ' + name, { statusCode: 400 });
112
113
  // The local header's extra field is allowed to differ in length from the
113
114
  // central directory's, so the data offset is computed from the local one.
114
115
  const nameLen = buf.readUInt16LE(lh + 26);
@@ -117,7 +118,7 @@ function readZipEntry(buf, entries, name) {
117
118
  const raw = buf.slice(start, start + e.compressedSize);
118
119
  if (e.method === 0) return raw;
119
120
  if (e.method === 8) return zlib.inflateRawSync(raw);
120
- throw new Error('unsupported zip compression method ' + e.method + ' for ' + name);
121
+ throw new Boom('unsupported zip compression method ' + e.method + ' for ' + name, { statusCode: 400 });
121
122
  }
122
123
 
123
124
  // ─── DER / PKCS#7 ─────────────────────────────────────────────────────────────
@@ -133,7 +134,7 @@ function _readTlv(buf, pos) {
133
134
  let len = buf[p++];
134
135
  if (len & 0x80) {
135
136
  const n = len & 0x7f;
136
- if (n === 0) throw new Error('indefinite DER length');
137
+ if (n === 0) throw new Boom('indefinite DER length', { statusCode: 400 });
137
138
  len = 0;
138
139
  for (let i = 0; i < n; i++) len = (len << 8) | buf[p++];
139
140
  }
@@ -322,12 +323,12 @@ function extractMaterial(base, splits) {
322
323
  if (aboutLogo) break;
323
324
  }
324
325
  if (!aboutLogo) {
325
- throw new Error('about_logo.png is in neither the base APK nor any density split — ' +
326
- 'pass the split APKs alongside the base one (' + ABOUT_LOGO_PATHS.join(', ') + ')');
326
+ throw new Boom('about_logo.png is in neither the base APK nor any density split — ' +
327
+ 'pass the split APKs alongside the base one (' + ABOUT_LOGO_PATHS.join(', ') + ')', { statusCode: 400 });
327
328
  }
328
329
 
329
330
  const classesDex = readZipEntry(base, entries, 'classes.dex');
330
- if (!classesDex) throw new Error('classes.dex missing from the base APK');
331
+ if (!classesDex) throw new Boom('classes.dex missing from the base APK', { statusCode: 400 });
331
332
 
332
333
  const certificates = [];
333
334
  for (const name of entries.keys()) {
@@ -337,8 +338,8 @@ function extractMaterial(base, splits) {
337
338
  }
338
339
  }
339
340
  if (!certificates.length) {
340
- throw new Error('no v1 signing certificate in META-INF — this APK is not JAR-signed, ' +
341
- 'and the token is built from the v1 signature block');
341
+ throw new Boom('no v1 signing certificate in META-INF — this APK is not JAR-signed, ' +
342
+ 'and the token is built from the v1 signature block', { statusCode: 400 });
342
343
  }
343
344
 
344
345
  const manifest = parseManifest(readZipEntry(base, entries, 'AndroidManifest.xml'));
@@ -493,7 +494,7 @@ function materialToJson(material) {
493
494
 
494
495
  function materialFromJson(json) {
495
496
  if (!json || !json.secretKey || !json.classesDexMd5 || !Array.isArray(json.certificates)) {
496
- throw new Error('android APK material file is incomplete');
497
+ throw new Boom('android APK material file is incomplete', { statusCode: 400 });
497
498
  }
498
499
  return {
499
500
  packageName: json.packageName || PERSONAL_PACKAGE,
package/lib/BinaryNode.js CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { Boom } = require('@hapi/boom');
3
4
  const { TAG } = require('./constants');
4
5
  const { SINGLE_BYTE, DICTS, tokenToString, dictTokenToString, stringToSingleByte, stringToDictToken } = require('./tokens');
5
6
 
@@ -219,7 +220,7 @@ class NodeDecoder {
219
220
  if (b === TAG.LIST_EMPTY) return 0;
220
221
  if (b === TAG.LIST_8) return this._readByte();
221
222
  if (b === TAG.LIST_16) return (this._readByte() << 8) | this._readByte();
222
- throw new Error(`Unknown list tag: ${b}`);
223
+ throw new Boom(`Unknown list tag: ${b}`, { statusCode: 400 });
223
224
  }
224
225
 
225
226
  _readString(token) {