@mosadd/mcp 3.0.0-alpha.5 → 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.
Files changed (64) hide show
  1. package/CHANGELOG.md +309 -0
  2. package/LICENSE +201 -201
  3. package/README.md +150 -126
  4. package/dist/bin/mcp.js +42 -3
  5. package/dist/chunk-L4PB6A6Z.js +3800 -0
  6. package/dist/index.d.ts +118 -5
  7. package/dist/index.js +7 -3
  8. package/package.json +10 -7
  9. package/src/__tests__/channel-e2ee.test.ts +62 -0
  10. package/src/__tests__/golden-path.test.ts +139 -137
  11. package/src/__tests__/integration.test.ts +182 -178
  12. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  13. package/src/__tests__/mdm-e2ee.test.ts +212 -178
  14. package/src/__tests__/mirc-invite.test.ts +112 -0
  15. package/src/__tests__/mtalk.test.ts +122 -122
  16. package/src/__tests__/presence.test.ts +199 -0
  17. package/src/__tests__/server.test.ts +71 -67
  18. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  19. package/src/__tests__/tool-count-consistency.test.ts +199 -0
  20. package/src/bin/login.ts +138 -138
  21. package/src/bin/mcp.ts +145 -97
  22. package/src/config.ts +66 -66
  23. package/src/crypto/channel-e2ee.ts +288 -0
  24. package/src/crypto/mdm-session.ts +502 -403
  25. package/src/index.ts +19 -17
  26. package/src/observability/sentry.ts +79 -79
  27. package/src/providers/blob-upload.ts +116 -0
  28. package/src/providers/memory-voice.ts +79 -79
  29. package/src/providers/supabase-dm.ts +122 -117
  30. package/src/providers/supabase-voice.ts +91 -91
  31. package/src/providers/supabase.ts +231 -96
  32. package/src/server.ts +162 -105
  33. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  34. package/src/tools/actions.ts +166 -0
  35. package/src/tools/attachments.ts +276 -0
  36. package/src/tools/capabilities.ts +70 -68
  37. package/src/tools/embed.ts +110 -0
  38. package/src/tools/index.ts +181 -51
  39. package/src/tools/knowledge-graph.ts +186 -0
  40. package/src/tools/knowledge.ts +344 -132
  41. package/src/tools/mail-agentbox.ts +155 -0
  42. package/src/tools/mail-aliases.ts +25 -0
  43. package/src/tools/mail-provenance.ts +137 -0
  44. package/src/tools/mail.ts +403 -157
  45. package/src/tools/mcall.ts +216 -216
  46. package/src/tools/mdm-as-agent.ts +126 -0
  47. package/src/tools/mdm-voice.ts +220 -206
  48. package/src/tools/mdm.ts +73 -26
  49. package/src/tools/mirc-edge.ts +196 -190
  50. package/src/tools/mirc-members.ts +287 -177
  51. package/src/tools/mirc-messages.ts +76 -27
  52. package/src/tools/mirc.ts +308 -170
  53. package/src/tools/mroom-messages.ts +142 -142
  54. package/src/tools/mroom.ts +221 -221
  55. package/src/tools/mtalk.ts +131 -121
  56. package/src/tools/murl.ts +314 -0
  57. package/src/tools/presence.ts +442 -0
  58. package/src/tools/ptt-ingest.ts +99 -0
  59. package/src/tools/threat.ts +123 -0
  60. package/src/tools/voice-format.ts +28 -0
  61. package/src/types.ts +121 -85
  62. package/src/version.ts +8 -0
  63. package/src/voice/floor.ts +132 -132
  64. package/dist/chunk-4C36JDTJ.js +0 -1836
