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/dist/daemon.js CHANGED
@@ -1,70 +1,122 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { EventEmitter } from "node:events";
3
- import WebSocket from "ws";
4
- import { keyFor, open, roomIdFor, seal } from "./crypto.js";
5
- import { Frame, HELLO_INTERVAL_MS, PEER_TIMEOUT_MS, Payload, PROTOCOL_VERSION } from "./protocol.js";
3
+ import { GroupChannel } from "./channel.js";
4
+ import { ACTIVITY_CHECK_MS, ACTIVITY_RESOLUTION_MS, PROTOCOL_VERSION } from "./protocol.js";
6
5
  export class Daemon extends EventEmitter {
7
6
  opts;
8
7
  peerId = randomUUID();
9
- key;
10
- roomUrl;
11
- ws = null;
12
- helloTimer = null;
13
- stopped = false;
8
+ channel;
9
+ activityTimer = null;
10
+ lastSentActive = 0;
11
+ _stopped = false;
14
12
  peers = new Map();
15
13
  pending = new Map();
16
14
  inbox = [];
17
15
  askLog = new Map();
16
+ /**
17
+ * Verified login that first used each peer id (only for channels that report logins). A hello,
18
+ * bye or reply for that peer id from any other login is ignored. Never cleared: peer ids are random.
19
+ */
20
+ peerOwner = new Map();
18
21
  share;
19
22
  constructor(opts) {
20
23
  super();
21
24
  this.opts = opts;
22
25
  this.share = opts.share === undefined ? { label: opts.project } : opts.share;
23
- this.key = keyFor(opts.secret);
24
- this.roomUrl = `${opts.relay.replace(/\/$/, "")}/room/${roomIdFor(opts.secret)}`;
26
+ if (!opts.channel && !opts.secret)
27
+ throw new Error("no group secret and no channel");
28
+ this.channel = opts.channel ?? new GroupChannel({ secret: opts.secret, relay: opts.relay, version: opts.version });
29
+ this.wireChannel();
30
+ }
31
+ /** Encrypted frames this client has sent (only transports that count them report it). */
32
+ get framesSent() {
33
+ return this.channel.framesSent ?? 0;
34
+ }
35
+ /** No reconnect and no "disconnected" event once stopped. Also forwarded to the channel (tests crash a daemon this way). */
36
+ get stopped() {
37
+ return this._stopped;
38
+ }
39
+ set stopped(v) {
40
+ this._stopped = v;
41
+ if ("stopped" in this.channel)
42
+ this.channel.stopped = v;
43
+ }
44
+ /** The channel's socket, if it has one. Kept so tests can kill the connection. */
45
+ get ws() {
46
+ return this.channel.ws ?? null;
25
47
  }
26
48
  start() {
27
- this.connect();
28
- this.helloTimer = setInterval(() => this.sendHello(), HELLO_INTERVAL_MS);
49
+ this.channel.start();
50
+ // Re-announce only when "last active" moved enough to matter for routing; no heartbeat.
51
+ this.activityTimer = setInterval(() => {
52
+ if (!this.share)
53
+ return;
54
+ const at = this.activeAt();
55
+ if (at && at - this.lastSentActive >= ACTIVITY_RESOLUTION_MS)
56
+ this.sendHello();
57
+ }, this.opts.activityCheckMs ?? ACTIVITY_CHECK_MS);
58
+ this.activityTimer.unref?.();
59
+ }
60
+ /** Version info from the relay: latest, minimum, and how many teammates run an old client. */
61
+ get server() {
62
+ return this.channel.server;
29
63
  }
30
64
  async stop() {
31
- this.stopped = true;
32
- if (this.helloTimer)
33
- clearInterval(this.helloTimer);
65
+ this._stopped = true;
66
+ if (this.activityTimer)
67
+ clearInterval(this.activityTimer);
34
68
  this.send({ type: "bye", peer: this.peerId });
35
- this.ws?.close();
69
+ const stopping = this.channel.stop();
36
70
  for (const p of this.pending.values())
37
71
  p.resolve({ error: "daemon stopped" });
72
+ await stopping;
38
73
  }
74
+ /** Peers present right now. The relay reports leaves, so there is no timeout to wait out. */
39
75
  onlinePeers() {
40
- const now = Date.now();
41
- return [...this.peers.values()].filter((p) => now - p.lastSeen < PEER_TIMEOUT_MS);
76
+ return [...this.peers.values()];
42
77
  }
43
- // ── relay connection ────────────────────────────────────────────────
44
- connect() {
45
- const ws = new WebSocket(this.roomUrl);
46
- this.ws = ws;
47
- ws.on("open", () => {
78
+ // ── channel events ──────────────────────────────────────────────────
79
+ wireChannel() {
80
+ const ch = this.channel;
81
+ ch.on("connected", () => {
82
+ // Connection ids from a previous connection are meaningless now; shared peers re-announce
83
+ // themselves in response to our "joined".
84
+ this.peers.clear();
48
85
  this.emit("connected");
49
86
  this.sendHello();
50
87
  });
51
- ws.on("message", (data) => this.handleFrame(data.toString()));
52
- ws.on("error", (e) => this.emit("relay-error", e));
53
- ws.on("close", () => {
54
- if (this.stopped)
55
- return;
56
- this.emit("disconnected");
57
- setTimeout(() => !this.stopped && this.connect(), 2000);
88
+ ch.on("disconnected", () => {
89
+ for (const peer of [...this.peers.values()])
90
+ this.dropPeer(peer.peer, "disconnected from the relay");
91
+ if (!this._stopped)
92
+ this.emit("disconnected");
93
+ });
94
+ ch.on("relay-error", (e) => this.emit("relay-error", e));
95
+ ch.on("server", (info) => this.emit("server", info));
96
+ ch.on("blocked", (info) => {
97
+ this._stopped = true;
98
+ this.emit("blocked", info);
99
+ });
100
+ ch.on("joined", () => {
101
+ if (this.share)
102
+ this.sendHello(); // let the newcomer see this shared session
58
103
  });
104
+ ch.on("left", (cid) => {
105
+ for (const p of [...this.peers.values()])
106
+ if (p.cid === cid)
107
+ this.dropPeer(p.peer, "closed");
108
+ });
109
+ ch.on("payload", (p, from) => this.handlePayload(p, from));
59
110
  }
60
111
  send(p) {
61
- if (this.ws?.readyState !== WebSocket.OPEN)
62
- return;
63
- const frame = { t: "msg", d: seal(this.key, JSON.stringify(p)) };
64
- this.ws.send(JSON.stringify(frame));
112
+ this.channel.send(p);
65
113
  }
66
114
  get connected() {
67
- return this.ws?.readyState === WebSocket.OPEN;
115
+ return this.channel.connected;
116
+ }
117
+ /** The name this daemon announces itself as (the login, on a team). */
118
+ get name() {
119
+ return this.opts.name;
68
120
  }
69
121
  get sharing() {
70
122
  return this.share;
@@ -81,13 +133,10 @@ export class Daemon extends EventEmitter {
81
133
  sendHello() {
82
134
  if (!this.share)
83
135
  return; // unshared sessions never announce themselves
84
- let info = {};
85
- try {
86
- info = this.opts.sessionInfo?.() ?? {};
87
- }
88
- catch {
89
- // best-effort metadata
90
- }
136
+ const activeAt = this.activeAt();
137
+ if (activeAt)
138
+ this.lastSentActive = activeAt;
139
+ const info = { activeAt };
91
140
  this.send({
92
141
  type: "hello",
93
142
  peer: this.peerId,
@@ -97,54 +146,79 @@ export class Daemon extends EventEmitter {
97
146
  v: PROTOCOL_VERSION,
98
147
  });
99
148
  }
100
- handleFrame(raw) {
101
- let frame;
149
+ activeAt() {
102
150
  try {
103
- frame = Frame.parse(JSON.parse(raw));
151
+ return this.opts.sessionInfo?.().activeAt;
104
152
  }
105
153
  catch {
106
- return;
154
+ return undefined; // best-effort metadata
107
155
  }
108
- const plain = open(this.key, frame.d);
109
- if (plain === null)
156
+ }
157
+ /** Forget a peer, and fail any question still waiting on it instead of letting it time out. */
158
+ dropPeer(peerId, why) {
159
+ const info = this.peers.get(peerId);
160
+ if (!info)
110
161
  return;
111
- const parsed = Payload.safeParse(JSON.parse(plain));
112
- if (!parsed.success)
162
+ this.peers.delete(peerId);
163
+ this.emit("peer-left", info);
164
+ for (const [id, p] of this.pending) {
165
+ if (p.target === peerId) {
166
+ this.pending.delete(id);
167
+ p.resolve({ error: `${info.name}'s session ${why} before answering` });
168
+ }
169
+ }
170
+ }
171
+ /** False if `login` (a verified identity key) is set and the peer id was first seen from a different one; binds it otherwise. */
172
+ ownsPeer(peerId, login) {
173
+ if (login === undefined)
174
+ return true;
175
+ const owner = this.peerOwner.get(peerId);
176
+ if (owner === undefined)
177
+ this.peerOwner.set(peerId, login);
178
+ return owner === undefined || owner === login;
179
+ }
180
+ /** False if a reply to a question came from a login other than the one that owns the asked peer. */
181
+ fromTarget(pending, login) {
182
+ if (login === undefined)
183
+ return true;
184
+ const owner = this.peerOwner.get(pending.target);
185
+ return owner === undefined || owner === login;
186
+ }
187
+ handlePayload(p, from) {
188
+ // An authenticated login beats any name the payload claims for itself (it is the display name).
189
+ const login = from.login;
190
+ // Ownership binds to the most stable verified identity: the GitHub id on a team, else the login.
191
+ const owner = from.uid !== undefined ? `uid:${from.uid}` : login;
192
+ if ((p.type === "hello" || p.type === "bye") && !this.ownsPeer(p.peer, owner))
113
193
  return;
114
- const p = parsed.data;
115
194
  switch (p.type) {
116
195
  case "hello": {
117
- const isNew = !this.onlinePeers().some((x) => x.peer === p.peer);
196
+ const isNew = !this.peers.has(p.peer);
118
197
  this.peers.set(p.peer, {
119
198
  peer: p.peer,
120
- name: p.name,
199
+ name: login ?? p.name,
121
200
  project: p.project,
122
201
  session: p.session,
123
202
  activeAt: p.activeAt,
124
203
  v: p.v,
204
+ cid: from.cid,
125
205
  lastSeen: Date.now(),
126
206
  });
127
- if (isNew) {
207
+ if (isNew)
128
208
  this.emit("peer-joined", this.peers.get(p.peer));
129
- this.sendHello(); // let the newcomer see us immediately
130
- }
131
209
  break;
132
210
  }
133
- case "bye": {
134
- const info = this.peers.get(p.peer);
135
- this.peers.delete(p.peer);
136
- if (info)
137
- this.emit("peer-left", info);
211
+ case "bye":
212
+ this.dropPeer(p.peer, "stopped sharing");
138
213
  break;
139
- }
140
214
  case "ask":
141
215
  // Only a shared session answers, and only questions addressed to it (or legacy broadcasts).
142
216
  if (this.share && (!p.to || p.to === this.opts.name || p.to === this.peerId))
143
- void this.handleAsk(p);
217
+ void this.handleAsk(p, login, owner);
144
218
  break;
145
219
  case "status": {
146
220
  const pending = this.pending.get(p.id);
147
- if (pending) {
221
+ if (pending && this.fromTarget(pending, owner)) {
148
222
  pending.acked = true;
149
223
  pending.onStatus?.(p.state);
150
224
  }
@@ -152,17 +226,17 @@ export class Daemon extends EventEmitter {
152
226
  }
153
227
  case "answer": {
154
228
  const pending = this.pending.get(p.id);
155
- if (pending) {
229
+ if (pending && this.fromTarget(pending, owner)) {
156
230
  this.pending.delete(p.id);
157
- pending.resolve({ from: this.nameOf(p.from), text: p.text });
231
+ pending.resolve({ from: this.nameOf(p.from, undefined, login), text: p.text });
158
232
  }
159
233
  break;
160
234
  }
161
235
  case "decline": {
162
236
  const pending = this.pending.get(p.id);
163
- if (!pending)
237
+ if (!pending || !this.fromTarget(pending, owner))
164
238
  break;
165
- pending.declines.push(`${this.nameOf(p.from)}: ${p.reason}`);
239
+ pending.declines.push(`${this.nameOf(p.from, undefined, login)}: ${p.reason}`);
166
240
  if (pending.declines.length >= pending.expected) {
167
241
  this.pending.delete(p.id);
168
242
  pending.resolve({ error: `declined — ${pending.declines.join("; ")}` });
@@ -171,14 +245,14 @@ export class Daemon extends EventEmitter {
171
245
  }
172
246
  case "snippet":
173
247
  if (!p.to || p.to === this.opts.name || p.to === this.peerId) {
174
- this.inbox.push({ ...p, from: this.nameOf(p.from) });
248
+ this.inbox.push({ ...p, from: this.nameOf(p.from, undefined, login) });
175
249
  this.emit("snippet", p);
176
250
  }
177
251
  break;
178
252
  }
179
253
  }
180
- nameOf(peerId, fallback) {
181
- return this.peers.get(peerId)?.name ?? fallback ?? peerId.slice(0, 8);
254
+ nameOf(peerId, fallback, login) {
255
+ return login ?? this.peers.get(peerId)?.name ?? fallback ?? peerId.slice(0, 8);
182
256
  }
183
257
  rateLimited(from) {
184
258
  const { max, windowMs } = this.opts.rateLimit ?? { max: 10, windowMs: 10 * 60_000 };
@@ -189,7 +263,7 @@ export class Daemon extends EventEmitter {
189
263
  return recent.length > max;
190
264
  }
191
265
  seenAsks = new Set();
192
- async handleAsk(ask) {
266
+ async handleAsk(ask, login, owner) {
193
267
  if (this.seenAsks.has(ask.id))
194
268
  return; // a resend of a question already being handled
195
269
  this.seenAsks.add(ask.id);
@@ -198,14 +272,15 @@ export class Daemon extends EventEmitter {
198
272
  : this.send({ type: "decline", id: ask.id, from: this.peerId, reason: d.reason });
199
273
  const report = (state) => this.send({ type: "status", id: ask.id, from: this.peerId, state });
200
274
  report("received");
201
- if (this.rateLimited(ask.from)) {
275
+ // A verified identity cannot dodge the limit by rotating peer ids.
276
+ if (this.rateLimited(owner ?? login ?? ask.from)) {
202
277
  reply({ action: "decline", reason: "rate limited — too many questions, try again later" });
203
278
  return;
204
279
  }
205
- const from = this.nameOf(ask.from, ask.fromName);
280
+ const from = this.nameOf(ask.from, ask.fromName, login);
206
281
  this.emit("question", { from, question: ask.question });
207
282
  try {
208
- const d = await this.opts.decide({ ...ask, from }, report);
283
+ const d = await this.opts.decide({ ...ask, from, fromName: from }, report);
209
284
  this.emit("handled", { from, question: ask.question, action: d.action });
210
285
  reply(d);
211
286
  }
@@ -269,7 +344,7 @@ export class Daemon extends EventEmitter {
269
344
  }
270
345
  }, ackMs));
271
346
  }
272
- this.pending.set(id, { resolve: finish, onStatus: opts.onStatus, acked: false, expected: 1, declines: [] });
347
+ this.pending.set(id, { target: target.peer, resolve: finish, onStatus: opts.onStatus, acked: false, expected: 1, declines: [] });
273
348
  this.send(payload);
274
349
  });
275
350
  }
@@ -0,0 +1,58 @@
1
+ import { createHash } from "node:crypto";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { ed25519, x25519 } from "@noble/curves/ed25519.js";
5
+ import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
6
+ import { homeDir } from "./config.js";
7
+ const sha256Hex = (bytes) => createHash("sha256").update(bytes).digest("hex");
8
+ /** Parse and verify an existing identity file; never regenerates, since that would change the device identity. */
9
+ function readIdentity(path) {
10
+ const bad = (why) => new Error(`${path} is corrupt (${why}). Repair it or delete it to create a new device identity.`);
11
+ let raw;
12
+ try {
13
+ raw = JSON.parse(readFileSync(path, "utf8"));
14
+ }
15
+ catch (e) {
16
+ throw bad(e.message);
17
+ }
18
+ const keys = ["deviceId", "signPub", "signPriv", "boxPub", "boxPriv"];
19
+ if (!raw || typeof raw !== "object" || keys.some((k) => typeof raw[k] !== "string"))
20
+ throw bad("missing or non-string fields");
21
+ const id = raw;
22
+ try {
23
+ if (id.deviceId !== sha256Hex(hexToBytes(id.signPub)).slice(0, 16) ||
24
+ id.signPub !== bytesToHex(ed25519.getPublicKey(hexToBytes(id.signPriv))) ||
25
+ id.boxPub !== bytesToHex(x25519.getPublicKey(hexToBytes(id.boxPriv))))
26
+ throw new Error("mismatch");
27
+ }
28
+ catch {
29
+ throw bad("keys do not match");
30
+ }
31
+ return id;
32
+ }
33
+ /** Read `identity.json` from the mindmeld home, creating it (mode 600) on first use. */
34
+ export function loadOrCreateIdentity() {
35
+ const path = join(homeDir(), "identity.json");
36
+ if (existsSync(path))
37
+ return readIdentity(path);
38
+ const signPriv = ed25519.utils.randomSecretKey();
39
+ const signPub = ed25519.getPublicKey(signPriv);
40
+ const boxPriv = x25519.utils.randomSecretKey();
41
+ const boxPub = x25519.getPublicKey(boxPriv);
42
+ const id = {
43
+ deviceId: sha256Hex(signPub).slice(0, 16),
44
+ signPub: bytesToHex(signPub),
45
+ signPriv: bytesToHex(signPriv),
46
+ boxPub: bytesToHex(boxPub),
47
+ boxPriv: bytesToHex(boxPriv),
48
+ };
49
+ mkdirSync(homeDir(), { recursive: true, mode: 0o700 });
50
+ writeFileSync(path, JSON.stringify(id, null, 2) + "\n", { mode: 0o600 });
51
+ chmodSync(path, 0o600);
52
+ return id;
53
+ }
54
+ /** Human-comparable key fingerprint: first 16 bytes of sha256(signPub) as groups of 4 hex chars. */
55
+ export function fingerprint(signPub) {
56
+ const hex = sha256Hex(hexToBytes(signPub)).slice(0, 32);
57
+ return hex.match(/.{4}/g).join(" ");
58
+ }