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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +5 -11
  2. package/LICENSE +21 -0
  3. package/README.md +151 -150
  4. package/dist/bin/mcp.js +1 -1
  5. package/dist/{chunk-IWUGKLDX.js → chunk-T3KDVUAT.js} +14 -10
  6. package/dist/index.js +1 -1
  7. package/package.json +10 -10
  8. package/src/__tests__/blob-upload.test.ts +93 -93
  9. package/src/__tests__/channel-e2ee.test.ts +62 -62
  10. package/src/__tests__/flota-jawnie.test.ts +2 -2
  11. package/src/__tests__/golden-path.test.ts +139 -139
  12. package/src/__tests__/integration.test.ts +209 -182
  13. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  14. package/src/__tests__/mdm-mcp-readable.test.ts +390 -390
  15. package/src/__tests__/mirc-invite.test.ts +112 -112
  16. package/src/__tests__/mtalk.test.ts +122 -122
  17. package/src/__tests__/presence.test.ts +199 -199
  18. package/src/__tests__/server.test.ts +71 -71
  19. package/src/__tests__/tool-count-consistency.test.ts +255 -199
  20. package/src/bin/login.ts +138 -138
  21. package/src/bin/mcp.ts +145 -145
  22. package/src/config.ts +66 -66
  23. package/src/crypto/channel-e2ee.ts +288 -288
  24. package/src/crypto/mdm-session.ts +842 -842
  25. package/src/index.ts +19 -19
  26. package/src/observability/sentry.ts +79 -79
  27. package/src/providers/blob-upload.ts +162 -162
  28. package/src/providers/memory-voice.ts +79 -79
  29. package/src/providers/supabase-dm.ts +202 -202
  30. package/src/providers/supabase-voice.ts +91 -91
  31. package/src/server.ts +195 -195
  32. package/src/tools/actions.ts +166 -166
  33. package/src/tools/attachments.ts +276 -276
  34. package/src/tools/capabilities.ts +70 -70
  35. package/src/tools/channel-payload.ts +2 -2
  36. package/src/tools/embed.ts +110 -110
  37. package/src/tools/index.ts +181 -181
  38. package/src/tools/knowledge.ts +344 -344
  39. package/src/tools/mail-aliases.ts +25 -25
  40. package/src/tools/mail-provenance.ts +137 -137
  41. package/src/tools/mail.ts +403 -403
  42. package/src/tools/mdm-as-agent.ts +138 -126
  43. package/src/tools/mdm.ts +3 -3
  44. package/src/tools/mirc-edge.ts +196 -196
  45. package/src/tools/mirc-members.ts +287 -287
  46. package/src/tools/mirc-messages.ts +1 -1
  47. package/src/tools/mirc.ts +308 -308
  48. package/src/tools/mroom.ts +221 -221
  49. package/src/tools/mtalk.ts +131 -131
  50. package/src/tools/presence.ts +442 -442
  51. package/src/tools/voice-format.ts +28 -28
  52. package/src/types.ts +121 -121
  53. package/src/voice/floor.ts +132 -132
@@ -1,390 +1,390 @@
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
- });
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
+ });