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

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 (51) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-3PUOM4R5.js → chunk-IWUGKLDX.js} +54 -20
  5. package/dist/index.js +1 -1
  6. package/package.json +1 -1
  7. package/src/__tests__/blob-upload.test.ts +93 -93
  8. package/src/__tests__/channel-e2ee.test.ts +62 -62
  9. package/src/__tests__/flota-jawnie.test.ts +244 -0
  10. package/src/__tests__/golden-path.test.ts +139 -139
  11. package/src/__tests__/integration.test.ts +182 -182
  12. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  13. package/src/__tests__/mdm-mcp-readable.test.ts +390 -386
  14. package/src/__tests__/mirc-invite.test.ts +112 -112
  15. package/src/__tests__/mtalk.test.ts +122 -122
  16. package/src/__tests__/server.test.ts +71 -71
  17. package/src/__tests__/tool-count-consistency.test.ts +199 -199
  18. package/src/bin/login.ts +138 -138
  19. package/src/bin/mcp.ts +145 -145
  20. package/src/config.ts +66 -66
  21. package/src/crypto/channel-e2ee.ts +288 -288
  22. package/src/crypto/mdm-session.ts +842 -842
  23. package/src/index.ts +19 -19
  24. package/src/observability/sentry.ts +79 -79
  25. package/src/providers/memory-voice.ts +79 -79
  26. package/src/providers/supabase-dm.ts +202 -202
  27. package/src/providers/supabase-voice.ts +91 -91
  28. package/src/server.ts +195 -195
  29. package/src/tools/actions.ts +166 -166
  30. package/src/tools/attachments.ts +276 -276
  31. package/src/tools/capabilities.ts +70 -70
  32. package/src/tools/channel-payload.ts +69 -0
  33. package/src/tools/embed.ts +110 -110
  34. package/src/tools/index.ts +181 -181
  35. package/src/tools/knowledge.ts +344 -344
  36. package/src/tools/mail-aliases.ts +25 -25
  37. package/src/tools/mail-provenance.ts +137 -137
  38. package/src/tools/mail.ts +403 -403
  39. package/src/tools/mdm-as-agent.ts +126 -126
  40. package/src/tools/mdm.ts +26 -11
  41. package/src/tools/mirc-edge.ts +196 -196
  42. package/src/tools/mirc-members.ts +287 -287
  43. package/src/tools/mirc-messages.ts +9 -13
  44. package/src/tools/mirc.ts +308 -308
  45. package/src/tools/mroom-messages.ts +4 -12
  46. package/src/tools/mroom.ts +221 -221
  47. package/src/tools/mtalk.ts +131 -131
  48. package/src/tools/presence.ts +442 -442
  49. package/src/tools/voice-format.ts +28 -28
  50. package/src/types.ts +121 -121
  51. package/src/voice/floor.ts +132 -132
