mindmeld-mcp 0.6.0 → 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.
package/README.md CHANGED
@@ -28,20 +28,20 @@ claude mcp add -s user mindmeld -- mindmeld mcp
28
28
 
29
29
  ## Teams (GitHub sign-in)
30
30
 
31
- A team is a group of people who sign in with GitHub. Each machine gets its own key pair, the team has a roster with admins and members, and an admin can remove someone for real: their devices are cut off and the team key is replaced, so they can't read anything sent afterwards. (Legacy groups below can't do that.) Teams need the hosted relay or your own relay running the 0.6 Worker. To use your own for teams, sign in with `mindmeld login --relay wss://your-relay` (or set `"teamRelay"` in `~/.mindmeld/config.json`); environment variables never change where your GitHub sign-in goes.
31
+ A team is a group of people who sign in with GitHub. Each machine gets its own key pair, the team has a roster with admins and members, and an admin can remove someone for real: their devices are cut off and the team key is replaced, so they can't read anything sent afterwards. (Legacy groups below can't do that.) Teams need mindmeld 0.7 or later on every machine, and the hosted relay or your own relay running the 0.7 Worker. To use your own for teams, sign in with `mindmeld login --relay wss://your-relay` (or set `"teamRelay"` in `~/.mindmeld/config.json`); environment variables never change where your GitHub sign-in goes.
32
32
 
33
33
  1. **Sign in, everyone, once:** `/mindmeld:login`. Claude shows a code and a link. Open the link, enter the code, approve on GitHub. Sign-in finishes on its own and `/mindmeld:status` shows who you are. It lasts 7 days, then you sign in again.
34
34
  2. **Create a team (an admin):** `/mindmeld:team create core`. You're its first admin and this machine is connected to it.
35
35
  3. **Invite by GitHub username:** `/mindmeld:team invite sarim-dev`. Claude gives you a short message to send them.
36
- 4. **They sign in and accept:** they install the plugin, run `/mindmeld:login`, then `/mindmeld:team accept core`. Their machine gets the team key the next time a teammate is online. `/mindmeld:status` shows "waiting" until then.
36
+ 4. **They sign in and accept:** they install the plugin, run `/mindmeld:login`, then `/mindmeld:team accept core`. `/mindmeld:team accept` on its own joins nothing: it lists their pending invites and who sent each one. Their machine gets the team key the next time a teammate is online. `/mindmeld:status` shows "waiting" until then.
37
37
  5. **Share a session:** `/mindmeld:share scraper work`, same as before. Sessions stay private until you do this.
38
38
  6. **Ask:** *"ask sarim-dev how they got the scraper so fast"*. Approval dialogs, the read-only fork and "always allow" work as described below.
39
39
 
40
- `/mindmeld:team` on its own shows the members, roles, pending invites, and each device's key fingerprint and whether it has the team key. `/mindmeld:team role <login> admin|member` changes a role.
40
+ `/mindmeld:team` on its own shows the members, roles, pending invites (and who sent them), and each device's key fingerprint and whether it has the team key. `/mindmeld:team role <login> admin|member` changes a role. `/mindmeld:team uninvite <login>` cancels a pending invite (admins only).
41
41
 
42
42
  **Removing someone:** `/mindmeld:team remove sarim-dev` (admins only). A dialog asks you to confirm. Then their devices are disconnected right away and the team key is rotated for everyone left. They keep whatever they already received, but not anything sent after.
43
43
 
44
- The relay learns team names, members' GitHub logins, roles, device public keys and who is connected. It never sees team keys or message content. One thing to know: the relay hands out the public keys, so a malicious relay could swap one. If that matters to you, compare fingerprints from `/mindmeld:team` with your teammates over another channel. Details, constructions and known gaps are in [`docs/security.md`](docs/security.md); it has not had an outside review yet.
44
+ The relay learns team names, members' GitHub logins, roles, device public keys and who is connected. It never sees team keys or message content. Questions and answers are sealed to the one device they are for, so other team members don't receive them either; which sessions are shared (and their labels) is visible to the whole team. One thing to know: the relay hands out the public keys, so a malicious relay could swap one. If that matters to you, compare fingerprints from `/mindmeld:team` with your teammates over another channel. Details, constructions and known gaps are in [`docs/security.md`](docs/security.md); it has not had an outside review yet.
45
45
 
46
46
  ## Legacy groups (invite codes)
47
47
 
