@oxidezap/baileyrs 0.3.14 → 0.3.15

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.
package/README.md CHANGED
@@ -152,6 +152,25 @@ out-of-order gaps can become native-only and need a new Signal handshake after
152
152
  rollback. Engines older than 0.2.8 cannot read newer seed-only skipped-key records;
153
153
  do not delete native-only session rows to force a downgrade.
154
154
 
155
+ ### Bridge 0.26.7 storage and media
156
+
157
+ Custom native stores must implement complete, account-scoped `listKeys` and set
158
+ `capabilities.enumerate: true` for ADV identity recovery. Enumeration must include
159
+ historical `session`, `identity` and `sender_key_devices` rows and observe other
160
+ writers on every call. Propagate scan errors; a successful partial list can leave
161
+ stale Signal state behind. `useMultiFileAuthState` and `useMemoryStore` provide
162
+ this capability. `wrapLegacyStore`, including `useLegacyMultiFileAuthState`, does
163
+ not advertise enumeration, so recovery requiring it fails with a storage error.
164
+ Ordinary reads and writes still work; a cache of newly written keys cannot make
165
+ historical legacy state enumerable. Use a native store when recovery is required.
166
+
167
+ The socket option `additionalStaticMediaHosts: ['cdn.example:8443']` adds exact
168
+ HTTPS authorities for static media at construction. Omit schemes, paths and
169
+ wildcards. It does not configure uploads or TLS trust. The built-in HTTP adapter
170
+ rejects redirects, including when `options.redirect` requests following them.
171
+ Custom host transports must also reject redirects or return the original visible
172
+ 3xx response; status-zero and opaque redirects are errors.
173
+
155
174
  ### Connection lifecycle
156
175
 
157
176
  Transient drops are retried by Rust and report `connecting`. A terminal `close`
@@ -1,7 +1,7 @@
1
1
  import { assertStoreCallbacks } from '../Utils/atomic-store.js';
2
2
  import { calculateSignature, generateKeyPair } from '@oxidezap/whatsapp-rust-bridge/host';
3
3
  import { concatBytes } from '../Runtime/bytes.js';
4
- import { createDeviceProjection } from './legacy-store/device.js';
4
+ import { createDeviceProjection, hasInlineDeviceAccount } from './legacy-store/device.js';
5
5
  import { base64Encode, randomBytes, readU16BE } from '../Runtime/bytes.js';
6
6
  const DEVICE_STORE = 'device';
7
7
  const DEVICE_RECORDS = ['device', 'account'];
@@ -9,7 +9,7 @@ const newKeyPair = () => {
9
9
  const pair = generateKeyPair();
10
10
  return {
11
11
  private: new Uint8Array(pair.privKey),
12
- public: new Uint8Array(pair.pubKey.subarray(1))
12
+ public: pair.pubKey.slice(1)
13
13
  };
14
14
  };
15
15
  /** Signal version-byte prefix, matching `Defaults.KEY_BUNDLE_TYPE` without importing Node's Buffer. */
