@ping-app/ping-openmls-sdk 0.0.0-stage → 0.10.0

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 (39) hide show
  1. package/README.md +94 -2
  2. package/dist/index.cjs +2782 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +1229 -0
  5. package/dist/index.d.ts +1229 -0
  6. package/dist/index.js +2715 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/notification-preview.cjs +137 -0
  9. package/dist/notification-preview.cjs.map +1 -0
  10. package/dist/notification-preview.d.cts +85 -0
  11. package/dist/notification-preview.d.ts +85 -0
  12. package/dist/notification-preview.js +98 -0
  13. package/dist/notification-preview.js.map +1 -0
  14. package/dist/storage/indexeddb.cjs +153 -0
  15. package/dist/storage/indexeddb.cjs.map +1 -0
  16. package/dist/storage/indexeddb.d.cts +21 -0
  17. package/dist/storage/indexeddb.d.ts +21 -0
  18. package/dist/storage/indexeddb.js +128 -0
  19. package/dist/storage/indexeddb.js.map +1 -0
  20. package/dist/transport/websocket.cjs +121 -0
  21. package/dist/transport/websocket.cjs.map +1 -0
  22. package/dist/transport/websocket.d.cts +23 -0
  23. package/dist/transport/websocket.d.ts +23 -0
  24. package/dist/transport/websocket.js +94 -0
  25. package/dist/transport/websocket.js.map +1 -0
  26. package/dist/types-B1GFwNXa.d.cts +535 -0
  27. package/dist/types-B1GFwNXa.d.ts +535 -0
  28. package/dist/worker.cjs +841 -0
  29. package/dist/worker.cjs.map +1 -0
  30. package/dist/worker.d.cts +2 -0
  31. package/dist/worker.d.ts +2 -0
  32. package/dist/worker.js +848 -0
  33. package/dist/worker.js.map +1 -0
  34. package/package.json +61 -4
  35. package/wasm/package.json +17 -0
  36. package/wasm/ping_wasm.d.ts +909 -0
  37. package/wasm/ping_wasm.js +3028 -0
  38. package/wasm/ping_wasm_bg.wasm +0 -0
  39. package/wasm/ping_wasm_bg.wasm.d.ts +112 -0
