@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/groups.js CHANGED
@@ -1,66 +1,204 @@
1
- import { createHash, randomBytes } from "node:crypto";
1
+ import { verifyEvent } from "nostr-tools/pure";
2
2
  import { ToolError } from "./deps.js";
3
- const TIMEOUT_MS = 15_000;
3
+ /** Most members one own group holds (invented, AB-57; 500 trust items fit strfry's 65536-byte event, RUN in AB-48). */
4
+ export const MAX_GROUP_MEMBERS = 100;
5
+ /** Most own groups (invented, AB-57; mirrors the site's `MAX_GROUPS`). */
6
+ export const MAX_OWN_GROUPS = 20;
7
+ const HEX64 = /^[0-9a-f]{64}$/;
8
+ /** The site's rule (`site/src/agents.ts`), so a name means the same in both places. */
9
+ const GROUP_NAME = /^[a-z0-9][a-z0-9._-]{0,31}$/;
10
+ const RESERVED = new Set(["all", "public"]);
11
+ /** True for a group name or label a sender may use: 1 to 32 of `[a-z0-9._-]`, not `all` or `public`. */
12
+ export const validGroupName = (name) => GROUP_NAME.test(name) && !RESERVED.has(name);
13
+ /** What a plain (`sealed: false`) send to a group is refused with (owner, AB-57 item 1(b) and Q6). */
14
+ export const plainGroupRefusal = (name) => `group "${name}" is sealed only: a plain group message would publish every member's key; send sealed`;
15
+ const reason = (e) => (e instanceof Error ? e.message : String(e));
4
16
  /**
5
- * Creates, changes, deletes or lists groups of this agent's own account through the site (AB-25). The
6
- * request is a NIP-98 kind 27235 event (u, method, payload = SHA-256 of the body) signed by this
7
- * agent's key, so the site learns who is calling from the signature; a `nonce` tag keeps two identical
8
- * calls in one second from sharing an event id, which the site refuses as a replay. The site publishes
9
- * the group set; this agent never holds the account key. After a change the roster is refreshed once,
10
- * so a send to the group in the next call sees it.
17
+ * The agent's own `d=group:<name>` sets: kind 30000 signed by this key, the `p` items a JSON array NIP-44
18
+ * encrypted to its own key in `content` (NIP-51, `51.md` lines 11 and 62). Newest per `d` wins (NIP-01).
19
+ * Nothing is cached: every send and every change reads the relay. An empty set is a deleted group.
11
20
  */
