mindmeld-mcp 0.4.0 → 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/relay.js CHANGED
@@ -1,26 +1,43 @@
1
+ import { randomBytes } from "node:crypto";
1
2
  import { createServer } from "node:http";
2
3
  import { WebSocketServer, WebSocket } from "ws";
4
+ import { compareVersions, VERSION } from "./version.js";
3
5
  const ROOM_PATH = /^\/room\/([0-9a-f]{64})$/;
4
6
  const PAIR_PATH = /^\/pair\/([a-z0-9]{4,16})$/;
5
7
  const MAX_FRAME_BYTES = 1024 * 1024;
6
8
  /**
7
9
  * A dumb fan-out relay. Two kinds of rooms:
8
10
  * - `/room/<id>`: a paired group; every frame is forwarded to the other members.
11
+ * Clients from 0.5 on connect with `?v=<version>`. They get version info, connection ids and
12
+ * joined/left events, and are kept apart from older clients, which see each other as before.
9
13
  * - `/pair/<rendezvous>`: a one-time pairing handshake between exactly two sockets.
10
14
  * When the second one arrives, both get `{"t":"peer-joined"}`.
11
15
  * Frames are end-to-end protected; the relay stores nothing and cannot read them.
16
+ * Same protocol as the Cloudflare relay in relay-worker/.
12
17
  */
13
- export function startRelay(port, host = "0.0.0.0") {
18
+ export function startRelay(port, host = "0.0.0.0", opts = {}) {
19
+ const latest = opts.latest ?? VERSION;
20
+ const minimum = opts.minimum ?? "0.5.0";
14
21
  const rooms = new Map();
15
22
  const http = createServer((_req, res) => {
16
23
  res.writeHead(200, { "content-type": "text/plain" });
17
24
  res.end("mindmeld relay\n");
18
25
  });
19
26
  const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES });
