@mosadd/mcp 3.0.0-alpha.54 → 3.0.0-alpha.56

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,244 @@
1
+ /**
2
+ * ZAMEK „ZERO SZYFROWANIA Z FLOTA" (29.09.2026, owner decision 28.09: no encryption on agent-line
3
+ * conversations, in any channel or identity).
4
+ *
5
+ * Dwie reguly bramy MCP, obie zmierzone jako zepsute 28–29.09 (Public\ZERO-SZYFROWANIA-29-09,
6
+ * D1 §3 i S1 §1b):
7
+ *
8
+ * c1 — DEKODER KANALU. #adm i #command sa otwarte, bez klucza grupowego. Aplikacja zapisuje
9
+ * tekst kanalu jako goly UTF-8 w base64 (apps/web ircApi.ts `encodePayload`). Stary dekoder
10
+ * (`mirc-messages.ts` / `mroom-messages.ts` `unpackPayload`) znal tylko koperte JSON, wiec
11
+ * KAZDY wpis Krola czytal sie liniom jako "<ciphertext>" (f159c8d7, 776b3e9a na #adm).
12
+ * Teraz: jawny tekst = tekst. "<ciphertext>" zostaje tylko dla prawdziwej koperty klucza
13
+ * grupowego {iv,ciphertext,hmac}, do ktorej linia nie ma klucza (i dla bajtow nie-UTF-8).
14
+ *
15
+ * b1 — mDM_send DO FLOTY JAWNIE. Gdy ktoras strona to linia agenta ALBO to wiadomosc do siebie
16
+ * (to === selfId), wysylka idzie sciezka jawna: encrypted:false, reason:"fleet_plaintext".
17
+ * Czlowiek↔czlowiek zostaje E2EE bez zmian (koperta X3DH + Double Ratchet).
18
+ *
19
+ * Kazdy zamek sprawdzony na czerwono przed naprawa (kod alpha.54) i pod sabotazem po naprawie.
20
+ */
21
+ import { describe, expect, it, vi, beforeEach } from "vitest";
22
+ import type { DmProvider, DmListArgs, DmListResult, DmSendResult } from "@mosadd/providers";
23
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
24
+ import type { DmSendArgsExt } from "../providers/supabase-dm.js";
25
+
26
+ // ---- message-list / channel-manage stand-in (the only EFs the list tools call) ----
27
+
28
+ type StoredRow = { id: string; sender_identity_id: string; encrypted_payload: string; created_at: string };
29
+ let storedRows: StoredRow[] = [];
30
+ /** channel id → the line holds that channel's group key and opens these payloads */
31
+ let groupKeyOpens: (channelId: string, payload: string) => string | null = () => null;
32
+
33
+ vi.mock("../providers/supabase.js", async (importOriginal) => ({
34
+ ...(await importOriginal<typeof import("../providers/supabase.js")>()),
35
+ readSupabaseEnv: () => ({ url: "https://example.supabase.co", anonKey: "anon", userJwt: "jwt" }),
36
+ invokeFunction: async (fn: string) => {
37
+ if (fn === "message-list") return { messages: storedRows, next_before: null };
38
+ throw new Error(`unexpected edge function ${fn}`);
39
+ },
40
+ }));
41
+
42
+ vi.mock("../crypto/channel-e2ee.js", async (importOriginal) => ({
43
+ ...(await importOriginal<typeof import("../crypto/channel-e2ee.js")>()),
44
+ decryptChannelPayload: async (channelId: string, payload: string) => groupKeyOpens(channelId, payload),
45
+ encryptChannelPayload: async () => null,
46
+ }));
47
+
48
+ const { mircMessagesTools } = await import("../tools/mirc-messages.js");
49
+ const { mroomMessagesTools } = await import("../tools/mroom-messages.js");
50
+ const { mdmTools } = await import("../tools/mdm.js");
51
+ const { defaultProviders } = await import("../server.js");
52
+ const { InMemoryVoiceProvider } = await import("../providers/memory-voice.js");
53
+ const { SeededMdmKeyStore, serializePublicBundle, isE2eeEnvelope, decryptFromPeer } = await import(
54
+ "../crypto/mdm-session.js"
55
+ );
56
+
57
+ const handler = (list: readonly MosaddTool[], name: string) => {
58
+ const t = list.find((x) => x.name === name);
59
+ if (!t) throw new Error(`tool ${name} not registered`);
60
+ return t.handler;
61
+ };
62
+ const noopLog: MosaddToolContext["log"] = () => {};
63
+ const listCtx = { log: noopLog } as unknown as MosaddToolContext;
64
+
65
+ /** Exactly what the app stores for a channel post: base64 of the UTF-8 bytes (ircApi encodePayload). */
66
+ const appEncode = (text: string) => Buffer.from(new TextEncoder().encode(text)).toString("base64");
67
+ const b64json = (obj: unknown) => Buffer.from(JSON.stringify(obj), "utf8").toString("base64");
68
+
69
+ const ADM = "6c251ebf-acb4-4f49-bd9a-7fc28e5cfee6";
70
+ const KING = "king-identity";
71
+ const LINE = "general-line-identity";
72
+ const PEER = "peer-human-identity";
73
+ // Synthetic (the repo is public — no real message of the King goes into a fixture): Polish
74
+ // diacritics, an em dash, an @mention, a newline and an emoji, like the King writes.
75
+ const KING_TEXT = "Kto dowodzi flotą? Zgłoście się na #adm — żółć, źdźbło 🦞\n@all baczność";
76
+
77
+ type ListOut = { messages: Array<{ id: string; text: string }> };
78
+
79
+ async function readChannel(rows: Array<[string, string]>): Promise<string[]> {
80
+ storedRows = rows.map(([id, payload], i) => ({
81
+ id,
82
+ sender_identity_id: KING,
83
+ encrypted_payload: payload,
84
+ created_at: new Date(i * 1000).toISOString(),
85
+ }));
86
+ const out = (await handler(mircMessagesTools, "mIRC_list_messages")(
87
+ { channel_id: ADM, space_id: "space-adm", limit: 50 },
88
+ listCtx,
89
+ )) as ListOut;
90
+ return out.messages.map((m) => m.text);
91
+ }
92
+
93
+ describe("c1 — dekoder kanalu: tekst Krola czyta sie jako tekst, <ciphertext> tylko dla zamknietej koperty", () => {
94
+ beforeEach(() => {
95
+ storedRows = [];
96
+ groupKeyOpens = () => null;
97
+ });
98
+
99
+ it("wpis Krola z aplikacji (goly UTF-8 w base64) na otwartym #adm → czytelny tekst, nie <ciphertext>", async () => {
100
+ const texts = await readChannel([
101
+ ["f159c8d7", appEncode(KING_TEXT)],
102
+ ["776b3e9a", appEncode("@all bacznosc")],
103
+ ]);
104
+ expect(texts).toEqual([KING_TEXT, "@all bacznosc"]);
105
+ expect(texts).not.toContain("<ciphertext>");
106
+ });
107
+
108
+ it("koperta mosadd.chat.v1 z narzedzia (linie) → jej tekst, jak dotad", async () => {
109
+ const texts = await readChannel([
110
+ ["line-1", b64json({ v: "mosadd.chat.v1", type: "text", text: "meldunek linii", reply_to: null })],
111
+ ]);
112
+ expect(texts).toEqual(["meldunek linii"]);
113
+ });
114
+
115
+ it("koperta klucza grupowego {iv,ciphertext,hmac} BEZ klucza → <ciphertext> zostaje", async () => {
116
+ const texts = await readChannel([["sealed", b64json({ iv: "AAAAAAAAAAAAAAAA", ciphertext: "c2VhbGVk", hmac: "aG1hYw==" })]]);
117
+ expect(texts).toEqual(["<ciphertext>"]);
118
+ });
119
+
120
+ it("koperta klucza grupowego, linia MA klucz → odszyfrowany tekst (sciezka bez zmian)", async () => {
121
+ const sealed = b64json({ iv: "AAAAAAAAAAAAAAAA", ciphertext: "c2VhbGVk", hmac: "aG1hYw==" });
122
+ groupKeyOpens = (_c, p) => (p === sealed ? JSON.stringify({ v: "mosadd.chat.v1", type: "text", text: "z klucza" }) : null);
123
+ expect(await readChannel([["sealed", sealed]])).toEqual(["z klucza"]);
124
+ });
125
+
126
+ it("koperta ratchetu mDM (v: mosadd.e2ee.*) wklejona w kanal → <ciphertext>", async () => {
127
+ const texts = await readChannel([["e2ee", b64json({ v: "mosadd.e2ee.v2", dh: "x", n: 0, ct: "y" })]]);
128
+ expect(texts).toEqual(["<ciphertext>"]);
129
+ });
130
+
131
+ it("bajty nie-UTF-8 → <ciphertext> (to nie slowa)", async () => {
132
+ const texts = await readChannel([["bin", Buffer.from([0xff, 0xfe, 0x00, 0x81, 0xc3]).toString("base64")]]);
133
+ expect(texts).toEqual(["<ciphertext>"]);
134
+ });
135
+
136
+ it("glos {audio, mime, dur} → znacznik notatki glosowej (formatVoiceIfAny bez zmian)", async () => {
137
+ const texts = await readChannel([["voice", b64json({ audio: "A".repeat(2000), mime: "audio/webm", dur: 4200 })]]);
138
+ expect(texts).toEqual(["[voice note — 4s]"]);
139
+ });
140
+
141
+ it("mROOM: ta sama regula — tekst z aplikacji czyta sie jako tekst", async () => {
142
+ storedRows = [{ id: "r1", sender_identity_id: KING, encrypted_payload: appEncode(KING_TEXT), created_at: new Date(0).toISOString() }];
143
+ const out = (await handler(mroomMessagesTools, "mROOM_list_messages")({ room_id: "room-1" }, listCtx)) as ListOut;
144
+ expect(out.messages.map((m) => m.text)).toEqual([KING_TEXT]);
145
+ });
146
+ });
147
+
148
+ // ---- b1: mDM_send — an in-memory backend shaped like message-send / identities / prekeys ----
149
+
150
+ type Row = { senderId: string; to: string; threadId: string; payload: Uint8Array; messageType: string };
151
+
152
+ class Backend {
153
+ readonly rows: Row[] = [];
154
+ readonly bundles = new Map<string, Uint8Array>();
155
+ readonly kinds = new Map<string, string>();
156
+ }
157
+
158
+ class Lane implements DmProvider {
159
+ constructor(private readonly b: Backend, private readonly me: string) {}
160
+ async selfId() { return this.me; }
161
+ async selfKind() { return this.b.kinds.get(this.me) ?? null; }
162
+ async peerKind(id: string) { return this.b.kinds.get(id) ?? null; }
163
+ async send(args: DmSendArgsExt): Promise<DmSendResult> {
164
+ this.b.rows.push({ senderId: this.me, to: args.to, threadId: args.threadId, payload: args.payload, messageType: args.messageType ?? "text" });
165
+ return { id: `m${this.b.rows.length}`, deliveredAt: new Date(0).toISOString() };
166
+ }
167
+ async list(_args: DmListArgs): Promise<DmListResult> { return { messages: [], nextCursor: null }; }
168
+ async publishPrekeyBundle(bundle: Uint8Array) { this.b.bundles.set(this.me, bundle); }
169
+ async fetchPrekeyBundle(peerId: string) { return this.b.bundles.get(peerId) ?? null; }
170
+ }
171
+
172
+ const KEY = "mosadd_sk_live_0123456789abcdef0123456789abcdef";
173
+ const gatewayRequest = (b: Backend, me: string): MosaddToolContext => ({
174
+ options: { mode: "cloud", hubUrl: "https://mcp.mosadd.com", apiKey: KEY },
175
+ providers: defaultProviders({ dm: new Lane(b, me), voice: new InMemoryVoiceProvider(me) }, { mdmSecret: KEY }),
176
+ log: noopLog,
177
+ });
178
+
179
+ /** A person with the app: kind human, prekey bundle published by the app at login. */
180
+ async function person(b: Backend, id: string, seedByte: number) {
181
+ const keys = new SeededMdmKeyStore(new Uint8Array(32).fill(seedByte));
182
+ b.bundles.set(id, serializePublicBundle(await keys.getOwnMaterial()));
183
+ b.kinds.set(id, "human");
184
+ return keys;
185
+ }
186
+
187
+ type SendOut = { encrypted: boolean; reason?: string; mode: string };
188
+ const send = (b: Backend, from: string, to: string, text: string) =>
189
+ handler(mdmTools, "mDM_send")({ to, text }, gatewayRequest(b, from)) as Promise<SendOut>;
190
+ const plain = (row: Row) => new TextDecoder().decode(row.payload);
191
+
192
+ describe("b1 — mDM_send: z liniami floty i z Krolem zawsze jawnie, czlowiek↔czlowiek E2EE", () => {
193
+ it("linia agenta → Krol: encrypted:false, reason fleet_plaintext, Krol czyta goly tekst", async () => {
194
+ const b = new Backend();
195
+ b.kinds.set(LINE, "agent");
196
+ await person(b, KING, 7);
197
+ const s = await send(b, LINE, KING, "meldunek");
198
+ expect(s).toMatchObject({ encrypted: false, reason: "fleet_plaintext" });
199
+ expect(b.rows.at(-1)!.messageType).toBe("txt");
200
+ expect(plain(b.rows.at(-1)!)).toBe("meldunek");
201
+ });
202
+
203
+ it("Krol (klucz czlowieka) → linia agenta: jawnie, mimo ze linia ma stary pek", async () => {
204
+ const b = new Backend();
205
+ b.kinds.set(LINE, "agent");
206
+ await person(b, KING, 7);
207
+ b.bundles.set(LINE, serializePublicBundle(await new SeededMdmKeyStore(new Uint8Array(32).fill(9)).getOwnMaterial()));
208
+ const s = await send(b, KING, LINE, "rozkaz");
209
+ expect(s).toMatchObject({ encrypted: false, reason: "fleet_plaintext" });
210
+ expect(plain(b.rows.at(-1)!)).toBe("rozkaz");
211
+ });
212
+
213
+ it("Krol pisze do SIEBIE (to === selfId) przez MCP: jawnie — zero kopert we wlasnym watku", async () => {
214
+ const b = new Backend();
215
+ await person(b, KING, 7);
216
+ const s = await send(b, KING, KING, "notatka do siebie");
217
+ expect(s).toMatchObject({ encrypted: false, reason: "fleet_plaintext" });
218
+ const row = b.rows.at(-1)!;
219
+ expect(row.threadId).toBe(`dm:${KING}:${KING}`);
220
+ expect(isE2eeEnvelope(row.payload)).toBe(false);
221
+ expect(plain(row)).toBe("notatka do siebie");
222
+ });
223
+
224
+ it("czlowiek → czlowiek: E2EE zostaje — koperta ratchetu, tekstu nie widac, odbiorca otwiera", async () => {
225
+ const b = new Backend();
226
+ await person(b, KING, 7);
227
+ const peerKeys = await person(b, PEER, 5);
228
+ const s = await send(b, KING, PEER, "tajne");
229
+ expect(s).toMatchObject({ encrypted: true, mode: "e2ee" });
230
+ expect(s.reason).not.toBe("fleet_plaintext");
231
+ const row = b.rows.at(-1)!;
232
+ expect(isE2eeEnvelope(row.payload)).toBe(true);
233
+ expect(plain(row)).not.toContain("tajne");
234
+ expect(new TextDecoder().decode(await decryptFromPeer(peerKeys, KING, row.payload))).toBe("tajne");
235
+ });
236
+
237
+ it("opisy narzedzi: mDM_send_unencrypted nie jest 'DEPRECATED / prefer mDM_send', obie mowia: floty zawsze jawnie", () => {
238
+ const d = (n: string) => mdmTools.find((t) => t.name === n)!.description;
239
+ expect(d("mDM_send_unencrypted")).not.toMatch(/DEPRECATED|Prefer mDM_send|Will be removed/i);
240
+ for (const n of ["mDM_send", "mDM_send_unencrypted"]) {
241
+ expect(d(n)).toMatch(/fleet lines and with the King: ALWAYS in the clear/);
242
+ }
243
+ });
244
+ });
@@ -9,11 +9,28 @@
9
9
  */