12
- export async function groups(deps, site, a, fetchImpl = fetch) {
13
- if (a.action !== "list" && !a.name) {
21
+ export async function readOwnGroups(deps, strict) {
22
+ const me = deps.signer.pubkey;
23
+ let evs;
24
+ try {
25
+ evs = await deps.pool.fetch({ kinds: [30000], authors: [me] }, { strict });
26
+ }
27
+ catch (e) {
28
+ throw new ToolError(`groups not read: ${reason(e)}`);
29
+ }
30
+ const newest = new Map();
31
+ for (const e of evs) {
32
+ if (e.pubkey !== me || !verifyEvent(e))
33
+ continue;
34
+ const d = e.tags.find((t) => t[0] === "d")?.[1];
35
+ if (d === undefined || !d.startsWith("group:"))
36
+ continue;
37
+ const cur = newest.get(d);
38
+ if (!cur ||
39
+ e.created_at > cur.created_at ||
40
+ (e.created_at === cur.created_at && e.id < cur.id)) {
41
+ newest.set(d, e);
42
+ }
43
+ }
44
+ const out = new Map();
45
+ for (const [d, e] of newest) {
46
+ let members;
47
+ try {
48
+ const items = JSON.parse(deps.signer.decryptFromSelf(e.content));
49
+ if (!Array.isArray(items))
50
+ throw new Error("not an array");
51
+ members = [
52
+ ...new Set(items.flatMap((it) => Array.isArray(it) && it[0] === "p" && typeof it[1] === "string" && HEX64.test(it[1])
53
+ ? [it[1]]
54
+ : [])),
55
+ ];
56
+ }
57
+ catch {
58
+ members = null;
59
+ }
60
+ out.set(d.slice("group:".length), { members, createdAt: e.created_at });
61
+ }
62
+ return out;
63
+ }
64
+ const view = (deps, name, members, source) => ({
65
+ name,
66
+ source,
67
+ members: members.map((pubkey) => ({ pubkey, name: deps.roster.nameOf(pubkey) })),
68
+ });
69
+ function resolveMembers(deps, inputs) {
70
+ const me = deps.signer.pubkey;
71
+ const out = [];
72
+ for (const input of inputs) {
73
+ const pk = deps.roster.resolve(input);
74
+ if (pk === null) {
75
+ throw new ToolError(`unknown member "${input}": a roster name, a 64-hex or an npub`);
76
+ }
77
+ // A key that cannot be sealed to would throw inside NIP-44 on the first send.
78
+ if (!deps.signer.canSealTo(pk))
79
+ throw new ToolError(`"${input}" is not a valid public key`);
80
+ if (pk !== me && !out.includes(pk))
81
+ out.push(pk);
82
+ }
83
+ return out;
84
+ }
85
+ /**
86
+ * `beacon_group`: the agent's own saved recipient lists (AB-57). Reads and writes the agent's own
87
+ * `d=group:<name>` sets on the relay; the site is not called. A change is a read-modify-write: a strict
88
+ * read first (a partial read must not publish a smaller set), the publish, and a strict read back.
89
+ */
90
+ export async function groups(deps, a) {
91
+ if (deps.roster.orchestrator === null) {
92
+ throw new ToolError("this server has no orchestrator configured; beacon_group needs a roster");
93
+ }
94
+ const write = a.action !== "list";
95
+ try {
96
+ await deps.roster.refresh(deps.now() * 1000, write);
97
+ }
98
+ catch (e) {
99
+ if (write || deps.roster.fetchedAt === null) {
100
+ throw new ToolError(`groups not read: ${reason(e)}`);
101
+ }
102
+ }
103
+ const own = await readOwnGroups(deps, true);
104
+ if (a.action === "list") {
105
+ const out = [];
106
+ for (const [name, g] of own) {
107
+ if (g.members === null)
108
+ out.push({ ...view(deps, name, [], "own"), unreadable: true });
109
+ else if (g.members.length > 0)
110
+ out.push(view(deps, name, g.members, "own"));
111
+ }
112
+ for (const [name, set] of deps.roster.groups) {
113
+ if (!own.has(name) && set.size > 0)
114
+ out.push(view(deps, name, [...set], "site"));
115
+ }
116
+ return {
117
+ groups: out,
118
+ ...(out.some((g) => g.source === "site")
119
+ ? {
120
+ note: 'A group with source "site" is signed by your account and is never used to send. Create your own with action "create" and the same name and members.',
121
+ }
122
+ : {}),
123
+ };
124
+ }
125
+ const name = a.name;
126
+ if (!name)
14
127
  throw new ToolError(`action ${a.action} needs a group name`);
128
+ const cur = own.get(name);
129
+ const existing = cur !== undefined && (cur.members === null || cur.members.length > 0);
130
+ if (cur?.members === null && a.action !== "delete") {
131
+ throw new ToolError(`group "${name}" is unreadable (a set exists that this key cannot decrypt); nothing was changed; delete it to start again`);
132
+ }
133
+ let next;
134
+ let changed = true;
135
+ const given = resolveMembers(deps, a.members ?? []);
136
+ if (a.action === "create") {
137
+ if (!validGroupName(name)) {
138
+ throw new ToolError("a group name is 1 to 32 characters: lower-case letters, digits, dot, dash or underscore, starting with a letter or digit; not `all` or `public`");
139
+ }
140
+ if (existing)
141
+ throw new ToolError(`group "${name}" exists; use add or remove`);
142
+ if (given.length === 0)
143
+ throw new ToolError("create needs at least one member");
144
+ if ([...own.values()].filter((g) => g.members === null || g.members.length > 0).length >=
145
+ MAX_OWN_GROUPS) {
146
+ throw new ToolError(`you may have at most ${MAX_OWN_GROUPS} groups`);
147
+ }
148
+ next = given;
149
+ }
150
+ else if (a.action === "delete") {
151
+ if (!existing)
152
+ return { changed: false, note: `no group "${name}"` };
153
+ next = [];
154
+ }
155
+ else {
156
+ if (!existing)
157
+ throw new ToolError(`no group "${name}"; create it first`);
158
+ if (given.length === 0)
159
+ throw new ToolError(`${a.action} needs members`);
160
+ const members = cur?.members;
161
+ next =
162
+ a.action === "add"
163
+ ? [...members, ...given.filter((p) => !members.includes(p))]
164
+ : members.filter((p) => !given.includes(p));
165
+ changed = next.length !== members.length;
166
+ if (!changed)
167
+ return { changed: false, group: view(deps, name, members, "own") };
168
+ }
169
+ if (next.length > MAX_GROUP_MEMBERS) {
170
+ throw new ToolError(`a group holds at most ${MAX_GROUP_MEMBERS} members (this change makes ${next.length})`);
15
171
  }
16
- const body = JSON.stringify({
17
- action: a.action,
18
- ...(a.name === undefined ? {} : { name: a.name }),
19
- ...(a.members === undefined ? {} : { members: a.members }),
20
- });
21
- const url = `${site.siteUrl}/agent/groups`;
22
172
  const event = deps.signer.sign({
23
- kind: 27235,
24
- created_at: deps.now(),
25
- content: "",
26
- tags: [
27
- ["u", url],
28
- ["method", "POST"],
29
- ["payload", createHash("sha256").update(body).digest("hex")],
30
- ["nonce", randomBytes(8).toString("hex")],
31
- ],
173
+ kind: 30000,
174
+ // Beats the previous event under NIP-01 even inside one second.
175
+ created_at: Math.max(deps.now(), (cur?.createdAt ?? 0) + 1),
176
+ tags: [["d", `group:${name}`]],
177
+ content: deps.signer.encryptToSelf(JSON.stringify(next.map((p) => ["p", p]))),
32
178
  });
33
- let res;
34
- try {
35
- res = await fetchImpl(url, {
36
- method: "POST",
37
- redirect: "error",
38
- signal: AbortSignal.timeout(TIMEOUT_MS),
39
- headers: {
40
- "content-type": "application/json",
41
- authorization: `Nostr ${Buffer.from(JSON.stringify(event)).toString("base64")}`,
42
- },
43
- body,
44
- });
45
- }
46
- catch {
47
- const unreachable = `Could not reach the site at ${site.siteUrl}.`;
48
- throw new ToolError(a.action === "list"
49
- ? `${unreachable} Nothing was changed; try again later.`
50
- : `${unreachable} Call list to see whether the change was applied.`);
51
- }
52
- let answer;
179
+ const { maxBytes } = await deps.pool.limits();
180
+ if (maxBytes !== undefined && JSON.stringify(event).length > maxBytes) {
181
+ throw new ToolError(`group of ${next.length} members is over this relay's ${maxBytes}-byte event limit`);
182
+ }
183
+ const results = await deps.pool.publish(event);
184
+ if (!results.some((r) => r.ok)) {
185
+ throw new ToolError(`group not published: ${results.map((r) => `${r.relay}: ${r.error ?? "rejected"}`).join("; ")}`);
186
+ }
187
+ const refused = results.filter((r) => !r.ok).map((r) => r.relay);
188
+ let back;
53
189
  try {
54
- answer = (await res.json());
190
+ back = await readOwnGroups(deps, true);
55
191
  }
56
- catch {
57
- throw new ToolError(`The site answered ${res.status} without a message.`);
192
+ catch (e) {
193
+ throw new ToolError(`${reason(e)}; the new set was published and may be in force: call list to see it`);
58
194
  }
59
- if (!res.ok) {
60
- const text = typeof answer?.error === "string" ? answer.error.slice(0, 500) : "no message";
61
- throw new ToolError(`The site refused (${res.status}): ${text}`);
195
+ const got = back.get(name)?.members ?? [];
196
+ if (got.length !== next.length || !next.every((p) => got.includes(p))) {
197
+ throw new ToolError("another session changed the group at the same moment; call again");
62
198
  }
63
- if (a.action !== "list")
64
- await deps.roster.refresh().catch(() => undefined);
65
- return answer;
199
+ return {
200
+ changed: true,
201
+ group: view(deps, name, next, "own"),
202
+ ...(refused.length > 0 ? { refused } : {}),
203
+ };
66
204
  }
package/dist/help.js ADDED
@@ -0,0 +1,102 @@
1
+ import { isExpired } from "./envelope.js";
2
+ import { MAX_BODY_BYTES } from "./send.js";
3
+ /** The kinds of NIP-90 a help exchange uses: job request, job result, job feedback (AB-56). */
4
+ export const HELP_KINDS = new Set([5050, 6050, 7000]);
5
+ /** Statuses the reader accepts on a kind 7000 (NIP-90 `90.md`); a writer sends the first four only. */
6
+ const READ_STATUSES = ["processing", "partial", "error", "success", "payment-required"];
7
+ const byteLength = (s) => Buffer.byteLength(s);
8
+ /**
9
+ * The size of an ask: the JSON bytes of its text plus those of its parameters. One measure for the writer
10
+ * (`beacon_ask`, before any wrap) and the reader, so nothing the writer accepts is dropped.
11
+ */
12
+ export function askBytes(text, param) {
13
+ const params = param !== undefined && Object.keys(param).length > 0 ? byteLength(JSON.stringify(param)) : 0;
14
+ return byteLength(JSON.stringify(text)) + params;
15
+ }
16
+ /** The size of a result or feedback: the UTF-8 bytes of its `content` string, never of its JSON. */
17
+ export function contentBytes(content) {
18
+ return byteLength(content);
19
+ }
20
+ function tagValue(tags, name) {
21
+ return tags.find((t) => t[0] === name)?.[1] ?? null;
22
+ }
23
+ const MALFORMED = { kind: "skip", why: "malformed" };
24
+ const SKIP = { kind: "skip" };
25
+ /**
26
+ * The one reader translation for a kind 5050, 6050 or 7000 (AB-56), sealed (a rumor in a wrap whose NIP-40
27
+ * `expiration` is on `wrapTags`) or plain (a signed 5050 in the room). It returns an ordinary `Candidate` with a
28
+ * synthesised envelope, so trust, held markers, `known`, cursors and `beacon_wait` run on it unchanged.
29
+ * An ask is a `request` (`body` the text of the `i` tag), a result a `response` (`re` the `e` tag), feedback an
30
+ * `event` (`body` `{status, note}`). Addressing, expiry and `since` are checked as for a kind 14.
31
+ */
32
+ export function translateHelp(deps, src, how) {
33
+ const me = deps.signer.pubkey;
34
+ if (src.pubkey === me)
35
+ return SKIP;
36
+ const { tags } = src;
37
+ const named = tags.some((t) => t[0] === "p" && t[1] === me);
38
+ if (how.sealed ? !named : tags.some((t) => t[0] === "p"))
39
+ return SKIP;
40
+ const session = tagValue(tags, "session");
41
+ if (session !== null && session !== deps.session)
42
+ return SKIP;
43
+ let type;
44
+ let body;
45
+ let re;
46
+ let help;
47
+ if (src.kind === 5050) {
48
+ const i = tags.find((t) => t[0] === "i" && t[2] === "text");
49
+ if (i?.[1] === undefined)
50
+ return MALFORMED;
51
+ const param = {};
52
+ for (const t of tags)
53
+ if (t[0] === "param" && t[1] !== undefined)
54
+ param[t[1]] = t[2] ?? "";
55
+ if (askBytes(i[1], param) > MAX_BODY_BYTES)
56
+ return MALFORMED;
57
+ type = "request";
58
+ body = i[1];
59
+ help = { kind: 5050, t: tags.filter((t) => t[0] === "t").map((t) => t[1] ?? ""), param };
60
+ }
61
+ else {
62
+ const e = tagValue(tags, "e");
63
+ if (e === null || !/^[0-9a-f]{64}$/.test(e))
64
+ return MALFORMED;
65
+ if (contentBytes(src.content) > MAX_BODY_BYTES)
66
+ return MALFORMED;
67
+ re = e;
68
+ if (src.kind === 6050) {
69
+ type = "response";
70
+ body = src.content;
71
+ help = { kind: 6050 };
72
+ }
73
+ else {
74
+ const status = tags.find((t) => t[0] === "status");
75
+ if (status?.[1] === undefined || !READ_STATUSES.includes(status[1]))
76
+ return MALFORMED;
77
+ type = "event";
78
+ body = { status: status[1], note: src.content !== "" ? src.content : (status[2] ?? null) };
79
+ help = { kind: 7000 };
80
+ }
81
+ }
82
+ const env = { v: 1, type, id: src.id, ct: "text/plain", body };
83
+ if (re !== undefined)
84
+ env.re = re;
85
+ if (isExpired(env, how.sealed ? how.wrapTags : tags, src.created_at, how.now))
86
+ return SKIP;
87
+ if (how.sealed && how.since !== undefined && src.created_at < how.since)
88
+ return SKIP;
89
+ const c = {
90
+ id: src.id,
91
+ from: src.pubkey,
92
+ fromSession: tagValue(tags, "from_session"),
93
+ session,
94
+ group: null,
95
+ sealed: how.sealed,
96
+ env,
97
+ createdAt: src.created_at,
98
+ trusted: (how.trust ?? deps.trust).isTrusted(src.pubkey),
99
+ help,
100
+ };
101
+ return { kind: "candidate", c };
102
+ }