@mosadd/mcp 3.0.0-alpha.6 → 3.0.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 (66) hide show
  1. package/CHANGELOG.md +410 -0
  2. package/README.md +79 -40
  3. package/dist/bin/mcp.js +132 -8
  4. package/dist/chunk-VMMJJYXF.js +4233 -0
  5. package/dist/index.d.ts +110 -6
  6. package/dist/index.js +3 -1
  7. package/package.json +19 -16
  8. package/src/__tests__/blob-upload.test.ts +93 -0
  9. package/src/__tests__/channel-e2ee.test.ts +62 -0
  10. package/src/__tests__/cli.test.ts +47 -0
  11. package/src/__tests__/flota-jawnie.test.ts +244 -0
  12. package/src/__tests__/golden-path.test.ts +4 -2
  13. package/src/__tests__/integration.test.ts +50 -11
  14. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  15. package/src/__tests__/label-room-owner.test.ts +22 -0
  16. package/src/__tests__/mdm-e2ee.test.ts +35 -1
  17. package/src/__tests__/mdm-mcp-readable.test.ts +390 -0
  18. package/src/__tests__/mirc-invite.test.ts +112 -0
  19. package/src/__tests__/mrag-search-answer.test.ts +42 -0
  20. package/src/__tests__/no-dead-host.test.ts +37 -0
  21. package/src/__tests__/presence.test.ts +199 -0
  22. package/src/__tests__/server.test.ts +11 -7
  23. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  24. package/src/__tests__/tool-count-consistency.test.ts +259 -0
  25. package/src/__tests__/voice-fields.test.ts +24 -0
  26. package/src/bin/mcp.ts +71 -6
  27. package/src/cli.ts +100 -0
  28. package/src/crypto/channel-e2ee.ts +288 -0
  29. package/src/crypto/mdm-session.ts +476 -37
  30. package/src/index.ts +2 -2
  31. package/src/providers/blob-upload.ts +162 -0
  32. package/src/providers/supabase-dm.ts +102 -7
  33. package/src/providers/supabase-voice.ts +13 -1
  34. package/src/providers/supabase.ts +121 -10
  35. package/src/server.ts +102 -12
  36. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  37. package/src/tools/actions.ts +166 -0
  38. package/src/tools/attachments.ts +276 -0
  39. package/src/tools/capabilities.ts +2 -0
  40. package/src/tools/channel-payload.ts +69 -0
  41. package/src/tools/embed.ts +110 -0
  42. package/src/tools/index.ts +136 -6
  43. package/src/tools/knowledge-graph.ts +186 -0
  44. package/src/tools/knowledge.ts +351 -132
  45. package/src/tools/mail-agentbox.ts +155 -0
  46. package/src/tools/mail-aliases.ts +25 -0
  47. package/src/tools/mail-provenance.ts +137 -0
  48. package/src/tools/mail.ts +284 -38
  49. package/src/tools/mdm-as-agent.ts +138 -0
  50. package/src/tools/mdm-voice.ts +17 -3
  51. package/src/tools/mdm.ts +303 -57
  52. package/src/tools/mirc-edge.ts +8 -2
  53. package/src/tools/mirc-members.ts +130 -20
  54. package/src/tools/mirc-messages.ts +80 -35
  55. package/src/tools/mirc.ts +149 -11
  56. package/src/tools/mroom-messages.ts +4 -12
  57. package/src/tools/mtalk.ts +11 -1
  58. package/src/tools/murl.ts +314 -0
  59. package/src/tools/presence.ts +442 -0
  60. package/src/tools/ptt-ingest.ts +99 -0
  61. package/src/tools/threat.ts +123 -0
  62. package/src/tools/voice-format.ts +43 -0
  63. package/src/types.ts +36 -0
  64. package/src/version.ts +8 -0
  65. package/LICENSE +0 -201
  66. package/dist/chunk-KAPG5FBN.js +0 -1844
@@ -24,6 +24,8 @@
24
24
 