package/dist/channel.js CHANGED
@@ -34,12 +34,14 @@ export class GroupChannel extends EventEmitter {
34
34
  get server() {
35
35
  return this.serverInfo;
36
36
  }
37
- send(p) {
37
+ /** Every member of a legacy group shares one key and gets every frame, so `to` is ignored. */
38
+ send(p, _to) {
38
39
  if (this.ws?.readyState !== WebSocket.OPEN)
39
- return;
40
+ return true;
40
41
  const frame = { t: "msg", d: seal(this.key, JSON.stringify(p)) };
41
42
  this.ws.send(JSON.stringify(frame));
42
43
  this.framesSent++;
44
+ return true;
43
45
  }
44
46
  connect() {
45
47
  const ws = new WebSocket(this.roomUrl);
package/dist/cli.js CHANGED
@@ -10,7 +10,7 @@ import { runMcpServer, teamLeaveNote, teamSetNote } from "./mcp.js";
10
10
  import { runInviter, runJoiner } from "./pairing.js";
11
11
  import { loadSession } from "./auth/session.js";
12
12
  import { loadOrCreateIdentity } from "./identity.js";
13
- import { acceptInvite, addDevice, createTeam, deleteMember, formatTeam, getRoster, inviteMember, inviteMessage, listTeams, normLogin, removeAndRotate, setRole, signIn, signInLine, signInState, } from "./teamapi.js";
13
+ import { acceptInvite, addDevice, createTeam, deleteMember, formatTeam, getRoster, inviteMember, inviteMessage, invitedByText, listTeams, normLogin, planAccept, removeAndRotate, revokeInvite, setRole, signIn, signInLine, signInState, } from "./teamapi.js";
14
14
  import { TeamChannel } from "./teamchannel.js";
15
15
  import { rotate } from "./teamkeys.js";
16
16
  import { startRelay } from "./relay.js";
@@ -28,7 +28,9 @@ const USAGE = `mindmeld — let teammates' Claude Code sessions ask each other q
28
28
  mindmeld team show your team: members, devices, invites, activity
29
29
  mindmeld team create <name> create a team (you're its admin)
30
30
  mindmeld team invite <github-login> invite someone (admins)
31
- mindmeld team accept [team] accept an invite, or use a team you're already in
31
+ mindmeld team uninvite <github-login> cancel a pending invite (admins)
32
+ mindmeld team accept [team] accept an invite, or use a team you're already in;
33
+ with no team, lists pending invites and who sent them
32
34
  mindmeld team remove <github-login> [-y] remove someone and rotate the team key (admins)
33
35
  mindmeld team role <github-login> admin|member change someone's role (admins)
34
36
  mindmeld sessions list Claude sessions in this directory
@@ -161,7 +163,7 @@ async function main() {
161
163
  process.exitCode = cmd && cmd !== "help" && cmd !== "--help" ? 1 : 0;
162
164
  }
163
165
  }
164
- /** `mindmeld team [create|invite|accept|remove|role]`: the CLI side of the MCP team tools. */
166
+ /** `mindmeld team [create|invite|uninvite|accept|remove|role]`: the CLI side of the MCP team tools. */
165
167
  async function team(args, yes) {
166
168
  const [sub, a, b] = args;
167
169
  const config = loadConfigOrNull();
@@ -182,7 +184,7 @@ async function team(args, yes) {
182
184
  const invites = (await listTeams(relay, session)).filter((t) => t.role === "invited");
183
185
  console.log("You're not in a team yet. Create one with `mindmeld team create <name>`, or accept an invite with `mindmeld team accept`.");
184
186
  if (invites.length)
185
- console.log(`Pending invites: ${invites.map((t) => `"${t.name}"`).join(", ")}`);
187
+ console.log(`Pending invites: ${invites.map((t) => `"${t.name}" (${invitedByText(t)})`).join(", ")}`);
186
188
  return;
187
189
  }
188
190
  console.log(formatTeam(await getRoster(relay, session, config.team.teamId), { uid: session.uid, deviceId: loadOrCreateIdentity().deviceId }));
@@ -205,22 +207,39 @@ async function team(args, yes) {
205
207
  console.log(inviteMessage(a, t.name));
206
208
  return;
207
209
  }
210
+ case "uninvite": {
211
+ if (!a)
212
+ throw new Error("usage: mindmeld team uninvite <github-login>");
213
+ const t = current();
214
+ const who = normLogin(a);
215
+ try {
216
+ await revokeInvite(relay, session, t.teamId, who);
217
+ }
218
+ catch (e) {
219
+ if (e.status === 404)
220
+ throw new Error(`@${who} has no pending invite to team "${t.name}"`);
221
+ throw e;
222
+ }
223
+ console.log(`${cyan("✓")} cancelled the invite for @${who} to team "${t.name}".`);
224
+ return;
225
+ }
208
226
  case "accept": {
209
- const teams = await listTeams(relay, session);
210
- const q = args.slice(1).join(" ").trim().toLowerCase();
211
- const match = q ? teams.filter((t) => t.teamId === q || t.name.toLowerCase() === q) : teams;
212
- if (match.length === 0)
213
- throw new Error(`no pending invite or team${q ? ` called "${q}"` : ""} for @${session.login}`);
214
- if (match.length > 1)
215
- throw new Error(`several teams and invites (${match.map((t) => `"${t.name}"`).join(", ")}): say which, e.g. mindmeld team accept ${match[0].name}`);
216
- if (match[0].role !== "invited") {
217
- useTeam({ teamId: match[0].teamId, name: match[0].name });
218
- console.log(`${cyan("✓")} this machine now uses team ${bold(match[0].name)}, where you're ${match[0].role}.`);
227
+ const plan = planAccept(await listTeams(relay, session), args.slice(1).join(" "), session.login, "mindmeld team accept");
228
+ if ("text" in plan) {
229
+ if (plan.isError)
230
+ throw new Error(plan.text);
231
+ console.log(plan.text);
232
+ return;
233
+ }
234
+ if ("use" in plan) {
235
+ useTeam({ teamId: plan.use.teamId, name: plan.use.name });
236
+ console.log(`${cyan("✓")} this machine now uses team ${bold(plan.use.name)}, where you're ${plan.use.role}.`);
219
237
  return;
220
238
  }
221
- await acceptInvite(relay, session, match[0].teamId);
222
- useTeam({ teamId: match[0].teamId, name: match[0].name });
223
- console.log(`${cyan("✓")} joined team ${bold(match[0].name)}. A teammate's mindmeld gives this device the team key when one of them is online.`);
239
+ const t = plan.join;
240
+ await acceptInvite(relay, session, t.teamId);
241
+ useTeam({ teamId: t.teamId, name: t.name });
242
+ console.log(`${cyan("✓")} joined team ${bold(t.name)} (${invitedByText(t)}). A teammate's mindmeld gives this device the team key when one of them is online.`);
224
243
  return;
225
244
  }
226
245
  case "remove": {
@@ -254,7 +273,7 @@ async function team(args, yes) {
254
273
  return;
255
274
  }
256
275
  default:
257
- throw new Error(`unknown team command "${sub}" (create, invite, accept, remove, role)`);
276
+ throw new Error(`unknown team command "${sub}" (create, invite, uninvite, accept, remove, role)`);
258
277
  }
259
278
  }
260
279
  function loadConfigOrNull() {
package/dist/daemon.js CHANGED
@@ -2,6 +2,10 @@ import { randomUUID } from "node:crypto";
2
2
  import { EventEmitter } from "node:events";
3
3
  import { GroupChannel } from "./channel.js";
4
4
  import { ACTIVITY_CHECK_MS, ACTIVITY_RESOLUTION_MS, PROTOCOL_VERSION } from "./protocol.js";
5
+ /** A directed payload the channel could not address (e.g. the peer's device is no longer on the team roster). */
6
+ const unreachable = (name) => `can't reach ${name}'s session right now`;
7
+ /** Peer-id ownership bindings kept, so hello spam with random peer ids stays bounded. */
8
+ const MAX_PEER_OWNERS = 1000;
5
9
  export class Daemon extends EventEmitter {
6
10
  opts;
7
11
  peerId = randomUUID();
@@ -15,7 +19,8 @@ export class Daemon extends EventEmitter {
15
19
  askLog = new Map();
16
20
  /**
17
21
  * 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.
22
+ * bye or reply for that peer id from any other login is ignored. Bounded by MAX_PEER_OWNERS: beyond
23
+ * it, the oldest bindings of peers that are not online are forgotten.
19
24
  */
20
25
  peerOwner = new Map();
21
26
  share;
@@ -108,8 +113,12 @@ export class Daemon extends EventEmitter {
108
113
  });
109
114
  ch.on("payload", (p, from) => this.handlePayload(p, from));
110
115
  }
111
- send(p) {
112
- this.channel.send(p);
116
+ /**
117
+ * Hand a payload to the channel. Directed payloads carry their recipient (`to`); presence (hello,
118
+ * bye) never does. False when the channel cannot resolve the recipient (nothing was sent).
119
+ */
120
+ send(p, to) {
121
+ return this.channel.send(p, to);
113
122
  }
114
123
  get connected() {
115
124
  return this.channel.connected;
@@ -173,8 +182,17 @@ export class Daemon extends EventEmitter {
173
182
  if (login === undefined)
174
183
  return true;
175
184
  const owner = this.peerOwner.get(peerId);
176
- if (owner === undefined)
185
+ if (owner === undefined) {
177
186
  this.peerOwner.set(peerId, login);
187
+ if (this.peerOwner.size > MAX_PEER_OWNERS) {
188
+ for (const old of this.peerOwner.keys()) {
189
+ if (this.peerOwner.size <= MAX_PEER_OWNERS)
190
+ break;
191
+ if (!this.peers.has(old) && old !== peerId)
192
+ this.peerOwner.delete(old);
193
+ }
194
+ }
195
+ }
178
196
  return owner === undefined || owner === login;
179
197
  }
180
198
  /** False if a reply to a question came from a login other than the one that owns the asked peer. */
@@ -214,7 +232,7 @@ export class Daemon extends EventEmitter {
214
232
  case "ask":
215
233
  // Only a shared session answers, and only questions addressed to it (or legacy broadcasts).
216
234
  if (this.share && (!p.to || p.to === this.opts.name || p.to === this.peerId))
217
- void this.handleAsk(p, login, owner);
235
+ void this.handleAsk(p, login, owner, from.device);
218
236
  break;
219
237
  case "status": {
220
238
  const pending = this.pending.get(p.id);
@@ -263,14 +281,16 @@ export class Daemon extends EventEmitter {
263
281
  return recent.length > max;
264
282
  }
265
283
  seenAsks = new Set();
266
- async handleAsk(ask, login, owner) {
284
+ async handleAsk(ask, login, owner, device) {
267
285
  if (this.seenAsks.has(ask.id))
268
286
  return; // a resend of a question already being handled
269
287
  this.seenAsks.add(ask.id);
288
+ // Replies go back to the device the question came from (askers never send a hello).
289
+ const asker = { device };
270
290
  const reply = (d) => d.action === "send"
271
- ? this.send({ type: "answer", id: ask.id, from: this.peerId, text: d.text })
272
- : this.send({ type: "decline", id: ask.id, from: this.peerId, reason: d.reason });
273
- const report = (state) => this.send({ type: "status", id: ask.id, from: this.peerId, state });
291
+ ? this.send({ type: "answer", id: ask.id, from: this.peerId, text: d.text }, asker)
292
+ : this.send({ type: "decline", id: ask.id, from: this.peerId, reason: d.reason }, asker);
293
+ const report = (state) => void this.send({ type: "status", id: ask.id, from: this.peerId, state }, asker);
274
294
  report("received");
275
295
  // A verified identity cannot dodge the limit by rotating peer ids.
276
296
  if (this.rateLimited(owner ?? login ?? ask.from)) {
@@ -332,12 +352,13 @@ export class Daemon extends EventEmitter {
332
352
  };
333
353
  timers.push(setTimeout(() => finish({ error: `no answer within ${timeoutSec}s` }), timeoutSec * 1000));
334
354
  // Peers from 0.4 on acknowledge at once; older ones don't, so only hold newer ones to it.
355
+ const to = { peer: target.peer };
335
356
  const payload = { type: "ask", id, from: this.peerId, fromName: this.opts.name, to: target.peer, question, context: opts.context };
336
357
  if ((target.v ?? 0) >= 2) {
337
358
  // Not acknowledged halfway through the window: resend once (a frame can be lost while
338
359
  // the socket reconnects). The answering side ignores duplicate ids.
339
360
  const ackMs = this.opts.ackTimeoutMs ?? 15_000;
340
- timers.push(setTimeout(() => !this.pending.get(id)?.acked && this.send(payload), ackMs / 2));
361
+ timers.push(setTimeout(() => !this.pending.get(id)?.acked && this.send(payload, to), ackMs / 2));
341
362
  timers.push(setTimeout(() => {
342
363
  if (!this.pending.get(id)?.acked) {
343
364
  finish({ error: `${target.name}'s session didn't acknowledge the question. It may have just closed or stopped sharing.` });
@@ -345,14 +366,17 @@ export class Daemon extends EventEmitter {
345
366
  }, ackMs));
346
367
  }
347
368
  this.pending.set(id, { target: target.peer, resolve: finish, onStatus: opts.onStatus, acked: false, expected: 1, declines: [] });
348
- this.send(payload);
369
+ if (!this.send(payload, to))
370
+ finish({ error: unreachable(target.name) });
349
371
  });
350
372
  }
351
373
  snippet(title, text, peer) {
352
374
  const target = this.route(peer);
353
375
  if ("error" in target)
354
376
  return target;
355
- this.send({ type: "snippet", id: randomUUID(), from: this.peerId, to: target.peer, title, text });
377
+ if (!this.send({ type: "snippet", id: randomUUID(), from: this.peerId, to: target.peer, title, text }, { peer: target.peer })) {
378
+ return { error: unreachable(target.name) };
379
+ }
356
380
  return { ok: true, to: target.name };
357
381
  }
358
382
  drainInbox() {
package/dist/mcpteam.js CHANGED
@@ -2,16 +2,16 @@ import { z } from "zod";
2
2
  import { loadSession } from "./auth/session.js";
3
3
  import { DEFAULT_RELAY, relayWarning, saveConfig, teamRelay, withTeam } from "./config.js";
4
4
  import { loadOrCreateIdentity } from "./identity.js";
5
- import { acceptInvite, addDevice, createTeam, deleteMember, formatTeam, getRoster, inviteMember, inviteMessage, listTeams, normLogin, removeAndRotate, setRole, signIn, signInLine, signInState, SIGNED_IN_EXPIRED, teamLine, } from "./teamapi.js";
5
+ import { acceptInvite, addDevice, createTeam, deleteMember, formatTeam, getRoster, inviteMember, inviteMessage, invitedByText, listTeams, normLogin, planAccept, removeAndRotate, revokeInvite, setRole, signIn, signInLine, signInState, SIGNED_IN_EXPIRED, teamLine, } from "./teamapi.js";
6
6
  import { SIGN_IN_EXPIRED, TeamChannel } from "./teamchannel.js";
7
7
  import { rotate } from "./teamkeys.js";
8
8
  const NO_TEAM = "You're not in a team yet. Create one with create_team, or accept an invite with accept_invite.";
9
- /** "invite to "core"" or "team "core" (member)". */
10
- const describeEntry = (t) => (t.role === "invited" ? `invite to "${t.name}"` : `team "${t.name}" (${t.role})`);
9
+ /** "invite to "core" (invited by @alice)" or "team "core" (member)". */
10
+ const describeEntry = (t) => (t.role === "invited" ? `invite to "${t.name}" (${invitedByText(t)})` : `team "${t.name}" (${t.role})`);
11
11
  const text = (t, isError = false) => ({ content: [{ type: "text", text: t }], isError });
12
12
  /**
13
13
  * GitHub sign-in and teams for the MCP server: registers login, create_team, invite_member,
14
- * accept_invite, team, remove_member and set_role, and builds the TeamChannel when config.json has a
14
+ * revoke_invite, accept_invite, team, remove_member and set_role, and builds the TeamChannel when config.json has a
15
15
  * team. Every tool answers with sign-in guidance when the session is missing or expired.
16
16
  */
17
17
  export function setupTeams(host) {
@@ -194,35 +194,48 @@ export function setupTeams(host) {
194
194
  return text(inviteMessage(who, r.team.name));
195
195
  });
196
196
  });
197
+ server.registerTool("revoke_invite", {
198
+ title: "Cancel an invite",
199
+ description: "Cancel a pending invite to the team (admins only), so that GitHub login can no longer accept it. Only when the user asks.",
200
+ inputSchema: { login: z.string().min(1).describe("The invited GitHub login") },
201
+ }, async ({ login: who }) => {
202
+ const r = ready(true);
203
+ if (typeof r === "string")
204
+ return text(r, true);
205
+ const target = normLogin(who);
206
+ try {
207
+ await revokeInvite(r.relay, r.session, r.team.teamId, target);
208
+ }
209
+ catch (e) {
210
+ if (e.status === 404)
211
+ return text(`@${target} has no pending invite to team "${r.team.name}".`, true);
212
+ return text(e.message, true);
213
+ }
214
+ return text(`Cancelled the invite for @${target} to team "${r.team.name}". They can no longer accept it.`);
215
+ });
197
216
  server.registerTool("accept_invite", {
198
217
  title: "Accept a team invite (or use a team you're in)",
199
- description: "Accept an invite to a mindmeld team and connect this machine to it. Also connects this machine to a team the user already belongs to. " +
200
- "Optional team name or id when there are several.",
201
- inputSchema: { team: z.string().optional().describe("Team name or id, if there is more than one") },
218
+ description: "Accept an invite to a mindmeld team and connect this machine to it, or connect this machine to a team the user already belongs to. " +
219
+ "Without a team it never joins anything: it lists pending invites and who sent each one, so the user can choose. " +
220
+ "Pass the team name or id (only one the user named) to accept that invite.",
221
+ inputSchema: { team: z.string().optional().describe("Team name or id, as the user named it") },
202
222
  }, async ({ team }) => {
203
223
  const r = ready(false);
204
224
  if (typeof r === "string")
205
225
  return text(r, true);
206
226
  return attempt(async () => {
207
- const teams = await listTeams(r.relay, r.session);
208
- const q = team?.trim().toLowerCase();
209
- const match = q ? teams.filter((t) => t.teamId === q || t.name.toLowerCase() === q) : teams;
210
- if (match.length === 0) {
211
- return text(q && teams.length
212
- ? `No invite to or team called "${team}". Yours: ${teams.map(describeEntry).join(", ")}.`
213
- : `No pending invites for @${r.session.login}. Ask a team admin to invite your GitHub login (@${r.session.login}).`, true);
214
- }
215
- if (match.length > 1) {
216
- return text(`You have ${match.map((t) => `${describeEntry(t)} (${t.teamId})`).join(", ")}. Which one? Call accept_invite with team set.`, true);
217
- }
218
- const t = match[0];
219
- if (t.role !== "invited") {
227
+ const plan = planAccept(await listTeams(r.relay, r.session), team, r.session.login, "/mindmeld:team accept");
228
+ if ("text" in plan)
229
+ return text(plan.text, plan.isError);
230
+ if ("use" in plan) {
231
+ const t = plan.use;
220
232
  const replaced = useTeam(r, { teamId: t.teamId, name: t.name });
221
233
  return text(`This machine now uses team "${t.name}", where you're ${t.role}.${replaced}`);
222
234
  }
235
+ const t = plan.join;
223
236
  await acceptInvite(r.relay, r.session, t.teamId);
224
237
  const replaced = useTeam(r, { teamId: t.teamId, name: t.name });
225
- return text(`Joined team "${t.name}" as @${r.session.login}.${replaced}\n` +
238
+ return text(`Joined team "${t.name}" as @${r.session.login} (${invitedByText(t)}).${replaced}\n` +
226
239
  "A teammate's mindmeld gives this device the team key the next time one of them is online; /mindmeld:status shows progress. " +
227
240
  "Your sessions stay private until you run /mindmeld:share in one.");
228
241
  });
package/dist/teamapi.js CHANGED
@@ -66,7 +66,19 @@ export const createTeam = (relay, s, name) => teamCall(relay, s, "POST", "/v1/te
66
66
  export const listTeams = (relay, s) => teamCall(relay, s, "GET", "/v1/teams");
67
67
  export const getRoster = (relay, s, teamId, timeoutMs) => teamCall(relay, s, "GET", `/v1/teams/${teamId}`, undefined, timeoutMs);
68
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`);
69
+ /** Cancel the pending invite for `login` (admins). */
70
+ export const revokeInvite = (relay, s, teamId, login) => teamCall(relay, s, "DELETE", `/v1/teams/${teamId}/invites/${encodeURIComponent(normLogin(login))}`);
71
+ /** Accept an invite. A 403 (no invite for this login) means it was cancelled or already used. */
72
+ export async function acceptInvite(relay, s, teamId) {
73
+ try {
74
+ return await teamCall(relay, s, "POST", `/v1/teams/${teamId}/accept`);
75
+ }
76
+ catch (e) {
77
+ if (e.status === 403)
78
+ throw new TeamApiError("this invite was cancelled or already used", 403);
79
+ throw e;
80
+ }
81
+ }
70
82
  /** Add this device to a team its login is already in (a second machine). */
71
83
  export const addDevice = (relay, s, teamId) => teamCall(relay, s, "POST", `/v1/teams/${teamId}/devices`);
72
84
  export const deleteMember = (relay, s, teamId, login) => teamCall(relay, s, "DELETE", `/v1/teams/${teamId}/members/${encodeURIComponent(normLogin(login))}`);
@@ -106,6 +118,50 @@ export function inviteMessage(login, teamName) {
106
118
  `If @${who} hasn't signed in to mindmeld yet, that's fine: they'll see the invite after signing in.`,
107
119
  ].join("\n");
108
120
  }
121
+ /** "invited by @alice", or "invited by an admin" when the relay doesn't know who. */
122
+ export const invitedByText = (t) => `invited by ${t.invitedBy ? `@${t.invitedBy}` : "an admin"}`;
123
+ /**
124
+ * Decide what `accept [team]` does with the caller's teams and invites. With no team named it never
125
+ * joins anything: pending invites are listed with who sent them; only when there are none and the
126
+ * caller is in exactly one team does it switch to that team. `acceptCmd` is how the user accepts
127
+ * ("/mindmeld:team accept" or "mindmeld team accept").
128
+ */
129
+ export function planAccept(teams, query, login, acceptCmd) {
130
+ const describe = (t) => (t.role === "invited" ? `invite to "${t.name}" (${invitedByText(t)})` : `team "${t.name}" (${t.role})`);
131
+ const q = query?.trim().toLowerCase();
132
+ if (q) {
133
+ const match = teams.filter((t) => t.teamId === q || t.name.toLowerCase() === q);
134
+ if (match.length === 0) {
135
+ return {
136
+ text: teams.length ? `No invite to or team called "${query.trim()}". Yours: ${teams.map(describe).join(", ")}.` : noInvites(login),
137
+ isError: true,
138
+ };
139
+ }
140
+ if (match.length > 1) {
141
+ return { text: `Several have that name: ${match.map((t) => `${describe(t)} (${t.teamId})`).join(", ")}. Say which by its id, e.g. ${acceptCmd} ${match[0].teamId}`, isError: true };
142
+ }
143
+ return match[0].role === "invited" ? { join: match[0] } : { use: match[0] };
144
+ }
145
+ const pending = teams.filter((t) => t.role === "invited");
146
+ if (pending.length) {
147
+ const collides = (t) => teams.filter((o) => o.name.toLowerCase() === t.name.toLowerCase()).length > 1;
148
+ return {
149
+ text: [
150
+ pending.length === 1 ? "You have a pending team invite:" : `You have ${pending.length} pending team invites:`,
151
+ ...pending.map((t) => `- ${t.name}${collides(t) ? ` (${t.teamId})` : ""}: ${invitedByText(t)}`),
152
+ "",
153
+ `Nothing was accepted. To join, run ${acceptCmd} <name>${pending.some(collides) ? " (use the team id when two share a name)" : ""}, e.g. ${acceptCmd} ${collides(pending[0]) ? pending[0].teamId : pending[0].name}`,
154
+ ].join("\n"),
155
+ isError: false,
156
+ };
157
+ }
158
+ if (teams.length === 0)
159
+ return { text: noInvites(login), isError: true };
160
+ if (teams.length === 1)
161
+ return { use: teams[0] };
162
+ return { text: `You're in ${teams.map((t) => `${describe(t)} (${t.teamId})`).join(", ")}. Which one? Say which, e.g. ${acceptCmd} ${teams[0].name}`, isError: true };
163
+ }
164
+ const noInvites = (login) => `No pending invites for @${login}. Ask a team admin to invite your GitHub login (@${login}).`;
109
165
  const roleText = (roster, uid) => roster.members.find((m) => m.uid === uid)?.role;
110
166
  /** "Team: core (you're admin)". `uid` is the signed-in GitHub id. */
111
167
  export function teamLine(name, roster, uid) {
@@ -120,6 +176,7 @@ const EVENTS = {
120
176
  rotated: (by, s) => `${by} rotated the team key (epoch ${s})`,
121
177
  removed: (by, s) => `${by} removed ${s}`,
122
178
  role: (by, s) => `${by} changed the role of ${s}`,
179
+ "invite-revoked": (by, s) => `${by} cancelled the invite for ${s}`,
123
180
  };
124
181
  /** The `team` tool's text: members, roles, devices (fingerprint, key), invites and the recent log. */
125
182
  export function formatTeam(roster, me) {
@@ -133,7 +190,10 @@ export function formatTeam(roster, me) {
133
190
  lines.push(` device ${fingerprint(d.signPub)}: ${key}${d.deviceId === me.deviceId ? " (this device)" : ""}`);
134
191
  }
135
192
  }
136
- lines.push("", `Pending invites: ${roster.invites.length ? roster.invites.map((l) => `@${l}`).join(", ") : "none"}`);
193
+ // inviteDetails (relays from 0.6.1) says who invited; older relays send only the logins.
194
+ const invites = roster.inviteDetails ?? roster.invites.map((login) => ({ login, invitedBy: null }));
195
+ const inviteText = (i) => `@${i.login}${i.invitedBy ? ` (invited by @${i.invitedBy})` : ""}`;
196
+ lines.push("", `Pending invites: ${invites.length ? invites.map(inviteText).join(", ") : "none"}`);
137
197
  const log = roster.log.slice(-20).reverse();
138
198
  lines.push("", "Recent activity:");
139
199
  if (log.length === 0)
@@ -3,8 +3,9 @@ import WebSocket from "ws";
3
3
  import { z } from "zod";
4
4
  import { sameRelay } from "./config.js";
5
5
  import { Payload, PING_INTERVAL_MS } from "./protocol.js";
6
- import { openFrame, sealFrame } from "./teamcrypto.js";
6
+ import { openDirect, openFrame, sealDirect, sealFrame } from "./teamcrypto.js";
7
7
  import { distributeKeys, fetchRoster, fetchTeamKeys, httpBase, rosterDevices, WAITING_FOR_KEY } from "./teamkeys.js";
8
+ import { VERSION } from "./version.js";
8
9
  /** Shown when the relay refuses the session token (or it has expired locally). */
9
10
  export const SIGN_IN_EXPIRED = "sign-in expired; run /mindmeld:login";
10
11
  /**
@@ -16,8 +17,18 @@ export function backoffDelay(failures, baseMs, maxMs, rand = Math.random()) {
16
17
  return Math.round(exp * (0.8 + 0.4 * rand));
17
18
  }
18
19
  /** Close codes the relay uses on team sockets. */
19
- export const TEAM_CLOSE = { removed: 4001, noKey: 4003, noTeam: 4004, signedOut: 4401 };
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`;
20
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;
21
32
  /** What the relay sends on a team socket. `c`, `uid` and `login` are routing hints only, never identity. */
22
33
  const TeamMessage = z.discriminatedUnion("t", [
23
34
  z.object({ t: z.literal("server"), latest: z.string(), minimum: z.string(), epoch: z.number() }),
@@ -25,6 +36,7 @@ const TeamMessage = z.discriminatedUnion("t", [
25
36
  z.object({ t: z.literal("left"), c: z.string(), uid: z.number().int(), login: z.string() }),
26
37
  z.object({ t: z.literal("roster") }),
27
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() }),
28
40
  ]);
29
41
  const RETRY_BASE_MS = 2000;
30
42
  const RETRY_MAX_MS = 60_000;
@@ -40,9 +52,15 @@ const MAX_HELD = 64;
40
52
  /** Key-distribution passes per refresh (each write is followed by a refetch). */
41
53
  const MAX_DISTRIBUTE_PASSES = 3;
42
54
  /**
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.
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.
46
64
  * The roster and verified keys are fetched on start, on reconnect, and whenever the relay says the
47
65
  * roster changed. Each fetch is followed by `distributeKeys` (see `ensureTeamKeys`): an admin creates
48
66
  * the first key, a device holding the key delivers it to roster devices that lack one, and a device
@@ -57,10 +75,17 @@ export class TeamChannel extends EventEmitter {
57
75
  admitted = false;
58
76
  stopped = false;
59
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();
60
84
  keys = new Map();
61
85
  currentEpoch = 0;
62
86
  /** Relay connection id -> the verified GitHub id of its first frame. */
63
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. */
64
89
  held = [];
65
90
  refreshing = null;
66
91
  refreshAgain = false;
@@ -79,6 +104,8 @@ export class TeamChannel extends EventEmitter {
79
104
  finished = false;
80
105
  /** Encrypted frames this client has sent; lets tests check that idle sessions stay quiet. */
81
106
  framesSent = 0;
107
+ /** Frames from the relay dropped for failing a check (bad signature, wrong recipient, stamp mismatch, wrong kind...). */
108
+ framesDropped = 0;
82
109
  constructor(opts) {
83
110
  super();
84
111
  this.opts = opts;
@@ -165,13 +192,31 @@ export class TeamChannel extends EventEmitter {
165
192
  const problem = this.keyProblems.find((p) => p.includes(`epoch ${this.currentEpoch} `));
166
193
  return this.reason ?? problem ?? (this.waiting && !this.admitted ? WAITING_FOR_KEY : null);
167
194
  }
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 }));
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 }));
174
218
  this.framesSent++;
219
+ return true;
175
220
  }
176
221
  setReason(r) {
177
222
  if (r === this.reason)
@@ -222,8 +267,12 @@ export class TeamChannel extends EventEmitter {
222
267
  this.refreshing = null;
223
268
  }
224
269
  const held = this.held.splice(0);
225
- for (const h of held)
226
- this.receive(h.f, h.c, h.uid, false);
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
+ }
227
276
  })();
228
277
  return this.refreshing;
229
278
  }
@@ -250,7 +299,8 @@ export class TeamChannel extends EventEmitter {
250
299
  this.emit("disconnected");
251
300
  }
252
301
  this.authRefused = false;
253
- const url = `${httpBase(this.opts.relayHttp).replace(/^http/, "ws")}/v1/teams/${this.opts.teamId}/ws`;
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}`;
254
304
  // closeTimeout: once close frames are exchanged, do not wait 30s for a peer that keeps TCP half open
255
305
  // (seen with relay-initiated closes of hibernated sockets); "closed" must arrive promptly.
256
306
  const ws = new WebSocket(url, { headers: { authorization: `Bearer ${this.opts.session.token}` }, closeTimeout: CLOSE_TIMEOUT_MS });
@@ -298,6 +348,8 @@ export class TeamChannel extends EventEmitter {
298
348
  return this.terminal(code, "removed from team");
299
349
  if (code === TEAM_CLOSE.noTeam)
300
350
  return this.terminal(code, "no such team");
351
+ if (code === TEAM_CLOSE.tooOld)
352
+ return this.terminal(code, tooOldForTeams(this.opts.version ?? VERSION));
301
353
  this.emit("closed", code, reason);
302
354
  if (code === TEAM_CLOSE.noKey) {
303
355
  this.setReason(this.waiting ? WAITING_FOR_KEY : "no team key yet");
@@ -338,6 +390,9 @@ export class TeamChannel extends EventEmitter {
338
390
  break;
339
391
  case "left":
340
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);
341
396
  this.emit("left", msg.c);
342
397
  break;
343
398
  case "roster":
@@ -346,40 +401,86 @@ export class TeamChannel extends EventEmitter {
346
401
  case "msg":
347
402
  this.receive(msg.f, msg.c, msg.uid, true);
348
403
  break;
404
+ case "dm":
405
+ this.receiveDirect(msg.f, msg.c, msg.uid, true);
406
+ break;
349
407
  }
350
408
  }
351
409
  /**
352
- * Verify and deliver one frame. The sender is the GitHub id the signature proves (via the roster);
410
+ * Verify and deliver one broadcast (team-key) frame. The sender is the GitHub id the signature proves (via the roster);
353
411
  * the relay's uid stamp must agree with it, and a connection id stays bound to the uid of its first
354
412
  * frame. The login delivered with it is the roster's, for display.
355
413
  */
356
414
  receive(f, c, stamped, mayHold) {
357
415
  if (mayHold && !this.keys.has(f.e) && f.e > this.currentEpoch) {
358
416
  // 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));
417
+ this.hold({ t: "msg", f, c, uid: stamped });
362
418
  return;
363
419
  }
364
420
  const opened = openFrame(f, this.keys, this.roster);
365
- if (!opened)
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++;
366
433
  return;
367
- if (opened.uid !== stamped)
434
+ }
435
+ if (mayHold && !this.roster.has(f.dev)) {
436
+ this.hold({ t: "dm", f, c, uid: stamped });
368
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;
369
452
  const bound = this.cidUid.get(c);
370
453
  if (bound !== undefined && bound !== opened.uid)
371
- return;
454
+ return false;
372
455
  let p;
373
456
  try {
374
457
  const parsed = Payload.safeParse(JSON.parse(opened.payload));
375
458
  if (!parsed.success)
376
- return;
459
+ return false;
377
460
  p = parsed.data;
378
461
  }
379
462
  catch {
380
- return;
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
+ }
381
481
  }
382
482
  this.cidUid.set(c, opened.uid);
383
- this.emit("payload", p, { cid: c, login: opened.login, uid: opened.uid });
483
+ this.emit("payload", p, { cid: c, login: opened.login, uid: opened.uid, device });
484
+ return true;
384
485
  }
385
486
  }
@@ -15,28 +15,29 @@ function sealKey(shared, ephPub, boxPub) {
15
15
  * Seal bytes to one device's X25519 key (anonymous sender).
16
16
  * Fresh ephemeral X25519 keypair; shared = X25519(ephPriv, boxPub);
17
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).
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).
19
20
  * The key is single-use (fresh ephemeral per call), so nonce reuse cannot occur.
20
21
  */
21
- export function sealToDevice(boxPub, plaintext) {
22
+ export function sealToDevice(boxPub, plaintext, aad) {
22
23
  const recipient = hexToBytes(boxPub);
23
24
  const ephPriv = x25519.utils.randomSecretKey();
24
25
  const ephPub = x25519.getPublicKey(ephPriv);
25
26
  const key = sealKey(x25519.getSharedSecret(ephPriv, recipient), ephPub, recipient);
26
- return Buffer.concat([ephPub, sealBytes(key, plaintext)]).toString("base64");
27
+ return Buffer.concat([ephPub, sealBytes(key, plaintext, aad)]).toString("base64");
27
28
  }
28
29
  /**
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.
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.
31
32
  */
32
- export function openFromDevice(id, sealed) {
33
+ export function openFromDevice(id, sealed, aad) {
33
34
  try {
34
35
  const buf = Buffer.from(sealed, "base64");
35
36
  if (buf.length < 32 + 28)
36
37
  return null;
37
38
  const ephPub = buf.subarray(0, 32);
38
39
  const key = sealKey(x25519.getSharedSecret(hexToBytes(id.boxPriv), ephPub), ephPub, hexToBytes(id.boxPub));
39
- const out = openBytes(key, buf.subarray(32));
40
+ const out = openBytes(key, buf.subarray(32), aad);
40
41
  return out === null ? null : new Uint8Array(out);
41
42
  }
42
43
  catch {
@@ -81,3 +82,49 @@ export function openFrame(f, keys, roster) {
81
82
  return null;
82
83
  }
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
+ }
package/dist/teamkeys.js CHANGED
@@ -23,7 +23,7 @@ export function rosterDevices(roster) {
23
23
  const out = new Map();
24
24
  for (const m of roster.members)
25
25
  for (const d of m.devices)
26
- out.set(d.deviceId, { uid: m.uid, login: m.login, signPub: d.signPub, role: m.role });
26
+ out.set(d.deviceId, { uid: m.uid, login: m.login, signPub: d.signPub, boxPub: d.boxPub, role: m.role });
27
27
  return out;
28
28
  }
29
29
  /** Why `w` (the wrap for epoch `epoch`) must be dropped, or the unwrapped key if it is sound. */
package/dist/version.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /** This client's version. A test keeps it equal to package.json. */
2
- export const VERSION = "0.6.0";
2
+ export const VERSION = "0.7.0";
3
3
  /** Compares dotted numeric versions ("0.4.2" vs "0.5.0"): negative, zero or positive. */
4
4
  export function compareVersions(a, b) {
5
5
  const pa = a.split(/[.-]/).map((n) => parseInt(n, 10) || 0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mindmeld-mcp",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "mindmeld: let your Claude Code session ask a teammate's Claude Code session questions. E2E encrypted, read-only answers, approved in Claude.",
5
5
  "type": "module",
6
6
  "license": "MIT",