@benjilabs/beaconfire-mcp 0.1.1 → 0.2.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
@@ -160,6 +160,69 @@ class Conn {
160
160
  });
161
161
  });
162
162
  }
163
+ /**
164
+ * One live subscription per filter. A CLOSED with auth-required runs AUTH and re-sends once. Resolves
165
+ * when every subscription has answered EOSE; `onend` runs once if any of them is closed afterwards.
166
+ */
167
+ async follow(filters, onevent, onend) {
168
+ const relay = await this.relay();
169
+ const subs = [];
170
+ let closing = false;
171
+ const close = () => {
172
+ closing = true;
173
+ for (const s of subs)
174
+ s.close();
175
+ };
176
+ const ended = (_reason) => {
177
+ if (closing)
178
+ return;
179
+ close();
180
+ onend();
181
+ };
182
+ try {
183
+ for (const filter of filters) {
184
+ let r = await this.#open(relay, filter, onevent, ended);
185
+ if (r.closed !== undefined && r.closed.includes("auth-required")) {
186
+ await this.#authenticate(relay);
187
+ r = await this.#open(relay, filter, onevent, ended);
188
+ }
189
+ if (r.sub === undefined) {
190
+ throw new Error(`relay ${this.cfg.url}: ${r.closed?.includes("auth-required") ? "auth failed" : `REQ closed: ${r.closed}`}`);
191
+ }
192
+ subs.push(r.sub);
193
+ }
194
+ }
195
+ catch (e) {
196
+ close();
197
+ throw e;
198
+ }
199
+ return { close };
200
+ }
201
+ /** Send a live-only REQ; resolves at its EOSE, or with the CLOSED reason if it was closed first. */
202
+ #open(relay, filter, onevent, onend) {
203
+ return new Promise((resolve, reject) => {
204
+ let ready = false;
205
+ const timer = setTimeout(() => {
206
+ sub.close();
207
+ reject(new Error(`relay ${this.cfg.url}: EOSE timed out`));
208
+ }, TIMEOUT.eose);
209
+ const sub = relay.subscribe([{ ...filter, limit: 0 }], {
210
+ onevent,
211
+ oneose: () => {
212
+ ready = true;
213
+ clearTimeout(timer);
214
+ resolve({ sub });
215
+ },
216
+ onclose: (reason) => {
217
+ clearTimeout(timer);
218
+ if (ready)
219
+ onend(reason);
220
+ else
221
+ resolve({ closed: reason });
222
+ },
223
+ });
224
+ });
225
+ }
163
226
  close() {
164
227
  this.#relay?.close();
165
228
  }