27
+ const send = (m, frame) => {
28
+ if (m.ws.readyState === WebSocket.OPEN)
29
+ m.ws.send(typeof frame === "string" ? frame : JSON.stringify(frame));
30
+ };
31
+ const serverInfo = (set) => ({
32
+ t: "server",
33
+ latest,
34
+ minimum,
35
+ legacy: [...set].filter((m) => m.v === null).length,
36
+ });
20
37
  http.on("upgrade", (req, socket, head) => {
21
- const url = req.url ?? "";
22
- const room = ROOM_PATH.exec(url);
23
- const pair = PAIR_PATH.exec(url);
38
+ const url = new URL(req.url ?? "/", "http://relay");
39
+ const room = ROOM_PATH.exec(url.pathname);
40
+ const pair = PAIR_PATH.exec(url.pathname);
24
41
  if (!room && !pair) {
25
42
  socket.end("HTTP/1.1 404 Not Found\r\n\r\n");
26
43
  return;
@@ -35,27 +52,81 @@ export function startRelay(port, host = "0.0.0.0") {
35
52
  let set = rooms.get(key);
36
53
  if (!set)
37
54
  rooms.set(key, (set = new Set()));
38
- set.add(ws);
55
+ const me = { ws, cid: randomBytes(6).toString("hex"), v: url.searchParams.get("v") };
56
+ if (room && me.v !== null && compareVersions(me.v, minimum) < 0) {
57
+ // Accept, explain, close: a refused upgrade would only make the client retry forever.
58
+ send(me, { ...serverInfo(set), blocked: true });
59
+ ws.close(4001, "update required");
60
+ return;
61
+ }
62
+ set.add(me);
63
+ const versioned = (m) => m.v !== null;
39
64
  if (pair && set.size === 2) {
40
65
  for (const m of set)
41
- m.send(JSON.stringify({ t: "peer-joined" }));
66
+ send(m, { t: "peer-joined" });
67
+ }
68
+ if (room) {
69
+ if (versioned(me)) {
70
+ send(me, serverInfo(set));
71
+ for (const m of set)
72
+ if (m !== me && versioned(m))
73
+ send(m, { t: "joined", c: me.cid });
74
+ }
75
+ else {
76
+ for (const m of set)
77
+ if (versioned(m))
78
+ send(m, serverInfo(set));
79
+ }
42
80
  }
43
81
  ws.on("message", (data, isBinary) => {
44
82
  if (isBinary)
45
83
  return;
46
- for (const other of set) {
47
- if (other !== ws && other.readyState === WebSocket.OPEN)
48
- other.send(data.toString());
84
+ const raw = data.toString();
85
+ if (pair) {
86
+ for (const m of set)
87
+ if (m !== me)
88
+ send(m, raw);
89
+ return;
49
90
  }
91
+ if (!versioned(me)) {
92
+ // Old clients only ever reach each other.
93
+ for (const m of set)
94
+ if (m !== me && !versioned(m))
95
+ send(m, raw);
96
+ return;
97
+ }
98
+ let frame;
99
+ try {
100
+ frame = JSON.parse(raw);
101
+ }
102
+ catch {
103
+ return;
104
+ }
105
+ if (frame.t !== "msg" || typeof frame.d !== "string")
106
+ return;
107
+ const stamped = JSON.stringify({ t: "msg", d: frame.d, c: me.cid });
108
+ for (const m of set)
109
+ if (m !== me && versioned(m))
110
+ send(m, stamped);
50
111
  });
51
112
  ws.on("close", () => {
52
- set.delete(ws);
113
+ set.delete(me);
53
114
  if (set.size === 0)
54
115
  rooms.delete(key);
55
116
  // A pairing room is single-use: if either side leaves, end it for the other too.
56
117
  if (pair)
57
118
  for (const m of set)
58
- m.close(1000, "peer left");
119
+ m.ws.close(1000, "peer left");
120
+ if (room) {
121
+ for (const m of set) {
122
+ if (!versioned(m))
123
+ continue;
124
+ if (versioned(me))
125
+ send(m, { t: "left", c: me.cid });
126
+ else
127
+ send(m, serverInfo(set));
128
+ }
129
+ }
59
130
  });
60
131
  });
61
132
  });
@@ -0,0 +1,174 @@
1
+ import { deviceFlowLogin } from "./auth/github.js";
2
+ import { GITHUB_CLIENT_ID } from "./auth/config.js";
3
+ import { assertSessionRelay, exchange, loadSession, savedSessionLogin } from "./auth/session.js";
4
+ import { credentialRelayAllowed } from "./config.js";
5
+ import { fingerprint, loadOrCreateIdentity } from "./identity.js";
6
+ import { httpBase } from "./teamkeys.js";
7
+ /**
8
+ * Team operations shared by the MCP tools (src/mcpteam.ts) and the CLI: relay calls for the team
9
+ * routes, the sign-in state, and the text shown to the user.
10
+ */
11
+ export const NOT_SIGNED_IN = "Not signed in: run /mindmeld:login";
12
+ export const SIGNED_IN_EXPIRED = "Sign-in expired: run /mindmeld:login";
13
+ export const INSTALL = "claude plugin install mindmeld --marketplace dhrupad-sah/mindmeld";
14
+ /** GitHub logins are case-insensitive; mindmeld compares and sends them lowercased. */
15
+ export const normLogin = (login) => login.trim().replace(/^@/, "").toLowerCase();
16
+ export function signInState(relay) {
17
+ const session = loadSession(relay);
18
+ if (session)
19
+ return { session };
20
+ const login = savedSessionLogin(relay);
21
+ return login ? { expired: login } : { none: true };
22
+ }
23
+ /** "Signed in: @x", or the guidance to sign in. */
24
+ export function signInLine(s) {
25
+ if ("session" in s)
26
+ return `Signed in: @${s.session.login}`;
27
+ return "expired" in s ? SIGNED_IN_EXPIRED : NOT_SIGNED_IN;
28
+ }
29
+ /** An error from a team route, with the HTTP status. */
30
+ export class TeamApiError extends Error {
31
+ status;
32
+ constructor(message, status) {
33
+ super(message);
34
+ this.status = status;
35
+ }
36
+ }
37
+ /** One call to a team route as `session`. A 401 becomes the sign-in guidance. */
38
+ export async function teamCall(relay, session, method, path, body, timeoutMs = 15_000) {
39
+ // The session token only ever goes to the relay that issued it.
40
+ try {
41
+ assertSessionRelay(relay, session);
42
+ }
43
+ catch (e) {
44
+ throw new TeamApiError(e.message, 401);
45
+ }
46
+ const res = await fetch(`${httpBase(relay)}${path}`, {
47
+ method,
48
+ headers: { authorization: `Bearer ${session.token}`, ...(body !== undefined ? { "content-type": "application/json" } : {}) },
49
+ body: body === undefined ? undefined : JSON.stringify(body),
50
+ signal: AbortSignal.timeout(timeoutMs),
51
+ });
52
+ let json = null;
53
+ try {
54
+ json = await res.json();
55
+ }
56
+ catch { }
57
+ if (!res.ok) {
58
+ if (res.status === 401)
59
+ throw new TeamApiError(SIGNED_IN_EXPIRED, 401);
60
+ const msg = json && typeof json.error === "string" ? json.error : `HTTP ${res.status}`;
61
+ throw new TeamApiError(`relay: ${msg}`, res.status);
62
+ }
63
+ return json;
64
+ }
65
+ export const createTeam = (relay, s, name) => teamCall(relay, s, "POST", "/v1/teams", { name });
66
+ export const listTeams = (relay, s) => teamCall(relay, s, "GET", "/v1/teams");
67
+ export const getRoster = (relay, s, teamId, timeoutMs) => teamCall(relay, s, "GET", `/v1/teams/${teamId}`, undefined, timeoutMs);
68
+ export const inviteMember = (relay, s, teamId, login) => teamCall(relay, s, "POST", `/v1/teams/${teamId}/invites`, { login: normLogin(login) });
69
+ export const acceptInvite = (relay, s, teamId) => teamCall(relay, s, "POST", `/v1/teams/${teamId}/accept`);
70
+ /** Add this device to a team its login is already in (a second machine). */
71
+ export const addDevice = (relay, s, teamId) => teamCall(relay, s, "POST", `/v1/teams/${teamId}/devices`);
72
+ export const deleteMember = (relay, s, teamId, login) => teamCall(relay, s, "DELETE", `/v1/teams/${teamId}/members/${encodeURIComponent(normLogin(login))}`);
73
+ export const setRole = (relay, s, teamId, login, role) => teamCall(relay, s, "POST", `/v1/teams/${teamId}/roles`, { login: normLogin(login), role });
74
+ /**
75
+ * Where the device flow runs: https://github.com, unless MINDMELD_GITHUB_BASE is exactly
76
+ * http://127.0.0.1:<port> or http://localhost:<port> (a local mock for tests). Nothing else is
77
+ * accepted, so a project-supplied env can't send the sign-in, and the user's GitHub token, to another host.
78
+ */
79
+ export function githubBase(env = process.env) {
80
+ const m = /^http:\/\/(127\.0\.0\.1|localhost):(\d{1,5})\/?$/.exec(env.MINDMELD_GITHUB_BASE ?? "");
81
+ return m && Number(m[2]) > 0 && Number(m[2]) < 65536 ? `http://${m[1]}:${m[2]}` : "https://github.com";
82
+ }
83
+ /**
84
+ * GitHub device-flow sign-in, then the exchange for a relay session (saved to session.json, bound
85
+ * to `relay`). `onCode` gets the code to show the user. Refuses, before asking GitHub, a relay that
86
+ * is not the hosted one, a loopback one, or the team relay the user chose in `config`.
87
+ */
88
+ export async function signIn(relay, config, onCode) {
89
+ if (!credentialRelayAllowed(relay, config)) {
90
+ throw new Error(`refusing to sign in at ${relay}: choose it explicitly with mindmeld login --relay ${relay}`);
91
+ }
92
+ const token = await deviceFlowLogin({ clientId: GITHUB_CLIENT_ID, onCode, githubBase: githubBase() });
93
+ return exchange(relay, token, loadOrCreateIdentity());
94
+ }
95
+ /** The message an admin sends to someone they invited. */
96
+ export function inviteMessage(login, teamName) {
97
+ const who = normLogin(login);
98
+ return [
99
+ `Invited @${who} to team "${teamName}".`,
100
+ "",
101
+ `Send @${who} this message:`,
102
+ ` 1. Install mindmeld if you don't have it yet: ${INSTALL}`,
103
+ " 2. In Claude Code, sign in with GitHub: /mindmeld:login",
104
+ ` 3. Accept the invite: /mindmeld:team accept ${teamName}`,
105
+ "",
106
+ `If @${who} hasn't signed in to mindmeld yet, that's fine: they'll see the invite after signing in.`,
107
+ ].join("\n");
108
+ }
109
+ const roleText = (roster, uid) => roster.members.find((m) => m.uid === uid)?.role;
110
+ /** "Team: core (you're admin)". `uid` is the signed-in GitHub id. */
111
+ export function teamLine(name, roster, uid) {
112
+ const role = roster && uid !== null ? roleText(roster, uid) : undefined;
113
+ return role ? `Team: ${name} (you're ${role})` : `Team: ${name}`;
114
+ }
115
+ const EVENTS = {
116
+ created: (by) => `${by} created the team`,
117
+ invited: (by, s) => `${by} invited ${s}`,
118
+ joined: (by) => `${by} joined`,
119
+ "device-added": (by, s) => `${by} added device ${s}`,
120
+ rotated: (by, s) => `${by} rotated the team key (epoch ${s})`,
121
+ removed: (by, s) => `${by} removed ${s}`,
122
+ role: (by, s) => `${by} changed the role of ${s}`,
123
+ };
124
+ /** The `team` tool's text: members, roles, devices (fingerprint, key), invites and the recent log. */
125
+ export function formatTeam(roster, me) {
126
+ const lines = [`Team: ${roster.name} (key epoch ${roster.epoch})`, "", "Members:"];
127
+ for (const m of roster.members) {
128
+ lines.push(`- @${m.login} (${m.role})${m.uid === me.uid ? " (you)" : ""}`);
129
+ if (m.devices.length === 0)
130
+ lines.push(" no devices");
131
+ for (const d of m.devices) {
132
+ const key = d.hasKey ? "has the team key" : "waiting for the team key";
133
+ lines.push(` device ${fingerprint(d.signPub)}: ${key}${d.deviceId === me.deviceId ? " (this device)" : ""}`);
134
+ }
135
+ }
136
+ lines.push("", `Pending invites: ${roster.invites.length ? roster.invites.map((l) => `@${l}`).join(", ") : "none"}`);
137
+ const log = roster.log.slice(-20).reverse();
138
+ lines.push("", "Recent activity:");
139
+ if (log.length === 0)
140
+ lines.push("- none");
141
+ for (const e of log) {
142
+ const say = EVENTS[e.event ?? ""] ?? ((by, s) => `${by} ${e.event} ${s}`);
143
+ lines.push(`- ${e.at ? new Date(e.at).toLocaleString() : "?"} ${say(e.by ?? "?", e.subject ?? "")}`);
144
+ }
145
+ return lines.join("\n");
146
+ }
147
+ /**
148
+ * Remove a member, then rotate the team key so they can't read anything sent from now on.
149
+ * A failed rotation is reported as an error, never as success.
150
+ */
151
+ export async function removeAndRotate(login, ops) {
152
+ const who = normLogin(login);
153
+ // Already gone (e.g. an earlier remove whose rotation failed): still rotate, so running it again finishes the job.
154
+ let gone = false;
155
+ try {
156
+ await ops.remove();
157
+ }
158
+ catch (e) {
159
+ if (e.status !== 404)
160
+ return { text: `Could not remove @${who}: ${e.message}`, isError: true };
161
+ gone = true;
162
+ }
163
+ try {
164
+ const epoch = await ops.rotate();
165
+ const did = gone ? `@${who} is not in the team. Rotated the team key anyway` : `Removed @${who} and rotated the team key`;
166
+ return { text: `${did} (now epoch ${epoch}). They can't read anything the team sends from now on.`, isError: false };
167
+ }
168
+ catch (e) {
169
+ return {
170
+ text: `Removed @${who}, but the team key could not be rotated: ${e.message}; run remove again or ask another admin`,
171
+ isError: true,
172
+ };
173
+ }
174
+ }