@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
@@ -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
+ });
@@ -111,8 +111,10 @@ describe("golden path — host injects transport under mDM", () => {
111
111
  expect(result.message_id).toBe("radio-1");
112
112
 
113
113
  // The payload is opaque to the provider but carries our text under the hood.
114
- const decoded = JSON.parse(Buffer.from(radio.sent[0]!.payload).toString("utf8"));
115
- expect(decoded.text).toBe("rendezvous at grid 4471, 0600");
114
+ // 2026-08-25: plaintext lane is RAW utf8 text (native app format), not a JSON
115
+ // envelope — packPlaintextPayload change, unpack tolerates both shapes.
116
+ const decoded = Buffer.from(radio.sent[0]!.payload).toString("utf8");
117
+ expect(decoded).toBe("rendezvous at grid 4471, 0600");
116
118
  });
117
119
 
118
120
  it("step 5: mDM_list round-trips the message back through the same provider", async () => {
@@ -9,11 +9,36 @@
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
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
15
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14
16
 
15
17
  const MCP_BIN = join(__dirname, "..", "..", "dist", "bin", "mcp.js");
16
18
 
19
+ // Every test boots a fresh node process (dist/bin/mcp.js) and waits for it on stdout. On a busy machine (this package's
20
+ // other test files in parallel, the other packages' suites under `pnpm -r test`, antivirus scanning node's module loads)
21
+ // that boot took more than 7 s on 2026-11-14: two of the three tests timed out at 5 s in each of two full runs, and
22
+ // passed in about 2 s each when this file ran alone, and in about 14 s each in a full run that gave them the time.
23
+ // The assertions are unchanged; only how long they may wait is. A server that never answers still fails.
24
+ const REQUEST_TIMEOUT_MS = 45_000;
25
+ vi.setConfig({ testTimeout: 120_000, hookTimeout: 30_000 });
26
+
27
+ /**
28
+ * The child server runs with an EMPTY home and no MOSADD_* variables.
29
+ *
30
+ * Until 2026-09-29 it inherited the developer's environment: on a machine with a `mosadd login` session
31
+ * (~/.mosadd/session.json) the "tool handler throws" case below sent a REAL mDM_send through that account
32
+ * (to 11111111-…, failing only on the missing prekey bundle), so running the suite wrote to production.
33
+ * Sealed, the server finds no credentials and every networked tool stops at MissingSupabaseEnvError.
34
+ */
35
+ export function sealedEnv(parent: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
36
+ const home = mkdtempSync(join(tmpdir(), "mosadd-mcp-it-"));
37
+ const env: NodeJS.ProcessEnv = {};
38
+ for (const [k, v] of Object.entries(parent)) if (!/^(MOSADD_|SUPABASE_)/i.test(k)) env[k] = v;
39
+ return { ...env, HOME: home, USERPROFILE: home, HOMEDRIVE: "", HOMEPATH: "" };
40
+ }
41
+
17
42
  interface JsonRpcMessage {
18
43
  jsonrpc: "2.0";
19
44
  id?: number | string;
@@ -30,7 +55,7 @@ class McpClient {
30
55
  private nextId = 1;
31
56
 
32
57
  async start(): Promise<void> {
33
- this.proc = spawn("node", [MCP_BIN], { stdio: ["pipe", "pipe", "pipe"] });
58
+ this.proc = spawn("node", [MCP_BIN], { stdio: ["pipe", "pipe", "pipe"], env: sealedEnv() });
34
59
 
35
60
  this.proc.stdout.on("data", (chunk: Buffer) => {
36
61
  this.buffer += chunk.toString("utf8");
@@ -74,7 +99,7 @@ class McpClient {
74
99
  await new Promise<void>((resolve) => this.proc.on("close", () => resolve()));
75
100
  }
76
101
 
77
- async send(method: string, params?: unknown, timeoutMs = 5000): Promise<JsonRpcMessage> {
102
+ async send(method: string, params?: unknown, timeoutMs = REQUEST_TIMEOUT_MS): Promise<JsonRpcMessage> {
78
103
  const id = this.nextId++;
79
104
  const req: JsonRpcMessage = { jsonrpc: "2.0", id, method, params };
80
105
  return new Promise((resolve, reject) => {
@@ -91,6 +116,19 @@ class McpClient {
91
116
  }
92
117
  }
93
118
 
119
+ describe("integration child environment (no real session, no real messages)", () => {
120
+ it("is sealed: no MOSADD_*/SUPABASE_* variable and a home that is not the developer's", () => {
121
+ const env = sealedEnv({ ...process.env, MOSADD_API_KEY: "mosadd_sk_live_x", MOSADD_USER_JWT: "jwt", SUPABASE_URL: "https://x", PATH: "p" });
122
+ expect(Object.keys(env).filter((k) => /^(MOSADD_|SUPABASE_)/i.test(k))).toEqual([]);
123
+ expect(env.PATH).toBe("p");
124
+ for (const k of ["HOME", "USERPROFILE"] as const) {
125
+ expect(env[k]).toBeTruthy();
126
+ expect(env[k]).not.toBe(homedir());
127
+ expect(env[k]!.startsWith(tmpdir())).toBe(true);
128
+ }
129
+ });
130
+ });
131
+
94
132
  describe("@mosadd/mcp — integration (real stdio)", () => {
95
133
  let client: McpClient;
96
134
 
@@ -134,11 +172,12 @@ describe("@mosadd/mcp — integration (real stdio)", () => {
134
172
  const result = resp.result as { tools?: Array<{ name: string }> };
135
173
  const names = result.tools?.map((t) => t.name) ?? [];
136
174
 
137
- // All 4 channels surface their tools
175
+ // All live channels surface their tools
138
176
  expect(names).toContain("mDM_send");
139
177
  expect(names).toContain("mIRC_create");
140
- expect(names).toContain("mROOM_create_guest_link");
141
- expect(names).toContain("mAIL_send");
178
+ expect(names).toContain("mURL_post"); // mURL revived module (2026-06-27)
179
+ expect(names).toContain("mAYL_send"); // mAYL = email 3.0 (was mp0st); threat_catalog/threat_classify ARE registered (LINEAR-3498)
180
+ expect(names).not.toContain("mp0st_send"); // mp0st_* aliases RETIRED 2026-07-15 — mAYL only
142
181
  expect(names).toContain("mTALK_press"); // mTALK PTT now shipped
143
182
  expect(names).toContain("mRAG_search"); // mRAG RAG-for-devs now shipped
144
183
  expect(names).toContain("mIRC_post_message"); // channel messaging now shipped
@@ -161,10 +200,10 @@ describe("@mosadd/mcp — integration (real stdio)", () => {
161
200
  clientInfo: { name: "vitest", version: "1.0" },
162
201
  });
163
202
 
164
- // mDM_send needs MOSADD_SUPABASE_URL etc. — in test env we don't have them,
165
- // so the handler will throw MissingSupabaseEnvError. The MCP layer must wrap
166
- // that in a normal `isError: true` content block, not a JSON-RPC error
167
- // (that would crash the agent loop).
203
+ // mDM_send to a nonexistent peer MUST fail — but as a normal `isError: true`
204
+ // content block, not a JSON-RPC error (that would crash the agent loop).
205
+ // The child runs sealed (sealedEnv), so it has no credentials on any machine and the
206
+ // call stops at MissingSupabaseEnvError before any network request.
168
207
  const resp = await client.send("tools/call", {
169
208
  name: "mDM_send",
170
209
  arguments: { to: "11111111-1111-1111-1111-111111111111", text: "hi" },
@@ -173,6 +212,6 @@ describe("@mosadd/mcp — integration (real stdio)", () => {
173
212
  expect(resp.error).toBeUndefined(); // JSON-RPC level OK
174
213
  const result = resp.result as { isError?: boolean; content?: Array<{ text?: string }> };
175
214
  expect(result.isError).toBe(true);
176
- expect(result.content?.[0]?.text).toContain("Missing");
215
+ expect(result.content?.[0]?.text ?? "").toMatch(/Missing/i);
177
216
  });
178
217
  });
@@ -0,0 +1,114 @@
1
+ /**
2
+ * mRAG_ingest — what actually reaches rag-index.
3
+ *
4
+ * Two things are pinned here, both found by measuring production on 2026-08-14:
5
+ *
6
+ * 1. THE GRAPH FIELDS ARE FORWARDED. The knowledge graph builds its nodes from
7
+ * metadata.sender / .recipient / .occurred_at and NOTHING else. This tool used to send only a
8
+ * title, so a corpus could be fully indexed and mRAG_graph_overview still come back empty —
9
+ * silently, with every call returning success. If these assertions ever go green-but-empty
10
+ * again, that failure is back.
11
+ *
12
+ * 2. A NON-UUID source_id DOES NOT BLOW UP THE CALL. `user_embeddings.source_id` is a uuid column,
13
+ * so passing the natural thing (a path, a case number) made the whole ingest fail with an
14
+ * opaque "rag-index (500): Internal error". Non-UUIDs are folded into a deterministic UUIDv5;
15
+ * real UUIDs pass through untouched.
16
+ */
17
+
18
+ import { describe, it, expect, vi, beforeEach } from "vitest";
19
+
20
+ const sent: Record<string, unknown>[] = [];
21
+
22
+ vi.mock("../providers/supabase.js", () => ({
23
+ readSupabaseEnv: () => ({ url: "https://example.supabase.co", anonKey: "anon", userJwt: "jwt" }),
24
+ invokeFunction: (_fn: string, body: Record<string, unknown>) => {
25
+ sent.push(body);
26
+ return Promise.resolve({ indexed: 1, chunk_count: 1 });
27
+ },
28
+ }));
29
+
30
+ const { knowledgeTools } = await import("../tools/knowledge.js");
31
+ const ingest = knowledgeTools.find((t) => t.name === "mRAG_ingest")!;
32
+ const ctx = { log: () => {} } as never;
33
+ const call = (input: Record<string, unknown>) => ingest.handler(input, ctx);
34
+ const last = () => sent[sent.length - 1];
35
+
36
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
37
+
38
+ describe("mRAG_ingest", () => {
39
+ beforeEach(() => {
40
+ sent.length = 0;
41
+ });
42
+
43
+ it("forwards the parties and the event date as TOP-LEVEL fields (where rag-index reads them)", async () => {
44
+ await call({
45
+ content_text: "Pismo procesowe.",
46
+ sender: { kind: "email", ref: "kancelaria@example.invalid", label: "Kancelaria" },
47
+ recipient: { kind: "unknown", ref: "sad-rejonowy", label: "Sąd Rejonowy" },
48
+ occurred_at: "2019-03-11T10:00:00.000Z",
49
+ direction: "in",
50
+ labels: ["M-01"],
51
+ name: "pozew.pdf",
52
+ mime: "application/pdf",
53
+ size: 1234,
54
+ });
55
+ expect(last()).toMatchObject({
56
+ sender: { kind: "email", ref: "kancelaria@example.invalid" },
57
+ recipient: { kind: "unknown", ref: "sad-rejonowy" },
58
+ occurred_at: "2019-03-11T10:00:00.000Z",
59
+ direction: "in",
60
+ labels: ["M-01"],
61
+ name: "pozew.pdf",
62
+ mime: "application/pdf",
63
+ size: 1234,
64
+ });
65
+ });
66
+
67
+ it("keeps caller metadata AND the title, without dropping either", async () => {
68
+ await call({
69
+ content_text: "x",
70
+ title: "Pozew z 11.03.2019",
71
+ metadata: { case_id: "M-01", jurisdiction: "PL", pii_flag: true },
72
+ });
73
+ expect(last().metadata).toMatchObject({
74
+ case_id: "M-01",
75
+ jurisdiction: "PL",
76
+ pii_flag: true,
77
+ title: "Pozew z 11.03.2019",
78
+ ingested_via: "mRAG_ingest",
79
+ });
80
+ });
81
+
82
+ it("a caller that passes nothing extra sends the same request shape as before", async () => {
83
+ await call({ content_text: "x", source_type: "note" });
84
+ expect(last()).toEqual({
85
+ source_type: "file", // "note" maps to "file" backend-side, unchanged behaviour
86
+ source_id: null,
87
+ thread_id: null,
88
+ content_text: "x",
89
+ metadata: { ingested_via: "mRAG_ingest" },
90
+ });
91
+ });
92
+
93
+ it("folds a non-UUID source_id into a stable uuid and keeps the original visible", async () => {
94
+ await call({ content_text: "x", source_id: "C:/LAW/M-01/pozew.pdf" });
95
+ const id = last().source_id as string;
96
+ expect(id).toMatch(UUID_RE);
97
+ expect(last().metadata).toMatchObject({ source_ref: "C:/LAW/M-01/pozew.pdf" });
98
+
99
+ // Deterministic: the same document re-ingested groups with itself rather than forking.
100
+ await call({ content_text: "y", source_id: "C:/LAW/M-01/pozew.pdf" });
101
+ expect(last().source_id).toBe(id);
102
+
103
+ // …and a different document does not collide with it.
104
+ await call({ content_text: "z", source_id: "C:/LAW/M-01/odpowiedz.pdf" });
105
+ expect(last().source_id).not.toBe(id);
106
+ });
107
+
108
+ it("passes a real UUID through untouched, with no rewrite marker", async () => {
109
+ const uuid = "b228b6ae-dda6-4823-9882-40ea91ed1530";
110
+ await call({ content_text: "x", source_id: uuid });
111
+ expect(last().source_id).toBe(uuid);
112
+ expect(last().metadata).not.toHaveProperty("source_ref");
113
+ });
114
+ });
@@ -0,0 +1,22 @@
1
+ // 15.11.2026 — pokój PTT z etykietą ma właściciela w nazwie (bramka: mosADD livekit-token/labelRoom.ts).
2
+ // Było `mosadd-room-<etykieta>`: jedna nazwa dla wszystkich kont, bez właściciela → 403 dla każdego,
3
+ // a wersja „pierwszy wchodzący zajmuje” pozwalała obcemu przejąć pokój.
4
+ import { describe, expect, it } from "vitest";
5
+ import { labelRoomId } from "../providers/supabase-voice.js";
6
+
7
+ const G = "68f326ac-3e8b-468e-9bac-328a930de541";
8
+
9
+ describe("labelRoomId", () => {
10
+ it("etykieta → mosadd-room-<id otwierającego>-<slug>", () => {
11
+ expect(labelRoomId(G, "Field Team")).toBe(`mosadd-room-${G}-field-team`);
12
+ });
13
+ it("bez etykiety → pokój osobisty (goły id, jak dotąd)", () => {
14
+ expect(labelRoomId(G)).toBe(`mosadd-room-${G}`);
15
+ });
16
+ it("dwa konta z tą samą etykietą dostają RÓŻNE pokoje (koniec wspólnej nazwy dla wszystkich)", () => {
17
+ expect(labelRoomId(G, "ops")).not.toBe(labelRoomId("1acbb607-9f66-4074-8295-17c4fb84832c", "ops"));
18
+ });
19
+ it("etykieta z samych znaków specjalnych nie robi z pokoju osobistego", () => {
20
+ expect(labelRoomId(G, "!!!")).toBe(`mosadd-room-${G}-room`);
21
+ });
22
+ });
@@ -21,6 +21,7 @@ import type {
21
21
  import { mdmTools } from "../tools/mdm.js";
22
22
  import { InMemoryMdmKeyStore } from "../crypto/mdm-session.js";
23
23
  import { InMemoryVoiceProvider } from "../providers/memory-voice.js";
24
+ import { createMosaddServer } from "../server.js";
24
25
  import type { MosaddToolContext } from "../types.js";
25
26
 
26
27
  /** Shared store: message log + key directory, both keyed in one place. */
@@ -104,7 +105,7 @@ describe("mDM E2EE golden path — X3DH handshake + ratchet, both directions", (
104
105
  const wire = backend.messages[0]!.payload;
105
106
  const wireStr = Buffer.from(wire).toString("utf8");
106
107
  expect(wireStr).not.toContain("first contact");
107
- expect(wireStr).toContain("mosadd.e2ee.v1"); // it IS our sealed envelope
108
+ expect(wireStr).toContain("mosadd.e2ee.v2"); // DH-ratchet sealed envelope (PCS — LINEAR-3409)
108
109
 
109
110
  // 4. Bob lists the thread and decrypts Alice's message.
110
111
  const bobView = (await tool("mDM_list")({ contact_id: "alice" }, bob)) as {
@@ -176,3 +177,36 @@ describe("mDM E2EE golden path — X3DH handshake + ratchet, both directions", (
176
177
  );
177
178
  });
178
179
  });
180
+
181
+ describe("auto-publish prekeys on startup (LINEAR-3104 cold-start fix)", () => {
182
+ it("publishes the local prekey bundle when autoPublishKeys is set", async () => {
183
+ const backend = new SharedBackend();
184
+ createMosaddServer({
185
+ mode: "local",
186
+ autoPublishKeys: true,
187
+ providers: {
188
+ dm: new ClientProvider(backend, "self-agent"),
189
+ keys: new InMemoryMdmKeyStore(),
190
+ voice: new InMemoryVoiceProvider("self-agent"),
191
+ },
192
+ });
193
+ // fire-and-forget; getOwnMaterial() does async key generation, so flush.
194
+ await new Promise((r) => setTimeout(r, 50));
195
+ expect(backend.bundles.has("self-agent")).toBe(true);
196
+ expect(backend.bundles.get("self-agent")!.byteLength).toBeGreaterThan(0);
197
+ });
198
+
199
+ it("does NOT publish when autoPublishKeys is unset (hosted/default)", async () => {
200
+ const backend = new SharedBackend();
201
+ createMosaddServer({
202
+ mode: "local",
203
+ providers: {
204
+ dm: new ClientProvider(backend, "quiet-agent"),
205
+ keys: new InMemoryMdmKeyStore(),
206
+ voice: new InMemoryVoiceProvider("quiet-agent"),
207
+ },
208
+ });
209
+ await new Promise((r) => setTimeout(r, 50));
210
+ expect(backend.bundles.has("quiet-agent")).toBe(false);
211
+ });
212
+ });