@mosadd/mcp 3.0.0-alpha.49 → 3.0.0-alpha.50

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.
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Channel E2EE for MCP toolkit LINES (F4 / LINEAR-5934).
3
+ *
4
+ * The mosadd.com app encrypts text on password/private channels with a per-channel
5
+ * group key (AES-256-GCM + HMAC-SHA256), wrapped for each member to the member's
6
+ * X25519 identity key published as `identities.signed_prekey_pub`. Until now the
7
+ * toolkit could not join that scheme: it held no identity key at all, so an agent
8
+ * line saw every encrypted channel as "<ciphertext>" and its own posts landed
9
+ * server-readable (unreadable by the app).
10
+ *
11
+ * This module gives a LINE the same parity:
12
+ * 1. ensureLineChannelKey() — resolves the key's identity (identities.user_id),
13
+ * provisions a PERSISTENT X25519 keypair in `channel_line_keys` (RLS: only the
14
+ * line's own auth user) and publishes the public half to
15
+ * identities.signed_prekey_pub, so app-side invites wrap the group key to it.
16
+ * Provisioning is REFUSED for human identities — their X25519 key is derived
17
+ * on-device from the vault master key and must never be shadowed.
18
+ * 2. getGroupKey(channelId) — reads the line's own `channel_keys` row (newest
19
+ * key_version), unwraps the group key (X25519 + HKDF "m0ssad-group-wrap"),
20
+ * caches it per process.
21
+ * 3. encryptChannelPayload / decryptChannelPayload — byte-compatible with the
22
+ * app (useChannelCrypto): ciphertext JSON {iv, ciphertext, hmac} with
23
+ * HMAC-SHA256 over the base64 ciphertext STRING, whole envelope base64.
24
+ *
25
+ * FAIL-SOFT: every entry point returns null on any error (no identity, no wrapped
26
+ * key, bad HMAC, wrong key) instead of throwing, so callers fall back to the
27
+ * legacy server-readable path exactly as before. The scheme only upgrades a
28
+ * channel the line actually holds a group key for.
29
+ */
30
+
31
+ import { createHmac, timingSafeEqual } from "node:crypto";
32
+ import {
33
+ decryptText,
34
+ encryptText,
35
+ exportX25519KeyPair,
36
+ fromBase64,
37
+ generateX25519KeyPair,
38
+ toBase64,
39
+ unwrapGroupKey,
40
+ type WrappedGroupKey,
41
+ } from "@mosadd/crypto";
42
+ import { getSupabase, readSupabaseEnv } from "../providers/supabase.js";
43
+
44
+ interface LineChannelKey {
45
+ publicKey: Uint8Array;
46
+ privateKey: Uint8Array;
47
+ }
48
+
49
+ // ---- Pure core (unit-tested) ----
50
+
51
+ /** HMAC-SHA256 over the base64 ciphertext string, exactly like the app (2C). */
52
+ export function signCiphertext(groupKey: Uint8Array, ciphertextB64: string): string {
53
+ return createHmac("sha256", Buffer.from(groupKey)).update(ciphertextB64, "utf8").digest("base64");
54
+ }
55
+
56
+ /** AES-256-GCM encrypt + HMAC + JSON envelope + base64 (the stored payload). */
57
+ export async function encryptWithGroupKey(groupKey: Uint8Array, plaintext: string): Promise<string> {
58
+ const encrypted = await encryptText(groupKey, plaintext);
59
+ const hmac = signCiphertext(groupKey, encrypted.ciphertext);
60
+ return Buffer.from(JSON.stringify({ ...encrypted, hmac }), "utf8").toString("base64");
61
+ }
62
+
63
+ /**
64
+ * Base64 envelope → HMAC check (tamper = null) → AES-GCM decrypt.
65
+ * Returns null for anything that is not a valid, untampered group-key payload.
66
+ */
67
+ export async function decryptWithGroupKey(groupKey: Uint8Array, payloadB64: string): Promise<string | null> {
68
+ try {
69
+ const decoded = Buffer.from(payloadB64, "base64").toString("utf8");
70
+ if (!decoded.startsWith("{")) return null;
71
+ const parsed = JSON.parse(decoded) as { iv?: string; ciphertext?: string; hmac?: string };
72
+ if (!parsed.iv || !parsed.ciphertext) return null;
73
+ if (parsed.hmac) {
74
+ const expected = createHmac("sha256", Buffer.from(groupKey)).update(parsed.ciphertext, "utf8").digest();
75
+ const got = Buffer.from(parsed.hmac, "base64");
76
+ if (got.length !== expected.length || !timingSafeEqual(got, expected)) return null;
77
+ }
78
+ return await decryptText(groupKey, { iv: parsed.iv, ciphertext: parsed.ciphertext });
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ /** Unwrap a `mosadd.chat.v1` envelope produced by toolkit posts; leave app-sent raw text. */
85
+ export function unwrapEnvelopeText(plain: string): string {
86
+ if (plain.length > 2 && plain.startsWith("{") && plain.endsWith("}") && plain.includes("mosadd.chat")) {
87
+ try {
88
+ const env = JSON.parse(plain) as { v?: string; type?: string; text?: string };
89
+ if (typeof env.text === "string" && env.v === "mosadd.chat.v1" && (env.type === "text" || env.type === undefined)) {
90
+ return env.text;
91
+ }
92
+ } catch {
93
+ /* not an envelope */
94
+ }
95
+ }
96
+ return plain;
97
+ }
98
+
99
+ // ---- Supabase glue (per-process caches) ----
100
+
101
+ let cachedIdentity: { id: string; kind: string | null } | null = null;
102
+ let cachedLineKey: LineChannelKey | null = null;
103
+ let provisioning: Promise<LineChannelKey | null> | null = null;
104
+ const groupKeyCache = new Map<string, Uint8Array>();
105
+
106
+ /** Resolve the identity behind the current Supabase session (per process). */
107
+ async function resolveIdentity(): Promise<{ id: string; kind: string | null } | null> {
108
+ if (cachedIdentity) return cachedIdentity;
109
+ try {
110
+ readSupabaseEnv();
111
+ const sb = getSupabase();
112
+ const { data: u, error: ue } = await sb.auth.getUser();
113
+ if (ue || !u?.user) return null;
114
+ const { data: identity, error } = await sb
115
+ .from("identities")
116
+ .select("id, kind")
117
+ .eq("user_id", u.user.id)
118
+ .maybeSingle();
119
+ if (error || !identity?.id) return null;
120
+ cachedIdentity = { id: identity.id as string, kind: (identity.kind as string | null) ?? null };
121
+ return cachedIdentity;
122
+ } catch {
123
+ return null;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Keep identities.signed_prekey_pub == the line's public key. Idempotent and
129
+ * silent-failing: a stale SPK only degrades NEW invites (they would wrap to the
130
+ * old key), so never throw here — the line key still works for existing rows.
131
+ */
132
+ async function syncPublishedKey(identityId: string, publicKeyB64: string): Promise<void> {
133
+ try {
134
+ const sb = getSupabase();
135
+ const { data: row } = await sb
136
+ .from("identities")
137
+ .select("signed_prekey_pub")
138
+ .eq("id", identityId)
139
+ .maybeSingle();
140
+ if (row?.signed_prekey_pub === publicKeyB64) return;
141
+ const { error } = await sb.from("identities").update({ signed_prekey_pub: publicKeyB64 }).eq("id", identityId);
142
+ if (error) {
143
+ // Surface the RLS/GRANT truth once per process instead of dying silently —
144
+ // agents must know WHY a future invite would wrap to the wrong key.
145
+ cachedIdentity = null;
146
+ }
147
+ } catch {
148
+ /* never throw from a sync helper */
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Get-or-provision the line's persistent channel keypair. Publishes the public
154
+ * half to identities.signed_prekey_pub so app-side invites wrap the group key to
155
+ * it. Returns null (never throws) for human identities or on any failure.
156
+ */
157
+ export async function ensureLineChannelKey(): Promise<LineChannelKey | null> {
158
+ if (cachedLineKey) return cachedLineKey;
159
+ if (provisioning) return provisioning;
160
+ provisioning = (async (): Promise<LineChannelKey | null> => {
161
+ try {
162
+ const identity = await resolveIdentity();
163
+ if (!identity) return null;
164
+ // ⛔ Only agent/robot lines: a human identity's X25519 key is vault-derived
165
+ // on-device; publishing a server-generated key here would hijack its
166
+ // signed_prekey_pub and break the app's own decrypt (F4 design decision).
167
+ if (identity.kind !== "agent" && identity.kind !== "robot") return null;
168
+
169
+ const sb = getSupabase();
170
+ const { data: row, error: readErr } = await sb
171
+ .from("channel_line_keys")
172
+ .select("public_key, private_key")
173
+ .eq("identity_id", identity.id)
174
+ .maybeSingle();
175
+ if (readErr) return null;
176
+
177
+ if (row?.private_key) {
178
+ const key: LineChannelKey = { publicKey: fromBase64(row.public_key), privateKey: fromBase64(row.private_key) };
179
+ await syncPublishedKey(identity.id, row.public_key);
180
+ cachedLineKey = key;
181
+ return key;
182
+ }
183
+
184
+ // Fresh keypair. Race (two cold processes): PK conflict → ignoreDuplicates,
185
+ // then re-read the winner so both processes converge on ONE keypair.
186
+ const pair = await generateX25519KeyPair();
187
+ const exported = await exportX25519KeyPair(pair);
188
+ const { data: u } = await sb.auth.getUser();
189
+ const userId = u?.user?.id;
190
+ if (!userId) return null;
191
+ await sb
192
+ .from("channel_line_keys")
193
+ .upsert(
194
+ { identity_id: identity.id, user_id: userId, public_key: exported.publicKey, private_key: exported.privateKey, key_version: 1 },
195
+ { onConflict: "identity_id", ignoreDuplicates: true },
196
+ );
197
+ const { data: winner, error: winnerErr } = await sb
198
+ .from("channel_line_keys")
199
+ .select("public_key, private_key")
200
+ .eq("identity_id", identity.id)
201
+ .maybeSingle();
202
+ if (winnerErr || !winner?.private_key) return null;
203
+
204
+ // Publish the public half — the app wraps group keys for new members to this.
205
+ await syncPublishedKey(identity.id, winner.public_key);
206
+
207
+ const key: LineChannelKey = { publicKey: fromBase64(winner.public_key), privateKey: fromBase64(winner.private_key) };
208
+ cachedLineKey = key;
209
+ return key;
210
+ } catch {
211
+ return null;
212
+ }
213
+ })();
214
+ try {
215
+ return await provisioning;
216
+ } finally {
217
+ provisioning = null;
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Unwrap this channel's group key for the line (newest key_version), cached per
223
+ * process. Returns null when the line has no key material or no wrapped row —
224
+ * callers then use the legacy plaintext path.
225
+ */
226
+ export async function getGroupKey(channelId: string): Promise<Uint8Array | null> {
227
+ const cached = groupKeyCache.get(channelId);
228
+ if (cached) return cached;
229
+ try {
230
+ const lineKey = await ensureLineChannelKey();
231
+ if (!lineKey) return null;
232
+ const identity = await resolveIdentity();
233
+ if (!identity) return null;
234
+ const sb = getSupabase();
235
+ const { data: row, error } = await sb
236
+ .from("channel_keys")
237
+ .select("wrapped_group_key")
238
+ .eq("channel_id", channelId)
239
+ .eq("identity_id", identity.id)
240
+ .order("key_version", { ascending: false })
241
+ .limit(1)
242
+ .maybeSingle();
243
+ if (error || !row?.wrapped_group_key) return null;
244
+ const wrapped = JSON.parse(row.wrapped_group_key) as WrappedGroupKey;
245
+ const groupKey = await unwrapGroupKey(wrapped, lineKey.privateKey);
246
+ groupKeyCache.set(channelId, groupKey);
247
+ return groupKey;
248
+ } catch {
249
+ return null;
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Encrypt text for a channel with a group key. Returns null (no encryption —
255
+ * caller uses legacy plaintext) when the line holds no group key for it.
256
+ */
257
+ export async function encryptChannelPayload(channelId: string, plaintext: string): Promise<string | null> {
258
+ const groupKey = await getGroupKey(channelId);
259
+ if (!groupKey) return null;
260
+ try {
261
+ return await encryptWithGroupKey(groupKey, plaintext);
262
+ } catch {
263
+ return null;
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Decrypt a stored payload for a channel. Returns null when the payload is not
269
+ * group-key encrypted, tampered, or the line holds no key for the channel.
270
+ */
271
+ export async function decryptChannelPayload(channelId: string, payloadB64: string): Promise<string | null> {
272
+ const groupKey = await getGroupKey(channelId);
273
+ if (!groupKey) return null;
274
+ return decryptWithGroupKey(groupKey, payloadB64);
275
+ }
276
+
277
+ /** Exposed for tests: reset the per-process caches. */
278
+ export function resetChannelE2eeCaches(): void {
279
+ cachedIdentity = null;
280
+ cachedLineKey = null;
281
+ groupKeyCache.clear();
282
+ }
283
+
284
+ /** Exposed for tests/ops: the line's published public key (base64), or null. */
285
+ export async function lineChannelPublicKey(): Promise<string | null> {
286
+ const lineKey = await ensureLineChannelKey();
287
+ return lineKey ? toBase64(lineKey.publicKey) : null;
288
+ }
@@ -12,6 +12,7 @@ import { z } from "zod";
12
12
  import type { MosaddTool, MosaddToolContext } from "../types.js";
13
13
  import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
14
14
  import { formatVoiceIfAny } from "./voice-format.js";
15
+ import { decryptChannelPayload, encryptChannelPayload, unwrapEnvelopeText } from "../crypto/channel-e2ee.js";
15
16
 
16
17
  const PROTOCOL_VERSION = "mosadd.chat.v1";
17
18
 
@@ -47,12 +48,12 @@ const mIRC_list_messages_input = z.object({
47
48
  space_id: z.string().optional().describe("Optional backing space id. Resolved automatically if omitted."),
48
49
  });
49
50
 
50
- // ALPHA: channel messages are NOT end-to-end encrypted here — the body is wrapped
51
- // in a JSON envelope and base64-encoded (server-readable). The mosadd.com app
52
- // encrypts channel messages with a per-channel group key, so app clients cannot
53
- // decrypt these dev-posted plaintext payloads (and vice-versa) until the toolkit
54
- // adopts the same group-key scheme. See docs/security/e2ee-posture.md.
55
- function packPlaintextPayload(text: string, replyToId?: string): string {
51
+ // Channel messages on password/private channels are group-key encrypted when the
52
+ // line holds the channel's group key (channel_keys row wrapped to the line's
53
+ // identity — F4/LINEAR-5934). Open channels have no key → the legacy server-readable
54
+ // envelope below. The envelope JSON is the PLAINTEXT inside the group-key seal, so
55
+ // the app unwraps toolkit posts into the same bubble shape as before.
56
+ function buildPlaintextEnvelope(text: string, replyToId?: string): string {
56
57
  const envelope = {
57
58
  v: PROTOCOL_VERSION,
58
59
  type: "text",
@@ -60,7 +61,7 @@ function packPlaintextPayload(text: string, replyToId?: string): string {
60
61
  reply_to: replyToId ?? null,
61
62
  sent_at: new Date().toISOString(),
62
63
  };
63
- return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
64
+ return JSON.stringify(envelope);
64
65
  }
65
66
 
66
67
  function unpackPayload(payload: string): { text: string } {
@@ -73,6 +74,13 @@ function unpackPayload(payload: string): { text: string } {
73
74
  return { text: "<ciphertext>" };
74
75
  }
75
76
 
77
+ /** Stored payload → readable text. Group-key decrypt first; legacy base64 envelope second. */
78
+ async function payloadToText(channelId: string, payload: string): Promise<string> {
79
+ const decrypted = await decryptChannelPayload(channelId, payload);
80
+ if (decrypted !== null) return unwrapEnvelopeText(decrypted);
81
+ return unpackPayload(payload).text;
82
+ }
83
+
76
84
  /** Resolve a channel's backing space id (metadata.linked_space_id) via channel-manage. */
77
85
  async function resolveLinkedSpaceId(channelId: string): Promise<string> {
78
86
  type GetResponse = {
@@ -101,10 +109,16 @@ async function mIRC_post_message(
101
109
  const thread_id = `chat:${input.channel_id}`;
102
110
  ctx.log("debug", "mIRC_post_message", { thread_id, space_id, agent: input.agent });
103
111
 
112
+ // Group-key seal when the line holds the channel's key (password/private channels).
113
+ // Fallback = legacy server-readable envelope (open channels / no key yet).
114
+ const envelope = buildPlaintextEnvelope(input.text, input.reply_to_id);
115
+ const encrypted = await encryptChannelPayload(input.channel_id, envelope);
116
+ const payload = encrypted ?? Buffer.from(envelope, "utf8").toString("base64");
117
+
104
118
  const data = await invokeFunction<{ message?: { id: string; created_at: string }; sent_as?: SentAs }>("message-send", {
105
119
  space_id,
106
120
  thread_id,
107
- encrypted_payload: packPlaintextPayload(input.text, input.reply_to_id),
121
+ encrypted_payload: payload,
108
122
  message_type: "txt",
109
123
  protocol_version: PROTOCOL_VERSION,
110
124
  reply_to_id: input.reply_to_id ?? null,
@@ -151,13 +165,18 @@ async function mIRC_list_messages(
151
165
  before: input.cursor,
152
166
  });
153
167
 
154
- return {
155
- messages: (data?.messages ?? []).map((m) => ({
168
+ const messages: Array<{ id: string; sender_identity_id: string; text: string; timestamp: string }> = [];
169
+ for (const m of data?.messages ?? []) {
170
+ messages.push({
156
171
  id: m.id,
157
172
  sender_identity_id: m.sender_identity_id,
158
- text: formatVoiceIfAny(unpackPayload(m.encrypted_payload).text),
173
+ text: formatVoiceIfAny(await payloadToText(input.channel_id, m.encrypted_payload)),
159
174
  timestamp: m.created_at,
160
- })),
175
+ });
176
+ }
177
+
178
+ return {
179
+ messages,
161
180
  next_cursor: data?.next_before ?? data?.cursor ?? null,
162
181
  };
163
182
  }
@@ -169,7 +188,7 @@ export const mircMessagesTools: MosaddTool[] = [
169
188
  annotations: { readOnlyHint: false },
170
189
  requires: "network",
171
190
  description:
172
- "Post a text message into a persistent channel (mIRC). Pass channel_id from mIRC_create / mIRC_list; the backing space is resolved automatically. This is how an agent actually talks in a channel — the other mIRC_* tools only manage it. ACCESS: banned/blocked users are refused on ALL access modes (including open); open channels accept anyone not banned; password channels require joining with the password; private channels require request-access + approval. ATTRIBUTION: by default the message is signed with the identity behind the API key — and a key belongs to a USER, so an agent runtime using its owner's key posts as the OWNER. Pass `agent` to sign as one of your own agents instead; the server verifies you own it and that it is in the channel. ENCRYPTION: this tool posts SERVER-READABLE plaintext base64 on EVERY access mode — private and password channels included; it is never end-to-end encrypted. Open channels: app clients CAN read toolkit-posted messages. Password/private channels: the mosadd.com app group-key-encrypts channel text on supported clients, but the toolkit does not hold that group key — the message still lands server-readable and app clients cannot decrypt it as channel text (group-key parity is not yet wired).",
191
+ "Post a text message into a persistent channel (mIRC). Pass channel_id from mIRC_create / mIRC_list; the backing space is resolved automatically. This is how an agent actually talks in a channel — the other mIRC_* tools only manage it. ACCESS: banned/blocked users are refused on ALL access modes (including open); open channels accept anyone not banned; password channels require joining with the password; private channels require request-access + approval. ATTRIBUTION: by default the message is signed with the identity behind the API key — and a key belongs to a USER, so an agent runtime using its owner's key posts as the OWNER. Pass `agent` to sign as one of your own agents instead; the server verifies you own it and that it is in the channel. ENCRYPTION: when your line holds the channel's group key (password/private channels where a wrapped key row exists for your identity — it is auto-provisioned on first use), the message is sealed AES-256-GCM + HMAC exactly like the app, so members read it as normal channel text. Open channels and channels without a wrapped key for your line fall back to the legacy server-readable envelope.",
173
192
  inputSchema: mIRC_post_message_input,
174
193
  handler: mIRC_post_message as MosaddTool["handler"],
175
194
  },
@@ -179,7 +198,7 @@ export const mircMessagesTools: MosaddTool[] = [
179
198
  annotations: { readOnlyHint: true },
180
199
  requires: "network",
181
200
  description:
182
- "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically.",
201
+ "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically. ENCRYPTION: messages your line can decrypt (group-key channels — auto-provisioned key material) come back as readable text; anything else falls back to the legacy envelope/plaintext decode.",
183
202
  inputSchema: mIRC_list_messages_input,
184
203
  handler: mIRC_list_messages as MosaddTool["handler"],
185
204
  },