package/src/bin/mcp.ts CHANGED
@@ -1,97 +1,145 @@
1
- #!/usr/bin/env node
2
- /**
3
- * `mosadd-mcp` (also runnable as `npx @mosadd/mcp`)
4
- *
5
- * Starts a mosadd MCP server over stdio. The standard transport for local
6
- * MCP clients (Claude Code, Cursor, Cline, Windsurf, Goose, ...).
7
- *
8
- * For HTTP/SSE transport (hosted mcp.mosadd.com), see packages/mcp-gateway
9
- * in the proprietary repo.
10
- */
11
-
12
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
- import { createMosaddServer } from "../server.js";
14
-
15
- const DEFAULT_EXCHANGE =
16
- "https://rooffhgbxafyjcwmwpsy.supabase.co/functions/v1/hub-key-exchange";
17
-
18
- /**
19
- * Hosted-hub path: when MOSADD_API_KEY is set, exchange it for a short-lived
20
- * session (URL + anon key + access token) so the tools act as the key's owner.
21
- * Removes the DevTools-JWT wall — paste one stable key, done. Falls through
22
- * silently if the key is unset or the exchange is unreachable (so BYOK/self-host
23
- * keep working).
24
- */
25
- async function bootstrapFromApiKey(): Promise<void> {
26
- const apiKey = process.env.MOSADD_API_KEY;
27
- if (!apiKey || process.env.MOSADD_USER_JWT) return;
28
- const endpoint = process.env.MOSADD_HUB_URL
29
- ? `${process.env.MOSADD_HUB_URL.replace(/\/$/, "")}/hub-key-exchange`
30
- : DEFAULT_EXCHANGE;
31
- try {
32
- const res = await fetch(endpoint, {
33
- method: "POST",
34
- headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
35
- body: "{}",
36
- });
37
- if (!res.ok) {
38
- process.stderr.write(
39
- JSON.stringify({ level: "warn", msg: "mosadd hub key exchange failed", status: res.status }) + "\n",
40
- );
41
- return;
42
- }
43
- const d = (await res.json()) as { url?: string; anon_key?: string; access_token?: string };
44
- if (d.url) process.env.MOSADD_SUPABASE_URL = d.url;
45
- if (d.anon_key) process.env.MOSADD_SUPABASE_ANON_KEY = d.anon_key;
46
- if (d.access_token) process.env.MOSADD_USER_JWT = d.access_token;
47
- } catch (err) {
48
- process.stderr.write(
49
- JSON.stringify({ level: "warn", msg: "mosadd hub unreachable", error: String(err) }) + "\n",
50
- );
51
- }
52
- }
53
-
54
- 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") {
58
- const { runAuthCommand } = await import("./login.js");
59
- await runAuthCommand(sub, process.argv.slice(3));
60
- return;
61
- }
62
-
63
- // Hosted: trade MOSADD_API_KEY for a live session before the server reads env.
64
- await bootstrapFromApiKey();
65
-
66
- const server = createMosaddServer({
67
- apiKey: process.env.MOSADD_API_KEY,
68
- hubUrl: process.env.MOSADD_HUB_URL,
69
- mode: (process.env.MOSADD_MODE as "cloud" | "local" | "self-host" | undefined),
70
- logLevel: (process.env.MOSADD_LOG_LEVEL as "debug" | "info" | "warn" | "error" | undefined),
71
- });
72
-
73
- const transport = new StdioServerTransport();
74
- await server.connect(transport);
75
-
76
- // The server now runs until stdin closes.
77
- process.stderr.write(
78
- JSON.stringify({
79
- level: "info",
80
- msg: "mosadd MCP server ready",
81
- version: "3.0.0-alpha.0",
82
- ts: new Date().toISOString(),
83
- }) + "\n",
84
- );
85
- }
86
-
87
- main().catch((err) => {
88
- process.stderr.write(
89
- JSON.stringify({
90
- level: "error",
91
- msg: "mosadd MCP server failed to start",
92
- error: err instanceof Error ? err.message : String(err),
93
- stack: err instanceof Error ? err.stack : undefined,
94
- }) + "\n",
95
- );
96
- process.exit(1);
97
- });
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `mosadd-mcp` (also runnable as `npx @mosadd/mcp`)
4
+ *
5
+ * Starts a mosadd MCP server over stdio. The standard transport for local
6
+ * MCP clients (Claude Code, Cursor, Cline, Windsurf, Goose, ...).
7
+ *
8
+ * For HTTP/SSE transport (hosted mcp.mosadd.com), see packages/mcp-gateway
9
+ * in the proprietary repo.
10
+ */
11
+
12
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
+ import { createClient } from "@supabase/supabase-js";
14
+ import { createMosaddServer } from "../server.js";
15
+ import { loadSession, saveSession, isSessionExpired } from "../config.js";
16
+
17
+ const DEFAULT_EXCHANGE =
18
+ "https://rooffhgbxafyjcwmwpsy.supabase.co/functions/v1/hub-key-exchange";
19
+
20
+ /**
21
+ * Hosted-hub path: when MOSADD_API_KEY is set, exchange it for a short-lived
22
+ * session (URL + anon key + access token) so the tools act as the key's owner.
23
+ * Removes the DevTools-JWT wall — paste one stable key, done. Falls through
24
+ * silently if the key is unset or the exchange is unreachable (so BYOK/self-host
25
+ * keep working).
26
+ */
27
+ async function bootstrapFromApiKey(): Promise<void> {
28
+ const apiKey = process.env.MOSADD_API_KEY;
29
+ if (!apiKey || process.env.MOSADD_USER_JWT) return;
30
+ const endpoint = process.env.MOSADD_HUB_URL
31
+ ? `${process.env.MOSADD_HUB_URL.replace(/\/$/, "")}/hub-key-exchange`
32
+ : DEFAULT_EXCHANGE;
33
+ try {
34
+ const res = await fetch(endpoint, {
35
+ method: "POST",
36
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
37
+ body: "{}",
38
+ });
39
+ if (!res.ok) {
40
+ process.stderr.write(
41
+ JSON.stringify({ level: "warn", msg: "mosadd hub key exchange failed", status: res.status }) + "\n",
42
+ );
43
+ return;
44
+ }
45
+ const d = (await res.json()) as { url?: string; anon_key?: string; access_token?: string };
46
+ if (d.url) process.env.MOSADD_SUPABASE_URL = d.url;
47
+ if (d.anon_key) process.env.MOSADD_SUPABASE_ANON_KEY = d.anon_key;
48
+ if (d.access_token) process.env.MOSADD_USER_JWT = d.access_token;
49
+ } catch (err) {
50
+ process.stderr.write(
51
+ JSON.stringify({ level: "warn", msg: "mosadd hub unreachable", error: String(err) }) + "\n",
52
+ );
53
+ }
54
+ }
55
+
56
+ /**
57
+ * `mosadd login` path: refresh the saved session at boot so a stored token that
58
+ * expired since the last launch (Supabase access tokens last ~1h) is renewed
59
+ * silently from its refresh token — instead of failing the first tool call with
60
+ * "session expired, run `mosadd login` again". This makes a single `mosadd login`
61
+ * durable across restarts (the founder's "set once, forget" expectation). No-op
62
+ * when an explicit env JWT or hub key already resolved a session, when there is no
63
+ * saved session, or when the saved token is still valid.
64
+ */
65
+ async function bootstrapFromSavedSession(): Promise<void> {
66
+ if (process.env.MOSADD_USER_JWT) return;
67
+ const session = loadSession();
68
+ if (!session?.refreshToken) return;
69
+ // Still-valid token → the provider uses it as-is; don't churn the refresh token.
70
+ if (!isSessionExpired(session)) return;
71
+ try {
72
+ const client = createClient(session.url, session.anonKey, {
73
+ auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },
74
+ });
75
+ const { data, error } = await client.auth.refreshSession({ refresh_token: session.refreshToken });
76
+ if (error || !data.session) {
77
+ process.stderr.write(
78
+ JSON.stringify({ level: "warn", msg: "mosadd session refresh failed — run `mosadd login`", error: error?.message }) + "\n",
79
+ );
80
+ return;
81
+ }
82
+ saveSession({
83
+ url: session.url,
84
+ anonKey: session.anonKey,
85
+ accessToken: data.session.access_token,
86
+ refreshToken: data.session.refresh_token ?? session.refreshToken,
87
+ expiresAt: data.session.expires_at,
88
+ email: data.user?.email ?? session.email,
89
+ });
90
+ } catch (err) {
91
+ process.stderr.write(
92
+ JSON.stringify({ level: "warn", msg: "mosadd session refresh error — run `mosadd login`", error: String(err) }) + "\n",
93
+ );
94
+ }
95
+ }
96
+
97
+ async function main(): Promise<void> {
98
+ // Auth subcommands: `mosadd login | logout | whoami`. Everything else starts the server.
99
+ const sub = process.argv[2];
100
+ if (sub === "login" || sub === "logout" || sub === "whoami") {
101
+ const { runAuthCommand } = await import("./login.js");
102
+ await runAuthCommand(sub, process.argv.slice(3));
103
+ return;
104
+ }
105
+
106
+ // Hosted: trade MOSADD_API_KEY for a live session before the server reads env.
107
+ await bootstrapFromApiKey();
108
+ // `mosadd login`: renew a saved session whose access token expired since last launch.
109
+ await bootstrapFromSavedSession();
110
+
111
+ const server = createMosaddServer({
112
+ apiKey: process.env.MOSADD_API_KEY,
113
+ hubUrl: process.env.MOSADD_HUB_URL,
114
+ mode: (process.env.MOSADD_MODE as "cloud" | "local" | "self-host" | undefined),
115
+ logLevel: (process.env.MOSADD_LOG_LEVEL as "debug" | "info" | "warn" | "error" | undefined),
116
+ // stdio is single-tenant: the session lives in env (set by bootstrapFromApiKey
117
+ // above), so auto-publish this identity's prekeys on boot → mDM is reachable.
118
+ autoPublishKeys: true,
119
+ });
120
+
121
+ const transport = new StdioServerTransport();
122
+ await server.connect(transport);
123
+
124
+ // The server now runs until stdin closes.
125
+ process.stderr.write(
126
+ JSON.stringify({
127
+ level: "info",
128
+ msg: "mosadd MCP server ready",
129
+ version: "3.0.0-alpha.0",
130
+ ts: new Date().toISOString(),
131
+ }) + "\n",
132
+ );
133
+ }
134
+
135
+ main().catch((err) => {
136
+ process.stderr.write(
137
+ JSON.stringify({
138
+ level: "error",
139
+ msg: "mosadd MCP server failed to start",
140
+ error: err instanceof Error ? err.message : String(err),
141
+ stack: err instanceof Error ? err.stack : undefined,
142
+ }) + "\n",
143
+ );
144
+ process.exit(1);
145
+ });
package/src/config.ts CHANGED
@@ -1,66 +1,66 @@
1
- /**
2
- * Local session config for the mosadd CLI (`mosadd login`).
3
- *
4
- * Stores the authenticated session at `~/.mosadd/session.json` so the MCP
5
- * server can pick up credentials without the user pasting an expiring JWT
6
- * from mosadd.com DevTools into env vars. Env vars still take precedence.
7
- *
8
- * The file holds a Supabase session (BYOK): the project URL + anon key (both
9
- * public, RLS-gated) and the user's access/refresh tokens.
10
- */
11
-
12
- import { homedir } from "node:os";
13
- import { join } from "node:path";
14
- import { mkdirSync, readFileSync, writeFileSync, rmSync, existsSync, chmodSync } from "node:fs";
15
-
16
- export interface MosaddSession {
17
- url: string;
18
- anonKey: string;
19
- accessToken: string;
20
- refreshToken?: string;
21
- /** Unix seconds when the access token expires. */
22
- expiresAt?: number;
23
- email?: string;
24
- }
25
-
26
- export function configDir(): string {
27
- return join(homedir(), ".mosadd");
28
- }
29
-
30
- export function sessionPath(): string {
31
- return join(configDir(), "session.json");
32
- }
33
-
34
- export function loadSession(): MosaddSession | null {
35
- try {
36
- const raw = readFileSync(sessionPath(), "utf8");
37
- const s = JSON.parse(raw) as MosaddSession;
38
- if (s && typeof s.url === "string" && typeof s.anonKey === "string") return s;
39
- return null;
40
- } catch {
41
- return null;
42
- }
43
- }
44
-
45
- export function saveSession(session: MosaddSession): void {
46
- mkdirSync(configDir(), { recursive: true });
47
- writeFileSync(sessionPath(), JSON.stringify(session, null, 2), "utf8");
48
- // Best-effort tighten perms (no-op on platforms that ignore it).
49
- try {
50
- chmodSync(sessionPath(), 0o600);
51
- } catch {
52
- /* ignore */
53
- }
54
- }
55
-
56
- export function clearSession(): boolean {
57
- if (!existsSync(sessionPath())) return false;
58
- rmSync(sessionPath());
59
- return true;
60
- }
61
-
62
- /** True if the stored token is past (or within 30s of) its expiry. */
63
- export function isSessionExpired(session: MosaddSession): boolean {
64
- if (!session.expiresAt) return false;
65
- return Date.now() / 1000 >= session.expiresAt - 30;
66
- }
1
+ /**
2
+ * Local session config for the mosadd CLI (`mosadd login`).
3
+ *
4
+ * Stores the authenticated session at `~/.mosadd/session.json` so the MCP
5
+ * server can pick up credentials without the user pasting an expiring JWT
6
+ * from mosadd.com DevTools into env vars. Env vars still take precedence.
7
+ *
8
+ * The file holds a Supabase session (BYOK): the project URL + anon key (both
9
+ * public, RLS-gated) and the user's access/refresh tokens.
10
+ */
11
+
12
+ import { homedir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { mkdirSync, readFileSync, writeFileSync, rmSync, existsSync, chmodSync } from "node:fs";
15
+
16
+ export interface MosaddSession {
17
+ url: string;
18
+ anonKey: string;
19
+ accessToken: string;
20
+ refreshToken?: string;
21
+ /** Unix seconds when the access token expires. */
22
+ expiresAt?: number;
23
+ email?: string;
24
+ }
25
+
26
+ export function configDir(): string {
27
+ return join(homedir(), ".mosadd");
28
+ }
29
+
30
+ export function sessionPath(): string {
31
+ return join(configDir(), "session.json");
32
+ }
33
+
34
+ export function loadSession(): MosaddSession | null {
35
+ try {
36
+ const raw = readFileSync(sessionPath(), "utf8");
37
+ const s = JSON.parse(raw) as MosaddSession;
38
+ if (s && typeof s.url === "string" && typeof s.anonKey === "string") return s;
39
+ return null;
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ export function saveSession(session: MosaddSession): void {
46
+ mkdirSync(configDir(), { recursive: true });
47
+ writeFileSync(sessionPath(), JSON.stringify(session, null, 2), "utf8");
48
+ // Best-effort tighten perms (no-op on platforms that ignore it).
49
+ try {
50
+ chmodSync(sessionPath(), 0o600);
51
+ } catch {
52
+ /* ignore */
53
+ }
54
+ }
55
+
56
+ export function clearSession(): boolean {
57
+ if (!existsSync(sessionPath())) return false;
58
+ rmSync(sessionPath());
59
+ return true;
60
+ }
61
+
62
+ /** True if the stored token is past (or within 30s of) its expiry. */
63
+ export function isSessionExpired(session: MosaddSession): boolean {
64
+ if (!session.expiresAt) return false;
65
+ return Date.now() / 1000 >= session.expiresAt - 30;
66
+ }
@@ -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
+ }