@@ -1,93 +1,93 @@
1
- /**
2
- * LANA PLIKOW — ŻYWA, NIE DOPISANA Z PAMIĘCI (16.09).
3
- *
4
- * Zmierzone PRZED poprawką, na żywym MCP (mcp.mosadd.com), 1 KB text/plain:
5
- * mDM_send_file → "blob upload to file-blobs/dm-…/….txt failed: Bucket not found"
6
- * mDM_send_voice → "blob upload to voice-blobs/dm-…/….webm failed: Bucket not found"
7
- * Buckety `file-blobs` i `voice-blobs` NIE ISTNIEJĄ w projekcie — lista bucketów
8
- * (16.09) to: secure_vault, brand_assets, chat-files, gemstone-models, voice-messages,
9
- * chat-attachments, odyssey-media, raydio-media, voice-samples, mayl-attachments,
10
- * rag-uploads, ptt-recordings, avatars, downloads, orb-media, founder-archive, krol-wrzutki.
11
- *
12
- * Dwa zamki, każdy pilnuje jednej połowy kontraktu z polityką RLS:
13
- * 1. bucket, który istnieje I przyjmie ten JWT (chat-files / voice-messages);
14
- * 2. ścieżka z `auth.uid()` jako PIERWSZYM segmentem, bo obie polityki INSERT
15
- * sprawdzają dokładnie `(storage.foldername(name))[1] = auth.uid()`.
16
- * Ścieżka bez segmentu użytkownika to wysyłka, która ZAWSZE padnie — i padnie
17
- * komunikatem, który nie mówi dlaczego.
18
- */
19
- import { describe, expect, it, vi, beforeEach } from "vitest";
20
-
21
- const SUB = "05261c7d-f34a-4fb2-a0e0-0f85149eb0ce";
22
- const THREAD = "dm-dbe85c4e-ec79-4e9a-a55d-7274e0e3296e-4cd1894d-b878-4fe4-b221-084419f7d225";
23
-
24
- function jwt(sub: string | null): string {
25
- const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64url");
26
- return `${b64({ alg: "HS256", typ: "JWT" })}.${b64(sub ? { sub, role: "authenticated" } : { role: "authenticated" })}.sig`;
27
- }
28
-
29
- /** Co dokładnie poszło do magazynu — jedno miejsce prawdy dla obu zamków. */
30
- let lastCall: { bucket: string; path: string; mime: string } | null = null;
31
- let userJwt: string | undefined = jwt(SUB);
32
-
33
- vi.mock("../providers/supabase.js", () => ({
34
- readSupabaseEnv: () => ({ url: "https://x.supabase.co", anonKey: "anon", userJwt }),
35
- getSupabase: () => ({
36
- storage: {
37
- from: (bucket: string) => ({
38
- upload: async (path: string, _bytes: Uint8Array, opts: { contentType: string }) => {
39
- lastCall = { bucket, path, mime: opts.contentType };
40
- return { error: null };
41
- },
42
- }),
43
- },
44
- }),
45
- }));
46
-
47
- const { uploadBlob, decodeBase64Body } = await import("../providers/blob-upload.js");
48
-
49
- beforeEach(() => { lastCall = null; userJwt = jwt(SUB); });
50
-
51
- describe("blob-upload — bucket i ścieżka, które polityka RLS naprawdę przyjmie", () => {
52
- it("plik idzie do chat-files, a ścieżka zaczyna się od auth.uid()", async () => {
53
- const desc = await uploadBlob({
54
- kind: "file",
55
- bytes: new Uint8Array([1, 2, 3]),
56
- mime: "text/plain",
57
- prefix: THREAD,
58
- filename: "lana-plikow-test.txt",
59
- });
60
-
61
- expect(lastCall!.bucket).toBe("chat-files");
62
- expect(desc.bucket).toBe("chat-files");
63
- const [uid, thread, file] = lastCall!.path.split("/");
64
- expect(uid).toBe(SUB); // ← to sprawdza polityka INSERT
65
- expect(thread).toBe(THREAD);
66
- expect(file).toMatch(/^[0-9a-f-]{36}\.txt$/);
67
- expect(desc.path).toBe(lastCall!.path);
68
- });
69
-
70
- it("głos idzie do voice-messages (nie do nieistniejącego voice-blobs)", async () => {
71
- const desc = await uploadBlob({ kind: "voice", bytes: new Uint8Array([1]), mime: "audio/webm", prefix: THREAD });
72
- expect(lastCall!.bucket).toBe("voice-messages");
73
- expect(desc.bucket).toBe("voice-messages");
74
- expect(lastCall!.path.split("/")[0]).toBe(SUB);
75
- });
76
-
77
- it("ptt też ląduje w buckecie, który istnieje i ma politykę INSERT", async () => {
78
- await uploadBlob({ kind: "ptt", bytes: new Uint8Array([1]), mime: "audio/ogg", prefix: "chat-abc" });
79
- expect(lastCall!.bucket).toBe("voice-messages");
80
- expect(lastCall!.path).toMatch(new RegExp(`^${SUB}/chat-abc/[0-9a-f-]{36}\\.ogg$`));
81
- });
82
-
83
- it("bez JWT użytkownika upload jest ODRZUCONY, zanim poleci bajt", async () => {
84
- userJwt = undefined;
85
- await expect(uploadBlob({ kind: "file", bytes: new Uint8Array([1]), mime: "text/plain" }))
86
- .rejects.toThrow(/auth\.uid\(\)/);
87
- expect(lastCall).toBeNull(); // nic nie poszło do magazynu
88
- });
89
-
90
- it("ścieżka z pamięci przechodzi przez ten sam dekoder base64 (kontrakt narzędzi)", () => {
91
- expect(new TextDecoder().decode(decodeBase64Body("VEVTVCAxNg=="))).toBe("TEST 16");
92
- });
93
- });
1
+ /**
2
+ * LANA PLIKOW — ŻYWA, NIE DOPISANA Z PAMIĘCI (16.09).
3
+ *
4
+ * Zmierzone PRZED poprawką, na żywym MCP (mcp.mosadd.com), 1 KB text/plain:
5
+ * mDM_send_file → "blob upload to file-blobs/dm-…/….txt failed: Bucket not found"
6
+ * mDM_send_voice → "blob upload to voice-blobs/dm-…/….webm failed: Bucket not found"
7
+ * Buckety `file-blobs` i `voice-blobs` NIE ISTNIEJĄ w projekcie — lista bucketów
8
+ * (16.09) to: secure_vault, brand_assets, chat-files, gemstone-models, voice-messages,
9
+ * chat-attachments, odyssey-media, raydio-media, voice-samples, mayl-attachments,
10
+ * rag-uploads, ptt-recordings, avatars, downloads, orb-media, founder-archive, krol-wrzutki.
11
+ *
12
+ * Dwa zamki, każdy pilnuje jednej połowy kontraktu z polityką RLS:
13
+ * 1. bucket, który istnieje I przyjmie ten JWT (chat-files / voice-messages);
14
+ * 2. ścieżka z `auth.uid()` jako PIERWSZYM segmentem, bo obie polityki INSERT
15
+ * sprawdzają dokładnie `(storage.foldername(name))[1] = auth.uid()`.
16
+ * Ścieżka bez segmentu użytkownika to wysyłka, która ZAWSZE padnie — i padnie
17
+ * komunikatem, który nie mówi dlaczego.
18
+ */
19
+ import { describe, expect, it, vi, beforeEach } from "vitest";
20
+
21
+ const SUB = "05261c7d-f34a-4fb2-a0e0-0f85149eb0ce";
22
+ const THREAD = "dm-dbe85c4e-ec79-4e9a-a55d-7274e0e3296e-4cd1894d-b878-4fe4-b221-084419f7d225";
23
+
24
+ function jwt(sub: string | null): string {
25
+ const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64url");
26
+ return `${b64({ alg: "HS256", typ: "JWT" })}.${b64(sub ? { sub, role: "authenticated" } : { role: "authenticated" })}.sig`;
27
+ }
28
+
29
+ /** Co dokładnie poszło do magazynu — jedno miejsce prawdy dla obu zamków. */
30
+ let lastCall: { bucket: string; path: string; mime: string } | null = null;
31
+ let userJwt: string | undefined = jwt(SUB);
32
+
33
+ vi.mock("../providers/supabase.js", () => ({
34
+ readSupabaseEnv: () => ({ url: "https://x.supabase.co", anonKey: "anon", userJwt }),
35
+ getSupabase: () => ({
36
+ storage: {
37
+ from: (bucket: string) => ({
38
+ upload: async (path: string, _bytes: Uint8Array, opts: { contentType: string }) => {
39
+ lastCall = { bucket, path, mime: opts.contentType };
40
+ return { error: null };
41
+ },
42
+ }),
43
+ },
44
+ }),
45
+ }));
46
+
47
+ const { uploadBlob, decodeBase64Body } = await import("../providers/blob-upload.js");
48
+
49
+ beforeEach(() => { lastCall = null; userJwt = jwt(SUB); });
50
+
51
+ describe("blob-upload — bucket i ścieżka, które polityka RLS naprawdę przyjmie", () => {
52
+ it("plik idzie do chat-files, a ścieżka zaczyna się od auth.uid()", async () => {
53
+ const desc = await uploadBlob({
54
+ kind: "file",
55
+ bytes: new Uint8Array([1, 2, 3]),
56
+ mime: "text/plain",
57
+ prefix: THREAD,
58
+ filename: "lana-plikow-test.txt",
59
+ });
60
+
61
+ expect(lastCall!.bucket).toBe("chat-files");
62
+ expect(desc.bucket).toBe("chat-files");
63
+ const [uid, thread, file] = lastCall!.path.split("/");
64
+ expect(uid).toBe(SUB); // ← to sprawdza polityka INSERT
65
+ expect(thread).toBe(THREAD);
66
+ expect(file).toMatch(/^[0-9a-f-]{36}\.txt$/);
67
+ expect(desc.path).toBe(lastCall!.path);
68
+ });
69
+
70
+ it("głos idzie do voice-messages (nie do nieistniejącego voice-blobs)", async () => {
71
+ const desc = await uploadBlob({ kind: "voice", bytes: new Uint8Array([1]), mime: "audio/webm", prefix: THREAD });
72
+ expect(lastCall!.bucket).toBe("voice-messages");
73
+ expect(desc.bucket).toBe("voice-messages");
74
+ expect(lastCall!.path.split("/")[0]).toBe(SUB);
75
+ });
76
+
77
+ it("ptt też ląduje w buckecie, który istnieje i ma politykę INSERT", async () => {
78
+ await uploadBlob({ kind: "ptt", bytes: new Uint8Array([1]), mime: "audio/ogg", prefix: "chat-abc" });
79
+ expect(lastCall!.bucket).toBe("voice-messages");
80
+ expect(lastCall!.path).toMatch(new RegExp(`^${SUB}/chat-abc/[0-9a-f-]{36}\\.ogg$`));
81
+ });
82
+
83
+ it("bez JWT użytkownika upload jest ODRZUCONY, zanim poleci bajt", async () => {
84
+ userJwt = undefined;
85
+ await expect(uploadBlob({ kind: "file", bytes: new Uint8Array([1]), mime: "text/plain" }))
86
+ .rejects.toThrow(/auth\.uid\(\)/);
87
+ expect(lastCall).toBeNull(); // nic nie poszło do magazynu
88
+ });
89
+
90
+ it("ścieżka z pamięci przechodzi przez ten sam dekoder base64 (kontrakt narzędzi)", () => {
91
+ expect(new TextDecoder().decode(decodeBase64Body("VEVTVCAxNg=="))).toBe("TEST 16");
92
+ });
93
+ });
@@ -1,62 +1,62 @@
1
- import { describe, expect, it } from "vitest";
2
- import { generateGroupKey } from "@mosadd/crypto";
3
- import {
4
- decryptWithGroupKey,
5
- encryptWithGroupKey,
6
- signCiphertext,
7
- unwrapEnvelopeText,
8
- } from "../crypto/channel-e2ee.js";
9
-
10
- const envelope = (text: string) =>
11
- JSON.stringify({ v: "mosadd.chat.v1", type: "text", text, reply_to: null, sent_at: new Date().toISOString() });
12
-
13
- describe("channel-e2ee pure core", () => {
14
- it("roundtrip: encrypt → decrypt returns the original text", async () => {
15
- const key = generateGroupKey();
16
- const plain = envelope("Fala 4 żyje");
17
- const payload = await encryptWithGroupKey(key, plain);
18
- expect(typeof payload).toBe("string");
19
- const out = await decryptWithGroupKey(key, payload);
20
- expect(out).toBe(plain);
21
- });
22
-
23
- it("decrypt of a legacy (non-JSON) payload returns null", async () => {
24
- const key = generateGroupKey();
25
- const legacy = Buffer.from(envelope("stara wiadomość"), "utf8").toString("base64");
26
- expect(await decryptWithGroupKey(key, legacy)).toBeNull();
27
- });
28
-
29
- it("tampered ciphertext fails the HMAC check and returns null", async () => {
30
- const key = generateGroupKey();
31
- const payload = await encryptWithGroupKey(key, envelope("nie ruszaj"));
32
- const parsed = JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as {
33
- iv: string;
34
- ciphertext: string;
35
- hmac: string;
36
- };
37
- // flip one character of the ciphertext
38
- parsed.ciphertext = (parsed.ciphertext[0] === "A" ? "B" : "A") + parsed.ciphertext.slice(1);
39
- const tampered = Buffer.from(JSON.stringify(parsed), "utf8").toString("base64");
40
- expect(await decryptWithGroupKey(key, tampered)).toBeNull();
41
- });
42
-
43
- it("wrong key does not decrypt", async () => {
44
- const keyA = generateGroupKey();
45
- const keyB = generateGroupKey();
46
- const payload = await encryptWithGroupKey(keyA, envelope("sekret"));
47
- expect(await decryptWithGroupKey(keyB, payload)).toBeNull();
48
- });
49
-
50
- it("HMAC is over the base64 ciphertext string (app parity 2C)", async () => {
51
- const key = generateGroupKey();
52
- const payload = await encryptWithGroupKey(key, "abc");
53
- const parsed = JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as { ciphertext: string; hmac: string };
54
- expect(parsed.hmac).toBe(signCiphertext(key, parsed.ciphertext));
55
- });
56
-
57
- it("unwrapEnvelopeText unwraps toolkit envelopes and leaves raw text", () => {
58
- expect(unwrapEnvelopeText(envelope("witaj"))).toBe("witaj");
59
- expect(unwrapEnvelopeText("zwykły tekst")).toBe("zwykły tekst");
60
- expect(unwrapEnvelopeText('{"audio":"AAAA"}')).toBe('{"audio":"AAAA"}');
61
- });
62
- });
1
+ import { describe, expect, it } from "vitest";
2
+ import { generateGroupKey } from "@mosadd/crypto";
3
+ import {
4
+ decryptWithGroupKey,
5
+ encryptWithGroupKey,
6
+ signCiphertext,
7
+ unwrapEnvelopeText,
8
+ } from "../crypto/channel-e2ee.js";
9
+
10
+ const envelope = (text: string) =>
11
+ JSON.stringify({ v: "mosadd.chat.v1", type: "text", text, reply_to: null, sent_at: new Date().toISOString() });
12
+
13
+ describe("channel-e2ee pure core", () => {
14
+ it("roundtrip: encrypt → decrypt returns the original text", async () => {
15
+ const key = generateGroupKey();
16
+ const plain = envelope("Fala 4 żyje");
17
+ const payload = await encryptWithGroupKey(key, plain);
18
+ expect(typeof payload).toBe("string");
19
+ const out = await decryptWithGroupKey(key, payload);
20
+ expect(out).toBe(plain);
21
+ });
22
+
23
+ it("decrypt of a legacy (non-JSON) payload returns null", async () => {
24
+ const key = generateGroupKey();
25
+ const legacy = Buffer.from(envelope("stara wiadomość"), "utf8").toString("base64");
26
+ expect(await decryptWithGroupKey(key, legacy)).toBeNull();
27
+ });
28
+
29
+ it("tampered ciphertext fails the HMAC check and returns null", async () => {
30
+ const key = generateGroupKey();
31
+ const payload = await encryptWithGroupKey(key, envelope("nie ruszaj"));
32
+ const parsed = JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as {
33
+ iv: string;
34
+ ciphertext: string;
35
+ hmac: string;
36
+ };
37
+ // flip one character of the ciphertext
38
+ parsed.ciphertext = (parsed.ciphertext[0] === "A" ? "B" : "A") + parsed.ciphertext.slice(1);
39
+ const tampered = Buffer.from(JSON.stringify(parsed), "utf8").toString("base64");
40
+ expect(await decryptWithGroupKey(key, tampered)).toBeNull();
41
+ });
42
+
43
+ it("wrong key does not decrypt", async () => {
44
+ const keyA = generateGroupKey();
45
+ const keyB = generateGroupKey();
46
+ const payload = await encryptWithGroupKey(keyA, envelope("sekret"));
47
+ expect(await decryptWithGroupKey(keyB, payload)).toBeNull();
48
+ });
49
+
50
+ it("HMAC is over the base64 ciphertext string (app parity 2C)", async () => {
51
+ const key = generateGroupKey();
52
+ const payload = await encryptWithGroupKey(key, "abc");
53
+ const parsed = JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as { ciphertext: string; hmac: string };
54
+ expect(parsed.hmac).toBe(signCiphertext(key, parsed.ciphertext));
55
+ });
56
+
57
+ it("unwrapEnvelopeText unwraps toolkit envelopes and leaves raw text", () => {
58
+ expect(unwrapEnvelopeText(envelope("witaj"))).toBe("witaj");
59
+ expect(unwrapEnvelopeText("zwykły tekst")).toBe("zwykły tekst");
60
+ expect(unwrapEnvelopeText('{"audio":"AAAA"}')).toBe('{"audio":"AAAA"}');
61
+ });
62
+ });
@@ -0,0 +1,244 @@
1
+ /**
2
+ * ZAMEK „ZERO SZYFROWANIA Z FLOTA" (29.09.2026, rozkaz Krola 28.09: „sciagnij te jebane
3
+ * szyfrowanie z naszych rozmow w kazdym kanale i w kazdej tozsamosci").
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
+ });