zapo-js 1.7.0 → 1.7.1

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 (97) hide show
  1. package/README.md +26 -12
  2. package/dist/appstate/crypto/WaAppStateCrypto.js +4 -6
  3. package/dist/auth/WaAuthClient.d.ts +14 -1
  4. package/dist/auth/WaAuthClient.js +22 -1
  5. package/dist/auth/credentials-flow.d.ts +3 -1
  6. package/dist/auth/credentials-flow.js +3 -0
  7. package/dist/auth/pairing/WaPairingFlow.d.ts +5 -0
  8. package/dist/auth/pairing/WaPairingFlow.js +66 -14
  9. package/dist/auth/types.d.ts +13 -0
  10. package/dist/client/WaClientFactory.js +3 -1
  11. package/dist/client/coordinators/WaMessageDispatchCoordinator.js +35 -27
  12. package/dist/client/messaging/messages.js +16 -12
  13. package/dist/client/newsletter/discovery.js +4 -2
  14. package/dist/client/persistence/history-sync.d.ts +18 -0
  15. package/dist/client/persistence/history-sync.js +134 -42
  16. package/dist/client/plugins/types.d.ts +10 -2
  17. package/dist/crypto/core/index.d.ts +1 -1
  18. package/dist/crypto/core/index.js +2 -1
  19. package/dist/crypto/core/primitives.d.ts +19 -0
  20. package/dist/crypto/core/primitives.js +48 -0
  21. package/dist/crypto/core/xeddsa.js +19 -4
  22. package/dist/crypto/curves/X25519.js +16 -2
  23. package/dist/esm/appstate/crypto/WaAppStateCrypto.js +4 -6
  24. package/dist/esm/auth/WaAuthClient.js +22 -1
  25. package/dist/esm/auth/credentials-flow.js +3 -0
  26. package/dist/esm/auth/pairing/WaPairingFlow.js +67 -15
  27. package/dist/esm/client/WaClientFactory.js +3 -1
  28. package/dist/esm/client/coordinators/WaMessageDispatchCoordinator.js +37 -29
  29. package/dist/esm/client/messaging/messages.js +16 -12
  30. package/dist/esm/client/newsletter/discovery.js +4 -2
  31. package/dist/esm/client/persistence/history-sync.js +133 -43
  32. package/dist/esm/crypto/core/index.js +1 -1
  33. package/dist/esm/crypto/core/primitives.js +47 -0
  34. package/dist/esm/crypto/core/xeddsa.js +19 -4
  35. package/dist/esm/crypto/curves/X25519.js +16 -2
  36. package/dist/esm/media/crypto/WaMediaCrypto.js +38 -19
  37. package/dist/esm/message/crypto/reporting-token.js +38 -216
  38. package/dist/esm/message/encode/content.js +53 -8
  39. package/dist/esm/message/primitives/incoming.js +14 -7
  40. package/dist/esm/protocol/defaults.js +1 -0
  41. package/dist/esm/protocol/device-identity.js +10 -5
  42. package/dist/esm/protocol/jid.js +83 -36
  43. package/dist/esm/signal/group/SenderKeyChain.js +1 -2
  44. package/dist/esm/signal/group/SenderKeyManager.js +1 -7
  45. package/dist/esm/signal/session/SignalProtocol.js +22 -21
  46. package/dist/esm/signal/session/SignalRatchet.js +20 -17
  47. package/dist/esm/signal/session/encoding.js +25 -3
  48. package/dist/esm/signal/session/resolver.js +11 -5
  49. package/dist/esm/transport/binary/constants.js +19 -0
  50. package/dist/esm/transport/binary/decoder.js +17 -19
  51. package/dist/esm/transport/binary/encoder.js +61 -18
  52. package/dist/esm/transport/node/builders/global.js +20 -0
  53. package/dist/esm/transport/node/builders/message.js +32 -15
  54. package/dist/esm/transport/noise/WaClientPayload.js +43 -22
  55. package/dist/esm/transport/noise/WaFrameCodec.js +14 -4
  56. package/dist/esm/util/protoscan.js +181 -0
  57. package/dist/esm/util/runtime.js +34 -0
  58. package/dist/media/crypto/WaMediaCrypto.js +36 -17
  59. package/dist/message/crypto/reporting-token.d.ts +3 -1
  60. package/dist/message/crypto/reporting-token.js +38 -216
  61. package/dist/message/encode/content.d.ts +17 -1
  62. package/dist/message/encode/content.js +54 -8
  63. package/dist/message/primitives/incoming.js +14 -7
  64. package/dist/message/types.d.ts +10 -0
  65. package/dist/protocol/defaults.d.ts +1 -0
  66. package/dist/protocol/defaults.js +1 -0
  67. package/dist/protocol/device-identity.d.ts +14 -4
  68. package/dist/protocol/device-identity.js +9 -4
  69. package/dist/protocol/jid.d.ts +4 -1
  70. package/dist/protocol/jid.js +83 -36
  71. package/dist/signal/group/SenderKeyChain.d.ts +1 -1
  72. package/dist/signal/group/SenderKeyChain.js +1 -2
  73. package/dist/signal/group/SenderKeyManager.js +1 -7
  74. package/dist/signal/session/SignalProtocol.d.ts +13 -0
  75. package/dist/signal/session/SignalProtocol.js +22 -21
  76. package/dist/signal/session/SignalRatchet.d.ts +4 -4
  77. package/dist/signal/session/SignalRatchet.js +19 -16
  78. package/dist/signal/session/SignalSession.d.ts +8 -1
  79. package/dist/signal/session/encoding.d.ts +5 -0
  80. package/dist/signal/session/encoding.js +25 -3
  81. package/dist/signal/session/resolver.js +11 -5
  82. package/dist/transport/binary/constants.d.ts +8 -0
  83. package/dist/transport/binary/constants.js +20 -1
  84. package/dist/transport/binary/decoder.js +17 -19
  85. package/dist/transport/binary/encoder.js +60 -17
  86. package/dist/transport/node/builders/global.d.ts +8 -0
  87. package/dist/transport/node/builders/global.js +21 -0
  88. package/dist/transport/node/builders/message.js +32 -15
  89. package/dist/transport/noise/WaClientPayload.js +43 -22
  90. package/dist/transport/noise/WaFrameCodec.d.ts +1 -0
  91. package/dist/transport/noise/WaFrameCodec.js +14 -4
  92. package/dist/transport/noise/types.d.ts +17 -0
  93. package/dist/util/protoscan.d.ts +33 -0
  94. package/dist/util/protoscan.js +186 -0
  95. package/dist/util/runtime.d.ts +12 -0
  96. package/dist/util/runtime.js +35 -0
  97. package/package.json +1 -1
