@oxidezap/baileyrs 0.3.12 → 0.3.14

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
@@ -4,610 +4,209 @@
4
4
  [![npm downloads](https://img.shields.io/npm/dm/@oxidezap/baileyrs?color=cb3837&logo=npm)](https://www.npmjs.com/package/@oxidezap/baileyrs)
5
5
  [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/oxidezap/baileyrs)
6
6
  [![pkg.pr.new](https://pkg.pr.new/badge/oxidezap/baileyrs)](https://pkg.pr.new/~/oxidezap/baileyrs)
7
+ [![CodSpeed](https://img.shields.io/endpoint?url=https://codspeed.io/badge.json)](https://app.codspeed.io/oxidezap/baileyrs?utm_source=badge)
7
8
 
8
- A Rust-powered WhatsApp Web library for JavaScript, with a Baileys-compatible API.
9
-
10
- ## How it works
11
-
12
- baileyrs is a thin JavaScript wrapper over [whatsapp-rust](https://github.com/oxidezap/whatsapp-rust)
13
- compiled to WebAssembly. The heavy lifting — Signal protocol, Noise handshake, media
14
- encryption, binary-node (de)serialization, protobuf codec — runs in Rust/WASM via the
15
- [whatsapp-rust-bridge](https://www.npmjs.com/package/whatsapp-rust-bridge) package.
16
-
17
- The public surface intentionally mirrors [Baileys](https://github.com/WhiskeySockets/Baileys)
18
- so existing integrations can migrate with minimal changes. See
19
- [ATTRIBUTION.md](ATTRIBUTION.md) for details.
20
-
21
- ### vs. Baileys
22
-
23
- | Area | Original Baileys | baileyrs |
24
- |---|---|---|
25
- | Signal Protocol | JS (libsignal) | Rust/WASM |
26
- | Media encrypt/decrypt | Node.js crypto | Rust AES-256-CBC + HMAC |
27
- | Media upload/download | JS fetch + temp files | Rust with CDN failover, auth refresh, resumable upload |
28
- | Key management | JS auth state | Rust `PersistenceManager` |
29
- | Auto-reconnect | Manual `startSock()` loop | Transient drops retried in Rust (fibonacci backoff); terminal ones still yours |
30
-
31
- Compatibility is checked rather than assumed: CI compiles and runs consumer code
32
- against the locally packed npm tarball under the upstream package name, exercises
33
- published deep imports and verifies host initialization in workerd with
34
- `nodejs_compat` disabled. It also runs the proto-runtime, wire-fidelity and
35
- lifecycle contract audits. The strict declaration audit is available as
36
- `npm run compat:audit:strict`; it currently reports known declaration gaps and
37
- is not a green gate yet. Layer ownership is checked by `npm run compat:layers`
38
- when sibling core and bridge checkouts are available.
39
- Behavioural suites and a [differential fuzz suite](src/__fuzz__/README.md)
40
- generate inputs from the proto schema and compare the two libraries directly.
41
- Differences the fuzzers find are recorded with a reason and a review date, and
42
- known open ones are listed in `src/__fuzz__/harness/divergence.ts`.
43
-
44
- ### Protobuf field names
45
-
46
- The bridge and upstream Baileys generate their schemas from different sources, so a
47
- field can keep its number and wire type and still be spelled differently. The `proto`
48
- facade always uses the Baileys spelling:
49
-
50
- | Type | Baileys | Bridge |
51
- | -------------------------------------- | ------------------------ | -------------------------------- |
52
- | `SyncActionValue.AgentAction` | `deviceID` | `deviceId` |
53
- | `SyncActionValue.ChatAssignmentAction` | `deviceAgentID` | `deviceAgentId` |
54
- | `Message.ExtendedTextMessage` | `faviconMMSMetadata` | `faviconMmsMetadata` |
55
- | `Message.MessageHistoryMetadata` | `oldestMessageTimestamp` | `oldestMessageTimestampInWindow` |
56
-
57
- Without the translation a write in the Baileys spelling is dropped by the codec and a
58
- read never sets the public property. Both the facade and the send path translate, in
59
- both directions, for fields nested at any depth. An own public property wins over the
60
- bridge name, including an explicit `null` or `undefined`, and inputs are never
61
- mutated. The bridge keeps its own names.
62
-
63
- ### Bridge 0.25 compatibility
64
-
65
- The runtime dependency is pinned to `@oxidezap/whatsapp-rust-bridge@0.25.0`.
66
- The public API still targets `baileys@7.0.0-rc14`.
67
-
68
- - `groupFetchAllParticipating()` and `communityFetchAllParticipating()` fetch full
69
- metadata for each slim bridge listing entry. This adds one metadata request per
70
- group, preserves participants and settings, and rejects on any failed fetch
71
- before emitting `groups.update`.
72
- - Reachout pushes use the typed bridge event once, ignoring its raw MEX twin.
73
- `connection.update.reachoutTimeLock` preserves unknown enforcement names at
74
- runtime; a missing `isActive` means unknown, not a lifted restriction. This
75
- reports server state and does not prevent device removal or impose send policy.
76
- - A terminal `device_removed` or unknown conflict reports `loggedOut` rather than
77
- `connectionReplaced`, including when run completion arrives before the event.
78
- - `newsletterMute()` and `newsletterUnmute()` change channel-update notifications.
79
- Metadata exposes that setting as `mute_state`, independently of admin-facing
80
- follower-activity notifications. Reactions still resolve to `undefined`.
81
- History results may omit `messageId`; `serverId` and large counters remain
82
- strings. The bridge's packed live-message format does not carry the new
83
- newsletter server ID; only object events and history results expose it.
84
- - A failed community configuration can reject after creation succeeded. Preserve
85
- the error's `createdJid`, `step`, `kind` and `cause`, then resume configuration on
86
- that JID instead of repeating `communityCreate()`.
87
- - Synced status privacy reaches `settings.update`; the unarchive setting reaches
88
- `creds.update`. Historical calls, favorite chats and sticker-list updates have
89
- no corresponding event in the pinned Baileys API and are acknowledged without
90
- emitting unrelated live-call or message events.
91
-
92
- ## Documentation
93
-
94
- The full API reference and guides live in the
95
- **[baileyrs wiki](https://deepwiki.com/oxidezap/baileyrs)** — sending messages and
96
- media, groups, privacy, newsletters, custom stores, socket configuration,
97
- error handling, memory monitoring, and more.
9
+ A WhatsApp Web library for JavaScript with a Baileys-compatible API, backed by
10
+ [whatsapp-rust](https://github.com/oxidezap/whatsapp-rust) through the
11
+ [@oxidezap/whatsapp-rust-bridge](https://www.npmjs.com/package/@oxidezap/whatsapp-rust-bridge) WASM package.
98
12
 
99
- ## Installation
13
+ See [ATTRIBUTION.md](ATTRIBUTION.md) for upstream attribution.
14
+
15
+ [Guides and API overview](https://deepwiki.com/oxidezap/baileyrs) ·
16
+ [Examples](Example) · [Changelog](CHANGELOG.md) · [Contributing](AGENTS.md)
100
17
 
101
- Requires Node.js 22.3 or newer for the Node API. A runtime-neutral `/host` entrypoint is available for Workers, Deno, and browser-like hosts.
18
+ ## Installation
102
19
 
103
- ### New project
20
+ Requires Node.js 22.3 or newer for the Node API.
104
21
 
105
22
  ```sh
106
23
  npm install @oxidezap/baileyrs
107
24
  ```
108
25
 
109
- ```ts
110
- import makeWASocket from '@oxidezap/baileyrs'
111
- ```
26
+ To keep existing Baileys imports, install an alias instead:
112
27
 
113
- ### Host-neutral entrypoint
114
-
115
- For Workers, Deno, or browser-like runtimes, import `/host` and initialize the bridge
116
- WASM before creating a socket. Provide a caller-owned `JsStoreCallbacks` auth store;
117
- this path does not use filesystem auth or Node streams.
118
-
119
- ```ts
120
- import makeWASocket, { createAuthenticationState, useMemoryStore } from '@oxidezap/baileyrs/host'
121
- import wasm from '@oxidezap/baileyrs/wasm'
122
- import { initSync } from '@oxidezap/whatsapp-rust-bridge/host'
123
-
124
- initSync({ module: wasm })
125
- const store = useMemoryStore()
126
- const auth = await createAuthenticationState(store)
127
- const socket = makeWASocket({ auth })
28
+ ```sh
29
+ npm install @whiskeysockets/baileys@npm:@oxidezap/baileyrs
128
30
  ```
129
31
 
130
- The socket initializes the bridge crypto engine during startup. If you call the
131
- standalone AES-backed media retry helpers without creating a socket, initialize
132
- the bridge engine yourself first (`initWasmEngine()`; after `initSync()` on
133
- hosts).
134
-
135
- For a custom host runtime, bind media helpers to its bridge and random source once:
136
- `makeMediaCryptoRuntime(runtime)` returns a capability you can pass as the final
137
- argument to `/host`'s `getMediaKeys`, `encryptMediaRetryRequest`, and
138
- `decryptMediaRetryData` helpers. This keeps HKDF and AES-GCM on the selected
139
- bridge instead of the default host singleton.
140
-
141
- Reuse the same byte-preserving store on restart: `await createAuthenticationState(store)`
142
- rehydrates the device written by the Rust engine, including its registration ID
143
- (which may exceed the 14-bit ID used to seed fresh Baileys-style credentials).
144
- Do not reset or truncate an existing device record to work around a failed read.
145
- Node consumers should continue using the root entrypoint and
146
- `useMultiFileAuthState` unchanged.
147
-
148
- ### Drop-in replacement for upstream Baileys
32
+ The API targets [Baileys 7.0.0-rc14](https://github.com/WhiskeySockets/Baileys).
33
+ Compatibility has known gaps; see [migration notes](#migrating-from-upstream-baileys)
34
+ and the [compatibility audits](scripts/compatibility).
149
35
 
150
- baileyrs is API-compatible with [@whiskeysockets/baileys](https://github.com/WhiskeySockets/Baileys).
151
- Existing projects switch over by aliasing the package — **the API and imports
152
- need no source changes**. Two things do:
153
-
154
- - Carrying an existing pairing across takes a one-line import swap, see
155
- [Migrating from Upstream Baileys](#migrating-from-upstream-baileys).
156
- - If your `connection.update` handler was written for a version of baileyrs
157
- before 0.1, see [Gotchas](#gotchas): a `close` now always means the socket
158
- is finished, and you have to recreate it. Code written against upstream
159
- Baileys already does the right thing.
36
+ ## Quick start
160
37
 
38
+ This example prints a pairing code for a new session and logs incoming messages.
39
+ Save it as `bot.mjs`. Set `PHONE_NUMBER` to your number with country
40
+ code, digits only, and enter the code in WhatsApp's linked-devices screen.
161
41
 
162
42
  ```sh
163
- npm install @whiskeysockets/baileys@npm:@oxidezap/baileyrs
43
+ PHONE_NUMBER=1234567890 node bot.mjs
164
44
  ```
165
45
 
166
- That writes the alias to your `package.json` (with the latest version at install time):
46
+ ```js
47
+ import makeWASocket, { useMultiFileAuthState } from '@oxidezap/baileyrs'
48
+
49
+ const { state } = await useMultiFileAuthState('auth_info')
50
+ const phoneNumber = process.env.PHONE_NUMBER
51
+ if (!state.creds.registered && !phoneNumber) throw new Error('Set PHONE_NUMBER to pair')
52
+ const sock = makeWASocket({ auth: state })
53
+ let pairingRequested = false
54
+
55
+ sock.ev.on('connection.update', ({ connection, qr, lastDisconnect }) => {
56
+ if (qr && phoneNumber && !state.creds.registered && !pairingRequested) {
57
+ pairingRequested = true
58
+ sock.requestPairingCode(phoneNumber)
59
+ .then(code => console.log('Pairing code:', code))
60
+ .catch(error => {
61
+ pairingRequested = false
62
+ console.error('Pairing failed:', error)
63
+ })
64
+ }
65
+ if (connection === 'open') console.log('Connected')
66
+ if (connection === 'close') console.error('Socket closed:', lastDisconnect?.error)
67
+ })
167
68
 
168
- ```jsonc
169
- {
170
- "dependencies": {
171
- "@whiskeysockets/baileys": "npm:@oxidezap/baileyrs@^x.x.x"
172
- }
173
- }
69
+ sock.ev.on('messages.upsert', ({ messages }) => {
70
+ for (const message of messages) console.log('Received:', message.key.id)
71
+ })
174
72
  ```
175
73
 
176
- Every `import { makeWASocket } from '@whiskeysockets/baileys'` in your codebase
177
- now resolves to baileyrs.
74
+ Native auth persists automatically. Keep `auth_info` private and reuse it on
75
+ restart. The example stops on terminal closure; [Example/example.ts](Example/example.ts)
76
+ includes QR authentication, sending messages and a reconnect policy.
178
77
 
179
- ### What gets installed
78
+ When QR refs expire while a pair code is still outstanding, the socket stays
79
+ open if the engine keeps that pairing flow alive. No `connection.update` is
80
+ emitted for that QR expiry. QR-only exhaustion still closes with a 408 timeout;
81
+ bridges that omit the disconnection flag retain that behavior.
180
82
 
181
- `npm install @oxidezap/baileyrs` always brings two runtime dependencies.
83
+ ### Host-neutral entrypoint
182
84
 
183
- - `@oxidezap/whatsapp-rust-bridge` is the Rust engine doing the protocol
184
- work. It is the library, not an add-on, so it stays a hard dependency.
185
- - `long` stays too. Fields like `messageTimestamp` and `fileLength` are
186
- `Long` objects in the types, and the package builds real ones at runtime.
187
- A consumer without it fails compilation in four declaration files and
188
- fails at import, so there is nothing to save by dropping it. I checked.
85
+ For Workers, Deno and browser-like hosts, initialize WASM before creating a socket:
189
86
 
190
- Everything else is an optional peer. It is used when present and skipped
191
- when not.
87
+ ```ts
88
+ import makeWASocket, { createAuthenticationState, useMemoryStore } from '@oxidezap/baileyrs/host'
89
+ import wasm from '@oxidezap/baileyrs/wasm'
90
+ import { initSync } from '@oxidezap/whatsapp-rust-bridge/host'
192
91
 
193
- | Peer | What it does | Without it |
194
- | --- | --- | --- |
195
- | `@hapi/boom` (`^9` or `^10`) | Backs the exported `Boom` errors | A built-in implementation with the same shape |
196
- | `pino` (`^9` or `^10`) | Backs the default logger | JSON lines on stdout, same redaction |
197
- | `sharp`, `jimp`, `audio-decode`, `link-preview-js`, `music-metadata` | Media work | Same behavior as before this change |
92
+ initSync({ module: wasm })
93
+ const store = useMemoryStore()
94
+ const auth = await createAuthenticationState(store)
95
+ const sock = makeWASocket({ auth })
96
+ ```
198
97
 
199
- Two setups both work.
98
+ Memory storage is temporary. For persistent sessions, supply a byte-preserving
99
+ `JsStoreCallbacks` store and reuse it on restart. Do not reset or truncate an
100
+ existing device record, including its registration ID, after a failed read.
101
+ This entrypoint uses no filesystem auth or Node streams.
200
102
 
201
- - Migrating a Baileys project. Your tree already has `@hapi/boom` and
202
- `pino`, and baileyrs reuses those copies. Error identity is shared, so
203
- `instanceof` and `isBoom` checks against your own copy keep passing.
204
- Install nothing, remove nothing.
205
- - Fresh project. Install only what you touch. The defaults work with zero
206
- extra dependencies. Add `@hapi/boom` if you compare errors against
207
- another library's copy, and `pino` if you want transports and
208
- pretty-printing instead of stdout JSON.
103
+ Standalone AES-backed media retry helpers require `initWasmEngine()` before use
104
+ if no socket has initialized the engine, after `initSync()` on hosts. With a
105
+ custom runtime, pass `makeMediaCryptoRuntime(runtime)` as the final argument to
106
+ `getMediaKeys`, `encryptMediaRetryRequest` and `decryptMediaRetryData`.
209
107
 
210
- ### Preview builds
108
+ ### Optional dependencies
211
109
 
212
- Every commit on `main` and every pull request publishes an installable build
213
- through [pkg.pr.new](https://github.com/stackblitz-labs/pkg.pr.new). Nothing is
214
- published to npm — the tarball is served from a URL, so a fix can be tried
215
- before it reaches a release:
110
+ Runtime dependencies are the bridge, `long`, `events` and `fs-native-extensions`.
111
+ All peer dependencies are optional:
216
112
 
217
- ```sh
218
- # the head of a pull request, following it as new commits land
219
- npm install https://pkg.pr.new/@oxidezap/baileyrs@94
113
+ - `@hapi/boom` and `pino` replace the built-in compatible error and JSON logger implementations. Install them for shared error identity or Pino transports.
114
+ - `sharp`, `jimp`, `audio-decode`, `link-preview-js` and `music-metadata` support media processing. Without `music-metadata`, audio sends without computed duration.
220
115
 
221
- # one specific commit
222
- npm install https://pkg.pr.new/@oxidezap/baileyrs@f59ae6f
223
- ```
116
+ ### Preview builds
224
117
 
225
- Projects using the Baileys alias point it at the same URL:
118
+ [Available previews](https://pkg.pr.new/~/oxidezap/baileyrs) include installation
119
+ URLs for PRs and commits. They are unreleased code with version
120
+ `0.0.0-preview-<sha>`; pin them explicitly for testing and use npm releases in production.
226
121
 
227
- ```jsonc
228
- {
229
- "dependencies": {
230
- "@whiskeysockets/baileys": "https://pkg.pr.new/@oxidezap/baileyrs@94"
231
- }
232
- }
233
- ```
122
+ ## Migrating from upstream Baileys
234
123
 
235
- Every open pull request comments the URL for its own head, and
236
- [pkg.pr.new/~/oxidezap/baileyrs](https://pkg.pr.new/~/oxidezap/baileyrs) lists
237
- what is available.
124
+ Custom upstream `{ creds, keys }` auth states require `keys.bridgeTransaction`
125
+ with backend-wide isolation and durable atomic commits. Adapter-local upstream
126
+ transactions do not meet this contract. Compatible states are wrapped automatically;
127
+ keep persisting `creds.update` with your loader's `saveCreds`.
238
128
 
239
- Preview builds carry the version `0.0.0-preview-<sha>`, which no range written
240
- for a real release can match — an install is a deliberate pin, and it stays on
241
- that commit until you change it. They are for trying a change, not for running
242
- one: they are unreleased code, and the URL is not a substitute for a published
243
- version in anything that has to keep resolving.
129
+ For an existing upstream JSON directory, use `useLegacyMultiFileAuthState`.
130
+ `useMultiFileAuthState` uses native binary storage and does not import upstream JSON.
244
131
 
245
- ## Quick Start
132
+ Stop every old auth writer and back up the entire directory, including hidden
133
+ files and archives, before the first migration:
246
134
 
247
135
  ```ts
248
- import makeWASocket, { Boom, DisconnectReason, useMultiFileAuthState } from '@oxidezap/baileyrs'
136
+ import makeWASocket, { useLegacyMultiFileAuthState } from '@oxidezap/baileyrs'
249
137
 
250
- const { state } = await useMultiFileAuthState('auth_info')
251
-
252
- // setTimeout caps at ~2^31-1 ms (~24.8 days) and fires immediately past that,
253
- // so a long ban has to be waited out in chunks.
254
- async function waitUntil(deadlineMs: number) {
255
- for (let left = deadlineMs - Date.now(); left > 0; left = deadlineMs - Date.now()) {
256
- await new Promise(resolve => setTimeout(resolve, Math.min(left, 2_147_483_647)))
257
- }
258
- }
259
-
260
- async function connectToWhatsApp() {
261
- const sock = makeWASocket({ auth: state })
262
-
263
- sock.ev.on('connection.update', ({ connection, lastDisconnect }) => {
264
- if (connection === 'close') {
265
- // `close` means this socket is finished — same as upstream Baileys.
266
- // Transient drops never get here; the Rust engine retries those and
267
- // reports `connecting`.
268
- const statusCode = (lastDisconnect?.error as Boom)?.output?.statusCode
269
- // See the reconnect table under Gotchas: a few terminal closes
270
- // reject the replacement just as fast, so they are not worth
271
- // retrying — or not yet. `Example/example.ts` has the full policy.
272
- if (statusCode === DisconnectReason.loggedOut || statusCode === 405) {
273
- console.log('Closed for good', statusCode)
274
- } else if (statusCode === DisconnectReason.forbidden) {
275
- // Temporary ban: `expire` is unix seconds. A missing or past
276
- // expiry means the ban is over — reconnect like any other
277
- // terminal close rather than staying offline forever.
278
- const expire = (lastDisconnect?.error as Boom)?.data?.expire
279
- console.log('Temporarily banned until', expire)
280
- waitUntil(typeof expire === 'number' ? expire * 1000 : 0).then(connectToWhatsApp)
281
- } else {
282
- setTimeout(connectToWhatsApp, 5_000)
283
- }
284
- }
285
- if (connection === 'open') {
286
- console.log('Connected')
287
- }
288
- })
289
-
290
- // Register every handler in here. A replacement socket is a new emitter,
291
- // so anything attached outside stops firing after the first reconnect.
292
- sock.ev.on('messages.upsert', ({ messages }) => {
293
- for (const msg of messages) {
294
- console.log('received message', msg.key.id)
295
- }
296
- })
297
-
298
- return sock
299
- }
300
-
301
- const sock = await connectToWhatsApp()
302
- await sock.sendMessage('1234567890@s.whatsapp.net', { text: 'Hello!' })
303
- ```
304
-
305
- ## Migrating from Upstream Baileys
306
-
307
- baileyrs accepts the upstream `auth: { creds, keys }` shape directly — the
308
- internal `wrapLegacyStore` adapter runs automatically when it sees that
309
- shape, so the **`makeWASocket(...)` call site needs zero changes**:
310
-
311
- ```ts
312
- // makeWASocket() works as-is once the npm alias is in place.
313
- // Auto-wrap kicks in when it sees {creds, keys}.
138
+ const { state, saveCreds } = await useLegacyMultiFileAuthState('auth_info', { migrate: true })
314
139
  const sock = makeWASocket({ auth: state })
315
-
316
- sock.ev.on('creds.update', saveCreds) // still fires — adapter re-emits
140
+ sock.ev.on('creds.update', saveCreds)
317
141
  ```
318
142
 
319
- The one switch you do make is **how you load `state`**. baileyrs's
320
- `useMultiFileAuthState` is a *new-state-only* helper: it provisions a
321
- binary `.bin` store for the Rust engine and ignores any pre-existing
322
- upstream JSON. To carry an existing pairing across the migration, swap
323
- the import to `useLegacyMultiFileAuthState` (one line):
324
-
325
- ```diff
326
- - import makeWASocket, { useMultiFileAuthState } from '@whiskeysockets/baileys'
327
- + import makeWASocket, { useLegacyMultiFileAuthState as useMultiFileAuthState } from '@whiskeysockets/baileys'
328
-
329
- const { state, saveCreds } = await useMultiFileAuthState('auth_info')
330
- const sock = makeWASocket({ auth: state })
331
- sock.ev.on('creds.update', saveCreds)
332
- ```
143
+ The transactional snapshot becomes authoritative; retained per-key files are
144
+ backups. Existing native stores also require `{ migrate: true }` for their first
145
+ transactional-storage upgrade. Subsequent opens can omit it.
333
146
 
334
- Same approach works for any custom upstream auth (`useMySQLAuthState`,
335
- `useRedisAuthState`, mysql-baileys, etc.) — your loader keeps returning
336
- `{creds, keys, saveCreds}`, baileyrs auto-wraps it on the way in.
337
-
338
- Existing sessions migrate without re-pairing: `useLegacyMultiFileAuthState`
339
- reads the existing `creds.json` + `pre-key-*.json` / `session-*.json` files
340
- from the same folder upstream Baileys was using and hands them to the Rust
341
- engine. Pair-ID, identity, signed pre-keys, and Signal sessions are all
342
- preserved. No QR re-scan, no logged-out events.
343
-
344
- > **Where the new state goes**: baileyrs continues to write the legacy
345
- > JSON files (via `saveCreds`) so the folder stays compatible with both
346
- > sides during a rollback window. The Rust engine treats the JSON as the
347
- > source of truth as long as you keep using `useLegacyMultiFileAuthState`.
348
- > One edge case: a Signal session imported while it still had pending
349
- > out-of-order message gaps becomes native-only on its first write-back —
350
- > after a rollback, that one session re-establishes itself through a fresh
351
- > Signal handshake (automatic; no re-pairing, other sessions unaffected).
352
- > If you later want to drop the JSON layer, switch to
353
- > `useMultiFileAuthState` — but that path requires a fresh QR.
354
-
355
- ### Gotchas
356
-
357
- A few behaviors that differ from upstream — almost always to your advantage:
358
-
359
- - **History contacts stay on `messaging-history.set`.** During HistorySync,
360
- read the `contacts` array from that event to hydrate a contact store. baileyrs
361
- does not re-emit those snapshot entries through `contacts.upsert`, including
362
- push-name-only syncs. Semantic updates such as `contacts.update` still emit
363
- normally for inbound push names and contact changes.
364
-
365
- - **`shouldSyncHistoryMessage` is supported, on a partial notification view.**
366
- The policy runs before the engine downloads or parses history content and
367
- receives a decoded `HistorySyncNotification` carrying only that pre-download
368
- metadata: `syncType`, `chunkOrder`, `progress`, `fileLength` (as `Long`) and
369
- `peerDataRequestSessionId`. Media and key fields stay absent rather than
370
- synthesized, and sync types outside the upstream processable set are rejected
371
- after the callback runs. Returning `false` permanently acknowledges the
372
- chunk — no retry — so it is not a transient load-shedding hook. Requesting
373
- full history (`syncFullHistory`) stays engine-owned, and unlike upstream the
374
- policy is not re-invoked to gate the initial-sync state machine: admission
375
- covers received notifications only.
376
-
377
- - **An undecryptable message tells you what it was.** The CIPHERTEXT stub
378
- emitted on `messages.upsert` for a message that failed to decrypt carries
379
- `stanzaType`: the envelope's `type` attribute as the server stamped it on the
380
- sending stanza — `"text"`, `"media"`, `"pay"`, `"poll"`, `"reaction"`,
381
- `"event"`. It describes the stanza rather than the ciphertext, so it survives
382
- the failure, and it is stamped on the sender's own outgoing stanza, so it
383
- cannot be pointed at anyone else. Upstream has no equivalent: there the
384
- placeholder is unclassifiable. `messageStubParameters` is untouched and still
385
- holds only the unavailability reason, when the server named one — the two are
386
- independently optional, which is exactly what a positional array cannot
387
- express.
388
-
389
- - **Auto-reconnect is built in, but `close` still means `close`.** The Rust
390
- engine retries transient drops on a fibonacci backoff and reports them as
391
- `connection: 'connecting'`, so the canonical upstream handler never fires
392
- for those and you never end up with two sockets on one account. A
393
- `connection: 'close'` is only emitted once the engine has given up — a
394
- replaced session, an outdated build, a temporary ban, an unrecoverable
395
- `<failure>` — and by then the socket has already released its resources.
396
- Ignoring it leaves the bot permanently offline, so handle it the upstream
397
- way and build a replacement — with three exceptions, because some of those
398
- failures reject the replacement just as fast:
399
-
400
- | `statusCode` | what to do |
401
- | --- | --- |
402
- | `DisconnectReason.loggedOut` (401) | stop; needs a fresh pairing |
403
- | `405` | stop; the server rejected this build, and the next one too |
404
- | `DisconnectReason.forbidden` (403) | wait until `lastDisconnect.error.data.expire` (unix seconds) — it is a temporary ban |
405
- | `500` (startup failure) | inspect `lastDisconnect.error.cause` before retrying; persistent storage/setup errors will repeat |
406
- | anything else | reconnect, after a short delay |
407
-
408
- `Example/example.ts` implements exactly this.
409
- - **`connecting` is not a short state here.** The engine's backoff grows with
410
- each consecutive failure, so a single `connecting` can stand for minutes of
411
- downtime with nothing else emitted in between. See
412
- [When `connecting` lasts minutes](#when-connecting-lasts-minutes): a
413
- readiness timeout written for upstream's `connecting` misreads this one.
414
- - **No `getMessage` / `cachedGroupMetadata` polyfill required.** The Rust
415
- side caches group metadata and message keys natively, and nothing here calls
416
- either hook: a `cachedGroupMetadata` carried over from upstream never runs,
417
- and neither does a `getMessage`. Passing them is harmless — the whole
418
- `SocketConfig` shape is accepted so a migration needs no edits — but they are
419
- not overrides, so delete them rather than maintain them. Every socket warns once
420
- at construction naming any option in that group it received; that list is the
421
- authority — the type system requires each `SocketConfig` member to be
422
- classified, so it cannot fall behind — and it also covers `keepAliveIntervalMs`,
423
- `markOnlineOnConnect`, `maxMsgRetryCount`, `msgRetryCounterCache`,
424
- `retryRequestDelayMs`, `fireInitQueries`, `syncFullHistory`,
425
- `generateHighQualityLinkPreview`,
426
- `linkPreviewImageThumbnailWidth`, `enableAutoSessionRecreation`,
427
- `enableRecentMessageCache`, `appStateMacVerification`,
428
- `patchMessageBeforeSending`, `customUploadHosts`, `countryCode`,
429
- `connectTimeoutMs`, `qrTimeout`, `printQRInTerminal`, `ignoreOfflineMessages`,
430
- `downloadHistory`, `agent`, `fetchAgent`, `mobile`, `mediaCache`,
431
- `userDevicesCache`, `callOfferCache` and `placeholderResendCache`.
432
- - **A sender's resend reaches you once, not once per delivery.** When a
433
- sender's network is bad, their client re-runs its own outbox and sends the
434
- same message again — same `key.id`, re-encrypted. Upstream Baileys emits a
435
- `messages.upsert` for each of those deliveries, so an auto-reply bot answers
436
- the same message two or three times; the engine now recognises the repeat and
437
- emits one. It is a short-lived, in-memory window (five minutes), so the one
438
- case still open is a sender whose retry spans a restart of your process. If
439
- your handler has side effects, keying them on the whole `key` — `remoteJid`,
440
- `id`, `fromMe` and `participant` — remains the thing that makes it safe. Not
441
- on `id` alone: the id is the sending client's to choose, so two participants
442
- of one group can pick the same one, and a handler that keys on it would drop
443
- the second person's message rather than a duplicate. That is why the engine's
444
- own check carries the sender too.
445
- - **`Boom` works with or without `@hapi/boom`.** baileyrs exports a
446
- `@hapi/boom`-compatible `Boom`, so the existing
447
- `(err as Boom).output.statusCode` pattern works unchanged. The package is
448
- an optional peer. With it installed your copy backs the export, without
449
- it a built-in implementation with the same shape does. See
450
- [What gets installed](#what-gets-installed).
451
- - **Audio duration needs the optional `music-metadata` peer.** Upstream
452
- Baileys bundles it as a hard dependency; here it is optional like the
453
- other media peers (`sharp`, `jimp`, `audio-decode`, `link-preview-js`).
454
- Without it, audio messages still send — they just carry no `seconds`
455
- value. Install `music-metadata` if you want durations computed.
456
- - **Your key store also holds bridge state, so "empty" is not "unpaired".**
457
- See [Bridge state in your key store](#bridge-state-in-your-key-store) — this
458
- one can break a boot path, so it has its own section.
459
-
460
- ### When `connecting` lasts minutes
461
-
462
- Socket startup emits `connecting` before awaiting credential hydration. If
463
- hydration, bridge construction, or client setup rejects, it emits one terminal
464
- `close` after cleanup with `statusCode` 500. `lastDisconnect.error` preserves
465
- the initialization failure in `cause`; pending socket methods reject with that
466
- same error. Check the cause before replacing a socket, since a storage error can
467
- persist across restarts. An explicit `sock.end()` during startup remains a silent shutdown.
468
-
469
- Upstream Baileys emits `connecting` once per socket, and it resolves to `open`
470
- or `close` within seconds, because upstream never retries on its own. On
471
- baileyrs the same value also covers every drop the engine is retrying, and the
472
- backoff between those retries climbs with each consecutive failure.
473
-
474
- Here is what that costs on a rate-limited account. Four consecutive
475
- `429 rate-overlimit`, measured against the production reconnect path:
476
-
477
- | failure | next attempt in | offline so far |
478
- | --- | --- | --- |
479
- | `429` #1 | 8.4s | 8.4s |
480
- | `429` #2 | 146.2s | 154.6s |
481
- | `429` #3 | 813.9s | 968.5s |
482
- | `429` #4 | 903.5s | 1872.0s |
483
-
484
- About 16 minutes offline once the third retry delay has run, and about 31 once
485
- the fourth has. For all of it the consumer sees exactly **one**
486
- `connection: 'connecting'`: no `lastDisconnect`, no status code, no repeat.
487
- `isConnected` and `isLoggedIn` are both `false` throughout, exactly as they are
488
- during a first connection, so neither tells you a retry is scheduled.
489
-
490
- **Do not arm a readiness timeout on `connecting`, and above all do not restart
491
- the process when one expires.** The backoff counter lives in the Rust client
492
- that your socket owns, so it dies with the process. The next boot starts a new
493
- attempt immediately, replays the whole startup burst against a server that just
494
- asked for less traffic, and earns the next `429` sooner. Restarting is the
495
- single worst answer to a rate limit, and an upstream-shaped readiness timeout
496
- leads straight to it.
497
-
498
- What to do instead:
499
-
500
- - Treat `open` and `close` as the only decision points. `connecting` carries no
501
- failure to react to, and it is never a reason to build a second socket. Only
502
- `close` is.
503
- - Read `connecting` in context: after an `open` it means the engine is retrying
504
- a drop it owns and will keep retrying; with no `open` before it, it is a first
505
- connection still being established. Neither one is stuck.
506
- - If you need a liveness watchdog anyway, budget it well past the ladder above,
507
- tens of minutes rather than seconds, and have it alert a human instead of
508
- killing the process. A shorter one fires on a backoff that was about to
509
- succeed.
510
- - Know what your own calls do meanwhile. A call issued while the engine is
511
- reconnecting no longer fails fast: it parks and goes out when the connection
512
- lands, which on the ladder above can be tens of minutes. That is the point,
513
- since the alternative was an error indistinguishable from a finished session,
514
- but it means a call you issue during `connecting` is a call you are committing
515
- to. Racing it against your own deadline bounds your waiting and not the work:
516
- the call still goes out when the reconnect lands, so a retry after the
517
- deadline sends it twice unless you pinned `messageId`.
518
- - Fix the cause on your side: send less. The engine restores the connection,
519
- but it does not pace your traffic, and the traffic is what earned the `429`.
520
- Queueing, throttling and deferral are yours to decide, the same as upstream.
147
+ Before reverting storage formats, stop all writers, back up the directory and
148
+ successfully run `prepareLegacyAuthRollback(folder, { offline: true })` for JSON
149
+ or `prepareNativeAuthRollback(folder, { offline: true })` for native storage.
150
+ Do not reopen stale files after a rejected export. Sessions imported with pending
151
+ out-of-order gaps can become native-only and need a new Signal handshake after
152
+ rollback. Engines older than 0.2.8 cannot read newer seed-only skipped-key records;
153
+ do not delete native-only session rows to force a downgrade.
521
154
 
522
- ### Bridge state in your key store
155
+ ### Connection lifecycle
523
156
 
524
- Upstream Baileys keeps engine state in `creds` (persisted by `saveCreds`) and
525
- puts only Signal key material in `keys`. baileyrs uses that same `keys` store
526
- as the persistence channel for the Rust core's own state as well: its device
527
- record, and the byte-level records the Signal namespaces are projected from.
528
- Those live under namespaces reserved with the **`bridge-` prefix**:
157
+ Transient drops are retried by Rust and report `connecting`. A terminal `close`
158
+ is emitted once after resource cleanup; create a replacement socket only then
159
+ and register its handlers again.
529
160
 
530
- | namespace | what it holds |
161
+ | Terminal status | Action |
531
162
  | --- | --- |
532
- | `bridge-native-*` | the core's own encoding of a namespace that also has a Baileys projection (`bridge-native-session`, `bridge-native-prekey`, `bridge-native-device`, …) |
533
- | `bridge-*` | core records with no Baileys equivalent (`bridge-signed-prekey`, `bridge-sent-message`, `bridge-msg-secret`, `bridge-meta`, …) |
534
-
535
- No upstream Baileys namespace starts with `bridge-`, and none of your data is
536
- stored under one. Which of them you actually see depends on what the engine
537
- touches; `bridge-native-device` shows up first, because the core reads its
538
- device record while the socket is still `connecting` — **before any QR, before
539
- any pairing**.
540
-
541
- That last point is the one that bites. A store that counted rows to decide
542
- whether this was a first run reports a session that does not exist:
543
-
544
- ```js
545
- // WRONG on baileyrs: bridge-native-device is already in the table before pairing,
546
- // so this never reports empty again — the bot skips its pairing flow and hangs.
547
- const isEmpty = () => !creds.registered && !creds.me?.id && countKeys() === 0
548
-
549
- // Right, on baileyrs and upstream alike: creds are the pairing record.
550
- const isEmpty = () => !creds.registered && !creds.me?.id
551
- ```
163
+ | `DisconnectReason.loggedOut` / 401 | Stop and pair again. |
164
+ | 405 | Stop and update the rejected build. |
165
+ | `DisconnectReason.forbidden` / 403 | Respect `lastDisconnect.error.data.expire`, in Unix seconds. |
166
+ | 500 during startup | Inspect `lastDisconnect.error.cause` for storage or setup errors before retrying. |
167
+ | Other | Reconnect after a delay. |
168
+
169
+ `connecting` can last tens of minutes during rate-limit backoff. Do not use it to
170
+ start another socket or restart the process. Alert rather than kill on a liveness
171
+ timeout. Calls made during reconnect wait for the connection; racing a call
172
+ against a deadline does not cancel it. Retrying sends can duplicate messages
173
+ unless you retain the same `messageId`. Application traffic pacing is your responsibility.
174
+
175
+ ### Compatibility notes
176
+
177
+ - History contacts arrive through `messaging-history.set`, not `contacts.upsert`.
178
+ - `shouldSyncHistoryMessage` receives pre-download metadata only: `syncType`, `chunkOrder`, `progress`, `fileLength` as `Long`, and `peerDataRequestSessionId`. Returning `false` permanently acknowledges the chunk. It does not gate the initial-sync state machine.
179
+ - Engine-owned options such as `getMessage` and `cachedGroupMetadata` are accepted but do not override engine behavior. Socket construction warns about ignored options; see the [option catalog](src/Socket/unsupported-config.ts).
180
+ - Undecryptable-message stubs may carry `stanzaType` independently of `messageStubParameters`.
181
+ - Duplicate delivery suppression is temporary and in memory. For durable side effects, deduplicate with the full key: `remoteJid`, `id`, `fromMe` and `participant`.
182
+ - The `proto` facade uses Baileys field names and translates bridge aliases in both directions without mutating inputs. See [compatibility rules](src/Compatibility/README.md).
183
+ - Group and community listings fetch full metadata per entry and reject on failed fetches before emitting `groups.update`.
184
+ - `reachoutTimeLock` reports server state without imposing send policy. Unknown enforcement names are preserved; an absent `isActive` is unknown.
185
+ - Newsletter `mute_state` controls channel-update notifications, independently of follower-activity notifications. History may omit `messageId`; `serverId` and large counters are strings. Packed live events do not carry the newsletter server ID.
186
+ - Community creation can succeed before configuration fails. Preserve `createdJid`, `step`, `kind` and `cause` from the error and resume configuration on that JID.
187
+ - Status privacy emits `settings.update`; unarchive settings emit `creds.update`. Historical calls, favorite chats and sticker-list updates have no matching event in the targeted Baileys API.
552
188
 
553
- **A non-empty key store is not evidence of a session.** `creds.registered` and
554
- `creds.me?.id` are, and they are the only thing to check.
189
+ ### Bridge state in your key store
555
190
 
556
- When you need to present a store the way upstream would — counting rows,
557
- listing the Signal namespaces, exporting an upstream-shaped dump — filter the
558
- bridge rows out with the exported classifier rather than matching the prefix
559
- yourself. It is derived from the internal routing catalog, so a namespace added
560
- in a later release is covered without you changing anything:
191
+ Wrapped upstream stores also contain `bridge-` engine records, including records
192
+ created before pairing. Determine pairing from `creds.registered` and `creds.me?.id`,
193
+ not the number of stored keys.
561
194
 
562
- ```ts
563
- // Aliased install? Import from '@whiskeysockets/baileys' instead; it resolves here.
564
- import { BRIDGE_INTERNAL_KEY_TYPES, isBridgeInternalKeyType } from '@oxidezap/baileyrs'
195
+ Use `isBridgeInternalKeyType` or `BRIDGE_INTERNAL_KEY_TYPES` for upstream-shaped
196
+ views. Full backups and moves between baileyrs stores must retain every `bridge-`
197
+ row, including native-only sessions and records without a Baileys projection.
198
+ This filtering concern does not apply to `useMultiFileAuthState`, whose `keys`
199
+ is already a projection over native storage.
565
200
 
566
- isBridgeInternalKeyType('bridge-native-device') // true
567
- isBridgeInternalKeyType('pre-key') // false
201
+ ## Development
568
202
 
569
- // Every bridge-internal namespace, e.g. for a SQL `NOT IN (...)` clause. The
570
- // store also holds the Baileys namespaces the engine projects into it.
571
- BRIDGE_INTERNAL_KEY_TYPES
572
- ```
203
+ See [AGENTS.md](AGENTS.md) for build, test, E2E and contribution instructions, and
204
+ the [fuzzing guide](src/__fuzz__/README.md) for differential testing. The strict
205
+ declaration audit has known gaps and is not currently a green gate.
573
206
 
574
- > **Do not drop these rows from a backup or a store-to-store move.** They are
575
- > effective state, not metadata. `bridge-signed-prekey`, `bridge-sender-key-devices`,
576
- > `bridge-base-key`, `bridge-sent-message`, `bridge-msg-secret`,
577
- > `bridge-mutation-mac` and `bridge-meta` have no Baileys projection at all, and
578
- > a Signal session that turned native-only lives under `bridge-native-session`
579
- > alone. Restoring only the non-bridge rows rolls those sessions back or loses
580
- > the state outright. Filter the bridge rows only where the destination is an
581
- > upstream-shaped view that cannot represent them; a full backup, or a move
582
- > between two baileyrs stores, carries every `bridge-` row across.
583
-
584
- This applies to stores you own — the upstream `{ creds, keys }` shape that
585
- baileyrs auto-wraps, including `useLegacyMultiFileAuthState`. It does not apply
586
- to `useMultiFileAuthState`, whose `keys` is a projection over the engine's own
587
- store; the `bridge-` namespaces never surface through it.
588
-
589
- The move back down is not symmetric either. From 0.2.8 on, the core buffers a
590
- skipped-message key as its seed alone, where an earlier release wrote the
591
- derived cipher/mac/iv triple beside it. Forward is fine — a record written
592
- before this carries both, and the newer engine reads it unchanged. Backward is
593
- not: an older engine cannot parse a record whose skipped keys carry no triple,
594
- and it fails on **the whole record**, not on the one key.
595
-
596
- Where that bites depends on which bytes the engine is handed, and a wrapped
597
- store is not automatically on the safe side of it. It holds the Baileys
598
- projection, which has only ever held seeds — but it also mirrors the core's
599
- exact bytes under `bridge-native-session`, and a read prefers that mirror for as
600
- long as its fingerprint still matches the projection. A downgrade can therefore
601
- be handed the newer record with a perfectly readable projection sitting right
602
- beside it.
603
-
604
- Dropping a mirror row makes the next read rebuild it from the projection, which
605
- is the format both versions agree on — but only for a session that has one. A
606
- session that turned native-only lives in that row alone, so dropping *that* one
607
- loses the session outright, which is the case the warning above is about. A
608
- session with no skipped keys buffered at the time is unaffected either way: the
609
- difference only exists while a chain is holding keys for messages that arrived
610
- out of order.
207
+ Micro-benchmarks for hot paths (JID helpers, proto codec, message content helpers,
208
+ bridge event adaptation, BufferJSON) live in [bench](bench) and run with
209
+ `npm run bench`. CI tracks them with [CodSpeed](https://app.codspeed.io/oxidezap/baileyrs).
611
210
 
612
211
  ## Disclaimer
613
212
 
@@ -622,3 +221,10 @@ violations of WhatsApp's Terms of Service that may result from the use of this s
622
221
  ## License
623
222
 
624
223
  MIT — see [LICENSE](LICENSE).
224
+
225
+ ## Performance benchmarks
226
+
227
+ CodSpeed tracks CPU simulation and memory using Vitest, with local codec/store
228
+ benchmarks and real socket workloads against the private Bartender mock. See the
229
+ [benchmark guide](benchmarks/README.md) for scenarios, warmup, commands and memory
230
+ interpretation.