mindmeld-mcp 0.4.2 → 0.7.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.
@@ -0,0 +1,486 @@
1
+ import { EventEmitter } from "node:events";
2
+ import WebSocket from "ws";
3
+ import { z } from "zod";
4
+ import { sameRelay } from "./config.js";
5
+ import { Payload, PING_INTERVAL_MS } from "./protocol.js";
6
+ import { openDirect, openFrame, sealDirect, sealFrame } from "./teamcrypto.js";
7
+ import { distributeKeys, fetchRoster, fetchTeamKeys, httpBase, rosterDevices, WAITING_FOR_KEY } from "./teamkeys.js";
8
+ import { VERSION } from "./version.js";
9
+ /** Shown when the relay refuses the session token (or it has expired locally). */
10
+ export const SIGN_IN_EXPIRED = "sign-in expired; run /mindmeld:login";
11
+ /**
12
+ * Reconnect delay after `failures` consecutive failures: base * 2^failures, capped at `maxMs`,
13
+ * with +/-20% jitter so a relay outage does not get every client back in lockstep.
14
+ */
15
+ export function backoffDelay(failures, baseMs, maxMs, rand = Math.random()) {
16
+ const exp = Math.min(maxMs, baseMs * 2 ** Math.min(failures, 30));
17
+ return Math.round(exp * (0.8 + 0.4 * rand));
18
+ }
19
+ /** Close codes the relay uses on team sockets. */
20
+ export const TEAM_CLOSE = { removed: 4001, noKey: 4003, noTeam: 4004, tooOld: 4005, signedOut: 4401 };
21
+ /** Shown when the relay refuses this client's version for teams (close code 4005). */
22
+ export const tooOldForTeams = (version) => `mindmeld ${version} is too old for teams; update: claude plugin update mindmeld@mindmeld`;
23
+ const TeamFrameSchema = z.object({ e: z.number().int(), dev: z.string(), d: z.string(), sig: z.string() });
24
+ const DirectFrameSchema = z.object({ dev: z.string(), to: z.string(), s: z.string(), sig: z.string() });
25
+ /**
26
+ * The only payloads broadcast to the team under the team key. Everything else (ask, status, answer,
27
+ * decline, snippet, and any kind added later) is sealed to the recipient device, never broadcast.
28
+ */
29
+ const PRESENCE = new Set(["hello", "bye"]);
30
+ /** Most peer bindings kept (oldest evicted first), so hello spam with random peer ids stays bounded. */
31
+ const MAX_PEERS = 1000;
32
+ /** What the relay sends on a team socket. `c`, `uid` and `login` are routing hints only, never identity. */
33
+ const TeamMessage = z.discriminatedUnion("t", [
34
+ z.object({ t: z.literal("server"), latest: z.string(), minimum: z.string(), epoch: z.number() }),
35
+ z.object({ t: z.literal("joined"), c: z.string(), uid: z.number().int(), login: z.string() }),
36
+ z.object({ t: z.literal("left"), c: z.string(), uid: z.number().int(), login: z.string() }),
37
+ z.object({ t: z.literal("roster") }),
38
+ z.object({ t: z.literal("msg"), f: TeamFrameSchema, c: z.string(), uid: z.number().int(), login: z.string() }),
39
+ z.object({ t: z.literal("dm"), f: DirectFrameSchema, c: z.string(), uid: z.number().int(), login: z.string() }),
40
+ ]);
41
+ const RETRY_BASE_MS = 2000;
42
+ const RETRY_MAX_MS = 60_000;
43
+ const CLOSE_TIMEOUT_MS = 1000;
44
+ /**
45
+ * A device without a key waits for a teammate to wrap one for it. On a normal onboarding the
46
+ * teammate is online and delivers within moments, so start short and back off to 30s.
47
+ */
48
+ const NO_KEY_RETRY_BASE_MS = 1000;
49
+ const NO_KEY_RETRY_MAX_MS = 30_000;
50
+ /** Frames for an epoch this client has no key for yet, held until the next key refresh. */
51
+ const MAX_HELD = 64;
52
+ /** Key-distribution passes per refresh (each write is followed by a refetch). */
53
+ const MAX_DISTRIBUTE_PASSES = 3;
54
+ /**
55
+ * The team transport: one socket at /v1/teams/:id/ws?v=<version> (bearer token in the Authorization header).
56
+ * Presence (hello, bye) is sealed with the current epoch's team key, signed by this device and broadcast
57
+ * to the team; incoming broadcasts are verified with `openFrame` against the roster. Everything between
58
+ * two people (ask, status, answer, decline, snippet) is sealed to the recipient device with `sealDirect`
59
+ * and sent as { t:"dm", to, f }, which the relay delivers only to that device; incoming ones are
60
+ * verified with `openDirect`. A directed payload names its recipient by peer id (resolved to the device
61
+ * that sent that peer's first hello) or by device (a reply to an asker); if it cannot be resolved
62
+ * nothing is sent and `send` returns false. Either way the sender (GitHub id, and login for display)
63
+ * comes from the signature.
64
+ * The roster and verified keys are fetched on start, on reconnect, and whenever the relay says the
65
+ * roster changed. Each fetch is followed by `distributeKeys` (see `ensureTeamKeys`): an admin creates
66
+ * the first key, a device holding the key delivers it to roster devices that lack one, and a device
67
+ * without one reports WAITING_FOR_KEY as its status until a teammate delivers it (picked up on the
68
+ * no-key retry). Emits the Channel events plus "closed" (code, reason) and "status" (reason | null).
69
+ */
70
+ export class TeamChannel extends EventEmitter {
71
+ opts;
72
+ ws = null;
73
+ pingTimer = null;
74
+ serverInfo = null;
75
+ admitted = false;
76
+ stopped = false;
77
+ roster = new Map();
78
+ /**
79
+ * Peer id -> the verified sender (uid, device) and connection of its hello. A hello or bye for a
80
+ * bound peer id from another GitHub id is dropped; the binding goes on that peer's bye, on its
81
+ * connection's "left", or when evicted (oldest first, beyond MAX_PEERS).
82
+ */
83
+ peerDevice = new Map();
84
+ keys = new Map();
85
+ currentEpoch = 0;
86
+ /** Relay connection id -> the verified GitHub id of its first frame. */
87
+ cidUid = new Map();
88
+ /** Frames held until the next refresh: a broadcast for an unknown epoch, or a dm from a device not in the roster yet. */
89
+ held = [];
90
+ refreshing = null;
91
+ refreshAgain = false;
92
+ keyProblems = [];
93
+ /** The last refresh found no usable key for the current epoch. */
94
+ waiting = false;
95
+ reason = null;
96
+ retryTimer = null;
97
+ /** Consecutive failed connection attempts; reset once the relay admits this device. */
98
+ failures = 0;
99
+ /** Consecutive "no team key yet" closes; reset once the relay admits this device. */
100
+ noKeyAttempts = 0;
101
+ /** Set when the relay answered 401 to the WebSocket upgrade. */
102
+ authRefused = false;
103
+ /** `terminal` ran: its "closed" event was the last one. */
104
+ finished = false;
105
+ /** Encrypted frames this client has sent; lets tests check that idle sessions stay quiet. */
106
+ framesSent = 0;
107
+ /** Frames from the relay dropped for failing a check (bad signature, wrong recipient, stamp mismatch, wrong kind...). */
108
+ framesDropped = 0;
109
+ constructor(opts) {
110
+ super();
111
+ this.opts = opts;
112
+ }
113
+ start() {
114
+ this.stopped = false;
115
+ this.finished = false;
116
+ this.failures = 0;
117
+ this.noKeyAttempts = 0;
118
+ void this.connect();
119
+ }
120
+ async stop() {
121
+ this.stopped = true;
122
+ if (this.retryTimer)
123
+ clearTimeout(this.retryTimer);
124
+ this.retryTimer = null;
125
+ if (this.pingTimer)
126
+ clearInterval(this.pingTimer);
127
+ this.ws?.close();
128
+ }
129
+ /** Try again after `delayMs`, or else the connection-failure backoff. Emits "retry" (delayMs). */
130
+ scheduleRetry(delayMs) {
131
+ if (this.stopped)
132
+ return;
133
+ const { baseMs, maxMs } = this.opts.retry ?? { baseMs: RETRY_BASE_MS, maxMs: RETRY_MAX_MS };
134
+ const delay = delayMs ?? backoffDelay(this.failures++, baseMs, maxMs);
135
+ if (this.retryTimer)
136
+ clearTimeout(this.retryTimer);
137
+ this.retryTimer = setTimeout(() => {
138
+ this.retryTimer = null;
139
+ void this.connect();
140
+ }, delay);
141
+ this.retryTimer.unref?.();
142
+ this.emit("retry", delay);
143
+ }
144
+ /** Stop for good: retrying cannot help (signed out, removed, no such team). */
145
+ terminal(code, reason) {
146
+ if (this.finished)
147
+ return;
148
+ this.finished = true;
149
+ this.stopped = true;
150
+ if (this.retryTimer)
151
+ clearTimeout(this.retryTimer);
152
+ this.retryTimer = null;
153
+ this.setReason(reason);
154
+ if (reason === SIGN_IN_EXPIRED)
155
+ this.emit("auth-expired", reason);
156
+ this.emit("closed", code, reason);
157
+ const ws = this.ws;
158
+ if (ws && ws.readyState !== WebSocket.CLOSED)
159
+ ws.close();
160
+ }
161
+ /** A roster/keys fetch failed: 401/403/404 end the channel; anything else is reported. */
162
+ refreshFailed(e) {
163
+ this.emit("relay-error", e);
164
+ const status = e.status;
165
+ if (status === 401)
166
+ this.terminal(TEAM_CLOSE.signedOut, SIGN_IN_EXPIRED);
167
+ else if (status === 403)
168
+ this.terminal(TEAM_CLOSE.removed, "removed from team");
169
+ else if (status === 404)
170
+ this.terminal(TEAM_CLOSE.noTeam, "no such team");
171
+ else
172
+ return false;
173
+ return true;
174
+ }
175
+ /** Admitted by the relay (socket open and the relay's "server" hello received). */
176
+ get connected() {
177
+ return this.admitted && this.ws?.readyState === WebSocket.OPEN;
178
+ }
179
+ get server() {
180
+ return this.serverInfo;
181
+ }
182
+ /** Current team epoch as far as this client knows. */
183
+ get epoch() {
184
+ return this.currentEpoch;
185
+ }
186
+ /**
187
+ * Why the channel is not working normally, for the status line: WAITING_FOR_KEY, "no team key
188
+ * yet", "removed from team", or a key verification failure such as "team key for epoch 3 failed
189
+ * verification (...)". Null when all is well.
190
+ */
191
+ get status() {
192
+ const problem = this.keyProblems.find((p) => p.includes(`epoch ${this.currentEpoch} `));
193
+ return this.reason ?? problem ?? (this.waiting && !this.admitted ? WAITING_FOR_KEY : null);
194
+ }
195
+ /**
196
+ * Presence (hello, bye) is broadcast under the team key. Any other payload must name its recipient
197
+ * (`to.device`, else the device behind `to.peer`) and goes only to that device; false if it names
198
+ * none or that device is not on the roster (nothing is sent, and never as a broadcast).
199
+ */
200
+ send(p, to) {
201
+ if (PRESENCE.has(p.type)) {
202
+ const key = this.keys.get(this.currentEpoch);
203
+ if (!this.connected || !key)
204
+ return true;
205
+ const f = sealFrame(this.currentEpoch, key, this.opts.id, JSON.stringify(p));
206
+ this.ws.send(JSON.stringify({ t: "msg", f }));
207
+ this.framesSent++;
208
+ return true;
209
+ }
210
+ const deviceId = to?.device ?? (to?.peer !== undefined ? this.peerDevice.get(to.peer)?.device : undefined);
211
+ const recipient = deviceId !== undefined ? this.roster.get(deviceId) : undefined;
212
+ if (deviceId === undefined || !recipient)
213
+ return false;
214
+ if (!this.connected)
215
+ return true;
216
+ const f = sealDirect(this.opts.teamId, this.opts.id, { deviceId, boxPub: recipient.boxPub }, JSON.stringify(p));
217
+ this.ws.send(JSON.stringify({ t: "dm", to: deviceId, f }));
218
+ this.framesSent++;
219
+ return true;
220
+ }
221
+ setReason(r) {
222
+ if (r === this.reason)
223
+ return;
224
+ this.reason = r;
225
+ this.emit("status", this.status);
226
+ }
227
+ /** Fetch the roster and verified keys; concurrent calls share one fetch, plus one rerun if asked again. */
228
+ refresh() {
229
+ if (this.refreshing) {
230
+ this.refreshAgain = true;
231
+ return this.refreshing;
232
+ }
233
+ this.refreshing = (async () => {
234
+ try {
235
+ let passes = 0;
236
+ do {
237
+ this.refreshAgain = false;
238
+ const { relayHttp, teamId, session, id } = this.opts;
239
+ const roster = await fetchRoster(relayHttp, teamId, session);
240
+ const k = await fetchTeamKeys(relayHttp, teamId, session, id, roster);
241
+ if (passes++ < MAX_DISTRIBUTE_PASSES) {
242
+ try {
243
+ if ((await distributeKeys({ relayHttp, teamId, session, id }, roster, k)).wrote)
244
+ this.refreshAgain = true;
245
+ }
246
+ catch (e) {
247
+ const s = e.status;
248
+ if (s === 401 || s === 403 || s === 404)
249
+ throw e;
250
+ // A race (400/409) or a relay hiccup: report it and look again; the channel still works.
251
+ this.emit("relay-error", e);
252
+ this.refreshAgain = true;
253
+ }
254
+ }
255
+ this.roster = rosterDevices(roster);
256
+ this.keys = k.keys;
257
+ this.currentEpoch = Math.max(k.epoch, roster.epoch);
258
+ this.waiting = !this.keys.has(this.currentEpoch) && !k.problems.some((p) => p.includes(`epoch ${this.currentEpoch} `));
259
+ for (const p of k.problems)
260
+ if (!this.keyProblems.includes(p))
261
+ this.emit("key-problem", p);
262
+ this.keyProblems = k.problems;
263
+ this.emit("status", this.status);
264
+ } while (this.refreshAgain);
265
+ }
266
+ finally {
267
+ this.refreshing = null;
268
+ }
269
+ const held = this.held.splice(0);
270
+ for (const h of held) {
271
+ if (h.t === "msg")
272
+ this.receive(h.f, h.c, h.uid, false);
273
+ else
274
+ this.receiveDirect(h.f, h.c, h.uid, false);
275
+ }
276
+ })();
277
+ return this.refreshing;
278
+ }
279
+ async connect() {
280
+ if (this.stopped)
281
+ return;
282
+ // The token only ever goes to the relay that issued it.
283
+ if (!this.opts.session.token || this.opts.session.expiresAt <= Date.now() / 1000 || !sameRelay(this.opts.relayHttp, this.opts.session.relay ?? "")) {
284
+ return this.terminal(TEAM_CLOSE.signedOut, SIGN_IN_EXPIRED);
285
+ }
286
+ try {
287
+ await this.refresh();
288
+ }
289
+ catch (e) {
290
+ if (!this.refreshFailed(e))
291
+ this.scheduleRetry();
292
+ return;
293
+ }
294
+ if (this.stopped)
295
+ return;
296
+ if (this.admitted) {
297
+ // A previous socket is still winding down; its close handler will ignore it from here on.
298
+ this.admitted = false;
299
+ this.emit("disconnected");
300
+ }
301
+ this.authRefused = false;
302
+ const v = encodeURIComponent(this.opts.version ?? VERSION);
303
+ const url = `${httpBase(this.opts.relayHttp).replace(/^http/, "ws")}/v1/teams/${this.opts.teamId}/ws?v=${v}`;
304
+ // closeTimeout: once close frames are exchanged, do not wait 30s for a peer that keeps TCP half open
305
+ // (seen with relay-initiated closes of hibernated sockets); "closed" must arrive promptly.
306
+ const ws = new WebSocket(url, { headers: { authorization: `Bearer ${this.opts.session.token}` }, closeTimeout: CLOSE_TIMEOUT_MS });
307
+ this.ws = ws;
308
+ ws.on("open", () => {
309
+ let alive = true;
310
+ ws.on("pong", () => (alive = true));
311
+ if (this.pingTimer)
312
+ clearInterval(this.pingTimer);
313
+ this.pingTimer = setInterval(() => {
314
+ if (!alive)
315
+ return ws.terminate(); // half-open connection: reconnect
316
+ alive = false;
317
+ ws.ping();
318
+ }, PING_INTERVAL_MS);
319
+ this.pingTimer.unref?.();
320
+ });
321
+ ws.on("message", (data) => this.handleMessage(data.toString()));
322
+ ws.on("error", (e) => {
323
+ // ws reports a refused upgrade as "Unexpected server response: <status>".
324
+ if (/Unexpected server response: 401\b/.test(e.message))
325
+ this.authRefused = true;
326
+ this.emit("relay-error", e);
327
+ });
328
+ ws.on("close", (code, buf) => {
329
+ if (ws !== this.ws)
330
+ return; // a stale socket from before a restart
331
+ if (this.pingTimer)
332
+ clearInterval(this.pingTimer);
333
+ const wasAdmitted = this.admitted;
334
+ this.admitted = false;
335
+ this.cidUid.clear();
336
+ const reason = buf.toString();
337
+ // Always reported once admitted, even when stopped, so the daemon can drop its peers.
338
+ if (wasAdmitted)
339
+ this.emit("disconnected");
340
+ if (this.stopped) {
341
+ if (!this.finished)
342
+ this.emit("closed", code, reason);
343
+ return;
344
+ }
345
+ if (this.authRefused)
346
+ return this.terminal(TEAM_CLOSE.signedOut, SIGN_IN_EXPIRED);
347
+ if (code === TEAM_CLOSE.removed)
348
+ return this.terminal(code, "removed from team");
349
+ if (code === TEAM_CLOSE.noTeam)
350
+ return this.terminal(code, "no such team");
351
+ if (code === TEAM_CLOSE.tooOld)
352
+ return this.terminal(code, tooOldForTeams(this.opts.version ?? VERSION));
353
+ this.emit("closed", code, reason);
354
+ if (code === TEAM_CLOSE.noKey) {
355
+ this.setReason(this.waiting ? WAITING_FOR_KEY : "no team key yet");
356
+ return this.scheduleRetry(backoffDelay(this.noKeyAttempts++, this.opts.noKeyRetryMs ?? NO_KEY_RETRY_BASE_MS, NO_KEY_RETRY_MAX_MS));
357
+ }
358
+ this.scheduleRetry();
359
+ });
360
+ }
361
+ /** One message from the relay. */
362
+ handleMessage(raw) {
363
+ let json;
364
+ try {
365
+ json = JSON.parse(raw);
366
+ }
367
+ catch {
368
+ return;
369
+ }
370
+ const m = TeamMessage.safeParse(json);
371
+ if (!m.success)
372
+ return;
373
+ const msg = m.data;
374
+ switch (msg.t) {
375
+ case "server":
376
+ this.serverInfo = { t: "server", latest: msg.latest, minimum: msg.minimum };
377
+ if (msg.epoch !== this.currentEpoch)
378
+ void this.refresh().catch((e) => this.refreshFailed(e));
379
+ if (!this.admitted) {
380
+ this.admitted = true;
381
+ this.failures = 0;
382
+ this.noKeyAttempts = 0;
383
+ this.setReason(null);
384
+ this.emit("connected");
385
+ }
386
+ this.emit("server", this.serverInfo);
387
+ break;
388
+ case "joined":
389
+ this.emit("joined", msg.c);
390
+ break;
391
+ case "left":
392
+ this.cidUid.delete(msg.c);
393
+ for (const [peer, b] of this.peerDevice)
394
+ if (b.cid === msg.c)
395
+ this.peerDevice.delete(peer);
396
+ this.emit("left", msg.c);
397
+ break;
398
+ case "roster":
399
+ void this.refresh().catch((e) => this.refreshFailed(e));
400
+ break;
401
+ case "msg":
402
+ this.receive(msg.f, msg.c, msg.uid, true);
403
+ break;
404
+ case "dm":
405
+ this.receiveDirect(msg.f, msg.c, msg.uid, true);
406
+ break;
407
+ }
408
+ }
409
+ /**
410
+ * Verify and deliver one broadcast (team-key) frame. The sender is the GitHub id the signature proves (via the roster);
411
+ * the relay's uid stamp must agree with it, and a connection id stays bound to the uid of its first
412
+ * frame. The login delivered with it is the roster's, for display.
413
+ */
414
+ receive(f, c, stamped, mayHold) {
415
+ if (mayHold && !this.keys.has(f.e) && f.e > this.currentEpoch) {
416
+ // Probably a rotation this client has not caught up with yet.
417
+ this.hold({ t: "msg", f, c, uid: stamped });
418
+ return;
419
+ }
420
+ const opened = openFrame(f, this.keys, this.roster);
421
+ // A broadcast only ever carries presence; anything else must have been sealed to its recipient.
422
+ if (!opened || !this.deliver(opened, f.dev, c, stamped, false))
423
+ this.framesDropped++;
424
+ }
425
+ /**
426
+ * Verify and deliver one directed frame: addressed to this device, signed by a roster device, opened
427
+ * with this device's key. Same stamp and connection checks as `receive`. A frame from a device the
428
+ * roster does not list yet (it just joined) is held for one refresh.
429
+ */
430
+ receiveDirect(f, c, stamped, mayHold) {
431
+ if (f.to !== this.opts.id.deviceId) {
432
+ this.framesDropped++;
433
+ return;
434
+ }
435
+ if (mayHold && !this.roster.has(f.dev)) {
436
+ this.hold({ t: "dm", f, c, uid: stamped });
437
+ return;
438
+ }
439
+ const opened = openDirect(this.opts.teamId, f, this.opts.id, this.roster);
440
+ if (!opened || !this.deliver(opened, f.dev, c, stamped, true))
441
+ this.framesDropped++;
442
+ }
443
+ hold(h) {
444
+ if (this.held.length < MAX_HELD)
445
+ this.held.push(h);
446
+ void this.refresh().catch((e) => this.refreshFailed(e));
447
+ }
448
+ /** Shared tail of `receive` / `receiveDirect`: identity checks, payload parse, kind check, emit. False if dropped. */
449
+ deliver(opened, device, c, stamped, direct) {
450
+ if (opened.uid !== stamped)
451
+ return false;
452
+ const bound = this.cidUid.get(c);
453
+ if (bound !== undefined && bound !== opened.uid)
454
+ return false;
455
+ let p;
456
+ try {
457
+ const parsed = Payload.safeParse(JSON.parse(opened.payload));
458
+ if (!parsed.success)
459
+ return false;
460
+ p = parsed.data;
461
+ }
462
+ catch {
463
+ return false;
464
+ }
465
+ // Presence only as a broadcast; everything else only sealed to this device.
466
+ if (PRESENCE.has(p.type) === direct)
467
+ return false;
468
+ if (p.type === "hello" || p.type === "bye") {
469
+ const bound = this.peerDevice.get(p.peer);
470
+ if (bound && bound.uid !== opened.uid)
471
+ return false; // another member's peer id
472
+ this.peerDevice.delete(p.peer);
473
+ if (p.type === "hello") {
474
+ this.peerDevice.set(p.peer, { uid: opened.uid, device, cid: c });
475
+ for (const oldest of this.peerDevice.keys()) {
476
+ if (this.peerDevice.size <= MAX_PEERS)
477
+ break;
478
+ this.peerDevice.delete(oldest);
479
+ }
480
+ }
481
+ }
482
+ this.cidUid.set(c, opened.uid);
483
+ this.emit("payload", p, { cid: c, login: opened.login, uid: opened.uid, device });
484
+ return true;
485
+ }
486
+ }
@@ -0,0 +1,130 @@
1
+ import { hkdfSync } from "node:crypto";
2
+ import { ed25519, x25519 } from "@noble/curves/ed25519.js";
3
+ import { hexToBytes } from "@noble/hashes/utils.js";
4
+ import { open, openBytes, seal, sealBytes } from "./crypto.js";
5
+ const SEAL_INFO = "mindmeld/seal/v1";
6
+ const DEVICE_ID = /^[0-9a-f]{16}$/;
7
+ const SIG_HEX = /^[0-9a-f]{128}$/;
8
+ const frameAad = (epoch, dev) => `mindmeld/frame/v1|${epoch}|${dev}`;
9
+ const sigMessage = (epoch, dev, d) => new TextEncoder().encode(`${epoch}|${dev}|${d}`);
10
+ function sealKey(shared, ephPub, boxPub) {
11
+ const salt = Buffer.concat([ephPub, boxPub]);
12
+ return Buffer.from(hkdfSync("sha256", shared, salt, SEAL_INFO, 32));
13
+ }
14
+ /**
15
+ * Seal bytes to one device's X25519 key (anonymous sender).
16
+ * Fresh ephemeral X25519 keypair; shared = X25519(ephPriv, boxPub);
17
+ * key = HKDF-SHA256(ikm = shared, salt = ephPub(32) ‖ boxPub(32), info = utf8 "mindmeld/seal/v1", L = 32);
18
+ * AES-256-GCM with a random 96-bit nonce and AAD = `aad` when given; without `aad` no AAD is set at all
19
+ * (byte-identical to before `aad` existed; team key wraps use it this way). Output base64(ephPub ‖ nonce ‖ ct ‖ tag).
20
+ * The key is single-use (fresh ephemeral per call), so nonce reuse cannot occur.
21
+ */
22
+ export function sealToDevice(boxPub, plaintext, aad) {
23
+ const recipient = hexToBytes(boxPub);
24
+ const ephPriv = x25519.utils.randomSecretKey();
25
+ const ephPub = x25519.getPublicKey(ephPriv);
26
+ const key = sealKey(x25519.getSharedSecret(ephPriv, recipient), ephPub, recipient);
27
+ return Buffer.concat([ephPub, sealBytes(key, plaintext, aad)]).toString("base64");
28
+ }
29
+ /**
30
+ * Inverse of `sealToDevice` using this device's boxPriv: shared = X25519(boxPriv, ephPub), same HKDF and AES-256-GCM,
31
+ * with the same `aad` (or none). Returns null on any failure (sealed to another device, other AAD, tampered, malformed); never throws.
32
+ */
33
+ export function openFromDevice(id, sealed, aad) {
34
+ try {
35
+ const buf = Buffer.from(sealed, "base64");
36
+ if (buf.length < 32 + 28)
37
+ return null;
38
+ const ephPub = buf.subarray(0, 32);
39
+ const key = sealKey(x25519.getSharedSecret(hexToBytes(id.boxPriv), ephPub), ephPub, hexToBytes(id.boxPub));
40
+ const out = openBytes(key, buf.subarray(32), aad);
41
+ return out === null ? null : new Uint8Array(out);
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ /**
48
+ * Encrypt and sign a team frame.
49
+ * d = base64(nonce ‖ ct ‖ tag) of AES-256-GCM(teamKey, utf8 payload, random 96-bit nonce,
50
+ * AAD = utf8 "mindmeld/frame/v1|" + epoch + "|" + deviceId);
51
+ * sig = hex Ed25519(signPriv, utf8(epoch + "|" + deviceId + "|" + d)).
52
+ */
53
+ export function sealFrame(epoch, teamKey, id, payload) {
54
+ const d = seal(teamKey, payload, frameAad(epoch, id.deviceId));
55
+ const sig = Buffer.from(ed25519.sign(sigMessage(epoch, id.deviceId, d), hexToBytes(id.signPriv))).toString("hex");
56
+ return { e: epoch, dev: id.deviceId, d, sig };
57
+ }
58
+ /**
59
+ * Verify then decrypt a team frame. `f.dev` must be exactly 16 lowercase hex (checked first). The sender is looked up in `roster` by `f.dev`; the Ed25519 signature over
60
+ * utf8(e + "|" + dev + "|" + d) is checked (strict Ed25519, zip215: false) against that entry's signPub BEFORE decryption; then `d` is opened with
61
+ * keys.get(e) and AAD "mindmeld/frame/v1|" + e + "|" + dev. Returns the roster uid, login and payload, or null on any
62
+ * failure (unknown device, bad signature, unknown epoch, decrypt failure, malformed input); never throws.
63
+ */
64
+ export function openFrame(f, keys, roster) {
65
+ try {
66
+ if (!f || typeof f.dev !== "string" || !DEVICE_ID.test(f.dev))
67
+ return null;
68
+ if (typeof f.e !== "number" || !Number.isSafeInteger(f.e) || typeof f.d !== "string" || typeof f.sig !== "string" || !SIG_HEX.test(f.sig))
69
+ return null;
70
+ const sender = roster.get(f.dev);
71
+ if (!sender)
72
+ return null;
73
+ if (!ed25519.verify(hexToBytes(f.sig), sigMessage(f.e, f.dev, f.d), hexToBytes(sender.signPub), { zip215: false }))
74
+ return null;
75
+ const key = keys.get(f.e);
76
+ if (!key)
77
+ return null;
78
+ const payload = open(key, f.d, frameAad(f.e, f.dev));
79
+ return payload === null ? null : { uid: sender.uid, login: sender.login, payload };
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ const directSigMessage = (teamId, dev, to, s) => new TextEncoder().encode(`mm-dm|v1|${teamId}|${dev}|${to}|${s}`);
86
+ const directAad = (teamId, dev, to) => new TextEncoder().encode(`mm-dm|v1|${teamId}|${dev}|${to}`);
87
+ /**
88
+ * Seal and sign a payload for one recipient device (questions, answers, statuses, declines, snippets).
89
+ * s = sealToDevice(to.boxPub, utf8 payload, aad = utf8("mm-dm|v1|" + teamId + "|" + id.deviceId + "|" + to.deviceId)),
90
+ * the construction documented on `sealToDevice` (fresh ephemeral X25519, HKDF-SHA256 "mindmeld/seal/v1", AES-256-GCM);
91
+ * sig = hex Ed25519(signPriv, utf8("mm-dm|v1|" + teamId + "|" + id.deviceId + "|" + to.deviceId + "|" + s)).
92
+ * Only the recipient's boxPriv opens `s`. The signature and the AAD both bind the sender device, the recipient
93
+ * device and the team, so `s` cannot be re-signed and passed off as another device's message.
94
+ */
95
+ export function sealDirect(teamId, id, to, payload) {
96
+ const s = sealToDevice(to.boxPub, new TextEncoder().encode(payload), directAad(teamId, id.deviceId, to.deviceId));
97
+ const sig = Buffer.from(ed25519.sign(directSigMessage(teamId, id.deviceId, to.deviceId, s), hexToBytes(id.signPriv))).toString("hex");
98
+ return { dev: id.deviceId, to: to.deviceId, s, sig };
99
+ }
100
+ /**
101
+ * Verify then open a direct frame addressed to this device. `f.dev` and `f.to` must be exactly 16
102
+ * lowercase hex (checked first) and `f.to` must be `id.deviceId`. The sender is looked up in `roster`
103
+ * by `f.dev`; the Ed25519 signature over utf8("mm-dm|v1|" + teamId + "|" + dev + "|" + to + "|" + s)
104
+ * is checked (strict Ed25519, zip215: false) against that entry's signPub BEFORE opening; then `s` is
105
+ * opened with `openFromDevice` and AAD utf8("mm-dm|v1|" + teamId + "|" + dev + "|" + to), and decoded as strict UTF-8. Returns the roster uid, login and payload,
106
+ * or null on any failure (wrong recipient, unknown device, bad signature, decrypt failure, malformed
107
+ * input); never throws.
108
+ */
109
+ export function openDirect(teamId, f, id, roster) {
110
+ try {
111
+ if (!f || typeof f !== "object" || typeof f.dev !== "string" || !DEVICE_ID.test(f.dev) || typeof f.to !== "string" || !DEVICE_ID.test(f.to))
112
+ return null;
113
+ if (typeof f.s !== "string" || typeof f.sig !== "string" || !SIG_HEX.test(f.sig))
114
+ return null;
115
+ if (f.to !== id.deviceId)
116
+ return null;
117
+ const sender = roster.get(f.dev);
118
+ if (!sender)
119
+ return null;
120
+ if (!ed25519.verify(hexToBytes(f.sig), directSigMessage(teamId, f.dev, f.to, f.s), hexToBytes(sender.signPub), { zip215: false }))
121
+ return null;
122
+ const plain = openFromDevice(id, f.s, directAad(teamId, f.dev, f.to));
123
+ if (plain === null)
124
+ return null;
125
+ return { uid: sender.uid, login: sender.login, payload: new TextDecoder("utf-8", { fatal: true }).decode(plain) };
126
+ }
127
+ catch {
128
+ return null;
129
+ }
130
+ }