@mosadd/mcp 3.0.0-alpha.53 → 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 +53 -0
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-AWKITPZQ.js → chunk-IWUGKLDX.js} +144 -33
  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 -284
  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 -798
  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 -174
  27. package/src/providers/supabase-voice.ts +91 -91
  28. package/src/server.ts +195 -186
  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 +140 -45
  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,284 +1,390 @@
1
- /**
2
- * ZAMEK (27.09.2026, nastepstwo LINEAR-6089): koperta wyslana przez mDM_send z MCP ma byc
3
- * CZYTELNA — u nadawcy i u odbiorcy — a nie tylko „zaszyfrowana".
4
- *
5
- * Zmierzone na prod 27.09: mDM_send przez brame mcp.mosadd.com
6
- * 1. przy kazdym wywolaniu rodzil NOWA tozsamosc (InMemoryMdmKeyStore na zadanie HTTP),
7
- * 2. nie zapisywal self_payload ani recipient_self_payload,
8
- * 3. pisal message_type "text" zamiast "txt".
9
- * Skutek: nadawca nie odczyta wlasnej wiadomosci nigdy wiecej, odbiorca tylko przez ratchet.
10
- *
11
- * Prawdziwa kryptografia (X3DH + Double Ratchet + AES-GCM + HKDF z @mosadd/crypto), zero atrap
12
- * szyfru. Kazde "zadanie" bramy = SWIEZY serwer z tym samym kluczem API — dokladnie jak handler
13
- * bramy (createMosaddServer per request). Otwieracze "s1."/"r1." w tym pliku sa WIERNA KOPIA
14
- * algorytmu aplikacji (apps/web/src/lib/mdmE2ee.ts: tryReadOwnSelf / tryOpenPeerRecoverable),
15
- * a wektory KAT policzone bibliotekami aplikacji (@noble 2.0.1 z drzewa mosADD).
16
- */
17
-
18
- import { describe, expect, it } from "vitest";
19
- import type { DmProvider, DmListArgs, DmListResult, DmSendResult } from "@mosadd/providers";
20
- import { deriveHkdfKey, deriveSharedSecret, fromBase64, toBase64 } from "@mosadd/crypto";
21
- import { mdmTools } from "../tools/mdm.js";
22
- import { defaultProviders } from "../server.js";
23
- import {
24
- SeededMdmKeyStore,
25
- decryptFromPeer,
26
- deriveOwnMaterialFromSeed,
27
- parsePublicBundle,
28
- serializePublicBundle,
29
- type MdmKeyStore,
30
- } from "../crypto/mdm-session.js";
31
- import type { DmMessageExt, DmSendArgsExt } from "../providers/supabase-dm.js";
32
- import { InMemoryVoiceProvider } from "../providers/memory-voice.js";
33
- import type { MosaddToolContext } from "../types.js";
34
-
35
- // ---- a backend shaped like message-send / message-list / prekey directory ----
36
-
37
- type Row = {
38
- id: string;
39
- senderId: string;
40
- to: string;
41
- threadId: string;
42
- payload: Uint8Array;
43
- messageType: string;
44
- selfPayload: string | null;
45
- recipientSelfPayload: string | null;
46
- };
47
-
48
- class Backend {
49
- readonly rows: Row[] = [];
50
- readonly bundles = new Map<string, Uint8Array>();
51
- readonly kinds = new Map<string, string>();
52
- }
53
-
54
- class Lane implements DmProvider {
55
- constructor(private readonly b: Backend, private readonly me: string) {}
56
- async selfId() { return this.me; }
57
- async selfKind() { return this.b.kinds.get(this.me) ?? null; }
58
- async send(args: DmSendArgsExt): Promise<DmSendResult> {
59
- const id = `m${this.b.rows.length + 1}`;
60
- this.b.rows.push({
61
- id,
62
- senderId: this.me,
63
- to: args.to,
64
- threadId: args.threadId,
65
- payload: args.payload,
66
- messageType: args.messageType ?? "text",
67
- selfPayload: args.selfPayload ?? null,
68
- recipientSelfPayload: args.recipientSelfPayload ?? null,
69
- });
70
- return { id, deliveredAt: new Date(0).toISOString() };
71
- }
72
- async list(args: DmListArgs): Promise<DmListResult> {
73
- // message_list_v2: self_payload only to its sender, recipient_self_payload only to the others.
74
- const messages: DmMessageExt[] = this.b.rows
75
- .filter((r) => r.threadId === args.threadId)
76
- .map((r) => ({
77
- id: r.id,
78
- senderId: r.senderId,
79
- payload: r.payload,
80
- timestamp: new Date(0).toISOString(),
81
- threadId: r.threadId,
82
- messageType: r.messageType,
83
- selfPayload: r.senderId === this.me ? r.selfPayload : null,
84
- recipientSelfPayload: r.senderId !== this.me ? r.recipientSelfPayload : null,
85
- }));
86
- return { messages, nextCursor: null };
87
- }
88
- async publishPrekeyBundle(bundle: Uint8Array) { this.b.bundles.set(this.me, bundle); }
89
- async fetchPrekeyBundle(peerId: string) { return this.b.bundles.get(peerId) ?? null; }
90
- }
91
-
92
- const tool = (name: string) => {
93
- const t = mdmTools.find((x) => x.name === name);
94
- if (!t) throw new Error(`tool ${name} not found`);
95
- return t.handler;
96
- };
97
-
98
- const noopLog: MosaddToolContext["log"] = () => {};
99
-
100
- /** One gateway request: a FRESH provider registry built from the API key, like handler.ts. */
101
- function gatewayRequest(b: Backend, me: string, apiKey: string): MosaddToolContext {
102
- const providers = defaultProviders(
103
- { dm: new Lane(b, me), voice: new InMemoryVoiceProvider(me) },
104
- { mdmSecret: apiKey },
105
- );
106
- return { options: { mode: "cloud", hubUrl: "https://mcp.mosadd.com", apiKey }, providers, log: noopLog };
107
- }
108
-
109
- /** The app of a person: a seed-anchored keystore with its bundle published (login did it). */
110
- async function appOf(b: Backend, me: string, seedByte: number) {
111
- const keys = new SeededMdmKeyStore(new Uint8Array(32).fill(seedByte));
112
- b.bundles.set(me, serializePublicBundle(await keys.getOwnMaterial()));
113
- b.kinds.set(me, "human");
114
- return keys;
115
- }
116
-
117
- // ---- the app's openers, copied algorithm-for-algorithm from apps/web/src/lib/mdmE2ee.ts ----
118
-
119
- async function appOpenAesGcm(tag: string, keyBytes: Uint8Array, sealed: string | null): Promise<string | null> {
120
- if (!sealed || !sealed.startsWith(tag)) return null;
121
- const packed = fromBase64(sealed.slice(tag.length));
122
- if (packed.length <= 12) return null;
123
- const key = await crypto.subtle.importKey("raw", keyBytes as BufferSource, { name: "AES-GCM" }, false, ["decrypt"]);
124
- const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: packed.slice(0, 12) }, key, packed.slice(12));
125
- return new TextDecoder().decode(pt);
126
- }
127
-
128
- /** tryOpenPeerRecoverable: HKDF(ECDH(my IK priv, SENDER's PUBLISHED IK), info) → AES-GCM. */
129
- async function appOpenRecipientCopy(b: Backend, me: MdmKeyStore, senderId: string, sealed: string | null) {
130
- const raw = b.bundles.get(senderId);
131
- if (!raw) return null;
132
- const sender = parsePublicBundle(raw);
133
- const own = await me.getOwnMaterial();
134
- const secret = await deriveSharedSecret(own.identity.privateKey, sender.identityPublicKey);
135
- const k = await deriveHkdfKey(secret, {
136
- info: new TextEncoder().encode("mosadd.mdm.recipient-recoverable.v1"),
137
- length: 32,
138
- });
139
- return appOpenAesGcm("r1.", k, sealed);
140
- }
141
-
142
- /** tryReadOwnSelf: HKDF(seed, "mosadd-mdm-self-read") → AES-GCM over "s1.". */
143
- async function appOpenSelfCopy(seed: Uint8Array, sealed: string | null) {
144
- const k = await deriveHkdfKey(seed, { info: new TextEncoder().encode("mosadd-mdm-self-read"), length: 32 });
145
- return appOpenAesGcm("s1.", k, sealed);
146
- }
147
-
148
- const API_KEY = "mosadd_sk_live_0123456789abcdef0123456789abcdef";
149
- const LINE = "general-line-identity";
150
- const KING = "king-identity";
151
-
152
- describe("mDM_send z MCP — koperta czytelna u nadawcy i u odbiorcy (zamek 27.09)", () => {
153
- it("KAT: tozsamosc z ziarna jest bit w bit ta, ktora wylicza aplikacja", async () => {
154
- const seed = new Uint8Array(32).map((_, i) => i + 1);
155
- const m = await deriveOwnMaterialFromSeed(seed);
156
- // policzone @noble/curves+hashes 2.0.1 z drzewa mosADD (tych samych, na ktorych stoi web)
157
- expect(toBase64(m.identity.publicKey)).toBe("kGJhDa1OHhlUYRQ0ZgztQfIucOPLxkdOK2iBJpNEWEU=");
158
- expect(toBase64(m.signingIdentity.publicKey)).toBe("4XxF9XwcOS25C+G8oS/NGXor6ahKsOklnpq3JUQHfVY=");
159
- expect(toBase64(m.signedPrekey.pair.publicKey)).toBe("0/QU9p52caXSkyjLx/PH4C/9A/UzOZaPRecMtVBQj0Y=");
160
- expect(m.signedPrekey.id).toBe(1);
161
- expect(m.oneTimePrekeys).toHaveLength(0);
162
- expect(toBase64((await new SeededMdmKeyStore(seed).getSelfKeyBytes())!)).toBe(
163
- "M3XnFLHiETCzgVS+X/Uvl52BhWL9l1EsorKIOXvmKjI=",
164
- );
165
- });
166
-
167
- it("dwa zadania bramy z tym samym kluczem = JEDNA tozsamosc (nie nowa co wywolanie)", async () => {
168
- const b = new Backend();
169
- const a = await gatewayRequest(b, LINE, API_KEY).providers.keys.getOwnMaterial();
170
- const c = await gatewayRequest(b, LINE, API_KEY).providers.keys.getOwnMaterial();
171
- expect(toBase64(a.identity.publicKey)).toBe(toBase64(c.identity.publicKey));
172
- expect(toBase64(a.signedPrekey.pair.publicKey)).toBe(toBase64(c.signedPrekey.pair.publicKey));
173
- const other = await gatewayRequest(b, LINE, API_KEY + "ff").providers.keys.getOwnMaterial();
174
- expect(toBase64(other.identity.publicKey)).not.toBe(toBase64(a.identity.publicKey));
175
- });
176
-
177
- it("wysylka linii do Krola: txt + self_payload + recipient_self_payload; oboje czytaja po nowym zadaniu", async () => {
178
- const b = new Backend();
179
- b.kinds.set(LINE, "agent");
180
- const kingSeed = new Uint8Array(32).fill(7);
181
- const king = await appOf(b, KING, 7);
182
-
183
- const sent = (await tool("mDM_send")({ to: KING, text: "meldunek: brama czytelna" }, gatewayRequest(b, LINE, API_KEY))) as {
184
- sender_copy: boolean; recipient_copy: boolean; identity: string; message_id: string;
185
- };
186
- expect(sent).toMatchObject({ sender_copy: true, recipient_copy: true });
187
- expect(["published", "consistent"]).toContain(sent.identity);
188
-
189
- const row = b.rows.at(-1)!;
190
- expect(row.messageType).toBe("txt");
191
- expect(row.selfPayload).toMatch(/^s1\./);
192
- expect(row.recipientSelfPayload).toMatch(/^r1\./);
193
- // ciphertext na drucie, nie tekst
194
- expect(Buffer.from(row.payload).toString("utf8")).not.toContain("meldunek");
195
- expect(row.selfPayload).not.toContain("meldunek");
196
-
197
- // NADAWCA: nowe zadanie bramy (inna lambda, pusta pamiec wyslanych) czyta swoja wiadomosc.
198
- const lineRead = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE, API_KEY))) as {
199
- messages: Array<{ text: string; sender_identity_id: string }>;
200
- };
201
- expect(lineRead.messages.map((m) => m.text)).toEqual(["meldunek: brama czytelna"]);
202
-
203
- // ODBIORCA w aplikacji, BEZ sesji ratchetu (nowe urzadzenie): kopia r1. algorytmem aplikacji.
204
- expect(await appOpenRecipientCopy(b, king, LINE, row.recipientSelfPayload)).toBe("meldunek: brama czytelna");
205
- // ODBIORCA przez ratchet (koperta niesie naglowek X3DH do opublikowanego peku Krola).
206
- const viaRatchet = await decryptFromPeer(new SeededMdmKeyStore(kingSeed), LINE, row.payload);
207
- expect(new TextDecoder().decode(viaRatchet)).toBe("meldunek: brama czytelna");
208
-
209
- // Druga wysylka z NOWEGO zadania: ta sama tozsamosc -> pek w katalogu sie nie zmienia.
210
- const bundleBefore = toBase64(b.bundles.get(LINE)!);
211
- const second = (await tool("mDM_send")({ to: KING, text: "drugi" }, gatewayRequest(b, LINE, API_KEY))) as { identity: string };
212
- expect(second.identity).toBe("consistent");
213
- expect(toBase64(b.bundles.get(LINE)!)).toBe(bundleBefore);
214
- expect(await appOpenRecipientCopy(b, king, LINE, b.rows.at(-1)!.recipientSelfPayload)).toBe("drugi");
215
- });
216
-
217
- it("watek wlasny linii (dm:ja:ja): nadawca czyta z nowego zadania, kopia s1. otwiera sie algorytmem aplikacji", async () => {
218
- const b = new Backend();
219
- b.kinds.set(LINE, "agent");
220
- await tool("mDM_send")({ to: LINE, text: "notatka do siebie" }, gatewayRequest(b, LINE, API_KEY));
221
- const row = b.rows.at(-1)!;
222
- expect(row.threadId).toBe(`dm:${LINE}:${LINE}`);
223
- expect(row.messageType).toBe("txt");
224
- expect(row.selfPayload).toMatch(/^s1\./);
225
-
226
- const read = (await tool("mDM_list")({ contact_id: LINE }, gatewayRequest(b, LINE, API_KEY))) as {
227
- messages: Array<{ text: string }>;
228
- };
229
- expect(read.messages.map((m) => m.text)).toEqual(["notatka do siebie"]);
230
-
231
- // To samo ziarno w aplikacji otwiera kopie wlasna jej algorytmem (tryReadOwnSelf).
232
- const { deriveMdmSeedFromSecret } = await import("../crypto/mdm-session.js");
233
- expect(await appOpenSelfCopy(await deriveMdmSeedFromSecret(API_KEY), row.selfPayload)).toBe("notatka do siebie");
234
- });
235
-
236
- it("linia agenta ze starym losowym pekiem: pek zastapiony; pek CZLOWIEKA z aplikacji nigdy nie nadpisany", async () => {
237
- // agent: martwy pek po dawnym losowym przebiegu -> zastapiony stala tozsamoscia
238
- const b = new Backend();
239
- b.kinds.set(LINE, "agent");
240
- const stale = serializePublicBundle(await new SeededMdmKeyStore(new Uint8Array(32).fill(99)).getOwnMaterial());
241
- b.bundles.set(LINE, stale);
242
- await appOf(b, KING, 7);
243
- const r = (await tool("mDM_send")({ to: KING, text: "x" }, gatewayRequest(b, LINE, API_KEY))) as { identity: string };
244
- expect(r.identity).toBe("published");
245
- expect(toBase64(b.bundles.get(LINE)!)).not.toBe(toBase64(stale));
246
-
247
- // czlowiek (klucz Krola uzyty przez agenta): pek aplikacji zostaje, kopii r1. nie ma (bylaby pod zla tozsamoscia)
248
- const h = new Backend();
249
- const kingApp = serializePublicBundle(await (await appOf(h, KING, 7)).getOwnMaterial());
250
- await appOf(h, "peer", 5);
251
- const hr = (await tool("mDM_send")({ to: "peer", text: "y" }, gatewayRequest(h, KING, API_KEY))) as {
252
- identity: string; recipient_copy: boolean; sender_copy: boolean;
253
- };
254
- expect(hr).toMatchObject({ identity: "foreign", recipient_copy: false, sender_copy: true });
255
- expect(toBase64(h.bundles.get(KING)!)).toBe(toBase64(kingApp));
256
- expect(h.rows.at(-1)!.messageType).toBe("txt");
257
- });
258
-
259
- it("odbior w MCP: wiadomosc Krola z kopia r1. czytelna w bramie bez sesji ratchetu", async () => {
260
- const b = new Backend();
261
- b.kinds.set(LINE, "agent");
262
- const king = await appOf(b, KING, 7);
263
- // linia publikuje swoj pek (pierwsze zadanie), Krol pisze z aplikacji z kopia r1.
264
- await tool("mDM_send")({ to: KING, text: "hej" }, gatewayRequest(b, LINE, API_KEY));
265
- const { sealForPeerRecoverable, fetchVerifiedBundle, encryptForPeer } = await import("../crypto/mdm-session.js");
266
- const kingLane = new Lane(b, KING);
267
- const lineBundle = (await fetchVerifiedBundle(kingLane, LINE))!;
268
- const inner = new TextEncoder().encode("rozkaz od Krola");
269
- // ratchet Krola jest juz daleko (n>=1, bez naglowka) — brama go nie ma; ratuje ja r1.
270
- await encryptForPeer(king, kingLane, LINE, new TextEncoder().encode("pierwsza"));
271
- const env = await encryptForPeer(king, kingLane, LINE, inner);
272
- await kingLane.send({
273
- to: LINE,
274
- threadId: `dm:${[KING, LINE].sort().join(":")}`,
275
- payload: env,
276
- messageType: "txt",
277
- recipientSelfPayload: await sealForPeerRecoverable(king, lineBundle, inner),
278
- });
279
- const read = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE, API_KEY))) as {
280
- messages: Array<{ text: string; sender_identity_id: string }>;
281
- };
282
- expect(read.messages.find((m) => m.sender_identity_id === KING)?.text).toBe("rozkaz od Krola");
283
- });
284
- });
1
+ /**
2
+ * ZAMEK (27.09.2026, nastepstwo LINEAR-6089, POPRAWKA po niezaleznej weryfikacji toru mdm-brama):
3
+ * wiadomosc wyslana przez mDM_send z MCP ma byc CZYTELNA u nadawcy i u odbiorcy — na KAZDYM
4
+ * kluczu tej samej tozsamosci, nie tylko na tym, ktory ja wyslal — a aplikacja ma mowic PRAWDE,
5
+ * gdy czegos pokazac nie moze.
6
+ *
7
+ * Co zmierzono 27.09:
8
+ * 1. mDM_send przez brame rodzil NOWA tozsamosc co wywolanie (keystore w pamieci na zadanie HTTP).
9
+ * 2. Pierwsza poprawka (alpha.53) dala tozsamosc stala per KLUCZ API i pozwolila linii agenta
10
+ * podmieniac pek w katalogu. Tozsamosc ma WIELE aktywnych kluczy (general@: 8, wszystkie
11
+ * uzywane w 3 dni; 7 z 17 agentow ma po kilka), wiec pek przeskakiwal miedzy tozsamosciami:
12
+ * kopia s1. otwierala sie tylko pod kluczem, ktory ja zapisal, a kopie r1. przestawaly sie
13
+ * otwierac u odbiorcy po nastepnej wysylce innym kluczem.
14
+ * 3. alpha.53 pisala tez `txt` + s1. pod ziarnem z klucza API na kluczu CZLOWIEKA — aplikacja
15
+ * (mdmE2ee.ts readOwnMdmMessage) nie otwiera takiej kopii i podawala FALSZYWY powod
16
+ * („wyslane z innego urzadzenia" / „odblokuj tozsamosc") zamiast „wyslane przez MCP".
17
+ *
18
+ * Naprawa u zrodla = regula Krola (DECYZJE-KROLA 20.09 12:56Z „E2EE wewnetrzne = zero"): gdy
19
+ * strona rozmowy jest linia agenta, DM idzie JAWNIE — tak samo robi aplikacja (peerIsAgent).
20
+ * Jawny tekst czyta kazdy klucz linii i aplikacja odbiorcy na kazdym urzadzeniu; pek nie jest
21
+ * potrzebny, wiec nie ma czego podmieniac. Czlowiek↔czlowiek zostaje E2EE, a MCP na kluczu
22
+ * czlowieka NIE rusza jego peku z aplikacji, nie pisze kopii s1. i znakuje koperte `text`.
23
+ *
24
+ * Prawdziwa kryptografia (X3DH + Double Ratchet + AES-GCM + HKDF z @mosadd/crypto), zero atrap
25
+ * szyfru. Kazde "zadanie" bramy = SWIEZY serwer z danym kluczem API — jak handler bramy.
26
+ */
27
+
28
+ import { execFileSync } from "node:child_process";
29
+ import { describe, expect, it } from "vitest";
30
+ import type { DmProvider, DmListArgs, DmListResult, DmSendResult } from "@mosadd/providers";
31
+ import { deriveHkdfKey, fromBase64, toBase64 } from "@mosadd/crypto";
32
+ import { mdmTools } from "../tools/mdm.js";
33
+ import { createMosaddServer, defaultProviders } from "../server.js";
34
+ import {
35
+ SeededMdmKeyStore,
36
+ decryptFromPeer,
37
+ deriveMdmSeedFromSecret,
38
+ deriveOwnMaterialFromSeed,
39
+ encryptForPeer,
40
+ fetchVerifiedBundle,
41
+ sealForPeerRecoverable,
42
+ serializePublicBundle,
43
+ type MdmKeyStore,
44
+ } from "../crypto/mdm-session.js";
45
+ import type { DmMessageExt, DmSendArgsExt } from "../providers/supabase-dm.js";
46
+ import { InMemoryVoiceProvider } from "../providers/memory-voice.js";
47
+ import type { MosaddToolContext } from "../types.js";
48
+
49
+ // ---- a backend shaped like message-send / message-list / prekey directory / identities ----
50
+
51
+ type Row = {
52
+ id: string;
53
+ senderId: string;
54
+ to: string;
55
+ threadId: string;
56
+ payload: Uint8Array;
57
+ messageType: string;
58
+ selfPayload: string | null;
59
+ recipientSelfPayload: string | null;
60
+ };
61
+
62
+ class Backend {
63
+ readonly rows: Row[] = [];
64
+ readonly bundles = new Map<string, Uint8Array>();
65
+ readonly kinds = new Map<string, string>();
66
+ publishes = 0;
67
+ }
68
+
69
+ class Lane implements DmProvider {
70
+ constructor(private readonly b: Backend, private readonly me: string) {}
71
+ async selfId() { return this.me; }
72
+ async selfKind() { return this.b.kinds.get(this.me) ?? null; }
73
+ async peerKind(id: string) { return this.b.kinds.get(id) ?? null; }
74
+ async send(args: DmSendArgsExt): Promise<DmSendResult> {
75
+ const id = `m${this.b.rows.length + 1}`;
76
+ this.b.rows.push({
77
+ id,
78
+ senderId: this.me,
79
+ to: args.to,
80
+ threadId: args.threadId,
81
+ payload: args.payload,
82
+ messageType: args.messageType ?? "text",
83
+ selfPayload: args.selfPayload ?? null,
84
+ recipientSelfPayload: args.recipientSelfPayload ?? null,
85
+ });
86
+ return { id, deliveredAt: new Date(0).toISOString() };
87
+ }
88
+ async list(args: DmListArgs): Promise<DmListResult> {
89
+ // message_list_v2: self_payload only to its sender, recipient_self_payload only to the others.
90
+ const messages: DmMessageExt[] = this.b.rows
91
+ .filter((r) => r.threadId === args.threadId)
92
+ .map((r) => ({
93
+ id: r.id,
94
+ senderId: r.senderId,
95
+ payload: r.payload,
96
+ timestamp: new Date(0).toISOString(),
97
+ threadId: r.threadId,
98
+ messageType: r.messageType,
99
+ selfPayload: r.senderId === this.me ? r.selfPayload : null,
100
+ recipientSelfPayload: r.senderId !== this.me ? r.recipientSelfPayload : null,
101
+ }));
102
+ return { messages, nextCursor: null };
103
+ }
104
+ async publishPrekeyBundle(bundle: Uint8Array) {
105
+ this.b.publishes += 1;
106
+ this.b.bundles.set(this.me, bundle);
107
+ }
108
+ async fetchPrekeyBundle(peerId: string) { return this.b.bundles.get(peerId) ?? null; }
109
+ }
110
+
111
+ const tool = (name: string) => {
112
+ const t = mdmTools.find((x) => x.name === name);
113
+ if (!t) throw new Error(`tool ${name} not found`);
114
+ return t.handler;
115
+ };
116
+
117
+ const noopLog: MosaddToolContext["log"] = () => {};
118
+
119
+ /** One gateway request: a FRESH provider registry built from the API key, like handler.ts. */
120
+ function gatewayRequest(b: Backend, me: string, apiKey: string): MosaddToolContext {
121
+ const providers = defaultProviders(
122
+ { dm: new Lane(b, me), voice: new InMemoryVoiceProvider(me) },
123
+ { mdmSecret: apiKey },
124
+ );
125
+ return { options: { mode: "cloud", hubUrl: "https://mcp.mosadd.com", apiKey }, providers, log: noopLog };
126
+ }
127
+
128
+ /** The app of a person: a seed-anchored keystore with its bundle published (login did it). */
129
+ async function appOf(b: Backend, me: string, seedByte: number) {
130
+ const keys = new SeededMdmKeyStore(new Uint8Array(32).fill(seedByte));
131
+ b.bundles.set(me, serializePublicBundle(await keys.getOwnMaterial()));
132
+ b.kinds.set(me, "human");
133
+ return keys;
134
+ }
135
+
136
+ /** What the app shows for a plaintext row (ircApi decodePayload: base64 → UTF-8 text). */
137
+ const appPlaintext = (row: Row) => new TextDecoder().decode(row.payload);
138
+
139
+ // ---- the app's decisions, algorithm-for-algorithm from apps/web/src/lib/mdmE2ee.ts ----
140
+ // (the drift check at the bottom compares these lines with the app's source on origin/main)
141
+
142
+ async function appOpenAesGcm(tag: string, keyBytes: Uint8Array, sealed: string | null): Promise<string | null> {
143
+ if (!sealed || !sealed.startsWith(tag)) return null;
144
+ const packed = fromBase64(sealed.slice(tag.length));
145
+ if (packed.length <= 12) return null;
146
+ const key = await crypto.subtle.importKey("raw", keyBytes as BufferSource, { name: "AES-GCM" }, false, ["decrypt"]);
147
+ try {
148
+ const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: packed.slice(0, 12) }, key, packed.slice(12));
149
+ return new TextDecoder().decode(pt);
150
+ } catch {
151
+ return null;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * readOwnMdmMessage (f95557f), for a device that holds the owner's app seed. Steps 2 (this
157
+ * device's sent memory) is empty by construction: the message was sent by MCP, not this device.
158
+ */
159
+ async function appReadOwn(
160
+ appSeed: Uint8Array,
161
+ appKeys: MdmKeyStore,
162
+ myIdentityId: string,
163
+ row: Row,
164
+ ): Promise<{ text: string; reason: null } | { text: null; reason: "key" | "agent" | "device" }> {
165
+ const selfKey = await deriveHkdfKey(appSeed, { info: new TextEncoder().encode("mosadd-mdm-self-read"), length: 32 });
166
+ const zKopii = await appOpenAesGcm("s1.", selfKey, row.selfPayload);
167
+ if (zKopii != null) return { text: zKopii, reason: null };
168
+ const maKlucz = true;
169
+ const para = row.threadId.slice(3).split(":thread:")[0]!.split(":");
170
+ const doSiebie = para.length === 2 && para[0] === myIdentityId && para[1] === myIdentityId;
171
+ if (doSiebie && maKlucz) {
172
+ try {
173
+ return { text: new TextDecoder().decode(await decryptFromPeer(appKeys, myIdentityId, row.payload)), reason: null };
174
+ } catch { /* fall through */ }
175
+ }
176
+ const kopiaDlaMnie = doSiebie || (!!row.selfPayload && row.selfPayload.startsWith("s1."));
177
+ if (!maKlucz && kopiaDlaMnie) return { text: null, reason: "key" };
178
+ return { text: null, reason: row.messageType === "text" ? "agent" : "device" };
179
+ }
180
+
181
+ const KEY_A = "mosadd_sk_live_0123456789abcdef0123456789abcdef";
182
+ const KEY_B = "mosadd_sk_live_fedcba9876543210fedcba9876543210"; // druga, rownolegle aktywna, ta sama linia
183
+ const LINE = "general-line-identity";
184
+ const KING = "king-identity";
185
+ const PEER = "peer-human-identity";
186
+
187
+ type SendOut = {
188
+ message_id: string;
189
+ encrypted: boolean;
190
+ mode: string;
191
+ identity: string;
192
+ sender_copy: boolean;
193
+ recipient_copy: boolean;
194
+ };
195
+ type ListOut = { messages: Array<{ text: string; sender_identity_id: string; encrypted: boolean }> };
196
+
197
+ describe("mDM_send z MCP — czytelne na kazdym kluczu, prawdziwe powody w aplikacji (zamek 27.09)", () => {
198
+ it("KAT: tozsamosc z ziarna jest bit w bit ta, ktora wylicza aplikacja", async () => {
199
+ const seed = new Uint8Array(32).map((_, i) => i + 1);
200
+ const m = await deriveOwnMaterialFromSeed(seed);
201
+ // policzone @noble/curves+hashes 2.0.1 z drzewa mosADD (tych samych, na ktorych stoi web)
202
+ expect(toBase64(m.identity.publicKey)).toBe("kGJhDa1OHhlUYRQ0ZgztQfIucOPLxkdOK2iBJpNEWEU=");
203
+ expect(toBase64(m.signingIdentity.publicKey)).toBe("4XxF9XwcOS25C+G8oS/NGXor6ahKsOklnpq3JUQHfVY=");
204
+ expect(toBase64(m.signedPrekey.pair.publicKey)).toBe("0/QU9p52caXSkyjLx/PH4C/9A/UzOZaPRecMtVBQj0Y=");
205
+ expect(m.signedPrekey.id).toBe(1);
206
+ expect(m.oneTimePrekeys).toHaveLength(0);
207
+ expect(toBase64((await new SeededMdmKeyStore(seed).getSelfKeyBytes())!)).toBe(
208
+ "M3XnFLHiETCzgVS+X/Uvl52BhWL9l1EsorKIOXvmKjI=",
209
+ );
210
+ });
211
+
212
+ it("dwa zadania bramy z tym samym kluczem = JEDNA tozsamosc (nie nowa co wywolanie)", async () => {
213
+ const b = new Backend();
214
+ const a = await gatewayRequest(b, LINE, KEY_A).providers.keys.getOwnMaterial();
215
+ const c = await gatewayRequest(b, LINE, KEY_A).providers.keys.getOwnMaterial();
216
+ expect(toBase64(a.identity.publicKey)).toBe(toBase64(c.identity.publicKey));
217
+ expect(toBase64(a.signedPrekey.pair.publicKey)).toBe(toBase64(c.signedPrekey.pair.publicKey));
218
+ });
219
+
220
+ it("linia agenta, DWA klucze naprzemiennie: jawny txt, kazdy klucz czyta wszystko, Krol czyta w aplikacji, katalog nietkniety", async () => {
221
+ const b = new Backend();
222
+ b.kinds.set(LINE, "agent");
223
+ await appOf(b, KING, 7);
224
+
225
+ const s1 = (await tool("mDM_send")({ to: KING, text: "meldunek z klucza A" }, gatewayRequest(b, LINE, KEY_A))) as SendOut;
226
+ const s2 = (await tool("mDM_send")({ to: KING, text: "meldunek z klucza B" }, gatewayRequest(b, LINE, KEY_B))) as SendOut;
227
+ const s3 = (await tool("mDM_send")({ to: KING, text: "znow klucz A" }, gatewayRequest(b, LINE, KEY_A))) as SendOut;
228
+ for (const s of [s1, s2, s3]) {
229
+ expect(s).toMatchObject({ encrypted: false, mode: "plaintext_agent_lane", sender_copy: true, recipient_copy: true, identity: "untouched" });
230
+ }
231
+
232
+ // Katalog kluczy: ZERO zapisow — pek linii nie istnieje, wiec nie ma czego przestawiac.
233
+ expect(b.publishes).toBe(0);
234
+ expect(b.bundles.has(LINE)).toBe(false);
235
+
236
+ for (const row of b.rows) {
237
+ expect(row.messageType).toBe("txt");
238
+ expect(row.selfPayload).toBeNull();
239
+ expect(row.recipientSelfPayload).toBeNull();
240
+ }
241
+ // Krol w aplikacji, na DOWOLNYM urzadzeniu: jawny tekst, bez kluczy i bez ratchetu.
242
+ expect(b.rows.map(appPlaintext)).toEqual(["meldunek z klucza A", "meldunek z klucza B", "znow klucz A"]);
243
+
244
+ // Nadawca: KAZDY klucz linii, swieze zadanie (pusta pamiec wyslanych), czyta WSZYSTKIE trzy.
245
+ for (const k of [KEY_A, KEY_B]) {
246
+ const read = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE, k))) as ListOut;
247
+ expect(read.messages.map((m) => m.text)).toEqual(["meldunek z klucza A", "meldunek z klucza B", "znow klucz A"]);
248
+ }
249
+ });
250
+
251
+ it("watek wlasny linii (dm:ja:ja): zapis kluczem A, odczyt kluczem B", async () => {
252
+ const b = new Backend();
253
+ b.kinds.set(LINE, "agent");
254
+ await tool("mDM_send")({ to: LINE, text: "notatka do siebie" }, gatewayRequest(b, LINE, KEY_A));
255
+ const row = b.rows.at(-1)!;
256
+ expect(row.threadId).toBe(`dm:${LINE}:${LINE}`);
257
+ expect(row.messageType).toBe("txt");
258
+ const read = (await tool("mDM_list")({ contact_id: LINE }, gatewayRequest(b, LINE, KEY_B))) as ListOut;
259
+ expect(read.messages.map((m) => m.text)).toEqual(["notatka do siebie"]);
260
+ expect(b.publishes).toBe(0);
261
+ });
262
+
263
+ it("czlowiek pisze przez MCP DO linii agenta: jawnie (jak peerIsAgent w aplikacji)", async () => {
264
+ const b = new Backend();
265
+ b.kinds.set(LINE, "agent");
266
+ await appOf(b, KING, 7);
267
+ const s = (await tool("mDM_send")({ to: LINE, text: "rozkaz" }, gatewayRequest(b, KING, KEY_A))) as SendOut;
268
+ expect(s.mode).toBe("plaintext_agent_lane");
269
+ expect(appPlaintext(b.rows.at(-1)!)).toBe("rozkaz");
270
+ const lineRead = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE, KEY_B))) as ListOut;
271
+ expect(lineRead.messages.map((m) => m.text)).toEqual(["rozkaz"]);
272
+ });
273
+
274
+ it("klucz CZLOWIEKA do czlowieka: E2EE, pek z aplikacji nietkniety, bez s1., typ `text` — aplikacja mowi PRAWDZIWY powod", async () => {
275
+ const b = new Backend();
276
+ const kingSeed = new Uint8Array(32).fill(7);
277
+ const kingApp = await appOf(b, KING, 7);
278
+ const kingBundle = toBase64(b.bundles.get(KING)!);
279
+ const peerApp = await appOf(b, PEER, 5);
280
+
281
+ const s = (await tool("mDM_send")({ to: PEER, text: "tajne" }, gatewayRequest(b, KING, KEY_A))) as SendOut;
282
+ expect(s).toMatchObject({ encrypted: true, mode: "e2ee", identity: "foreign", sender_copy: false, recipient_copy: false });
283
+ const row = b.rows.at(-1)!;
284
+ expect(row.messageType).toBe("text");
285
+ expect(row.selfPayload).toBeNull();
286
+ expect(appPlaintext(row)).not.toContain("tajne");
287
+ expect(b.publishes).toBe(0);
288
+ expect(toBase64(b.bundles.get(KING)!)).toBe(kingBundle);
289
+
290
+ // Odbiorca czyta przez ratchet (koperta niesie naglowek X3DH do JEGO peku z aplikacji).
291
+ expect(new TextDecoder().decode(await decryptFromPeer(peerApp, KING, row.payload))).toBe("tajne");
292
+ // Wlasciciel w aplikacji: tresci nie ma (MCP nie zna ziarna aplikacji) i powod jest PRAWDZIWY.
293
+ expect(await appReadOwn(kingSeed, kingApp, KING, row)).toEqual({ text: null, reason: "agent" });
294
+ });
295
+
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 () => {
299
+ const b = new Backend();
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" });
303
+ const row = b.rows.at(-1)!;
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);
308
+ });
309
+
310
+ it("czlowiek BEZ peku: MCP nie publikuje sam (ani mDM_send, ani autoPublishKeys); jawne mDM_publish_keys moze", async () => {
311
+ const b = new Backend();
312
+ b.kinds.set(KING, "human");
313
+ await appOf(b, PEER, 5);
314
+ const s = (await tool("mDM_send")({ to: PEER, text: "x" }, gatewayRequest(b, KING, KEY_A))) as SendOut;
315
+ expect(s.identity).toBe("absent");
316
+ expect(b.bundles.has(KING)).toBe(false);
317
+
318
+ createMosaddServer({ apiKey: KEY_A, autoPublishKeys: true, providers: { dm: new Lane(b, KING), voice: new InMemoryVoiceProvider(KING) } });
319
+ await new Promise((r) => setTimeout(r, 50));
320
+ expect(b.bundles.has(KING)).toBe(false);
321
+ expect(b.publishes).toBe(0);
322
+
323
+ const p = (await tool("mDM_publish_keys")({}, gatewayRequest(b, KING, KEY_A))) as { published: boolean; identity: string };
324
+ expect(p).toMatchObject({ published: true, identity: "published" });
325
+ });
326
+
327
+ it("jawne mDM_publish_keys na kluczu czlowieka NIE nadpisuje peku z aplikacji", async () => {
328
+ const b = new Backend();
329
+ await appOf(b, KING, 7);
330
+ const before = toBase64(b.bundles.get(KING)!);
331
+ const p = (await tool("mDM_publish_keys")({}, gatewayRequest(b, KING, KEY_A))) as { published: boolean; identity: string; note?: string };
332
+ expect(p).toMatchObject({ published: false, identity: "foreign" });
333
+ expect(p.note).toBeTruthy();
334
+ expect(toBase64(b.bundles.get(KING)!)).toBe(before);
335
+ expect(b.publishes).toBe(0);
336
+ });
337
+
338
+ it("autoPublishKeys na linii agenta: zero zapisow w katalogu (zaden z jej kluczy nie przestawia peku)", async () => {
339
+ const b = new Backend();
340
+ b.kinds.set(LINE, "agent");
341
+ for (const k of [KEY_A, KEY_B]) {
342
+ createMosaddServer({ apiKey: k, autoPublishKeys: true, providers: { dm: new Lane(b, LINE), voice: new InMemoryVoiceProvider(LINE) } });
343
+ }
344
+ await new Promise((r) => setTimeout(r, 50));
345
+ expect(b.publishes).toBe(0);
346
+ expect(b.bundles.has(LINE)).toBe(false);
347
+ });
348
+
349
+ it("stara koperta E2EE od Krola z kopia r1. (pek linii sprzed poprawki) dalej czytelna w bramie", async () => {
350
+ const b = new Backend();
351
+ b.kinds.set(LINE, "agent");
352
+ const king = await appOf(b, KING, 7);
353
+ // pek linii opublikowany przez alpha.53 z ziarna klucza A
354
+ b.bundles.set(LINE, serializePublicBundle(await new SeededMdmKeyStore(await deriveMdmSeedFromSecret(KEY_A)).getOwnMaterial()));
355
+ const kingLane = new Lane(b, KING);
356
+ const lineBundle = (await fetchVerifiedBundle(kingLane, LINE))!;
357
+ const inner = new TextEncoder().encode("rozkaz od Krola");
358
+ await encryptForPeer(king, kingLane, LINE, new TextEncoder().encode("pierwsza"));
359
+ const env = await encryptForPeer(king, kingLane, LINE, inner);
360
+ await kingLane.send({
361
+ to: LINE,
362
+ threadId: `dm:${[KING, LINE].sort().join(":")}`,
363
+ payload: env,
364
+ messageType: "txt",
365
+ recipientSelfPayload: await sealForPeerRecoverable(king, lineBundle, inner),
366
+ });
367
+ const read = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE, KEY_A))) as ListOut;
368
+ expect(read.messages.find((m) => m.sender_identity_id === KING)?.text).toBe("rozkaz od Krola");
369
+ });
370
+
371
+ // Straznik rozjazdu z aplikacja: dwie reguly, na ktorych stoi ta poprawka, czytane ze zrodla
372
+ // aplikacji na origin/main repo mosADD (MOSADD_WEB_REPO albo C:/Projects/mosADD). Bez repo obok
373
+ // (np. CI bez siostrzanego drzewa) — pominiety, nie zielony na slepo.
374
+ const webRepo = process.env.MOSADD_WEB_REPO ?? "C:/Projects/mosADD";
375
+ const appSource = (path: string): string | null => {
376
+ try {
377
+ return execFileSync("git", ["-C", webRepo, "show", `origin/main:${path}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
378
+ } catch {
379
+ return null;
380
+ }
381
+ };
382
+ const mdmE2ee = appSource("apps/web/src/lib/mdmE2ee.ts");
383
+ const ircApi = appSource("apps/web/src/lib/ircApi.ts");
384
+ it.skipIf(!mdmE2ee || !ircApi)("kontrakt aplikacji: `text` = powod agent, s1. = kopia dla mnie, agent = jawnie", () => {
385
+ expect(mdmE2ee).toContain('reason: msg.message_type === "text" ? "agent" : "device"');
386
+ expect(mdmE2ee).toContain("const kopiaDlaMnie = doSiebie || (!!msg.self_payload && msg.self_payload.startsWith(SELF_TAG));");
387
+ expect(mdmE2ee).toContain('const SELF_TAG = "s1.";');
388
+ expect(ircApi).toContain('input.threadId.startsWith("dm:") && !input.peerIsAgent');
389
+ });
390
+ });