@mosadd/mcp 3.0.0-alpha.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.
@@ -0,0 +1,149 @@
1
+ /**
2
+ * mDM E2EE golden path (LINEAR-2357) — the "done" bar.
3
+ *
4
+ * Two parties (alice, bob) sharing ONE backend that acts as both the message
5
+ * store AND the key directory (decision "1a": prekey bundles ride the same
6
+ * DmProvider as messages). Proves:
7
+ * 1. both publish prekey bundles via the provider,
8
+ * 2. alice mDM_send → X3DH handshake + ratchet → bob mDM_list decrypts it,
9
+ * 3. the bytes on the wire are CIPHERTEXT, not plaintext (no test-theater),
10
+ * 4. bob replies on the established session → alice mDM_list decrypts it.
11
+ */
12
+
13
+ import { describe, expect, it } from "vitest";
14
+ import type {
15
+ DmProvider,
16
+ DmSendArgs,
17
+ DmListArgs,
18
+ DmSendResult,
19
+ DmListResult,
20
+ } from "@mosadd/providers";
21
+ import { mdmTools } from "../tools/mdm.js";
22
+ import { InMemoryMdmKeyStore } from "../crypto/mdm-session.js";
23
+ import type { MosaddToolContext } from "../types.js";
24
+
25
+ /** Shared store: message log + key directory, both keyed in one place. */
26
+ class SharedBackend {
27
+ readonly messages: Array<{ id: string; senderId: string; payload: Uint8Array; threadId: string }> = [];
28
+ readonly bundles = new Map<string, Uint8Array>();
29
+ }
30
+
31
+ /** One participant's view onto the shared backend. */
32
+ class ClientProvider implements DmProvider {
33
+ constructor(
34
+ private readonly backend: SharedBackend,
35
+ private readonly myId: string,
36
+ ) {}
37
+ async selfId(): Promise<string> {
38
+ return this.myId;
39
+ }
40
+ async send(args: DmSendArgs): Promise<DmSendResult> {
41
+ const id = `m${this.backend.messages.length + 1}`;
42
+ this.backend.messages.push({ id, senderId: this.myId, payload: args.payload, threadId: args.threadId });
43
+ return { id, deliveredAt: new Date(0).toISOString() };
44
+ }
45
+ async list(args: DmListArgs): Promise<DmListResult> {
46
+ return {
47
+ messages: this.backend.messages
48
+ .filter((m) => m.threadId === args.threadId)
49
+ .map((m) => ({
50
+ id: m.id,
51
+ senderId: m.senderId,
52
+ payload: m.payload,
53
+ timestamp: new Date(0).toISOString(),
54
+ threadId: m.threadId,
55
+ })),
56
+ nextCursor: null,
57
+ };
58
+ }
59
+ async publishPrekeyBundle(bundle: Uint8Array): Promise<void> {
60
+ this.backend.bundles.set(this.myId, bundle);
61
+ }
62
+ async fetchPrekeyBundle(peerId: string): Promise<Uint8Array | null> {
63
+ return this.backend.bundles.get(peerId) ?? null;
64
+ }
65
+ }
66
+
67
+ const tool = (name: string) => {
68
+ const t = mdmTools.find((x) => x.name === name);
69
+ if (!t) throw new Error(`tool ${name} not found`);
70
+ return t.handler;
71
+ };
72
+
73
+ function ctxFor(backend: SharedBackend, id: string): MosaddToolContext {
74
+ return {
75
+ options: { mode: "local", hubUrl: "https://mcp.mosadd.com" },
76
+ providers: { dm: new ClientProvider(backend, id), keys: new InMemoryMdmKeyStore() },
77
+ log: () => {},
78
+ };
79
+ }
80
+
81
+ describe("mDM E2EE golden path — X3DH handshake + ratchet, both directions", () => {
82
+ it("delivers an encrypted message alice→bob and a reply bob→alice", async () => {
83
+ const backend = new SharedBackend();
84
+ const alice = ctxFor(backend, "alice");
85
+ const bob = ctxFor(backend, "bob");
86
+
87
+ // 1. Both publish their prekey bundles (so first contact is possible).
88
+ await tool("mDM_publish_keys")({}, alice);
89
+ const bobPub = (await tool("mDM_publish_keys")({}, bob)) as { one_time_prekeys: number };
90
+ expect(bobPub.one_time_prekeys).toBeGreaterThan(0);
91
+
92
+ // 2. Alice sends an encrypted DM to Bob (first contact → X3DH handshake).
93
+ const sent = (await tool("mDM_send")({ to: "bob", text: "first contact" }, alice)) as {
94
+ encrypted: boolean;
95
+ };
96
+ expect(sent.encrypted).toBe(true);
97
+
98
+ // 3. The wire bytes must be CIPHERTEXT — the plaintext must NOT appear.
99
+ const wire = backend.messages[0]!.payload;
100
+ const wireStr = Buffer.from(wire).toString("utf8");
101
+ expect(wireStr).not.toContain("first contact");
102
+ expect(wireStr).toContain("mosadd.e2ee.v1"); // it IS our sealed envelope
103
+
104
+ // 4. Bob lists the thread and decrypts Alice's message.
105
+ const bobView = (await tool("mDM_list")({ contact_id: "alice" }, bob)) as {
106
+ messages: Array<{ text: string; sender_identity_id: string; encrypted: boolean }>;
107
+ };
108
+ const fromAlice = bobView.messages.find((m) => m.sender_identity_id === "alice");
109
+ expect(fromAlice?.text).toBe("first contact");
110
+ expect(fromAlice?.encrypted).toBe(true);
111
+
112
+ // 5. Bob replies on the now-established session (no new handshake).
113
+ await tool("mDM_send")({ to: "alice", text: "copy that" }, bob);
114
+
115
+ // 6. Alice decrypts Bob's reply.
116
+ const aliceView = (await tool("mDM_list")({ contact_id: "bob" }, alice)) as {
117
+ messages: Array<{ text: string; sender_identity_id: string }>;
118
+ };
119
+ const fromBob = aliceView.messages.find((m) => m.sender_identity_id === "bob");
120
+ expect(fromBob?.text).toBe("copy that");
121
+ });
122
+
123
+ it("mDM_send fails with an actionable error when the peer has no published keys", async () => {
124
+ const backend = new SharedBackend();
125
+ const alice = ctxFor(backend, "alice");
126
+ // Bob never published — no bundle to fetch.
127
+ await expect(tool("mDM_send")({ to: "bob", text: "hi" }, alice)).rejects.toThrow(
128
+ /has not published a prekey bundle/i,
129
+ );
130
+ });
131
+
132
+ it("rejects a tampered (MITM) prekey bundle instead of starting a session", async () => {
133
+ const backend = new SharedBackend();
134
+ const alice = ctxFor(backend, "alice");
135
+ const bob = ctxFor(backend, "bob");
136
+
137
+ await tool("mDM_publish_keys")({}, bob);
138
+
139
+ // MITM swaps Bob's DH identity key (a SIGNED field) in the directory entry,
140
+ // keeping it valid base64 so it parses — only the signature should catch it.
141
+ const obj = JSON.parse(Buffer.from(backend.bundles.get("bob")!).toString("utf8"));
142
+ obj.ik = (obj.ik[0] === "A" ? "B" : "A") + obj.ik.slice(1);
143
+ backend.bundles.set("bob", new Uint8Array(Buffer.from(JSON.stringify(obj), "utf8")));
144
+
145
+ await expect(tool("mDM_send")({ to: "bob", text: "intercept me" }, alice)).rejects.toThrow(
146
+ /signature verification|man-in-the-middle/i,
147
+ );
148
+ });
149
+ });
@@ -0,0 +1,67 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { allTools, createMosaddServer } from "../index.js";
3
+
4
+ describe("@mosadd/mcp", () => {
5
+ describe("allTools registry", () => {
6
+ it("exposes at least the 4 alpha channels", () => {
7
+ const names = allTools.map((t) => t.name);
8
+ // mDM (6 tools)
9
+ expect(names).toContain("mDM_list_contacts");
10
+ expect(names).toContain("mDM_publish_keys");
11
+ expect(names).toContain("mDM_send");
12
+ expect(names).toContain("mDM_send_unencrypted");
13
+ expect(names).toContain("mDM_list");
14
+ expect(names).toContain("mDM_respond_request");
15
+ // mIRC (5 tools)
16
+ expect(names).toContain("mIRC_create");
17
+ expect(names).toContain("mIRC_delete");
18
+ // mROOM (6 tools, including the USP guest-link)
19
+ expect(names).toContain("mROOM_create");
20
+ expect(names).toContain("mROOM_create_guest_link");
21
+ // mAIL (2 tools)
22
+ expect(names).toContain("mAIL_send");
23
+ expect(names).toContain("mAIL_view");
24
+ });
25
+
26
+ it("follows RFC 0001 naming — channel tools m<MODULE>_<operation>, meta tools comms_<op>", () => {
27
+ const channelName = /^m[A-Z][A-Z0-9_]*_[a-z][a-z0-9_]*$/;
28
+ const metaName = /^comms_[a-z][a-z0-9_]*$/; // discovery/meta namespace
29
+ for (const tool of allTools) {
30
+ expect(tool.name).toMatch(new RegExp(`${channelName.source}|${metaName.source}`));
31
+ }
32
+ });
33
+
34
+ it("every tool declares a transport requirement (any | radio | network)", () => {
35
+ for (const tool of allTools) {
36
+ expect(["any", "radio", "network"]).toContain(tool.requires);
37
+ }
38
+ });
39
+
40
+ it("every tool ships a description and a Zod schema", () => {
41
+ for (const tool of allTools) {
42
+ expect(typeof tool.description).toBe("string");
43
+ expect(tool.description.length).toBeGreaterThan(20);
44
+ expect(tool.inputSchema).toBeDefined();
45
+ // Zod schemas have _def
46
+ expect((tool.inputSchema as { _def?: unknown })._def).toBeDefined();
47
+ }
48
+ });
49
+ });
50
+
51
+ describe("createMosaddServer", () => {
52
+ it("constructs without throwing in local mode", () => {
53
+ const server = createMosaddServer({ mode: "local", logLevel: "error" });
54
+ expect(server).toBeDefined();
55
+ });
56
+
57
+ it("defaults to local mode when no apiKey", () => {
58
+ const server = createMosaddServer({ logLevel: "error" });
59
+ expect(server).toBeDefined();
60
+ });
61
+
62
+ it("accepts cloud mode with apiKey", () => {
63
+ const server = createMosaddServer({ apiKey: "test", logLevel: "error" });
64
+ expect(server).toBeDefined();
65
+ });
66
+ });
67
+ });
package/src/bin/mcp.ts ADDED
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `mosadd-mcp` (also runnable as `npx @mosadd/mcp`)
4
+ *
5
+ * Starts a mosadd MCP server over stdio. The standard transport for local
6
+ * MCP clients (Claude Code, Cursor, Cline, Windsurf, Goose, ...).
7
+ *
8
+ * For HTTP/SSE transport (hosted mcp.mosadd.com), see packages/mcp-gateway
9
+ * in the proprietary repo.
10
+ */
11
+
12
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
+ import { createMosaddServer } from "../server.js";
14
+
15
+ async function main(): Promise<void> {
16
+ const server = createMosaddServer({
17
+ apiKey: process.env.MOSADD_API_KEY,
18
+ hubUrl: process.env.MOSADD_HUB_URL,
19
+ mode: (process.env.MOSADD_MODE as "cloud" | "local" | "self-host" | undefined),
20
+ logLevel: (process.env.MOSADD_LOG_LEVEL as "debug" | "info" | "warn" | "error" | undefined),
21
+ });
22
+
23
+ const transport = new StdioServerTransport();
24
+ await server.connect(transport);
25
+
26
+ // The server now runs until stdin closes.
27
+ process.stderr.write(
28
+ JSON.stringify({
29
+ level: "info",
30
+ msg: "mosadd MCP server ready",
31
+ version: "3.0.0-alpha.0",
32
+ ts: new Date().toISOString(),
33
+ }) + "\n",
34
+ );
35
+ }
36
+
37
+ main().catch((err) => {
38
+ process.stderr.write(
39
+ JSON.stringify({
40
+ level: "error",
41
+ msg: "mosadd MCP server failed to start",
42
+ error: err instanceof Error ? err.message : String(err),
43
+ stack: err instanceof Error ? err.stack : undefined,
44
+ }) + "\n",
45
+ );
46
+ process.exit(1);
47
+ });
@@ -0,0 +1,378 @@
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
+ encryptBytes,
28
+ generateEd25519KeyPair,
29
+ generateX25519KeyPair,
30
+ initializeRatchet,
31
+ performX3dh,
32
+ performX3dhResponder,
33
+ ratchetReceive,
34
+ ratchetSend,
35
+ signEd25519,
36
+ verifyEd25519,
37
+ toBase64,
38
+ fromBase64,
39
+ type EncryptedPayload,
40
+ type RatchetState,
41
+ type SessionRole,
42
+ } from "@mosadd/crypto";
43
+ import type { DmProvider } from "@mosadd/providers";
44
+
45
+ export const PREKEY_BUNDLE_VERSION = "mosadd.prekeys.v1" as const;
46
+ export const E2EE_ENVELOPE_VERSION = "mosadd.e2ee.v1" as const;
47
+
48
+ const DEFAULT_ONE_TIME_PREKEYS = 8;
49
+
50
+ // ---- Key material types ----
51
+
52
+ interface X25519Pair {
53
+ publicKey: Uint8Array;
54
+ privateKey: Uint8Array;
55
+ }
56
+
57
+ /** The local peer's long-term identity + prekeys (private halves included). */
58
+ export interface OwnPrekeyMaterial {
59
+ /** X25519 DH identity — used in X3DH. */
60
+ identity: X25519Pair;
61
+ /**
62
+ * Ed25519 SIGNING identity — the long-term key a peer pins out-of-band
63
+ * (the "safety number"). Signs the bundle so a network/radio MITM can't swap
64
+ * the signed prekey or DH identity in transit.
65
+ */
66
+ signingIdentity: { publicKey: Uint8Array; privateKey: Uint8Array };
67
+ signedPrekey: { id: number; pair: X25519Pair };
68
+ oneTimePrekeys: Array<{ id: number; pair: X25519Pair }>;
69
+ }
70
+
71
+ /** A peer's PUBLIC prekey bundle, as parsed off the wire. */
72
+ export interface PublicPrekeyBundle {
73
+ identityPublicKey: Uint8Array;
74
+ /** Ed25519 signing-identity public key the signature is verified against. */
75
+ signingIdentityPublicKey: Uint8Array;
76
+ signedPrekey: { id: number; publicKey: Uint8Array };
77
+ oneTimePrekeys: Array<{ id: number; publicKey: Uint8Array }>;
78
+ /** Ed25519 signature over (DH identity pub ‖ signed-prekey pub). */
79
+ signature: Uint8Array;
80
+ }
81
+
82
+ /** Persisted per-peer ratchet session. Plain data → trivially serializable. */
83
+ export interface MdmSessionRecord {
84
+ ratchet: RatchetState;
85
+ role: SessionRole;
86
+ /** Handshake header still owed to the peer (initiator only, until first send). */
87
+ pendingHandshake?: { ik: Uint8Array; ek: Uint8Array; opkId?: number };
88
+ }
89
+
90
+ /**
91
+ * Local custody of private key material + ratchet sessions. The default impl
92
+ * is in-memory; a host may inject a file- or keychain-backed implementation.
93
+ */
94
+ export interface MdmKeyStore {
95
+ /** Own identity + prekeys. Generated lazily on first access, then stable. */
96
+ getOwnMaterial(): Promise<OwnPrekeyMaterial>;
97
+ /** Consume (one-time) a prekey private by id. Returns undefined if unknown. */
98
+ takeOneTimePrekey(id: number): Promise<Uint8Array | undefined>;
99
+ getSession(peerId: string): Promise<MdmSessionRecord | undefined>;
100
+ putSession(peerId: string, record: MdmSessionRecord): Promise<void>;
101
+ }
102
+
103
+ // ---- In-memory keystore (default) ----
104
+
105
+ export class InMemoryMdmKeyStore implements MdmKeyStore {
106
+ private material: OwnPrekeyMaterial | null = null;
107
+ private readonly oneTimeById = new Map<number, Uint8Array>();
108
+ private readonly sessions = new Map<string, MdmSessionRecord>();
109
+
110
+ async getOwnMaterial(): Promise<OwnPrekeyMaterial> {
111
+ if (this.material) return this.material;
112
+ const identity = await generateX25519KeyPair();
113
+ const signingIdentity = await generateEd25519KeyPair();
114
+ const signedPrekeyPair = await generateX25519KeyPair();
115
+ const signedPrekey = { id: randomId(), pair: signedPrekeyPair };
116
+ const oneTimePrekeys: OwnPrekeyMaterial["oneTimePrekeys"] = [];
117
+ for (let i = 0; i < DEFAULT_ONE_TIME_PREKEYS; i += 1) {
118
+ const pair = await generateX25519KeyPair();
119
+ const id = randomId();
120
+ oneTimePrekeys.push({ id, pair });
121
+ this.oneTimeById.set(id, pair.privateKey);
122
+ }
123
+ this.material = { identity, signingIdentity, signedPrekey, oneTimePrekeys };
124
+ return this.material;
125
+ }
126
+
127
+ async takeOneTimePrekey(id: number): Promise<Uint8Array | undefined> {
128
+ const priv = this.oneTimeById.get(id);
129
+ if (priv) this.oneTimeById.delete(id); // one-time: consume on use
130
+ return priv;
131
+ }
132
+
133
+ async getSession(peerId: string): Promise<MdmSessionRecord | undefined> {
134
+ return this.sessions.get(peerId);
135
+ }
136
+
137
+ async putSession(peerId: string, record: MdmSessionRecord): Promise<void> {
138
+ this.sessions.set(peerId, record);
139
+ }
140
+ }
141
+
142
+ function randomId(): number {
143
+ return crypto.getRandomValues(new Uint32Array(1))[0]!;
144
+ }
145
+
146
+ // ---- Bundle codec (opaque bytes the provider moves) ----
147
+
148
+ /**
149
+ * The exact bytes signed by / verified against the Ed25519 signing identity:
150
+ * the DH identity public key concatenated with the signed-prekey public key.
151
+ * Binding both means a MITM cannot swap either without invalidating the sig.
152
+ */
153
+ function bundleSigningMessage(dhIdentityPub: Uint8Array, signedPrekeyPub: Uint8Array): Uint8Array {
154
+ const msg = new Uint8Array(dhIdentityPub.length + signedPrekeyPub.length);
155
+ msg.set(dhIdentityPub, 0);
156
+ msg.set(signedPrekeyPub, dhIdentityPub.length);
157
+ return msg;
158
+ }
159
+
160
+ export function serializePublicBundle(material: OwnPrekeyMaterial): Uint8Array {
161
+ const signature = signEd25519(
162
+ material.signingIdentity.privateKey,
163
+ bundleSigningMessage(material.identity.publicKey, material.signedPrekey.pair.publicKey),
164
+ );
165
+ const json = JSON.stringify({
166
+ v: PREKEY_BUNDLE_VERSION,
167
+ ik: toBase64(material.identity.publicKey),
168
+ sik: toBase64(material.signingIdentity.publicKey),
169
+ spk: { id: material.signedPrekey.id, pub: toBase64(material.signedPrekey.pair.publicKey) },
170
+ opks: material.oneTimePrekeys.map((k) => ({ id: k.id, pub: toBase64(k.pair.publicKey) })),
171
+ sig: toBase64(signature),
172
+ });
173
+ return new Uint8Array(Buffer.from(json, "utf8"));
174
+ }
175
+
176
+ export function parsePublicBundle(bytes: Uint8Array): PublicPrekeyBundle {
177
+ const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
178
+ if (obj?.v !== PREKEY_BUNDLE_VERSION) {
179
+ throw new Error(`Unsupported prekey bundle version: ${obj?.v}`);
180
+ }
181
+ if (typeof obj.sik !== "string" || typeof obj.sig !== "string") {
182
+ throw new Error("Prekey bundle is missing its signing identity / signature.");
183
+ }
184
+ return {
185
+ identityPublicKey: fromBase64(obj.ik),
186
+ signingIdentityPublicKey: fromBase64(obj.sik),
187
+ signedPrekey: { id: obj.spk.id, publicKey: fromBase64(obj.spk.pub) },
188
+ oneTimePrekeys: (obj.opks ?? []).map((k: { id: number; pub: string }) => ({
189
+ id: k.id,
190
+ publicKey: fromBase64(k.pub),
191
+ })),
192
+ signature: fromBase64(obj.sig),
193
+ };
194
+ }
195
+
196
+ /**
197
+ * Verify the bundle's self-signature: the signing identity must have signed
198
+ * (DH identity ‖ signed prekey). Rejecting a bad signature is the MITM defense
199
+ * at X3DH first contact — an attacker who rewrites the bundle in transit cannot
200
+ * forge this without the peer's Ed25519 signing private key.
201
+ *
202
+ * NOTE: this authenticates the bundle UNDER its signing identity. Pinning that
203
+ * identity (safety numbers / TOFU) is a separate layer, tracked on 2342.
204
+ */
205
+ export function verifyPublicBundle(bundle: PublicPrekeyBundle): boolean {
206
+ return verifyEd25519(
207
+ bundle.signature,
208
+ bundleSigningMessage(bundle.identityPublicKey, bundle.signedPrekey.publicKey),
209
+ bundle.signingIdentityPublicKey,
210
+ );
211
+ }
212
+
213
+ // ---- Envelope codec ----
214
+
215
+ interface E2eeEnvelope {
216
+ v: typeof E2EE_ENVELOPE_VERSION;
217
+ /** Handshake header — present only on the initiator's first message. */
218
+ hdr?: { ik: string; ek: string; opk?: number };
219
+ /** Ratchet message index (strict in-order). */
220
+ i: number;
221
+ ct: EncryptedPayload;
222
+ }
223
+
224
+ /** Quick check whether on-wire bytes are an mDM E2EE envelope (vs legacy plaintext). */
225
+ export function isE2eeEnvelope(bytes: Uint8Array): boolean {
226
+ try {
227
+ const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
228
+ return obj?.v === E2EE_ENVELOPE_VERSION && typeof obj?.i === "number" && !!obj?.ct;
229
+ } catch {
230
+ return false;
231
+ }
232
+ }
233
+
234
+ function serializeEnvelope(env: E2eeEnvelope): Uint8Array {
235
+ return new Uint8Array(Buffer.from(JSON.stringify(env), "utf8"));
236
+ }
237
+
238
+ function parseEnvelope(bytes: Uint8Array): E2eeEnvelope {
239
+ const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
240
+ if (obj?.v !== E2EE_ENVELOPE_VERSION) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
241
+ return obj as E2eeEnvelope;
242
+ }
243
+
244
+ // ---- Publish ----
245
+
246
+ /** Serialize the local bundle and hand it to the provider's key directory. */
247
+ export async function publishOwnPrekeys(
248
+ keystore: MdmKeyStore,
249
+ dm: DmProvider,
250
+ ): Promise<{ oneTimePrekeyCount: number }> {
251
+ const material = await keystore.getOwnMaterial();
252
+ await dm.publishPrekeyBundle(serializePublicBundle(material));
253
+ return { oneTimePrekeyCount: material.oneTimePrekeys.length };
254
+ }
255
+
256
+ // ---- Encrypt (send) ----
257
+
258
+ /**
259
+ * Seal `plaintext` for `peerId`, establishing an X3DH+ratchet session on first
260
+ * contact (fetching the peer's published bundle via the provider). Returns the
261
+ * opaque envelope bytes to hand to `dm.send`.
262
+ */
263
+ export async function encryptForPeer(
264
+ keystore: MdmKeyStore,
265
+ dm: DmProvider,
266
+ peerId: string,
267
+ plaintext: Uint8Array,
268
+ ): Promise<Uint8Array> {
269
+ let session = await keystore.getSession(peerId);
270
+
271
+ if (!session) {
272
+ const raw = await dm.fetchPrekeyBundle(peerId);
273
+ if (!raw) {
274
+ throw new Error(
275
+ `Peer "${peerId}" has not published a prekey bundle yet, so an encrypted session cannot be established. ` +
276
+ `Ask them to run mDM_publish_keys, or use mDM_send_unencrypted (deprecated) for the migration window.`,
277
+ );
278
+ }
279
+ const peer = parsePublicBundle(raw);
280
+ // MITM defense: reject a bundle whose self-signature doesn't verify before
281
+ // we derive any key material from it.
282
+ if (!verifyPublicBundle(peer)) {
283
+ throw new Error(
284
+ `Prekey bundle for "${peerId}" failed signature verification — refusing to start an ` +
285
+ `encrypted session (possible tampering / man-in-the-middle).`,
286
+ );
287
+ }
288
+ const own = await keystore.getOwnMaterial();
289
+ const ephemeral = await generateX25519KeyPair();
290
+ const opk = peer.oneTimePrekeys[0]; // pick one if offered
291
+
292
+ const { rootKey } = await performX3dh(own.identity.privateKey, ephemeral.privateKey, {
293
+ identityPublicKey: peer.identityPublicKey,
294
+ signedPreKeyPublicKey: peer.signedPrekey.publicKey,
295
+ oneTimePreKeyPublicKey: opk?.publicKey,
296
+ });
297
+ const ratchet = await initializeRatchet(rootKey, "initiator");
298
+ session = {
299
+ ratchet,
300
+ role: "initiator",
301
+ pendingHandshake: { ik: own.identity.publicKey, ek: ephemeral.publicKey, opkId: opk?.id },
302
+ };
303
+ }
304
+
305
+ const step = await ratchetSend(session.ratchet);
306
+ const ct = await encryptBytes(step.messageKey, plaintext);
307
+ const env: E2eeEnvelope = { v: E2EE_ENVELOPE_VERSION, i: step.messageIndex, ct };
308
+
309
+ if (session.pendingHandshake && step.messageIndex === 0) {
310
+ env.hdr = {
311
+ ik: toBase64(session.pendingHandshake.ik),
312
+ ek: toBase64(session.pendingHandshake.ek),
313
+ opk: session.pendingHandshake.opkId,
314
+ };
315
+ }
316
+ // Header owed only on the first message; clear it after.
317
+ session.pendingHandshake = undefined;
318
+ await keystore.putSession(peerId, session);
319
+ return serializeEnvelope(env);
320
+ }
321
+
322
+ // ---- Decrypt (receive) ----
323
+
324
+ /**
325
+ * Open an envelope from `peerId`, running X3DH (responder) on the first message
326
+ * to derive the shared root key. Returns the inner plaintext bytes.
327
+ */
328
+ export async function decryptFromPeer(
329
+ keystore: MdmKeyStore,
330
+ peerId: string,
331
+ envelopeBytes: Uint8Array,
332
+ ): Promise<Uint8Array> {
333
+ const env = parseEnvelope(envelopeBytes);
334
+ let session = await keystore.getSession(peerId);
335
+
336
+ if (!session) {
337
+ if (!env.hdr) {
338
+ throw new Error(
339
+ `No session with "${peerId}" and the message carries no handshake header — cannot decrypt.`,
340
+ );
341
+ }
342
+ const own = await keystore.getOwnMaterial();
343
+ let oneTimePreKeyPrivateKey: Uint8Array | undefined;
344
+ if (env.hdr.opk !== undefined) {
345
+ oneTimePreKeyPrivateKey = await keystore.takeOneTimePrekey(env.hdr.opk);
346
+ if (!oneTimePreKeyPrivateKey) {
347
+ throw new Error(
348
+ `Handshake references one-time prekey ${env.hdr.opk} which is unknown or already consumed.`,
349
+ );
350
+ }
351
+ }
352
+ const { rootKey } = await performX3dhResponder(
353
+ {
354
+ identityPrivateKey: own.identity.privateKey,
355
+ signedPreKeyPrivateKey: own.signedPrekey.pair.privateKey,
356
+ oneTimePreKeyPrivateKey,
357
+ },
358
+ {
359
+ initiatorIdentityPublicKey: fromBase64(env.hdr.ik),
360
+ initiatorEphemeralPublicKey: fromBase64(env.hdr.ek),
361
+ usedOneTimePreKeyId: env.hdr.opk,
362
+ },
363
+ );
364
+ const ratchet = await initializeRatchet(rootKey, "responder");
365
+ session = { ratchet, role: "responder" };
366
+ }
367
+
368
+ const step = await ratchetReceive(session.ratchet);
369
+ if (step.messageIndex !== env.i) {
370
+ throw new Error(
371
+ `Out-of-order mDM message (expected ratchet index ${step.messageIndex}, got ${env.i}). ` +
372
+ `Skipped-key handling is a tracked follow-up (LINEAR-2357).`,
373
+ );
374
+ }
375
+ const plaintext = await decryptBytes(step.messageKey, env.ct);
376
+ await keystore.putSession(peerId, session);
377
+ return plaintext;
378
+ }
package/src/index.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @mosadd/mcp — Model Context Protocol server for mosadd
3
+ *
4
+ * Exposes mosadd OS modules (m*) as MCP tools to any agent runtime
5
+ * (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, etc.).
6
+ *
7
+ * License: Apache-2.0
8
+ */
9
+
10
+ export { createMosaddServer, defaultProviders } from "./server.js";
11
+ export type {
12
+ MosaddServerOptions,
13
+ MosaddTool,
14
+ MosaddToolContext,
15
+ ProviderRegistry,
16
+ } from "./types.js";
17
+ export { allTools } from "./tools/index.js";