mindmeld-mcp 0.4.2 → 0.6.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.
- package/README.md +25 -2
- package/dist/answerer.js +52 -10
- package/dist/auth/config.js +7 -0
- package/dist/auth/github.js +60 -0
- package/dist/auth/session.js +101 -0
- package/dist/channel.js +115 -0
- package/dist/cli.js +167 -11
- package/dist/config.js +55 -3
- package/dist/crypto.js +24 -8
- package/dist/daemon.js +151 -76
- package/dist/identity.js +58 -0
- package/dist/mcp.js +116 -32
- package/dist/mcpteam.js +304 -0
- package/dist/protocol.js +26 -5
- package/dist/relay.js +82 -11
- package/dist/teamapi.js +174 -0
- package/dist/teamchannel.js +385 -0
- package/dist/teamcrypto.js +83 -0
- package/dist/teamkeys.js +245 -0
- package/dist/version.js +13 -0
- package/package.json +3 -2
|
@@ -0,0 +1,385 @@
|
|
|
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 { openFrame, sealFrame } from "./teamcrypto.js";
|
|
7
|
+
import { distributeKeys, fetchRoster, fetchTeamKeys, httpBase, rosterDevices, WAITING_FOR_KEY } from "./teamkeys.js";
|
|
8
|
+
/** Shown when the relay refuses the session token (or it has expired locally). */
|
|
9
|
+
export const SIGN_IN_EXPIRED = "sign-in expired; run /mindmeld:login";
|
|
10
|
+
/**
|
|
11
|
+
* Reconnect delay after `failures` consecutive failures: base * 2^failures, capped at `maxMs`,
|
|
12
|
+
* with +/-20% jitter so a relay outage does not get every client back in lockstep.
|
|
13
|
+
*/
|
|
14
|
+
export function backoffDelay(failures, baseMs, maxMs, rand = Math.random()) {
|
|
15
|
+
const exp = Math.min(maxMs, baseMs * 2 ** Math.min(failures, 30));
|
|
16
|
+
return Math.round(exp * (0.8 + 0.4 * rand));
|
|
17
|
+
}
|
|
18
|
+
/** Close codes the relay uses on team sockets. */
|
|
19
|
+
export const TEAM_CLOSE = { removed: 4001, noKey: 4003, noTeam: 4004, signedOut: 4401 };
|
|
20
|
+
const TeamFrameSchema = z.object({ e: z.number().int(), dev: z.string(), d: z.string(), sig: z.string() });
|
|
21
|
+
/** What the relay sends on a team socket. `c`, `uid` and `login` are routing hints only, never identity. */
|
|
22
|
+
const TeamMessage = z.discriminatedUnion("t", [
|
|
23
|
+
z.object({ t: z.literal("server"), latest: z.string(), minimum: z.string(), epoch: z.number() }),
|
|
24
|
+
z.object({ t: z.literal("joined"), c: z.string(), uid: z.number().int(), login: z.string() }),
|
|
25
|
+
z.object({ t: z.literal("left"), c: z.string(), uid: z.number().int(), login: z.string() }),
|
|
26
|
+
z.object({ t: z.literal("roster") }),
|
|
27
|
+
z.object({ t: z.literal("msg"), f: TeamFrameSchema, c: z.string(), uid: z.number().int(), login: z.string() }),
|
|
28
|
+
]);
|
|
29
|
+
const RETRY_BASE_MS = 2000;
|
|
30
|
+
const RETRY_MAX_MS = 60_000;
|
|
31
|
+
const CLOSE_TIMEOUT_MS = 1000;
|
|
32
|
+
/**
|
|
33
|
+
* A device without a key waits for a teammate to wrap one for it. On a normal onboarding the
|
|
34
|
+
* teammate is online and delivers within moments, so start short and back off to 30s.
|
|
35
|
+
*/
|
|
36
|
+
const NO_KEY_RETRY_BASE_MS = 1000;
|
|
37
|
+
const NO_KEY_RETRY_MAX_MS = 30_000;
|
|
38
|
+
/** Frames for an epoch this client has no key for yet, held until the next key refresh. */
|
|
39
|
+
const MAX_HELD = 64;
|
|
40
|
+
/** Key-distribution passes per refresh (each write is followed by a refetch). */
|
|
41
|
+
const MAX_DISTRIBUTE_PASSES = 3;
|
|
42
|
+
/**
|
|
43
|
+
* The team transport: one socket at /v1/teams/:id/ws (bearer token in the Authorization header).
|
|
44
|
+
* Every frame is sealed with the current epoch's team key and signed by this device; incoming frames
|
|
45
|
+
* are verified with `openFrame` against the roster, and the sender (GitHub id, and login for display) comes from that signature.
|
|
46
|
+
* The roster and verified keys are fetched on start, on reconnect, and whenever the relay says the
|
|
47
|
+
* roster changed. Each fetch is followed by `distributeKeys` (see `ensureTeamKeys`): an admin creates
|
|
48
|
+
* the first key, a device holding the key delivers it to roster devices that lack one, and a device
|
|
49
|
+
* without one reports WAITING_FOR_KEY as its status until a teammate delivers it (picked up on the
|
|
50
|
+
* no-key retry). Emits the Channel events plus "closed" (code, reason) and "status" (reason | null).
|
|
51
|
+
*/
|
|
52
|
+
export class TeamChannel extends EventEmitter {
|
|
53
|
+
opts;
|
|
54
|
+
ws = null;
|
|
55
|
+
pingTimer = null;
|
|
56
|
+
serverInfo = null;
|
|
57
|
+
admitted = false;
|
|
58
|
+
stopped = false;
|
|
59
|
+
roster = new Map();
|
|
60
|
+
keys = new Map();
|
|
61
|
+
currentEpoch = 0;
|
|
62
|
+
/** Relay connection id -> the verified GitHub id of its first frame. */
|
|
63
|
+
cidUid = new Map();
|
|
64
|
+
held = [];
|
|
65
|
+
refreshing = null;
|
|
66
|
+
refreshAgain = false;
|
|
67
|
+
keyProblems = [];
|
|
68
|
+
/** The last refresh found no usable key for the current epoch. */
|
|
69
|
+
waiting = false;
|
|
70
|
+
reason = null;
|
|
71
|
+
retryTimer = null;
|
|
72
|
+
/** Consecutive failed connection attempts; reset once the relay admits this device. */
|
|
73
|
+
failures = 0;
|
|
74
|
+
/** Consecutive "no team key yet" closes; reset once the relay admits this device. */
|
|
75
|
+
noKeyAttempts = 0;
|
|
76
|
+
/** Set when the relay answered 401 to the WebSocket upgrade. */
|
|
77
|
+
authRefused = false;
|
|
78
|
+
/** `terminal` ran: its "closed" event was the last one. */
|
|
79
|
+
finished = false;
|
|
80
|
+
/** Encrypted frames this client has sent; lets tests check that idle sessions stay quiet. */
|
|
81
|
+
framesSent = 0;
|
|
82
|
+
constructor(opts) {
|
|
83
|
+
super();
|
|
84
|
+
this.opts = opts;
|
|
85
|
+
}
|
|
86
|
+
start() {
|
|
87
|
+
this.stopped = false;
|
|
88
|
+
this.finished = false;
|
|
89
|
+
this.failures = 0;
|
|
90
|
+
this.noKeyAttempts = 0;
|
|
91
|
+
void this.connect();
|
|
92
|
+
}
|
|
93
|
+
async stop() {
|
|
94
|
+
this.stopped = true;
|
|
95
|
+
if (this.retryTimer)
|
|
96
|
+
clearTimeout(this.retryTimer);
|
|
97
|
+
this.retryTimer = null;
|
|
98
|
+
if (this.pingTimer)
|
|
99
|
+
clearInterval(this.pingTimer);
|
|
100
|
+
this.ws?.close();
|
|
101
|
+
}
|
|
102
|
+
/** Try again after `delayMs`, or else the connection-failure backoff. Emits "retry" (delayMs). */
|
|
103
|
+
scheduleRetry(delayMs) {
|
|
104
|
+
if (this.stopped)
|
|
105
|
+
return;
|
|
106
|
+
const { baseMs, maxMs } = this.opts.retry ?? { baseMs: RETRY_BASE_MS, maxMs: RETRY_MAX_MS };
|
|
107
|
+
const delay = delayMs ?? backoffDelay(this.failures++, baseMs, maxMs);
|
|
108
|
+
if (this.retryTimer)
|
|
109
|
+
clearTimeout(this.retryTimer);
|
|
110
|
+
this.retryTimer = setTimeout(() => {
|
|
111
|
+
this.retryTimer = null;
|
|
112
|
+
void this.connect();
|
|
113
|
+
}, delay);
|
|
114
|
+
this.retryTimer.unref?.();
|
|
115
|
+
this.emit("retry", delay);
|
|
116
|
+
}
|
|
117
|
+
/** Stop for good: retrying cannot help (signed out, removed, no such team). */
|
|
118
|
+
terminal(code, reason) {
|
|
119
|
+
if (this.finished)
|
|
120
|
+
return;
|
|
121
|
+
this.finished = true;
|
|
122
|
+
this.stopped = true;
|
|
123
|
+
if (this.retryTimer)
|
|
124
|
+
clearTimeout(this.retryTimer);
|
|
125
|
+
this.retryTimer = null;
|
|
126
|
+
this.setReason(reason);
|
|
127
|
+
if (reason === SIGN_IN_EXPIRED)
|
|
128
|
+
this.emit("auth-expired", reason);
|
|
129
|
+
this.emit("closed", code, reason);
|
|
130
|
+
const ws = this.ws;
|
|
131
|
+
if (ws && ws.readyState !== WebSocket.CLOSED)
|
|
132
|
+
ws.close();
|
|
133
|
+
}
|
|
134
|
+
/** A roster/keys fetch failed: 401/403/404 end the channel; anything else is reported. */
|
|
135
|
+
refreshFailed(e) {
|
|
136
|
+
this.emit("relay-error", e);
|
|
137
|
+
const status = e.status;
|
|
138
|
+
if (status === 401)
|
|
139
|
+
this.terminal(TEAM_CLOSE.signedOut, SIGN_IN_EXPIRED);
|
|
140
|
+
else if (status === 403)
|
|
141
|
+
this.terminal(TEAM_CLOSE.removed, "removed from team");
|
|
142
|
+
else if (status === 404)
|
|
143
|
+
this.terminal(TEAM_CLOSE.noTeam, "no such team");
|
|
144
|
+
else
|
|
145
|
+
return false;
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
/** Admitted by the relay (socket open and the relay's "server" hello received). */
|
|
149
|
+
get connected() {
|
|
150
|
+
return this.admitted && this.ws?.readyState === WebSocket.OPEN;
|
|
151
|
+
}
|
|
152
|
+
get server() {
|
|
153
|
+
return this.serverInfo;
|
|
154
|
+
}
|
|
155
|
+
/** Current team epoch as far as this client knows. */
|
|
156
|
+
get epoch() {
|
|
157
|
+
return this.currentEpoch;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Why the channel is not working normally, for the status line: WAITING_FOR_KEY, "no team key
|
|
161
|
+
* yet", "removed from team", or a key verification failure such as "team key for epoch 3 failed
|
|
162
|
+
* verification (...)". Null when all is well.
|
|
163
|
+
*/
|
|
164
|
+
get status() {
|
|
165
|
+
const problem = this.keyProblems.find((p) => p.includes(`epoch ${this.currentEpoch} `));
|
|
166
|
+
return this.reason ?? problem ?? (this.waiting && !this.admitted ? WAITING_FOR_KEY : null);
|
|
167
|
+
}
|
|
168
|
+
send(p) {
|
|
169
|
+
const key = this.keys.get(this.currentEpoch);
|
|
170
|
+
if (!this.connected || !key)
|
|
171
|
+
return;
|
|
172
|
+
const f = sealFrame(this.currentEpoch, key, this.opts.id, JSON.stringify(p));
|
|
173
|
+
this.ws.send(JSON.stringify({ t: "msg", f }));
|
|
174
|
+
this.framesSent++;
|
|
175
|
+
}
|
|
176
|
+
setReason(r) {
|
|
177
|
+
if (r === this.reason)
|
|
178
|
+
return;
|
|
179
|
+
this.reason = r;
|
|
180
|
+
this.emit("status", this.status);
|
|
181
|
+
}
|
|
182
|
+
/** Fetch the roster and verified keys; concurrent calls share one fetch, plus one rerun if asked again. */
|
|
183
|
+
refresh() {
|
|
184
|
+
if (this.refreshing) {
|
|
185
|
+
this.refreshAgain = true;
|
|
186
|
+
return this.refreshing;
|
|
187
|
+
}
|
|
188
|
+
this.refreshing = (async () => {
|
|
189
|
+
try {
|
|
190
|
+
let passes = 0;
|
|
191
|
+
do {
|
|
192
|
+
this.refreshAgain = false;
|
|
193
|
+
const { relayHttp, teamId, session, id } = this.opts;
|
|
194
|
+
const roster = await fetchRoster(relayHttp, teamId, session);
|
|
195
|
+
const k = await fetchTeamKeys(relayHttp, teamId, session, id, roster);
|
|
196
|
+
if (passes++ < MAX_DISTRIBUTE_PASSES) {
|
|
197
|
+
try {
|
|
198
|
+
if ((await distributeKeys({ relayHttp, teamId, session, id }, roster, k)).wrote)
|
|
199
|
+
this.refreshAgain = true;
|
|
200
|
+
}
|
|
201
|
+
catch (e) {
|
|
202
|
+
const s = e.status;
|
|
203
|
+
if (s === 401 || s === 403 || s === 404)
|
|
204
|
+
throw e;
|
|
205
|
+
// A race (400/409) or a relay hiccup: report it and look again; the channel still works.
|
|
206
|
+
this.emit("relay-error", e);
|
|
207
|
+
this.refreshAgain = true;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
this.roster = rosterDevices(roster);
|
|
211
|
+
this.keys = k.keys;
|
|
212
|
+
this.currentEpoch = Math.max(k.epoch, roster.epoch);
|
|
213
|
+
this.waiting = !this.keys.has(this.currentEpoch) && !k.problems.some((p) => p.includes(`epoch ${this.currentEpoch} `));
|
|
214
|
+
for (const p of k.problems)
|
|
215
|
+
if (!this.keyProblems.includes(p))
|
|
216
|
+
this.emit("key-problem", p);
|
|
217
|
+
this.keyProblems = k.problems;
|
|
218
|
+
this.emit("status", this.status);
|
|
219
|
+
} while (this.refreshAgain);
|
|
220
|
+
}
|
|
221
|
+
finally {
|
|
222
|
+
this.refreshing = null;
|
|
223
|
+
}
|
|
224
|
+
const held = this.held.splice(0);
|
|
225
|
+
for (const h of held)
|
|
226
|
+
this.receive(h.f, h.c, h.uid, false);
|
|
227
|
+
})();
|
|
228
|
+
return this.refreshing;
|
|
229
|
+
}
|
|
230
|
+
async connect() {
|
|
231
|
+
if (this.stopped)
|
|
232
|
+
return;
|
|
233
|
+
// The token only ever goes to the relay that issued it.
|
|
234
|
+
if (!this.opts.session.token || this.opts.session.expiresAt <= Date.now() / 1000 || !sameRelay(this.opts.relayHttp, this.opts.session.relay ?? "")) {
|
|
235
|
+
return this.terminal(TEAM_CLOSE.signedOut, SIGN_IN_EXPIRED);
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
await this.refresh();
|
|
239
|
+
}
|
|
240
|
+
catch (e) {
|
|
241
|
+
if (!this.refreshFailed(e))
|
|
242
|
+
this.scheduleRetry();
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (this.stopped)
|
|
246
|
+
return;
|
|
247
|
+
if (this.admitted) {
|
|
248
|
+
// A previous socket is still winding down; its close handler will ignore it from here on.
|
|
249
|
+
this.admitted = false;
|
|
250
|
+
this.emit("disconnected");
|
|
251
|
+
}
|
|
252
|
+
this.authRefused = false;
|
|
253
|
+
const url = `${httpBase(this.opts.relayHttp).replace(/^http/, "ws")}/v1/teams/${this.opts.teamId}/ws`;
|
|
254
|
+
// closeTimeout: once close frames are exchanged, do not wait 30s for a peer that keeps TCP half open
|
|
255
|
+
// (seen with relay-initiated closes of hibernated sockets); "closed" must arrive promptly.
|
|
256
|
+
const ws = new WebSocket(url, { headers: { authorization: `Bearer ${this.opts.session.token}` }, closeTimeout: CLOSE_TIMEOUT_MS });
|
|
257
|
+
this.ws = ws;
|
|
258
|
+
ws.on("open", () => {
|
|
259
|
+
let alive = true;
|
|
260
|
+
ws.on("pong", () => (alive = true));
|
|
261
|
+
if (this.pingTimer)
|
|
262
|
+
clearInterval(this.pingTimer);
|
|
263
|
+
this.pingTimer = setInterval(() => {
|
|
264
|
+
if (!alive)
|
|
265
|
+
return ws.terminate(); // half-open connection: reconnect
|
|
266
|
+
alive = false;
|
|
267
|
+
ws.ping();
|
|
268
|
+
}, PING_INTERVAL_MS);
|
|
269
|
+
this.pingTimer.unref?.();
|
|
270
|
+
});
|
|
271
|
+
ws.on("message", (data) => this.handleMessage(data.toString()));
|
|
272
|
+
ws.on("error", (e) => {
|
|
273
|
+
// ws reports a refused upgrade as "Unexpected server response: <status>".
|
|
274
|
+
if (/Unexpected server response: 401\b/.test(e.message))
|
|
275
|
+
this.authRefused = true;
|
|
276
|
+
this.emit("relay-error", e);
|
|
277
|
+
});
|
|
278
|
+
ws.on("close", (code, buf) => {
|
|
279
|
+
if (ws !== this.ws)
|
|
280
|
+
return; // a stale socket from before a restart
|
|
281
|
+
if (this.pingTimer)
|
|
282
|
+
clearInterval(this.pingTimer);
|
|
283
|
+
const wasAdmitted = this.admitted;
|
|
284
|
+
this.admitted = false;
|
|
285
|
+
this.cidUid.clear();
|
|
286
|
+
const reason = buf.toString();
|
|
287
|
+
// Always reported once admitted, even when stopped, so the daemon can drop its peers.
|
|
288
|
+
if (wasAdmitted)
|
|
289
|
+
this.emit("disconnected");
|
|
290
|
+
if (this.stopped) {
|
|
291
|
+
if (!this.finished)
|
|
292
|
+
this.emit("closed", code, reason);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (this.authRefused)
|
|
296
|
+
return this.terminal(TEAM_CLOSE.signedOut, SIGN_IN_EXPIRED);
|
|
297
|
+
if (code === TEAM_CLOSE.removed)
|
|
298
|
+
return this.terminal(code, "removed from team");
|
|
299
|
+
if (code === TEAM_CLOSE.noTeam)
|
|
300
|
+
return this.terminal(code, "no such team");
|
|
301
|
+
this.emit("closed", code, reason);
|
|
302
|
+
if (code === TEAM_CLOSE.noKey) {
|
|
303
|
+
this.setReason(this.waiting ? WAITING_FOR_KEY : "no team key yet");
|
|
304
|
+
return this.scheduleRetry(backoffDelay(this.noKeyAttempts++, this.opts.noKeyRetryMs ?? NO_KEY_RETRY_BASE_MS, NO_KEY_RETRY_MAX_MS));
|
|
305
|
+
}
|
|
306
|
+
this.scheduleRetry();
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
/** One message from the relay. */
|
|
310
|
+
handleMessage(raw) {
|
|
311
|
+
let json;
|
|
312
|
+
try {
|
|
313
|
+
json = JSON.parse(raw);
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
const m = TeamMessage.safeParse(json);
|
|
319
|
+
if (!m.success)
|
|
320
|
+
return;
|
|
321
|
+
const msg = m.data;
|
|
322
|
+
switch (msg.t) {
|
|
323
|
+
case "server":
|
|
324
|
+
this.serverInfo = { t: "server", latest: msg.latest, minimum: msg.minimum };
|
|
325
|
+
if (msg.epoch !== this.currentEpoch)
|
|
326
|
+
void this.refresh().catch((e) => this.refreshFailed(e));
|
|
327
|
+
if (!this.admitted) {
|
|
328
|
+
this.admitted = true;
|
|
329
|
+
this.failures = 0;
|
|
330
|
+
this.noKeyAttempts = 0;
|
|
331
|
+
this.setReason(null);
|
|
332
|
+
this.emit("connected");
|
|
333
|
+
}
|
|
334
|
+
this.emit("server", this.serverInfo);
|
|
335
|
+
break;
|
|
336
|
+
case "joined":
|
|
337
|
+
this.emit("joined", msg.c);
|
|
338
|
+
break;
|
|
339
|
+
case "left":
|
|
340
|
+
this.cidUid.delete(msg.c);
|
|
341
|
+
this.emit("left", msg.c);
|
|
342
|
+
break;
|
|
343
|
+
case "roster":
|
|
344
|
+
void this.refresh().catch((e) => this.refreshFailed(e));
|
|
345
|
+
break;
|
|
346
|
+
case "msg":
|
|
347
|
+
this.receive(msg.f, msg.c, msg.uid, true);
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Verify and deliver one frame. The sender is the GitHub id the signature proves (via the roster);
|
|
353
|
+
* the relay's uid stamp must agree with it, and a connection id stays bound to the uid of its first
|
|
354
|
+
* frame. The login delivered with it is the roster's, for display.
|
|
355
|
+
*/
|
|
356
|
+
receive(f, c, stamped, mayHold) {
|
|
357
|
+
if (mayHold && !this.keys.has(f.e) && f.e > this.currentEpoch) {
|
|
358
|
+
// Probably a rotation this client has not caught up with yet.
|
|
359
|
+
if (this.held.length < MAX_HELD)
|
|
360
|
+
this.held.push({ f, c, uid: stamped });
|
|
361
|
+
void this.refresh().catch((e) => this.refreshFailed(e));
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const opened = openFrame(f, this.keys, this.roster);
|
|
365
|
+
if (!opened)
|
|
366
|
+
return;
|
|
367
|
+
if (opened.uid !== stamped)
|
|
368
|
+
return;
|
|
369
|
+
const bound = this.cidUid.get(c);
|
|
370
|
+
if (bound !== undefined && bound !== opened.uid)
|
|
371
|
+
return;
|
|
372
|
+
let p;
|
|
373
|
+
try {
|
|
374
|
+
const parsed = Payload.safeParse(JSON.parse(opened.payload));
|
|
375
|
+
if (!parsed.success)
|
|
376
|
+
return;
|
|
377
|
+
p = parsed.data;
|
|
378
|
+
}
|
|
379
|
+
catch {
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
this.cidUid.set(c, opened.uid);
|
|
383
|
+
this.emit("payload", p, { cid: c, login: opened.login, uid: opened.uid });
|
|
384
|
+
}
|
|
385
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
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, no AAD. Output base64(ephPub ‖ nonce ‖ ct ‖ tag).
|
|
19
|
+
* The key is single-use (fresh ephemeral per call), so nonce reuse cannot occur.
|
|
20
|
+
*/
|
|
21
|
+
export function sealToDevice(boxPub, plaintext) {
|
|
22
|
+
const recipient = hexToBytes(boxPub);
|
|
23
|
+
const ephPriv = x25519.utils.randomSecretKey();
|
|
24
|
+
const ephPub = x25519.getPublicKey(ephPriv);
|
|
25
|
+
const key = sealKey(x25519.getSharedSecret(ephPriv, recipient), ephPub, recipient);
|
|
26
|
+
return Buffer.concat([ephPub, sealBytes(key, plaintext)]).toString("base64");
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Inverse of `sealToDevice` using this device's boxPriv: shared = X25519(boxPriv, ephPub), same HKDF and AES-256-GCM.
|
|
30
|
+
* Returns null on any failure (sealed to another device, tampered, malformed); never throws.
|
|
31
|
+
*/
|
|
32
|
+
export function openFromDevice(id, sealed) {
|
|
33
|
+
try {
|
|
34
|
+
const buf = Buffer.from(sealed, "base64");
|
|
35
|
+
if (buf.length < 32 + 28)
|
|
36
|
+
return null;
|
|
37
|
+
const ephPub = buf.subarray(0, 32);
|
|
38
|
+
const key = sealKey(x25519.getSharedSecret(hexToBytes(id.boxPriv), ephPub), ephPub, hexToBytes(id.boxPub));
|
|
39
|
+
const out = openBytes(key, buf.subarray(32));
|
|
40
|
+
return out === null ? null : new Uint8Array(out);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Encrypt and sign a team frame.
|
|
48
|
+
* d = base64(nonce ‖ ct ‖ tag) of AES-256-GCM(teamKey, utf8 payload, random 96-bit nonce,
|
|
49
|
+
* AAD = utf8 "mindmeld/frame/v1|" + epoch + "|" + deviceId);
|
|
50
|
+
* sig = hex Ed25519(signPriv, utf8(epoch + "|" + deviceId + "|" + d)).
|
|
51
|
+
*/
|
|
52
|
+
export function sealFrame(epoch, teamKey, id, payload) {
|
|
53
|
+
const d = seal(teamKey, payload, frameAad(epoch, id.deviceId));
|
|
54
|
+
const sig = Buffer.from(ed25519.sign(sigMessage(epoch, id.deviceId, d), hexToBytes(id.signPriv))).toString("hex");
|
|
55
|
+
return { e: epoch, dev: id.deviceId, d, sig };
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* 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
|
|
59
|
+
* utf8(e + "|" + dev + "|" + d) is checked (strict Ed25519, zip215: false) against that entry's signPub BEFORE decryption; then `d` is opened with
|
|
60
|
+
* keys.get(e) and AAD "mindmeld/frame/v1|" + e + "|" + dev. Returns the roster uid, login and payload, or null on any
|
|
61
|
+
* failure (unknown device, bad signature, unknown epoch, decrypt failure, malformed input); never throws.
|
|
62
|
+
*/
|
|
63
|
+
export function openFrame(f, keys, roster) {
|
|
64
|
+
try {
|
|
65
|
+
if (!f || typeof f.dev !== "string" || !DEVICE_ID.test(f.dev))
|
|
66
|
+
return null;
|
|
67
|
+
if (typeof f.e !== "number" || !Number.isSafeInteger(f.e) || typeof f.d !== "string" || typeof f.sig !== "string" || !SIG_HEX.test(f.sig))
|
|
68
|
+
return null;
|
|
69
|
+
const sender = roster.get(f.dev);
|
|
70
|
+
if (!sender)
|
|
71
|
+
return null;
|
|
72
|
+
if (!ed25519.verify(hexToBytes(f.sig), sigMessage(f.e, f.dev, f.d), hexToBytes(sender.signPub), { zip215: false }))
|
|
73
|
+
return null;
|
|
74
|
+
const key = keys.get(f.e);
|
|
75
|
+
if (!key)
|
|
76
|
+
return null;
|
|
77
|
+
const payload = open(key, f.d, frameAad(f.e, f.dev));
|
|
78
|
+
return payload === null ? null : { uid: sender.uid, login: sender.login, payload };
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|