@@ -197,6 +260,39 @@ export class RealRelayPool {
197
260
  const settled = await Promise.allSettled(this.#conns.map((c) => pagedFetch((f) => c.page(f), filter, maxLimit)));
198
261
  return mergeSettled(settled, opts.strict === true);
199
262
  }
263
+ async follow(filters, onevent) {
264
+ let started = -1;
265
+ let ended = 0;
266
+ let done;
267
+ const closed = new Promise((res) => {
268
+ done = res;
269
+ });
270
+ const check = () => {
271
+ if (started >= 0 && ended >= started)
272
+ done();
273
+ };
274
+ const settled = await Promise.allSettled(this.#conns.map((c) => c.follow(filters, onevent, () => {
275
+ ended++;
276
+ check();
277
+ })));
278
+ const ok = settled.filter((s) => s.status === "fulfilled");
279
+ const failed = settled.filter((s) => s.status === "rejected");
280
+ for (const f of failed)
281
+ log(String(f.reason.message));
282
+ if (ok[0] === undefined)
283
+ throw failed[0].reason;
284
+ started = ok.length;
285
+ check();
286
+ return {
287
+ closed,
288
+ close: () => {
289
+ for (const s of ok)
290
+ s.value.close();
291
+ ended = started;
292
+ check();
293
+ },
294
+ };
295
+ }
200
296
  publish(event) {
201
297
  return Promise.all(this.#conns.map((c) => c.publish(event)));
202
298
  }
package/dist/roster.js CHANGED
@@ -8,7 +8,7 @@ const HEX64 = /^[0-9a-f]{64}$/;
8
8
  */
9
9
  export class Roster {
10
10
  entries = [];
11
- /** Group name to member pubkeys, from the orchestrator's `d=group:<name>` sets (NIP-51 follow sets). */
11
+ /** Group name to member pubkeys, from the orchestrator's (site-signed) `d=group:<name>` sets; read for the `#h` REQs of old senders, never to send (AB-57). */
12
12
  groups = new Map();
13
13
  fetchedAt = null;
14
14
  #lastOk = false;
@@ -91,9 +91,6 @@ export class Roster {
91
91
  groupsOf(pubkey) {
92
92
  return [...this.groups].filter(([, m]) => m.has(pubkey)).map(([g]) => g);
93
93
  }
94
- inGroup(group, pubkey) {
95
- return this.groups.get(group)?.has(pubkey) ?? false;
96
- }
97
94
  nameOf(pubkey) {
98
95
  return this.entries.find((e) => e.pubkey === pubkey)?.name ?? null;
99
96
  }
package/dist/send.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { SESSION_PATTERN } from "./config.js";
2
2
  import { ToolError } from "./deps.js";
3
3
  import { buildEnvelope } from "./envelope.js";
4
+ import { plainGroupRefusal, readOwnGroups } from "./groups.js";
4
5
  import { makeWrap } from "./signer.js";
5
6
  /** NIP-17 line 106: "more than 10 participants" need another scheme. Participants include the sender. */
6
7
  const MAX_SEALED_PARTICIPANTS = 10;
@@ -14,35 +15,40 @@ function overCap(participants) {
14
15
  * the worst-case sealed wrap of a body this size is about 19.3 KB.
15
16
  */
16
17
  export const MAX_BODY_BYTES = 4096;
17
- function unknownRecipient(deps, input) {
18
+ function unknownRecipient(deps, input, hint = "") {
18
19
  const names = deps.roster.names();
19
- return new ToolError(`unknown recipient "${input}"; roster names: ${names.length ? names.join(", ") : "(none)"}`);
20
+ return new ToolError(`unknown recipient "${input}"; roster names: ${names.length ? names.join(", ") : "(none)"}${hint}`);
20
21
  }
21
22
  /**
22
- * The members other than me of group `name`, for a sealed send. Every refusal is before any wrap is made:
23
- * the reader drops an author who is not in the group, and the relay refuses a wrap to an unrostered key.
23
+ * The members other than me of group `name`, for a sealed send, from the agent's own set read strictly
24
+ * from the relay now (AB-57): a removed member must not receive, and a site-signed set is never used to
25
+ * send. Every refusal is before any wrap is made.
24
26
  */
25
- function sealedGroupMembers(deps, name) {
27
+ async function sealedGroupMembers(deps, name) {
26
28
  const me = deps.signer.pubkey;
27
- const set = deps.roster.groups.get(name);
28
- if (!set || set.size === 0) {
29
- const names = [...deps.roster.groups.keys()];
30
- throw new ToolError(`unknown group "${name}"; groups: ${names.length ? names.join(", ") : "(none)"}`);
29
+ const own = await readOwnGroups(deps, true);
30
+ const set = own.get(name);
31
+ if (set?.members === null) {
32
+ throw new ToolError(`group "${name}" is unreadable (a set exists that this key cannot decrypt); nothing was sent`);
31
33
  }
32
- if (!set.has(me))
33
- throw new ToolError(`you are not a member of group "${name}"`);
34
- const offRoster = [...set].filter((p) => !deps.roster.has(p));
35
- if (offRoster.length > 0) {
36
- throw new ToolError(`group "${name}" has members who are not on the roster: ${offRoster.join(", ")}`);
34
+ if (set === undefined && deps.roster.groups.has(name)) {
35
+ throw new ToolError(`group "${name}" exists only as a set signed by your account; create your own with beacon_group {action: "create", name: "${name}", members: [...]} (beacon_group list shows its members); nothing was sent`);
36
+ }
37
+ const others = (set?.members ?? []).filter((p) => p !== me);
38
+ if (others.length === 0) {
39
+ const names = [...own].filter(([, g]) => (g.members ?? []).length > 0).map(([n]) => n);
40
+ throw new ToolError(`group "${name}" is unknown or has no members, so nothing was sent. Create it with beacon_group {action: "create", name: "${name}", members: [...]}; your groups: ${names.length ? names.join(", ") : "(none)"}`);
41
+ }
42
+ if (others.length + 1 > MAX_SEALED_PARTICIPANTS)
43
+ throw overCap(others.length + 1);
44
+ // A set written by another client may hold a key NIP-44 cannot use; refuse before the first wrap.
45
+ const bad = others.filter((p) => !deps.signer.canSealTo(p));
46
+ if (bad.length > 0) {
47
+ throw new ToolError(`group "${name}" holds keys that cannot be sealed to: ${bad.join(", ")}; nothing was sent`);
37
48
  }
38
- const others = [...set].filter((p) => p !== me);
39
- if (others.length === 0)
40
- throw new ToolError(`group "${name}" has no other members`);
41
- if (set.size > MAX_SEALED_PARTICIPANTS)
42
- throw overCap(set.size);
43
49
  return others;
44
50
  }
45
- export function resolveTarget(deps, to, sealed) {
51
+ export async function resolveTarget(deps, to, sealed) {
46
52
  if (deps.roster.status() === "missing") {
47
53
  throw new ToolError("roster not available: no roster event from the orchestrator was found");
48
54
  }
@@ -60,15 +66,24 @@ export function resolveTarget(deps, to, sealed) {
60
66
  const name = to.slice("group:".length);
61
67
  if (!name)
62
68
  throw new ToolError("group name is empty");
63
- return { kind: "group", name, pubkeys: sealed ? sealedGroupMembers(deps, name) : [] };
69
+ if (!sealed)
70
+ throw new ToolError(plainGroupRefusal(name));
71
+ return { kind: "group", name, pubkeys: await sealedGroupMembers(deps, name) };
64
72
  }
65
73
  const pk = deps.roster.resolve(to);
66
74
  if (pk === null)
67
- throw unknownRecipient(deps, to);
75
+ throw unknownRecipient(deps, to, "; or a 64-hex pubkey");
68
76
  if (pk === me)
69
77
  throw new ToolError("cannot send to yourself");
70
- if (!deps.roster.has(pk))
71
- throw unknownRecipient(deps, to);
78
+ if (!deps.roster.has(pk)) {
79
+ // Off the account roster (AB-54). The relay checks the recipient of a kind 1059 only (allowlist.mjs rules 4
80
+ // and 6); it admits any plain kind 7400 from a roster author, so the client is the only gate on a plain send.
81
+ if (!sealed) {
82
+ throw new ToolError("a plain send cannot leave your account: the relay does not check the recipient; send sealed");
83
+ }
84
+ if (!deps.signer.canSealTo(pk))
85
+ throw new ToolError("to is not a valid public key");
86
+ }
72
87
  return { kind: "direct", pubkeys: [pk] };
73
88
  }
74
89
  function recipientsOf(deps, pubkeys) {
@@ -104,7 +119,7 @@ function byRelay(perEvent) {
104
119
  return [...rows.values()];
105
120
  }
106
121
  /** Publish `events`; throws if one reached no relay. */
107
- async function publishAll(deps, events) {
122
+ export async function publishAll(deps, events) {
108
123
  const perEvent = await publishEach(deps, events);
109
124
  const unreached = perEvent.filter((results) => !results.some((r) => r.ok)).length;
110
125
  const published = byRelay(perEvent);
@@ -115,7 +130,7 @@ async function publishAll(deps, events) {
115
130
  return published;
116
131
  }
117
132
  /** `session` names the addressee's session; `from_session` is this server's own, on every send. */
118
- function sessionTags(deps, session) {
133
+ export function sessionTags(deps, session) {
119
134
  const tags = [];
120
135
  if (session !== null)
121
136
  tags.push(["session", session]);
@@ -142,12 +157,41 @@ function addresseeSession(deps, a, target) {
142
157
  return known.fromSession;
143
158
  return null;
144
159
  }
160
+ /** A sealed send that did not reach every wrap's relay. `delivered` holds the recipients (not me) whose wrap a relay took. */
161
+ export class PartialDelivery extends ToolError {
162
+ delivered;
163
+ constructor(message, delivered) {
164
+ super(message);
165
+ this.delivered = delivered;
166
+ }
167
+ }
168
+ /**
169
+ * Seal `rumor` and wrap it to each of `recipients` plus a copy to self (NIP-17 / NIP-59), then publish.
170
+ * Throws `PartialDelivery` (a `ToolError` with the same text a sealed send always gave) when a wrap reached no relay.
171
+ */
172
+ export async function wrapAndPublish(deps, rumor, recipients, expiration, now) {
173
+ const addressed = [...recipients, deps.signer.pubkey];
174
+ const wraps = addressed.map((r) => makeWrap(deps.signer.seal(rumor, r), r, expiration, now));
175
+ const perWrap = await publishEach(deps, wraps);
176
+ const failed = addressed.flatMap((r, i) => perWrap[i]?.some((x) => x.ok) ? [] : [{ pubkey: r, results: perWrap[i] ?? [] }]);
177
+ if (failed.length > 0) {
178
+ const label = (p) => p === deps.signer.pubkey ? "self copy" : (deps.roster.nameOf(p) ?? p);
179
+ const why = (rs) => rs.map((x) => `${x.relay}: ${x.error ?? "failed"}`).join("; ");
180
+ const deliveredKeys = addressed.filter((r) => !failed.some((f) => f.pubkey === r));
181
+ const delivered = deliveredKeys.map(label);
182
+ const state = delivered.length ? "partly delivered" : "not delivered";
183
+ const notDelivered = failed.map((f) => `${label(f.pubkey)} (${why(f.results)})`).join(", ");
184
+ throw new PartialDelivery(`sealed send ${state}: delivered to ${delivered.length ? delivered.join(", ") : "nobody"}; NOT delivered to ${notDelivered}; id ${rumor.id}`, deliveredKeys.filter((r) => r !== deps.signer.pubkey));
185
+ }
186
+ return byRelay(perWrap);
187
+ }
145
188
  /** One rumor, then seal and wrap per recipient plus a copy to self (NIP-17 / NIP-59). */
146
189
  export async function sendSealed(deps, recipients, envelope, session = null, group) {
147
190
  const now = deps.now();
148
191
  const tags = recipients.map((r) => ["p", r]);
192
+ // `h` for a server not yet upgraded; `subject` is the label of record (NIP-17, `17.md` line 19).
149
193
  if (group !== undefined)
150
- tags.push(["h", group]);
194
+ tags.push(["h", group], ["subject", group]);
151
195
  tags.push(...sessionTags(deps, session));
152
196
  if (envelope.re)
153
197
  tags.push(["e", envelope.re, "", "reply"]);
@@ -158,24 +202,13 @@ export async function sendSealed(deps, recipients, envelope, session = null, gro
158
202
  tags,
159
203
  });
160
204
  const expiration = envelope.ttl === undefined ? undefined : now + envelope.ttl;
161
- const addressed = [...recipients, deps.signer.pubkey];
162
- const wraps = addressed.map((r) => makeWrap(deps.signer.seal(rumor, r), r, expiration, now));
163
- const perWrap = await publishEach(deps, wraps);
164
- const failed = addressed.flatMap((r, i) => perWrap[i]?.some((x) => x.ok) ? [] : [{ pubkey: r, results: perWrap[i] ?? [] }]);
165
- if (failed.length > 0) {
166
- const label = (p) => p === deps.signer.pubkey ? "self copy" : (deps.roster.nameOf(p) ?? p);
167
- const why = (rs) => rs.map((x) => `${x.relay}: ${x.error ?? "failed"}`).join("; ");
168
- const delivered = addressed.filter((r) => !failed.some((f) => f.pubkey === r)).map(label);
169
- const state = delivered.length ? "partly delivered" : "not delivered";
170
- const notDelivered = failed.map((f) => `${label(f.pubkey)} (${why(f.results)})`).join(", ");
171
- throw new ToolError(`sealed send ${state}: delivered to ${delivered.length ? delivered.join(", ") : "nobody"}; NOT delivered to ${notDelivered}; id ${rumor.id}`);
172
- }
205
+ const published = await wrapAndPublish(deps, rumor, recipients, expiration, now);
173
206
  return {
174
207
  id: rumor.id,
175
208
  kind: 14,
176
209
  recipients: recipientsOf(deps, recipients),
177
210
  ...(group !== undefined ? { group } : {}),
178
- published: byRelay(perWrap),
211
+ published,
179
212
  };
180
213
  }
181
214
  export async function sendPlain(deps, target, envelope, session = null) {
@@ -184,8 +217,6 @@ export async function sendPlain(deps, target, envelope, session = null) {
184
217
  if (target.kind === "direct")
185
218
  tags.push(["p", target.pubkeys[0]]);
186
219
  tags.push(...sessionTags(deps, session));
187
- if (target.kind === "group")
188
- tags.push(["h", target.name]);
189
220
  if (envelope.re)
190
221
  tags.push(["e", envelope.re, "", "reply"]);
191
222
  if (envelope.ttl !== undefined)
@@ -197,12 +228,10 @@ export async function sendPlain(deps, target, envelope, session = null) {
197
228
  content: JSON.stringify(envelope),
198
229
  });
199
230
  const published = await publishAll(deps, [ev]);
200
- const pubkeys = target.kind === "group" ? [] : target.pubkeys;
201
231
  return {
202
232
  id: ev.id,
203
233
  kind: 7400,
204
- recipients: recipientsOf(deps, pubkeys),
205
- ...(target.kind === "group" ? { group: target.name } : {}),
234
+ recipients: recipientsOf(deps, target.pubkeys),
206
235
  published,
207
236
  };
208
237
  }
@@ -245,6 +274,8 @@ async function sendPublic(deps, a) {
245
274
  return { id: ev.id, kind: 7400, recipients: [], group: PUBLIC_ROOM, published };
246
275
  }
247
276
  export async function send(deps, a) {
277
+ if (isHelpAnswer(deps, a))
278
+ return sendHelpAnswer(deps, a);
248
279
  if (a.to === PUBLIC_ROOM)
249
280
  return sendPublic(deps, a);
250
281
  if (a.to === `group:${PUBLIC_ROOM}`) {
@@ -253,18 +284,40 @@ export async function send(deps, a) {
253
284
  if (deps.orchestrator === null) {
254
285
  throw new ToolError("this server has no orchestrator configured; it can only send to `public`");
255
286
  }
287
+ // Groups are sealed only (AB-57): refused before any relay read.
288
+ if (a.to.startsWith("group:") && !a.sealed) {
289
+ throw new ToolError(plainGroupRefusal(a.to.slice("group:".length)));
290
+ }
256
291
  await deps.roster.ensureFresh();
257
- const target = resolveTarget(deps, a.to, a.sealed);
292
+ const target = await resolveTarget(deps, a.to, a.sealed);
258
293
  const session = addresseeSession(deps, a, target);
259
294
  const size = Buffer.byteLength(JSON.stringify(a.body));
260
295
  if (size > MAX_BODY_BYTES) {
261
296
  throw new ToolError(`body is ${size} bytes of JSON; the cap is ${MAX_BODY_BYTES} bytes (beacon_inbox must return ten messages in under 64 KB); send less, or send a link to the data`);
262
297
  }
263
298
  const envelope = buildEnvelope(a);
264
- if (a.sealed) {
265
- return sendSealed(deps, target.pubkeys, envelope, session, target.kind === "group" ? target.name : undefined);
299
+ const sentAt = deps.now();
300
+ const result = a.sealed
301
+ ? await sendSealed(deps, target.pubkeys, envelope, session, target.kind === "group" ? target.name : undefined)
302
+ : await sendPlain(deps, target, envelope, session);
303
+ // Only a send that reached every recipient is recorded; one that threw is not (its id is in the error text only).
304
+ if (a.type === "request") {
305
+ const known = a.sealed || target.kind === "direct";
306
+ recordAsk(deps, result.id, { at: sentAt, to: known ? target.pubkeys : null });
266
307
  }
267
- return sendPlain(deps, target, envelope, session);
308
+ return result;
309
+ }
310
+ const SENT_MAX = 1000;
311
+ const SENT_MAX_AGE = 7 * 24 * 60 * 60;
312
+ /** Remember a sent request for `beacon_wait`; drops entries older than seven days, then the oldest beyond 1000. */
313
+ export function recordAsk(deps, id, ask) {
314
+ const { sent } = deps;
315
+ for (const [k, v] of sent)
316
+ if (v.at < ask.at - SENT_MAX_AGE)
317
+ sent.delete(k);
318
+ sent.set(id, ask);
319
+ while (sent.size > SENT_MAX)
320
+ sent.delete(sent.keys().next().value);
268
321
  }
269
322
  /** Sealed `type: ack` to the sender of message `id`, as recorded when it was read. */
270
323
  export async function ack(deps, id) {
@@ -285,3 +338,65 @@ export async function ack(deps, id) {
285
338
  const r = await sendSealed(deps, [known.from], envelope, known.fromSession ?? null);
286
339
  return { ...r, re: id };
287
340
  }
341
+ /** `re` names a kind 5050 ask this session read, and the message is an answer or progress (AB-56). */
342
+ function isHelpAnswer(deps, a) {
343
+ if (a.re === undefined || (a.type !== "response" && a.type !== "event"))
344
+ return false;
345
+ return deps.state.known.get(a.re)?.help === 5050;
346
+ }
347
+ const HELP_STATUSES = ["processing", "partial", "error", "success"];
348
+ /**
349
+ * An answer to a kind 5050 ask (AB-56): a kind 6050 result or a kind 7000 status, a rumor in a NIP-59 wrap to the
350
+ * asker plus a copy to self. Always sealed (decision 0064 item 1); the asker's `beacon_wait` matches it by `e`.
351
+ */
352
+ async function sendHelpAnswer(deps, a) {
353
+ const re = a.re;
354
+ const asker = deps.state.known.get(re)?.from;
355
+ if (deps.orchestrator === null) {
356
+ throw new ToolError("this server has no orchestrator configured; it can only send to `public`");
357
+ }
358
+ await deps.roster.ensureFresh();
359
+ const notAsker = new ToolError(`re names a request from ${asker}; an answer goes to the asker`);
360
+ if (a.to === "all" || a.to === PUBLIC_ROOM || a.to.startsWith("group:"))
361
+ throw notAsker;
362
+ const target = await resolveTarget(deps, a.to, true);
363
+ if (target.kind !== "direct" || target.pubkeys[0] !== asker)
364
+ throw notAsker;
365
+ if (!a.sealed)
366
+ throw new ToolError("an answer to a help request is always sealed");
367
+ if (a.thread !== undefined) {
368
+ throw new ToolError("a help answer cannot carry thread; NIP-90 has no such field");
369
+ }
370
+ const size = Buffer.byteLength(JSON.stringify(a.body));
371
+ if (size > MAX_BODY_BYTES) {
372
+ throw new ToolError(`body is ${size} bytes of JSON; the cap is ${MAX_BODY_BYTES} bytes`);
373
+ }
374
+ const session = addresseeSession(deps, a, target);
375
+ let kind;
376
+ let content;
377
+ const tags = [];
378
+ if (a.type === "response") {
379
+ kind = 6050;
380
+ content = typeof a.body === "string" ? a.body : JSON.stringify(a.body);
381
+ }
382
+ else {
383
+ kind = 7000;
384
+ content = "";
385
+ const b = a.body;
386
+ const status = b !== null && typeof b === "object" ? b.status : undefined;
387
+ if (typeof status !== "string" || !HELP_STATUSES.includes(status)) {
388
+ throw new ToolError(`a status update needs body {status, note?} with status one of ${HELP_STATUSES.join(", ")}`);
389
+ }
390
+ const note = b?.note;
391
+ if (note !== undefined && typeof note !== "string") {
392
+ throw new ToolError("note must be a string");
393
+ }
394
+ tags.push(note === undefined ? ["status", status] : ["status", status, note]);
395
+ }
396
+ tags.push(["e", re], ["p", asker], ...sessionTags(deps, session));
397
+ const now = deps.now();
398
+ const rumor = deps.signer.rumor({ kind, created_at: now, content, tags });
399
+ const expiration = a.ttl === undefined ? undefined : now + a.ttl;
400
+ const published = await wrapAndPublish(deps, rumor, [asker], expiration, now);
401
+ return { id: rumor.id, kind, recipients: recipientsOf(deps, [asker]), published };
402
+ }