package/README.md CHANGED
@@ -41,8 +41,8 @@ npm install zapo-js
41
41
  ```
42
42
 
43
43
  Zero mandatory runtime dependencies. Pick the optional packages you need
44
- on top: a persistent store and (optionally) the media processor for
45
- thumbnails / voice-note metadata.
44
+ on top: a persistent store, the media processor for thumbnails /
45
+ voice-note metadata, and the native crypto accelerator.
46
46
 
47
47
  ```bash
48
48
  # Persistent store - choose one
@@ -56,10 +56,21 @@ npm install @zapo-js/store-sqlite better-sqlite3
56
56
  npm install @zapo-js/media-utils sharp
57
57
  # plus a system `ffmpeg` + `ffprobe` on PATH (see media-utils README)
58
58
 
59
+ # Optional - Rust crypto accelerator, no code change required
60
+ npm install @zapo-js/native
61
+
59
62
  # Optional - structured logging
60
63
  npm install pino pino-pretty
61
64
  ```
62
65
 
66
+ `@zapo-js/native` is picked up automatically once installed: the core
67
+ resolves it on first use and falls back to the JS implementation when it is
68
+ absent, so nothing else changes. It accelerates the two primitives that
69
+ dominate the messaging hot path, X25519 ECDH and XEdDSA sign / verify. The
70
+ published build is the WASM one (`ZAPO_NATIVE_BACKEND=auto` tries the NAPI
71
+ addon first, then WASM); the compiled NAPI addon is not on npm yet and has
72
+ to be built from `packages/native`. Set `ZAPO_NATIVE_BACKEND=js` to opt out.
73
+
63
74
  ## Quick Start
64
75
 
65
76
  ```ts
@@ -116,16 +127,19 @@ The core lives at the repo root (`zapo-js`). Optional packages live in
116
127
  [`packages/`](packages/) and ship under the `@zapo-js/*` scope. Install
117
128
  only what you need.
118
129
 
119
- | Package | Peer dependency | Purpose |
120
- | ---------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
121
- | [`@zapo-js/store-sqlite`](packages/store-sqlite) | `better-sqlite3` | SQLite persistent store (single-process bots, dev sessions, small-to-medium prod). |
122
- | [`@zapo-js/store-redis`](packages/store-redis) | `ioredis` | Redis-backed store with native TTL eviction. |
123
- | [`@zapo-js/store-mongo`](packages/store-mongo) | `mongodb` | MongoDB-backed store with TTL-index eviction. |
124
- | [`@zapo-js/store-mysql`](packages/store-mysql) | `mysql2` | MySQL / MariaDB-backed store with background cleanup poller. |
125
- | [`@zapo-js/store-postgres`](packages/store-postgres) | `pg` | PostgreSQL-backed store with background cleanup poller. |
126
- | [`@zapo-js/media-utils`](packages/media-utils) | `sharp` + `ffmpeg` | `WaMediaProcessor`: thumbnails, waveforms, voice-note normalization. |
127
- | [`@zapo-js/fake-server`](packages/fake-server) | (none) | In-process fake WhatsApp Web server for end-to-end testing. |
128
- | [`@zapo-js/mcp-server`](packages/mcp-server) | `@modelcontextprotocol/sdk` | **Dev-only.** MCP server exposing multi-session `WaClient`s as dynamic tools for an LLM agent (Claude Code / Cursor / etc.). Not for production. |
130
+ | Package | Peer dependency | Purpose |
131
+ | ---------------------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
132
+ | [`@zapo-js/store-sqlite`](packages/store-sqlite) | `better-sqlite3` | SQLite persistent store (single-process bots, dev sessions, small-to-medium prod). |
133
+ | [`@zapo-js/store-redis`](packages/store-redis) | `ioredis` | Redis-backed store with native TTL eviction. |
134
+ | [`@zapo-js/store-mongo`](packages/store-mongo) | `mongodb` | MongoDB-backed store with TTL-index eviction. |
135
+ | [`@zapo-js/store-mysql`](packages/store-mysql) | `mysql2` | MySQL / MariaDB-backed store with background cleanup poller. |
136
+ | [`@zapo-js/store-postgres`](packages/store-postgres) | `pg` | PostgreSQL-backed store with background cleanup poller. |
137
+ | [`@zapo-js/media-utils`](packages/media-utils) | `sharp` + `file-type` + `ffmpeg` | `WaMediaProcessor`: thumbnails, waveforms, voice-note normalization. |
138
+ | [`@zapo-js/native`](packages/native) | (none) | Rust crypto accelerator for the messaging hot path (X25519 ECDH, XEdDSA sign / verify). Auto-detected once installed; ships as a WASM build. |
139
+ | [`@zapo-js/voip`](packages/voip) | `@roamhq/wrtc` + `libmlow-wasm` | `client.voip` plugin for calls: MLow/WASM codec, SRTP, STUN, WebRTC/SCTP relay transport. |
140
+ | [`@zapo-js/wam`](packages/wam) | (none) | `client.wam` plugin emitting the client-side WAM telemetry batches WA Web sends, for wire parity and anti-fingerprinting. |
141
+ | [`@zapo-js/fake-server`](packages/fake-server) | (none) | In-process fake WhatsApp Web server for end-to-end testing. |
142
+ | [`@zapo-js/mcp-server`](packages/mcp-server) | `@modelcontextprotocol/sdk` | **Dev-only.** MCP server exposing multi-session `WaClient`s as dynamic tools for an LLM agent (Claude Code / Cursor / etc.). Not for production. |
129
143
 
130
144
  Each package's README has the install + config + integration notes.