10
10
 
11
11
  import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
12
+ import { mkdtempSync } from "node:fs";
13
+ import { homedir, tmpdir } from "node:os";
12
14
  import { join } from "node:path";
13
15
  import { afterEach, beforeEach, describe, expect, it } from "vitest";
14
16
 
15
17
  const MCP_BIN = join(__dirname, "..", "..", "dist", "bin", "mcp.js");
16
18
 
19
+ /**
20
+ * The child server runs with an EMPTY home and no MOSADD_* variables.
21
+ *
22
+ * Until 2026-09-29 it inherited the developer's environment: on a machine with a `mosadd login` session
23
+ * (~/.mosadd/session.json) the "tool handler throws" case below sent a REAL mDM_send through that account
24
+ * (to 11111111-…, failing only on the missing prekey bundle), so running the suite wrote to production.
25
+ * Sealed, the server finds no credentials and every networked tool stops at MissingSupabaseEnvError.
26
+ */
27
+ export function sealedEnv(parent: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
28
+ const home = mkdtempSync(join(tmpdir(), "mosadd-mcp-it-"));
29
+ const env: NodeJS.ProcessEnv = {};
30
+ for (const [k, v] of Object.entries(parent)) if (!/^(MOSADD_|SUPABASE_)/i.test(k)) env[k] = v;
31
+ return { ...env, HOME: home, USERPROFILE: home, HOMEDRIVE: "", HOMEPATH: "" };
32
+ }
33
+
17
34
  interface JsonRpcMessage {
18
35
  jsonrpc: "2.0";
19
36
  id?: number | string;
@@ -30,7 +47,7 @@ class McpClient {
30
47
  private nextId = 1;
31
48
 
32
49
  async start(): Promise<void> {
33
- this.proc = spawn("node", [MCP_BIN], { stdio: ["pipe", "pipe", "pipe"] });
50
+ this.proc = spawn("node", [MCP_BIN], { stdio: ["pipe", "pipe", "pipe"], env: sealedEnv() });
34
51
 
35
52
  this.proc.stdout.on("data", (chunk: Buffer) => {
36
53
  this.buffer += chunk.toString("utf8");
@@ -91,6 +108,19 @@ class McpClient {
91
108
  }
92
109
  }
93
110
 
111
+ describe("integration child environment (no real session, no real messages)", () => {
112
+ it("is sealed: no MOSADD_*/SUPABASE_* variable and a home that is not the developer's", () => {
113
+ const env = sealedEnv({ ...process.env, MOSADD_API_KEY: "mosadd_sk_live_x", MOSADD_USER_JWT: "jwt", SUPABASE_URL: "https://x", PATH: "p" });
114
+ expect(Object.keys(env).filter((k) => /^(MOSADD_|SUPABASE_)/i.test(k))).toEqual([]);
115
+ expect(env.PATH).toBe("p");
116
+ for (const k of ["HOME", "USERPROFILE"] as const) {
117
+ expect(env[k]).toBeTruthy();
118
+ expect(env[k]).not.toBe(homedir());
119
+ expect(env[k]!.startsWith(tmpdir())).toBe(true);
120
+ }
121
+ });
122
+ });
123
+
94
124
  describe("@mosadd/mcp — integration (real stdio)", () => {
95
125
  let client: McpClient;
96
126
 
@@ -164,11 +194,8 @@ describe("@mosadd/mcp — integration (real stdio)", () => {
164
194
 
165
195
  // mDM_send to a nonexistent peer MUST fail — but as a normal `isError: true`
166
196
  // content block, not a JSON-RPC error (that would crash the agent loop).
167
- // The exact message depends on the machine: without credentials it's
168
- // MissingSupabaseEnvError, with a logged-in `mosadd login` session the call
169
- // reaches the real server and fails on the peer's missing prekey bundle.
170
- // Both are the correct envelope; asserting one exact message made the test
171
- // red on any machine with a live session (audyt 2026-08-27).
197
+ // The child runs sealed (sealedEnv), so it has no credentials on any machine and the
198
+ // call stops at MissingSupabaseEnvError before any network request.
172
199
  const resp = await client.send("tools/call", {
173
200
  name: "mDM_send",
174
201
  arguments: { to: "11111111-1111-1111-1111-111111111111", text: "hi" },
@@ -177,6 +204,6 @@ describe("@mosadd/mcp — integration (real stdio)", () => {
177
204
  expect(resp.error).toBeUndefined(); // JSON-RPC level OK
178
205
  const result = resp.result as { isError?: boolean; content?: Array<{ text?: string }> };
179
206
  expect(result.isError).toBe(true);
180
- expect(result.content?.[0]?.text ?? "").toMatch(/Missing|error/i);
207
+ expect(result.content?.[0]?.text ?? "").toMatch(/Missing/i);
181
208
  });
182
209
  });
@@ -293,14 +293,18 @@ describe("mDM_send z MCP — czytelne na kazdym kluczu, prawdziwe powody w aplik
293
293
  expect(await appReadOwn(kingSeed, kingApp, KING, row)).toEqual({ text: null, reason: "agent" });
294
294
  });
295
295
 
296
- it("klucz czlowieka, notatka do siebie: aplikacja OTWIERA ja wlasnymi kluczami", async () => {
296
+ // 29.09 (ZERO SZYFROWANIA, rozkaz Krola 28.09): notatka do siebie z MCP idzie JAWNIE — do 28.09
297
+ // byla koperta E2EE, ktora aplikacja otwierala kluczami z ziarna; teraz nie ma czego otwierac.
298
+ it("klucz czlowieka, notatka do siebie: jawny txt — aplikacja czyta goly tekst na kazdym urzadzeniu", async () => {
297
299
  const b = new Backend();
298
- const kingSeed = new Uint8Array(32).fill(7);
299
- const kingApp = await appOf(b, KING, 7);
300
- await tool("mDM_send")({ to: KING, text: "do siebie z MCP" }, gatewayRequest(b, KING, KEY_A));
300
+ await appOf(b, KING, 7);
301
+ const s = (await tool("mDM_send")({ to: KING, text: "do siebie z MCP" }, gatewayRequest(b, KING, KEY_A))) as SendOut;
302
+ expect(s).toMatchObject({ encrypted: false, mode: "plaintext_agent_lane", identity: "untouched" });
301
303
  const row = b.rows.at(-1)!;
302
- expect(row.messageType).toBe("text");
303
- expect(await appReadOwn(kingSeed, kingApp, KING, row)).toEqual({ text: "do siebie z MCP", reason: null });
304
+ expect(row.messageType).toBe("txt");
305
+ expect(row.selfPayload).toBeNull();
306
+ expect(appPlaintext(row)).toBe("do siebie z MCP");
307
+ expect(b.publishes).toBe(0);
304
308
  });
305
309
 
306
310
  it("czlowiek BEZ peku: MCP nie publikuje sam (ani mDM_send, ani autoPublishKeys); jawne mDM_publish_keys moze", async () => {