@benjilabs/beaconfire-mcp 0.0.0-stage → 0.1.1
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/config.js +151 -0
- package/dist/deps.js +3 -0
- package/dist/enroll.js +81 -0
- package/dist/envelope.js +57 -0
- package/dist/groups.js +66 -0
- package/dist/inbox.js +400 -0
- package/dist/index.js +54 -0
- package/dist/redact.js +14 -0
- package/dist/relay.js +210 -0
- package/dist/roster.js +115 -0
- package/dist/send.js +287 -0
- package/dist/setup.js +217 -0
- package/dist/signer.js +65 -0
- package/dist/state.js +67 -0
- package/dist/tools.js +185 -0
- package/package.json +24 -4
- package/README.md +0 -3
package/dist/config.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { nip19 } from "nostr-tools";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
const hex64 = /^[0-9a-f]{64}$/;
|
|
5
|
+
/** Decode a 64-hex or npub string to hex; throws a message that never echoes the input. */
|
|
6
|
+
export function pubkeyToHex(input) {
|
|
7
|
+
if (hex64.test(input))
|
|
8
|
+
return input;
|
|
9
|
+
if (input.startsWith("npub1")) {
|
|
10
|
+
try {
|
|
11
|
+
const d = nip19.decode(input);
|
|
12
|
+
if (d.type === "npub")
|
|
13
|
+
return d.data;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
// fall through
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
throw new Error("not a valid public key (expected 64 hex or npub)");
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A session name: lowercase only, so two names cannot differ only in case and share one directory on a
|
|
23
|
+
* case-insensitive filesystem (macOS); starts with a letter or digit, so `.` and `..` cannot name a
|
|
24
|
+
* directory outside `sessions/`.
|
|
25
|
+
*/
|
|
26
|
+
export const SESSION_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
27
|
+
const SESSION_MESSAGE = `session name is invalid; it must match ${SESSION_PATTERN.source}`;
|
|
28
|
+
/** Returns `name` or throws a message that states the pattern and never echoes the value. */
|
|
29
|
+
export function parseSessionName(name) {
|
|
30
|
+
if (!SESSION_PATTERN.test(name))
|
|
31
|
+
throw new Error(SESSION_MESSAGE);
|
|
32
|
+
return name;
|
|
33
|
+
}
|
|
34
|
+
const RelayEntry = z.object({
|
|
35
|
+
url: z.string().regex(/^wss?:\/\//, "relay url must start with ws:// or wss://"),
|
|
36
|
+
/** Value signed into the kind 22242 `relay` tag; strfry compares it to its one serviceUrl. */
|
|
37
|
+
auth_url: z.string().optional(),
|
|
38
|
+
});
|
|
39
|
+
const SITE_URL_MESSAGE = "siteUrl must be the site's address only, for example https://beaconfire.example";
|
|
40
|
+
/** http(s), a host, no path beyond `/`, no query, no fragment, no credentials. */
|
|
41
|
+
function isSiteOrigin(text) {
|
|
42
|
+
try {
|
|
43
|
+
const u = new URL(text);
|
|
44
|
+
return ((u.protocol === "http:" || u.protocol === "https:") &&
|
|
45
|
+
u.pathname === "/" &&
|
|
46
|
+
u.search === "" &&
|
|
47
|
+
u.hash === "" &&
|
|
48
|
+
u.username === "" &&
|
|
49
|
+
u.password === "");
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const ConfigFile = z
|
|
56
|
+
.object({
|
|
57
|
+
keyFile: z.string().min(1),
|
|
58
|
+
relays: z.array(RelayEntry).min(1),
|
|
59
|
+
/** Absent: a public-only server (the public room is its only target). */
|
|
60
|
+
orchestrator: z.string().min(1).optional(),
|
|
61
|
+
/** Read and send in the public room. Default: on without an `orchestrator`, off with one. */
|
|
62
|
+
publicRoom: z.boolean().optional(),
|
|
63
|
+
/** NIP-13 bits a public post is mined to; must match the relay's `BEACON_PUBLIC_DIFFICULTY`. */
|
|
64
|
+
publicPowBits: z.number().int().min(1).max(255).optional(),
|
|
65
|
+
/** The beaconfire site's origin; it enables `beacon_register`. */
|
|
66
|
+
siteUrl: z.string().refine(isSiteOrigin, SITE_URL_MESSAGE).optional(),
|
|
67
|
+
stateDir: z.string().min(1),
|
|
68
|
+
session: z.string().regex(SESSION_PATTERN, SESSION_MESSAGE).optional(),
|
|
69
|
+
})
|
|
70
|
+
.strict()
|
|
71
|
+
.refine((c) => c.orchestrator !== undefined || c.publicRoom !== false, {
|
|
72
|
+
message: "publicRoom is false and no orchestrator is set: the server would expose nothing",
|
|
73
|
+
path: ["publicRoom"],
|
|
74
|
+
});
|
|
75
|
+
/** The relay's default `BEACON_PUBLIC_DIFFICULTY` (AB-12). */
|
|
76
|
+
export const DEFAULT_PUBLIC_POW_BITS = 20;
|
|
77
|
+
export function parseConfig(raw) {
|
|
78
|
+
const c = ConfigFile.parse(raw);
|
|
79
|
+
return {
|
|
80
|
+
keyFile: c.keyFile,
|
|
81
|
+
relays: c.relays.map((r) => ({ url: r.url, authUrl: r.auth_url ?? r.url })),
|
|
82
|
+
orchestrator: c.orchestrator === undefined ? null : pubkeyToHex(c.orchestrator),
|
|
83
|
+
fileSettings: {
|
|
84
|
+
...(c.publicRoom === undefined ? {} : { publicRoom: c.publicRoom }),
|
|
85
|
+
...(c.publicPowBits === undefined ? {} : { publicPowBits: c.publicPowBits }),
|
|
86
|
+
},
|
|
87
|
+
publicRoom: (c.publicRoom ?? c.orchestrator === undefined)
|
|
88
|
+
? { powBits: c.publicPowBits ?? DEFAULT_PUBLIC_POW_BITS }
|
|
89
|
+
: null,
|
|
90
|
+
siteUrl: c.siteUrl === undefined ? null : new URL(c.siteUrl).origin,
|
|
91
|
+
stateDir: c.stateDir,
|
|
92
|
+
session: c.session ?? null,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
export function loadConfig(path) {
|
|
96
|
+
let text;
|
|
97
|
+
try {
|
|
98
|
+
text = readFileSync(path, "utf8");
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
throw new Error(`cannot read config file ${path}`);
|
|
102
|
+
}
|
|
103
|
+
let json;
|
|
104
|
+
try {
|
|
105
|
+
json = JSON.parse(text);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
throw new Error(`config file ${path} is not valid JSON`);
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
return parseConfig(json);
|
|
112
|
+
}
|
|
113
|
+
catch (e) {
|
|
114
|
+
if (e instanceof z.ZodError) {
|
|
115
|
+
const where = e.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`);
|
|
116
|
+
throw new Error(`config file ${path} is invalid: ${where.join("; ")}`);
|
|
117
|
+
}
|
|
118
|
+
throw new Error(`config file ${path} is invalid: ${e.message}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Read the secret key from `path`: one line, `nsec1...` or 64 hex.
|
|
123
|
+
* Refuses a file readable by group or other. Errors name the path and the
|
|
124
|
+
* reason, never the content.
|
|
125
|
+
*/
|
|
126
|
+
export function readSecretKey(path) {
|
|
127
|
+
let mode;
|
|
128
|
+
try {
|
|
129
|
+
mode = statSync(path).mode;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
throw new Error(`cannot read key file ${path}`);
|
|
133
|
+
}
|
|
134
|
+
if ((mode & 0o077) !== 0) {
|
|
135
|
+
throw new Error(`key file ${path} has mode ${(mode & 0o777).toString(8)}; it must not be readable by group or other (chmod 600)`);
|
|
136
|
+
}
|
|
137
|
+
const text = readFileSync(path, "utf8").trim();
|
|
138
|
+
if (hex64.test(text))
|
|
139
|
+
return Uint8Array.from(Buffer.from(text, "hex"));
|
|
140
|
+
if (text.startsWith("nsec1")) {
|
|
141
|
+
try {
|
|
142
|
+
const d = nip19.decode(text);
|
|
143
|
+
if (d.type === "nsec")
|
|
144
|
+
return d.data;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// fall through
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
throw new Error(`key file ${path} does not hold an nsec or 64 hex characters`);
|
|
151
|
+
}
|
package/dist/deps.js
ADDED
package/dist/enroll.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { ToolError } from "./deps.js";
|
|
3
|
+
const hex64 = /^[0-9a-f]{64}$/;
|
|
4
|
+
const TIMEOUT_MS = 15_000;
|
|
5
|
+
/**
|
|
6
|
+
* Registers this agent's key with the site under the account that issued `token` (AB-24). The request
|
|
7
|
+
* is a NIP-98 kind 27235 event (u, method, payload = SHA-256 of the body) signed by this agent's key,
|
|
8
|
+
* so the site learns the key from the signature, never from the body. The site's answer holds the
|
|
9
|
+
* account key `O_a` and its relays; the result is the whole config this server would need, built from
|
|
10
|
+
* the running config (key file, state dir, site URL, session, and a public-room setting only if the file set one) with those two replaced.
|
|
11
|
+
* Nothing is written: the agent replaces its config file and restarts.
|
|
12
|
+
*/
|
|
13
|
+
export async function register(deps, enroll, a, fetchImpl = fetch) {
|
|
14
|
+
const hideToken = (text) => text.split(a.token).join("[token]");
|
|
15
|
+
const body = JSON.stringify({ token: a.token, name: a.name });
|
|
16
|
+
const url = `${enroll.siteUrl}/enroll`;
|
|
17
|
+
const event = deps.signer.sign({
|
|
18
|
+
kind: 27235,
|
|
19
|
+
created_at: deps.now(),
|
|
20
|
+
content: "",
|
|
21
|
+
tags: [
|
|
22
|
+
["u", url],
|
|
23
|
+
["method", "POST"],
|
|
24
|
+
["payload", createHash("sha256").update(body).digest("hex")],
|
|
25
|
+
],
|
|
26
|
+
});
|
|
27
|
+
let res;
|
|
28
|
+
try {
|
|
29
|
+
res = await fetchImpl(url, {
|
|
30
|
+
method: "POST",
|
|
31
|
+
redirect: "error",
|
|
32
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
33
|
+
headers: {
|
|
34
|
+
"content-type": "application/json",
|
|
35
|
+
authorization: `Nostr ${Buffer.from(JSON.stringify(event)).toString("base64")}`,
|
|
36
|
+
},
|
|
37
|
+
body,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw new ToolError(`Could not reach the site at ${enroll.siteUrl}. Calling again with the same token and name is safe.`);
|
|
42
|
+
}
|
|
43
|
+
let answer;
|
|
44
|
+
try {
|
|
45
|
+
answer = (await res.json());
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new ToolError(`The site answered ${res.status} without a message.`);
|
|
49
|
+
}
|
|
50
|
+
if (!res.ok) {
|
|
51
|
+
const text = typeof answer?.error === "string" ? answer.error.slice(0, 500) : "no message";
|
|
52
|
+
throw new ToolError(hideToken(`The site refused (${res.status}): ${text}`));
|
|
53
|
+
}
|
|
54
|
+
const relays = (Array.isArray(answer.relays) ? answer.relays : []);
|
|
55
|
+
const usable = relays.every((r) => typeof r?.url === "string" &&
|
|
56
|
+
/^wss?:\/\//.test(r.url) &&
|
|
57
|
+
(r.auth_url === undefined || typeof r.auth_url === "string"));
|
|
58
|
+
if (typeof answer.name !== "string" ||
|
|
59
|
+
typeof answer.orchestrator !== "string" ||
|
|
60
|
+
!hex64.test(answer.orchestrator) ||
|
|
61
|
+
relays.length === 0 ||
|
|
62
|
+
!usable) {
|
|
63
|
+
throw new ToolError("The site's answer was not understood.");
|
|
64
|
+
}
|
|
65
|
+
const c = enroll.config;
|
|
66
|
+
const config = {
|
|
67
|
+
keyFile: c.keyFile,
|
|
68
|
+
relays: relays.map((r) => (r.auth_url ? { url: r.url, auth_url: r.auth_url } : { url: r.url })),
|
|
69
|
+
orchestrator: answer.orchestrator,
|
|
70
|
+
...c.fileSettings,
|
|
71
|
+
stateDir: c.stateDir,
|
|
72
|
+
...(c.session ? { session: c.session } : {}),
|
|
73
|
+
siteUrl: enroll.siteUrl,
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
registered: answer.name,
|
|
77
|
+
orchestrator: answer.orchestrator,
|
|
78
|
+
config: JSON.stringify(config, null, 2),
|
|
79
|
+
next: "Replace the contents of your MCP config file with `config`, then restart this MCP server to get the roster tools. This tool did not write the file.",
|
|
80
|
+
};
|
|
81
|
+
}
|
package/dist/envelope.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
const hex64 = z.string().regex(/^[0-9a-f]{64}$/);
|
|
3
|
+
export const Envelope = z.object({
|
|
4
|
+
v: z.literal(1),
|
|
5
|
+
type: z.enum(["request", "response", "event", "ack"]),
|
|
6
|
+
/** Sender-chosen ulid, shown to the agent. Not the Nostr id. */
|
|
7
|
+
id: z.string().min(1),
|
|
8
|
+
/** Nostr id (rumor or event id) of the message answered. */
|
|
9
|
+
re: hex64.optional(),
|
|
10
|
+
thread: z.string().min(1).optional(),
|
|
11
|
+
ttl: z.number().int().positive().optional(),
|
|
12
|
+
ct: z.string(),
|
|
13
|
+
body: z.unknown(),
|
|
14
|
+
});
|
|
15
|
+
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
16
|
+
export function ulid(nowMs = Date.now()) {
|
|
17
|
+
let t = nowMs;
|
|
18
|
+
let ts = "";
|
|
19
|
+
for (let i = 0; i < 10; i++) {
|
|
20
|
+
ts = ALPHABET[t % 32] + ts;
|
|
21
|
+
t = Math.floor(t / 32);
|
|
22
|
+
}
|
|
23
|
+
const rnd = crypto.getRandomValues(new Uint8Array(16));
|
|
24
|
+
return ts + Array.from(rnd, (b) => ALPHABET[b % 32]).join("");
|
|
25
|
+
}
|
|
26
|
+
export function buildEnvelope(a) {
|
|
27
|
+
const env = { v: 1, type: a.type, id: ulid(), ct: "application/json", body: a.body };
|
|
28
|
+
if (a.re !== undefined)
|
|
29
|
+
env.re = a.re;
|
|
30
|
+
if (a.thread !== undefined)
|
|
31
|
+
env.thread = a.thread;
|
|
32
|
+
if (a.ttl !== undefined)
|
|
33
|
+
env.ttl = a.ttl;
|
|
34
|
+
return env;
|
|
35
|
+
}
|
|
36
|
+
/** Returns null for malformed content or an unknown version. */
|
|
37
|
+
export function parseEnvelope(content) {
|
|
38
|
+
try {
|
|
39
|
+
const r = Envelope.safeParse(JSON.parse(content));
|
|
40
|
+
return r.success ? r.data : null;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export function expirationOf(tags) {
|
|
47
|
+
const v = tags.find((t) => t[0] === "expiration")?.[1];
|
|
48
|
+
const n = v === undefined ? Number.NaN : Number(v);
|
|
49
|
+
return Number.isFinite(n) ? n : undefined;
|
|
50
|
+
}
|
|
51
|
+
/** True when an `expiration` tag, or `createdAt + ttl`, is in the past. */
|
|
52
|
+
export function isExpired(env, tags, createdAt, now) {
|
|
53
|
+
const exp = expirationOf(tags);
|
|
54
|
+
if (exp !== undefined && exp < now)
|
|
55
|
+
return true;
|
|
56
|
+
return env.ttl !== undefined && createdAt + env.ttl < now;
|
|
57
|
+
}
|
package/dist/groups.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { ToolError } from "./deps.js";
|
|
3
|
+
const TIMEOUT_MS = 15_000;
|
|
4
|
+
/**
|
|
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.
|
|
11
|
+
*/
|
|
12
|
+
export async function groups(deps, site, a, fetchImpl = fetch) {
|
|
13
|
+
if (a.action !== "list" && !a.name) {
|
|
14
|
+
throw new ToolError(`action ${a.action} needs a group name`);
|
|
15
|
+
}
|
|
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
|
+
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
|
+
],
|
|
32
|
+
});
|
|
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;
|
|
53
|
+
try {
|
|
54
|
+
answer = (await res.json());
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
throw new ToolError(`The site answered ${res.status} without a message.`);
|
|
58
|
+
}
|
|
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}`);
|
|
62
|
+
}
|
|
63
|
+
if (a.action !== "list")
|
|
64
|
+
await deps.roster.refresh().catch(() => undefined);
|
|
65
|
+
return answer;
|
|
66
|
+
}
|