@mosadd/mcp 3.0.0-alpha.7 → 3.0.0

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 (66) hide show
  1. package/CHANGELOG.md +410 -0
  2. package/README.md +79 -40
  3. package/dist/bin/mcp.js +132 -8
  4. package/dist/chunk-VMMJJYXF.js +4233 -0
  5. package/dist/index.d.ts +110 -6
  6. package/dist/index.js +3 -1
  7. package/package.json +19 -16
  8. package/src/__tests__/blob-upload.test.ts +93 -0
  9. package/src/__tests__/channel-e2ee.test.ts +62 -0
  10. package/src/__tests__/cli.test.ts +47 -0
  11. package/src/__tests__/flota-jawnie.test.ts +244 -0
  12. package/src/__tests__/golden-path.test.ts +4 -2
  13. package/src/__tests__/integration.test.ts +50 -11
  14. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  15. package/src/__tests__/label-room-owner.test.ts +22 -0
  16. package/src/__tests__/mdm-e2ee.test.ts +35 -1
  17. package/src/__tests__/mdm-mcp-readable.test.ts +390 -0
  18. package/src/__tests__/mirc-invite.test.ts +112 -0
  19. package/src/__tests__/mrag-search-answer.test.ts +42 -0
  20. package/src/__tests__/no-dead-host.test.ts +37 -0
  21. package/src/__tests__/presence.test.ts +199 -0
  22. package/src/__tests__/server.test.ts +11 -7
  23. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  24. package/src/__tests__/tool-count-consistency.test.ts +259 -0
  25. package/src/__tests__/voice-fields.test.ts +24 -0
  26. package/src/bin/mcp.ts +71 -6
  27. package/src/cli.ts +100 -0
  28. package/src/crypto/channel-e2ee.ts +288 -0
  29. package/src/crypto/mdm-session.ts +476 -37
  30. package/src/index.ts +2 -2
  31. package/src/providers/blob-upload.ts +162 -0
  32. package/src/providers/supabase-dm.ts +102 -7
  33. package/src/providers/supabase-voice.ts +13 -1
  34. package/src/providers/supabase.ts +121 -10
  35. package/src/server.ts +102 -12
  36. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  37. package/src/tools/actions.ts +166 -0
  38. package/src/tools/attachments.ts +276 -0
  39. package/src/tools/capabilities.ts +2 -0
  40. package/src/tools/channel-payload.ts +69 -0
  41. package/src/tools/embed.ts +110 -0
  42. package/src/tools/index.ts +136 -6
  43. package/src/tools/knowledge-graph.ts +186 -0
  44. package/src/tools/knowledge.ts +351 -191
  45. package/src/tools/mail-agentbox.ts +155 -0
  46. package/src/tools/mail-aliases.ts +25 -0
  47. package/src/tools/mail-provenance.ts +137 -0
  48. package/src/tools/mail.ts +214 -60
  49. package/src/tools/mdm-as-agent.ts +138 -0
  50. package/src/tools/mdm-voice.ts +17 -3
  51. package/src/tools/mdm.ts +303 -57
  52. package/src/tools/mirc-edge.ts +8 -2
  53. package/src/tools/mirc-members.ts +130 -20
  54. package/src/tools/mirc-messages.ts +80 -35
  55. package/src/tools/mirc.ts +149 -11
  56. package/src/tools/mroom-messages.ts +4 -12
  57. package/src/tools/mtalk.ts +11 -1
  58. package/src/tools/murl.ts +314 -0
  59. package/src/tools/presence.ts +442 -0
  60. package/src/tools/ptt-ingest.ts +99 -0
  61. package/src/tools/threat.ts +123 -0
  62. package/src/tools/voice-format.ts +43 -0
  63. package/src/types.ts +36 -0
  64. package/src/version.ts +8 -0
  65. package/LICENSE +0 -201
  66. package/dist/chunk-EFTB743G.js +0 -1924
package/src/bin/mcp.ts CHANGED
@@ -10,10 +10,15 @@
10
10
  */
11
11
 
12
12
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
+ import { createClient } from "@supabase/supabase-js";
13
14
  import { createMosaddServer } from "../server.js";
15
+ import { loadSession, saveSession, isSessionExpired } from "../config.js";
16
+ import { allTools } from "../tools/index.js";
17
+ import { PKG_VERSION } from "../version.js";
18
+ import { parseCli, renderHelp, renderTools, renderVersion } from "../cli.js";
14
19
 
15
20
  const DEFAULT_EXCHANGE =
16
- "https://rooffhgbxafyjcwmwpsy.supabase.co/functions/v1/hub-key-exchange";
21
+ "https://api.mosadd.com/functions/v1/hub-key-exchange";
17
22
 
