@mosadd/mcp 3.0.0-alpha.53 → 3.0.0-alpha.54
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.
- package/CHANGELOG.md +29 -0
- package/dist/bin/mcp.js +1 -1
- package/dist/{chunk-AWKITPZQ.js → chunk-3PUOM4R5.js} +96 -19
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/src/__tests__/mdm-mcp-readable.test.ts +216 -114
- package/src/crypto/mdm-session.ts +56 -12
- package/src/providers/supabase-dm.ts +28 -0
- package/src/server.ts +15 -6
- package/src/tools/mdm.ts +118 -38
package/CHANGELOG.md
CHANGED
|
@@ -21,6 +21,35 @@ gateway (Phase 2) ships.
|
|
|
21
21
|
|
|
22
22
|
Tool count **84 → 85** (mIRC **24 → 25**); `TOOL_COUNT` (`= allTools.length`) stays the truth.
|
|
23
23
|
|
|
24
|
+
## [3.0.0-alpha.54] — 2026-09-27
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
- **`mDM_send` — readable on EVERY key of the identity, and never a false reason in the app**
|
|
28
|
+
(correction of alpha.53 after independent verification, LINEAR-6089 follow-up). alpha.53 seeded
|
|
29
|
+
the mDM identity from ONE API key and let an agent line (re)publish it. An identity holds many
|
|
30
|
+
keys (each OAuth connector mints its own; measured 27.09: general@ has 8 active, 7 of 17 agent
|
|
31
|
+
identities have several), so the key directory flapped between per-key identities: a `s1.`
|
|
32
|
+
copy opened only under the key that wrote it, and `r1.` copies stopped opening for the
|
|
33
|
+
recipient after the next send from another key. alpha.53 also typed sends on a PERSON's key
|
|
34
|
+
`txt` with a `s1.` copy the app can never open, so the app told the owner a false reason
|
|
35
|
+
("sent from another device" / "unlock your identity") instead of "sent by MCP".
|
|
36
|
+
- **Agent lines send in the clear** — the King's rule of 20.09 (no E2EE for lines<->lines,
|
|
37
|
+
lines<->King, human->line), the same rule the app applies (`peerIsAgent`). When the sender
|
|
38
|
+
or the recipient is `kind = 'agent'`, `mDM_send` writes plain UTF-8, type `txt`, and never
|
|
39
|
+
touches the key directory. Every key of the line and the recipient's app on every device read
|
|
40
|
+
it. Result field `mode: "plaintext_agent_lane"`, `encrypted: false`.
|
|
41
|
+
- **Human<->human stays E2EE**, but on a person's key MCP never writes their key directory
|
|
42
|
+
automatically (neither over the app's bundle nor on an empty directory), writes no `s1.`
|
|
43
|
+
copy, and types the envelope `text`, which the app reads as "sent by MCP, no copy for this
|
|
44
|
+
device". A note-to-self is sealed to the app's bundle and opens in the app.
|
|
45
|
+
- **`mDM_publish_keys` no longer overwrites a person's app bundle** (`published: false`,
|
|
46
|
+
`identity: "foreign"`, with a note). It may fill an empty directory. Agent lines may still
|
|
47
|
+
publish explicitly.
|
|
48
|
+
- **`autoPublishKeys`** (stdio) follows the same policy (`bundlePolicyForKind`): agent lines and
|
|
49
|
+
people write nothing; other lanes (radio) publish on an empty directory as before.
|
|
50
|
+
- New `SupabaseDmProvider.peerKind(id)`; `ensureOwnBundlePublished` takes a `BundlePolicy` and
|
|
51
|
+
can return `"absent"`.
|
|
52
|
+
|
|
24
53
|
## [3.0.0-alpha.53] — 2026-09-27
|
|
25
54
|
|
|
26
55
|
### Fixed
|
package/dist/bin/mcp.js
CHANGED
|
@@ -385,7 +385,16 @@ function sameBytes(a, b) {
|
|
|
385
385
|
for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
|
|
386
386
|
return true;
|
|
387
387
|
}
|
|
388
|
-
|
|
388
|
+
function bundlePolicyForKind(kind, opts) {
|
|
389
|
+
if (kind === "agent") {
|
|
390
|
+
return opts.explicit ? { mayPublishWhenEmpty: true, mayReplaceForeign: true } : { mayPublishWhenEmpty: false, mayReplaceForeign: false };
|
|
391
|
+
}
|
|
392
|
+
if (kind === "human") {
|
|
393
|
+
return { mayPublishWhenEmpty: opts.explicit, mayReplaceForeign: false };
|
|
394
|
+
}
|
|
395
|
+
return { mayPublishWhenEmpty: true, mayReplaceForeign: opts.explicit };
|
|
396
|
+
}
|
|
397
|
+
async function ensureOwnBundlePublished(keystore, dm, selfId, policy) {
|
|
389
398
|
const own = await keystore.getOwnMaterial();
|
|
390
399
|
const raw = await dm.fetchPrekeyBundle(selfId);
|
|
391
400
|
if (raw) {
|
|
@@ -398,7 +407,9 @@ async function ensureOwnBundlePublished(keystore, dm, selfId, opts) {
|
|
|
398
407
|
if (published && sameBytes(published.identityPublicKey, own.identity.publicKey) && sameBytes(published.signingIdentityPublicKey, own.signingIdentity.publicKey) && sameBytes(published.signedPrekey.publicKey, own.signedPrekey.pair.publicKey)) {
|
|
399
408
|
return "consistent";
|
|
400
409
|
}
|
|
401
|
-
if (!
|
|
410
|
+
if (!policy.mayReplaceForeign) return "foreign";
|
|
411
|
+
} else if (!policy.mayPublishWhenEmpty) {
|
|
412
|
+
return "absent";
|
|
402
413
|
}
|
|
403
414
|
await dm.publishPrekeyBundle(serializePublicBundle(own));
|
|
404
415
|
return "published";
|
|
@@ -481,11 +492,6 @@ function parseEnvelopeV2(bytes) {
|
|
|
481
492
|
if (obj?.v !== E2EE_ENVELOPE_VERSION_V2) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
|
|
482
493
|
return obj;
|
|
483
494
|
}
|
|
484
|
-
async function publishOwnPrekeys(keystore, dm) {
|
|
485
|
-
const material = await keystore.getOwnMaterial();
|
|
486
|
-
await dm.publishPrekeyBundle(serializePublicBundle(material));
|
|
487
|
-
return { oneTimePrekeyCount: material.oneTimePrekeys.length };
|
|
488
|
-
}
|
|
489
495
|
async function encryptForPeer(keystore, dm, peerId, plaintext) {
|
|
490
496
|
let session = await keystore.getSession(peerId);
|
|
491
497
|
if (!session) {
|
|
@@ -627,6 +633,7 @@ async function decryptFromPeer(keystore, peerId, envelopeBytes) {
|
|
|
627
633
|
// src/providers/supabase-dm.ts
|
|
628
634
|
var PROTOCOL_VERSION = "mosadd.chat.v1";
|
|
629
635
|
var MDM_TEXT_MESSAGE_TYPE = "txt";
|
|
636
|
+
var MDM_MCP_SEALED_MESSAGE_TYPE = "text";
|
|
630
637
|
var SupabaseDmProvider = class {
|
|
631
638
|
cachedSelfId = null;
|
|
632
639
|
cachedSelfKind = null;
|
|
@@ -639,6 +646,22 @@ var SupabaseDmProvider = class {
|
|
|
639
646
|
await this.selfId();
|
|
640
647
|
return this.cachedSelfKind;
|
|
641
648
|
}
|
|
649
|
+
/**
|
|
650
|
+
* `identities.kind` of a PEER, or null when it cannot be read (RLS can_see_identity scopes rows
|
|
651
|
+
* to contacts / thread co-members; a miss is not an error). mDM_send uses it exactly like the
|
|
652
|
+
* app's ChatPanel `peerIsAgent` (theirIdent.kind === 'agent' || iAmAgent): a DM to an agent
|
|
653
|
+
* line is sent in the clear, because the line must read it (rozkaz Króla 20.09).
|
|
654
|
+
*/
|
|
655
|
+
async peerKind(peerId) {
|
|
656
|
+
try {
|
|
657
|
+
const sb = getSupabase();
|
|
658
|
+
const { data, error } = await sb.from("identities").select("kind").eq("id", peerId).limit(1).maybeSingle();
|
|
659
|
+
if (error || !data) return null;
|
|
660
|
+
return typeof data.kind === "string" ? data.kind : null;
|
|
661
|
+
} catch {
|
|
662
|
+
return null;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
642
665
|
async selfId() {
|
|
643
666
|
if (this.cachedSelfId) return this.cachedSelfId;
|
|
644
667
|
readSupabaseEnv();
|
|
@@ -783,24 +806,60 @@ async function selfKindOf(dm) {
|
|
|
783
806
|
const f = dm.selfKind;
|
|
784
807
|
return typeof f === "function" ? await f.call(dm) : null;
|
|
785
808
|
}
|
|
809
|
+
async function peerKindOf(dm, peerId) {
|
|
810
|
+
const f = dm.peerKind;
|
|
811
|
+
if (typeof f !== "function") return null;
|
|
812
|
+
try {
|
|
813
|
+
return await f.call(dm, peerId);
|
|
814
|
+
} catch {
|
|
815
|
+
return null;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
786
818
|
async function mDM_send(input, ctx) {
|
|
787
819
|
const dm = ctx.providers.dm;
|
|
788
820
|
const selfId = await dm.selfId();
|
|
789
821
|
const threadId = dmThreadId(selfId, input.to, input.thread_label);
|
|
790
822
|
const keys = ctx.providers.keys;
|
|
823
|
+
const selfKind = await selfKindOf(dm);
|
|
824
|
+
const peerKind = selfKind === "agent" || input.to === selfId ? selfKind : await peerKindOf(dm, input.to);
|
|
825
|
+
if (selfKind === "agent" || peerKind === "agent") {
|
|
826
|
+
const payload = packPlaintextPayload(input.text);
|
|
827
|
+
ctx.log("debug", "mDM_send plaintext agent lane (rozkaz Krola 20.09)", {
|
|
828
|
+
thread_id: threadId,
|
|
829
|
+
self_kind: selfKind,
|
|
830
|
+
peer_kind: peerKind
|
|
831
|
+
});
|
|
832
|
+
const plainArgs = {
|
|
833
|
+
to: input.to,
|
|
834
|
+
threadId,
|
|
835
|
+
payload,
|
|
836
|
+
replyToId: input.reply_to_id,
|
|
837
|
+
messageType: MDM_TEXT_MESSAGE_TYPE
|
|
838
|
+
};
|
|
839
|
+
const result2 = await dm.send(plainArgs);
|
|
840
|
+
return {
|
|
841
|
+
message_id: result2.id,
|
|
842
|
+
delivered_at: result2.deliveredAt,
|
|
843
|
+
thread_id: threadId,
|
|
844
|
+
encrypted: false,
|
|
845
|
+
mode: "plaintext_agent_lane",
|
|
846
|
+
sender_copy: true,
|
|
847
|
+
recipient_copy: true,
|
|
848
|
+
identity: "untouched"
|
|
849
|
+
};
|
|
850
|
+
}
|
|
791
851
|
let identity = "foreign";
|
|
792
852
|
try {
|
|
793
|
-
identity = await ensureOwnBundlePublished(keys, dm, selfId, {
|
|
794
|
-
mayReplaceForeign: await selfKindOf(dm) === "agent"
|
|
795
|
-
});
|
|
853
|
+
identity = await ensureOwnBundlePublished(keys, dm, selfId, bundlePolicyForKind(selfKind, { explicit: false }));
|
|
796
854
|
} catch (err) {
|
|
797
855
|
ctx.log("warn", "mDM_send could not reconcile own prekey bundle", { error: String(err) });
|
|
798
856
|
}
|
|
857
|
+
const ourIdentityIsPublished = identity === "consistent" || identity === "published";
|
|
799
858
|
const inner = packPlaintextPayload(input.text);
|
|
800
859
|
const sealed = await encryptForPeer(keys, dm, input.to, inner);
|
|
801
|
-
const selfPayload = await sealForSelf(keys, inner);
|
|
860
|
+
const selfPayload = selfKind !== "human" && ourIdentityIsPublished ? await sealForSelf(keys, inner) : null;
|
|
802
861
|
let recipientSelfPayload = null;
|
|
803
|
-
if (
|
|
862
|
+
if (ourIdentityIsPublished && input.to !== selfId) {
|
|
804
863
|
try {
|
|
805
864
|
const peer = await fetchVerifiedBundle(dm, input.to);
|
|
806
865
|
if (peer) recipientSelfPayload = await sealForPeerRecoverable(keys, peer, inner);
|
|
@@ -820,7 +879,7 @@ async function mDM_send(input, ctx) {
|
|
|
820
879
|
threadId,
|
|
821
880
|
payload: sealed,
|
|
822
881
|
replyToId: input.reply_to_id,
|
|
823
|
-
messageType:
|
|
882
|
+
messageType: MDM_MCP_SEALED_MESSAGE_TYPE,
|
|
824
883
|
selfPayload,
|
|
825
884
|
recipientSelfPayload
|
|
826
885
|
};
|
|
@@ -833,6 +892,7 @@ async function mDM_send(input, ctx) {
|
|
|
833
892
|
delivered_at: result.deliveredAt,
|
|
834
893
|
thread_id: threadId,
|
|
835
894
|
encrypted: true,
|
|
895
|
+
mode: "e2ee",
|
|
836
896
|
sender_copy: !!selfPayload,
|
|
837
897
|
recipient_copy: !!recipientSelfPayload,
|
|
838
898
|
identity
|
|
@@ -863,9 +923,26 @@ async function mDM_send_unencrypted(input, ctx) {
|
|
|
863
923
|
};
|
|
864
924
|
}
|
|
865
925
|
async function mDM_publish_keys(_input, ctx) {
|
|
866
|
-
const
|
|
867
|
-
|
|
868
|
-
|
|
926
|
+
const dm = ctx.providers.dm;
|
|
927
|
+
const keys = ctx.providers.keys;
|
|
928
|
+
const selfId = await dm.selfId();
|
|
929
|
+
const identity = await ensureOwnBundlePublished(
|
|
930
|
+
keys,
|
|
931
|
+
dm,
|
|
932
|
+
selfId,
|
|
933
|
+
bundlePolicyForKind(await selfKindOf(dm), { explicit: true })
|
|
934
|
+
);
|
|
935
|
+
const { oneTimePrekeys } = await keys.getOwnMaterial();
|
|
936
|
+
ctx.log("debug", "mDM_publish_keys", { identity, one_time_prekeys: oneTimePrekeys.length });
|
|
937
|
+
if (identity === "foreign") {
|
|
938
|
+
return {
|
|
939
|
+
published: false,
|
|
940
|
+
identity,
|
|
941
|
+
one_time_prekeys: 0,
|
|
942
|
+
note: "This identity already has keys published by the mosADD app. They were left untouched: replacing them from an API key would make every conversation with you unreadable in the app."
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
return { published: identity === "published", identity, one_time_prekeys: oneTimePrekeys.length };
|
|
869
946
|
}
|
|
870
947
|
async function mDM_list(input, ctx) {
|
|
871
948
|
const dm = ctx.providers.dm;
|
|
@@ -1029,7 +1106,7 @@ var mdmTools = [
|
|
|
1029
1106
|
title: "Send encrypted DM",
|
|
1030
1107
|
annotations: { readOnlyHint: false },
|
|
1031
1108
|
requires: "any",
|
|
1032
|
-
description: "Send
|
|
1109
|
+
description: "Send a direct message via mosadd mDM. Between two PEOPLE it is END-TO-END-ENCRYPTED; when either side is an agent line it goes in the clear (mosadd rule: agents must read their DMs), exactly like the mosadd app. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts). Establishes an X3DH + Double Ratchet session on first contact (the recipient must have run mDM_publish_keys). Optional thread_label puts the message in a named thread \u2014 mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram. If the recipient has no published keys yet, use mDM_send_unencrypted.",
|
|
1033
1110
|
inputSchema: mDM_send_input,
|
|
1034
1111
|
handler: mDM_send
|
|
1035
1112
|
},
|
|
@@ -3849,7 +3926,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
|
3849
3926
|
// package.json
|
|
3850
3927
|
var package_default = {
|
|
3851
3928
|
name: "@mosadd/mcp",
|
|
3852
|
-
version: "3.0.0-alpha.
|
|
3929
|
+
version: "3.0.0-alpha.54",
|
|
3853
3930
|
mcpName: "io.github.hei33enberg/mosadd-mcp",
|
|
3854
3931
|
description: "Model Context Protocol server for mosadd. Exposes 4 modules (mDM, mIRC, mURL, mAYL) and capabilities (mTALK, mRAG) plus comms agent-actions \u2014 85 tools \u2014 to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
|
|
3855
3932
|
homepage: "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
|
|
@@ -4012,7 +4089,7 @@ function createMosaddServer(options = {}) {
|
|
|
4012
4089
|
void (async () => {
|
|
4013
4090
|
const selfId = await providers.dm.selfId();
|
|
4014
4091
|
const kind = await providers.dm.selfKind?.();
|
|
4015
|
-
return ensureOwnBundlePublished(providers.keys, providers.dm, selfId, {
|
|
4092
|
+
return ensureOwnBundlePublished(providers.keys, providers.dm, selfId, bundlePolicyForKind(kind, { explicit: false }));
|
|
4016
4093
|
})().then((state) => ctx.log("debug", "auto-ensure mDM prekeys", { state })).catch((err) => ctx.log("debug", "auto-publish mDM prekeys skipped", { error: String(err) }));
|
|
4017
4094
|
}
|
|
4018
4095
|
const server = new McpServer(
|
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mosadd/mcp",
|
|
3
|
-
"version": "3.0.0-alpha.
|
|
3
|
+
"version": "3.0.0-alpha.54",
|
|
4
4
|
"mcpName": "io.github.hei33enberg/mosadd-mcp",
|
|
5
5
|
"description": "Model Context Protocol server for mosadd. Exposes 4 modules (mDM, mIRC, mURL, mAYL) and capabilities (mTALK, mRAG) plus comms agent-actions — 85 tools — to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
|
|
6
6
|
"homepage": "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
|
|
@@ -1,30 +1,44 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* ZAMEK (27.09.2026, nastepstwo LINEAR-6089
|
|
3
|
-
* CZYTELNA
|
|
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.
|
|
4
6
|
*
|
|
5
|
-
*
|
|
6
|
-
* 1.
|
|
7
|
-
* 2.
|
|
8
|
-
*
|
|
9
|
-
*
|
|
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`.
|
|
10
23
|
*
|
|
11
24
|
* Prawdziwa kryptografia (X3DH + Double Ratchet + AES-GCM + HKDF z @mosadd/crypto), zero atrap
|
|
12
|
-
* szyfru. Kazde "zadanie" bramy = SWIEZY serwer z
|
|
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).
|
|
25
|
+
* szyfru. Kazde "zadanie" bramy = SWIEZY serwer z danym kluczem API — jak handler bramy.
|
|
16
26
|
*/
|
|
17
27
|
|
|
28
|
+
import { execFileSync } from "node:child_process";
|
|
18
29
|
import { describe, expect, it } from "vitest";
|
|
19
30
|
import type { DmProvider, DmListArgs, DmListResult, DmSendResult } from "@mosadd/providers";
|
|
20
|
-
import { deriveHkdfKey,
|
|
31
|
+
import { deriveHkdfKey, fromBase64, toBase64 } from "@mosadd/crypto";
|
|
21
32
|
import { mdmTools } from "../tools/mdm.js";
|
|
22
|
-
import { defaultProviders } from "../server.js";
|
|
33
|
+
import { createMosaddServer, defaultProviders } from "../server.js";
|
|
23
34
|
import {
|
|
24
35
|
SeededMdmKeyStore,
|
|
25
36
|
decryptFromPeer,
|
|
37
|
+
deriveMdmSeedFromSecret,
|
|
26
38
|
deriveOwnMaterialFromSeed,
|
|
27
|
-
|
|
39
|
+
encryptForPeer,
|
|
40
|
+
fetchVerifiedBundle,
|
|
41
|
+
sealForPeerRecoverable,
|
|
28
42
|
serializePublicBundle,
|
|
29
43
|
type MdmKeyStore,
|
|
30
44
|
} from "../crypto/mdm-session.js";
|
|
@@ -32,7 +46,7 @@ import type { DmMessageExt, DmSendArgsExt } from "../providers/supabase-dm.js";
|
|
|
32
46
|
import { InMemoryVoiceProvider } from "../providers/memory-voice.js";
|
|
33
47
|
import type { MosaddToolContext } from "../types.js";
|
|
34
48
|
|
|
35
|
-
// ---- a backend shaped like message-send / message-list / prekey directory ----
|
|
49
|
+
// ---- a backend shaped like message-send / message-list / prekey directory / identities ----
|
|
36
50
|
|
|
37
51
|
type Row = {
|
|
38
52
|
id: string;
|
|
@@ -49,12 +63,14 @@ class Backend {
|
|
|
49
63
|
readonly rows: Row[] = [];
|
|
50
64
|
readonly bundles = new Map<string, Uint8Array>();
|
|
51
65
|
readonly kinds = new Map<string, string>();
|
|
66
|
+
publishes = 0;
|
|
52
67
|
}
|
|
53
68
|
|
|
54
69
|
class Lane implements DmProvider {
|
|
55
70
|
constructor(private readonly b: Backend, private readonly me: string) {}
|
|
56
71
|
async selfId() { return this.me; }
|
|
57
72
|
async selfKind() { return this.b.kinds.get(this.me) ?? null; }
|
|
73
|
+
async peerKind(id: string) { return this.b.kinds.get(id) ?? null; }
|
|
58
74
|
async send(args: DmSendArgsExt): Promise<DmSendResult> {
|
|
59
75
|
const id = `m${this.b.rows.length + 1}`;
|
|
60
76
|
this.b.rows.push({
|
|
@@ -85,7 +101,10 @@ class Lane implements DmProvider {
|
|
|
85
101
|
}));
|
|
86
102
|
return { messages, nextCursor: null };
|
|
87
103
|
}
|
|
88
|
-
async publishPrekeyBundle(bundle: Uint8Array) {
|
|
104
|
+
async publishPrekeyBundle(bundle: Uint8Array) {
|
|
105
|
+
this.b.publishes += 1;
|
|
106
|
+
this.b.bundles.set(this.me, bundle);
|
|
107
|
+
}
|
|
89
108
|
async fetchPrekeyBundle(peerId: string) { return this.b.bundles.get(peerId) ?? null; }
|
|
90
109
|
}
|
|
91
110
|
|
|
@@ -114,42 +133,68 @@ async function appOf(b: Backend, me: string, seedByte: number) {
|
|
|
114
133
|
return keys;
|
|
115
134
|
}
|
|
116
135
|
|
|
117
|
-
|
|
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)
|
|
118
141
|
|
|
119
142
|
async function appOpenAesGcm(tag: string, keyBytes: Uint8Array, sealed: string | null): Promise<string | null> {
|
|
120
143
|
if (!sealed || !sealed.startsWith(tag)) return null;
|
|
121
144
|
const packed = fromBase64(sealed.slice(tag.length));
|
|
122
145
|
if (packed.length <= 12) return null;
|
|
123
146
|
const key = await crypto.subtle.importKey("raw", keyBytes as BufferSource, { name: "AES-GCM" }, false, ["decrypt"]);
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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);
|
|
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
|
+
}
|
|
140
153
|
}
|
|
141
154
|
|
|
142
|
-
/**
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
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" };
|
|
146
179
|
}
|
|
147
180
|
|
|
148
|
-
const
|
|
181
|
+
const KEY_A = "mosadd_sk_live_0123456789abcdef0123456789abcdef";
|
|
182
|
+
const KEY_B = "mosadd_sk_live_fedcba9876543210fedcba9876543210"; // druga, rownolegle aktywna, ta sama linia
|
|
149
183
|
const LINE = "general-line-identity";
|
|
150
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 }> };
|
|
151
196
|
|
|
152
|
-
describe("mDM_send z MCP —
|
|
197
|
+
describe("mDM_send z MCP — czytelne na kazdym kluczu, prawdziwe powody w aplikacji (zamek 27.09)", () => {
|
|
153
198
|
it("KAT: tozsamosc z ziarna jest bit w bit ta, ktora wylicza aplikacja", async () => {
|
|
154
199
|
const seed = new Uint8Array(32).map((_, i) => i + 1);
|
|
155
200
|
const m = await deriveOwnMaterialFromSeed(seed);
|
|
@@ -166,107 +211,146 @@ describe("mDM_send z MCP — koperta czytelna u nadawcy i u odbiorcy (zamek 27.0
|
|
|
166
211
|
|
|
167
212
|
it("dwa zadania bramy z tym samym kluczem = JEDNA tozsamosc (nie nowa co wywolanie)", async () => {
|
|
168
213
|
const b = new Backend();
|
|
169
|
-
const a = await gatewayRequest(b, LINE,
|
|
170
|
-
const c = await gatewayRequest(b, LINE,
|
|
214
|
+
const a = await gatewayRequest(b, LINE, KEY_A).providers.keys.getOwnMaterial();
|
|
215
|
+
const c = await gatewayRequest(b, LINE, KEY_A).providers.keys.getOwnMaterial();
|
|
171
216
|
expect(toBase64(a.identity.publicKey)).toBe(toBase64(c.identity.publicKey));
|
|
172
217
|
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
218
|
});
|
|
176
219
|
|
|
177
|
-
it("
|
|
220
|
+
it("linia agenta, DWA klucze naprzemiennie: jawny txt, kazdy klucz czyta wszystko, Krol czyta w aplikacji, katalog nietkniety", async () => {
|
|
178
221
|
const b = new Backend();
|
|
179
222
|
b.kinds.set(LINE, "agent");
|
|
180
|
-
|
|
181
|
-
const king = await appOf(b, KING, 7);
|
|
223
|
+
await appOf(b, KING, 7);
|
|
182
224
|
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
};
|
|
186
|
-
|
|
187
|
-
|
|
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
|
+
}
|
|
188
231
|
|
|
189
|
-
|
|
190
|
-
expect(
|
|
191
|
-
expect(
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
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");
|
|
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
|
+
}
|
|
215
249
|
});
|
|
216
250
|
|
|
217
|
-
it("watek wlasny linii (dm:ja:ja):
|
|
251
|
+
it("watek wlasny linii (dm:ja:ja): zapis kluczem A, odczyt kluczem B", async () => {
|
|
218
252
|
const b = new Backend();
|
|
219
253
|
b.kinds.set(LINE, "agent");
|
|
220
|
-
await tool("mDM_send")({ to: LINE, text: "notatka do siebie" }, gatewayRequest(b, LINE,
|
|
254
|
+
await tool("mDM_send")({ to: LINE, text: "notatka do siebie" }, gatewayRequest(b, LINE, KEY_A));
|
|
221
255
|
const row = b.rows.at(-1)!;
|
|
222
256
|
expect(row.threadId).toBe(`dm:${LINE}:${LINE}`);
|
|
223
257
|
expect(row.messageType).toBe("txt");
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
const read = (await tool("mDM_list")({ contact_id: LINE }, gatewayRequest(b, LINE, API_KEY))) as {
|
|
227
|
-
messages: Array<{ text: string }>;
|
|
228
|
-
};
|
|
258
|
+
const read = (await tool("mDM_list")({ contact_id: LINE }, gatewayRequest(b, LINE, KEY_B))) as ListOut;
|
|
229
259
|
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");
|
|
260
|
+
expect(b.publishes).toBe(0);
|
|
234
261
|
});
|
|
235
262
|
|
|
236
|
-
it("
|
|
237
|
-
// agent: martwy pek po dawnym losowym przebiegu -> zastapiony stala tozsamoscia
|
|
263
|
+
it("czlowiek pisze przez MCP DO linii agenta: jawnie (jak peerIsAgent w aplikacji)", async () => {
|
|
238
264
|
const b = new Backend();
|
|
239
265
|
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
266
|
await appOf(b, KING, 7);
|
|
243
|
-
const
|
|
244
|
-
expect(
|
|
245
|
-
expect(
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
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
|
+
it("klucz czlowieka, notatka do siebie: aplikacja OTWIERA ja wlasnymi kluczami", async () => {
|
|
297
|
+
const b = new Backend();
|
|
298
|
+
const kingSeed = new Uint8Array(32).fill(7);
|
|
299
|
+
const kingApp = await appOf(b, KING, 7);
|
|
300
|
+
await tool("mDM_send")({ to: KING, text: "do siebie z MCP" }, gatewayRequest(b, KING, KEY_A));
|
|
301
|
+
const row = b.rows.at(-1)!;
|
|
302
|
+
expect(row.messageType).toBe("text");
|
|
303
|
+
expect(await appReadOwn(kingSeed, kingApp, KING, row)).toEqual({ text: "do siebie z MCP", reason: null });
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
it("czlowiek BEZ peku: MCP nie publikuje sam (ani mDM_send, ani autoPublishKeys); jawne mDM_publish_keys moze", async () => {
|
|
307
|
+
const b = new Backend();
|
|
308
|
+
b.kinds.set(KING, "human");
|
|
309
|
+
await appOf(b, PEER, 5);
|
|
310
|
+
const s = (await tool("mDM_send")({ to: PEER, text: "x" }, gatewayRequest(b, KING, KEY_A))) as SendOut;
|
|
311
|
+
expect(s.identity).toBe("absent");
|
|
312
|
+
expect(b.bundles.has(KING)).toBe(false);
|
|
313
|
+
|
|
314
|
+
createMosaddServer({ apiKey: KEY_A, autoPublishKeys: true, providers: { dm: new Lane(b, KING), voice: new InMemoryVoiceProvider(KING) } });
|
|
315
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
316
|
+
expect(b.bundles.has(KING)).toBe(false);
|
|
317
|
+
expect(b.publishes).toBe(0);
|
|
318
|
+
|
|
319
|
+
const p = (await tool("mDM_publish_keys")({}, gatewayRequest(b, KING, KEY_A))) as { published: boolean; identity: string };
|
|
320
|
+
expect(p).toMatchObject({ published: true, identity: "published" });
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
it("jawne mDM_publish_keys na kluczu czlowieka NIE nadpisuje peku z aplikacji", async () => {
|
|
324
|
+
const b = new Backend();
|
|
325
|
+
await appOf(b, KING, 7);
|
|
326
|
+
const before = toBase64(b.bundles.get(KING)!);
|
|
327
|
+
const p = (await tool("mDM_publish_keys")({}, gatewayRequest(b, KING, KEY_A))) as { published: boolean; identity: string; note?: string };
|
|
328
|
+
expect(p).toMatchObject({ published: false, identity: "foreign" });
|
|
329
|
+
expect(p.note).toBeTruthy();
|
|
330
|
+
expect(toBase64(b.bundles.get(KING)!)).toBe(before);
|
|
331
|
+
expect(b.publishes).toBe(0);
|
|
257
332
|
});
|
|
258
333
|
|
|
259
|
-
it("
|
|
334
|
+
it("autoPublishKeys na linii agenta: zero zapisow w katalogu (zaden z jej kluczy nie przestawia peku)", async () => {
|
|
335
|
+
const b = new Backend();
|
|
336
|
+
b.kinds.set(LINE, "agent");
|
|
337
|
+
for (const k of [KEY_A, KEY_B]) {
|
|
338
|
+
createMosaddServer({ apiKey: k, autoPublishKeys: true, providers: { dm: new Lane(b, LINE), voice: new InMemoryVoiceProvider(LINE) } });
|
|
339
|
+
}
|
|
340
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
341
|
+
expect(b.publishes).toBe(0);
|
|
342
|
+
expect(b.bundles.has(LINE)).toBe(false);
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
it("stara koperta E2EE od Krola z kopia r1. (pek linii sprzed poprawki) dalej czytelna w bramie", async () => {
|
|
260
346
|
const b = new Backend();
|
|
261
347
|
b.kinds.set(LINE, "agent");
|
|
262
348
|
const king = await appOf(b, KING, 7);
|
|
263
|
-
//
|
|
264
|
-
|
|
265
|
-
const { sealForPeerRecoverable, fetchVerifiedBundle, encryptForPeer } = await import("../crypto/mdm-session.js");
|
|
349
|
+
// pek linii opublikowany przez alpha.53 z ziarna klucza A
|
|
350
|
+
b.bundles.set(LINE, serializePublicBundle(await new SeededMdmKeyStore(await deriveMdmSeedFromSecret(KEY_A)).getOwnMaterial()));
|
|
266
351
|
const kingLane = new Lane(b, KING);
|
|
267
352
|
const lineBundle = (await fetchVerifiedBundle(kingLane, LINE))!;
|
|
268
353
|
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
354
|
await encryptForPeer(king, kingLane, LINE, new TextEncoder().encode("pierwsza"));
|
|
271
355
|
const env = await encryptForPeer(king, kingLane, LINE, inner);
|
|
272
356
|
await kingLane.send({
|
|
@@ -276,9 +360,27 @@ describe("mDM_send z MCP — koperta czytelna u nadawcy i u odbiorcy (zamek 27.0
|
|
|
276
360
|
messageType: "txt",
|
|
277
361
|
recipientSelfPayload: await sealForPeerRecoverable(king, lineBundle, inner),
|
|
278
362
|
});
|
|
279
|
-
const read = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE,
|
|
280
|
-
messages: Array<{ text: string; sender_identity_id: string }>;
|
|
281
|
-
};
|
|
363
|
+
const read = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE, KEY_A))) as ListOut;
|
|
282
364
|
expect(read.messages.find((m) => m.sender_identity_id === KING)?.text).toBe("rozkaz od Krola");
|
|
283
365
|
});
|
|
366
|
+
|
|
367
|
+
// Straznik rozjazdu z aplikacja: dwie reguly, na ktorych stoi ta poprawka, czytane ze zrodla
|
|
368
|
+
// aplikacji na origin/main repo mosADD (MOSADD_WEB_REPO albo C:/Projects/mosADD). Bez repo obok
|
|
369
|
+
// (np. CI bez siostrzanego drzewa) — pominiety, nie zielony na slepo.
|
|
370
|
+
const webRepo = process.env.MOSADD_WEB_REPO ?? "C:/Projects/mosADD";
|
|
371
|
+
const appSource = (path: string): string | null => {
|
|
372
|
+
try {
|
|
373
|
+
return execFileSync("git", ["-C", webRepo, "show", `origin/main:${path}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
374
|
+
} catch {
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
const mdmE2ee = appSource("apps/web/src/lib/mdmE2ee.ts");
|
|
379
|
+
const ircApi = appSource("apps/web/src/lib/ircApi.ts");
|
|
380
|
+
it.skipIf(!mdmE2ee || !ircApi)("kontrakt aplikacji: `text` = powod agent, s1. = kopia dla mnie, agent = jawnie", () => {
|
|
381
|
+
expect(mdmE2ee).toContain('reason: msg.message_type === "text" ? "agent" : "device"');
|
|
382
|
+
expect(mdmE2ee).toContain("const kopiaDlaMnie = doSiebie || (!!msg.self_payload && msg.self_payload.startsWith(SELF_TAG));");
|
|
383
|
+
expect(mdmE2ee).toContain('const SELF_TAG = "s1.";');
|
|
384
|
+
expect(ircApi).toContain('input.threadId.startsWith("dm:") && !input.peerIsAgent');
|
|
385
|
+
});
|
|
284
386
|
});
|
|
@@ -438,25 +438,67 @@ export type OwnBundleState =
|
|
|
438
438
|
/** the directory had no bundle (or we own the identity) and now holds ours */
|
|
439
439
|
| "published"
|
|
440
440
|
/** someone else's key material is published for this identity and we must not replace it */
|
|
441
|
-
| "foreign"
|
|
441
|
+
| "foreign"
|
|
442
|
+
/** the directory holds NO bundle for this identity and this runtime may not create one */
|
|
443
|
+
| "absent";
|
|
444
|
+
|
|
445
|
+
/** What this runtime may write to the key directory for its own identity. */
|
|
446
|
+
export interface BundlePolicy {
|
|
447
|
+
/** directory empty → publish this keystore's bundle */
|
|
448
|
+
mayPublishWhenEmpty: boolean;
|
|
449
|
+
/** directory holds a DIFFERENT bundle → replace it with this keystore's */
|
|
450
|
+
mayReplaceForeign: boolean;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* ⛔ WHO MAY WRITE THE KEY DIRECTORY FROM MCP (27.09.2026, poprawka po weryfikacji toru mdm-brama).
|
|
455
|
+
*
|
|
456
|
+
* The MCP identity is seeded from ONE API key. A mosADD identity has MANY active keys (every OAuth
|
|
457
|
+
* connector mints its own — measured 27.09: 7 of 17 agent identities hold several, general@ alone
|
|
458
|
+
* 8, all used within 3 days). A per-key identity that is allowed to (re)publish therefore makes the
|
|
459
|
+
* directory FLAP between up to 8 identities: copies sealed under key A stop opening once key B
|
|
460
|
+
* published, and envelopes sealed to "the" bundle open on one key only. So:
|
|
461
|
+
*
|
|
462
|
+
* - kind "agent": an agent LINE sends JAWNIE (plaintext) — rozkaz Króla 20.09 12:56Z „E2EE
|
|
463
|
+
* wewnętrzne = zero": linie↔linie, linie↔Król, człowiek→linia bez E2EE; the app does the same
|
|
464
|
+
* (ircApi.ts peerIsAgent). An agent never needs a bundle for mDM_send, so the AUTOMATIC paths
|
|
465
|
+
* write nothing. Only an explicit mDM_publish_keys still publishes (the caller asked for it).
|
|
466
|
+
* - kind "human": the person's bundle is anchored to their login secret IN THE APP
|
|
467
|
+
* (mdmKeyStore.setIdentitySeed; kanon in hub-key-exchange: only the identity's own client
|
|
468
|
+
* publishes). MCP never replaces it and never pre-empts it on an empty directory automatically
|
|
469
|
+
* — a bundle published from an API-key seed would be overwritten by the app later and strand
|
|
470
|
+
* everything sealed to it meanwhile. Explicit mDM_publish_keys may fill an EMPTY directory.
|
|
471
|
+
* - unknown kind (non-Supabase lanes, e.g. radio): the pre-27.09 behaviour, empty → publish;
|
|
472
|
+
* explicit → publish.
|
|
473
|
+
*/
|
|
474
|
+
export function bundlePolicyForKind(kind: string | null | undefined, opts: { explicit: boolean }): BundlePolicy {
|
|
475
|
+
if (kind === "agent") {
|
|
476
|
+
return opts.explicit
|
|
477
|
+
? { mayPublishWhenEmpty: true, mayReplaceForeign: true }
|
|
478
|
+
: { mayPublishWhenEmpty: false, mayReplaceForeign: false };
|
|
479
|
+
}
|
|
480
|
+
if (kind === "human") {
|
|
481
|
+
return { mayPublishWhenEmpty: opts.explicit, mayReplaceForeign: false };
|
|
482
|
+
}
|
|
483
|
+
return { mayPublishWhenEmpty: true, mayReplaceForeign: opts.explicit };
|
|
484
|
+
}
|
|
442
485
|
|
|
443
486
|
/**
|
|
444
|
-
* Make the key directory agree with this keystore's identity —
|
|
487
|
+
* Make the key directory agree with this keystore's identity — only as far as `policy` allows.
|
|
445
488
|
*
|
|
446
|
-
* - directory == ours
|
|
447
|
-
* - directory empty
|
|
448
|
-
* - directory
|
|
449
|
-
*
|
|
450
|
-
* - directory differs,
|
|
451
|
-
*
|
|
452
|
-
*
|
|
453
|
-
* recoverable copy is skipped, because it would be sealed under the wrong identity.
|
|
489
|
+
* - directory == ours → "consistent" (no write).
|
|
490
|
+
* - directory empty, may publish → publish ours → "published".
|
|
491
|
+
* - directory empty, may not → "absent" (no write).
|
|
492
|
+
* - directory differs, may replace → publish ours → "published".
|
|
493
|
+
* - directory differs, may not → "foreign" (no write). The ratchet envelope still
|
|
494
|
+
* works (it carries its own handshake); recoverable copies are skipped, because they would
|
|
495
|
+
* be sealed under an identity nobody can look up.
|
|
454
496
|
*/
|
|
455
497
|
export async function ensureOwnBundlePublished(
|
|
456
498
|
keystore: MdmKeyStore,
|
|
457
499
|
dm: DmProvider,
|
|
458
500
|
selfId: string,
|
|
459
|
-
|
|
501
|
+
policy: BundlePolicy,
|
|
460
502
|
): Promise<OwnBundleState> {
|
|
461
503
|
const own = await keystore.getOwnMaterial();
|
|
462
504
|
const raw = await dm.fetchPrekeyBundle(selfId);
|
|
@@ -471,7 +513,9 @@ export async function ensureOwnBundlePublished(
|
|
|
471
513
|
) {
|
|
472
514
|
return "consistent";
|
|
473
515
|
}
|
|
474
|
-
if (!
|
|
516
|
+
if (!policy.mayReplaceForeign) return "foreign";
|
|
517
|
+
} else if (!policy.mayPublishWhenEmpty) {
|
|
518
|
+
return "absent";
|
|
475
519
|
}
|
|
476
520
|
await dm.publishPrekeyBundle(serializePublicBundle(own));
|
|
477
521
|
return "published";
|
|
@@ -31,6 +31,17 @@ const PROTOCOL_VERSION = "mosadd.chat.v1";
|
|
|
31
31
|
*/
|
|
32
32
|
export const MDM_TEXT_MESSAGE_TYPE = "txt";
|
|
33
33
|
|
|
34
|
+
/**
|
|
35
|
+
* ⛔ AN E2EE ENVELOPE SEALED BY MCP ON A PERSON'S KEY IS TYPED `text` — ON PURPOSE (27.09.2026).
|
|
36
|
+
* The app's readOwnMdmMessage (apps/web/src/lib/mdmE2ee.ts, from f95557f) explains an unreadable
|
|
37
|
+
* OWN bubble by message_type: `text` → reason "agent" („wysłane przez agenta/MCP bez kopii dla
|
|
38
|
+
* Ciebie"), anything else → "device" („wysłane z innego urządzenia"). MCP holds an API-key seed,
|
|
39
|
+
* never the person's app seed, so it can never write a self copy the app opens — typing its
|
|
40
|
+
* envelope `txt` made the app tell the owner a false reason. `text` stays client-sendable in
|
|
41
|
+
* message-send (CLIENT_SENDABLE_MESSAGE_TYPES) precisely for this lane. Plaintext stays `txt`.
|
|
42
|
+
*/
|
|
43
|
+
export const MDM_MCP_SEALED_MESSAGE_TYPE = "text";
|
|
44
|
+
|
|
34
45
|
/**
|
|
35
46
|
* Supabase-only extras for a DM send. The transport-agnostic DmSendArgs (@mosadd/providers)
|
|
36
47
|
* carries opaque bytes only; the network lane can additionally store the two recoverable copies
|
|
@@ -67,6 +78,23 @@ export class SupabaseDmProvider implements DmProvider {
|
|
|
67
78
|
return this.cachedSelfKind;
|
|
68
79
|
}
|
|
69
80
|
|
|
81
|
+
/**
|
|
82
|
+
* `identities.kind` of a PEER, or null when it cannot be read (RLS can_see_identity scopes rows
|
|
83
|
+
* to contacts / thread co-members; a miss is not an error). mDM_send uses it exactly like the
|
|
84
|
+
* app's ChatPanel `peerIsAgent` (theirIdent.kind === 'agent' || iAmAgent): a DM to an agent
|
|
85
|
+
* line is sent in the clear, because the line must read it (rozkaz Króla 20.09).
|
|
86
|
+
*/
|
|
87
|
+
async peerKind(peerId: string): Promise<string | null> {
|
|
88
|
+
try {
|
|
89
|
+
const sb = getSupabase();
|
|
90
|
+
const { data, error } = await sb.from("identities").select("kind").eq("id", peerId).limit(1).maybeSingle();
|
|
91
|
+
if (error || !data) return null;
|
|
92
|
+
return typeof data.kind === "string" ? data.kind : null;
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
70
98
|
async selfId(): Promise<string> {
|
|
71
99
|
if (this.cachedSelfId) return this.cachedSelfId;
|
|
72
100
|
readSupabaseEnv(); // fail fast with an actionable error if BYOK env missing
|
package/src/server.ts
CHANGED
|
@@ -8,7 +8,12 @@ import { autoBeatFromActivity } from "./tools/presence.js";
|
|
|
8
8
|
import { PKG_VERSION } from "./version.js";
|
|
9
9
|
import { SupabaseDmProvider } from "./providers/supabase-dm.js";
|
|
10
10
|
import { SupabaseVoiceProvider } from "./providers/supabase-voice.js";
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
InMemoryMdmKeyStore,
|
|
13
|
+
SecretMdmKeyStore,
|
|
14
|
+
bundlePolicyForKind,
|
|
15
|
+
ensureOwnBundlePublished,
|
|
16
|
+
} from "./crypto/mdm-session.js";
|
|
12
17
|
import type { MosaddServerOptions, MosaddToolContext, ProviderRegistry } from "./types.js";
|
|
13
18
|
|
|
14
19
|
/**
|
|
@@ -35,6 +40,10 @@ export function defaultProviders(
|
|
|
35
40
|
* a new server per HTTP request, and with a random in-memory keystore every mDM_send was sealed
|
|
36
41
|
* by an identity that lived for one request. Without any secret (BYOK JWT only) there is nothing
|
|
37
42
|
* stable to derive from, so the old per-process random keystore remains.
|
|
43
|
+
*
|
|
44
|
+
* ⛔ STABLE PER KEY, NOT PER IDENTITY. One identity holds many keys (each OAuth connector mints
|
|
45
|
+
* its own), so this seed never publishes on its own authority: agent lines send in the clear and
|
|
46
|
+
* people keep the app's bundle (bundlePolicyForKind in crypto/mdm-session.ts).
|
|
38
47
|
*/
|
|
39
48
|
function defaultKeyStore(secret?: string) {
|
|
40
49
|
const s = (secret ?? "").trim();
|
|
@@ -69,15 +78,15 @@ export function createMosaddServer(options: MosaddServerOptions = {}) {
|
|
|
69
78
|
// etc.) and never blocks startup. Uses the SAME keystore the tools use, so the
|
|
70
79
|
// published identity matches what mDM_send/encryptForPeer will use this process.
|
|
71
80
|
//
|
|
72
|
-
// ⛔ ENSURE, NOT BLIND PUBLISH (27.09.2026
|
|
73
|
-
//
|
|
74
|
-
//
|
|
75
|
-
//
|
|
81
|
+
// ⛔ ENSURE, NOT BLIND PUBLISH (27.09.2026, poprawka po weryfikacji): the policy is
|
|
82
|
+
// bundlePolicyForKind — the SAME one mDM_send uses. Agent line: writes NOTHING (it sends in the
|
|
83
|
+
// clear, rozkaz Krola 20.09; a per-key bundle from each of its keys only made the directory flap).
|
|
84
|
+
// Human: writes NOTHING (the app owns that bundle). Unknown kind (e.g. radio): empty -> publish.
|
|
76
85
|
if (options.autoPublishKeys) {
|
|
77
86
|
void (async () => {
|
|
78
87
|
const selfId = await providers.dm.selfId();
|
|
79
88
|
const kind = await (providers.dm as { selfKind?: () => Promise<string | null> }).selfKind?.();
|
|
80
|
-
return ensureOwnBundlePublished(providers.keys, providers.dm, selfId, {
|
|
89
|
+
return ensureOwnBundlePublished(providers.keys, providers.dm, selfId, bundlePolicyForKind(kind, { explicit: false }));
|
|
81
90
|
})()
|
|
82
91
|
.then((state) => ctx.log("debug", "auto-ensure mDM prekeys", { state }))
|
|
83
92
|
.catch((err) => ctx.log("debug", "auto-publish mDM prekeys skipped", { error: String(err) }));
|
package/src/tools/mdm.ts
CHANGED
|
@@ -21,9 +21,9 @@ import { invokeFunction, getSupabase, readSupabaseEnv } from "../providers/supab
|
|
|
21
21
|
import {
|
|
22
22
|
encryptForPeer,
|
|
23
23
|
decryptFromPeer,
|
|
24
|
-
publishOwnPrekeys,
|
|
25
24
|
isE2eeEnvelope,
|
|
26
25
|
ensureOwnBundlePublished,
|
|
26
|
+
bundlePolicyForKind,
|
|
27
27
|
fetchVerifiedBundle,
|
|
28
28
|
sealForSelf,
|
|
29
29
|
sealForPeerRecoverable,
|
|
@@ -32,7 +32,12 @@ import {
|
|
|
32
32
|
type OwnBundleState,
|
|
33
33
|
type PublicPrekeyBundle,
|
|
34
34
|
} from "../crypto/mdm-session.js";
|
|
35
|
-
import {
|
|
35
|
+
import {
|
|
36
|
+
MDM_TEXT_MESSAGE_TYPE,
|
|
37
|
+
MDM_MCP_SEALED_MESSAGE_TYPE,
|
|
38
|
+
type DmSendArgsExt,
|
|
39
|
+
type DmMessageExt,
|
|
40
|
+
} from "../providers/supabase-dm.js";
|
|
36
41
|
|
|
37
42
|
// ---- Constants ----
|
|
38
43
|
|
|
@@ -154,58 +159,110 @@ async function selfKindOf(dm: MosaddToolContext["providers"]["dm"]): Promise<str
|
|
|
154
159
|
return typeof f === "function" ? await f.call(dm) : null;
|
|
155
160
|
}
|
|
156
161
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
)
|
|
162
|
+
/** A peer's identity kind when the provider can tell (Supabase lane); null = unknown. */
|
|
163
|
+
async function peerKindOf(dm: MosaddToolContext["providers"]["dm"], peerId: string): Promise<string | null> {
|
|
164
|
+
const f = (dm as { peerKind?: (id: string) => Promise<string | null> }).peerKind;
|
|
165
|
+
if (typeof f !== "function") return null;
|
|
166
|
+
try {
|
|
167
|
+
return await f.call(dm, peerId);
|
|
168
|
+
} catch {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
type MdmSendResultOut = {
|
|
161
174
|
message_id: string;
|
|
162
175
|
delivered_at: string;
|
|
163
176
|
thread_id: string;
|
|
164
|
-
encrypted:
|
|
165
|
-
/**
|
|
177
|
+
encrypted: boolean;
|
|
178
|
+
/**
|
|
179
|
+
* "plaintext_agent_lane": an agent line is a party, so the DM goes in the clear (rozkaz Krola
|
|
180
|
+
* 20.09, same rule as the app's peerIsAgent). "e2ee": human to human, X3DH + Double Ratchet.
|
|
181
|
+
*/
|
|
182
|
+
mode: "plaintext_agent_lane" | "e2ee";
|
|
183
|
+
/** the sender can read this message back from ANY process / ANY key of the same identity */
|
|
166
184
|
sender_copy: boolean;
|
|
167
|
-
/** the recipient can
|
|
185
|
+
/** the recipient can read it without a ratchet session */
|
|
168
186
|
recipient_copy: boolean;
|
|
169
|
-
/** state of this identity in the key directory
|
|
170
|
-
identity: OwnBundleState;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
187
|
+
/** state of this identity in the key directory (E2EE only; the plaintext lane never touches it) */
|
|
188
|
+
identity: OwnBundleState | "untouched";
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
async function mDM_send(
|
|
192
|
+
input: z.infer<typeof mDM_send_input>,
|
|
193
|
+
ctx: MosaddToolContext,
|
|
194
|
+
): Promise<MdmSendResultOut> {
|
|
176
195
|
const dm = ctx.providers.dm;
|
|
177
196
|
const selfId = await dm.selfId();
|
|
178
197
|
const threadId = dmThreadId(selfId, input.to, input.thread_label);
|
|
179
|
-
|
|
180
198
|
const keys = ctx.providers.keys;
|
|
181
199
|
|
|
182
|
-
// ⛔ 27.09.2026
|
|
183
|
-
//
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
//
|
|
187
|
-
//
|
|
200
|
+
// ⛔ POPRAWKA 27.09.2026 (niezalezna weryfikacja toru mdm-brama). The first fix seeded the mDM
|
|
201
|
+
// identity from ONE API key and let an agent line (re)publish it. An identity holds MANY keys
|
|
202
|
+
// (general@: 8 active), so the directory flapped between per-key identities and every copy
|
|
203
|
+
// sealed under the previous key stopped opening. The source answer is the King's rule, not a
|
|
204
|
+
// better key: an agent line NEVER uses E2EE (DECYZJE-KROLA 20.09 12:56Z: linie<->linie,
|
|
205
|
+
// linie<->Krol, czlowiek->linia: jawnie). Plaintext is readable by every key of the line and by
|
|
206
|
+
// the recipient's app on every device, and no bundle is needed, so nothing can flap.
|
|
207
|
+
const selfKind = await selfKindOf(dm);
|
|
208
|
+
const peerKind = selfKind === "agent" || input.to === selfId ? selfKind : await peerKindOf(dm, input.to);
|
|
209
|
+
if (selfKind === "agent" || peerKind === "agent") {
|
|
210
|
+
const payload = packPlaintextPayload(input.text);
|
|
211
|
+
ctx.log("debug", "mDM_send plaintext agent lane (rozkaz Krola 20.09)", {
|
|
212
|
+
thread_id: threadId,
|
|
213
|
+
self_kind: selfKind,
|
|
214
|
+
peer_kind: peerKind,
|
|
215
|
+
});
|
|
216
|
+
const plainArgs: DmSendArgsExt = {
|
|
217
|
+
to: input.to,
|
|
218
|
+
threadId,
|
|
219
|
+
payload,
|
|
220
|
+
replyToId: input.reply_to_id,
|
|
221
|
+
messageType: MDM_TEXT_MESSAGE_TYPE,
|
|
222
|
+
};
|
|
223
|
+
const result = await dm.send(plainArgs);
|
|
224
|
+
return {
|
|
225
|
+
message_id: result.id,
|
|
226
|
+
delivered_at: result.deliveredAt,
|
|
227
|
+
thread_id: threadId,
|
|
228
|
+
encrypted: false,
|
|
229
|
+
mode: "plaintext_agent_lane",
|
|
230
|
+
sender_copy: true,
|
|
231
|
+
recipient_copy: true,
|
|
232
|
+
identity: "untouched",
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// E2EE path (human to human, or a lane that cannot tell kinds). The plaintext is packed into
|
|
237
|
+
// the inner envelope, then SEALED via X3DH + Double Ratchet into an opaque envelope the
|
|
238
|
+
// DmProvider moves without understanding. First contact fetches the peer's published prekey
|
|
239
|
+
// bundle through the same provider (decision "1a").
|
|
240
|
+
//
|
|
241
|
+
// On a PERSON's key MCP writes nothing to the key directory (bundlePolicyForKind: the app owns
|
|
242
|
+
// a human's bundle) and no "s1." self copy: the app opens only copies sealed under its own seed,
|
|
243
|
+
// and an unopenable "s1." makes it state a FALSE reason ("device"/"key") for the bubble. The
|
|
244
|
+
// envelope is typed `text` so the app states the true one: sent by MCP, no copy for this device.
|
|
188
245
|
let identity: OwnBundleState = "foreign";
|
|
189
246
|
try {
|
|
190
|
-
identity = await ensureOwnBundlePublished(keys, dm, selfId, {
|
|
191
|
-
mayReplaceForeign: (await selfKindOf(dm)) === "agent",
|
|
192
|
-
});
|
|
247
|
+
identity = await ensureOwnBundlePublished(keys, dm, selfId, bundlePolicyForKind(selfKind, { explicit: false }));
|
|
193
248
|
} catch (err) {
|
|
194
249
|
// Directory unreachable: the ratchet envelope still carries its own handshake, so the send
|
|
195
250
|
// proceeds; only the recipient copy is skipped (it would be sealed under an unverified identity).
|
|
196
251
|
ctx.log("warn", "mDM_send could not reconcile own prekey bundle", { error: String(err) });
|
|
197
252
|
}
|
|
253
|
+
const ourIdentityIsPublished = identity === "consistent" || identity === "published";
|
|
198
254
|
|
|
199
|
-
// reply-linkage jedzie w dm.send({replyToId}) — surowy tekst nie ma koperty, w
|
|
200
|
-
//
|
|
255
|
+
// reply-linkage jedzie w dm.send({replyToId}) — surowy tekst nie ma koperty, w ktora
|
|
256
|
+
// mozna by go wpakowac (zmiana formatu 2026-08-25, patrz packPlaintextPayload).
|
|
201
257
|
const inner = packPlaintextPayload(input.text);
|
|
202
258
|
const sealed = await encryptForPeer(keys, dm, input.to, inner);
|
|
203
259
|
|
|
204
|
-
|
|
260
|
+
// "s1." only where the reader of that copy is MCP itself: never on a human key (see above).
|
|
261
|
+
const selfPayload = selfKind !== "human" && ourIdentityIsPublished ? await sealForSelf(keys, inner) : null;
|
|
205
262
|
let recipientSelfPayload: string | null = null;
|
|
206
|
-
// The recipient opens "r1." with OUR PUBLISHED identity
|
|
207
|
-
// directory holds exactly our key. A note-to-self needs none
|
|
208
|
-
if (
|
|
263
|
+
// The recipient opens "r1." with OUR PUBLISHED identity, so it is written only when the
|
|
264
|
+
// directory holds exactly our key. A note-to-self needs none.
|
|
265
|
+
if (ourIdentityIsPublished && input.to !== selfId) {
|
|
209
266
|
try {
|
|
210
267
|
const peer = await fetchVerifiedBundle(dm, input.to);
|
|
211
268
|
if (peer) recipientSelfPayload = await sealForPeerRecoverable(keys, peer, inner);
|
|
@@ -227,7 +284,7 @@ async function mDM_send(
|
|
|
227
284
|
threadId,
|
|
228
285
|
payload: sealed,
|
|
229
286
|
replyToId: input.reply_to_id,
|
|
230
|
-
messageType:
|
|
287
|
+
messageType: MDM_MCP_SEALED_MESSAGE_TYPE,
|
|
231
288
|
selfPayload,
|
|
232
289
|
recipientSelfPayload,
|
|
233
290
|
};
|
|
@@ -245,6 +302,7 @@ async function mDM_send(
|
|
|
245
302
|
delivered_at: result.deliveredAt,
|
|
246
303
|
thread_id: threadId,
|
|
247
304
|
encrypted: true,
|
|
305
|
+
mode: "e2ee",
|
|
248
306
|
sender_copy: !!selfPayload,
|
|
249
307
|
recipient_copy: !!recipientSelfPayload,
|
|
250
308
|
identity,
|
|
@@ -288,12 +346,34 @@ async function mDM_send_unencrypted(
|
|
|
288
346
|
async function mDM_publish_keys(
|
|
289
347
|
_input: Record<string, never>,
|
|
290
348
|
ctx: MosaddToolContext,
|
|
291
|
-
): Promise<{ published:
|
|
349
|
+
): Promise<{ published: boolean; identity: OwnBundleState; one_time_prekeys: number; note?: string }> {
|
|
292
350
|
// Publish the local prekey bundle so peers can start encrypted sessions with
|
|
293
351
|
// us. Rides the same provider as messages (network row / radio announce).
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
352
|
+
//
|
|
353
|
+
// ⛔ 27.09.2026: never over a PERSON's app-anchored bundle. The MCP identity is seeded from the
|
|
354
|
+
// API key, the app's from the login secret; replacing the app's bundle breaks every DM to that
|
|
355
|
+
// person on every device (bundlePolicyForKind, explicit). An empty directory may be filled.
|
|
356
|
+
const dm = ctx.providers.dm;
|
|
357
|
+
const keys = ctx.providers.keys;
|
|
358
|
+
const selfId = await dm.selfId();
|
|
359
|
+
const identity = await ensureOwnBundlePublished(
|
|
360
|
+
keys,
|
|
361
|
+
dm,
|
|
362
|
+
selfId,
|
|
363
|
+
bundlePolicyForKind(await selfKindOf(dm), { explicit: true }),
|
|
364
|
+
);
|
|
365
|
+
const { oneTimePrekeys } = await keys.getOwnMaterial();
|
|
366
|
+
ctx.log("debug", "mDM_publish_keys", { identity, one_time_prekeys: oneTimePrekeys.length });
|
|
367
|
+
if (identity === "foreign") {
|
|
368
|
+
return {
|
|
369
|
+
published: false,
|
|
370
|
+
identity,
|
|
371
|
+
one_time_prekeys: 0,
|
|
372
|
+
note:
|
|
373
|
+
"This identity already has keys published by the mosADD app. They were left untouched: replacing them from an API key would make every conversation with you unreadable in the app.",
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
return { published: identity === "published", identity, one_time_prekeys: oneTimePrekeys.length };
|
|
297
377
|
}
|
|
298
378
|
|
|
299
379
|
async function mDM_list(
|
|
@@ -540,7 +620,7 @@ export const mdmTools: MosaddTool[] = [
|
|
|
540
620
|
annotations: { readOnlyHint: false },
|
|
541
621
|
requires: "any",
|
|
542
622
|
description:
|
|
543
|
-
"Send
|
|
623
|
+
"Send a direct message via mosadd mDM. Between two PEOPLE it is END-TO-END-ENCRYPTED; when either side is an agent line it goes in the clear (mosadd rule: agents must read their DMs), exactly like the mosadd app. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts). Establishes an X3DH + Double Ratchet session on first contact (the recipient must have run mDM_publish_keys). Optional thread_label puts the message in a named thread — mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram. If the recipient has no published keys yet, use mDM_send_unencrypted.",
|
|
544
624
|
inputSchema: mDM_send_input,
|
|
545
625
|
handler: mDM_send as MosaddTool["handler"],
|
|
546
626
|
},
|