@mosadd/mcp 3.0.0-alpha.55 → 3.0.0-alpha.57

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 (54) hide show
  1. package/CHANGELOG.md +15 -11
  2. package/README.md +152 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-IWUGKLDX.js → chunk-WEGSITAH.js} +30 -14
  5. package/dist/index.js +1 -1
  6. package/package.json +2 -2
  7. package/src/__tests__/blob-upload.test.ts +93 -93
  8. package/src/__tests__/channel-e2ee.test.ts +62 -62
  9. package/src/__tests__/flota-jawnie.test.ts +2 -2
  10. package/src/__tests__/golden-path.test.ts +139 -139
  11. package/src/__tests__/integration.test.ts +217 -182
  12. package/src/__tests__/label-room-owner.test.ts +22 -0
  13. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  14. package/src/__tests__/mdm-mcp-readable.test.ts +390 -390
  15. package/src/__tests__/mirc-invite.test.ts +112 -112
  16. package/src/__tests__/mtalk.test.ts +122 -122
  17. package/src/__tests__/presence.test.ts +199 -199
  18. package/src/__tests__/server.test.ts +71 -71
  19. package/src/__tests__/tool-count-consistency.test.ts +259 -199
  20. package/src/__tests__/voice-fields.test.ts +24 -0
  21. package/src/bin/login.ts +138 -138
  22. package/src/bin/mcp.ts +145 -145
  23. package/src/config.ts +66 -66
  24. package/src/crypto/channel-e2ee.ts +288 -288
  25. package/src/crypto/mdm-session.ts +842 -842
  26. package/src/index.ts +19 -19
  27. package/src/observability/sentry.ts +79 -79
  28. package/src/providers/blob-upload.ts +162 -162
  29. package/src/providers/memory-voice.ts +79 -79
  30. package/src/providers/supabase-dm.ts +212 -202
  31. package/src/providers/supabase-voice.ts +103 -91
  32. package/src/server.ts +195 -195
  33. package/src/tools/actions.ts +166 -166
  34. package/src/tools/attachments.ts +276 -276
  35. package/src/tools/capabilities.ts +70 -70
  36. package/src/tools/channel-payload.ts +2 -2
  37. package/src/tools/embed.ts +110 -110
  38. package/src/tools/index.ts +181 -181
  39. package/src/tools/knowledge.ts +344 -344
  40. package/src/tools/mail-aliases.ts +25 -25
  41. package/src/tools/mail-provenance.ts +137 -137
  42. package/src/tools/mail.ts +403 -403
  43. package/src/tools/mdm-as-agent.ts +138 -126
  44. package/src/tools/mdm.ts +6 -4
  45. package/src/tools/mirc-edge.ts +196 -196
  46. package/src/tools/mirc-members.ts +287 -287
  47. package/src/tools/mirc-messages.ts +1 -1
  48. package/src/tools/mirc.ts +308 -308
  49. package/src/tools/mroom.ts +221 -221
  50. package/src/tools/mtalk.ts +131 -131
  51. package/src/tools/presence.ts +442 -442
  52. package/src/tools/voice-format.ts +43 -28
  53. package/src/types.ts +121 -121
  54. package/src/voice/floor.ts +132 -132
