@benjilabs/beaconfire-mcp 0.0.0-stage → 0.1.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/roster.js ADDED
@@ -0,0 +1,115 @@
1
+ import { verifyEvent } from "nostr-tools/pure";
2
+ import { pubkeyToHex } from "./config.js";
3
+ const FRESH_MS = 5 * 60 * 1000;
4
+ const HEX64 = /^[0-9a-f]{64}$/;
5
+ /**
6
+ * The orchestrator's kind 30000 `d=agents` event: `["p", <hex>, "", <name>]` per agent
7
+ * (NIP-02 petname position, element 3). Only an event signed by the orchestrator counts.
8
+ */
9
+ export class Roster {
10
+ entries = [];
11
+ /** Group name to member pubkeys, from the orchestrator's `d=group:<name>` sets (NIP-51 follow sets). */
12
+ groups = new Map();
13
+ fetchedAt = null;
14
+ #lastOk = false;
15
+ pool;
16
+ /** null: no roster to fetch; `refresh` does nothing and the status stays `missing`. */
17
+ orchestrator;
18
+ constructor(pool, orchestrator) {
19
+ this.pool = pool;
20
+ this.orchestrator = orchestrator;
21
+ }
22
+ status(nowMs = Date.now()) {
23
+ if (this.fetchedAt === null)
24
+ return "missing";
25
+ return this.#lastOk && nowMs - this.fetchedAt < FRESH_MS ? "fresh" : "stale";
26
+ }
27
+ /**
28
+ * Refetch the orchestrator's kind 30000 sets: `d=agents` (the roster) and every `d=group:<name>`.
29
+ * On failure the previous entries and groups stay and status becomes stale/missing. A fetch that
30
+ * succeeds is the whole truth about groups: a set that is absent or empty removes the group.
31
+ */
32
+ async refresh(nowMs = Date.now(), strict = false) {
33
+ if (this.orchestrator === null)
34
+ return;
35
+ try {
36
+ const evs = await this.pool.fetch({ kinds: [30000], authors: [this.orchestrator] }, { strict });
37
+ const sets = new Map();
38
+ for (const e of evs) {
39
+ if (e.pubkey !== this.orchestrator || !verifyEvent(e))
40
+ continue;
41
+ const d = e.tags.find((t) => t[0] === "d")?.[1];
42
+ if (d === undefined)
43
+ continue;
44
+ const cur = sets.get(d);
45
+ // NIP-01: greater created_at wins, lower id on a tie (as relay/plugin/allowlist.mjs).
46
+ if (!cur ||
47
+ e.created_at > cur.created_at ||
48
+ (e.created_at === cur.created_at && e.id < cur.id)) {
49
+ sets.set(d, e);
50
+ }
51
+ }
52
+ this.groups = new Map();
53
+ for (const [d, e] of sets) {
54
+ if (!d.startsWith("group:"))
55
+ continue;
56
+ this.groups.set(d.slice("group:".length), new Set(e.tags.filter((t) => t[0] === "p" && HEX64.test(t[1] ?? "")).map((t) => t[1])));
57
+ }
58
+ const newest = sets.get("agents");
59
+ if (newest) {
60
+ this.entries = newest.tags
61
+ .filter((t) => t[0] === "p" && /^[0-9a-f]{64}$/.test(t[1] ?? ""))
62
+ .map((t) => ({ pubkey: t[1], name: t[3] ? t[3] : null }));
63
+ this.fetchedAt = nowMs;
64
+ this.#lastOk = true;
65
+ }
66
+ else if (this.fetchedAt !== null) {
67
+ this.#lastOk = false;
68
+ }
69
+ }
70
+ catch (e) {
71
+ this.#lastOk = false;
72
+ throw e;
73
+ }
74
+ }
75
+ /** Refresh when older than five minutes or never fetched; a failure with cached entries is swallowed. */
76
+ async ensureFresh(nowMs = Date.now()) {
77
+ if (this.status(nowMs) === "fresh")
78
+ return;
79
+ try {
80
+ await this.refresh(nowMs);
81
+ }
82
+ catch (e) {
83
+ if (this.fetchedAt === null)
84
+ throw e;
85
+ }
86
+ }
87
+ has(pubkey) {
88
+ return this.entries.some((e) => e.pubkey === pubkey);
89
+ }
90
+ /** The groups whose set lists `pubkey`. */
91
+ groupsOf(pubkey) {
92
+ return [...this.groups].filter(([, m]) => m.has(pubkey)).map(([g]) => g);
93
+ }
94
+ inGroup(group, pubkey) {
95
+ return this.groups.get(group)?.has(pubkey) ?? false;
96
+ }
97
+ nameOf(pubkey) {
98
+ return this.entries.find((e) => e.pubkey === pubkey)?.name ?? null;
99
+ }
100
+ names() {
101
+ return this.entries.flatMap((e) => (e.name ? [e.name] : []));
102
+ }
103
+ /** Name (case-insensitive), 64-hex or npub to a hex pubkey; null when it is none of those. */
104
+ resolve(input) {
105
+ const byName = this.entries.find((e) => e.name?.toLowerCase() === input.toLowerCase());
106
+ if (byName)
107
+ return byName.pubkey;
108
+ try {
109
+ return pubkeyToHex(input);
110
+ }
111
+ catch {
112
+ return null;
113
+ }
114
+ }
115
+ }
package/dist/send.js ADDED
@@ -0,0 +1,287 @@
1
+ import { SESSION_PATTERN } from "./config.js";
2
+ import { ToolError } from "./deps.js";
3
+ import { buildEnvelope } from "./envelope.js";
4
+ import { makeWrap } from "./signer.js";
5
+ /** NIP-17 line 106: "more than 10 participants" need another scheme. Participants include the sender. */
6
+ const MAX_SEALED_PARTICIPANTS = 10;
7
+ function overCap(participants) {
8
+ return new ToolError(`sealed send to ${participants} participants (the sender counts); NIP-17 allows at most ${MAX_SEALED_PARTICIPANTS}; groups or accounts over ${MAX_SEALED_PARTICIPANTS} need Marmot (MLS), which is not built`);
9
+ }
10
+ /**
11
+ * Largest body, as UTF-8 bytes of its JSON, that `send` accepts. Set by the reader, not the relay:
12
+ * the Hermes adapter peeks ten messages and Hermes truncates an MCP result over about 64 KB, and ten
13
+ * messages at this size come to about 48 KB. The relay limit (`maxEventSize` 65536) never binds here:
14
+ * the worst-case sealed wrap of a body this size is about 19.3 KB.
15
+ */
16
+ export const MAX_BODY_BYTES = 4096;
17
+ function unknownRecipient(deps, input) {
18
+ const names = deps.roster.names();
19
+ return new ToolError(`unknown recipient "${input}"; roster names: ${names.length ? names.join(", ") : "(none)"}`);
20
+ }
21
+ /**
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.
24
+ */
25
+ function sealedGroupMembers(deps, name) {
26
+ 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)"}`);
31
+ }
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(", ")}`);
37
+ }
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
+ return others;
44
+ }
45
+ export function resolveTarget(deps, to, sealed) {
46
+ if (deps.roster.status() === "missing") {
47
+ throw new ToolError("roster not available: no roster event from the orchestrator was found");
48
+ }
49
+ const me = deps.signer.pubkey;
50
+ if (to === "all") {
51
+ const pubkeys = deps.roster.entries.map((e) => e.pubkey).filter((p) => p !== me);
52
+ if (sealed && pubkeys.length === 0)
53
+ throw new ToolError("roster has no other agents to send to");
54
+ if (sealed && pubkeys.length + 1 > MAX_SEALED_PARTICIPANTS) {
55
+ throw overCap(pubkeys.length + 1);
56
+ }
57
+ return { kind: "all", pubkeys };
58
+ }
59
+ if (to.startsWith("group:")) {
60
+ const name = to.slice("group:".length);
61
+ if (!name)
62
+ throw new ToolError("group name is empty");
63
+ return { kind: "group", name, pubkeys: sealed ? sealedGroupMembers(deps, name) : [] };
64
+ }
65
+ const pk = deps.roster.resolve(to);
66
+ if (pk === null)
67
+ throw unknownRecipient(deps, to);
68
+ if (pk === me)
69
+ throw new ToolError("cannot send to yourself");
70
+ if (!deps.roster.has(pk))
71
+ throw unknownRecipient(deps, to);
72
+ return { kind: "direct", pubkeys: [pk] };
73
+ }
74
+ function recipientsOf(deps, pubkeys) {
75
+ return pubkeys.map((pubkey) => ({ pubkey, name: deps.roster.nameOf(pubkey) }));
76
+ }
77
+ /** Size-check every event, then publish each; one result list per event, in order. */
78
+ async function publishEach(deps, events) {
79
+ const limits = await deps.pool.limits();
80
+ if (limits.maxBytes !== undefined) {
81
+ for (const e of events) {
82
+ if (e.content.length > limits.maxBytes ||
83
+ JSON.stringify(["EVENT", e]).length > limits.maxBytes) {
84
+ throw new ToolError(`message too large for the relay (limit ${limits.maxBytes} bytes)`);
85
+ }
86
+ }
87
+ }
88
+ return Promise.all(events.map((e) => deps.pool.publish(e)));
89
+ }
90
+ /** One row per relay; a relay that rejected any event is not ok. */
91
+ function byRelay(perEvent) {
92
+ const rows = new Map();
93
+ for (const results of perEvent) {
94
+ for (const r of results) {
95
+ const prev = rows.get(r.relay);
96
+ if (!prev)
97
+ rows.set(r.relay, { ...r });
98
+ else if (!r.ok) {
99
+ prev.ok = false;
100
+ prev.error = r.error ?? "rejected";
101
+ }
102
+ }
103
+ }
104
+ return [...rows.values()];
105
+ }
106
+ /** Publish `events`; throws if one reached no relay. */
107
+ async function publishAll(deps, events) {
108
+ const perEvent = await publishEach(deps, events);
109
+ const unreached = perEvent.filter((results) => !results.some((r) => r.ok)).length;
110
+ const published = byRelay(perEvent);
111
+ if (unreached > 0) {
112
+ const why = published.map((p) => `${p.relay}: ${p.error ?? "failed"}`).join("; ");
113
+ throw new ToolError(`${unreached} of ${events.length} events reached no relay (${why})`);
114
+ }
115
+ return published;
116
+ }
117
+ /** `session` names the addressee's session; `from_session` is this server's own, on every send. */
118
+ function sessionTags(deps, session) {
119
+ const tags = [];
120
+ if (session !== null)
121
+ tags.push(["session", session]);
122
+ if (deps.session !== null)
123
+ tags.push(["from_session", deps.session]);
124
+ return tags;
125
+ }
126
+ /**
127
+ * The session a send is addressed to: the explicit `session`, else the session that sent the message `re`
128
+ * names (when this server read it and `to` is that message's sender), else none (the agent).
129
+ */
130
+ function addresseeSession(deps, a, target) {
131
+ if (a.session !== undefined) {
132
+ if (!SESSION_PATTERN.test(a.session))
133
+ throw new ToolError("invalid session name");
134
+ if (target.kind !== "direct")
135
+ throw new ToolError("a session needs one agent");
136
+ return a.session;
137
+ }
138
+ if (target.kind !== "direct" || a.re === undefined)
139
+ return null;
140
+ const known = deps.state.known.get(a.re);
141
+ if (known?.fromSession && known.from === target.pubkeys[0])
142
+ return known.fromSession;
143
+ return null;
144
+ }
145
+ /** One rumor, then seal and wrap per recipient plus a copy to self (NIP-17 / NIP-59). */
146
+ export async function sendSealed(deps, recipients, envelope, session = null, group) {
147
+ const now = deps.now();
148
+ const tags = recipients.map((r) => ["p", r]);
149
+ if (group !== undefined)
150
+ tags.push(["h", group]);
151
+ tags.push(...sessionTags(deps, session));
152
+ if (envelope.re)
153
+ tags.push(["e", envelope.re, "", "reply"]);
154
+ const rumor = deps.signer.rumor({
155
+ kind: 14,
156
+ created_at: now,
157
+ content: JSON.stringify(envelope),
158
+ tags,
159
+ });
160
+ 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
+ }
173
+ return {
174
+ id: rumor.id,
175
+ kind: 14,
176
+ recipients: recipientsOf(deps, recipients),
177
+ ...(group !== undefined ? { group } : {}),
178
+ published: byRelay(perWrap),
179
+ };
180
+ }
181
+ export async function sendPlain(deps, target, envelope, session = null) {
182
+ const now = deps.now();
183
+ const tags = [];
184
+ if (target.kind === "direct")
185
+ tags.push(["p", target.pubkeys[0]]);
186
+ tags.push(...sessionTags(deps, session));
187
+ if (target.kind === "group")
188
+ tags.push(["h", target.name]);
189
+ if (envelope.re)
190
+ tags.push(["e", envelope.re, "", "reply"]);
191
+ if (envelope.ttl !== undefined)
192
+ tags.push(["expiration", String(now + envelope.ttl)]);
193
+ const ev = deps.signer.sign({
194
+ kind: 7400,
195
+ created_at: now,
196
+ tags,
197
+ content: JSON.stringify(envelope),
198
+ });
199
+ const published = await publishAll(deps, [ev]);
200
+ const pubkeys = target.kind === "group" ? [] : target.pubkeys;
201
+ return {
202
+ id: ev.id,
203
+ kind: 7400,
204
+ recipients: recipientsOf(deps, pubkeys),
205
+ ...(target.kind === "group" ? { group: target.name } : {}),
206
+ published,
207
+ };
208
+ }
209
+ /** The one global public room: the `h` tag value of a plain kind 7400 that anyone may read and post. */
210
+ export const PUBLIC_ROOM = "public";
211
+ /**
212
+ * Seven days (the relay's `BEACON_PUBLIC_EXPIRY_MAX` default) minus one hour, so a client clock ahead of
213
+ * the relay's cannot push the NIP-40 expiration past the relay's bound. Both default and cap.
214
+ */
215
+ export const PUBLIC_MAX_TTL = 7 * 24 * 60 * 60 - 3600;
216
+ /**
217
+ * A plain kind 7400, `h=public`, no `p`, with an `expiration` and NIP-13 proof of work: the shape the
218
+ * relay's public-tier rule accepts from a key on no roster (AB-12). `expiration` and the envelope `ttl`
219
+ * come from `deps.now()`; `created_at` is the wall clock, set by the miner.
220
+ */
221
+ async function sendPublic(deps, a) {
222
+ if (!deps.publicRoom)
223
+ throw new ToolError("the public room is turned off in this server's config");
224
+ if (a.sealed) {
225
+ throw new ToolError("the public room is never sealed: anyone can read it; omit `sealed` or send `sealed: false`");
226
+ }
227
+ if (a.session !== undefined)
228
+ throw new ToolError("a session needs one agent");
229
+ const ttl = a.ttl ?? PUBLIC_MAX_TTL;
230
+ if (ttl > PUBLIC_MAX_TTL) {
231
+ throw new ToolError(`ttl ${ttl} is over the public room's cap of ${PUBLIC_MAX_TTL} seconds (the relay allows 7 days ahead)`);
232
+ }
233
+ const size = Buffer.byteLength(JSON.stringify(a.body));
234
+ if (size > MAX_BODY_BYTES) {
235
+ throw new ToolError(`body is ${size} bytes of JSON; the cap is ${MAX_BODY_BYTES} bytes`);
236
+ }
237
+ const envelope = buildEnvelope({ ...a, ttl });
238
+ const now = deps.now();
239
+ const tags = [["h", PUBLIC_ROOM]];
240
+ if (envelope.re)
241
+ tags.push(["e", envelope.re, "", "reply"]);
242
+ tags.push(["expiration", String(now + ttl)]);
243
+ const ev = deps.signer.signWithPow({ kind: 7400, created_at: now, tags, content: JSON.stringify(envelope) }, deps.publicRoom.powBits);
244
+ const published = await publishAll(deps, [ev]);
245
+ return { id: ev.id, kind: 7400, recipients: [], group: PUBLIC_ROOM, published };
246
+ }
247
+ export async function send(deps, a) {
248
+ if (a.to === PUBLIC_ROOM)
249
+ return sendPublic(deps, a);
250
+ if (a.to === `group:${PUBLIC_ROOM}`) {
251
+ throw new ToolError(`"${PUBLIC_ROOM}" is the public room, not a group: send to \`public\``);
252
+ }
253
+ if (deps.orchestrator === null) {
254
+ throw new ToolError("this server has no orchestrator configured; it can only send to `public`");
255
+ }
256
+ await deps.roster.ensureFresh();
257
+ const target = resolveTarget(deps, a.to, a.sealed);
258
+ const session = addresseeSession(deps, a, target);
259
+ const size = Buffer.byteLength(JSON.stringify(a.body));
260
+ if (size > MAX_BODY_BYTES) {
261
+ 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
+ }
263
+ const envelope = buildEnvelope(a);
264
+ if (a.sealed) {
265
+ return sendSealed(deps, target.pubkeys, envelope, session, target.kind === "group" ? target.name : undefined);
266
+ }
267
+ return sendPlain(deps, target, envelope, session);
268
+ }
269
+ /** Sealed `type: ack` to the sender of message `id`, as recorded when it was read. */
270
+ export async function ack(deps, id) {
271
+ if (deps.orchestrator === null) {
272
+ throw new ToolError("this server has no orchestrator configured; it can only use `public`");
273
+ }
274
+ await deps.roster.ensureFresh();
275
+ const known = deps.state.known.get(id);
276
+ if (!known)
277
+ throw new ToolError(`unknown message id ${id}; call beacon_inbox first`);
278
+ if (known.public)
279
+ throw new ToolError("public messages are not acked");
280
+ if (known.type === "ack")
281
+ throw new ToolError("an ack is not itself acked");
282
+ if (!deps.roster.has(known.from))
283
+ throw unknownRecipient(deps, known.from);
284
+ const envelope = buildEnvelope({ type: "ack", body: {}, re: id });
285
+ const r = await sendSealed(deps, [known.from], envelope, known.fromSession ?? null);
286
+ return { ...r, re: id };
287
+ }
package/dist/setup.js ADDED
@@ -0,0 +1,217 @@
1
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parseArgs } from "node:util";
6
+ import { generateSecretKey, getPublicKey } from "nostr-tools/pure";
7
+ import { loadConfig, readSecretKey, SESSION_PATTERN } from "./config.js";
8
+ import { ToolError } from "./deps.js";
9
+ import { register } from "./enroll.js";
10
+ import { Signer } from "./signer.js";
11
+ /** The agent and group name rule, copied from `site/src/agents.ts`. */
12
+ const NAME_PATTERN = /^[a-z0-9][a-z0-9._-]{0,31}$/;
13
+ const RESERVED = new Set(["all", "public"]);
14
+ export class SetupError extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = "SetupError";
18
+ }
19
+ }
20
+ function die(msg) {
21
+ throw new SetupError(msg);
22
+ }
23
+ function validName(name) {
24
+ return NAME_PATTERN.test(name) && !RESERVED.has(name);
25
+ }
26
+ /**
27
+ * Runs `beaconfire-mcp setup`. Throws `SetupError` on invalid input; other throws are unexpected.
28
+ *
29
+ * `opts.fetchImpl` replaces `fetch` for tests.
30
+ * `opts.serverPath` replaces the computed `dist/index.js` path in the printed snippet for tests.
31
+ */
32
+ export async function runSetup(argv, opts) {
33
+ const { values } = parseArgs({
34
+ args: argv,
35
+ strict: true,
36
+ options: {
37
+ site: { type: "string" },
38
+ token: { type: "string" },
39
+ relay: { type: "string" },
40
+ name: { type: "string" },
41
+ "key-file": { type: "string" },
42
+ config: { type: "string" },
43
+ "state-dir": { type: "string" },
44
+ project: { type: "string" },
45
+ session: { type: "string" },
46
+ force: { type: "boolean", default: false },
47
+ },
48
+ });
49
+ const name = values.name ?? die("--name is required");
50
+ if (!validName(name)) {
51
+ die("--name: use 1-32 characters of lower-case letters, digits, dot, dash or underscore, " +
52
+ "starting with a letter or digit; not 'all' or 'public'");
53
+ }
54
+ const hasSite = values.site !== undefined;
55
+ const hasRelay = values.relay !== undefined;
56
+ // --token wins over the env var; both are checked before anything is written.
57
+ // Empty string from either source is treated as unset.
58
+ const token = (values.token || undefined) ?? (process.env.BEACONFIRE_TOKEN || undefined);
59
+ const hasToken = token !== undefined;
60
+ if (hasSite && hasRelay) {
61
+ die("--site and --relay cannot both be given; use --site + --token for private, --relay for public-only");
62
+ }
63
+ if (hasSite && !hasToken)
64
+ die("a non-empty token is required; use --token or BEACONFIRE_TOKEN");
65
+ if (values.token !== undefined && !hasSite)
66
+ die("--token requires --site");
67
+ if (!hasSite && !hasRelay)
68
+ die("one of --site + --token (private) or --relay (public-only) is required");
69
+ const isPrivate = hasSite;
70
+ let siteOrigin;
71
+ if (isPrivate) {
72
+ const siteStr = values.site ?? die("unreachable");
73
+ let u;
74
+ try {
75
+ u = new URL(siteStr);
76
+ }
77
+ catch {
78
+ die("--site is not a valid URL");
79
+ }
80
+ if ((u.protocol !== "http:" && u.protocol !== "https:") ||
81
+ u.pathname !== "/" ||
82
+ u.search ||
83
+ u.hash ||
84
+ u.username ||
85
+ u.password) {
86
+ die("--site must be the site's origin only, e.g. https://beaconfire.example");
87
+ }
88
+ siteOrigin = u.origin;
89
+ }
90
+ if (!isPrivate && !/^wss?:\/\//.test(values.relay ?? die("unreachable"))) {
91
+ die("--relay must start with ws:// or wss://");
92
+ }
93
+ if (values.session !== undefined && !SESSION_PATTERN.test(values.session)) {
94
+ die(`--session: must match ${SESSION_PATTERN.source}`);
95
+ }
96
+ const base = join(homedir(), ".config", "beaconfire");
97
+ const keyFile = resolve(values["key-file"] ?? join(base, `${name}.key`));
98
+ const configPath = resolve(values.config ?? join(base, `${name}.json`));
99
+ const stateDir = resolve(values["state-dir"] ?? join(base, `${name}-state`));
100
+ // ── pre-flight checks (nothing written before this block completes) ──────────
101
+ if (existsSync(configPath) && !values.force) {
102
+ die(`config ${configPath} already exists; use --force to overwrite`);
103
+ }
104
+ let mcpExisting = {};
105
+ if (values.project !== undefined) {
106
+ const projectDir = resolve(values.project);
107
+ if (!existsSync(projectDir) || !statSync(projectDir).isDirectory()) {
108
+ die(`--project: directory ${projectDir} does not exist`);
109
+ }
110
+ const mcpPath = join(projectDir, ".mcp.json");
111
+ if (existsSync(mcpPath)) {
112
+ let parsed;
113
+ try {
114
+ parsed = JSON.parse(readFileSync(mcpPath, "utf8"));
115
+ }
116
+ catch {
117
+ die(`${mcpPath} is not valid JSON`);
118
+ }
119
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
120
+ die(`${mcpPath} is not a JSON object`);
121
+ }
122
+ const obj = parsed;
123
+ if (obj.mcpServers !== undefined &&
124
+ (typeof obj.mcpServers !== "object" ||
125
+ obj.mcpServers === null ||
126
+ Array.isArray(obj.mcpServers))) {
127
+ die(`${mcpPath}: mcpServers is not an object`);
128
+ }
129
+ const servers = obj.mcpServers;
130
+ if (servers?.beaconfire !== undefined && !values.force) {
131
+ die(`${mcpPath} already has a beaconfire entry; use --force to replace it`);
132
+ }
133
+ mcpExisting = obj;
134
+ }
135
+ }
136
+ // ── set up directories ───────────────────────────────────────────────────────
137
+ mkdirSync(dirname(keyFile), { recursive: true, mode: 0o700 });
138
+ mkdirSync(dirname(configPath), { recursive: true, mode: 0o700 });
139
+ // ── generate or load key ─────────────────────────────────────────────────────
140
+ let sk;
141
+ if (existsSync(keyFile)) {
142
+ try {
143
+ sk = readSecretKey(keyFile);
144
+ }
145
+ catch (e) {
146
+ throw new SetupError(e.message);
147
+ }
148
+ console.log(`reusing key at ${keyFile}`);
149
+ }
150
+ else {
151
+ sk = generateSecretKey();
152
+ writeFileSync(keyFile, `${Buffer.from(sk).toString("hex")}\n`, { mode: 0o600, flag: "wx" });
153
+ console.log(`key written to ${keyFile}`);
154
+ }
155
+ console.log(`pubkey ${getPublicKey(sk)}`);
156
+ const signer = new Signer(sk);
157
+ let finalConfig;
158
+ if (isPrivate) {
159
+ let result;
160
+ try {
161
+ result = await register({ signer, now: () => Math.floor(Date.now() / 1000) }, {
162
+ siteUrl: siteOrigin ?? die("unreachable"),
163
+ config: { keyFile, fileSettings: {}, stateDir, session: values.session ?? null },
164
+ }, { token: token ?? die("unreachable"), name }, opts?.fetchImpl);
165
+ }
166
+ catch (e) {
167
+ if (e instanceof ToolError)
168
+ throw new SetupError(e.message);
169
+ throw e;
170
+ }
171
+ console.log(`registered as ${result.registered}`);
172
+ finalConfig = result.config;
173
+ }
174
+ else {
175
+ const cfg = {
176
+ keyFile,
177
+ relays: [{ url: values.relay ?? die("unreachable") }],
178
+ stateDir,
179
+ };
180
+ if (values.session)
181
+ cfg.session = values.session;
182
+ finalConfig = JSON.stringify(cfg, null, 2);
183
+ }
184
+ writeFileSync(configPath, `${finalConfig}\n`, { mode: 0o600, flag: values.force ? "w" : "wx" });
185
+ console.log(`config written to ${configPath}`);
186
+ // validate the config we just wrote
187
+ loadConfig(configPath);
188
+ const serverPath = opts?.serverPath ?? join(dirname(fileURLToPath(import.meta.url)), "index.js");
189
+ const mcpEntry = {
190
+ command: "node",
191
+ args: [serverPath],
192
+ env: { BEACONFIRE_CONFIG: configPath },
193
+ };
194
+ if (values.project !== undefined) {
195
+ const projectDir = resolve(values.project);
196
+ const mcpPath = join(projectDir, ".mcp.json");
197
+ const updated = {
198
+ ...mcpExisting,
199
+ mcpServers: {
200
+ ...mcpExisting.mcpServers,
201
+ beaconfire: mcpEntry,
202
+ },
203
+ };
204
+ writeFileSync(mcpPath, `${JSON.stringify(updated, null, 2)}\n`);
205
+ console.log(`wrote ${mcpPath}`);
206
+ }
207
+ else {
208
+ console.log("\nAdd to your project's .mcp.json:");
209
+ console.log(JSON.stringify({ mcpServers: { beaconfire: mcpEntry } }, null, 2));
210
+ }
211
+ if (isPrivate) {
212
+ console.log(`\nDone. Send messages to this agent with to: "${name}"`);
213
+ }
214
+ else {
215
+ console.log(`\nDone. Public-only mode: beacon_send {"to":"public"} and beacon_inbox.`);
216
+ }
217
+ }
package/dist/signer.js ADDED
@@ -0,0 +1,65 @@
1
+ import { nip19 } from "nostr-tools";
2
+ import { minePow } from "nostr-tools/nip13";
3
+ import { encrypt, getConversationKey } from "nostr-tools/nip44";
4
+ import { createRumor, createSeal, unwrapEvent } from "nostr-tools/nip59";
5
+ import { finalizeEvent, generateSecretKey, getPublicKey, } from "nostr-tools/pure";
6
+ const TWO_DAYS = 2 * 24 * 60 * 60;
7
+ /**
8
+ * Holds the secret key in a private field. No method returns it and
9
+ * serialisation yields `{}`, so it cannot reach a tool result or log by accident.
10
+ */
11
+ export class Signer {
12
+ #sk;
13
+ pubkey;
14
+ constructor(sk) {
15
+ this.#sk = sk;
16
+ this.pubkey = getPublicKey(sk);
17
+ }
18
+ toJSON() {
19
+ return {};
20
+ }
21
+ /** Strings that must never appear in any output: the key as hex and as nsec. */
22
+ secretForms() {
23
+ return [Buffer.from(this.#sk).toString("hex"), nip19.nsecEncode(this.#sk)];
24
+ }
25
+ sign(template) {
26
+ return finalizeEvent(template, this.#sk);
27
+ }
28
+ /**
29
+ * Sign `template` after mining its id to `bits` leading zero bits (NIP-13). Mined with this key's
30
+ * `pubkey` in the hash, so the signed event has the same id. `minePow` resets `created_at` to the
31
+ * wall clock; the caller sets any `expiration` before calling.
32
+ */
33
+ signWithPow(template, bits) {
34
+ const mined = minePow({ ...template, tags: [...template.tags], pubkey: this.pubkey }, bits);
35
+ return finalizeEvent({ kind: mined.kind, created_at: mined.created_at, tags: mined.tags, content: mined.content }, this.#sk);
36
+ }
37
+ rumor(partial) {
38
+ return createRumor(partial, this.#sk);
39
+ }
40
+ seal(rumor, recipient) {
41
+ return createSeal(rumor, this.#sk, recipient);
42
+ }
43
+ /** Throws unless wrap, seal signature and `rumor.pubkey == seal.pubkey` all hold (nip59). */
44
+ unwrap(wrap) {
45
+ return unwrapEvent(wrap, this.#sk);
46
+ }
47
+ }
48
+ /**
49
+ * Kind 1059 gift wrap under a one-time key, `created_at` up to two days back
50
+ * (NIP-59). Own implementation because nostr-tools' createWrap cannot add the
51
+ * `expiration` tag (NIP-17 line 91 puts it on the wrap).
52
+ */
53
+ export function makeWrap(seal, recipient, expiration, now) {
54
+ const oneTime = generateSecretKey();
55
+ const tags = [["p", recipient]];
56
+ if (expiration !== undefined)
57
+ tags.push(["expiration", String(expiration)]);
58
+ const t = now ?? Math.floor(Date.now() / 1000);
59
+ return finalizeEvent({
60
+ kind: 1059,
61
+ content: encrypt(JSON.stringify(seal), getConversationKey(oneTime, recipient)),
62
+ created_at: t - Math.floor(Math.random() * TWO_DAYS),
63
+ tags,
64
+ }, oneTime);
65
+ }