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

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