@@ -1,842 +1,842 @@
1
- /**
2
- * mDM end-to-end encryption — session layer (LINEAR-2357).
3
- *
4
- * Sits ABOVE the DmProvider. The provider moves opaque bytes; THIS module
5
- * decides what those bytes are: an X3DH handshake + Double Ratchet ciphertext
6
- * envelope, produced from `@mosadd/crypto` primitives.
7
- *
8
- * Flow (decision "1a" — prekey distribution rides the DmProvider):
9
- * - Each peer publishes a prekey bundle via `dm.publishPrekeyBundle(bytes)`.
10
- * - First contact: sender `dm.fetchPrekeyBundle(peer)` → X3DH (initiator) →
11
- * Double Ratchet. The first ciphertext carries a handshake header
12
- * (initiator IK + EK + consumed one-time-prekey id) so the recipient can
13
- * run X3DH (responder) and derive the SAME root key.
14
- * - Subsequent messages reuse the stored ratchet session (no header).
15
- *
16
- * SCOPE / known follow-ups (tracked on LINEAR-2357, NOT silently hidden):
17
- * - Ratchet is strict in-order (no skipped-message keys) — fine for a single
18
- * ordered thread; out-of-order/lossy transports need skipped-key handling.
19
- * - Signed-prekey signature is carried but NOT yet verified (auth follow-up).
20
- * - Initiator "glare" (both sides open simultaneously) not resolved.
21
- * - Default keystore is in-memory (per-process); file/OS-keychain backing is
22
- * a follow-up. The MdmKeyStore seam makes that a drop-in.
23
- */
24
-
25
- import {
26
- decryptBytes,
27
- deriveHkdfKey,
28
- deriveSharedSecret,
29
- encryptBytes,
30
- generateEd25519KeyPair,
31
- generateX25519KeyPair,
32
- initializeRatchet,
33
- performX3dh,
34
- performX3dhResponder,
35
- ratchetReceive,
36
- ratchetSend,
37
- signEd25519,
38
- verifyEd25519,
39
- toBase64,
40
- fromBase64,
41
- initRatchetInitiator,
42
- initRatchetResponder,
43
- ratchetEncrypt,
44
- ratchetDecrypt,
45
- type EncryptedPayload,
46
- type RatchetState,
47
- type DhRatchetState,
48
- type SessionRole,
49
- } from "@mosadd/crypto";
50
- import type { DmProvider } from "@mosadd/providers";
51
-
52
- export const PREKEY_BUNDLE_VERSION = "mosadd.prekeys.v1" as const;
53
- /** Legacy symmetric-ratchet envelope (no PCS). Still DECODED for back-compat. */
54
- export const E2EE_ENVELOPE_VERSION = "mosadd.e2ee.v1" as const;
55
- /** Double-Ratchet-with-DH envelope — post-compromise security (LINEAR-3409). New sends use this. */
56
- export const E2EE_ENVELOPE_VERSION_V2 = "mosadd.e2ee.v2" as const;
57
-
58
- const DEFAULT_ONE_TIME_PREKEYS = 8;
59
-
60
- // ---- Key material types ----
61
-
62
- interface X25519Pair {
63
- publicKey: Uint8Array;
64
- privateKey: Uint8Array;
65
- }
66
-
67
- /** The local peer's long-term identity + prekeys (private halves included). */
68
- export interface OwnPrekeyMaterial {
69
- /** X25519 DH identity — used in X3DH. */
70
- identity: X25519Pair;
71
- /**
72
- * Ed25519 SIGNING identity — the long-term key a peer pins out-of-band
73
- * (the "safety number"). Signs the bundle so a network/radio MITM can't swap
74
- * the signed prekey or DH identity in transit.
75
- */
76
- signingIdentity: { publicKey: Uint8Array; privateKey: Uint8Array };
77
- signedPrekey: { id: number; pair: X25519Pair };
78
- oneTimePrekeys: Array<{ id: number; pair: X25519Pair }>;
79
- }
80
-
81
- /** A peer's PUBLIC prekey bundle, as parsed off the wire. */
82
- export interface PublicPrekeyBundle {
83
- identityPublicKey: Uint8Array;
84
- /** Ed25519 signing-identity public key the signature is verified against. */
85
- signingIdentityPublicKey: Uint8Array;
86
- signedPrekey: { id: number; publicKey: Uint8Array };
87
- oneTimePrekeys: Array<{ id: number; publicKey: Uint8Array }>;
88
- /** Ed25519 signature over (DH identity pub ‖ signed-prekey pub). */
89
- signature: Uint8Array;
90
- }
91
-
92
- /**
93
- * Persisted per-peer ratchet session. Plain data → trivially serializable.
94
- * A session is either v1 (`ratchet`, symmetric) or v2 (`ratchet2`, DH ratchet /
95
- * PCS). New sessions are v2; an existing v1 session keeps running v1.
96
- */
97
- export interface MdmSessionRecord {
98
- ratchet?: RatchetState; // v1 (legacy symmetric)
99
- ratchet2?: DhRatchetState; // v2 (DH ratchet, PCS — LINEAR-3409)
100
- role: SessionRole;
101
- /** Handshake header still owed to the peer (initiator only, until first send). */
102
- pendingHandshake?: { ik: Uint8Array; ek: Uint8Array; opkId?: number };
103
- }
104
-
105
- /**
106
- * Local custody of private key material + ratchet sessions. The default impl
107
- * is in-memory; a host may inject a file- or keychain-backed implementation.
108
- */
109
- export interface MdmKeyStore {
110
- /** Own identity + prekeys. Generated lazily on first access, then stable. */
111
- getOwnMaterial(): Promise<OwnPrekeyMaterial>;
112
- /** Consume (one-time) a prekey private by id. Returns undefined if unknown. */
113
- takeOneTimePrekey(id: number): Promise<Uint8Array | undefined>;
114
- getSession(peerId: string): Promise<MdmSessionRecord | undefined>;
115
- putSession(peerId: string, record: MdmSessionRecord): Promise<void>;
116
-
117
- /**
118
- * OPTIONAL local "sent items" cache. The Double Ratchet is forward-secret and
119
- * asymmetric: once we seal a message for a peer we cannot re-derive its
120
- * plaintext from our own ratchet on read. So mDM_list cannot show the sender
121
- * their OWN outgoing text unless we keep a local copy. These two methods are
122
- * that copy — keyed by the provider-assigned message id.
123
- *
124
- * Honesty note: this is a LOCAL plaintext cache, not synced across devices.
125
- * A second device (or a fresh process) won't have it and will fall back to a
126
- * "<encrypted · sent by you>" marker. Cross-device sent-history sync is a
127
- * tracked follow-up (would need an encrypt-to-self session). Optional so
128
- * existing MdmKeyStore implementations keep compiling.
129
- */
130
- putSentMessage?(messageId: string, plaintext: Uint8Array): Promise<void>;
131
- getSentMessage?(messageId: string): Promise<Uint8Array | undefined>;
132
-
133
- /**
134
- * OPTIONAL symmetric SELF-READ key (32 bytes), derived from the same recoverable
135
- * seed as the identity. Present only on seed-backed keystores. With it the sender
136
- * seals a copy of every outgoing DM to itself (`self_payload`, tag "s1.") that any
137
- * process holding the same seed can open again — the cross-process answer to the
138
- * "local sent-items cache only" note above. Null/absent = no self copy.
139
- */
140
- getSelfKeyBytes?(): Promise<Uint8Array | null>;
141
- }
142
-
143
- // ---- In-memory keystore (default) ----
144
-
145
- export class InMemoryMdmKeyStore implements MdmKeyStore {
146
- private material: OwnPrekeyMaterial | null = null;
147
- private readonly oneTimeById = new Map<number, Uint8Array>();
148
- private readonly sessions = new Map<string, MdmSessionRecord>();
149
- private readonly sentMessages = new Map<string, Uint8Array>();
150
-
151
- async getOwnMaterial(): Promise<OwnPrekeyMaterial> {
152
- if (this.material) return this.material;
153
- const identity = await generateX25519KeyPair();
154
- const signingIdentity = await generateEd25519KeyPair();
155
- const signedPrekeyPair = await generateX25519KeyPair();
156
- const signedPrekey = { id: randomId(), pair: signedPrekeyPair };
157
- const oneTimePrekeys: OwnPrekeyMaterial["oneTimePrekeys"] = [];
158
- for (let i = 0; i < DEFAULT_ONE_TIME_PREKEYS; i += 1) {
159
- const pair = await generateX25519KeyPair();
160
- const id = randomId();
161
- oneTimePrekeys.push({ id, pair });
162
- this.oneTimeById.set(id, pair.privateKey);
163
- }
164
- this.material = { identity, signingIdentity, signedPrekey, oneTimePrekeys };
165
- return this.material;
166
- }
167
-
168
- async takeOneTimePrekey(id: number): Promise<Uint8Array | undefined> {
169
- const priv = this.oneTimeById.get(id);
170
- if (priv) this.oneTimeById.delete(id); // one-time: consume on use
171
- return priv;
172
- }
173
-
174
- async getSession(peerId: string): Promise<MdmSessionRecord | undefined> {
175
- return this.sessions.get(peerId);
176
- }
177
-
178
- async putSession(peerId: string, record: MdmSessionRecord): Promise<void> {
179
- this.sessions.set(peerId, record);
180
- }
181
-
182
- async putSentMessage(messageId: string, plaintext: Uint8Array): Promise<void> {
183
- this.sentMessages.set(messageId, plaintext);
184
- }
185
-
186
- async getSentMessage(messageId: string): Promise<Uint8Array | undefined> {
187
- return this.sentMessages.get(messageId);
188
- }
189
- }
190
-
191
- function randomId(): number {
192
- return crypto.getRandomValues(new Uint32Array(1))[0]!;
193
- }
194
-
195
- // ---- Seed-backed keystore: ONE stable identity, not a new one per call ----
196
- //
197
- // ⛔ WHY (measured 27.09.2026, LINEAR-6089 follow-up): the hosted gateway builds a fresh
198
- // McpServer per HTTP request, so the default InMemoryMdmKeyStore minted a BRAND-NEW random
199
- // identity for every single mDM_send. Every envelope carried an X3DH header from an identity
200
- // that existed for one request and was never published — the sender could never read its own
201
- // message again (no self_payload, no key), and the recipient's recoverable copy could not be
202
- // written (it needs the sender's PUBLISHED identity). The app (mosADD f95557f) now says WHY such
203
- // a bubble is unreadable; this is the source fix, so new messages are born readable.
204
- //
205
- // The fix mirrors the web client exactly (apps/web/src/lib/mdmKeyStore.ts, LINEAR-3521 P2): the
206
- // whole identity is derived by HKDF from ONE recoverable 32-byte seed, with the SAME labels, zero
207
- // one-time prekeys and signed-prekey id 1 — so the bundle is byte-identical on every process that
208
- // knows the seed. The web takes its seed from the login secret; an MCP runtime has no password,
209
- // its login secret IS the API key (`mosadd_sk_live_…`) — see deriveMdmSeedFromSecret below.
210
-
211
- /** X25519 base point (u = 9, little-endian). X25519(k, 9) is exactly k's public key. */
212
- const X25519_BASE_POINT = (() => {
213
- const b = new Uint8Array(32);
214
- b[0] = 9;
215
- return b;
216
- })();
217
-
218
- /**
219
- * Deterministic X25519 pair from a 32-byte seed (the seed IS the private scalar — same
220
- * convention as the web's x25519KeyPairFromSeed). The published @mosadd/crypto has no
221
- * seed constructor, so the public half is computed as X25519(seed, basepoint), which is the
222
- * definition of the public key (the curve library clamps the scalar in both paths).
223
- */
224
- async function x25519PairFromSeed(seed: Uint8Array): Promise<X25519Pair> {
225
- const privateKey = seed.length === 32 ? seed : seed.slice(0, 32);
226
- const publicKey = await deriveSharedSecret(privateKey, X25519_BASE_POINT);
227
- return { privateKey, publicKey };
228
- }
229
-
230
- const utf8 = new TextEncoder();
231
-
232
- async function subSeed(seed: Uint8Array, label: string): Promise<Uint8Array> {
233
- return deriveHkdfKey(seed, { info: utf8.encode(label), length: 32 });
234
- }
235
-
236
- /** Same derivation, same labels as the web's deriveOwnMaterialFromSeed — keep them in lockstep. */
237
- export async function deriveOwnMaterialFromSeed(seed: Uint8Array): Promise<OwnPrekeyMaterial> {
238
- const [idSeed, signSeed, spkSeed] = await Promise.all([
239
- subSeed(seed, "mosadd-mdm-identity-x25519"),
240
- subSeed(seed, "mosadd-mdm-signing-ed25519"),
241
- subSeed(seed, "mosadd-mdm-signed-prekey-x25519"),
242
- ]);
243
- return {
244
- identity: await x25519PairFromSeed(idSeed),
245
- signingIdentity: await generateEd25519KeyPair(signSeed),
246
- signedPrekey: { id: 1, pair: await x25519PairFromSeed(spkSeed) },
247
- oneTimePrekeys: [],
248
- };
249
- }
250
-
251
- /**
252
- * The recoverable 32-byte seed of an MCP runtime, from its login secret (the API key).
253
- * Same key → same identity on every gateway instance, every call, every restart. A rotated
254
- * key is a new login secret and therefore a new identity — exactly like a changed PIN on web.
255
- * Not escrow: nothing here is stored; whoever holds the key could already act as the account.
256
- */
257
- export async function deriveMdmSeedFromSecret(secret: string): Promise<Uint8Array> {
258
- return deriveHkdfKey(utf8.encode(secret), {
259
- salt: utf8.encode("mosadd-mcp-api-key"),
260
- info: utf8.encode("mosadd-mdm-identity-seed"),
261
- length: 32,
262
- });
263
- }
264
-
265
- /**
266
- * Keystore anchored to a recoverable seed. Identity, signing key and signed prekey are
267
- * derived (stable); ratchet sessions and the sent cache stay in memory for this process.
268
- * No one-time prekeys: a stateless process could never remember which ones were consumed.
269
- */
270
- export class SeededMdmKeyStore implements MdmKeyStore {
271
- private material: Promise<OwnPrekeyMaterial> | null = null;
272
- private readonly sessions = new Map<string, MdmSessionRecord>();
273
- private readonly sentMessages = new Map<string, Uint8Array>();
274
-
275
- constructor(private readonly seed: Uint8Array) {
276
- if (!seed || seed.length < 32) throw new Error("SeededMdmKeyStore needs a 32-byte seed");
277
- }
278
-
279
- static async fromSecret(secret: string): Promise<SeededMdmKeyStore> {
280
- return new SeededMdmKeyStore(await deriveMdmSeedFromSecret(secret));
281
- }
282
-
283
- getOwnMaterial(): Promise<OwnPrekeyMaterial> {
284
- if (!this.material) this.material = deriveOwnMaterialFromSeed(this.seed);
285
- return this.material;
286
- }
287
-
288
- async takeOneTimePrekey(_id: number): Promise<Uint8Array | undefined> {
289
- return undefined; // the seeded bundle publishes none
290
- }
291
-
292
- async getSession(peerId: string): Promise<MdmSessionRecord | undefined> {
293
- return this.sessions.get(peerId);
294
- }
295
-
296
- async putSession(peerId: string, record: MdmSessionRecord): Promise<void> {
297
- this.sessions.set(peerId, record);
298
- }
299
-
300
- async putSentMessage(messageId: string, plaintext: Uint8Array): Promise<void> {
301
- this.sentMessages.set(messageId, plaintext);
302
- }
303
-
304
- async getSentMessage(messageId: string): Promise<Uint8Array | undefined> {
305
- return this.sentMessages.get(messageId);
306
- }
307
-
308
- /** Same label as the web's getSelfKeyBytes ("mosadd-mdm-self-read"). */
309
- async getSelfKeyBytes(): Promise<Uint8Array | null> {
310
- return deriveHkdfKey(this.seed, { info: utf8.encode("mosadd-mdm-self-read"), length: 32 });
311
- }
312
- }
313
-
314
- /**
315
- * A keystore that derives its seed lazily from a secret — lets a synchronous factory
316
- * (defaultProviders) hand out a stable-identity keystore without awaiting HKDF up front.
317
- */
318
- export class SecretMdmKeyStore implements MdmKeyStore {
319
- private inner: Promise<SeededMdmKeyStore> | null = null;
320
- constructor(private readonly secret: string) {}
321
- private store(): Promise<SeededMdmKeyStore> {
322
- if (!this.inner) this.inner = SeededMdmKeyStore.fromSecret(this.secret);
323
- return this.inner;
324
- }
325
- async getOwnMaterial() { return (await this.store()).getOwnMaterial(); }
326
- async takeOneTimePrekey(id: number) { return (await this.store()).takeOneTimePrekey(id); }
327
- async getSession(peerId: string) { return (await this.store()).getSession(peerId); }
328
- async putSession(peerId: string, record: MdmSessionRecord) { return (await this.store()).putSession(peerId, record); }
329
- async putSentMessage(messageId: string, plaintext: Uint8Array) { return (await this.store()).putSentMessage(messageId, plaintext); }
330
- async getSentMessage(messageId: string) { return (await this.store()).getSentMessage(messageId); }
331
- async getSelfKeyBytes() { return (await this.store()).getSelfKeyBytes(); }
332
- }
333
-
334
- // ---- Recoverable copies: the web's wire format, byte for byte ----
335
- //
336
- // Two opaque AES-GCM strings ride next to the ratchet envelope in `messages`:
337
- // self_payload "s1." + b64(iv‖ct) — sealed to the SENDER's self-read key
338
- // recipient_self_payload "r1." + b64(iv‖ct) — sealed to HKDF(ECDH(sender IK, recipient IK))
339
- // Formats, tags and HKDF labels are copied from apps/web/src/lib/mdmE2ee.ts (sealForSelf /
340
- // sealForPeerRecoverable) — the app opens exactly these. The server never reads them.
341
-
342
- const SELF_TAG = "s1.";
343
- const PEER_RECOVERABLE_TAG = "r1.";
344
- const PEER_RECOVERABLE_INFO = "mosadd.mdm.recipient-recoverable.v1";
345
-
346
- async function aesGcmSeal(tag: string, keyBytes: Uint8Array, plaintext: Uint8Array): Promise<string> {
347
- const key = await crypto.subtle.importKey("raw", keyBytes as BufferSource, { name: "AES-GCM" }, false, ["encrypt"]);
348
- const iv = crypto.getRandomValues(new Uint8Array(12));
349
- const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, plaintext as BufferSource));
350
- const packed = new Uint8Array(iv.length + ct.length);
351
- packed.set(iv, 0);
352
- packed.set(ct, iv.length);
353
- return tag + toBase64(packed);
354
- }
355
-
356
- async function aesGcmOpen(tag: string, keyBytes: Uint8Array, sealed: string): Promise<Uint8Array | null> {
357
- if (!sealed.startsWith(tag)) return null;
358
- const packed = fromBase64(sealed.slice(tag.length));
359
- if (packed.length <= 12) return null;
360
- const key = await crypto.subtle.importKey("raw", keyBytes as BufferSource, { name: "AES-GCM" }, false, ["decrypt"]);
361
- const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: packed.slice(0, 12) }, key, packed.slice(12));
362
- return new Uint8Array(pt);
363
- }
364
-
365
- /** Sender's own copy ("s1."). Null when the keystore has no seed. Never throws. */
366
- export async function sealForSelf(keystore: MdmKeyStore, plaintext: Uint8Array): Promise<string | null> {
367
- try {
368
- const keyBytes = (await keystore.getSelfKeyBytes?.()) ?? null;
369
- if (!keyBytes) return null;
370
- return await aesGcmSeal(SELF_TAG, keyBytes, plaintext);
371
- } catch {
372
- return null;
373
- }
374
- }
375
-
376
- /** Open an "s1." copy with this keystore's self-read key. Null when absent/foreign. Never throws. */
377
- export async function openSelfSealed(keystore: MdmKeyStore, sealed: string | null | undefined): Promise<Uint8Array | null> {
378
- try {
379
- if (!sealed) return null;
380
- const keyBytes = (await keystore.getSelfKeyBytes?.()) ?? null;
381
- if (!keyBytes) return null;
382
- return await aesGcmOpen(SELF_TAG, keyBytes, sealed);
383
- } catch {
384
- return null;
385
- }
386
- }
387
-
388
- async function pairKey(keystore: MdmKeyStore, otherIdentityPublicKey: Uint8Array): Promise<Uint8Array> {
389
- const own = await keystore.getOwnMaterial();
390
- const secret = await deriveSharedSecret(own.identity.privateKey, otherIdentityPublicKey);
391
- return deriveHkdfKey(secret, { info: utf8.encode(PEER_RECOVERABLE_INFO), length: 32 });
392
- }
393
-
394
- /** Recipient-openable copy ("r1.") for a VERIFIED peer bundle. Never throws. */
395
- export async function sealForPeerRecoverable(
396
- keystore: MdmKeyStore,
397
- peer: PublicPrekeyBundle,
398
- plaintext: Uint8Array,
399
- ): Promise<string | null> {
400
- try {
401
- return await aesGcmSeal(PEER_RECOVERABLE_TAG, await pairKey(keystore, peer.identityPublicKey), plaintext);
402
- } catch {
403
- return null;
404
- }
405
- }
406
-
407
- /** Open an "r1." copy written by the peer whose VERIFIED bundle is given. Never throws. */
408
- export async function openPeerRecoverable(
409
- keystore: MdmKeyStore,
410
- sender: PublicPrekeyBundle,
411
- sealed: string | null | undefined,
412
- ): Promise<Uint8Array | null> {
413
- try {
414
- if (!sealed) return null;
415
- return await aesGcmOpen(PEER_RECOVERABLE_TAG, await pairKey(keystore, sender.identityPublicKey), sealed);
416
- } catch {
417
- return null;
418
- }
419
- }
420
-
421
- /** Fetch + parse + signature-check a peer bundle. Null when absent or failing verification. */
422
- export async function fetchVerifiedBundle(dm: DmProvider, peerId: string): Promise<PublicPrekeyBundle | null> {
423
- const raw = await dm.fetchPrekeyBundle(peerId);
424
- if (!raw) return null;
425
- const parsed = parsePublicBundle(raw);
426
- return verifyPublicBundle(parsed) ? parsed : null;
427
- }
428
-
429
- function sameBytes(a: Uint8Array, b: Uint8Array): boolean {
430
- if (a.length !== b.length) return false;
431
- for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
432
- return true;
433
- }
434
-
435
- export type OwnBundleState =
436
- /** the directory already holds exactly our identity */
437
- | "consistent"
438
- /** the directory had no bundle (or we own the identity) and now holds ours */
439
- | "published"
440
- /** someone else's key material is published for this identity and we must not replace it */
441
- | "foreign"
442
- /** the directory holds NO bundle for this identity and this runtime may not create one */
443
- | "absent";
444
-
445
- /** What this runtime may write to the key directory for its own identity. */
446
- export interface BundlePolicy {
447
- /** directory empty → publish this keystore's bundle */
448
- mayPublishWhenEmpty: boolean;
449
- /** directory holds a DIFFERENT bundle → replace it with this keystore's */
450
- mayReplaceForeign: boolean;
451
- }
452
-
453
- /**
454
- * ⛔ WHO MAY WRITE THE KEY DIRECTORY FROM MCP (27.09.2026, poprawka po weryfikacji toru mdm-brama).
455
- *
456
- * The MCP identity is seeded from ONE API key. A mosADD identity has MANY active keys (every OAuth
457
- * connector mints its own — measured 27.09: 7 of 17 agent identities hold several, general@ alone
458
- * 8, all used within 3 days). A per-key identity that is allowed to (re)publish therefore makes the
459
- * directory FLAP between up to 8 identities: copies sealed under key A stop opening once key B
460
- * published, and envelopes sealed to "the" bundle open on one key only. So:
461
- *
462
- * - kind "agent": an agent LINE sends JAWNIE (plaintext) — rozkaz Króla 20.09 12:56Z „E2EE
463
- * wewnętrzne = zero": linie↔linie, linie↔Król, człowiek→linia bez E2EE; the app does the same
464
- * (ircApi.ts peerIsAgent). An agent never needs a bundle for mDM_send, so the AUTOMATIC paths
465
- * write nothing. Only an explicit mDM_publish_keys still publishes (the caller asked for it).
466
- * - kind "human": the person's bundle is anchored to their login secret IN THE APP
467
- * (mdmKeyStore.setIdentitySeed; kanon in hub-key-exchange: only the identity's own client
468
- * publishes). MCP never replaces it and never pre-empts it on an empty directory automatically
469
- * — a bundle published from an API-key seed would be overwritten by the app later and strand
470
- * everything sealed to it meanwhile. Explicit mDM_publish_keys may fill an EMPTY directory.
471
- * - unknown kind (non-Supabase lanes, e.g. radio): the pre-27.09 behaviour, empty → publish;
472
- * explicit → publish.
473
- */
474
- export function bundlePolicyForKind(kind: string | null | undefined, opts: { explicit: boolean }): BundlePolicy {
475
- if (kind === "agent") {
476
- return opts.explicit
477
- ? { mayPublishWhenEmpty: true, mayReplaceForeign: true }
478
- : { mayPublishWhenEmpty: false, mayReplaceForeign: false };
479
- }
480
- if (kind === "human") {
481
- return { mayPublishWhenEmpty: opts.explicit, mayReplaceForeign: false };
482
- }
483
- return { mayPublishWhenEmpty: true, mayReplaceForeign: opts.explicit };
484
- }
485
-
486
- /**
487
- * Make the key directory agree with this keystore's identity — only as far as `policy` allows.
488
- *
489
- * - directory == ours → "consistent" (no write).
490
- * - directory empty, may publish → publish ours → "published".
491
- * - directory empty, may not → "absent" (no write).
492
- * - directory differs, may replace → publish ours → "published".
493
- * - directory differs, may not → "foreign" (no write). The ratchet envelope still
494
- * works (it carries its own handshake); recoverable copies are skipped, because they would
495
- * be sealed under an identity nobody can look up.
496
- */
497
- export async function ensureOwnBundlePublished(
498
- keystore: MdmKeyStore,
499
- dm: DmProvider,
500
- selfId: string,
501
- policy: BundlePolicy,
502
- ): Promise<OwnBundleState> {
503
- const own = await keystore.getOwnMaterial();
504
- const raw = await dm.fetchPrekeyBundle(selfId);
505
- if (raw) {
506
- let published: PublicPrekeyBundle | null = null;
507
- try { published = parsePublicBundle(raw); } catch { published = null; }
508
- if (
509
- published &&
510
- sameBytes(published.identityPublicKey, own.identity.publicKey) &&
511
- sameBytes(published.signingIdentityPublicKey, own.signingIdentity.publicKey) &&
512
- sameBytes(published.signedPrekey.publicKey, own.signedPrekey.pair.publicKey)
513
- ) {
514
- return "consistent";
515
- }
516
- if (!policy.mayReplaceForeign) return "foreign";
517
- } else if (!policy.mayPublishWhenEmpty) {
518
- return "absent";
519
- }
520
- await dm.publishPrekeyBundle(serializePublicBundle(own));
521
- return "published";
522
- }
523
-
524
- // ---- Bundle codec (opaque bytes the provider moves) ----
525
-
526
- /**
527
- * The exact bytes signed by / verified against the Ed25519 signing identity:
528
- * the DH identity public key concatenated with the signed-prekey public key.
529
- * Binding both means a MITM cannot swap either without invalidating the sig.
530
- */
531
- function bundleSigningMessage(dhIdentityPub: Uint8Array, signedPrekeyPub: Uint8Array): Uint8Array {
532
- const msg = new Uint8Array(dhIdentityPub.length + signedPrekeyPub.length);
533
- msg.set(dhIdentityPub, 0);
534
- msg.set(signedPrekeyPub, dhIdentityPub.length);
535
- return msg;
536
- }
537
-
538
- export function serializePublicBundle(material: OwnPrekeyMaterial): Uint8Array {
539
- const signature = signEd25519(
540
- material.signingIdentity.privateKey,
541
- bundleSigningMessage(material.identity.publicKey, material.signedPrekey.pair.publicKey),
542
- );
543
- const json = JSON.stringify({
544
- v: PREKEY_BUNDLE_VERSION,
545
- ik: toBase64(material.identity.publicKey),
546
- sik: toBase64(material.signingIdentity.publicKey),
547
- spk: { id: material.signedPrekey.id, pub: toBase64(material.signedPrekey.pair.publicKey) },
548
- opks: material.oneTimePrekeys.map((k) => ({ id: k.id, pub: toBase64(k.pair.publicKey) })),
549
- sig: toBase64(signature),
550
- });
551
- return new Uint8Array(Buffer.from(json, "utf8"));
552
- }
553
-
554
- export function parsePublicBundle(bytes: Uint8Array): PublicPrekeyBundle {
555
- const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
556
- if (obj?.v !== PREKEY_BUNDLE_VERSION) {
557
- throw new Error(`Unsupported prekey bundle version: ${obj?.v}`);
558
- }
559
- if (typeof obj.sik !== "string" || typeof obj.sig !== "string") {
560
- throw new Error("Prekey bundle is missing its signing identity / signature.");
561
- }
562
- return {
563
- identityPublicKey: fromBase64(obj.ik),
564
- signingIdentityPublicKey: fromBase64(obj.sik),
565
- signedPrekey: { id: obj.spk.id, publicKey: fromBase64(obj.spk.pub) },
566
- oneTimePrekeys: (obj.opks ?? []).map((k: { id: number; pub: string }) => ({
567
- id: k.id,
568
- publicKey: fromBase64(k.pub),
569
- })),
570
- signature: fromBase64(obj.sig),
571
- };
572
- }
573
-
574
- /**
575
- * Verify the bundle's self-signature: the signing identity must have signed
576
- * (DH identity ‖ signed prekey). Rejecting a bad signature is the MITM defense
577
- * at X3DH first contact — an attacker who rewrites the bundle in transit cannot
578
- * forge this without the peer's Ed25519 signing private key.
579
- *
580
- * NOTE: this authenticates the bundle UNDER its signing identity. Pinning that
581
- * identity (safety numbers / TOFU) is a separate layer, tracked on 2342.
582
- */
583
- export function verifyPublicBundle(bundle: PublicPrekeyBundle): boolean {
584
- return verifyEd25519(
585
- bundle.signature,
586
- bundleSigningMessage(bundle.identityPublicKey, bundle.signedPrekey.publicKey),
587
- bundle.signingIdentityPublicKey,
588
- );
589
- }
590
-
591
- // ---- Envelope codec ----
592
-
593
- interface E2eeEnvelope {
594
- v: typeof E2EE_ENVELOPE_VERSION;
595
- /** Handshake header — present only on the initiator's first message. */
596
- hdr?: { ik: string; ek: string; opk?: number };
597
- /** Ratchet message index (strict in-order). */
598
- i: number;
599
- ct: EncryptedPayload;
600
- }
601
-
602
- /** v2 envelope: carries the DH ratchet header (dh/pn/n) instead of a flat index. */
603
- interface E2eeEnvelopeV2 {
604
- v: typeof E2EE_ENVELOPE_VERSION_V2;
605
- hdr?: { ik: string; ek: string; opk?: number };
606
- dh: string; // base64 ratchet public key
607
- pn: number;
608
- n: number;
609
- ct: EncryptedPayload;
610
- }
611
-
612
- /** Quick check whether on-wire bytes are an mDM E2EE envelope (v1 or v2). */
613
- export function isE2eeEnvelope(bytes: Uint8Array): boolean {
614
- try {
615
- const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
616
- if (!obj?.ct) return false;
617
- if (obj.v === E2EE_ENVELOPE_VERSION) return typeof obj.i === "number";
618
- if (obj.v === E2EE_ENVELOPE_VERSION_V2) return typeof obj.dh === "string" && typeof obj.n === "number";
619
- return false;
620
- } catch {
621
- return false;
622
- }
623
- }
624
-
625
- /** Read the envelope version without validating the rest. */
626
- function peekEnvelopeVersion(bytes: Uint8Array): string | undefined {
627
- try {
628
- return JSON.parse(Buffer.from(bytes).toString("utf8"))?.v;
629
- } catch {
630
- return undefined;
631
- }
632
- }
633
-
634
- function serializeEnvelope(env: E2eeEnvelope | E2eeEnvelopeV2): Uint8Array {
635
- return new Uint8Array(Buffer.from(JSON.stringify(env), "utf8"));
636
- }
637
-
638
- function parseEnvelope(bytes: Uint8Array): E2eeEnvelope {
639
- const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
640
- if (obj?.v !== E2EE_ENVELOPE_VERSION) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
641
- return obj as E2eeEnvelope;
642
- }
643
-
644
- function parseEnvelopeV2(bytes: Uint8Array): E2eeEnvelopeV2 {
645
- const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
646
- if (obj?.v !== E2EE_ENVELOPE_VERSION_V2) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
647
- return obj as E2eeEnvelopeV2;
648
- }
649
-
650
- // ---- Publish ----
651
-
652
- /** Serialize the local bundle and hand it to the provider's key directory. */
653
- export async function publishOwnPrekeys(
654
- keystore: MdmKeyStore,
655
- dm: DmProvider,
656
- ): Promise<{ oneTimePrekeyCount: number }> {
657
- const material = await keystore.getOwnMaterial();
658
- await dm.publishPrekeyBundle(serializePublicBundle(material));
659
- return { oneTimePrekeyCount: material.oneTimePrekeys.length };
660
- }
661
-
662
- // ---- Encrypt (send) ----
663
-
664
- /**
665
- * Seal `plaintext` for `peerId`, establishing an X3DH+ratchet session on first
666
- * contact (fetching the peer's published bundle via the provider). Returns the
667
- * opaque envelope bytes to hand to `dm.send`.
668
- */
669
- export async function encryptForPeer(
670
- keystore: MdmKeyStore,
671
- dm: DmProvider,
672
- peerId: string,
673
- plaintext: Uint8Array,
674
- ): Promise<Uint8Array> {
675
- let session = await keystore.getSession(peerId);
676
-
677
- if (!session) {
678
- const raw = await dm.fetchPrekeyBundle(peerId);
679
- if (!raw) {
680
- throw new Error(
681
- `Peer "${peerId}" has not published a prekey bundle yet, so an encrypted session cannot be established. ` +
682
- `Ask them to run mDM_publish_keys, or use mDM_send_unencrypted (deprecated) for the migration window.`,
683
- );
684
- }
685
- const peer = parsePublicBundle(raw);
686
- // MITM defense: reject a bundle whose self-signature doesn't verify before
687
- // we derive any key material from it.
688
- if (!verifyPublicBundle(peer)) {
689
- throw new Error(
690
- `Prekey bundle for "${peerId}" failed signature verification — refusing to start an ` +
691
- `encrypted session (possible tampering / man-in-the-middle).`,
692
- );
693
- }
694
- const own = await keystore.getOwnMaterial();
695
- const ephemeral = await generateX25519KeyPair();
696
- const opk = peer.oneTimePrekeys[0]; // pick one if offered
697
-
698
- const { rootKey } = await performX3dh(own.identity.privateKey, ephemeral.privateKey, {
699
- identityPublicKey: peer.identityPublicKey,
700
- signedPreKeyPublicKey: peer.signedPrekey.publicKey,
701
- oneTimePreKeyPublicKey: opk?.publicKey,
702
- });
703
- // New sessions use the DH ratchet (v2 / PCS). The initial remote ratchet key
704
- // is the peer's signed prekey (the X3DH→DR handoff). LINEAR-3409.
705
- const ratchet2 = await initRatchetInitiator(rootKey, peer.signedPrekey.publicKey);
706
- session = {
707
- ratchet2,
708
- role: "initiator",
709
- pendingHandshake: { ik: own.identity.publicKey, ek: ephemeral.publicKey, opkId: opk?.id },
710
- };
711
- }
712
-
713
- // v2 (DH ratchet) path for new + v2 sessions.
714
- if (session.ratchet2) {
715
- const { header, ct } = await ratchetEncrypt(session.ratchet2, plaintext);
716
- const env: E2eeEnvelopeV2 = {
717
- v: E2EE_ENVELOPE_VERSION_V2,
718
- dh: toBase64(header.dh),
719
- pn: header.pn,
720
- n: header.n,
721
- ct,
722
- };
723
- if (session.pendingHandshake) {
724
- env.hdr = {
725
- ik: toBase64(session.pendingHandshake.ik),
726
- ek: toBase64(session.pendingHandshake.ek),
727
- opk: session.pendingHandshake.opkId,
728
- };
729
- session.pendingHandshake = undefined;
730
- }
731
- await keystore.putSession(peerId, session);
732
- return serializeEnvelope(env);
733
- }
734
-
735
- // v1 (legacy symmetric) path — only for a session already established as v1.
736
- const step = await ratchetSend(session.ratchet!);
737
- const ct = await encryptBytes(step.messageKey, plaintext);
738
- const env: E2eeEnvelope = { v: E2EE_ENVELOPE_VERSION, i: step.messageIndex, ct };
739
- if (session.pendingHandshake && step.messageIndex === 0) {
740
- env.hdr = {
741
- ik: toBase64(session.pendingHandshake.ik),
742
- ek: toBase64(session.pendingHandshake.ek),
743
- opk: session.pendingHandshake.opkId,
744
- };
745
- }
746
- session.pendingHandshake = undefined;
747
- await keystore.putSession(peerId, session);
748
- return serializeEnvelope(env);
749
- }
750
-
751
- // ---- Decrypt (receive) ----
752
-
753
- /**
754
- * Open an envelope from `peerId`, running X3DH (responder) on the first message
755
- * to derive the shared root key. Returns the inner plaintext bytes.
756
- */
757
- /** Run X3DH (responder side) from a first-contact handshake header → shared root key. */
758
- async function responderRootKey(
759
- keystore: MdmKeyStore,
760
- hdr: { ik: string; ek: string; opk?: number },
761
- ): Promise<Uint8Array> {
762
- const own = await keystore.getOwnMaterial();
763
- let oneTimePreKeyPrivateKey: Uint8Array | undefined;
764
- if (hdr.opk !== undefined) {
765
- oneTimePreKeyPrivateKey = await keystore.takeOneTimePrekey(hdr.opk);
766
- if (!oneTimePreKeyPrivateKey) {
767
- throw new Error(`Handshake references one-time prekey ${hdr.opk} which is unknown or already consumed.`);
768
- }
769
- }
770
- const { rootKey } = await performX3dhResponder(
771
- {
772
- identityPrivateKey: own.identity.privateKey,
773
- signedPreKeyPrivateKey: own.signedPrekey.pair.privateKey,
774
- oneTimePreKeyPrivateKey,
775
- },
776
- {
777
- initiatorIdentityPublicKey: fromBase64(hdr.ik),
778
- initiatorEphemeralPublicKey: fromBase64(hdr.ek),
779
- usedOneTimePreKeyId: hdr.opk,
780
- },
781
- );
782
- return rootKey;
783
- }
784
-
785
- export async function decryptFromPeer(
786
- keystore: MdmKeyStore,
787
- peerId: string,
788
- envelopeBytes: Uint8Array,
789
- ): Promise<Uint8Array> {
790
- // v2 (DH ratchet / PCS) — LINEAR-3409.
791
- if (peekEnvelopeVersion(envelopeBytes) === E2EE_ENVELOPE_VERSION_V2) {
792
- const env = parseEnvelopeV2(envelopeBytes);
793
- let session = await keystore.getSession(peerId);
794
- if (!session) {
795
- if (!env.hdr) {
796
- throw new Error(`No session with "${peerId}" and the message carries no handshake header — cannot decrypt.`);
797
- }
798
- const rootKey = await responderRootKey(keystore, env.hdr);
799
- const own = await keystore.getOwnMaterial();
800
- const ratchet2 = await initRatchetResponder(rootKey, {
801
- publicKey: own.signedPrekey.pair.publicKey,
802
- privateKey: own.signedPrekey.pair.privateKey,
803
- });
804
- session = { ratchet2, role: "responder" };
805
- }
806
- if (!session.ratchet2) {
807
- throw new Error(`Received a v2 mDM envelope but the session with "${peerId}" is v1 — refusing to mix ratchets.`);
808
- }
809
- const plaintext = await ratchetDecrypt(
810
- session.ratchet2,
811
- { dh: fromBase64(env.dh), pn: env.pn, n: env.n },
812
- env.ct,
813
- );
814
- await keystore.putSession(peerId, session);
815
- return plaintext;
816
- }
817
-
818
- // v1 (legacy symmetric) — back-compat decode.
819
- const env = parseEnvelope(envelopeBytes);
820
- let session = await keystore.getSession(peerId);
821
- if (!session) {
822
- if (!env.hdr) {
823
- throw new Error(`No session with "${peerId}" and the message carries no handshake header — cannot decrypt.`);
824
- }
825
- const rootKey = await responderRootKey(keystore, env.hdr);
826
- const ratchet = await initializeRatchet(rootKey, "responder");
827
- session = { ratchet, role: "responder" };
828
- }
829
- if (!session.ratchet) {
830
- throw new Error(`Received a v1 mDM envelope but the session with "${peerId}" is v2 — refusing to mix ratchets.`);
831
- }
832
- const step = await ratchetReceive(session.ratchet);
833
- if (step.messageIndex !== env.i) {
834
- throw new Error(
835
- `Out-of-order mDM message (expected ratchet index ${step.messageIndex}, got ${env.i}). ` +
836
- `Skipped-key handling is a tracked follow-up (LINEAR-2357).`,
837
- );
838
- }
839
- const plaintext = await decryptBytes(step.messageKey, env.ct);
840
- await keystore.putSession(peerId, session);
841
- return plaintext;
842
- }
1
+ /**
2
+ * mDM end-to-end encryption — session layer (LINEAR-2357).
3
+ *
4
+ * Sits ABOVE the DmProvider. The provider moves opaque bytes; THIS module
5
+ * decides what those bytes are: an X3DH handshake + Double Ratchet ciphertext
6
+ * envelope, produced from `@mosadd/crypto` primitives.
7
+ *
8
+ * Flow (decision "1a" — prekey distribution rides the DmProvider):
9
+ * - Each peer publishes a prekey bundle via `dm.publishPrekeyBundle(bytes)`.
10
+ * - First contact: sender `dm.fetchPrekeyBundle(peer)` → X3DH (initiator) →
11
+ * Double Ratchet. The first ciphertext carries a handshake header
12
+ * (initiator IK + EK + consumed one-time-prekey id) so the recipient can
13
+ * run X3DH (responder) and derive the SAME root key.
14
+ * - Subsequent messages reuse the stored ratchet session (no header).
15
+ *
16
+ * SCOPE / known follow-ups (tracked on LINEAR-2357, NOT silently hidden):
17
+ * - Ratchet is strict in-order (no skipped-message keys) — fine for a single
18
+ * ordered thread; out-of-order/lossy transports need skipped-key handling.
19
+ * - Signed-prekey signature is carried but NOT yet verified (auth follow-up).
20
+ * - Initiator "glare" (both sides open simultaneously) not resolved.
21
+ * - Default keystore is in-memory (per-process); file/OS-keychain backing is
22
+ * a follow-up. The MdmKeyStore seam makes that a drop-in.
23
+ */
24
+
25
+ import {
26
+ decryptBytes,
27
+ deriveHkdfKey,
28
+ deriveSharedSecret,
29
+ encryptBytes,
30
+ generateEd25519KeyPair,
31
+ generateX25519KeyPair,
32
+ initializeRatchet,
33
+ performX3dh,
34
+ performX3dhResponder,
35
+ ratchetReceive,
36
+ ratchetSend,
37
+ signEd25519,
38
+ verifyEd25519,
39
+ toBase64,
40
+ fromBase64,
41
+ initRatchetInitiator,
42
+ initRatchetResponder,
43
+ ratchetEncrypt,
44
+ ratchetDecrypt,
45
+ type EncryptedPayload,
46
+ type RatchetState,
47
+ type DhRatchetState,
48
+ type SessionRole,
49
+ } from "@mosadd/crypto";
50
+ import type { DmProvider } from "@mosadd/providers";
51
+
52
+ export const PREKEY_BUNDLE_VERSION = "mosadd.prekeys.v1" as const;
53
+ /** Legacy symmetric-ratchet envelope (no PCS). Still DECODED for back-compat. */
54
+ export const E2EE_ENVELOPE_VERSION = "mosadd.e2ee.v1" as const;
55
+ /** Double-Ratchet-with-DH envelope — post-compromise security (LINEAR-3409). New sends use this. */
56
+ export const E2EE_ENVELOPE_VERSION_V2 = "mosadd.e2ee.v2" as const;
57
+
58
+ const DEFAULT_ONE_TIME_PREKEYS = 8;
59
+
60
+ // ---- Key material types ----
61
+
62
+ interface X25519Pair {
63
+ publicKey: Uint8Array;
64
+ privateKey: Uint8Array;
65
+ }
66
+
67
+ /** The local peer's long-term identity + prekeys (private halves included). */
68
+ export interface OwnPrekeyMaterial {
69
+ /** X25519 DH identity — used in X3DH. */
70
+ identity: X25519Pair;
71
+ /**
72
+ * Ed25519 SIGNING identity — the long-term key a peer pins out-of-band
73
+ * (the "safety number"). Signs the bundle so a network/radio MITM can't swap
74
+ * the signed prekey or DH identity in transit.
75
+ */
76
+ signingIdentity: { publicKey: Uint8Array; privateKey: Uint8Array };
77
+ signedPrekey: { id: number; pair: X25519Pair };
78
+ oneTimePrekeys: Array<{ id: number; pair: X25519Pair }>;
79
+ }
80
+
81
+ /** A peer's PUBLIC prekey bundle, as parsed off the wire. */
82
+ export interface PublicPrekeyBundle {
83
+ identityPublicKey: Uint8Array;
84
+ /** Ed25519 signing-identity public key the signature is verified against. */
85
+ signingIdentityPublicKey: Uint8Array;
86
+ signedPrekey: { id: number; publicKey: Uint8Array };
87
+ oneTimePrekeys: Array<{ id: number; publicKey: Uint8Array }>;
88
+ /** Ed25519 signature over (DH identity pub ‖ signed-prekey pub). */
89
+ signature: Uint8Array;
90
+ }
91
+
92
+ /**
93
+ * Persisted per-peer ratchet session. Plain data → trivially serializable.
94
+ * A session is either v1 (`ratchet`, symmetric) or v2 (`ratchet2`, DH ratchet /
95
+ * PCS). New sessions are v2; an existing v1 session keeps running v1.
96
+ */
97
+ export interface MdmSessionRecord {
98
+ ratchet?: RatchetState; // v1 (legacy symmetric)
99
+ ratchet2?: DhRatchetState; // v2 (DH ratchet, PCS — LINEAR-3409)
100
+ role: SessionRole;
101
+ /** Handshake header still owed to the peer (initiator only, until first send). */
102
+ pendingHandshake?: { ik: Uint8Array; ek: Uint8Array; opkId?: number };
103
+ }
104
+
105
+ /**
106
+ * Local custody of private key material + ratchet sessions. The default impl
107
+ * is in-memory; a host may inject a file- or keychain-backed implementation.
108
+ */
109
+ export interface MdmKeyStore {
110
+ /** Own identity + prekeys. Generated lazily on first access, then stable. */
111
+ getOwnMaterial(): Promise<OwnPrekeyMaterial>;
112
+ /** Consume (one-time) a prekey private by id. Returns undefined if unknown. */
113
+ takeOneTimePrekey(id: number): Promise<Uint8Array | undefined>;
114
+ getSession(peerId: string): Promise<MdmSessionRecord | undefined>;
115
+ putSession(peerId: string, record: MdmSessionRecord): Promise<void>;
116
+
117
+ /**
118
+ * OPTIONAL local "sent items" cache. The Double Ratchet is forward-secret and
119
+ * asymmetric: once we seal a message for a peer we cannot re-derive its
120
+ * plaintext from our own ratchet on read. So mDM_list cannot show the sender
121
+ * their OWN outgoing text unless we keep a local copy. These two methods are
122
+ * that copy — keyed by the provider-assigned message id.
123
+ *
124
+ * Honesty note: this is a LOCAL plaintext cache, not synced across devices.
125
+ * A second device (or a fresh process) won't have it and will fall back to a
126
+ * "<encrypted · sent by you>" marker. Cross-device sent-history sync is a
127
+ * tracked follow-up (would need an encrypt-to-self session). Optional so
128
+ * existing MdmKeyStore implementations keep compiling.
129
+ */
130
+ putSentMessage?(messageId: string, plaintext: Uint8Array): Promise<void>;
131
+ getSentMessage?(messageId: string): Promise<Uint8Array | undefined>;
132
+
133
+ /**
134
+ * OPTIONAL symmetric SELF-READ key (32 bytes), derived from the same recoverable
135
+ * seed as the identity. Present only on seed-backed keystores. With it the sender
136
+ * seals a copy of every outgoing DM to itself (`self_payload`, tag "s1.") that any
137
+ * process holding the same seed can open again — the cross-process answer to the
138
+ * "local sent-items cache only" note above. Null/absent = no self copy.
139
+ */
140
+ getSelfKeyBytes?(): Promise<Uint8Array | null>;
141
+ }
142
+
143
+ // ---- In-memory keystore (default) ----
144
+
145
+ export class InMemoryMdmKeyStore implements MdmKeyStore {
146
+ private material: OwnPrekeyMaterial | null = null;
147
+ private readonly oneTimeById = new Map<number, Uint8Array>();
148
+ private readonly sessions = new Map<string, MdmSessionRecord>();
149
+ private readonly sentMessages = new Map<string, Uint8Array>();
150
+
151
+ async getOwnMaterial(): Promise<OwnPrekeyMaterial> {
152
+ if (this.material) return this.material;
153
+ const identity = await generateX25519KeyPair();
154
+ const signingIdentity = await generateEd25519KeyPair();
155
+ const signedPrekeyPair = await generateX25519KeyPair();
156
+ const signedPrekey = { id: randomId(), pair: signedPrekeyPair };
157
+ const oneTimePrekeys: OwnPrekeyMaterial["oneTimePrekeys"] = [];
158
+ for (let i = 0; i < DEFAULT_ONE_TIME_PREKEYS; i += 1) {
159
+ const pair = await generateX25519KeyPair();
160
+ const id = randomId();
161
+ oneTimePrekeys.push({ id, pair });
162
+ this.oneTimeById.set(id, pair.privateKey);
163
+ }
164
+ this.material = { identity, signingIdentity, signedPrekey, oneTimePrekeys };
165
+ return this.material;
166
+ }
167
+
168
+ async takeOneTimePrekey(id: number): Promise<Uint8Array | undefined> {
169
+ const priv = this.oneTimeById.get(id);
170
+ if (priv) this.oneTimeById.delete(id); // one-time: consume on use
171
+ return priv;
172
+ }
173
+
174
+ async getSession(peerId: string): Promise<MdmSessionRecord | undefined> {
175
+ return this.sessions.get(peerId);
176
+ }
177
+
178
+ async putSession(peerId: string, record: MdmSessionRecord): Promise<void> {
179
+ this.sessions.set(peerId, record);
180
+ }
181
+
182
+ async putSentMessage(messageId: string, plaintext: Uint8Array): Promise<void> {
183
+ this.sentMessages.set(messageId, plaintext);
184
+ }
185
+
186
+ async getSentMessage(messageId: string): Promise<Uint8Array | undefined> {
187
+ return this.sentMessages.get(messageId);
188
+ }
189
+ }
190
+
191
+ function randomId(): number {
192
+ return crypto.getRandomValues(new Uint32Array(1))[0]!;
193
+ }
194
+
195
+ // ---- Seed-backed keystore: ONE stable identity, not a new one per call ----
196
+ //
197
+ // ⛔ WHY (measured 27.09.2026, LINEAR-6089 follow-up): the hosted gateway builds a fresh
198
+ // McpServer per HTTP request, so the default InMemoryMdmKeyStore minted a BRAND-NEW random
199
+ // identity for every single mDM_send. Every envelope carried an X3DH header from an identity
200
+ // that existed for one request and was never published — the sender could never read its own
201
+ // message again (no self_payload, no key), and the recipient's recoverable copy could not be
202
+ // written (it needs the sender's PUBLISHED identity). The app (mosADD f95557f) now says WHY such
203
+ // a bubble is unreadable; this is the source fix, so new messages are born readable.
204
+ //
205
+ // The fix mirrors the web client exactly (apps/web/src/lib/mdmKeyStore.ts, LINEAR-3521 P2): the
206
+ // whole identity is derived by HKDF from ONE recoverable 32-byte seed, with the SAME labels, zero
207
+ // one-time prekeys and signed-prekey id 1 — so the bundle is byte-identical on every process that
208
+ // knows the seed. The web takes its seed from the login secret; an MCP runtime has no password,
209
+ // its login secret IS the API key (`mosadd_sk_live_…`) — see deriveMdmSeedFromSecret below.
210
+
211
+ /** X25519 base point (u = 9, little-endian). X25519(k, 9) is exactly k's public key. */
212
+ const X25519_BASE_POINT = (() => {
213
+ const b = new Uint8Array(32);
214
+ b[0] = 9;
215
+ return b;
216
+ })();
217
+
218
+ /**
219
+ * Deterministic X25519 pair from a 32-byte seed (the seed IS the private scalar — same
220
+ * convention as the web's x25519KeyPairFromSeed). The published @mosadd/crypto has no
221
+ * seed constructor, so the public half is computed as X25519(seed, basepoint), which is the
222
+ * definition of the public key (the curve library clamps the scalar in both paths).
223
+ */
224
+ async function x25519PairFromSeed(seed: Uint8Array): Promise<X25519Pair> {
225
+ const privateKey = seed.length === 32 ? seed : seed.slice(0, 32);
226
+ const publicKey = await deriveSharedSecret(privateKey, X25519_BASE_POINT);
227
+ return { privateKey, publicKey };
228
+ }
229
+
230
+ const utf8 = new TextEncoder();
231
+
232
+ async function subSeed(seed: Uint8Array, label: string): Promise<Uint8Array> {
233
+ return deriveHkdfKey(seed, { info: utf8.encode(label), length: 32 });
234
+ }
235
+
236
+ /** Same derivation, same labels as the web's deriveOwnMaterialFromSeed — keep them in lockstep. */
237
+ export async function deriveOwnMaterialFromSeed(seed: Uint8Array): Promise<OwnPrekeyMaterial> {
238
+ const [idSeed, signSeed, spkSeed] = await Promise.all([
239
+ subSeed(seed, "mosadd-mdm-identity-x25519"),
240
+ subSeed(seed, "mosadd-mdm-signing-ed25519"),
241
+ subSeed(seed, "mosadd-mdm-signed-prekey-x25519"),
242
+ ]);
243
+ return {
244
+ identity: await x25519PairFromSeed(idSeed),
245
+ signingIdentity: await generateEd25519KeyPair(signSeed),
246
+ signedPrekey: { id: 1, pair: await x25519PairFromSeed(spkSeed) },
247
+ oneTimePrekeys: [],
248
+ };
249
+ }
250
+
251
+ /**
252
+ * The recoverable 32-byte seed of an MCP runtime, from its login secret (the API key).
253
+ * Same key → same identity on every gateway instance, every call, every restart. A rotated
254
+ * key is a new login secret and therefore a new identity — exactly like a changed PIN on web.
255
+ * Not escrow: nothing here is stored; whoever holds the key could already act as the account.
256
+ */
257
+ export async function deriveMdmSeedFromSecret(secret: string): Promise<Uint8Array> {
258
+ return deriveHkdfKey(utf8.encode(secret), {
259
+ salt: utf8.encode("mosadd-mcp-api-key"),
260
+ info: utf8.encode("mosadd-mdm-identity-seed"),
261
+ length: 32,
262
+ });
263
+ }
264
+
265
+ /**
266
+ * Keystore anchored to a recoverable seed. Identity, signing key and signed prekey are
267
+ * derived (stable); ratchet sessions and the sent cache stay in memory for this process.
268
+ * No one-time prekeys: a stateless process could never remember which ones were consumed.
269
+ */
270
+ export class SeededMdmKeyStore implements MdmKeyStore {
271
+ private material: Promise<OwnPrekeyMaterial> | null = null;
272
+ private readonly sessions = new Map<string, MdmSessionRecord>();
273
+ private readonly sentMessages = new Map<string, Uint8Array>();
274
+
275
+ constructor(private readonly seed: Uint8Array) {
276
+ if (!seed || seed.length < 32) throw new Error("SeededMdmKeyStore needs a 32-byte seed");
277
+ }
278
+
279
+ static async fromSecret(secret: string): Promise<SeededMdmKeyStore> {
280
+ return new SeededMdmKeyStore(await deriveMdmSeedFromSecret(secret));
281
+ }
282
+
283
+ getOwnMaterial(): Promise<OwnPrekeyMaterial> {
284
+ if (!this.material) this.material = deriveOwnMaterialFromSeed(this.seed);
285
+ return this.material;
286
+ }
287
+
288
+ async takeOneTimePrekey(_id: number): Promise<Uint8Array | undefined> {
289
+ return undefined; // the seeded bundle publishes none
290
+ }
291
+
292
+ async getSession(peerId: string): Promise<MdmSessionRecord | undefined> {
293
+ return this.sessions.get(peerId);
294
+ }
295
+
296
+ async putSession(peerId: string, record: MdmSessionRecord): Promise<void> {
297
+ this.sessions.set(peerId, record);
298
+ }
299
+
300
+ async putSentMessage(messageId: string, plaintext: Uint8Array): Promise<void> {
301
+ this.sentMessages.set(messageId, plaintext);
302
+ }
303
+
304
+ async getSentMessage(messageId: string): Promise<Uint8Array | undefined> {
305
+ return this.sentMessages.get(messageId);
306
+ }
307
+
308
+ /** Same label as the web's getSelfKeyBytes ("mosadd-mdm-self-read"). */
309
+ async getSelfKeyBytes(): Promise<Uint8Array | null> {
310
+ return deriveHkdfKey(this.seed, { info: utf8.encode("mosadd-mdm-self-read"), length: 32 });
311
+ }
312
+ }
313
+
314
+ /**
315
+ * A keystore that derives its seed lazily from a secret — lets a synchronous factory
316
+ * (defaultProviders) hand out a stable-identity keystore without awaiting HKDF up front.
317
+ */
318
+ export class SecretMdmKeyStore implements MdmKeyStore {
319
+ private inner: Promise<SeededMdmKeyStore> | null = null;
320
+ constructor(private readonly secret: string) {}
321
+ private store(): Promise<SeededMdmKeyStore> {
322
+ if (!this.inner) this.inner = SeededMdmKeyStore.fromSecret(this.secret);
323
+ return this.inner;
324
+ }
325
+ async getOwnMaterial() { return (await this.store()).getOwnMaterial(); }
326
+ async takeOneTimePrekey(id: number) { return (await this.store()).takeOneTimePrekey(id); }
327
+ async getSession(peerId: string) { return (await this.store()).getSession(peerId); }
328
+ async putSession(peerId: string, record: MdmSessionRecord) { return (await this.store()).putSession(peerId, record); }
329
+ async putSentMessage(messageId: string, plaintext: Uint8Array) { return (await this.store()).putSentMessage(messageId, plaintext); }
330
+ async getSentMessage(messageId: string) { return (await this.store()).getSentMessage(messageId); }
331
+ async getSelfKeyBytes() { return (await this.store()).getSelfKeyBytes(); }
332
+ }
333
+
334
+ // ---- Recoverable copies: the web's wire format, byte for byte ----
335
+ //
336
+ // Two opaque AES-GCM strings ride next to the ratchet envelope in `messages`:
337
+ // self_payload "s1." + b64(iv‖ct) — sealed to the SENDER's self-read key
338
+ // recipient_self_payload "r1." + b64(iv‖ct) — sealed to HKDF(ECDH(sender IK, recipient IK))
339
+ // Formats, tags and HKDF labels are copied from apps/web/src/lib/mdmE2ee.ts (sealForSelf /
340
+ // sealForPeerRecoverable) — the app opens exactly these. The server never reads them.
341
+
342
+ const SELF_TAG = "s1.";
343
+ const PEER_RECOVERABLE_TAG = "r1.";
344
+ const PEER_RECOVERABLE_INFO = "mosadd.mdm.recipient-recoverable.v1";
345
+
346
+ async function aesGcmSeal(tag: string, keyBytes: Uint8Array, plaintext: Uint8Array): Promise<string> {
347
+ const key = await crypto.subtle.importKey("raw", keyBytes as BufferSource, { name: "AES-GCM" }, false, ["encrypt"]);
348
+ const iv = crypto.getRandomValues(new Uint8Array(12));
349
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, plaintext as BufferSource));
350
+ const packed = new Uint8Array(iv.length + ct.length);
351
+ packed.set(iv, 0);
352
+ packed.set(ct, iv.length);
353
+ return tag + toBase64(packed);
354
+ }
355
+
356
+ async function aesGcmOpen(tag: string, keyBytes: Uint8Array, sealed: string): Promise<Uint8Array | null> {
357
+ if (!sealed.startsWith(tag)) return null;
358
+ const packed = fromBase64(sealed.slice(tag.length));
359
+ if (packed.length <= 12) return null;
360
+ const key = await crypto.subtle.importKey("raw", keyBytes as BufferSource, { name: "AES-GCM" }, false, ["decrypt"]);
361
+ const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: packed.slice(0, 12) }, key, packed.slice(12));
362
+ return new Uint8Array(pt);
363
+ }
364
+
365
+ /** Sender's own copy ("s1."). Null when the keystore has no seed. Never throws. */
366
+ export async function sealForSelf(keystore: MdmKeyStore, plaintext: Uint8Array): Promise<string | null> {
367
+ try {
368
+ const keyBytes = (await keystore.getSelfKeyBytes?.()) ?? null;
369
+ if (!keyBytes) return null;
370
+ return await aesGcmSeal(SELF_TAG, keyBytes, plaintext);
371
+ } catch {
372
+ return null;
373
+ }
374
+ }
375
+
376
+ /** Open an "s1." copy with this keystore's self-read key. Null when absent/foreign. Never throws. */
377
+ export async function openSelfSealed(keystore: MdmKeyStore, sealed: string | null | undefined): Promise<Uint8Array | null> {
378
+ try {
379
+ if (!sealed) return null;
380
+ const keyBytes = (await keystore.getSelfKeyBytes?.()) ?? null;
381
+ if (!keyBytes) return null;
382
+ return await aesGcmOpen(SELF_TAG, keyBytes, sealed);
383
+ } catch {
384
+ return null;
385
+ }
386
+ }
387
+
388
+ async function pairKey(keystore: MdmKeyStore, otherIdentityPublicKey: Uint8Array): Promise<Uint8Array> {
389
+ const own = await keystore.getOwnMaterial();
390
+ const secret = await deriveSharedSecret(own.identity.privateKey, otherIdentityPublicKey);
391
+ return deriveHkdfKey(secret, { info: utf8.encode(PEER_RECOVERABLE_INFO), length: 32 });
392
+ }
393
+
394
+ /** Recipient-openable copy ("r1.") for a VERIFIED peer bundle. Never throws. */
395
+ export async function sealForPeerRecoverable(
396
+ keystore: MdmKeyStore,
397
+ peer: PublicPrekeyBundle,
398
+ plaintext: Uint8Array,
399
+ ): Promise<string | null> {
400
+ try {
401
+ return await aesGcmSeal(PEER_RECOVERABLE_TAG, await pairKey(keystore, peer.identityPublicKey), plaintext);
402
+ } catch {
403
+ return null;
404
+ }
405
+ }
406
+
407
+ /** Open an "r1." copy written by the peer whose VERIFIED bundle is given. Never throws. */
408
+ export async function openPeerRecoverable(
409
+ keystore: MdmKeyStore,
410
+ sender: PublicPrekeyBundle,
411
+ sealed: string | null | undefined,
412
+ ): Promise<Uint8Array | null> {
413
+ try {
414
+ if (!sealed) return null;
415
+ return await aesGcmOpen(PEER_RECOVERABLE_TAG, await pairKey(keystore, sender.identityPublicKey), sealed);
416
+ } catch {
417
+ return null;
418
+ }
419
+ }
420
+
421
+ /** Fetch + parse + signature-check a peer bundle. Null when absent or failing verification. */
422
+ export async function fetchVerifiedBundle(dm: DmProvider, peerId: string): Promise<PublicPrekeyBundle | null> {
423
+ const raw = await dm.fetchPrekeyBundle(peerId);
424
+ if (!raw) return null;
425
+ const parsed = parsePublicBundle(raw);
426
+ return verifyPublicBundle(parsed) ? parsed : null;
427
+ }
428
+
429
+ function sameBytes(a: Uint8Array, b: Uint8Array): boolean {
430
+ if (a.length !== b.length) return false;
431
+ for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
432
+ return true;
433
+ }
434
+
435
+ export type OwnBundleState =
436
+ /** the directory already holds exactly our identity */
437
+ | "consistent"
438
+ /** the directory had no bundle (or we own the identity) and now holds ours */
439
+ | "published"
440
+ /** someone else's key material is published for this identity and we must not replace it */
441
+ | "foreign"
442
+ /** the directory holds NO bundle for this identity and this runtime may not create one */
443
+ | "absent";
444
+
445
+ /** What this runtime may write to the key directory for its own identity. */
446
+ export interface BundlePolicy {
447
+ /** directory empty → publish this keystore's bundle */
448
+ mayPublishWhenEmpty: boolean;
449
+ /** directory holds a DIFFERENT bundle → replace it with this keystore's */
450
+ mayReplaceForeign: boolean;
451
+ }
452
+
453
+ /**
454
+ * ⛔ WHO MAY WRITE THE KEY DIRECTORY FROM MCP (27.09.2026, poprawka po weryfikacji toru mdm-brama).
455
+ *
456
+ * The MCP identity is seeded from ONE API key. A mosADD identity has MANY active keys (every OAuth
457
+ * connector mints its own — measured 27.09: 7 of 17 agent identities hold several, general@ alone
458
+ * 8, all used within 3 days). A per-key identity that is allowed to (re)publish therefore makes the
459
+ * directory FLAP between up to 8 identities: copies sealed under key A stop opening once key B
460
+ * published, and envelopes sealed to "the" bundle open on one key only. So:
461
+ *
462
+ * - kind "agent": an agent LINE sends JAWNIE (plaintext) — rozkaz Króla 20.09 12:56Z „E2EE
463
+ * wewnętrzne = zero": linie↔linie, linie↔Król, człowiek→linia bez E2EE; the app does the same
464
+ * (ircApi.ts peerIsAgent). An agent never needs a bundle for mDM_send, so the AUTOMATIC paths
465
+ * write nothing. Only an explicit mDM_publish_keys still publishes (the caller asked for it).
466
+ * - kind "human": the person's bundle is anchored to their login secret IN THE APP
467
+ * (mdmKeyStore.setIdentitySeed; kanon in hub-key-exchange: only the identity's own client
468
+ * publishes). MCP never replaces it and never pre-empts it on an empty directory automatically
469
+ * — a bundle published from an API-key seed would be overwritten by the app later and strand
470
+ * everything sealed to it meanwhile. Explicit mDM_publish_keys may fill an EMPTY directory.
471
+ * - unknown kind (non-Supabase lanes, e.g. radio): the pre-27.09 behaviour, empty → publish;
472
+ * explicit → publish.
473
+ */
474
+ export function bundlePolicyForKind(kind: string | null | undefined, opts: { explicit: boolean }): BundlePolicy {
475
+ if (kind === "agent") {
476
+ return opts.explicit
477
+ ? { mayPublishWhenEmpty: true, mayReplaceForeign: true }
478
+ : { mayPublishWhenEmpty: false, mayReplaceForeign: false };
479
+ }
480
+ if (kind === "human") {
481
+ return { mayPublishWhenEmpty: opts.explicit, mayReplaceForeign: false };
482
+ }
483
+ return { mayPublishWhenEmpty: true, mayReplaceForeign: opts.explicit };
484
+ }
485
+
486
+ /**
487
+ * Make the key directory agree with this keystore's identity — only as far as `policy` allows.
488
+ *
489
+ * - directory == ours → "consistent" (no write).
490
+ * - directory empty, may publish → publish ours → "published".
491
+ * - directory empty, may not → "absent" (no write).
492
+ * - directory differs, may replace → publish ours → "published".
493
+ * - directory differs, may not → "foreign" (no write). The ratchet envelope still
494
+ * works (it carries its own handshake); recoverable copies are skipped, because they would
495
+ * be sealed under an identity nobody can look up.
496
+ */
497
+ export async function ensureOwnBundlePublished(
498
+ keystore: MdmKeyStore,
499
+ dm: DmProvider,
500
+ selfId: string,
501
+ policy: BundlePolicy,
502
+ ): Promise<OwnBundleState> {
503
+ const own = await keystore.getOwnMaterial();
504
+ const raw = await dm.fetchPrekeyBundle(selfId);
505
+ if (raw) {
506
+ let published: PublicPrekeyBundle | null = null;
507
+ try { published = parsePublicBundle(raw); } catch { published = null; }
508
+ if (
509
+ published &&
510
+ sameBytes(published.identityPublicKey, own.identity.publicKey) &&
511
+ sameBytes(published.signingIdentityPublicKey, own.signingIdentity.publicKey) &&
512
+ sameBytes(published.signedPrekey.publicKey, own.signedPrekey.pair.publicKey)
513
+ ) {
514
+ return "consistent";
515
+ }
516
+ if (!policy.mayReplaceForeign) return "foreign";
517
+ } else if (!policy.mayPublishWhenEmpty) {
518
+ return "absent";
519
+ }
520
+ await dm.publishPrekeyBundle(serializePublicBundle(own));
521
+ return "published";
522
+ }
523
+
524
+ // ---- Bundle codec (opaque bytes the provider moves) ----
525
+
526
+ /**
527
+ * The exact bytes signed by / verified against the Ed25519 signing identity:
528
+ * the DH identity public key concatenated with the signed-prekey public key.
529
+ * Binding both means a MITM cannot swap either without invalidating the sig.
530
+ */
531
+ function bundleSigningMessage(dhIdentityPub: Uint8Array, signedPrekeyPub: Uint8Array): Uint8Array {
532
+ const msg = new Uint8Array(dhIdentityPub.length + signedPrekeyPub.length);
533
+ msg.set(dhIdentityPub, 0);
534
+ msg.set(signedPrekeyPub, dhIdentityPub.length);
535
+ return msg;
536
+ }
537
+
538
+ export function serializePublicBundle(material: OwnPrekeyMaterial): Uint8Array {
539
+ const signature = signEd25519(
540
+ material.signingIdentity.privateKey,
541
+ bundleSigningMessage(material.identity.publicKey, material.signedPrekey.pair.publicKey),
542
+ );
543
+ const json = JSON.stringify({
544
+ v: PREKEY_BUNDLE_VERSION,
545
+ ik: toBase64(material.identity.publicKey),
546
+ sik: toBase64(material.signingIdentity.publicKey),
547
+ spk: { id: material.signedPrekey.id, pub: toBase64(material.signedPrekey.pair.publicKey) },
548
+ opks: material.oneTimePrekeys.map((k) => ({ id: k.id, pub: toBase64(k.pair.publicKey) })),
549
+ sig: toBase64(signature),
550
+ });
551
+ return new Uint8Array(Buffer.from(json, "utf8"));
552
+ }
553
+
554
+ export function parsePublicBundle(bytes: Uint8Array): PublicPrekeyBundle {
555
+ const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
556
+ if (obj?.v !== PREKEY_BUNDLE_VERSION) {
557
+ throw new Error(`Unsupported prekey bundle version: ${obj?.v}`);
558
+ }
559
+ if (typeof obj.sik !== "string" || typeof obj.sig !== "string") {
560
+ throw new Error("Prekey bundle is missing its signing identity / signature.");
561
+ }
562
+ return {
563
+ identityPublicKey: fromBase64(obj.ik),
564
+ signingIdentityPublicKey: fromBase64(obj.sik),
565
+ signedPrekey: { id: obj.spk.id, publicKey: fromBase64(obj.spk.pub) },
566
+ oneTimePrekeys: (obj.opks ?? []).map((k: { id: number; pub: string }) => ({
567
+ id: k.id,
568
+ publicKey: fromBase64(k.pub),
569
+ })),
570
+ signature: fromBase64(obj.sig),
571
+ };
572
+ }
573
+
574
+ /**
575
+ * Verify the bundle's self-signature: the signing identity must have signed
576
+ * (DH identity ‖ signed prekey). Rejecting a bad signature is the MITM defense
577
+ * at X3DH first contact — an attacker who rewrites the bundle in transit cannot
578
+ * forge this without the peer's Ed25519 signing private key.
579
+ *
580
+ * NOTE: this authenticates the bundle UNDER its signing identity. Pinning that
581
+ * identity (safety numbers / TOFU) is a separate layer, tracked on 2342.
582
+ */
583
+ export function verifyPublicBundle(bundle: PublicPrekeyBundle): boolean {
584
+ return verifyEd25519(
585
+ bundle.signature,
586
+ bundleSigningMessage(bundle.identityPublicKey, bundle.signedPrekey.publicKey),
587
+ bundle.signingIdentityPublicKey,
588
+ );
589
+ }
590
+
591
+ // ---- Envelope codec ----
592
+
593
+ interface E2eeEnvelope {
594
+ v: typeof E2EE_ENVELOPE_VERSION;
595
+ /** Handshake header — present only on the initiator's first message. */
596
+ hdr?: { ik: string; ek: string; opk?: number };
597
+ /** Ratchet message index (strict in-order). */
598
+ i: number;
599
+ ct: EncryptedPayload;
600
+ }
601
+
602
+ /** v2 envelope: carries the DH ratchet header (dh/pn/n) instead of a flat index. */
603
+ interface E2eeEnvelopeV2 {
604
+ v: typeof E2EE_ENVELOPE_VERSION_V2;
605
+ hdr?: { ik: string; ek: string; opk?: number };
606
+ dh: string; // base64 ratchet public key
607
+ pn: number;
608
+ n: number;
609
+ ct: EncryptedPayload;
610
+ }
611
+
612
+ /** Quick check whether on-wire bytes are an mDM E2EE envelope (v1 or v2). */
613
+ export function isE2eeEnvelope(bytes: Uint8Array): boolean {
614
+ try {
615
+ const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
616
+ if (!obj?.ct) return false;
617
+ if (obj.v === E2EE_ENVELOPE_VERSION) return typeof obj.i === "number";
618
+ if (obj.v === E2EE_ENVELOPE_VERSION_V2) return typeof obj.dh === "string" && typeof obj.n === "number";
619
+ return false;
620
+ } catch {
621
+ return false;
622
+ }
623
+ }
624
+
625
+ /** Read the envelope version without validating the rest. */
626
+ function peekEnvelopeVersion(bytes: Uint8Array): string | undefined {
627
+ try {
628
+ return JSON.parse(Buffer.from(bytes).toString("utf8"))?.v;
629
+ } catch {
630
+ return undefined;
631
+ }
632
+ }
633
+
634
+ function serializeEnvelope(env: E2eeEnvelope | E2eeEnvelopeV2): Uint8Array {
635
+ return new Uint8Array(Buffer.from(JSON.stringify(env), "utf8"));
636
+ }
637
+
638
+ function parseEnvelope(bytes: Uint8Array): E2eeEnvelope {
639
+ const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
640
+ if (obj?.v !== E2EE_ENVELOPE_VERSION) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
641
+ return obj as E2eeEnvelope;
642
+ }
643
+
644
+ function parseEnvelopeV2(bytes: Uint8Array): E2eeEnvelopeV2 {
645
+ const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
646
+ if (obj?.v !== E2EE_ENVELOPE_VERSION_V2) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
647
+ return obj as E2eeEnvelopeV2;
648
+ }
649
+
650
+ // ---- Publish ----
651
+
652
+ /** Serialize the local bundle and hand it to the provider's key directory. */
653
+ export async function publishOwnPrekeys(
654
+ keystore: MdmKeyStore,
655
+ dm: DmProvider,
656
+ ): Promise<{ oneTimePrekeyCount: number }> {
657
+ const material = await keystore.getOwnMaterial();
658
+ await dm.publishPrekeyBundle(serializePublicBundle(material));
659
+ return { oneTimePrekeyCount: material.oneTimePrekeys.length };
660
+ }
661
+
662
+ // ---- Encrypt (send) ----
663
+
664
+ /**
665
+ * Seal `plaintext` for `peerId`, establishing an X3DH+ratchet session on first
666
+ * contact (fetching the peer's published bundle via the provider). Returns the
667
+ * opaque envelope bytes to hand to `dm.send`.
668
+ */
669
+ export async function encryptForPeer(
670
+ keystore: MdmKeyStore,
671
+ dm: DmProvider,
672
+ peerId: string,
673
+ plaintext: Uint8Array,
674
+ ): Promise<Uint8Array> {
675
+ let session = await keystore.getSession(peerId);
676
+
677
+ if (!session) {
678
+ const raw = await dm.fetchPrekeyBundle(peerId);
679
+ if (!raw) {
680
+ throw new Error(
681
+ `Peer "${peerId}" has not published a prekey bundle yet, so an encrypted session cannot be established. ` +
682
+ `Ask them to run mDM_publish_keys, or use mDM_send_unencrypted (deprecated) for the migration window.`,
683
+ );
684
+ }
685
+ const peer = parsePublicBundle(raw);
686
+ // MITM defense: reject a bundle whose self-signature doesn't verify before
687
+ // we derive any key material from it.
688
+ if (!verifyPublicBundle(peer)) {
689
+ throw new Error(
690
+ `Prekey bundle for "${peerId}" failed signature verification — refusing to start an ` +
691
+ `encrypted session (possible tampering / man-in-the-middle).`,
692
+ );
693
+ }
694
+ const own = await keystore.getOwnMaterial();
695
+ const ephemeral = await generateX25519KeyPair();
696
+ const opk = peer.oneTimePrekeys[0]; // pick one if offered
697
+
698
+ const { rootKey } = await performX3dh(own.identity.privateKey, ephemeral.privateKey, {
699
+ identityPublicKey: peer.identityPublicKey,
700
+ signedPreKeyPublicKey: peer.signedPrekey.publicKey,
701
+ oneTimePreKeyPublicKey: opk?.publicKey,
702
+ });
703
+ // New sessions use the DH ratchet (v2 / PCS). The initial remote ratchet key
704
+ // is the peer's signed prekey (the X3DH→DR handoff). LINEAR-3409.
705
+ const ratchet2 = await initRatchetInitiator(rootKey, peer.signedPrekey.publicKey);
706
+ session = {
707
+ ratchet2,
708
+ role: "initiator",
709
+ pendingHandshake: { ik: own.identity.publicKey, ek: ephemeral.publicKey, opkId: opk?.id },
710
+ };
711
+ }
712
+
713
+ // v2 (DH ratchet) path for new + v2 sessions.
714
+ if (session.ratchet2) {
715
+ const { header, ct } = await ratchetEncrypt(session.ratchet2, plaintext);
716
+ const env: E2eeEnvelopeV2 = {
717
+ v: E2EE_ENVELOPE_VERSION_V2,
718
+ dh: toBase64(header.dh),
719
+ pn: header.pn,
720
+ n: header.n,
721
+ ct,
722
+ };
723
+ if (session.pendingHandshake) {
724
+ env.hdr = {
725
+ ik: toBase64(session.pendingHandshake.ik),
726
+ ek: toBase64(session.pendingHandshake.ek),
727
+ opk: session.pendingHandshake.opkId,
728
+ };
729
+ session.pendingHandshake = undefined;
730
+ }
731
+ await keystore.putSession(peerId, session);
732
+ return serializeEnvelope(env);
733
+ }
734
+
735
+ // v1 (legacy symmetric) path — only for a session already established as v1.
736
+ const step = await ratchetSend(session.ratchet!);
737
+ const ct = await encryptBytes(step.messageKey, plaintext);
738
+ const env: E2eeEnvelope = { v: E2EE_ENVELOPE_VERSION, i: step.messageIndex, ct };
739
+ if (session.pendingHandshake && step.messageIndex === 0) {
740
+ env.hdr = {
741
+ ik: toBase64(session.pendingHandshake.ik),
742
+ ek: toBase64(session.pendingHandshake.ek),
743
+ opk: session.pendingHandshake.opkId,
744
+ };
745
+ }
746
+ session.pendingHandshake = undefined;
747
+ await keystore.putSession(peerId, session);
748
+ return serializeEnvelope(env);
749
+ }
750
+
751
+ // ---- Decrypt (receive) ----
752
+
753
+ /**
754
+ * Open an envelope from `peerId`, running X3DH (responder) on the first message
755
+ * to derive the shared root key. Returns the inner plaintext bytes.
756
+ */
757
+ /** Run X3DH (responder side) from a first-contact handshake header → shared root key. */
758
+ async function responderRootKey(
759
+ keystore: MdmKeyStore,
760
+ hdr: { ik: string; ek: string; opk?: number },
761
+ ): Promise<Uint8Array> {
762
+ const own = await keystore.getOwnMaterial();
763
+ let oneTimePreKeyPrivateKey: Uint8Array | undefined;
764
+ if (hdr.opk !== undefined) {
765
+ oneTimePreKeyPrivateKey = await keystore.takeOneTimePrekey(hdr.opk);
766
+ if (!oneTimePreKeyPrivateKey) {
767
+ throw new Error(`Handshake references one-time prekey ${hdr.opk} which is unknown or already consumed.`);
768
+ }
769
+ }
770
+ const { rootKey } = await performX3dhResponder(
771
+ {
772
+ identityPrivateKey: own.identity.privateKey,
773
+ signedPreKeyPrivateKey: own.signedPrekey.pair.privateKey,
774
+ oneTimePreKeyPrivateKey,
775
+ },
776
+ {
777
+ initiatorIdentityPublicKey: fromBase64(hdr.ik),
778
+ initiatorEphemeralPublicKey: fromBase64(hdr.ek),
779
+ usedOneTimePreKeyId: hdr.opk,
780
+ },
781
+ );
782
+ return rootKey;
783
+ }
784
+
785
+ export async function decryptFromPeer(
786
+ keystore: MdmKeyStore,
787
+ peerId: string,
788
+ envelopeBytes: Uint8Array,
789
+ ): Promise<Uint8Array> {
790
+ // v2 (DH ratchet / PCS) — LINEAR-3409.
791
+ if (peekEnvelopeVersion(envelopeBytes) === E2EE_ENVELOPE_VERSION_V2) {
792
+ const env = parseEnvelopeV2(envelopeBytes);
793
+ let session = await keystore.getSession(peerId);
794
+ if (!session) {
795
+ if (!env.hdr) {
796
+ throw new Error(`No session with "${peerId}" and the message carries no handshake header — cannot decrypt.`);
797
+ }
798
+ const rootKey = await responderRootKey(keystore, env.hdr);
799
+ const own = await keystore.getOwnMaterial();
800
+ const ratchet2 = await initRatchetResponder(rootKey, {
801
+ publicKey: own.signedPrekey.pair.publicKey,
802
+ privateKey: own.signedPrekey.pair.privateKey,
803
+ });
804
+ session = { ratchet2, role: "responder" };
805
+ }
806
+ if (!session.ratchet2) {
807
+ throw new Error(`Received a v2 mDM envelope but the session with "${peerId}" is v1 — refusing to mix ratchets.`);
808
+ }
809
+ const plaintext = await ratchetDecrypt(
810
+ session.ratchet2,
811
+ { dh: fromBase64(env.dh), pn: env.pn, n: env.n },
812
+ env.ct,
813
+ );
814
+ await keystore.putSession(peerId, session);
815
+ return plaintext;
816
+ }
817
+
818
+ // v1 (legacy symmetric) — back-compat decode.
819
+ const env = parseEnvelope(envelopeBytes);
820
+ let session = await keystore.getSession(peerId);
821
+ if (!session) {
822
+ if (!env.hdr) {
823
+ throw new Error(`No session with "${peerId}" and the message carries no handshake header — cannot decrypt.`);
824
+ }
825
+ const rootKey = await responderRootKey(keystore, env.hdr);
826
+ const ratchet = await initializeRatchet(rootKey, "responder");
827
+ session = { ratchet, role: "responder" };
828
+ }
829
+ if (!session.ratchet) {
830
+ throw new Error(`Received a v1 mDM envelope but the session with "${peerId}" is v2 — refusing to mix ratchets.`);
831
+ }
832
+ const step = await ratchetReceive(session.ratchet);
833
+ if (step.messageIndex !== env.i) {
834
+ throw new Error(
835
+ `Out-of-order mDM message (expected ratchet index ${step.messageIndex}, got ${env.i}). ` +
836
+ `Skipped-key handling is a tracked follow-up (LINEAR-2357).`,
837
+ );
838
+ }
839
+ const plaintext = await decryptBytes(step.messageKey, env.ct);
840
+ await keystore.putSession(peerId, session);
841
+ return plaintext;
842
+ }