@@ -0,0 +1,1229 @@
1
+ import { M as MessageEnvelope, S as Storage, T as Transport, E as ExpectedOwner, C as ConversationId, K as KeyPackageEntry, A as AddMembersReport, a as DeviceId, U as UserId, b as ConversationMeta, L as LinkingTicket, c as DeviceReauthProof, d as DeviceLinkApproval, e as DeviceLinkPossession, I as IdentityRotation, f as CommitInDoubt, g as MemberInfo, h as ConversationPolicy, i as IncomingMessage, j as SequencedEnvelope, k as ApplyBatchResult, l as SyncStepResult, m as LogPosition, n as LogHead, P as PendingApply, o as CatchupAppEvent, p as CatchupSnapshotView, R as RecoveryBackup, H as HistoryBundle, q as AdmitChatEntry, r as AdmitChatOutcome, s as DeviceRemovalReport, t as MessageBatchMeta } from './types-B1GFwNXa.cjs';
2
+ export { u as AddMemberStatus, v as AddMemberVerdict, B as BufferOverflow, w as Bytes, x as CatchupSnapshotEntry, y as ConversationRemoval, z as ConversationUpdate, F as DeviceInfo, G as DeviceRemovalFailure, D as DiscoveredDevice, J as HistoryAppEvent, N as Hlc, O as IdentityRotationFailure, Q as LogGap, V as MessageKind, W as OverflowReason, X as SenderRole, Y as StrandReason, Z as StrandedConversation, _ as WelcomeFailure, $ as WelcomeFailureReason } from './types-B1GFwNXa.cjs';
3
+ export { IndexedDbStorage } from './storage/indexeddb.cjs';
4
+ export { WebSocketTransport } from './transport/websocket.cjs';
5
+ export { NotificationPreviewOptions, NotificationPreviewSession, openNotificationPreview } from './notification-preview.cjs';
6
+
7
+ /**
8
+ * Ping wire contract version. Bumped on incompatible profile changes.
9
+ *
10
+ * Currently `2` — CR-6 changes the `content_hash` semantics for `Application` envelopes
11
+ * (now hashed over plaintext, not the MLS ciphertext). Receivers run a 90-day dual-accept
12
+ * window per Q-ARCH-02; see [[validate]] for the per-version routing.
13
+ */
14
+ declare const PING_WIRE_CONTRACT_VERSION = 2;
15
+ /** Lowest envelope version accepted by [[validate]] during the dual-accept window. */
16
+ declare const WIRE_VERSION_MIN_ACCEPTED = 1;
17
+ /** Canonical CBOR content type. Production transports SHOULD use this. */
18
+ declare const CONTENT_TYPE_CBOR = "application/vnd.ping.wire.v2+cbor";
19
+ /** JSON projection — development and tooling only. Production MUST NOT use this. */
20
+ declare const CONTENT_TYPE_JSON = "application/vnd.ping.wire.v2+json";
21
+ /** Legacy v1 CBOR type, accepted during the CR-6 dual-accept window. */
22
+ declare const CONTENT_TYPE_CBOR_LEGACY_V1 = "application/vnd.ping.wire.v1+cbor";
23
+ /** Legacy v1 JSON type, accepted during the CR-6 dual-accept window. */
24
+ declare const CONTENT_TYPE_JSON_LEGACY_V1 = "application/vnd.ping.wire.v1+json";
25
+ /** Header used over transports that don't surface a content type (e.g. WebSocket). */
26
+ declare const PING_WIRE_CONTRACT_HEADER = "X-Ping-Wire-Contract";
27
+ /** Header value: `ping/<VERSION>`. */
28
+ declare const PING_WIRE_CONTRACT_HEADER_VALUE = "ping/2";
29
+ type ValidationErrorKind = "UnsupportedVersion" | "BadConversationIdLen" | "BadSenderDeviceLen" | "ContentHashMismatch";
30
+ declare class ValidationError extends Error {
31
+ readonly kind: ValidationErrorKind;
32
+ constructor(kind: ValidationErrorKind, message: string);
33
+ }
34
+ /**
35
+ * Validate an envelope against the ping-wire-contract.
36
+ *
37
+ * Receivers claiming contract conformance MUST call this before applying any envelope.
38
+ * External consumers using the raw envelope under their own profile are not bound by
39
+ * these rules.
40
+ *
41
+ * CR-6 dual-accept window: `v ∈ [WIRE_VERSION_MIN_ACCEPTED, PING_WIRE_CONTRACT_VERSION]`
42
+ * passes the version gate. For v=2 `Application` envelopes the content_hash is over
43
+ * plaintext, so this function skips that check — callers MUST run
44
+ * [[verifyApplicationContentHash]] after MLS decrypt to close the loop.
45
+ */
46
+ declare function validate(env: MessageEnvelope): Promise<void>;
47
+ /**
48
+ * Verify a v=2 `Application` envelope's content_hash against the decrypted plaintext.
49
+ *
50
+ * Caller MUST run this after MLS decrypt for application envelopes whose `v >= 2`. For
51
+ * v=1 envelopes or handshake kinds this is a no-op (those are covered by [[validate]]).
52
+ */
53
+ declare function verifyApplicationContentHash(env: MessageEnvelope, plaintext: Uint8Array): Promise<void>;
54
+ /**
55
+ * True if the supplied content type negotiates the ping-wire-contract.
56
+ *
57
+ * Accepts the v2 canonical types AND the v1 legacy types during the CR-6 dual-accept
58
+ * window. Tolerates whitespace and parameters (e.g. `; charset=utf-8`).
59
+ */
60
+ declare function negotiates(contentType: string | null | undefined): boolean;
61
+
62
+ interface ClientConfig {
63
+ identityExport: Uint8Array;
64
+ deviceLabel: string;
65
+ storage: Storage;
66
+ transport: Transport;
67
+ /** Override the wall clock (test/sim only). */
68
+ now?: () => number;
69
+ /**
70
+ * Optional 32-byte Ed25519 secret key. When supplied AND no
71
+ * `LocalDevice` is yet persisted in `storage`, the SDK adopts this
72
+ * as its device signing key — so `deviceId()` returns
73
+ * `SHA-256(public_key_of(secret))`, deterministic from what the
74
+ * caller passed.
75
+ *
76
+ * Use case: align the SDK's `device_id` (which the SDK stamps into
77
+ * every envelope's `sender_device` field) with an externally-
78
+ * computed device id — typically `SHA-256(device_signing_pubkey)`
79
+ * in the host's auth layer, where the JWT carries that same value
80
+ * as its `device_id` claim. Without this alignment, a server that
81
+ * validates `envelope.sender_device == jwt.device_id` rejects every
82
+ * upload with `sender_device_mismatch`.
83
+ *
84
+ * Ignored on subsequent inits (when `storage` already holds a
85
+ * persisted `LocalDevice`) — the on-disk identity is authoritative
86
+ * for stability across restarts.
87
+ */
88
+ deviceSigningSecretKey?: Uint8Array;
89
+ /**
90
+ * Optional per-account storage scope. When set, the SDK prefixes EVERY
91
+ * storage namespace it reads/writes with `${accountNamespace}\0`, so
92
+ * multiple accounts that share one `Storage` backend can never read or
93
+ * overwrite each other's MLS group state, device identity, or key
94
+ * material. Hosts that already give each account its own physical store
95
+ * (e.g. a per-account IndexedDB database) can still set this as
96
+ * defense-in-depth — the prefix is stable across restarts and MUST be
97
+ * the same value every init for a given account or its data becomes
98
+ * unreachable. Use a stable, opaque per-account id (e.g. the account id
99
+ * hex); never a display name.
100
+ */
101
+ accountNamespace?: string;
102
+ /**
103
+ * The owner each conversation's FIRST roles write must name (2026-11-04,
104
+ * round 2): the server's recorded creator, as an MLS user id (map the
105
+ * account id through the roster). Consulted only when a group without
106
+ * roles gains them; a first roles write naming another owner strands as
107
+ * `"notPermitted"`. A conversation with no entry accepts the first write
108
+ * from any member. Refresh later with `setExpectedOwners`.
109
+ */
110
+ expectedOwners?: ExpectedOwner[];
111
+ }
112
+ interface Conversation {
113
+ readonly id: ConversationId;
114
+ send(plaintext: Uint8Array): Promise<MessageEnvelope>;
115
+ /** [CR-2] Add members by (device_id, KeyPackage) pair. Hosts typically pull these
116
+ * straight from `transport.discoverDevices(userId)`. All or nothing: one
117
+ * unusable entry fails the whole add (see `addMembersWithVerdicts`). */
118
+ addMembers(entries: KeyPackageEntry[]): Promise<void>;
119
+ /** Add members with one verdict per entry: every entry is screened on its
120
+ * own (KeyPackage verification, lifetime included; capabilities; an
121
+ * existing leaf; a repeat), the usable ones go into ONE Commit sent with
122
+ * its Welcome as one batch, and the rest are reported instead of failing
123
+ * the Commit for every other invitee. A device that already has a leaf is
124
+ * reported (`alreadyMember`, with its leaf), never evicted. */
125
+ addMembersWithVerdicts(entries: KeyPackageEntry[]): Promise<AddMembersReport>;
126
+ /** Re-admit a device that kept its signature key: ONE Commit that removes
127
+ * the leaf holding the KeyPackage's own key (the device's stale leaf: a
128
+ * stranded device, a restore over the same store) and adds its fresh
129
+ * KeyPackage. A re-admission never brings in an account and never makes an
130
+ * account's leaf count grow: with no leaf of that key it rejects
131
+ * "not permitted: ..." (`isNotPermittedError`) in EVERY conversation,
132
+ * before anything is sent. A device that came back with a NEW key is added
133
+ * (`addMembers`) by a device of its own account, the owner or an admin.
134
+ * In a conversation with roles the committer is a device of the same
135
+ * account as the device it re-admits, the owner, or an admin (never an
136
+ * admin for a device of the owner); anybody else is rejected the same way
137
+ * (2026-11-18: the `replace` argument is gone, and a plain member no
138
+ * longer re-admits another account's device). Ask the client's
139
+ * `mayReadmit` BEFORE claiming the device's KeyPackage.
140
+ * Resolves to the device id of the leaf the Commit replaced (the device
141
+ * that kept its key). `null`: no leaf was replaced. */
142
+ reAdmitDevice(entry: KeyPackageEntry): Promise<DeviceId | null>;
143
+ removeMembers(leafIndexes: number[]): Promise<void>;
144
+ /** Remove every OTHER leaf of this account from this conversation (step 2
145
+ * of an account's leave, before leaving): one Commit removing every leaf
146
+ * whose credential verifies for this client's own identity, except this
147
+ * device's. Resolves to how many leaves it removed; 0 sends nothing. The
148
+ * leaves are read from the tree on every call. Any role may call it. */
149
+ removeOwnOtherLeaves(): Promise<number>;
150
+ /** Remove an account from this conversation by identity: one Commit
151
+ * removing every leaf whose credential verifies for one of `identities`
152
+ * (MLS user ids, 32 bytes each: the account's current identity and any
153
+ * older ones the host names). Resolves to how many leaves ITS OWN
154
+ * Removes took (a leaf whose leave was already pending goes with the same
155
+ * Commit and is not counted): read the roster for the outcome, never the
156
+ * count. Read from the tree on every call, so a retry removes
157
+ * what the tree holds then. In a group with roles it is the owner's or an
158
+ * admin's call (rejects "not permitted: ..." otherwise) and it never
159
+ * removes the owner's leaves. */
160
+ removeMembersByIdentity(identities: UserId[]): Promise<number>;
161
+ /** Record the group's roles in its policy (2026-11-04, round 2): `owner` and
162
+ * `admins` as MLS user ids. One GroupContextExtensions Commit, no Welcome.
163
+ * Rejects with "not permitted ..." before anything is sent when this
164
+ * device's role does not allow the change (the first roles write is any
165
+ * member's unless an expected owner says otherwise; then the owner hands
166
+ * over, the owner or an admin changes the admins), when a member's app is
167
+ * too old for roles (`conversationPolicy().incapableMembers`), or in the
168
+ * DeviceGroup. Admins keep promotion order; the owner is never listed. */
169
+ setConversationRoles(owner: UserId, admins: UserId[]): Promise<void>;
170
+ /** Change the conversation `name` (carried in the GroupContext) via an MLS
171
+ * GroupContextExtensions commit — the rename / embedded avatar-media-id change
172
+ * propagates to every member and future joiner through group STATE, not a side
173
+ * broadcast. Pass `null` to clear. All members must have re-linked since the
174
+ * group-name capability shipped, else the SDK throws. */
175
+ setConversationName(name: string | null): Promise<void>;
176
+ /**
177
+ * The conversation's MLS GroupContext name as the group holds it now, or
178
+ * `undefined` when the group has none or the client holds no metadata for
179
+ * the conversation (it is not held, or nothing has reported it yet: read it
180
+ * with `readConversationMeta(id)`).
181
+ *
182
+ * Never the name from before a change. The client's copy of a conversation's
183
+ * metadata is replaced before any `onConversationUpdated` listener is told
184
+ * the conversation changed, and before this device's own call that changed
185
+ * it resolves (see `MessagingClient.readConversationMeta`).
186
+ *
187
+ * This accessor was MISSING, and hosts reasonably assumed it existed:
188
+ * `getConversation(id).name` read `undefined` on every call, so any host logic
189
+ * driven by group state — titles, rosters, avatars and roles carried in the
190
+ * GroupContext — saw nothing. A group then materialised unnamed until a
191
+ * best-effort broadcast happened to arrive, and never converged from group
192
+ * state at all. Prefer `meta()` when you need the full record; this is the
193
+ * one-field convenience that hosts were already reaching for.
194
+ */
195
+ readonly name?: string | undefined;
196
+ /** The conversation's current MLS epoch, or `undefined` when the client
197
+ * holds no metadata for the conversation. Never an epoch from before a
198
+ * change the host was already told about. */
199
+ readonly epoch?: number | undefined;
200
+ /** The whole record, as fresh as `name`. Throws when the client holds no
201
+ * metadata for the conversation: `readConversationMeta(id)` answers `null`
202
+ * instead, and tells "not held" from "not read yet". */
203
+ meta(): ConversationMeta;
204
+ }
205
+ declare class MessagingClient {
206
+ private worker;
207
+ private nextId;
208
+ private pending;
209
+ private storage;
210
+ private transport;
211
+ private now;
212
+ /** `onMessage` / `onMessageBatch` handlers and the guarded delivery to them. */
213
+ private readonly fanout;
214
+ private conversationHandlers;
215
+ private subscription;
216
+ /**
217
+ * This client's copy of each conversation's metadata, keyed by lowercase-hex
218
+ * conversation id: what a conversation handle's `name`, `epoch` and `meta()`
219
+ * answer from.
220
+ *
221
+ * It is never older than what the host has been told. The worker attaches a
222
+ * conversation's metadata to every change it reports, and {@link handleWorker}
223
+ * stores it before it calls a listener or settles a call; an entry whose
224
+ * conversation changed with no metadata attached is dropped, never kept.
225
+ * Bounded by the conversations the client holds: an entry goes when its
226
+ * conversation is left, dropped or removed, and `listConversations()`
227
+ * replaces the whole map.
228
+ */
229
+ private metaCache;
230
+ /**
231
+ * Per-conversation batching of sequenced live frames: the first frame goes
232
+ * to the worker at once, frames that arrive while that batch is in flight
233
+ * go out as ONE `processSequencedBatch` when it returns. See
234
+ * {@link dispatchIncoming}.
235
+ */
236
+ private readonly coalescer;
237
+ /** Single-flight gap fills, one `syncConversationStep` loop per conversation. */
238
+ private readonly gapFiller;
239
+ /** Set by {@link close}: every later call rejects instead of hanging. */
240
+ private closed;
241
+ private ownDeviceId;
242
+ /**
243
+ * Per-conversation dispatch chains. See {@link dispatchIncoming}.
244
+ *
245
+ * Keyed by lowercase-hex conversation id. Bounded: a chain is deleted the
246
+ * moment it settles and is still the tail, so an account with thousands of
247
+ * conversations holds at most one entry per conversation with work IN FLIGHT,
248
+ * not one per conversation it has ever seen.
249
+ */
250
+ private dispatchChains;
251
+ private constructor();
252
+ /** Generate a fresh identity. The returned bytes are a secret — store them encrypted. */
253
+ static generateIdentity(): Promise<Uint8Array>;
254
+ /**
255
+ * HPKE-seal a `LinkingTicket` for delivery to a new device ([CR-3]).
256
+ *
257
+ * Returns CBOR-encoded bytes safe to relay through an untrusted inbox. The new device's
258
+ * X25519 public key (`newDevicePub`) is exchanged out-of-band — typically as part of a
259
+ * QR-encoded handshake on the linking screen. Pure function; runs in an ephemeral
260
+ * worker so no live `MessagingClient` is required on the sender side.
261
+ *
262
+ * Suite: `DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM` (matches MLS).
263
+ */
264
+ static sealLinkingTicket(ticket: LinkingTicket, newDevicePub: Uint8Array): Promise<Uint8Array>;
265
+ /**
266
+ * HPKE-open a sealed `LinkingTicket` on the new device ([CR-3]).
267
+ *
268
+ * The receiving device hasn't booted a `MessagingClient` yet — it only has its X25519
269
+ * ephemeral keypair. This static method runs the open in an ephemeral worker, returning
270
+ * the cleartext ticket which the host then feeds to `init()` + `consumeLinkingTicket()`.
271
+ *
272
+ * On failure the error message is deliberately generic (no discriminator between "wrong
273
+ * key" vs "tampered ciphertext") so a probing attacker can't tell the new device's key
274
+ * was the issue.
275
+ */
276
+ static openLinkingTicket(sealed: Uint8Array, newDevicePriv: Uint8Array): Promise<LinkingTicket>;
277
+ /**
278
+ * Generic HPKE-Base seal of arbitrary bytes to `recipientPub` (32-byte X25519)
279
+ * under a caller-supplied `info`. One shared HPKE implementation so app layers
280
+ * (e.g. the device-linking auth envelope) stop hand-rolling per-platform HPKE
281
+ * that drifts and breaks cross-platform. Runs in an ephemeral worker.
282
+ */
283
+ static hpkeSeal(plaintext: Uint8Array, recipientPub: Uint8Array, info: Uint8Array): Promise<Uint8Array>;
284
+ /** Generic HPKE-Base open — inverse of {@link hpkeSeal}. `info` must match the sender. */
285
+ static hpkeOpen(sealed: Uint8Array, recipientPriv: Uint8Array, info: Uint8Array): Promise<Uint8Array>;
286
+ /**
287
+ * HPKE-Base seal in the RFC 9180 CANONICAL layout, `enc || ct||tag`, with no
288
+ * CBOR wrapper.
289
+ *
290
+ * Use this, not {@link hpkeSeal}, for anything the app layers already speak.
291
+ * `hpkeSeal` wraps its output in CBOR `{v, enc, ct}` for the linking ticket,
292
+ * and because that could not read the RFC layout, iOS, Android, web and the
293
+ * third-party `ping-notify` sender each ended up hand-composing their own
294
+ * HPKE for the same suite. This is the one they agree on.
295
+ */
296
+ static hpkeSealRaw(plaintext: Uint8Array, recipientPub: Uint8Array, info: Uint8Array): Promise<Uint8Array>;
297
+ /**
298
+ * Inverse of {@link hpkeSealRaw}. `info` must match the sender's.
299
+ *
300
+ * Rejects with one uniform error whatever went wrong. This opens bytes from
301
+ * an unauthenticated inbox, so a caller that could tell "wrong key" from
302
+ * "tampered" from "truncated" would be an oracle for whoever wrote them.
303
+ */
304
+ static hpkeOpenRaw(sealed: Uint8Array, recipientPriv: Uint8Array, info: Uint8Array): Promise<Uint8Array>;
305
+ /**
306
+ * A fresh X25519 keypair for the suite.
307
+ *
308
+ * Exposed so a caller minting a recipient key (a Ping Notify inbox, a linking
309
+ * handshake) does not reach for WebCrypto to do it, which is the same problem
310
+ * one layer down.
311
+ */
312
+ static hpkeGenerateKeypair(): Promise<{
313
+ publicKey: Uint8Array;
314
+ privateKey: Uint8Array;
315
+ }>;
316
+ /**
317
+ * HPKE-seal a `LinkingTicket` under the new device's X-Wing public key
318
+ * ([CR-3], post-quantum). CBOR `{v: 2, enc, ct}` under `ping/link/v2`; the
319
+ * classical {@link openLinkingTicket} refuses it and {@link openLinkingTicketPq}
320
+ * refuses a `v: 1` blob, so there is no downgrade in either direction.
321
+ */
322
+ static sealLinkingTicketPq(ticket: LinkingTicket, newDevicePub: Uint8Array): Promise<Uint8Array>;
323
+ /**
324
+ * HPKE-open a sealed `v: 2` ticket with the new device's 32-byte X-Wing seed
325
+ * ([CR-3], post-quantum). The error is deliberately generic, like
326
+ * {@link openLinkingTicket}.
327
+ */
328
+ static openLinkingTicketPq(sealed: Uint8Array, newDevicePriv: Uint8Array): Promise<LinkingTicket>;
329
+ /** Post-quantum {@link hpkeSeal}: CBOR-wrapped (`v: 2`), `recipientPub` is 1216 bytes. */
330
+ static hpkeSealPq(plaintext: Uint8Array, recipientPub: Uint8Array, info: Uint8Array): Promise<Uint8Array>;
331
+ /** Inverse of {@link hpkeSealPq}. `recipientPriv` is the 32-byte seed; `info` must match. */
332
+ static hpkeOpenPq(sealed: Uint8Array, recipientPriv: Uint8Array, info: Uint8Array): Promise<Uint8Array>;
333
+ /**
334
+ * Post-quantum {@link hpkeSealRaw}: RFC 9180 canonical `enc(1120) || ct || tag`.
335
+ * The `v2` form of every app-layer envelope (`ping/link-auth/v2`,
336
+ * `ping/app-inbox/v2`).
337
+ */
338
+ static hpkeSealRawPq(plaintext: Uint8Array, recipientPub: Uint8Array, info: Uint8Array): Promise<Uint8Array>;
339
+ /** Inverse of {@link hpkeSealRawPq}. One uniform error, as for {@link hpkeOpenRaw}. */
340
+ static hpkeOpenRawPq(sealed: Uint8Array, recipientPriv: Uint8Array, info: Uint8Array): Promise<Uint8Array>;
341
+ /**
342
+ * A fresh X-Wing keypair: `publicKey` is {@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes,
343
+ * `privateKey` the 32-byte seed. Persist only the seed and recompute the public
344
+ * half with {@link hpkePublicKeyFromSeed}; wipe both buffers when done.
345
+ */
346
+ static hpkeGenerateKeypairPq(): Promise<{
347
+ publicKey: Uint8Array;
348
+ privateKey: Uint8Array;
349
+ }>;
350
+ /**
351
+ * The X-Wing public key for a stored 32-byte seed. Deterministic: the pairing
352
+ * code carries SHA-256 of exactly these bytes, so what a device advertises
353
+ * always matches what it will open with.
354
+ */
355
+ static hpkePublicKeyFromSeed(seed: Uint8Array): Promise<Uint8Array>;
356
+ /**
357
+ * The id of an account's DeviceGroup (the private sync group of the
358
+ * account's own devices), derived by the SDK core from the account's MLS
359
+ * user id: `userId` is `client.userId()` (32 bytes), NOT the server's
360
+ * account id. Deterministic: every device of the account derives the same
361
+ * id, so a host recognises the DeviceGroup without copying the derivation.
362
+ * Stateless (no client needed); bytes that are not an MLS user id derive an
363
+ * id no device uses.
364
+ */
365
+ static deviceGroupIdFor(userId: UserId): Promise<ConversationId>;
366
+ /** The 32-byte X25519 public key for a stored classical private key. */
367
+ static hpkePublicKeyFromPrivate(privateKey: Uint8Array): Promise<Uint8Array>;
368
+ /**
369
+ * Answer a device re-authentication challenge (`POST /v1/auth/device/challenge`) with
370
+ * the device signing key, so a device whose session tokens are gone or dead gets fresh
371
+ * ones for the SAME device without a code (`POST /v1/auth/device/verify`).
372
+ *
373
+ * The SDK builds the signed bytes itself (`"ping/device-reauth/v1" || challengeId ||
374
+ * nonce || deviceId || accountId || audience`), so this cannot sign anything else with
375
+ * the device key. `deviceSigningSecretKey` is the 32-byte secret the host passes as
376
+ * `deviceSigningSecretKey` to {@link init}; `challengeId` (16 bytes) and `nonce`
377
+ * (32 bytes) come from the challenge response. `accountId` (16 bytes) is the account
378
+ * the host stored with its session; the server refuses a proof for any other account,
379
+ * so send the same id with the proof. `audience` is the canonical origin of the API
380
+ * THIS host is configured to reach (`new URL(apiBase).origin`, for example
381
+ * `https://api-prod.ping.live`), never the value the server returned: that is what
382
+ * makes a challenge relayed from another deployment useless there. The returned
383
+ * `deviceId` is SHA-256 of the key's public half; send it with the signature.
384
+ *
385
+ * Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.
386
+ */
387
+ static signDeviceReauth(params: {
388
+ deviceSigningSecretKey: Uint8Array;
389
+ challengeId: Uint8Array;
390
+ nonce: Uint8Array;
391
+ accountId: Uint8Array;
392
+ audience: string;
393
+ }): Promise<DeviceReauthProof>;
394
+ /**
395
+ * Link verification v2, on the APPROVING device: approve ONE new device on ONE
396
+ * server link session (`POST /v1/auth/link/sessions` returned `approvalSessionId`)
397
+ * with this device's signing key. The new device sends the result with its own
398
+ * {@link signDeviceLinkPossession} proof to `POST /v1/auth/link/verify`.
399
+ *
400
+ * The SDK builds the signed bytes itself (`"ping/device-link-approve/v1" ||
401
+ * approvalSessionId || accountId || approverDeviceId || newDeviceId ||
402
+ * newDevicePubkey || audience`, see docs/DEVICE_LINK_V2_VECTORS.md) and derives
403
+ * both device ids from the keys, so this cannot sign anything else with the device
404
+ * key. `deviceSigningSecretKey` is the 32-byte seed the host holds for THIS device
405
+ * (the one registered as its device signing key); `accountId` (16 bytes) is the
406
+ * account stored with this device's session; `newDevicePubkey` (32 bytes) is the
407
+ * new device's key from its handshake; `audience` is the canonical origin of the API
408
+ * THIS host is configured to reach (`new URL(apiBase).origin`), as for
409
+ * {@link signDeviceReauth}.
410
+ *
411
+ * Rejects wrong widths, a non-canonical audience, a new key that is not a canonical
412
+ * Ed25519 point outside the small-order subgroup, and this device's own key. Runs in
413
+ * an ephemeral worker.
414
+ */
415
+ static signDeviceLinkApproval(params: {
416
+ deviceSigningSecretKey: Uint8Array;
417
+ approvalSessionId: Uint8Array;
418
+ accountId: Uint8Array;
419
+ newDevicePubkey: Uint8Array;
420
+ audience: string;
421
+ }): Promise<DeviceLinkApproval>;
422
+ /**
423
+ * Link verification v2, on the NEW device: prove that this device holds the key the
424
+ * link session names (`"ping/device-link-possess/v1" || approvalSessionId ||
425
+ * accountId || deviceId || audience`). `deviceSigningSecretKey` is this device's own
426
+ * 32-byte seed (the key its handshake advertised); `approvalSessionId` and
427
+ * `accountId` come from the approving device's sealed envelope; `audience` as for
428
+ * {@link signDeviceReauth}. Check `approval.newDeviceId` equals the returned
429
+ * `deviceId` before verifying: a substituted handshake is refused locally.
430
+ *
431
+ * Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.
432
+ */
433
+ static signDeviceLinkPossession(params: {
434
+ deviceSigningSecretKey: Uint8Array;
435
+ approvalSessionId: Uint8Array;
436
+ accountId: Uint8Array;
437
+ audience: string;
438
+ }): Promise<DeviceLinkPossession>;
439
+ private static ephemeralWorkerCall;
440
+ static init(cfg: ClientConfig): Promise<MessagingClient>;
441
+ /**
442
+ * Internal: route an inbound envelope to the right handler, IN ARRIVAL ORDER
443
+ * PER CONVERSATION.
444
+ *
445
+ * ## Why the ordering is load-bearing
446
+ *
447
+ * A group invitation arrives as a Welcome immediately followed by the
448
+ * inviter's hydration Application messages (group title, roster, avatar id).
449
+ * `joinConversation` is asynchronous — it is several round trips to the WASM
450
+ * worker — so a naive `void dispatchIncoming(...)` per frame let the
451
+ * Applications reach `processEnvelope` while the join was still in flight.
452
+ * The conversation did not exist yet, so every one of them was dropped with
453
+ * "envelope drop: unknown conversation".
454
+ *
455
+ * That loss is PERMANENT and silent: MLS ratchets forward, the transport has
456
+ * already marked the frames seen and advanced its cursor, and the server will
457
+ * not resend them. The visible symptom was an invitation landing as an
458
+ * unnamed "New chat" with no avatar and no roster, and — for the same reason —
459
+ * a rename, avatar change, member add/remove or role change being lost
460
+ * whenever it happened to land while a join or another commit for that group
461
+ * was still being applied.
462
+ *
463
+ * Chaining PER CONVERSATION (not globally) is deliberate: MLS state is
464
+ * per-group, so that is the granularity correctness actually requires, and a
465
+ * busy conversation must not be able to head-of-line block every other one.
466
+ * The chain is built synchronously on entry, so chain order is exactly frame
467
+ * arrival order.
468
+ *
469
+ * ## Sequenced frames
470
+ *
471
+ * A frame that carries its server position (`{ envelope, serverSeq }`,
472
+ * `serverSeq > 0`) does not need the chain: the core applies it at its
473
+ * position, holds it ahead of a hole and drops it at or below what was
474
+ * applied, whatever order it arrived in. What it needs is BATCHING: one
475
+ * MLS checkpoint and one host transaction per burst instead of one per
476
+ * frame. So the first frame for a conversation goes to the worker at once
477
+ * as a batch of one, and frames that arrive while that batch is in flight
478
+ * accumulate and go out as ONE `processSequencedBatch` when it returns; no
479
+ * timer ever delays a frame. Own-device echoes are NOT dropped on this
480
+ * path: the core advances the position past them without touching MLS,
481
+ * and dropping one would leave a hole the next frame reports as a gap. A
482
+ * sequenced frame at `serverSeq` 0 is a legacy frame in a wrapper and
483
+ * takes the legacy path unchanged.
484
+ */
485
+ private dispatchIncoming;
486
+ /** The legacy per-envelope path: own-device drop, then the per-conversation chain. */
487
+ private dispatchLegacy;
488
+ /** The actual routing, run inside the per-conversation chain. */
489
+ private dispatchIncomingOrdered;
490
+ /**
491
+ * One coalesced batch of live frames. Errors are logged at debug and
492
+ * swallowed, exactly as the legacy path treats a failed envelope: the
493
+ * dispatch promise a transport may await resolves either way, and the
494
+ * core retains anything it could not apply yet.
495
+ */
496
+ private applyLiveBatch;
497
+ /** Start a fill for every gap a batch reported; each is single-flight. */
498
+ private scheduleGapFills;
499
+ /** One page, delivered as a page, on the requested lane. */
500
+ private stepConversation;
501
+ userId(): Promise<UserId>;
502
+ /**
503
+ * Export the account identity seed (CBOR-wrapped Ed25519, **SECRET**).
504
+ * Transfer to a newly-linked device over the sealed linking channel so all of
505
+ * an account's devices share one `userId` — the basis for cross-device
506
+ * self-attribution (`IncomingMessage.sender_user_id === userId()`). Never log
507
+ * or persist in cleartext.
508
+ */
509
+ exportIdentity(): Promise<Uint8Array>;
510
+ /**
511
+ * RETIRED (2026-11-03): always rejects (`Invalid`) and changes nothing.
512
+ *
513
+ * It moved every conversation's own leaf to a new account identity with a
514
+ * credential-changing Commit, the way out of `409 mls_identity_conflict`.
515
+ * Every Ping client now refuses a Commit that changes a member's leaf
516
+ * credential (a hostile linked device could otherwise move its leaf to a
517
+ * peer's identity and escape the account's removal), so a rotation would
518
+ * strand every conversation it touched. The way out of an identity conflict
519
+ * is to link this device again, or sign out and in. Kept so no caller
520
+ * breaks. See `docs/MULTIDEVICE.md` "Identity rotation".
521
+ *
522
+ * @deprecated Retired: always rejects. Link this device again instead.
523
+ */
524
+ rotateIdentity(newIdentityExport: Uint8Array, nowMs?: number): Promise<IdentityRotation>;
525
+ /**
526
+ * RETIRED with [[rotateIdentity]]: always rejects (`Invalid`).
527
+ *
528
+ * @deprecated Retired: always rejects.
529
+ */
530
+ rotateIdentityRetry(conv: ConversationId, nowMs?: number): Promise<void>;
531
+ deviceId(): Promise<DeviceId>;
532
+ /**
533
+ * Release every file lock the MLS store holds so the host process can be
534
+ * suspended. Resolves `true` when the locks are genuinely gone.
535
+ *
536
+ * Present on web for API parity, and a no-op returning `true` here: this build
537
+ * persists through the host's `Storage` (IndexedDB by default), which holds no
538
+ * file locks and has nothing to release. It is load-bearing on the native
539
+ * bindings, where iOS kills a backgrounded process that still holds a lock on
540
+ * a file in an App Group container. Exposed on every platform so a host
541
+ * sharing code across web and native does not have to branch on it.
542
+ *
543
+ * Pair with `resumeStorage()`.
544
+ */
545
+ suspendStorage(): Promise<boolean>;
546
+ /** Undo `suspendStorage()`. Idempotent. */
547
+ resumeStorage(): Promise<void>;
548
+ freshKeyPackage(): Promise<Uint8Array>;
549
+ /**
550
+ * Generate a fresh LAST-RESORT KeyPackage (RFC 9420 §10). Publish exactly one
551
+ * per device so the server can serve it repeatedly as a fallback when the
552
+ * single-use pool empties — invites then never hard-fail purely because the
553
+ * peer ran out of KeyPackages.
554
+ */
555
+ freshLastResortKeyPackage(): Promise<Uint8Array>;
556
+ createConversation(opts?: {
557
+ name?: string;
558
+ }): Promise<Conversation>;
559
+ /**
560
+ * Create an ephemeral per-call MLS group. Identical to {@link createConversation}
561
+ * except the id carries the `0xFF 0xCC` call-group sentinel, so every device
562
+ * recognises it structurally (by id alone — no name, no registry) and keeps it
563
+ * out of the chat list. Hosts MUST use this for call groups.
564
+ */
565
+ createCallConversation(opts?: {
566
+ name?: string;
567
+ }): Promise<Conversation>;
568
+ joinConversation(welcome: MessageEnvelope): Promise<Conversation>;
569
+ /**
570
+ * Get a `Conversation` proxy for an already-known conversation. Use this when you have a
571
+ * conversation id (e.g., from `listConversations()`) and want to send/addMembers without
572
+ * re-creating it. Throws if the id isn't known to the worker — call `listConversations()`
573
+ * first to verify membership.
574
+ */
575
+ getConversation(id: ConversationId): Conversation;
576
+ listConversations(): Promise<ConversationMeta[]>;
577
+ /**
578
+ * ONE conversation's metadata as the group holds it now: the same record as
579
+ * its element of {@link listConversations}, without listing the others.
580
+ * Resolves `null` when this client does not hold the conversation (unknown,
581
+ * dropped, removed, or left). A pure read of local state: nothing is
582
+ * fetched. Rejects for an id that is not 16 bytes.
583
+ *
584
+ * It also brings the conversation handle's `name`, `epoch` and `meta()` to
585
+ * the answer, though they do not need it to be fresh: the client replaces
586
+ * its copy of a conversation's metadata
587
+ * - before any {@link onConversationUpdated} listener is told the
588
+ * conversation changed (a Commit from another member, a join, a page of
589
+ * a catch-up), and
590
+ * - before this device's own call that changed it resolves (a rename, a
591
+ * roles or membership change, a creation, a leave).
592
+ * Use this read for a conversation nothing has reported yet in this
593
+ * session, or to learn that a conversation is no longer held.
594
+ */
595
+ readConversationMeta(id: Uint8Array): Promise<ConversationMeta | null>;
596
+ /**
597
+ * Conversations detected as STRANDED during catch-up — a Commit was missed
598
+ * and the group can no longer advance from local state, so new messages stop
599
+ * arriving. Poll after a sync and recover each (re-Welcome / state-snapshot
600
+ * import). Returns 16-byte conversation ids; the set self-clears as a
601
+ * conversation makes progress or is re-joined.
602
+ */
603
+ strandedConversations(): Promise<ConversationId[]>;
604
+ /**
605
+ * Conversations this device asked to leave and is still a member of:
606
+ * the leave is OWED. The SDK holds their state and proposes the leave
607
+ * again by itself; the host only keeps delivering their rows (live
608
+ * frames and catch-up pages). An id leaves the list when the leave has
609
+ * completed: this device processed its own removal and the state is
610
+ * deleted. Sorted 16-byte conversation ids.
611
+ */
612
+ conversationsLeaving(): Promise<ConversationId[]>;
613
+ /**
614
+ * The leaving conversations whose leave has STALLED: 8 sends of it
615
+ * FAILED and this device is still a member, or this device can no longer
616
+ * follow the group. Nothing more is proposed for them. The host may call
617
+ * {@link leaveConversation} again (the count starts over) or give up with
618
+ * {@link dropConversationLocal}, which leaves this device's leaf in the group
619
+ * until somebody removes it. Sorted 16-byte conversation ids.
620
+ */
621
+ conversationsLeaveStalled(): Promise<ConversationId[]>;
622
+ /**
623
+ * Conversations this device was just torn down from by a SELF-RE-ADD Commit
624
+ * — a peer's `reAdmitDevice` of this device — whose Welcome for the new
625
+ * leaf is expected within seconds. Treat these as "re-admission in flight",
626
+ * not stranded or evicted: no repair advertise, no delivery-key rotation,
627
+ * no KeyPackage-pool replace, until the join lands or the entry ages out
628
+ * (ten minutes). Returns 16-byte conversation ids.
629
+ */
630
+ readmitPendingConversations(nowMs?: number): Promise<ConversationId[]>;
631
+ /**
632
+ * How many inbound envelopes are currently RETAINED awaiting replay, across
633
+ * all conversations.
634
+ *
635
+ * An envelope that cannot be applied yet — its Welcome has not been processed,
636
+ * or a Commit that advances the epoch is missing — is buffered and replayed on
637
+ * join / epoch advance / catch-up sync rather than dropped (see
638
+ * docs/INVITE_HARDENING.md §S6).
639
+ *
640
+ * A non-zero count means "delivered but not yet applicable", which is
641
+ * materially different from "not delivered" and is the distinction a host
642
+ * needs to explain a chat that looks incomplete. Expected to be 0 at rest; a
643
+ * value that stays high points at a conversation whose handshake never
644
+ * arrived.
645
+ */
646
+ undeliverableCount(): Promise<number>;
647
+ /**
648
+ * Leave a conversation: broadcasts a self-Remove PROPOSAL (MLS forbids
649
+ * committing your own removal: a remaining member commits it via
650
+ * `commitPendingProposals`) and answers at once. From then on the conversation is
651
+ * LEFT for the host: it is no longer listed, every call that names it
652
+ * answers `UnknownConversation`, and nothing of it is surfaced again.
653
+ *
654
+ * Do NOT delete it locally afterwards ({@link dropConversationLocal}). The SDK keeps the
655
+ * group's state, follows its Commits, and proposes the leave again after
656
+ * each Commit that did not carry it (a Commit built before the proposal
657
+ * arrived voids it), until this device is removed; then it deletes the
658
+ * state itself. Keep delivering the conversation's rows to the client
659
+ * while {@link conversationsLeaving} lists it. The bound is 8 FAILED sends;
660
+ * after that {@link conversationsLeaveStalled} lists the conversation and calling
661
+ * this again starts over.
662
+ *
663
+ * The group's OWNER hands over first: this call commits the successor (the
664
+ * one every device computes when the owner's last leaf goes) and only then
665
+ * proposes the leave. If that Commit cannot be made the call fails with the
666
+ * Commit's error and nothing is marked: call it again. Nothing is handed
667
+ * over when the owner's account keeps another device in the group or when
668
+ * no other member could take over.
669
+ */
670
+ leaveConversation(id: ConversationId, nowMs?: number): Promise<void>;
671
+ /**
672
+ * Drop a conversation's local state with NO network side effect. Unlike
673
+ * {@link leaveConversation} (which broadcasts a self-Remove proposal), this
674
+ * sends nothing — use it for a group the SERVER does not back: an invite that
675
+ * minted the MLS group locally but never completed server-side, so the backend
676
+ * 404s `fetchSince` / 403s the member roster for it. Deletes the OpenMLS group
677
+ * state + the on-disk snapshot rows so the dead group stops rehydrating on the
678
+ * next restart (and re-materialising as a ghost "New chat"). Idempotent — safe
679
+ * on an unknown/already-dropped id.
680
+ */
681
+ dropConversationLocal(id: ConversationId): Promise<void>;
682
+ /**
683
+ * Conversations with buffered pending proposals (e.g. a peer's leave). Poll
684
+ * after a sync; if you're the designated committer, call
685
+ * `commitPendingProposals` to evict the leaver.
686
+ */
687
+ conversationsWithPendingProposals(): Promise<ConversationId[]>;
688
+ /**
689
+ * Commit buffered pending proposals for a conversation (evicts a peer who
690
+ * left). No-op if nothing is pending; on an epoch-advanced rejection re-sync
691
+ * (another member already committed). Call it on receipt (a batch or page
692
+ * result's `proposalsPending`), elected with
693
+ * {@link pendingProposalsCommitRank}. A `send` commits pending proposals
694
+ * itself first, so a proposal never blocks a message.
695
+ */
696
+ commitPendingProposals(id: ConversationId, nowMs?: number): Promise<void>;
697
+ /**
698
+ * This device's rank in the deterministic election of who commits a
699
+ * conversation's pending proposals: members by leaf index, excluding any
700
+ * leaf a pending proposal removes; identical on every member. `0` means
701
+ * commit now; rank `n` means wait `n` intervals (a few seconds each), then
702
+ * commit if the proposals are still pending. `null` when nothing is pending
703
+ * or this device is not eligible.
704
+ */
705
+ pendingProposalsCommitRank(id: ConversationId): Promise<number | null>;
706
+ /**
707
+ * The Commits this device holds in doubt: a Commit whose send got no
708
+ * definite answer (no response, a 5xx) is neither merged nor discarded; the
709
+ * SDK settles it on a capped exponential backoff, and every operation in
710
+ * that conversation fails with `commit in doubt` until it settles. Retry
711
+ * such an operation at `nextAttemptAtMs`.
712
+ */
713
+ commitsInDoubt(): Promise<CommitInDoubt[]>;
714
+ /**
715
+ * Member roster for a conversation, recovered locally from the MLS
716
+ * group's leaf credentials (no network, no out-of-band message). Returns
717
+ * one entry per device leaf — a multi-device user appears multiple times,
718
+ * so dedup by `user_id` for a per-user roster. Empty for an unknown id.
719
+ */
720
+ members(conv: ConversationId): Promise<MemberInfo[]>;
721
+ /**
722
+ * A conversation's credential policy (account-signed device credentials,
723
+ * 2026-11-04): whether every leaf must carry a credential the account key signed
724
+ * (`credentialsRequired`; a KeyPackage without one gets the add verdict
725
+ * `credentialMissing`), the roles once the policy records them (round 2), and
726
+ * `incapableMembers`, the accounts with a member on an app too old for this
727
+ * group, which is what blocks the upgrade. Rejects for a conversation this client
728
+ * does not hold. No host action is needed for the credentials themselves: the SDK
729
+ * signs and verifies them internally.
730
+ */
731
+ conversationPolicy(conv: ConversationId): Promise<ConversationPolicy>;
732
+ /**
733
+ * Whether a Commit of THIS device that re-admits or adds the device `deviceId` of
734
+ * the account `identity` would pass the membership rules of the conversation in
735
+ * its state now, without building or sending anything (2026-11-18). True when
736
+ * this device may add a leaf of that account (the owner, an admin, or a device of
737
+ * that same account; a device of the OWNER only when this device is the owner's)
738
+ * and, if `deviceId` holds a leaf there, may also remove that leaf. Always true in
739
+ * a conversation without roles. Ask it BEFORE leasing a re-admission request or
740
+ * claiming a KeyPackage: a device that is not privileged never claims another
741
+ * account's KeyPackage. Advisory: the Commit is judged again when it is built and
742
+ * by every receiver. Rejects for a conversation this client does not hold.
743
+ */
744
+ mayReadmit(conv: ConversationId, identity: UserId, deviceId: DeviceId): Promise<boolean>;
745
+ /**
746
+ * The identity (the account's user id) a KeyPackage's credential CLAIMS, read
747
+ * without changing anything (2026-11-18, rule R13). `null` for a credential that
748
+ * is not the project's. Rejects for bytes that are not a valid KeyPackage: the
749
+ * checks OpenMLS runs on a KeyPackage an add carries run first (both signatures
750
+ * under the leaf's own key, the version, the init key, the extensions against the
751
+ * capabilities, the lifetime: an expired KeyPackage rejects).
752
+ *
753
+ * Before adding ANOTHER account's device, read it and compare it with the account
754
+ * you meant to add, byte for byte; a different answer, or `null`, is enough to
755
+ * refuse the KeyPackage the server handed out, before any Commit.
756
+ *
757
+ * The read runs the SAME credential verdict the add runs (the device
758
+ * credential, then the leaf-ready check) and rejects for a claim the add
759
+ * would refuse, so an identity answered is one the account's key vouched
760
+ * for (rulings part 13, ruling 1; until then the answer was a bare claim).
761
+ */
762
+ keyPackageIdentity(keyPackage: Uint8Array): Promise<UserId | null>;
763
+ /**
764
+ * Replace the owners this client expects first roles writes to name
765
+ * (2026-11-04, round 2; see `ClientConfig.expectedOwners`).
766
+ */
767
+ setExpectedOwners(entries: ExpectedOwner[]): Promise<void>;
768
+ /**
769
+ * Record a group's roles in its policy (2026-11-04, round 2): `owner` and
770
+ * `admins` as MLS user ids (map account ids through the roster). One
771
+ * GroupContextExtensions Commit, no Welcome, send-then-merge. Rejects with
772
+ * "not permitted ..." before anything is sent when this device's role does not
773
+ * allow the change, when a member's app is too old for roles
774
+ * (`conversationPolicy().incapableMembers` names it), or in the DeviceGroup.
775
+ * The same call as `getConversation(id).setConversationRoles`.
776
+ */
777
+ setConversationRoles(conv: ConversationId, owner: UserId, admins: UserId[]): Promise<void>;
778
+ /**
779
+ * Whole-account catch-up. The worker runs it one conversation at a time and
780
+ * lets every other request (a `send` the user is waiting on, a live frame)
781
+ * run between conversations, so a pass over many conversations never parks
782
+ * an interactive call behind all of them. Resolves when every conversation
783
+ * held at the start of the pass (plus any joined while it ran) has been
784
+ * paged, with the decrypted application messages in apply order.
785
+ */
786
+ syncConversations(): Promise<IncomingMessage[]>;
787
+ /**
788
+ * Catch-up for ONE conversation: the unit `syncConversations` is built from.
789
+ * Use it to bring the conversation the user is looking at up to date ahead
790
+ * of the rest (a message must be encrypted at the epoch the group is really
791
+ * at, so a host calls this before the first send after a reconnect), or to
792
+ * step a pass in an order of its own. Rejects with the SDK's
793
+ * `unknown conversation` error for an id this client does not hold.
794
+ */
795
+ syncConversation(id: ConversationId): Promise<IncomingMessage[]>;
796
+ processEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;
797
+ /**
798
+ * Apply a batch of live frames, each with its server log position, and
799
+ * checkpoint once per touched conversation. Per conversation: the next
800
+ * position applies, one ahead of a hole is held and reported in `gaps`,
801
+ * one at or below the applied position is a duplicate. Welcomes are routed
802
+ * to a join inside the SDK (a join anchors the new conversation at the
803
+ * Welcome's position); own-device echoes advance the position without
804
+ * touching MLS, so pass them through. Frames at `serverSeq` 0 take the
805
+ * legacy per-sender path.
806
+ *
807
+ * The decrypted messages are returned AND delivered: to `onMessageBatch`
808
+ * handlers as one call (source `live`) when any is registered, else per
809
+ * message to `onMessage` handlers. `onConversationUpdated` fires once per
810
+ * entry of `updated`. A reported gap starts {@link fillGap} for that
811
+ * conversation.
812
+ */
813
+ processSequencedBatch(items: SequencedEnvelope[]): Promise<ApplyBatchResult>;
814
+ /**
815
+ * ONE page of a conversation's server log through `Transport.fetchLogSince`,
816
+ * applied in order and checkpointed once, then whatever held frames the
817
+ * page made contiguous. `hasMore` means step again. Same delivery as
818
+ * {@link processSequencedBatch}, with source `page`. An ordinary request:
819
+ * it runs ahead of any background pass, so a host can bring the open chat
820
+ * current first. Rejects with the SDK's `unknown conversation` error for an
821
+ * id this client does not hold; the durable cursor is unchanged on a
822
+ * transport failure.
823
+ */
824
+ syncConversationStep(id: ConversationId): Promise<SyncStepResult>;
825
+ /**
826
+ * Fill a conversation's gap: run {@link syncConversationStep} until
827
+ * `hasMore` is false, single-flight per conversation, on the worker's
828
+ * stepped lane so a send posted meanwhile goes between pages. The SDK
829
+ * starts this itself for every gap a batch reports; hosts call it for the
830
+ * heads a socket `resume_ack` shows above the local position. A call
831
+ * while a fill is running rides on it (and the loop runs once more after,
832
+ * in case the running one ended before the new gap's rows were appended).
833
+ */
834
+ fillGap(conversationId: ConversationId): Promise<void>;
835
+ /**
836
+ * This device's applied position in every conversation it holds, sorted by
837
+ * conversation id: what a host puts in its socket resume frame and
838
+ * compares against the server's heads.
839
+ */
840
+ logPositions(): Promise<LogPosition[]>;
841
+ /** This device's applied position in one conversation; `null` when not held. */
842
+ logPosition(id: ConversationId): Promise<LogPosition | null>;
843
+ /**
844
+ * Anchor a conversation whose cursor predates positions at the
845
+ * `(epoch, serverSeq)` the host had recorded for it, so an existing install
846
+ * does not page its whole current epoch again. Resolves `false` (a no-op)
847
+ * when the conversation is already anchored; the MLS epoch is never
848
+ * touched. Call it once at start-up for every conversation the host's own
849
+ * cursor store holds a position for.
850
+ */
851
+ adoptLogPosition(id: ConversationId, epoch: number, serverSeq: number): Promise<boolean>;
852
+ /**
853
+ * Conversations the server's heads show this device is behind on: not
854
+ * anchored yet, a head above the applied position, or frames held in the
855
+ * reorder buffer. Sorted by id. A held conversation absent from `heads` is
856
+ * not listed.
857
+ */
858
+ conversationsBehind(heads: LogHead[]): Promise<ConversationId[]>;
859
+ /** Frames held in reorder buffers right now (diagnostics). */
860
+ heldFrameCount(): Promise<number>;
861
+ /**
862
+ * {@link joinConversation} at the Welcome's log position, so the new
863
+ * conversation is anchored there and its first live frame applies without
864
+ * a page. Pass `null` (or omit) when the position is unknown.
865
+ */
866
+ joinConversationAt(welcome: MessageEnvelope, position?: number | null): Promise<Conversation>;
867
+ /**
868
+ * The Welcome routing rule at a known position: joins when the conversation
869
+ * is unknown or held stranded and resolves to it, resolves `null` when it
870
+ * is held healthy (a relay duplicate), rejects when the Welcome is not
871
+ * addressed to this device.
872
+ */
873
+ processWelcomeAt(welcome: MessageEnvelope, position?: number | null): Promise<Conversation | null>;
874
+ /**
875
+ * [D27] Decrypted-but-unconfirmed messages surviving in the pending-apply
876
+ * journal, oldest first.
877
+ *
878
+ * The MLS ratchet advances at decrypt, BEFORE the host persists its own row
879
+ * for the message; a crash inside that gap used to lose the message for good
880
+ * (the server re-delivers, but MLS cannot re-decrypt a consumed generation).
881
+ * The SDK now journals every decrypt in the same checkpoint that persists
882
+ * the ratchet advance.
883
+ *
884
+ * CRASH-RECOVERY CONTRACT: on boot, BEFORE advancing any sync cursor or
885
+ * sending any delivery ack, drain this list through the normal ingest —
886
+ * dedup by `content_hash` / envelope identity exactly as for a redelivered
887
+ * envelope — persist each message, then {@link confirmApplied} the drained
888
+ * ids. Reading does not consume; unconfirmed entries survive further
889
+ * restarts (bounded: 512 entries / 4 MiB, oldest evicted). See
890
+ * docs/PENDING_APPLIES.md.
891
+ */
892
+ pendingApplies(): Promise<PendingApply[]>;
893
+ /**
894
+ * [D27] Delete journal entries whose messages the host has durably
895
+ * persisted (`IncomingMessage.journal_id` from live processing, or
896
+ * `PendingApply.journal_id` from a boot drain), and checkpoint so the
897
+ * deletion survives a reload. Unknown ids are ignored (idempotent).
898
+ */
899
+ confirmApplied(journalIds: string[]): Promise<void>;
900
+ /**
901
+ * Build a `LinkingTicket` for a new device.
902
+ *
903
+ * [CR-13] `lastAppEvents` is host-supplied per-conversation "what you missed" data
904
+ * (decrypted AppEvent bytes the new device will render before sync catches up).
905
+ * Pass `[]` to suppress catchup data — the new device will see an empty conversation
906
+ * list until normal sync runs.
907
+ *
908
+ * Caller is responsible for HPKE-sealing the returned ticket via
909
+ * `MessagingClient.sealLinkingTicket` before transmitting (CR-3).
910
+ *
911
+ * Rejects (`Invalid`), before anything is sent, a KeyPackage that claims the
912
+ * identity of another account this client knows: a new device links under an
913
+ * identity of its own, or the account's.
914
+ */
915
+ buildLinkingTicket(newDeviceId: DeviceId, newDeviceKp: Uint8Array, lastAppEvents?: CatchupAppEvent[]): Promise<LinkingTicket>;
916
+ /**
917
+ * Decode a `LinkingTicket.catchup_snapshot` blob ([CR-13]).
918
+ *
919
+ * Pure WASM — runs in an ephemeral worker so the new device can call this before
920
+ * `MessagingClient.init()` completes (just like `openLinkingTicket`). Returns the
921
+ * structured view: per-conversation metas + last-known AppEvent bytes.
922
+ *
923
+ * Throws on malformed or oversized inputs. Empty bytes return `null` — that's the
924
+ * "no catchup data" case (sender passed `[]` to buildLinkingTicket).
925
+ */
926
+ static decodeCatchupSnapshot(snapshotBytes: Uint8Array): Promise<CatchupSnapshotView | null>;
927
+ consumeLinkingTicket(ticket: LinkingTicket): Promise<void>;
928
+ /** Generate a fresh 12-word BIP39 mnemonic, returned as its canonical phrase string. */
929
+ static generateMnemonicPhrase(): Promise<string>;
930
+ /** Validate + canonicalise a user-entered phrase (BIP39 wordlist + checksum). Rejects
931
+ * malformed input. Use on the recovery screen before calling `decryptBackup`. */
932
+ static normalizeMnemonicPhrase(phrase: string): Promise<string>;
933
+ /** Encrypt an IdentityBackup for `POST /v1/recovery/blobs`. `deviceGroupSnapshot` may be
934
+ * empty (Conservative path) or the DeviceGroup's `exportConversationStateSnapshot`. */
935
+ static encryptBackup(args: {
936
+ mnemonicPhrase: string;
937
+ accountId: Uint8Array;
938
+ identityExport: Uint8Array;
939
+ deviceGroupSnapshot: Uint8Array;
940
+ /** External conversations to embed so recovery restores them offline. Pass
941
+ * `[]` (the default) for identity + DeviceGroup only. Each `groupStateBytes`
942
+ * is `Conversation.exportConversationStateSnapshot` output. Forward-secrecy
943
+ * trade-off — see the SDK recovery docs. */
944
+ conversationSnapshots?: {
945
+ conversationId: Uint8Array;
946
+ groupStateBytes: Uint8Array;
947
+ }[];
948
+ createdAtMs: number;
949
+ }): Promise<Uint8Array>;
950
+ /** Decrypt a recovery blob from `GET /v1/recovery/blobs`. Throws on wrong mnemonic or a
951
+ * tampered blob. The returned `identity_export` is the secret seed for `init`. */
952
+ static decryptBackup(blob: Uint8Array, mnemonicPhrase: string): Promise<RecoveryBackup>;
953
+ /** Seal+sign a `HistoryBundle` for a recipient device. `recipientPub` (X25519, 32B) is the
954
+ * recipient's ephemeral pubkey from the linking QR; `senderIdentitySecret` (Ed25519 seed,
955
+ * 32B) is this account's identity key. Returns the blob to POST to /v1/history-transfers. */
956
+ static sealHistoryBundle(bundle: HistoryBundle, recipientPub: Uint8Array, senderIdentitySecret: Uint8Array): Promise<Uint8Array>;
957
+ /** Open+verify a sealed history bundle. `recipientPriv` (X25519, 32B) is this device's
958
+ * ephemeral private key; `senderIdentityPub` (Ed25519, 32B) is the account identity pubkey
959
+ * from the linking handshake. Throws if the signature doesn't verify. */
960
+ static openHistoryBundle(sealed: Uint8Array, recipientPriv: Uint8Array, senderIdentityPub: Uint8Array): Promise<HistoryBundle>;
961
+ /**
962
+ * Post-quantum {@link sealHistoryBundle}: `recipientPub` is the recipient's
963
+ * X-Wing public key ({@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes). Wrapper `v: 2`;
964
+ * the classical open refuses it and vice versa.
965
+ */
966
+ static sealHistoryBundlePq(bundle: HistoryBundle, recipientPub: Uint8Array, senderIdentitySecret: Uint8Array): Promise<Uint8Array>;
967
+ /** Post-quantum {@link openHistoryBundle}: `recipientPriv` is the 32-byte X-Wing seed. */
968
+ static openHistoryBundlePq(sealed: Uint8Array, recipientPriv: Uint8Array, senderIdentityPub: Uint8Array): Promise<HistoryBundle>;
969
+ /**
970
+ * Admit a freshly-linked device to every chat in `entries` — one MLS
971
+ * Commit + Welcome per chat, with the Welcome's `?recipient=` priming
972
+ * handled inside the SDK. This is the post-link reconciliation step
973
+ * that follows `consumeLinkingTicket`: the new device has the
974
+ * DeviceGroup (from the ticket) and metadata for external chats (from
975
+ * the catchup snapshot), but its leaf is not yet in any external
976
+ * MLS group. The host on the EXISTING device calls this once the
977
+ * new device shows up in `/v1/auth/sessions` and has uploaded its
978
+ * KeyPackage batch, passing one freshly-claimed KP per chat.
979
+ *
980
+ * Per-chat failures (stale KP, transport error, unknown chat) are
981
+ * captured in the returned outcomes rather than aborting — one bad
982
+ * chat shouldn't lose the user access to all the others.
983
+ *
984
+ * Each KeyPackage must carry this account's identity (a linked device
985
+ * adopts it with the link): one that claims any other identity fails its
986
+ * chat and nothing is sent there.
987
+ */
988
+ admitDeviceToChats(deviceId: DeviceId, entries: AdmitChatEntry[]): Promise<AdmitChatOutcome[]>;
989
+ /**
990
+ * `admitDeviceToChats` with up to `concurrency` admissions in flight at
991
+ * once. Same input, same per-chat outcomes in INPUT order whatever order
992
+ * the sends finish in; `concurrency` 1 is exactly `admitDeviceToChats`,
993
+ * 0 is treated as 1. Safe because every admission is its own conversation
994
+ * (one Commit + Welcome per chat, the conversation lock is never held
995
+ * across the send), so two admissions never touch the same epoch.
996
+ *
997
+ * This is the ONLY way to overlap admissions on web: the worker runs one
998
+ * call at a time, so several `admitDeviceToChats` calls issued together
999
+ * still run one after another. The overlap happens inside this one call.
1000
+ */
1001
+ admitDeviceToChatsConcurrent(deviceId: DeviceId, entries: AdmitChatEntry[], concurrency: number): Promise<AdmitChatOutcome[]>;
1002
+ /**
1003
+ * Revoke a device ([CR-2]).
1004
+ *
1005
+ * Removes `deviceId`'s leaf from every conversation where this client locally
1006
+ * tracked the device→leaf mapping (i.e. conversations where this client itself
1007
+ * admitted the device via `addMembers`, or where this client is the device being
1008
+ * revoked). The SDK has already broadcast each Commit envelope via
1009
+ * `transport.send`; the returned array is for any additional host-side handling
1010
+ * (audit logs, UI). An empty array is a valid outcome — the device wasn't locally
1011
+ * known anywhere.
1012
+ *
1013
+ * **Scope note.** Conversations where a peer admitted the device on this client's
1014
+ * behalf are silently skipped — the leaf index isn't locally known. Host can fall
1015
+ * back to `transport.discoverDevices` + a manual `remove_members(leafIndex)` for
1016
+ * those, or wait for the affected user to revoke from a device that did the admit.
1017
+ * See `docs/architecture/multi-device.md §Device removal`.
1018
+ */
1019
+ revokeDevice(deviceId: DeviceId): Promise<MessageEnvelope[]>;
1020
+ /**
1021
+ * Remove one of THIS account's devices from every group this client is in, the
1022
+ * DeviceGroup included, without stopping at a failure, and report where it stands.
1023
+ *
1024
+ * Unlike {@link revokeDevice}, the device's leaf is read from each ratchet tree (the
1025
+ * leaf whose key hashes to the id), so this reaches leaves a sibling or a peer
1026
+ * admitted. The id is the server's word that the device is this account's; outside
1027
+ * the DeviceGroup a leaf is removed only when its credential names this account, or
1028
+ * when the device was seen in the account's DeviceGroup and its credential names no
1029
+ * other account this client knows (docs/MULTIDEVICE.md, "Which leaf"). An id that
1030
+ * names no leaf of this account is rejected before anything is sent. Every held
1031
+ * conversation is checked: a Commit of this device in doubt is settled first, and
1032
+ * the log is read to its end before the device is reported absent (what that read
1033
+ * applies comes with the next batch or page); a conversation that failed to load
1034
+ * is a failure with reason `Unloadable`. The DeviceGroup goes first, then the
1035
+ * conversations, a few at a time, each a send-then-merge Commit. Persist the report
1036
+ * and call again until `failed` is empty and `deviceGroup !== "failed"`. A
1037
+ * `CommitInDoubt` reason settles on its own backoff ({@link commitsInDoubt});
1038
+ * `NotOwnAccount` and `RefusedCommit` never resolve by retrying (for
1039
+ * `RefusedCommit`, offer to recreate the conversation). Groups this device joins
1040
+ * later are checked for the device too.
1041
+ *
1042
+ * MLS only: revoke the device on the server yourself. Rejects for this device's own
1043
+ * id (leave a conversation with `leaveConversation` instead) and for a device that
1044
+ * is not this account's.
1045
+ */
1046
+ removeDeviceEverywhere(deviceId: DeviceId, nowMs?: number): Promise<DeviceRemovalReport>;
1047
+ /**
1048
+ * Remove every other device of THIS account from every group this client is in,
1049
+ * except the devices in `keep` and this device: the "secure my account" sweep.
1050
+ *
1051
+ * `listed` is the server's list of this account's devices to remove (a reset's
1052
+ * `revoked_device_ids`). In the DeviceGroup every leaf but this device's and the
1053
+ * kept ones goes. Elsewhere a leaf goes when its credential names this client's
1054
+ * account (no device id has to match, so a device that moved its leaf to another
1055
+ * signature key is still reached), or when its device is in `listed` and was seen in
1056
+ * the account's DeviceGroup, whatever identity its leaf claims. A leaf the sweep
1057
+ * leaves although one of those two says it may be the account's (seen but not
1058
+ * listed, or listed but not seen) is reported: its conversation fails with
1059
+ * `NotOwnAccount`, so the report is never complete over it. Same pass and report as
1060
+ * {@link removeDeviceEverywhere}; call again until it is complete. MLS only.
1061
+ */
1062
+ removeOwnDevicesExcept(keep: DeviceId[], listed: DeviceId[], nowMs?: number): Promise<DeviceRemovalReport>;
1063
+ /**
1064
+ * Export a portable MLS state snapshot for one conversation ([CR-7]).
1065
+ *
1066
+ * Returned bytes can be embedded in a recovery blob or shipped through a
1067
+ * linking ticket so another device of the same user identity can re-attach to
1068
+ * the group via [[importStateSnapshot]]. The bytes contain past epoch secrets;
1069
+ * never log, never persist unencrypted, wipe (`.fill(0)`) after use.
1070
+ */
1071
+ exportConversationStateSnapshot(conv: ConversationId): Promise<Uint8Array>;
1072
+ /**
1073
+ * Import a `GroupStateSnapshot` from another device of the same user identity
1074
+ * ([CR-7]).
1075
+ *
1076
+ * On success, the conversation appears in [[listConversations]] and decryption
1077
+ * of subsequent peer-originated traffic works against the imported state. For
1078
+ * full multi-device participation, the recovered device SHOULD then issue an
1079
+ * MLS Update Proposal to rotate onto a fresh leaf (post-v1 follow-up — see
1080
+ * `docs/design/CR4_CR7_PERSISTENCE.md` open question #3).
1081
+ */
1082
+ importStateSnapshot(snapshotBytes: Uint8Array): Promise<ConversationId>;
1083
+ /**
1084
+ * Export a derived secret from a conversation's MLS exporter ([CR-8]).
1085
+ *
1086
+ * Used to seed the ephemeral channel (`ping/ephemeral`), call-media keys
1087
+ * (`ping/calls/media/<call_id>`), and call-ephemeral framer keys
1088
+ * (`ping/calls/ephemeral/<call_id>`). The returned bytes are a secret — never log,
1089
+ * persist only encrypted, and call `bytes.fill(0)` after use to wipe the typed array.
1090
+ *
1091
+ * Same `(conversationId, current_epoch, label, context, length)` produces the same
1092
+ * bytes across every binding (Rust core, native UniFFI, WASM/JS). Cross-platform
1093
+ * byte-equality is enforced by `protocol/conformance/export_secret/`.
1094
+ */
1095
+ exportConversationSecret(conv: ConversationId, label: string, context: Uint8Array, length: number): Promise<Uint8Array>;
1096
+ /**
1097
+ * Subscribe to decrypted application messages, one call per message. A
1098
+ * batch or page result (the sequenced paths) is fanned out here per
1099
+ * message only while no {@link onMessageBatch} handler is registered.
1100
+ */
1101
+ onMessage(handler: (m: IncomingMessage) => void): () => void;
1102
+ /**
1103
+ * Subscribe to decrypted messages one BATCH at a time: one call per
1104
+ * `processSequencedBatch` result (source `live`) or per page of the server
1105
+ * log (source `page`: a gap fill, or the whole-account catch-up), so the
1106
+ * host persists the batch in one store transaction. While at least one
1107
+ * batch handler is registered, batch and page results go ONLY here, never
1108
+ * per message to `onMessage`; the legacy per-envelope path still delivers
1109
+ * per message. An empty result is not delivered.
1110
+ */
1111
+ onMessageBatch(handler: (messages: IncomingMessage[], meta: MessageBatchMeta) => void): () => void;
1112
+ /** Fired after every state-changing event for a conversation (Commit, member changes). */
1113
+ /**
1114
+ * Fires after every conversation state change — joining via Welcome, processing a Commit,
1115
+ * etc. `sender` carries the device id of whoever triggered the event when known (e.g. the
1116
+ * inviter's device on auto-join), so the host can label peers in its UI.
1117
+ */
1118
+ onConversationUpdated(handler: (id: ConversationId, epoch: number, sender?: DeviceId) => void): () => void;
1119
+ /**
1120
+ * Stop the live subscription and terminate the worker. Every call still in
1121
+ * flight rejects with a {@link MessagingClientClosedError} (reason
1122
+ * `closed`), and every later call rejects the same way instead of waiting
1123
+ * on a worker that no longer exists. Idempotent.
1124
+ */
1125
+ close(): Promise<void>;
1126
+ /** Reject every pending call with `error` and forget them. */
1127
+ private failPending;
1128
+ private conversationProxy;
1129
+ /** Replace this client's copy of one conversation's metadata with what the
1130
+ * worker read; no metadata means the copy is dropped, so the handle answers
1131
+ * "not held" instead of what the group held before. */
1132
+ private storeMeta;
1133
+ private call;
1134
+ /** Dispatch a worker-side transport proxy call onto the host transport.
1135
+ * `sendBatch` is the one method the worker proxy always declares but a
1136
+ * host may not implement: emulate it with sequential sends and report a
1137
+ * partial delivery with the sentinel the wasm bridge maps to
1138
+ * `TransportPartial`, so the SDK still learns the Commit landed while the
1139
+ * Welcome did not (and surfaces `WelcomeUndelivered`). The two
1140
+ * sequenced-log methods cross in the wasm's wire shape and are converted
1141
+ * to the public shape here, both ways; the worker only asks for them when
1142
+ * the host declared them at `init`. */
1143
+ private callTransportMethod;
1144
+ private handleWorker;
1145
+ }
1146
+ /** A stateless SDK call ran on a one-shot worker that failed before it could answer:
1147
+ * the worker could not be created (`spawn`), the request could not be posted (`post`),
1148
+ * the worker script failed to load, import or run (`error`), or its reply could not be
1149
+ * deserialised (`messageerror`). The worker has already been terminated; the event's
1150
+ * details (which may name a script URL) are not carried. */
1151
+ declare class EphemeralWorkerError extends Error {
1152
+ readonly reason: "spawn" | "post" | "error" | "messageerror";
1153
+ constructor(reason: "spawn" | "post" | "error" | "messageerror");
1154
+ }
1155
+ /**
1156
+ * The typed rejection every call still pending gets when the client is
1157
+ * closed (`reason: "closed"`) or the worker reported an uncaught error
1158
+ * (`reason: "worker-error"`), and what every call made after `close()`
1159
+ * rejects with. Before this, `close()` terminated the worker and left those
1160
+ * promises pending forever.
1161
+ */
1162
+ declare class MessagingClientClosedError extends Error {
1163
+ readonly reason: "closed" | "worker-error";
1164
+ constructor(reason: "closed" | "worker-error");
1165
+ }
1166
+ /** Sentinel prefix for an emulated batch that only partially landed. Kept in
1167
+ * lockstep with `core/ping-wasm/src/lib.rs` (`BATCH_PARTIAL_PREFIX`). */
1168
+ /** Width of an X-Wing (post-quantum HPKE) public key, `hpkeGenerateKeypairPq().publicKey`. */
1169
+ declare const HPKE_PQ_PUBLIC_KEY_BYTES = 1216;
1170
+ /** Width of the KEM encapsulation at the front of a post-quantum raw envelope. */
1171
+ declare const HPKE_PQ_ENC_BYTES = 1120;
1172
+ declare const BATCH_PARTIAL_PREFIX = "batch partial after ";
1173
+ /** How the rejection of a call reads when the conversation's roles do not
1174
+ * permit it (the core's `Error::NotPermitted`): this prefix, then the rule
1175
+ * that was broken (fixed text, no id, safe to log). No other failure starts
1176
+ * this way (a malformed request reads `invalid input: ...`). Kept in
1177
+ * lockstep with the core's display (`stringify` in
1178
+ * `core/ping-wasm/src/lib.rs`, pinned by `ping-core/tests/typed_errors.rs`). */
1179
+ declare const NOT_PERMITTED_PREFIX = "not permitted: ";
1180
+ /** The typed role refusal: what a `MessagingClient` call rejects with when
1181
+ * the encrypted group's roles do not permit it. Raised before anything was
1182
+ * built or sent, and final until the roles or the membership change: drop
1183
+ * the intent (never retry or queue it), read `conversationPolicy()` again.
1184
+ * A join from a Welcome and `importStateSnapshot` reject with it too, for a
1185
+ * state that names an owner or an admin without a verified leaf: drop that
1186
+ * invitation, or skip that conversation of the import. `message` stays the
1187
+ * core's text, so `isNotPermittedError` also reads a copy that lost its
1188
+ * class (a structured clone, another realm). */
1189
+ declare class NotPermittedError extends Error {
1190
+ /** The rule that was broken: fixed text, no id, safe to log. */
1191
+ readonly rule: string;
1192
+ constructor(message: string);
1193
+ }
1194
+ /** The rule a role refusal names, or `null` when `e` is any other failure.
1195
+ * Accepts the rejection itself, any object with a `message`, or the text. */
1196
+ declare function notPermittedRule(e: unknown): string | null;
1197
+ /** True when `e` is the typed role refusal ("the encrypted group's roles do
1198
+ * not permit this") and no other failure. */
1199
+ declare function isNotPermittedError(e: unknown): boolean;
1200
+ /** How the rejection of a call reads when an envelope names a sender device
1201
+ * other than the one that sealed its MLS message (the core's
1202
+ * `Error::SenderMismatch`). No other failure starts this way. Kept in
1203
+ * lockstep with the core's display (`stringify` in
1204
+ * `core/ping-wasm/src/lib.rs`, pinned by `ping-core/tests/typed_errors.rs`). */
1205
+ declare const SENDER_MISMATCH_PREFIX = "sender mismatch: ";
1206
+ /** The typed refusal of an envelope whose `senderDevice` is not the device
1207
+ * that sealed its message (checked after decryption against the sender
1208
+ * leaf's signature key). The message was not delivered, a Commit in it was
1209
+ * not applied, and no dedupe or ordering mark moved: the named device's own
1210
+ * messages are delivered as before. Drop the envelope, never retry it, show
1211
+ * nothing. `message` stays the core's text, so `isSenderMismatchError` also
1212
+ * reads a copy that lost its class. */
1213
+ declare class SenderMismatchError extends Error {
1214
+ constructor(message: string);
1215
+ }
1216
+ /** True when `e` is the typed sender refusal and no other failure. Accepts
1217
+ * the rejection itself, any object with a `message`, or the text. */
1218
+ declare function isSenderMismatchError(e: unknown): boolean;
1219
+ /** Sequential stand-in for a host transport without `sendBatch`: sends in
1220
+ * order and reports a failure after at least one success with the partial
1221
+ * sentinel, so the SDK learns the Commit landed while the Welcome did not. */
1222
+ declare function emulateSendBatch(transport: Pick<Transport, "send">, envelopes: MessageEnvelope[]): Promise<void>;
1223
+ /** Serialise a transport rejection for the worker so the wasm bridge can
1224
+ * still classify it: the HTTP status survives as `http <status>` in the
1225
+ * text (a definite 4xx lets the SDK roll a staged Commit back), and any
1226
+ * server error code rides along for diagnostics. */
1227
+ declare function describeTransportError(e: unknown): string;
1228
+
1229
+ export { AddMembersReport, AdmitChatEntry, AdmitChatOutcome, ApplyBatchResult, BATCH_PARTIAL_PREFIX, CONTENT_TYPE_CBOR, CONTENT_TYPE_CBOR_LEGACY_V1, CONTENT_TYPE_JSON, CONTENT_TYPE_JSON_LEGACY_V1, CatchupAppEvent, CatchupSnapshotView, type ClientConfig, CommitInDoubt, type Conversation, ConversationId, ConversationMeta, ConversationPolicy, DeviceId, DeviceLinkApproval, DeviceLinkPossession, DeviceReauthProof, DeviceRemovalReport, EphemeralWorkerError, ExpectedOwner, HPKE_PQ_ENC_BYTES, HPKE_PQ_PUBLIC_KEY_BYTES, HistoryBundle, IdentityRotation, IncomingMessage, KeyPackageEntry, LinkingTicket, LogHead, LogPosition, MemberInfo, MessageBatchMeta, MessageEnvelope, MessagingClient, MessagingClientClosedError, NOT_PERMITTED_PREFIX, NotPermittedError, PING_WIRE_CONTRACT_HEADER, PING_WIRE_CONTRACT_HEADER_VALUE, PING_WIRE_CONTRACT_VERSION, PendingApply, RecoveryBackup, SENDER_MISMATCH_PREFIX, SenderMismatchError, SequencedEnvelope, Storage, SyncStepResult, Transport, UserId, ValidationError, WIRE_VERSION_MIN_ACCEPTED, describeTransportError, emulateSendBatch, isNotPermittedError, isSenderMismatchError, negotiates, notPermittedRule, validate, verifyApplicationContentHash };