25
25
  import {
26
26
  decryptBytes,
27
+ deriveHkdfKey,
28
+ deriveSharedSecret,
27
29
  encryptBytes,
28
30
  generateEd25519KeyPair,
29
31
  generateX25519KeyPair,
@@ -36,14 +38,22 @@ import {
36
38
  verifyEd25519,
37
39
  toBase64,
38
40
  fromBase64,
41
+ initRatchetInitiator,
42
+ initRatchetResponder,
43
+ ratchetEncrypt,
44
+ ratchetDecrypt,
39
45
  type EncryptedPayload,
40
46
  type RatchetState,
47
+ type DhRatchetState,
41
48
  type SessionRole,
42
49
  } from "@mosadd/crypto";
43
50
  import type { DmProvider } from "@mosadd/providers";
44
51
 
45
52
  export const PREKEY_BUNDLE_VERSION = "mosadd.prekeys.v1" as const;
53
+ /** Legacy symmetric-ratchet envelope (no PCS). Still DECODED for back-compat. */
46
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;
47
57
 
48
58
  const DEFAULT_ONE_TIME_PREKEYS = 8;
49
59
 
@@ -79,9 +89,14 @@ export interface PublicPrekeyBundle {
79
89
  signature: Uint8Array;
80
90
  }
81
91
 
82
- /** Persisted per-peer ratchet session. Plain data → trivially serializable. */
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
+ */
83
97
  export interface MdmSessionRecord {
84
- ratchet: RatchetState;
98
+ ratchet?: RatchetState; // v1 (legacy symmetric)
99
+ ratchet2?: DhRatchetState; // v2 (DH ratchet, PCS — LINEAR-3409)
85
100
  role: SessionRole;
86
101
  /** Handshake header still owed to the peer (initiator only, until first send). */
87
102
  pendingHandshake?: { ik: Uint8Array; ek: Uint8Array; opkId?: number };
@@ -114,6 +129,15 @@ export interface MdmKeyStore {
114
129
  */
115
130
  putSentMessage?(messageId: string, plaintext: Uint8Array): Promise<void>;
116
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>;
117
141
  }
118
142
 
119
143
  // ---- In-memory keystore (default) ----
@@ -168,6 +192,335 @@ function randomId(): number {
168
192
  return crypto.getRandomValues(new Uint32Array(1))[0]!;
169
193
  }
170
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
+
171
524
  // ---- Bundle codec (opaque bytes the provider moves) ----
172
525
 
173
526
  /**
@@ -246,17 +599,39 @@ interface E2eeEnvelope {
246
599
  ct: EncryptedPayload;
247
600
  }
248
601
 
249
- /** Quick check whether on-wire bytes are an mDM E2EE envelope (vs legacy plaintext). */
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). */
250
613
  export function isE2eeEnvelope(bytes: Uint8Array): boolean {
251
614
  try {
252
615
  const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
253
- return obj?.v === E2EE_ENVELOPE_VERSION && typeof obj?.i === "number" && !!obj?.ct;
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;
254
620
  } catch {
255
621
  return false;
256
622
  }
257
623
  }
258
624
 
259
- function serializeEnvelope(env: E2eeEnvelope): Uint8Array {
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 {
260
635
  return new Uint8Array(Buffer.from(JSON.stringify(env), "utf8"));
261
636
  }
262
637
 
@@ -266,6 +641,12 @@ function parseEnvelope(bytes: Uint8Array): E2eeEnvelope {
266
641
  return obj as E2eeEnvelope;
267
642
  }
268
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
+
269
650
  // ---- Publish ----
270
651
 
271
652
  /** Serialize the local bundle and hand it to the provider's key directory. */
@@ -319,18 +700,42 @@ export async function encryptForPeer(
319
700
  signedPreKeyPublicKey: peer.signedPrekey.publicKey,
320
701
  oneTimePreKeyPublicKey: opk?.publicKey,
321
702
  });
322
- const ratchet = await initializeRatchet(rootKey, "initiator");
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);
323
706
  session = {
324
- ratchet,
707
+ ratchet2,
325
708
  role: "initiator",
326
709
  pendingHandshake: { ik: own.identity.publicKey, ek: ephemeral.publicKey, opkId: opk?.id },
327
710
  };