18
23
  /**
19
24
  * Hosted-hub path: when MOSADD_API_KEY is set, exchange it for a short-lived
@@ -51,23 +56,83 @@ async function bootstrapFromApiKey(): Promise<void> {
51
56
  }
52
57
  }
53
58
 
59
+ /**
60
+ * `mosadd login` path: refresh the saved session at boot so a stored token that
61
+ * expired since the last launch (Supabase access tokens last ~1h) is renewed
62
+ * silently from its refresh token — instead of failing the first tool call with
63
+ * "session expired, run `mosadd login` again". This makes a single `mosadd login`
64
+ * durable across restarts (the founder's "set once, forget" expectation). No-op
65
+ * when an explicit env JWT or hub key already resolved a session, when there is no
66
+ * saved session, or when the saved token is still valid.
67
+ */
68
+ async function bootstrapFromSavedSession(): Promise<void> {
69
+ if (process.env.MOSADD_USER_JWT) return;
70
+ const session = loadSession();
71
+ if (!session?.refreshToken) return;
72
+ // Still-valid token → the provider uses it as-is; don't churn the refresh token.
73
+ if (!isSessionExpired(session)) return;
74
+ try {
75
+ const client = createClient(session.url, session.anonKey, {
76
+ auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },
77
+ });
78
+ const { data, error } = await client.auth.refreshSession({ refresh_token: session.refreshToken });
79
+ if (error || !data.session) {
80
+ process.stderr.write(
81
+ JSON.stringify({ level: "warn", msg: "mosadd session refresh failed — run `mosadd login`", error: error?.message }) + "\n",
82
+ );
83
+ return;
84
+ }
85
+ saveSession({
86
+ url: session.url,
87
+ anonKey: session.anonKey,
88
+ accessToken: data.session.access_token,
89
+ refreshToken: data.session.refresh_token ?? session.refreshToken,
90
+ expiresAt: data.session.expires_at,
91
+ email: data.user?.email ?? session.email,
92
+ });
93
+ } catch (err) {
94
+ process.stderr.write(
95
+ JSON.stringify({ level: "warn", msg: "mosadd session refresh error — run `mosadd login`", error: String(err) }) + "\n",
96
+ );
97
+ }
98
+ }
99
+
54
100
  async function main(): Promise<void> {
55
- // Auth subcommands: `mosadd login | logout | whoami`. Everything else starts the server.
56
- const sub = process.argv[2];
57
- if (sub === "login" || sub === "logout" || sub === "whoami") {
101
+ // CLI: `--version`, `--help`, `tools` print and exit (they must NEVER start the stdio server — a bare
102
+ // `npx @mosadd/mcp --version` used to hang waiting for an MCP client). Auth subcommands: login | logout | whoami.
103
+ // Everything else starts the server.
104
+ const action = parseCli(process.argv.slice(2));
105
+ if (action.kind === "version") {
106
+ process.stdout.write(renderVersion(PKG_VERSION));
107
+ return;
108
+ }
109
+ if (action.kind === "help") {
110
+ process.stdout.write(renderHelp(PKG_VERSION));
111
+ return;
112
+ }
113
+ if (action.kind === "tools") {
114
+ process.stdout.write(renderTools(allTools));
115
+ return;
116
+ }
117
+ if (action.kind === "auth") {
58
118
  const { runAuthCommand } = await import("./login.js");
59
- await runAuthCommand(sub, process.argv.slice(3));
119
+ await runAuthCommand(action.sub, action.rest);
60
120
  return;
61
121
  }
62
122
 
63
123
  // Hosted: trade MOSADD_API_KEY for a live session before the server reads env.
64
124
  await bootstrapFromApiKey();
125
+ // `mosadd login`: renew a saved session whose access token expired since last launch.
126
+ await bootstrapFromSavedSession();
65
127
 
66
128
  const server = createMosaddServer({
67
129
  apiKey: process.env.MOSADD_API_KEY,
68
130
  hubUrl: process.env.MOSADD_HUB_URL,
69
131
  mode: (process.env.MOSADD_MODE as "cloud" | "local" | "self-host" | undefined),
70
132
  logLevel: (process.env.MOSADD_LOG_LEVEL as "debug" | "info" | "warn" | "error" | undefined),
133
+ // stdio is single-tenant: the session lives in env (set by bootstrapFromApiKey
134
+ // above), so auto-publish this identity's prekeys on boot → mDM is reachable.
135
+ autoPublishKeys: true,
71
136
  });
72
137
 
73
138
  const transport = new StdioServerTransport();
@@ -78,7 +143,7 @@ async function main(): Promise<void> {
78
143
  JSON.stringify({
79
144
  level: "info",
80
145
  msg: "mosadd MCP server ready",
81
- version: "3.0.0-alpha.0",
146
+ version: PKG_VERSION,
82
147
  ts: new Date().toISOString(),
83
148
  }) + "\n",
84
149
  );
package/src/cli.ts ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * CLI front of `npx @mosadd/mcp` — the parts that print and exit instead of starting the stdio server.
3
+ *
4
+ * --version / -v print the package.json version and exit
5
+ * --help / -h print commands + env vars and exit
6
+ * tools print every registered tool, grouped by module, and exit
7
+ *
8
+ * Pure functions on purpose (no process.exit, no I/O): bin/mcp.ts decides what to do with the result,
9
+ * and the tests call these directly. The version comes from ./version.js (= package.json), never typed here.
10
+ */
11
+
12
+ export interface CliTool {
13
+ name: string;
14
+ description?: string;
15
+ }
16
+
17
+ export type CliAction =
18
+ | { kind: "version" }
19
+ | { kind: "help" }
20
+ | { kind: "tools" }
21
+ | { kind: "auth"; sub: "login" | "logout" | "whoami"; rest: string[] }
22
+ | { kind: "serve" };
23
+
24
+ /** Decide what `argv` (process.argv.slice(2)) asks for. Flags win over subcommands; anything unknown starts the server. */
25
+ export function parseCli(args: readonly string[]): CliAction {
26
+ const first = args[0];
27
+ if (args.includes("--version") || args.includes("-v") || first === "version") return { kind: "version" };
28
+ if (args.includes("--help") || args.includes("-h") || first === "help") return { kind: "help" };
29
+ if (first === "tools") return { kind: "tools" };
30
+ if (first === "login" || first === "logout" || first === "whoami") return { kind: "auth", sub: first, rest: args.slice(1) };
31
+ return { kind: "serve" };
32
+ }
33
+
34
+ export function renderVersion(version: string): string {
35
+ return `${version}\n`;
36
+ }
37
+
38
+ export function renderHelp(version: string): string {
39
+ return [
40
+ `mosadd-mcp ${version} — mosADD MCP server (stdio)`,
41
+ ``,
42
+ `Usage:`,
43
+ ` npx @mosadd/mcp [command] [options]`,
44
+ ``,
45
+ `Commands:`,
46
+ ` (none) start the MCP server over stdio (what your agent runtime runs)`,
47
+ ` login sign in and save a session on this machine`,
48
+ ` logout delete the saved session`,
49
+ ` whoami show which identity the saved session / MOSADD_API_KEY resolves to`,
50
+ ` tools list every tool this server registers, grouped by module, and exit`,
51
+ ``,
52
+ `Options:`,
53
+ ` -v, --version print the version and exit`,
54
+ ` -h, --help print this help and exit`,
55
+ ``,
56
+ `Environment:`,
57
+ ` MOSADD_API_KEY hub API key — exchanged for a short-lived session at boot (hosted mode)`,
58
+ ` MOSADD_HUB_URL override the hub url`,
59
+ ` MOSADD_MODE local | cloud`,
60
+ ` MOSADD_LOG_LEVEL debug | info | warn | error (default info)`,
61
+ ` See the README for the full list (Supabase BYOK, Resend, LiveKit).`,
62
+ ``,
63
+ ].join("\n");
64
+ }
65
+
66
+ /** Module a tool belongs to: the part of the name before the first underscore (mDM_send -> mDM). */
67
+ export function moduleOf(toolName: string): string {
68
+ const i = toolName.indexOf("_");
69
+ return i > 0 ? toolName.slice(0, i) : toolName;
70
+ }
71
+
72
+ /** Tools grouped by module, groups ordered by size (largest first, then name), tools alphabetical inside a group. */
73
+ export function groupTools(tools: readonly CliTool[]): { module: string; tools: CliTool[] }[] {
74
+ const by = new Map<string, CliTool[]>();
75
+ for (const t of tools) {
76
+ const m = moduleOf(t.name);
77
+ by.set(m, [...(by.get(m) ?? []), t]);
78
+ }
79
+ return [...by.entries()]
80
+ .map(([module, list]) => ({ module, tools: [...list].sort((a, b) => a.name.localeCompare(b.name)) }))
81
+ .sort((a, b) => b.tools.length - a.tools.length || a.module.localeCompare(b.module));
82
+ }
83
+
84
+ const oneLine = (s: string | undefined, max = 90): string => {
85
+ const t = String(s ?? "").replace(/\s+/g, " ").trim();
86
+ const dot = t.search(/[.!?](\s|$)/);
87
+ const first = dot > 0 ? t.slice(0, dot + 1) : t;
88
+ return first.length > max ? `${first.slice(0, max - 1)}…` : first;
89
+ };
90
+
91
+ export function renderTools(tools: readonly CliTool[]): string {
92
+ const groups = groupTools(tools);
93
+ const lines: string[] = [`${tools.length} tools in ${groups.length} groups`, ``];
94
+ for (const g of groups) {
95
+ lines.push(`${g.module} (${g.tools.length})`);
96
+ for (const t of g.tools) lines.push(` ${t.name}${t.description ? ` — ${oneLine(t.description)}` : ""}`);
97
+ lines.push(``);
98
+ }
99
+ return lines.join("\n");
100
+ }
@@ -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 `mosadd_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("mosadd_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("mosadd_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("mosadd_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
+ }