131
145
 
@@ -177,12 +177,10 @@ class WaAppStateCrypto {
177
177
  if (out.byteLength !== left.byteLength) {
178
178
  throw new Error('lt hash output length mismatch');
179
179
  }
180
- const leftView = new DataView(left.buffer, left.byteOffset, left.byteLength);
181
- const rightView = new DataView(right.buffer, right.byteOffset, right.byteLength);
182
- const outView = new DataView(out.buffer, out.byteOffset, out.byteLength);
183
180
  for (let offset = 0; offset < left.byteLength; offset += constants_1.APP_STATE_POINT_SIZE) {
184
- const value = combine(leftView.getUint16(offset, true), rightView.getUint16(offset, true));
185
- outView.setUint16(offset, value & 0xffff, true);
181
+ const value = combine(left[offset] | (left[offset + 1] << 8), right[offset] | (right[offset + 1] << 8));
182
+ out[offset] = value & 0xff;
183
+ out[offset + 1] = (value >>> 8) & 0xff;
186
184
  }
187
185
  return out;
188
186
  }
@@ -199,7 +197,7 @@ class WaAppStateCrypto {
199
197
  generateValueMac(valueMacHmacKey, associatedData, iv, cipherText) {
200
198
  const octetLength = new Uint8Array(constants_1.APP_STATE_MAC_OCTET_LENGTH);
201
199
  octetLength[octetLength.length - 1] = associatedData.byteLength & 0xff;
202
- const full = (0, primitives_1.hmacSha512Sign)(valueMacHmacKey, (0, bytes_1.concatBytes)([associatedData, iv, cipherText, octetLength]));
200
+ const full = (0, primitives_1.hmacSha512Sign)(valueMacHmacKey, [associatedData, iv, cipherText, octetLength]);
203
201
  return full.subarray(0, constants_1.APP_STATE_VALUE_MAC_LENGTH);
204
202
  }
205
203
  touchDerivedKeysCacheEntry(cacheKey, keys) {
@@ -52,6 +52,12 @@ export declare class WaAuthClient {
52
52
  private credentials;
53
53
  private versionOverride;
54
54
  private mobileAppVersionOverride;
55
+ /**
56
+ * Successful logins made by this instance, advertised as
57
+ * `connectAttemptCount`. Process-local by design – the persisted
58
+ * counterpart is `credentials.loginCounter`.
59
+ */
60
+ private connectAttemptCount;
55
61
  constructor(options: WaAuthClientOptions, deps: WaAuthClientDeps);
56
62
  /**
57
63
  * Returns a snapshot of auth readiness flags (connection, registration,
@@ -121,8 +127,15 @@ export declare class WaAuthClient {
121
127
  * Persists the per-connection success attributes from the server (LID,
122
128
  * display name, companion key, last-success ts, props versions, ...). Only
123
129
  * persists when at least one attribute actually changed.
130
+ *
131
+ * Pass `countsAsLogin` only for the server `success` node: it advances the
132
+ * login counters advertised as `lc` / `connectAttemptCount`. Callers that
133
+ * merely reuse this to persist a single attribute (a push-name change, for
134
+ * instance) must leave it unset.
124
135
  */
125
- persistSuccessAttributes(attributes: WaSuccessPersistAttributes): Promise<void>;
136
+ persistSuccessAttributes(attributes: WaSuccessPersistAttributes, { countsAsLogin }?: {
137
+ readonly countsAsLogin?: boolean;
138
+ }): Promise<void>;
126
139
  /**
127
140
  * Requests an 8-character pairing code for `phoneNumber` (link-code flow).
128
141
  * Pass `customCode` to suggest a specific code; the server still validates
@@ -23,11 +23,18 @@ class WaAuthClient {
23
23
  constructor(options, deps) {
24
24
  this.versionOverride = null;
25
25
  this.mobileAppVersionOverride = null;
26
+ /**
27
+ * Successful logins made by this instance, advertised as
28
+ * `connectAttemptCount`. Process-local by design – the persisted
29
+ * counterpart is `credentials.loginCounter`.
30
+ */
31
+ this.connectAttemptCount = 0;
26
32
  const device = (0, constants_1.resolveWaDeviceIdentity)(options);
27
33
  this.options = Object.freeze({
28
34
  ...options,
29
35
  deviceBrowser: device.browser,
30
36
  deviceOsDisplayName: device.osDisplayName,
37
+ deviceOsVersion: device.osVersion ?? undefined,
31
38
  devicePlatform: device.platform,
32
39
  requireFullSync: options.requireFullSync
33
40
  });
@@ -125,8 +132,10 @@ class WaAuthClient {
125
132
  const mobileAppVersionOverride = this.mobileAppVersionOverride;
126
133
  this.mobileAppVersionOverride = null;
127
134
  return (0, credentials_flow_1.buildCommsConfig)(this.logger, this.requireCredentials(), socketOptions, {
135
+ connectAttemptCount: this.connectAttemptCount,
128
136
  deviceBrowser: this.options.deviceBrowser,
129
137
  deviceOsDisplayName: this.options.deviceOsDisplayName,
138
+ deviceOsVersion: this.options.deviceOsVersion,
130
139
  requireFullSync: this.options.requireFullSync,
131
140
  version: override ?? this.options.version,
132
141
  mobileTransport: this.options.mobileTransport,
@@ -239,10 +248,19 @@ class WaAuthClient {
239
248
  * Persists the per-connection success attributes from the server (LID,
240
249
  * display name, companion key, last-success ts, props versions, ...). Only
241
250
  * persists when at least one attribute actually changed.
251
+ *
252
+ * Pass `countsAsLogin` only for the server `success` node: it advances the
253
+ * login counters advertised as `lc` / `connectAttemptCount`. Callers that
254
+ * merely reuse this to persist a single attribute (a push-name change, for
255
+ * instance) must leave it unset.
242
256
  */
243
- async persistSuccessAttributes(attributes) {
257
+ async persistSuccessAttributes(attributes, { countsAsLogin = false } = {}) {
258
+ if (countsAsLogin) {
259
+ this.connectAttemptCount += 1;
260
+ }
244
261
  let persistDiff;
245
262
  const computeDiff = (current, next) => ({
263
+ loginCounterChanged: next.loginCounter !== current.loginCounter,
246
264
  lidChanged: next.meLid !== current.meLid,
247
265
  displayNameChanged: next.meDisplayName !== current.meDisplayName,
248
266
  companionChanged: (current.companionEncStatic === undefined) !==
@@ -262,6 +280,9 @@ class WaAuthClient {
262
280
  meDisplayName: attributes.meDisplayName ?? credentials.meDisplayName,
263
281
  companionEncStatic: attributes.companionEncStatic ?? credentials.companionEncStatic,
264
282
  lastSuccessTs: attributes.lastSuccessTs ?? credentials.lastSuccessTs,
283
+ loginCounter: countsAsLogin
284
+ ? (credentials.loginCounter ?? 0) + 1
285
+ : credentials.loginCounter,
265
286
  propsVersion: attributes.propsVersion ?? credentials.propsVersion,
266
287
  abPropsVersion: attributes.abPropsVersion ?? credentials.abPropsVersion,
267
288
  connectionLocation: attributes.connectionLocation ?? credentials.connectionLocation,
@@ -14,7 +14,7 @@ interface WaAuthCredentialsFlowArgs {
14
14
  }
15
15
  export declare function loadOrCreateCredentials(args: WaAuthCredentialsFlowArgs): Promise<WaAuthCredentials>;
16
16
  export declare function persistCredentials(args: WaAuthCredentialsFlowArgs, credentials: WaAuthCredentials): Promise<void>;
17
- export declare function buildCommsConfig(logger: Logger, credentials: WaAuthCredentials, socketOptions: WaAuthSocketOptions, clientOptions: Pick<WaAuthClientOptions, 'deviceBrowser' | 'deviceOsDisplayName' | 'requireFullSync' | 'version' | 'mobileTransport'> & {
17
+ export declare function buildCommsConfig(logger: Logger, credentials: WaAuthCredentials, socketOptions: WaAuthSocketOptions, clientOptions: Pick<WaAuthClientOptions, 'deviceBrowser' | 'deviceOsDisplayName' | 'deviceOsVersion' | 'requireFullSync' | 'version' | 'mobileTransport'> & {
18
18
  readonly noiseTrustedRootCa?: WaNoiseRootCa;
19
19
  readonly disableNoiseCertificateChainVerification?: boolean;
20
20
  /**
@@ -25,5 +25,7 @@ export declare function buildCommsConfig(logger: Logger, credentials: WaAuthCred
25
25
  * sessions.
26
26
  */
27
27
  readonly mobileAppVersionOverride?: string;
28
+ /** Successful logins made by the calling client instance so far. */
29
+ readonly connectAttemptCount?: number;
28
30
  }): Promise<WaCommsConfig>;
29
31
  export {};
@@ -179,6 +179,8 @@ async function buildCommsConfig(logger, credentials, socketOptions, clientOption
179
179
  ? {
180
180
  username: loginIdentity.username,
181
181
  device: loginIdentity.device,
182
+ loginCounter: credentials.loginCounter ?? 0,
183
+ connectAttemptCount: clientOptions.connectAttemptCount ?? 0,
182
184
  deviceBrowser: clientOptions.deviceBrowser,
183
185
  deviceOsDisplayName: clientOptions.deviceOsDisplayName,
184
186
  versionBase
@@ -190,6 +192,7 @@ async function buildCommsConfig(logger, credentials, socketOptions, clientOption
190
192
  signedPreKey: credentials.signedPreKey,
191
193
  deviceBrowser: clientOptions.deviceBrowser,
192
194
  deviceOsDisplayName: clientOptions.deviceOsDisplayName,
195
+ deviceOsVersion: clientOptions.deviceOsVersion,
193
196
  requireFullSync: clientOptions.requireFullSync,
194
197
  versionBase
195
198
  }
@@ -31,6 +31,7 @@ interface WaPairingFlowOptions {
31
31
  export declare class WaPairingFlow {
32
32
  private readonly opts;
33
33
  private pairingSession;
34
+ private pairSuccessInFlight;
34
35
  constructor(options: WaPairingFlowOptions);
35
36
  hasPairingSession(): boolean;
36
37
  clearSession(): void;
@@ -41,7 +42,11 @@ export declare class WaPairingFlow {
41
42
  handleCompanionRegRefreshNotification(node: BinaryNode): Promise<boolean>;
42
43
  private handlePairDevice;
43
44
  private handlePairSuccess;
45
+ private completePairSuccess;
46
+ /** Returns `null` when the primary's account signature does not verify. */
44
47
  private buildPairSuccessResponseIdentity;
48
+ /** Mirrors the `not-authorized` IQ error WhatsApp Web returns on a failed pair-success. */
49
+ private sendPairSuccessValidationError;
45
50
  private handlePrimaryHello;
46
51
  private rotateAdvSecret;
47
52
  private requireCredentials;
@@ -13,8 +13,13 @@ const pairing_1 = require("../../transport/node/builders/pairing");
13
13
  const helpers_1 = require("../../transport/node/helpers");
14
14
  const query_1 = require("../../transport/node/query");
15
15
  const bytes_1 = require("../../util/bytes");
16
+ const primitives_1 = require("../../util/primitives");
17
+ /** Server-enforced bounds on the `pair-success` `device-identity` payload. */
18
+ const PAIR_SUCCESS_DEVICE_IDENTITY_MIN_BYTES = 1;
19
+ const PAIR_SUCCESS_DEVICE_IDENTITY_MAX_BYTES = 500;
16
20
  class WaPairingFlow {
17
21
  constructor(options) {
22
+ this.pairSuccessInFlight = false;
18
23
  this.opts = options;
19
24
  this.pairingSession = null;
20
25
  }
@@ -33,6 +38,7 @@ class WaPairingFlow {
33
38
  const normalizedCustomCode = customCode !== undefined ? (0, pairing_code_crypto_1.normalizeCustomPairingCode)(customCode) : undefined;
34
39
  const credentials = this.requireCredentials();
35
40
  const phoneJid = (0, jid_1.parsePhoneJid)(phoneNumber);
41
+ const createdAtSeconds = Math.floor(Date.now() / 1000);
36
42
  const [companionHello, refreshedCredentials] = await Promise.all([
37
43
  (0, pairing_code_crypto_1.createCompanionHello)({ customCode: normalizedCustomCode }),
38
44
  this.rotateAdvSecret(credentials)
@@ -64,7 +70,7 @@ class WaPairingFlow {
64
70
  pairingCode: companionHello.pairingCode,
65
71
  phoneJid,
66
72
  ref,
67
- createdAtSeconds: Math.floor(Date.now() / 1000),
73
+ createdAtSeconds,
68
74
  companionEphemeralKeyPair: companionHello.companionEphemeralKeyPair,
69
75
  attempts: 0,
70
76
  finished: false
@@ -166,6 +172,23 @@ class WaPairingFlow {
166
172
  this.opts.logger.debug('pair-device refs updated', { refsCount: refs.length });
167
173
  }
168
174
  async handlePairSuccess(iqNode, pairSuccessNode) {
175
+ if (this.pairSuccessInFlight) {
176
+ this.opts.logger.debug('pair-success ignored: already processing');
177
+ return;
178
+ }
179
+ if (this.opts.auth.getCredentials()?.meJid) {
180
+ this.opts.logger.debug('pair-success ignored: session already registered');
181
+ return;
182
+ }
183
+ this.pairSuccessInFlight = true;
184
+ try {
185
+ await this.completePairSuccess(iqNode, pairSuccessNode);
186
+ }
187
+ finally {
188
+ this.pairSuccessInFlight = false;
189
+ }
190
+ }
191
+ async completePairSuccess(iqNode, pairSuccessNode) {
169
192
  this.opts.logger.debug('processing pair-success node');
170
193
  const credentials = this.requireCredentials();
171
194
  const [deviceIdentityNode, deviceNode, platformNode] = (0, helpers_1.findNodeChildrenByTags)(pairSuccessNode, [constants_1.WA_NODE_TAGS.DEVICE_IDENTITY, 'device', constants_1.WA_NODE_TAGS.PLATFORM]);
@@ -177,7 +200,12 @@ class WaPairingFlow {
177
200
  });
178
201
  throw new Error('pair-success stanza is missing required nodes');
179
202
  }
180
- const wrappedIdentity = _proto_1.proto.ADVSignedDeviceIdentityHMAC.decode((0, helpers_1.decodeNodeContentUtf8OrBytes)(deviceIdentityNode.content, 'pair-success.device-identity'));
203
+ const deviceIdentityBytes = (0, helpers_1.decodeNodeContentUtf8OrBytes)(deviceIdentityNode.content, 'pair-success.device-identity');
204
+ if (deviceIdentityBytes.length < PAIR_SUCCESS_DEVICE_IDENTITY_MIN_BYTES ||
205
+ deviceIdentityBytes.length > PAIR_SUCCESS_DEVICE_IDENTITY_MAX_BYTES) {
206
+ throw new Error(`pair-success device-identity must be ${PAIR_SUCCESS_DEVICE_IDENTITY_MIN_BYTES}-${PAIR_SUCCESS_DEVICE_IDENTITY_MAX_BYTES} bytes, got ${deviceIdentityBytes.length}`);
207
+ }
208
+ const wrappedIdentity = _proto_1.proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityBytes);
181
209
  const wrappedDetails = (0, bytes_1.decodeProtoBytes)(wrappedIdentity.details, 'ADVSignedDeviceIdentityHMAC.details');
182
210
  const wrappedHmac = (0, bytes_1.decodeProtoBytes)(wrappedIdentity.hmac, 'ADVSignedDeviceIdentityHMAC.hmac');
183
211
  const accountType = wrappedIdentity.accountType ?? _proto_1.proto.ADVEncryptionType.E2EE;
@@ -194,16 +222,23 @@ class WaPairingFlow {
194
222
  platform: platformNode.attrs.name,
195
223
  isHosted
196
224
  });
225
+ await this.sendPairSuccessValidationError(iqNode);
197
226
  throw new Error('pair-success HMAC validation failed');
198
227
  }
199
228
  }
200
- const { signedIdentity, keyIndex, responseIdentityBytes } = await this.buildPairSuccessResponseIdentity(credentials, wrappedDetails);
229
+ const built = await this.buildPairSuccessResponseIdentity(credentials, wrappedDetails);
230
+ if (!built) {
231
+ await this.sendPairSuccessValidationError(iqNode);
232
+ throw new Error('pair-success account signature validation failed');
233
+ }
234
+ const { signedIdentity, keyIndex, responseIdentityBytes } = built;
201
235
  const nextCredentials = {
202
236
  ...credentials,
203
237
  signedIdentity,
204
238
  meJid: deviceNode.attrs.jid,
205
239
  meLid: deviceNode.attrs.lid,
206
- platform: platformNode.attrs.name
240
+ platform: platformNode.attrs.name,
241
+ loginCounter: 0
207
242
  };
208
243
  await this.opts.auth.updateCredentials(nextCredentials);
209
244
  this.opts.logger.info('pair-success credentials updated', {
@@ -238,6 +273,7 @@ class WaPairingFlow {
238
273
  this.opts.callbacks.emitPaired(nextCredentials);
239
274
  this.opts.logger.debug('pair-success completed and paired event emitted');
240
275
  }
276
+ /** Returns `null` when the primary's account signature does not verify. */
241
277
  async buildPairSuccessResponseIdentity(credentials, wrappedDetails) {
242
278
  const signedIdentity = _proto_1.proto.ADVSignedDeviceIdentity.decode(wrappedDetails);
243
279
  const details = (0, bytes_1.decodeProtoBytes)(signedIdentity.details, 'ADVSignedDeviceIdentity.details');
@@ -253,7 +289,7 @@ class WaPairingFlow {
253
289
  keyIndex: advDeviceIdentity.keyIndex ?? 0,
254
290
  isDeviceHosted
255
291
  });
256
- throw new Error('pair-success account signature validation failed');
292
+ return null;
257
293
  }
258
294
  }
259
295
  signedIdentity.deviceSignature = await (0, WaAdvSignature_1.generateDeviceSignature)(details, localIdentity, accountSignatureKey, false);
@@ -268,19 +304,35 @@ class WaPairingFlow {
268
304
  responseIdentityBytes
269
305
  };
270
306
  }
307
+ /** Mirrors the `not-authorized` IQ error WhatsApp Web returns on a failed pair-success. */
308
+ async sendPairSuccessValidationError(iqNode) {
309
+ try {
310
+ await this.opts.socket.sendNode((0, global_1.buildIqErrorNode)(iqNode, { code: 401, text: 'not-authorized' }));
311
+ }
312
+ catch (error) {
313
+ this.opts.logger.warn('failed to send pair-success error response', {
314
+ message: (0, primitives_1.toError)(error).message
315
+ });
316
+ }
317
+ }
271
318
  async handlePrimaryHello(linkCodeNode) {
272
- const credentials = this.requireCredentials();
319
+ let credentials = this.requireCredentials();
273
320
  const pairingSession = this.pairingSession;
274
- if (!pairingSession || pairingSession.finished) {
321
+ if (!pairingSession) {
275
322
  this.opts.logger.trace('primary_hello ignored: no active session');
276
323
  return;
277
324
  }
278
325
  pairingSession.attempts += 1;
279
326
  this.opts.logger.debug('processing primary_hello', {
280
- attempts: pairingSession.attempts
327
+ attempts: pairingSession.attempts,
328
+ finished: pairingSession.finished
281
329
  });
282
- if (pairingSession.attempts > 3) {
283
- throw new Error('pairing code exceeded maximum primary hello attempts');
330
+ if (pairingSession.finished) {
331
+ if (pairingSession.attempts > constants_1.WA_DEFAULTS.PAIRING_CODE_MAX_PRIMARY_HELLOS) {
332
+ throw new Error('pairing code exceeded maximum primary hello attempts');
333
+ }
334
+ credentials = await this.rotateAdvSecret(credentials);
335
+ pairingSession.finished = false;
284
336
  }
285
337
  const [refNode, wrappedPrimaryNode, primaryIdentityNode] = (0, helpers_1.findNodeChildrenByTags)(linkCodeNode, [
286
338
  constants_1.WA_NODE_TAGS.LINK_CODE_PAIRING_REF,
@@ -309,6 +361,10 @@ class WaPairingFlow {
309
361
  companionEphemeralPrivKey: pairingSession.companionEphemeralKeyPair.privKey,
310
362
  registrationIdentityKeyPair: credentials.registrationInfo.identityKeyPair
311
363
  });
364
+ await this.opts.auth.updateCredentials({
365
+ ...credentials,
366
+ advSecretKey: finish.advSecret
367
+ });
312
368
  const result = await this.opts.socket.query((0, pairing_1.buildCompanionFinishRequestNode)({
313
369
  phoneJid: pairingSession.phoneJid,
314
370
  wrappedKeyBundle: finish.wrappedKeyBundle,
@@ -318,10 +374,6 @@ class WaPairingFlow {
318
374
  if (result.attrs.type === constants_1.WA_IQ_TYPES.ERROR) {
319
375
  throw new Error('companion_finish returned error');
320
376
  }
321
- await this.opts.auth.updateCredentials({
322
- ...credentials,
323
- advSecretKey: finish.advSecret
324
- });
325
377
  pairingSession.finished = true;
326
378
  this.opts.logger.debug('primary_hello completed with companion_finish success');
327
379
  }
@@ -24,6 +24,11 @@ export interface WaAuthCredentials {
24
24
  readonly serverHasPreKeys?: boolean;
25
25
  readonly routingInfo?: Uint8Array;
26
26
  readonly lastSuccessTs?: number;
27
+ /**
28
+ * Successful logins since this device was paired, advertised as `lc` in the
29
+ * noise login payload. Reset to `0` when a new pairing completes.
30
+ */
31
+ readonly loginCounter?: number;
27
32
  readonly propsVersion?: number;
28
33
  readonly abPropsVersion?: number;
29
34
  readonly connectionLocation?: string;
@@ -65,6 +70,14 @@ export interface WaAuthClientOptions {
65
70
  * `'Mac OS'`, `'Linux'`). Defaults to the current runtime's OS.
66
71
  */
67
72
  readonly deviceOsDisplayName?: string;
73
+ /**
74
+ * OS version advertised in `DeviceProps.version` (`'10'`, `'14.6'`, ...).
75
+ * Defaults to the detected runtime OS version. Set this alongside
76
+ * {@link deviceOsDisplayName} when advertising an OS the process is not
77
+ * running on, so the advertised name and version agree. Values that are
78
+ * not dotted-numeric leave the field unset.
79
+ */
80
+ readonly deviceOsVersion?: string;
68
81
  /**
69
82
  * When `true`, request a full history download from the primary device on
70
83
  * pairing instead of just recent messages. Off by default.
@@ -100,6 +100,7 @@ function resolveWaClientBase(options, logger) {
100
100
  sessionId,
101
101
  deviceBrowser: device.browser,
102
102
  deviceOsDisplayName: device.osDisplayName,
103
+ deviceOsVersion: device.osVersion ?? undefined,
103
104
  devicePlatform: device.platform,
104
105
  urls: options.urls ?? options.chatSocketUrls ?? constants_1.WA_DEFAULTS.CHAT_SOCKET_URLS,
105
106
  iqTimeoutMs: options.iqTimeoutMs ?? constants_1.WA_DEFAULTS.IQ_TIMEOUT_MS,
@@ -124,7 +125,7 @@ function createIncomingNodeRuntime(input) {
124
125
  const { logger, emitEvent, authClient, connectionManager, nodeOrchestrator, streamControl, mediaMessageBuildOptions, retryCoordinator, messageDispatch, sendNode, syncAppState, disconnect, clearStoredCredentials, getCurrentCredentials, handleClientDirtyBits, incomingMessageAckOptions } = input;
125
126
  return {
126
127
  handleStreamControlResult: streamControl.handleStreamControlResult,
127
- persistSuccessAttributes: (attributes) => authClient.persistSuccessAttributes(attributes),
128
+ persistSuccessAttributes: (attributes) => authClient.persistSuccessAttributes(attributes, { countsAsLogin: true }),
128
129
  emitSuccessNode: (node) => emitEvent('debug_connection_success', { node }),
129
130
  updateClockSkewFromSuccess: (serverUnixSeconds) => connectionManager.updateClockSkewFromSuccess(serverUnixSeconds),
130
131
  shouldWarmupMediaConn: () => !!(getCurrentCredentials()?.meJid && connectionManager.isConnected()),
@@ -332,6 +333,7 @@ function buildWaClientDependencies(input) {
332
333
  const authClient = new WaAuthClient_1.WaAuthClient({
333
334
  deviceBrowser: options.deviceBrowser,
334
335
  deviceOsDisplayName: options.deviceOsDisplayName,
336
+ deviceOsVersion: options.deviceOsVersion,
335
337
  devicePlatform: options.devicePlatform,
336
338
  requireFullSync: options.requireFullSync,
337
339
  version: options.version,
@@ -398,17 +398,16 @@ class WaMessageDispatchCoordinator {
398
398
  ]);
399
399
  const messageWithIcdc = (0, icdc_1.injectDeviceListMetadata)(messageWithSecret, senderIcdc, recipientIcdc);
400
400
  const plaintext = await (0, padding_1.writeRandomPadMax16)(_proto_1.proto.Message.encode(messageWithIcdc).finish());
401
- const buttonAddonKind = (0, content_1.resolveButtonAddonKind)(messageWithIcdc);
401
+ const outboundAttrs = (0, content_1.resolveOutboundMessageAttrs)(messageWithIcdc);
402
+ const buttonAddonKind = outboundAttrs.buttonAddonKind;
402
403
  const buttonAddonNode = buttonAddonKind ? (0, message_1.buildButtonAddonNode)(buttonAddonKind) : undefined;
403
404
  // when a <biz> companion is attached the stanza must advertise type=text and
404
405
  // omit enc.mediatype; sending type=media + mediatype=list/button alongside the
405
406
  // companion is rejected by the server as SMAX_INVALID (479).
406
- const type = buttonAddonKind ? 'text' : (0, content_1.resolveMessageTypeAttr)(messageWithIcdc);
407
- const edit = (0, content_1.resolveEditAttr)(messageWithIcdc) ?? undefined;
408
- const mediatype = buttonAddonKind
409
- ? undefined
410
- : ((0, content_1.resolveEncMediaType)(messageWithIcdc) ?? undefined);
411
- const metaAttrs = (0, content_1.resolveMetaAttrs)(messageWithIcdc);
407
+ const type = buttonAddonKind ? 'text' : outboundAttrs.typeAttr;
408
+ const edit = outboundAttrs.edit ?? undefined;
409
+ const mediatype = buttonAddonKind ? undefined : (outboundAttrs.mediatype ?? undefined);
410
+ const metaAttrs = outboundAttrs.metaAttrs;
412
411
  const metaNode = metaAttrs ? (0, message_1.buildMetaNode)(metaAttrs) : undefined;
413
412
  const customNodes = [];
414
413
  if (metaNode)
@@ -420,7 +419,7 @@ class WaMessageDispatchCoordinator {
420
419
  customNodes.push(node);
421
420
  }
422
421
  }
423
- const decryptFail = (0, content_1.resolveDecryptFailAttr)(messageWithIcdc);
422
+ const decryptFail = outboundAttrs.decryptFail;
424
423
  const envelope = {
425
424
  message: messageWithIcdc,
426
425
  plaintext,
@@ -540,7 +539,7 @@ class WaMessageDispatchCoordinator {
540
539
  replayStatusSetting: statusSetting,
541
540
  // Bare `<to jid=user>` ack hints route the skmsg through primary
542
541
  // devices that already hold the sender key.
543
- customize: async ({ fanoutDeviceJids, distributionParticipants, messageWithSecret, sendOptions }) => {
542
+ customize: ({ fanoutDeviceJids, distributionParticipants, messageWithSecret, sendOptions }) => {
544
543
  const distributedAddressKeys = new Set();
545
544
  for (let i = 0; i < distributionParticipants.length; i += 1) {
546
545
  distributedAddressKeys.add((0, jid_1.signalAddressKey)(distributionParticipants[i].address));
@@ -560,7 +559,7 @@ class WaMessageDispatchCoordinator {
560
559
  seenAck.add(userJid);
561
560
  ackHints.push({ jid: userJid });
562
561
  }
563
- const reportingArtifacts = await this.tryBuildReportingTokenArtifacts({
562
+ const reportingArtifacts = this.tryBuildReportingTokenArtifacts({
564
563
  message: messageWithSecret,
565
564
  stanzaId: sendOptions.id,
566
565
  senderUserJid: (0, jid_1.toUserJid)(senderJid),
@@ -638,14 +637,15 @@ class WaMessageDispatchCoordinator {
638
637
  participants.push(entry);
639
638
  }
640
639
  }
640
+ const outboundAttrs = (0, content_1.resolveOutboundMessageAttrs)(messageWithSecret);
641
641
  const messageNode = (0, message_1.buildGroupSenderKeyMessageNode)({
642
642
  to: input.groupJid,
643
- type: (0, content_1.resolveMessageTypeAttr)(messageWithSecret),
643
+ type: outboundAttrs.typeAttr,
644
644
  id: sendOptions.id,
645
645
  phash: extras.phash,
646
- edit: (0, content_1.resolveEditAttr)(messageWithSecret) ?? undefined,
647
- mediatype: (0, content_1.resolveEncMediaType)(messageWithSecret) ?? undefined,
648
- decryptFail: (0, content_1.resolveDecryptFailAttr)(messageWithSecret),
646
+ edit: outboundAttrs.edit ?? undefined,
647
+ mediatype: outboundAttrs.mediatype ?? undefined,
648
+ decryptFail: outboundAttrs.decryptFail,
649
649
  groupCiphertext: groupCiphertext.ciphertext,
650
650
  participants,
651
651
  deviceIdentity: shouldAttachDeviceIdentity
@@ -819,8 +819,9 @@ class WaMessageDispatchCoordinator {
819
819
  break;
820
820
  }
821
821
  }
822
- const reportingArtifacts = await this.tryBuildReportingTokenArtifacts({
822
+ const reportingArtifacts = this.tryBuildReportingTokenArtifacts({
823
823
  message,
824
+ messageBytes: (0, padding_1.unpadPkcs7)(plaintext),
824
825
  stanzaId: sendOptions.id,
825
826
  senderUserJid: (0, jid_1.toUserJid)(senderJid),
826
827
  remoteJid: groupJid,
@@ -975,8 +976,9 @@ class WaMessageDispatchCoordinator {
975
976
  phashTargets[phashTargetCount] = senderJid;
976
977
  phashTargets.length = phashTargetCount + 1;
977
978
  const localPhash = (0, phash_1.computePhashV2)(phashTargets);
978
- const reportingArtifacts = await this.tryBuildReportingTokenArtifacts({
979
+ const reportingArtifacts = this.tryBuildReportingTokenArtifacts({
979
980
  message,
981
+ messageBytes: (0, padding_1.unpadPkcs7)(plaintext),
980
982
  stanzaId: sendOptions.id,
981
983
  senderUserJid: (0, jid_1.toUserJid)(senderJid),
982
984
  remoteJid: groupJid,
@@ -1088,9 +1090,6 @@ class WaMessageDispatchCoordinator {
1088
1090
  return (0, jid_1.normalizeDeviceJid)(meJid);
1089
1091
  }
1090
1092
  async encryptGroupDistributionParticipants(groupJid, senderKeyId, senderKeyDistributionMessage, participantUserJids) {
1091
- const distributionPayload = await (0, padding_1.writeRandomPadMax16)(_proto_1.proto.Message.encode({
1092
- senderKeyDistributionMessage
1093
- }).finish());
1094
1093
  const fanoutDeviceJids = await this.deps.fanoutResolver.resolveGroupParticipantDeviceJids(participantUserJids);
1095
1094
  if (fanoutDeviceJids.length === 0) {
1096
1095
  return {
@@ -1098,13 +1097,9 @@ class WaMessageDispatchCoordinator {
1098
1097
  distributionParticipants: []
1099
1098
  };
1100
1099
  }
1101
- const fanoutTargetsByAddressKey = new Map();
1102
1100
  const fanoutAddresses = new Array(fanoutDeviceJids.length);
1103
1101
  for (let index = 0; index < fanoutDeviceJids.length; index += 1) {
1104
- const jid = fanoutDeviceJids[index];
1105
- const address = (0, jid_1.parseSignalAddressFromJid)(jid);
1106
- fanoutAddresses[index] = address;
1107
- fanoutTargetsByAddressKey.set((0, jid_1.signalAddressKey)(address), { jid, address });
1102
+ fanoutAddresses[index] = (0, jid_1.parseSignalAddressFromJid)(fanoutDeviceJids[index]);
1108
1103
  }
1109
1104
  const pendingAddresses = await this.deps.senderKeyManager.filterParticipantsNeedingDistribution(groupJid, senderKeyId, fanoutAddresses);
1110
1105
  if (pendingAddresses.length === 0) {
@@ -1113,6 +1108,14 @@ class WaMessageDispatchCoordinator {
1113
1108
  distributionParticipants: []
1114
1109
  };
1115
1110
  }
1111
+ const fanoutTargetsByAddressKey = new Map();
1112
+ for (let index = 0; index < fanoutAddresses.length; index += 1) {
1113
+ const address = fanoutAddresses[index];
1114
+ fanoutTargetsByAddressKey.set((0, jid_1.signalAddressKey)(address), {
1115
+ jid: fanoutDeviceJids[index],
1116
+ address
1117
+ });
1118
+ }
1116
1119
  const pendingAddressKeys = new Set();
1117
1120
  const pendingTargets = [];
1118
1121
  for (let index = 0; index < pendingAddresses.length; index += 1) {
@@ -1172,6 +1175,9 @@ class WaMessageDispatchCoordinator {
1172
1175
  distributionParticipants: []
1173
1176
  };
1174
1177
  }
1178
+ const distributionPayload = await (0, padding_1.writeRandomPadMax16)(_proto_1.proto.Message.encode({
1179
+ senderKeyDistributionMessage
1180
+ }).finish());
1175
1181
  const distributionEncryptRequests = new Array(availableTargets.length);
1176
1182
  for (let index = 0; index < availableTargets.length; index += 1) {
1177
1183
  const target = availableTargets[index];
@@ -1324,8 +1330,9 @@ class WaMessageDispatchCoordinator {
1324
1330
  const deviceIdentity = shouldAttachDeviceIdentity
1325
1331
  ? this.getEncodedSignedDeviceIdentity()
1326
1332
  : undefined;
1327
- const reportingArtifacts = await this.tryBuildReportingTokenArtifacts({
1333
+ const reportingArtifacts = this.tryBuildReportingTokenArtifacts({
1328
1334
  message,
1335
+ messageBytes: (0, padding_1.unpadPkcs7)(plaintext),
1329
1336
  stanzaId: sendOptions.id,
1330
1337
  senderUserJid: meUserJid,
1331
1338
  remoteJid: recipientUserJid,
@@ -1428,13 +1435,14 @@ class WaMessageDispatchCoordinator {
1428
1435
  return `3EB0${(0, bytes_1.bytesToHex)(await (0, _crypto_1.randomBytesAsync)(8)).toUpperCase()}`;
1429
1436
  }
1430
1437
  }
1431
- async tryBuildReportingTokenArtifacts(input) {
1438
+ tryBuildReportingTokenArtifacts(input) {
1432
1439
  if (!input.stanzaId) {
1433
1440
  return null;
1434
1441
  }
1435
1442
  try {
1436
- return await (0, reporting_token_1.buildReportingTokenArtifacts)({
1443
+ return (0, reporting_token_1.buildReportingTokenArtifacts)({
1437
1444
  message: input.message,
1445
+ messageBytes: input.messageBytes,
1438
1446
  stanzaId: input.stanzaId,
1439
1447
  senderUserJid: input.senderUserJid,
1440
1448
  remoteJid: input.remoteJid