328
711
  }
329
712
 
330
- const step = await ratchetSend(session.ratchet);
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!);
331
737
  const ct = await encryptBytes(step.messageKey, plaintext);
332
738
  const env: E2eeEnvelope = { v: E2EE_ENVELOPE_VERSION, i: step.messageIndex, ct };
333
-
334
739
  if (session.pendingHandshake && step.messageIndex === 0) {
335
740
  env.hdr = {
336
741
  ik: toBase64(session.pendingHandshake.ik),
@@ -338,7 +743,6 @@ export async function encryptForPeer(
338
743
  opk: session.pendingHandshake.opkId,
339
744
  };
340
745
  }
341
- // Header owed only on the first message; clear it after.
342
746
  session.pendingHandshake = undefined;
343
747
  await keystore.putSession(peerId, session);
344
748
  return serializeEnvelope(env);
@@ -350,46 +754,81 @@ export async function encryptForPeer(
350
754
  * Open an envelope from `peerId`, running X3DH (responder) on the first message
351
755
  * to derive the shared root key. Returns the inner plaintext bytes.
352
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
+
353
785
  export async function decryptFromPeer(
354
786
  keystore: MdmKeyStore,
355
787
  peerId: string,
356
788
  envelopeBytes: Uint8Array,
357
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.
358
819
  const env = parseEnvelope(envelopeBytes);
359
820
  let session = await keystore.getSession(peerId);
360
-
361
821
  if (!session) {
362
822
  if (!env.hdr) {
363
- throw new Error(
364
- `No session with "${peerId}" and the message carries no handshake header — cannot decrypt.`,
365
- );
823
+ throw new Error(`No session with "${peerId}" and the message carries no handshake header — cannot decrypt.`);
366
824
  }
367
- const own = await keystore.getOwnMaterial();
368
- let oneTimePreKeyPrivateKey: Uint8Array | undefined;
369
- if (env.hdr.opk !== undefined) {
370
- oneTimePreKeyPrivateKey = await keystore.takeOneTimePrekey(env.hdr.opk);
371
- if (!oneTimePreKeyPrivateKey) {
372
- throw new Error(
373
- `Handshake references one-time prekey ${env.hdr.opk} which is unknown or already consumed.`,
374
- );
375
- }
376
- }
377
- const { rootKey } = await performX3dhResponder(
378
- {
379
- identityPrivateKey: own.identity.privateKey,
380
- signedPreKeyPrivateKey: own.signedPrekey.pair.privateKey,
381
- oneTimePreKeyPrivateKey,
382
- },
383
- {
384
- initiatorIdentityPublicKey: fromBase64(env.hdr.ik),
385
- initiatorEphemeralPublicKey: fromBase64(env.hdr.ek),
386
- usedOneTimePreKeyId: env.hdr.opk,
387
- },
388
- );
825
+ const rootKey = await responderRootKey(keystore, env.hdr);
389
826
  const ratchet = await initializeRatchet(rootKey, "responder");
390
827
  session = { ratchet, role: "responder" };
391
828
  }
392
-
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
+ }
393
832
  const step = await ratchetReceive(session.ratchet);
394
833
  if (step.messageIndex !== env.i) {
395
834
  throw new Error(
package/src/index.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * Exposes mosadd OS modules (m*) as MCP tools to any agent runtime
5
5
  * (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, etc.).
6
6
  *
7
- * License: Apache-2.0
7
+ * License: MIT (releases before 2026-09-29: Apache-2.0)
8
8
  */
9
9
 
10
10
  export { createMosaddServer, defaultProviders } from "./server.js";
@@ -14,6 +14,6 @@ export type {
14
14
  MosaddToolContext,
15
15
  ProviderRegistry,
16
16
  } from "./types.js";
17
- export { allTools } from "./tools/index.js";
17
+ export { allTools, TOOL_COUNT } from "./tools/index.js";
18
18
  // Per-request session context for the hosted HTTP gateway (mcp.mosadd.com).
19
19
  export { runWithSupabaseEnv, type SupabaseEnv } from "./providers/supabase.js";