@@ -33,14 +33,15 @@ const newSignedKeyPair = (identityKeyPair, keyId) => {
33
33
  */
34
34
  export const initHostAuthCreds = () => {
35
35
  const signedIdentityKey = newKeyPair();
36
- const registration = readU16BE(randomBytes(2)) & 0x3fff;
36
+ const entropy = randomBytes(34);
37
+ const registration = readU16BE(entropy) & 0x3fff;
37
38
  return {
38
39
  noiseKey: newKeyPair(),
39
40
  pairingEphemeralKeyPair: newKeyPair(),
40
41
  signedIdentityKey,
41
42
  signedPreKey: newSignedKeyPair(signedIdentityKey, 1),
42
43
  registrationId: registration,
43
- advSecretKey: base64Encode(randomBytes(32)),
44
+ advSecretKey: base64Encode(entropy.slice(2)),
44
45
  processedHistoryMessages: [],
45
46
  nextPreKeyId: 1,
46
47
  firstUnuploadedPreKeyId: 1,
@@ -55,11 +56,16 @@ export const initHostAuthCreds = () => {
55
56
  };
56
57
  const hydrateFromStore = async (store, creds) => {
57
58
  const projection = createDeviceProjection(creds);
59
+ let inlineAccount = false;
58
60
  for (const record of DEVICE_RECORDS) {
61
+ if (record === 'account' && inlineAccount)
62
+ continue;
59
63
  const payload = await store.get(DEVICE_STORE, record);
60
64
  if (!payload)
61
65
  continue;
62
66
  try {
67
+ if (record === 'device')
68
+ inlineAccount = hasInlineDeviceAccount(payload);
63
69
  projection.prepare(record, payload)();
64
70
  }
65
71
  catch (error) {
@@ -6,7 +6,7 @@ import { base64Encode, concatBytes, randomBytes, readU16BE, utf8Decode } from '.
6
6
  import { jidEncode } from '../WABinary/jid-utils.js';
7
7
  const pair = () => {
8
8
  const value = generateKeyPair();
9
- return { private: new Uint8Array(value.privKey), public: new Uint8Array(value.pubKey.subarray(1)) };
9
+ return { private: new Uint8Array(value.privKey), public: value.pubKey.slice(1) };
10
10
  };
11
11
  const signed = (identity) => {
12
12
  const keyPair = pair();
@@ -15,13 +15,14 @@ const signed = (identity) => {
15
15
  };
16
16
  export const initHostAuthCreds = () => {
17
17
  const identity = pair();
18
+ const entropy = randomBytes(34);
18
19
  return {
19
20
  noiseKey: pair(),
20
21
  pairingEphemeralKeyPair: pair(),
21
22
  signedIdentityKey: identity,
22
23
  signedPreKey: signed(identity),
23
- registrationId: readU16BE(randomBytes(2)) & 0x3fff,
24
- advSecretKey: base64Encode(randomBytes(32)),
24
+ registrationId: readU16BE(entropy) & 0x3fff,
25
+ advSecretKey: base64Encode(entropy.slice(2)),
25
26
  processedHistoryMessages: [],
26
27
  nextPreKeyId: 1,
27
28
  firstUnuploadedPreKeyId: 1,
@@ -1,5 +1,7 @@
1
1
  import type { AuthenticationCreds } from '../../Types/index.js';
2
2
  import { type DeviceRecordKeyName } from './constants.js';
3
+ /** Only omission permits loading the historical account sidecar. */
4
+ export declare const hasInlineDeviceAccount: (payload: Uint8Array) => boolean;
3
5
  export type DeviceProjection = {
4
6
  read(key: DeviceRecordKeyName): Uint8Array | null;
5
7
  prepare(key: DeviceRecordKeyName, payload: Uint8Array): () => void;
@@ -61,6 +61,7 @@ function deviceFromCreds(creds) {
61
61
  return null;
62
62
  const pn = legacyJidToNative(creds.me.id);
63
63
  const lid = legacyJidToNative(creds.me.lid);
64
+ const account = accountBytes(creds);
64
65
  return toJsonBytes({
65
66
  pn,
66
67
  lid,
@@ -75,7 +76,7 @@ function deviceFromCreds(creds) {
75
76
  adv_secret_key: creds.advSecretKey
76
77
  ? bytesToNumbers(base64Decode(creds.advSecretKey))
77
78
  : Array(SignalKeyLength.ADV_SECRET).fill(0),
78
- account: null,
79
+ account: account ? bytesToNumbers(account) : null,
79
80
  push_name: creds.me.name ?? '',
80
81
  app_version_primary: APP_VERSION_PRIMARY,
81
82
  app_version_secondary: APP_VERSION_SECONDARY,
@@ -100,6 +101,11 @@ const accountBytes = (creds) => {
100
101
  };
101
102
  function prepareNativeDevice(payload) {
102
103
  const native = fromJsonBytes(payload);
104
+ // Inline presence is authoritative in the bridge. Omission alone permits
105
+ // the older account sidecar fallback; null explicitly retires the account.
106
+ const account = native.account == null
107
+ ? native.account
108
+ : signedDeviceIdentityCodec.decode(new Uint8Array(requireByteArray(native.account, 'device account')));
103
109
  const pn = nativeJidToString(native.pn);
104
110
  const lid = nativeJidToString(native.lid);
105
111
  const registrationId = native.registration_id === undefined
@@ -128,6 +134,10 @@ function prepareNativeDevice(payload) {
128
134
  // Upstream marks the initial Signal material readonly on the public
129
135
  // credential contract. Native-state hydration is the one internal owner
130
136
  // allowed to replace that material after reading Rust's persisted device.
137
+ if (account === null)
138
+ delete creds.account;
139
+ else if (account !== undefined)
140
+ creds.account = account;
131
141
  const mutableCreds = creds;
132
142
  if (pn) {
133
143
  mutableCreds.me = { ...creds.me, id: pn };
@@ -167,6 +177,8 @@ function prepareNativeDevice(payload) {
167
177
  creds.routingInfo = publicBytes(new Uint8Array(routingInfo));
168
178
  };
169
179
  }
180
+ /** Only omission permits loading the historical account sidecar. */
181
+ export const hasInlineDeviceAccount = (payload) => Object.hasOwn(fromJsonBytes(payload), 'account');
170
182
  export function parseDeviceRecordKey(value) {
171
183
  if (value === DeviceRecordKey.DEVICE || value === DeviceRecordKey.ACCOUNT)
172
184
  return value;
@@ -595,7 +595,10 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
595
595
  // other truthy value at construction, so a `!!`/ternary-style
596
596
  // coercion could promote a malformed opt-out into an opt-in.
597
597
  // Absent stays strict.
598
- fullConfig.dangerSkipCertChainVerify, makeHistorySyncAdmission(shouldSyncHistoryMessage));
598
+ fullConfig.dangerSkipCertChainVerify, {
599
+ ...makeHistorySyncAdmission(shouldSyncHistoryMessage),
600
+ additionalStaticMediaHosts: fullConfig.additionalStaticMediaHosts
601
+ });
599
602
  // `end()` can land while the client is still being built — a `sock.end()`
600
603
  // or `await using` right after `makeWASocket()` does exactly that. When
601
604
  // it has, `adopt` frees this client and tells us to stop: nothing else
@@ -153,12 +153,15 @@ export const makeTransport = (config) => {
153
153
  };
154
154
  export const makeHttpClient = (config) => ({
155
155
  async execute(url, method, headers, body) {
156
- const fetchOpts = { method, headers };
156
+ const fetchOpts = { method, headers, redirect: 'error' };
157
157
  if (body)
158
158
  fetchOpts.body = body;
159
159
  if (config.options?.dispatcher)
160
160
  fetchOpts.dispatcher = config.options.dispatcher;
161
161
  const resp = await fetch(url, fetchOpts);
162
+ if (resp.status === 0 || resp.type === 'opaqueredirect') {
163
+ throw new Error('HTTP adapter received an unobservable redirect or network response');
164
+ }
162
165
  const buf = new Uint8Array(await resp.arrayBuffer());
163
166
  return { statusCode: resp.status, body: buf };
164
167
  }
@@ -33,7 +33,7 @@ export declare const UNSUPPORTED_CONFIG_KEYS: readonly ["keepAliveIntervalMs", "
33
33
  * member of `SocketConfig` belongs to neither list — which is exactly how the
34
34
  * first version of the catalog shipped twelve keys short.
35
35
  */
36
- export declare const READ_CONFIG_KEYS: readonly ["waWebSocketUrl", "options", "logger", "version", "browser", "pushName", "auth", "cache", "deviceProps", "wantedPreKeyCount", "dangerSkipCertChainVerify", "shouldSyncHistoryMessage", "emitOwnEvents", "shouldIgnoreJid", "defaultQueryTimeoutMs", "transactionOpts", "makeSignalRepository"];
36
+ export declare const READ_CONFIG_KEYS: readonly ["waWebSocketUrl", "options", "logger", "version", "browser", "pushName", "auth", "cache", "additionalStaticMediaHosts", "deviceProps", "wantedPreKeyCount", "dangerSkipCertChainVerify", "shouldSyncHistoryMessage", "emitOwnEvents", "shouldIgnoreJid", "defaultQueryTimeoutMs", "transactionOpts", "makeSignalRepository"];
37
37
  /**
38
38
  * Which unsupported options this caller actually passed.
39
39
  *
@@ -96,6 +96,7 @@ export const READ_CONFIG_KEYS = [
96
96
  'pushName',
97
97
  'auth',
98
98
  'cache',
99
+ 'additionalStaticMediaHosts',
99
100
  'deviceProps',
100
101
  'wantedPreKeyCount',
101
102
  'dangerSkipCertChainVerify',
@@ -59,6 +59,9 @@ export type SocketConfig = {
59
59
  emitOwnEvents: boolean;
60
60
  /** Custom media upload hosts. */
61
61
  customUploadHosts: MediaConnInfo['hosts'];
62
+ /** Additional exact HTTPS authorities for static media. No schemes, paths,
63
+ * wildcards or redirects. Captured by the bridge at client construction. */
64
+ additionalStaticMediaHosts?: readonly string[];
62
65
  /** provide an auth state object to maintain the auth state */
63
66
  auth: AuthenticationState;
64
67
  /**
@@ -1,4 +1,4 @@
1
- import { recordFlushFailure, settledFlushError, trackFlushFailures, withTrackedFailures } from './flush-deadline.js';
1
+ import { settleBeforeFlushDeadline, flushDeadlineError, recordFlushFailure, settledFlushError, trackFlushFailures, withTrackedFailures } from './flush-deadline.js';
2
2
  import { defaultSyncDir } from './durable-directory.js';
3
3
  import { transactionalFileStore } from './transactional-file-store.js';
4
4
  import { Buffer } from 'node:buffer';
@@ -356,6 +356,7 @@ async function usePerKeyBridgeStore(folder, options) {
356
356
  const FLUSH_MAX_PASSES = 32;
357
357
  const newDrainScope = () => ({ failedEntries: new WeakSet() });
358
358
  const flushAll = (scope = newDrainScope()) => {
359
+ const deadline = Date.now() + 30000;
359
360
  const errors = new Map();
360
361
  const drain = async () => {
361
362
  if (scope.exhausted) {
@@ -381,17 +382,20 @@ async function usePerKeyBridgeStore(folder, options) {
381
382
  // guards a caller emitting writes in a tight loop —
382
383
  // `Socket/index.ts.end()` waits on this and must return.
383
384
  for (let i = 0; i < FLUSH_MAX_PASSES; i++) {
384
- const outstanding = [...admitted];
385
- if (outstanding.length > 0) {
386
- await Promise.all(outstanding.map(operation => operation.catch(error => {
387
- recordFlushFailure(errors, operation, error);
388
- })));
389
- }
390
- if (eligibleKeys().length === 0) {
391
- if (admitted.size === 0)
385
+ // Consecutive critical callbacks are already writing through. Join
386
+ // their admission barrier within this pass, under the same 30s
387
+ // deadline; only actual pending-write drains spend the 32 passes.
388
+ while (admitted.size > 0) {
389
+ // Cache hits can settle only through microtasks and starve the
390
+ // timeout callback, so enforce the wall clock before each batch.
391
+ if (Date.now() >= deadline)
392
+ throw flushDeadlineError('use-bridge-store flush', errors);
393
+ await settleBeforeFlushDeadline([...admitted], deadline, 'use-bridge-store flush', errors);
394
+ if (errors.size)
392
395
  break;
393
- continue;
394
396
  }
397
+ if (errors.size || eligibleKeys().length === 0)
398
+ break;
395
399
  const keys = eligibleKeys();
396
400
  let failed = false;
397
401
  await Promise.all(keys.map(key => {
@@ -623,8 +627,10 @@ async function usePerKeyBridgeStore(folder, options) {
623
627
  key = decodeURIComponent(encoded);
624
628
  }
625
629
  catch {
626
- continue; // skip a filename we can't decode rather than crash
630
+ throw new TypeError(`invalid native auth filename: ${file}`);
627
631
  }
632
+ if (encodeURIComponent(key) !== encoded)
633
+ throw new TypeError(`noncanonical native auth filename: ${file}`);
628
634
  if (prefix && !key.startsWith(prefix))
629
635
  continue;
630
636
  found.add(key);
@@ -1,5 +1,5 @@
1
1
  import { mkdir, stat } from 'node:fs/promises';
2
- import { createDeviceProjection } from '../Compatibility/legacy-store/device.js';
2
+ import { createDeviceProjection, hasInlineDeviceAccount } from '../Compatibility/legacy-store/device.js';
3
3
  import { projectNativeStore } from '../Compatibility/legacy-store/native-projection.js';
4
4
  import { initAuthCreds } from './generics.js';
5
5
  import { useBridgeStore } from './use-bridge-store.js';
@@ -27,11 +27,16 @@ const DEVICE_RECORDS = ['device', 'account'];
27
27
  */
28
28
  const hydrateFromStore = async (store, creds) => {
29
29
  const projection = createDeviceProjection(creds);
30
+ let inlineAccount = false;
30
31
  for (const record of DEVICE_RECORDS) {
32
+ if (record === 'account' && inlineAccount)
33
+ continue;
31
34
  const payload = await store.get(DEVICE_STORE, record);
32
35
  if (!payload)
33
36
  continue;
34
37
  try {
38
+ if (record === 'device')
39
+ inlineAccount = hasInlineDeviceAccount(payload);
35
40
  projection.prepare(record, payload)();
36
41
  }
37
42
  catch {
@@ -121,6 +121,8 @@ export type HostSocketConfig = {
121
121
  browser?: [os: string, browser: string, version: string];
122
122
  pushName?: string;
123
123
  emitOwnEvents?: boolean;
124
+ /** Additional exact HTTPS authorities for static media; redirects remain disabled. */
125
+ additionalStaticMediaHosts?: readonly string[];
124
126
  customUploadHosts?: Array<{
125
127
  hostname: string;
126
128
  maxContentLengthBytes: number;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oxidezap/baileyrs",
3
3
  "type": "module",
4
- "version": "0.3.14",
4
+ "version": "0.3.15",
5
5
  "description": "A Rust-powered WhatsApp Web library for JavaScript, with a Baileys-compatible API",
6
6
  "keywords": [
7
7
  "whatsapp",
@@ -96,7 +96,7 @@
96
96
  "typecheck:bench": "tsc -p bench/tsconfig.json"
97
97
  },
98
98
  "dependencies": {
99
- "@oxidezap/whatsapp-rust-bridge": "0.26.4",
99
+ "@oxidezap/whatsapp-rust-bridge": "0.26.8",
100
100
  "events": "^3.3.0",
101
101
  "fs-native-extensions": "1.5.3",
102
102
  "long": "^5.3.2"
@@ -119,6 +119,7 @@
119
119
  "tsc-esm-fix": "^3.1.2",
120
120
  "typescript": "^7.0.2",
121
121
  "typescript-compat-auditor": "npm:typescript@6.0.3",
122
+ "undici": "7.30.1",
122
123
  "vite": "8.3.6",
123
124
  "vitest": "5.1.0",
124
125
  "wrangler": "4.158.0"