claude-flow 3.40.0 → 3.41.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/.claude-plugin/marketplace.json +18 -18
- package/package.json +1 -1
- package/v3/@claude-flow/cli/catalog-manifest.json +3 -3
- package/v3/@claude-flow/cli/dist/src/commands/federation.d.ts +8 -0
- package/v3/@claude-flow/cli/dist/src/commands/federation.js +98 -0
- package/v3/@claude-flow/cli/dist/src/commands/index.d.ts +1 -0
- package/v3/@claude-flow/cli/dist/src/commands/index.js +4 -0
- package/v3/@claude-flow/cli/dist/src/commands/memory.js +11 -0
- package/v3/@claude-flow/cli/dist/src/mcp-client.js +8 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/index.d.ts +4 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/index.js +4 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/seraphina-tools.d.ts +21 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/seraphina-tools.js +88 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/x-federation-channels.d.ts +30 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/x-federation-channels.js +299 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/x-federation-join.d.ts +31 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/x-federation-join.js +87 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/x-federation-tools.d.ts +12 -0
- package/v3/@claude-flow/cli/dist/src/mcp-tools/x-federation-tools.js +96 -0
- package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.d.ts +4 -0
- package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.js +66 -14
- package/v3/@claude-flow/cli/dist/src/memory/sibling-store.d.ts +11 -0
- package/v3/@claude-flow/cli/dist/src/memory/sibling-store.js +53 -0
- package/v3/@claude-flow/cli/dist/src/services/distill-oracle.d.ts +1 -1
- package/v3/@claude-flow/cli/dist/src/services/distill-oracle.js +1 -1
- package/v3/@claude-flow/cli/package.json +4 -3
- package/.claude/.proven-config-version +0 -1
- package/.claude/proven-config.json +0 -42
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join, dirname } from 'node:path';
|
|
5
|
+
import { loadOrCreateKey } from './x-federation-join.js';
|
|
6
|
+
// ADR-125 precedence: tool args > env var > default.
|
|
7
|
+
const RELAY_WS = (o) => o || process.env.RUFLO_X_RELAY_WS || 'wss://relay.ruv.io';
|
|
8
|
+
const KEY_FILE = () => process.env.RUFLO_NOSTR_KEY_FILE || join(homedir(), '.ruflo', 'nostr.key');
|
|
9
|
+
const STORE_FILE = () => process.env.RUFLO_CHANNELS_FILE || join(homedir(), '.ruflo', 'channels.json');
|
|
10
|
+
export const CHANNEL_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
11
|
+
export const CHANNEL_ID_RE = /^(pub:[a-z0-9][a-z0-9._-]{0,63}|prv:[0-9a-f]{16})$/;
|
|
12
|
+
async function loadTools() {
|
|
13
|
+
try {
|
|
14
|
+
const nt = (await import('nostr-tools/pure'));
|
|
15
|
+
const { nip44 } = (await import('nostr-tools'));
|
|
16
|
+
return { nt, nip44 };
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const degraded = () => ({ degraded: true, reason: 'nostr-tools not installed', hint: 'npm i nostr-tools (secp256k1 + NIP-44 are not in node:crypto)' });
|
|
23
|
+
export function readStore(file = STORE_FILE()) {
|
|
24
|
+
if (!existsSync(file))
|
|
25
|
+
return {};
|
|
26
|
+
try {
|
|
27
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return {};
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function writeStore(store, file = STORE_FILE()) {
|
|
34
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
35
|
+
writeFileSync(file, JSON.stringify(store, null, 2), { mode: 0o600 });
|
|
36
|
+
}
|
|
37
|
+
export function publicChannelId(name) {
|
|
38
|
+
if (!CHANNEL_NAME_RE.test(String(name)))
|
|
39
|
+
throw new Error('channel name must match [a-z0-9][a-z0-9._-]{0,63}');
|
|
40
|
+
return `pub:${name}`;
|
|
41
|
+
}
|
|
42
|
+
export function privateChannelId(keyHex) {
|
|
43
|
+
const k = Buffer.from(keyHex, 'hex');
|
|
44
|
+
if (k.length !== 32)
|
|
45
|
+
throw new Error('channel key must be 32 bytes (64 hex)');
|
|
46
|
+
return `prv:${createHash('sha256').update(k).digest('hex').slice(0, 16)}`;
|
|
47
|
+
}
|
|
48
|
+
export function newChannelKey() { return randomBytes(32).toString('hex'); }
|
|
49
|
+
export function isPrivateChannel(id) { return String(id).startsWith('prv:'); }
|
|
50
|
+
async function relayCall(relayWs, sk, nt, fn) {
|
|
51
|
+
const { default: WebSocket } = await import('ws');
|
|
52
|
+
const ws = new WebSocket(relayWs, { perMessageDeflate: false });
|
|
53
|
+
await new Promise((resolve, reject) => {
|
|
54
|
+
const t = setTimeout(() => reject(new Error('relay auth timeout')), 15000);
|
|
55
|
+
ws.on('message', (d) => {
|
|
56
|
+
const m = JSON.parse(d.toString());
|
|
57
|
+
if (m[0] === 'AUTH' && typeof m[1] === 'string') {
|
|
58
|
+
ws.send(JSON.stringify(['AUTH', nt.finalizeEvent({ kind: 22242, created_at: Math.floor(Date.now() / 1000), tags: [['relay', relayWs], ['challenge', m[1]]], content: '' }, sk)]));
|
|
59
|
+
}
|
|
60
|
+
else if (m[0] === 'OK') {
|
|
61
|
+
clearTimeout(t);
|
|
62
|
+
m[2] ? resolve() : reject(new Error(`relay refused auth: ${m[3] || 'not a member'}`));
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
ws.on('error', (e) => { clearTimeout(t); reject(e); });
|
|
66
|
+
});
|
|
67
|
+
try {
|
|
68
|
+
return await fn(ws);
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
try {
|
|
72
|
+
ws.close();
|
|
73
|
+
}
|
|
74
|
+
catch { /* */ }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function publishEvent(ws, nt, sk, tags, content) {
|
|
78
|
+
const ev = nt.finalizeEvent({ kind: 1, created_at: Math.floor(Date.now() / 1000), tags, content }, sk);
|
|
79
|
+
return new Promise((resolve, reject) => {
|
|
80
|
+
const t = setTimeout(() => reject(new Error('publish timeout')), 15000);
|
|
81
|
+
ws.on('message', (d) => {
|
|
82
|
+
const m = JSON.parse(d.toString());
|
|
83
|
+
if (m[0] === 'OK' && m[1] === ev.id) {
|
|
84
|
+
clearTimeout(t);
|
|
85
|
+
m[2] ? resolve(ev.id) : reject(new Error(m[3] || 'publish rejected'));
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
ws.send(JSON.stringify(['EVENT', ev]));
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
function reqEvents(ws, filter) {
|
|
92
|
+
const out = [];
|
|
93
|
+
return new Promise((resolve) => {
|
|
94
|
+
const t = setTimeout(() => resolve(out), 12000);
|
|
95
|
+
ws.on('message', (d) => {
|
|
96
|
+
const m = JSON.parse(d.toString());
|
|
97
|
+
if (m[0] === 'EVENT')
|
|
98
|
+
out.push(m[2]);
|
|
99
|
+
else if (m[0] === 'EOSE') {
|
|
100
|
+
clearTimeout(t);
|
|
101
|
+
resolve(out);
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
ws.send(JSON.stringify(['REQ', 'ruflo-ch', filter]));
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
export const xFederationChannelTools = [
|
|
108
|
+
{
|
|
109
|
+
name: 'x_federation_channel_create',
|
|
110
|
+
description: 'Create a swarm channel. visibility=public gives a named stream every relay member can read (pub:<name>). visibility=private generates a 32-byte key HERE, stores it at ~/.ruflo/channels.json (0600), and returns an opaque id (prv:<hex>) that leaks neither the name nor the topic. Use when a stream of work should be separated from the shared firehose, or kept unreadable by the relay and the gateway. Creating a private channel and then expecting the gateway to read it is wrong: the gateway holds no channel key and cannot decrypt (ADR-386). Losing the key file loses the channel.',
|
|
111
|
+
inputSchema: { type: 'object', properties: {
|
|
112
|
+
name: { type: 'string', description: 'Channel name, [a-z0-9][a-z0-9._-]{0,63}. For a private channel this is a local label only — it never reaches the relay.' },
|
|
113
|
+
visibility: { type: 'string', enum: ['public', 'private'], description: 'public = plaintext, readable by all members. private = NIP-44 encrypted under a key only you hold.' },
|
|
114
|
+
}, required: ['name', 'visibility'] },
|
|
115
|
+
handler: async (input) => {
|
|
116
|
+
const { name, visibility } = input;
|
|
117
|
+
if (visibility === 'public')
|
|
118
|
+
return { channel: publicChannelId(name), visibility, note: 'Any relay member can read this channel.' };
|
|
119
|
+
const key = newChannelKey();
|
|
120
|
+
const channel = privateChannelId(key);
|
|
121
|
+
const store = readStore();
|
|
122
|
+
store[channel] = { key, name, at: new Date().toISOString() };
|
|
123
|
+
writeStore(store);
|
|
124
|
+
return { channel, visibility, name, keyStoredAt: STORE_FILE(),
|
|
125
|
+
note: 'The key never leaves this machine. Grant others with x_federation_channel_grant. There is no recovery if the key file is lost, and no revocation — removing someone means rotating to a new channel.' };
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
name: 'x_federation_channel_grant',
|
|
130
|
+
description: "Grant a member access to a private channel by sealing its key to their pubkey with NIP-44 (ECDH), published as a ChannelGrant event only they can open. Use when adding a participant to an existing private channel. Publishing the raw key into a channel or a chat is wrong: it is a bearer secret, and anyone who sees it can read every past and future message, because there is no revocation.",
|
|
131
|
+
inputSchema: { type: 'object', properties: {
|
|
132
|
+
channel: { type: 'string', description: 'Private channel id (prv:<16 hex>) you hold the key for.' },
|
|
133
|
+
pubkey: { type: 'string', description: "The member's 64-hex Nostr pubkey." },
|
|
134
|
+
relayWs: { type: 'string', description: 'Relay URL; takes precedence over RUFLO_X_RELAY_WS (default wss://relay.ruv.io).' },
|
|
135
|
+
}, required: ['channel', 'pubkey'] },
|
|
136
|
+
handler: async (input) => {
|
|
137
|
+
const i = input;
|
|
138
|
+
if (!isPrivateChannel(i.channel))
|
|
139
|
+
throw new Error('only private channels have keys to grant');
|
|
140
|
+
if (!/^[0-9a-f]{64}$/i.test(i.pubkey))
|
|
141
|
+
throw new Error('pubkey must be 64 hex');
|
|
142
|
+
const t = await loadTools();
|
|
143
|
+
if (!t)
|
|
144
|
+
return degraded();
|
|
145
|
+
const entry = readStore()[i.channel];
|
|
146
|
+
if (!entry)
|
|
147
|
+
throw new Error(`no key held for ${i.channel} — create it or accept a grant first`);
|
|
148
|
+
const { sk, pubkey } = loadOrCreateKey(t.nt, KEY_FILE());
|
|
149
|
+
const conv = t.nip44.v2.utils.getConversationKey(sk, i.pubkey);
|
|
150
|
+
const sealed = t.nip44.v2.encrypt(entry.key, conv);
|
|
151
|
+
const relay = RELAY_WS(i.relayWs);
|
|
152
|
+
const eventId = await relayCall(relay, sk, t.nt, (ws) => publishEvent(ws, t.nt, sk, [['t', 'ruflo-swarm'], ['k', 'ChannelGrant'], ['c', i.channel], ['p', i.pubkey]], JSON.stringify({ type: 'ChannelGrant', channel: i.channel, sealed, ts: new Date().toISOString() })));
|
|
153
|
+
return { ok: true, channel: i.channel, grantedTo: i.pubkey, grantedBy: pubkey, eventId,
|
|
154
|
+
note: 'Only that pubkey can open the seal. Grants are not revocable — rotate the channel to remove someone.' };
|
|
155
|
+
},
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
name: 'x_federation_channel_accept',
|
|
159
|
+
description: 'Accept private-channel grants addressed to your key: finds ChannelGrant events tagged to your pubkey, opens each with your own secret key, and caches the channel keys locally. Use when someone tells you they granted you a channel. Asking them to send you the key directly is wrong because it exposes a bearer secret in a channel you do not control.',
|
|
160
|
+
inputSchema: { type: 'object', properties: {
|
|
161
|
+
sinceSeconds: { type: 'number', description: 'Look-back window (default 7 days).' },
|
|
162
|
+
relayWs: { type: 'string', description: 'Relay URL; takes precedence over RUFLO_X_RELAY_WS.' },
|
|
163
|
+
}, required: [] },
|
|
164
|
+
handler: async (input) => {
|
|
165
|
+
const i = input;
|
|
166
|
+
const t = await loadTools();
|
|
167
|
+
if (!t)
|
|
168
|
+
return degraded();
|
|
169
|
+
const { sk, pubkey } = loadOrCreateKey(t.nt, KEY_FILE());
|
|
170
|
+
const relay = RELAY_WS(i.relayWs);
|
|
171
|
+
const evs = await relayCall(relay, sk, t.nt, (ws) => reqEvents(ws, {
|
|
172
|
+
kinds: [1], '#t': ['ruflo-swarm'], '#k': ['ChannelGrant'], '#p': [pubkey],
|
|
173
|
+
since: Math.floor(Date.now() / 1000) - (i.sinceSeconds ?? 7 * 86400), limit: 200,
|
|
174
|
+
}));
|
|
175
|
+
const store = readStore();
|
|
176
|
+
const accepted = [];
|
|
177
|
+
const failed = [];
|
|
178
|
+
for (const e of evs) {
|
|
179
|
+
const ev = e;
|
|
180
|
+
let body;
|
|
181
|
+
try {
|
|
182
|
+
body = JSON.parse(ev.content);
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (!body.channel || !body.sealed)
|
|
188
|
+
continue;
|
|
189
|
+
try {
|
|
190
|
+
const conv = t.nip44.v2.utils.getConversationKey(sk, ev.pubkey);
|
|
191
|
+
const key = t.nip44.v2.decrypt(body.sealed, conv);
|
|
192
|
+
if (!/^[0-9a-f]{64}$/.test(key) || privateChannelId(key) !== body.channel) {
|
|
193
|
+
failed.push(body.channel);
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
store[body.channel] = { key, grantedBy: ev.pubkey, at: new Date().toISOString() };
|
|
197
|
+
accepted.push(body.channel);
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
failed.push(body.channel);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (accepted.length)
|
|
204
|
+
writeStore(store);
|
|
205
|
+
return { pubkey, accepted: [...new Set(accepted)], unopenable: [...new Set(failed)], keyStoredAt: STORE_FILE() };
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
name: 'x_federation_channel_publish',
|
|
210
|
+
description: 'Publish a message to a channel with YOUR OWN key. A private channel is encrypted locally under its channel key before it leaves this machine, and the message type is hidden behind k=enc so the relay sees only an opaque id and ciphertext. Use when the message should be attributable to you. The admin-gated gateway channel_publish is wrong for that, because it signs as the gateway and cannot reach private channels at all.',
|
|
211
|
+
inputSchema: { type: 'object', properties: {
|
|
212
|
+
channel: { type: 'string', description: 'Channel id (pub:<name> or prv:<16 hex>).' },
|
|
213
|
+
msgType: { type: 'string', description: 'Message type (Status, Task, Result, …). Hidden on private channels.' },
|
|
214
|
+
payload: { type: 'object', description: 'JSON body. Never put secrets or credentials in it, even on a private channel.' },
|
|
215
|
+
relayWs: { type: 'string', description: 'Relay URL; takes precedence over RUFLO_X_RELAY_WS.' },
|
|
216
|
+
}, required: ['channel', 'msgType', 'payload'] },
|
|
217
|
+
handler: async (input) => {
|
|
218
|
+
const i = input;
|
|
219
|
+
if (!CHANNEL_ID_RE.test(i.channel))
|
|
220
|
+
throw new Error('channel must be pub:<name> or prv:<16 hex>');
|
|
221
|
+
const t = await loadTools();
|
|
222
|
+
if (!t)
|
|
223
|
+
return degraded();
|
|
224
|
+
const { sk, pubkey } = loadOrCreateKey(t.nt, KEY_FILE());
|
|
225
|
+
const priv = isPrivateChannel(i.channel);
|
|
226
|
+
const body = { type: i.msgType, from: pubkey, ts: new Date().toISOString(), ...i.payload };
|
|
227
|
+
let content;
|
|
228
|
+
if (priv) {
|
|
229
|
+
const entry = readStore()[i.channel];
|
|
230
|
+
if (!entry)
|
|
231
|
+
throw new Error(`no key held for ${i.channel} — accept a grant first (x_federation_channel_accept)`);
|
|
232
|
+
content = t.nip44.v2.encrypt(JSON.stringify(body), Uint8Array.from(Buffer.from(entry.key, 'hex')));
|
|
233
|
+
}
|
|
234
|
+
else {
|
|
235
|
+
content = JSON.stringify(body);
|
|
236
|
+
}
|
|
237
|
+
const tags = [['t', 'ruflo-swarm'], ['c', i.channel], ['k', priv ? 'enc' : i.msgType]];
|
|
238
|
+
const eventId = await relayCall(RELAY_WS(i.relayWs), sk, t.nt, (ws) => publishEvent(ws, t.nt, sk, tags, content));
|
|
239
|
+
return { ok: true, channel: i.channel, visibility: priv ? 'private' : 'public', encrypted: priv, eventId, pubkey };
|
|
240
|
+
},
|
|
241
|
+
},
|
|
242
|
+
{
|
|
243
|
+
name: 'x_federation_channel_read',
|
|
244
|
+
description: 'Read a channel and decrypt what your keys can open. Public messages come back as JSON; private ones are decrypted locally with the cached channel key, and anything you have no key for is returned as encrypted:true rather than silently dropped. Use when the channel is private: reading it through the gateway channel_sync tool is wrong there, because the gateway holds no key and can only hand you ciphertext.',
|
|
245
|
+
inputSchema: { type: 'object', properties: {
|
|
246
|
+
channel: { type: 'string', description: 'Channel id (pub:<name> or prv:<16 hex>).' },
|
|
247
|
+
sinceSeconds: { type: 'number', description: 'Look-back window (default 3600).' },
|
|
248
|
+
limit: { type: 'number', description: 'Max messages (default 100).' },
|
|
249
|
+
relayWs: { type: 'string', description: 'Relay URL; takes precedence over RUFLO_X_RELAY_WS.' },
|
|
250
|
+
}, required: ['channel'] },
|
|
251
|
+
handler: async (input) => {
|
|
252
|
+
const i = input;
|
|
253
|
+
if (!CHANNEL_ID_RE.test(i.channel))
|
|
254
|
+
throw new Error('channel must be pub:<name> or prv:<16 hex>');
|
|
255
|
+
const t = await loadTools();
|
|
256
|
+
if (!t)
|
|
257
|
+
return degraded();
|
|
258
|
+
const { sk } = loadOrCreateKey(t.nt, KEY_FILE());
|
|
259
|
+
const evs = await relayCall(RELAY_WS(i.relayWs), sk, t.nt, (ws) => reqEvents(ws, {
|
|
260
|
+
kinds: [1], '#t': ['ruflo-swarm'], '#c': [i.channel],
|
|
261
|
+
since: Math.floor(Date.now() / 1000) - (i.sinceSeconds ?? 3600), limit: i.limit ?? 100,
|
|
262
|
+
}));
|
|
263
|
+
const entry = readStore()[i.channel];
|
|
264
|
+
const key = entry ? Uint8Array.from(Buffer.from(entry.key, 'hex')) : null;
|
|
265
|
+
const messages = evs.map((e) => {
|
|
266
|
+
const ev = e;
|
|
267
|
+
const k = ev.tags.find((x) => x[0] === 'k')?.[1];
|
|
268
|
+
const base = { id: ev.id, pubkey: ev.pubkey, created_at: ev.created_at };
|
|
269
|
+
if (k !== 'enc') {
|
|
270
|
+
try {
|
|
271
|
+
return { ...base, ...JSON.parse(ev.content) };
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
return { ...base, raw: ev.content };
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (!key)
|
|
278
|
+
return { ...base, encrypted: true, reason: 'no channel key held' };
|
|
279
|
+
try {
|
|
280
|
+
return { ...base, ...JSON.parse(t.nip44.v2.decrypt(ev.content, key)) };
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
return { ...base, encrypted: true, reason: 'held key does not open this message' };
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
return { channel: i.channel, visibility: isPrivateChannel(i.channel) ? 'private' : 'public', count: messages.length, messages };
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
{
|
|
290
|
+
name: 'x_federation_channel_list',
|
|
291
|
+
description: 'List the private channels this machine holds keys for, plus their local labels. Use when you want to know what you can actually read before calling channel_read. The gateway channel_list is the wrong tool for that: it reports channels seen on the relay, including ones whose contents you cannot open.',
|
|
292
|
+
inputSchema: { type: 'object', properties: {}, required: [] },
|
|
293
|
+
handler: async () => {
|
|
294
|
+
const store = readStore();
|
|
295
|
+
return { keyStoredAt: STORE_FILE(), channels: Object.entries(store).map(([channel, v]) => ({ channel, name: v.name, grantedBy: v.grantedBy, at: v.at })) };
|
|
296
|
+
},
|
|
297
|
+
},
|
|
298
|
+
];
|
|
299
|
+
//# sourceMappingURL=x-federation-channels.js.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-service join for the open swarm federation — the user-facing invite path.
|
|
3
|
+
*
|
|
4
|
+
* Decentralized by design: the user generates/holds THEIR OWN Nostr key locally,
|
|
5
|
+
* redeems an invite code with a NIP-98-signed claim (no admin in the loop), proves
|
|
6
|
+
* membership with NIP-42, and announces themselves. The gateway never signs for them.
|
|
7
|
+
*
|
|
8
|
+
* `nostr-tools` is an optional dependency (secp256k1/Schnorr is not in node:crypto):
|
|
9
|
+
* when absent the tool degrades with an install hint instead of throwing at load.
|
|
10
|
+
*/
|
|
11
|
+
import type { MCPTool } from './types.js';
|
|
12
|
+
type NostrTools = {
|
|
13
|
+
generateSecretKey: () => Uint8Array;
|
|
14
|
+
getPublicKey: (sk: Uint8Array) => string;
|
|
15
|
+
finalizeEvent: (t: Record<string, unknown>, sk: Uint8Array) => Record<string, unknown> & {
|
|
16
|
+
id: string;
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
export declare function loadOrCreateKey(nt: NostrTools, file?: string): {
|
|
20
|
+
sk: Uint8Array;
|
|
21
|
+
pubkey: string;
|
|
22
|
+
created: boolean;
|
|
23
|
+
};
|
|
24
|
+
export declare function nip98Header(nt: NostrTools, sk: Uint8Array, url: string, method: string, body?: string): string;
|
|
25
|
+
export declare function verifyMembership(nt: NostrTools, sk: Uint8Array, relayWs: string): Promise<{
|
|
26
|
+
ok: boolean;
|
|
27
|
+
reason?: string;
|
|
28
|
+
}>;
|
|
29
|
+
export declare const xFederationJoinTools: MCPTool[];
|
|
30
|
+
export {};
|
|
31
|
+
//# sourceMappingURL=x-federation-join.d.ts.map
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join, dirname } from 'node:path';
|
|
5
|
+
// ADR-125 precedence: tool args (relayHttp / relayWs / keyFile) take precedence over the
|
|
6
|
+
// RUFLO_X_RELAY_HTTP / RUFLO_X_RELAY_WS / RUFLO_NOSTR_KEY_FILE env vars, which precede defaults.
|
|
7
|
+
const HTTP_BASE = (o) => (o || process.env.RUFLO_X_RELAY_HTTP || 'https://relay.ruv.io').replace(/\/$/, '');
|
|
8
|
+
const RELAY_WS = (o) => o || process.env.RUFLO_X_RELAY_WS || 'wss://relay.ruv.io';
|
|
9
|
+
const KEY_FILE = () => process.env.RUFLO_NOSTR_KEY_FILE || join(homedir(), '.ruflo', 'nostr.key');
|
|
10
|
+
const hex = (b) => Buffer.from(b).toString('hex');
|
|
11
|
+
const unhex = (h) => Uint8Array.from(Buffer.from(h, 'hex'));
|
|
12
|
+
async function loadNostrTools() {
|
|
13
|
+
try {
|
|
14
|
+
return (await import('nostr-tools/pure'));
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export function loadOrCreateKey(nt, file = KEY_FILE()) {
|
|
21
|
+
if (existsSync(file)) {
|
|
22
|
+
const sk = unhex(readFileSync(file, 'utf8').trim());
|
|
23
|
+
return { sk, pubkey: nt.getPublicKey(sk), created: false };
|
|
24
|
+
}
|
|
25
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
26
|
+
const sk = nt.generateSecretKey();
|
|
27
|
+
writeFileSync(file, hex(sk), { mode: 0o600 });
|
|
28
|
+
return { sk, pubkey: nt.getPublicKey(sk), created: true };
|
|
29
|
+
}
|
|
30
|
+
export function nip98Header(nt, sk, url, method, body) {
|
|
31
|
+
const ev = nt.finalizeEvent({ kind: 27235, created_at: Math.floor(Date.now() / 1000),
|
|
32
|
+
tags: [['u', url], ['method', method], ...(body ? [['payload', createHash('sha256').update(body).digest('hex')]] : [])], content: '' }, sk);
|
|
33
|
+
return 'Nostr ' + Buffer.from(JSON.stringify(ev)).toString('base64');
|
|
34
|
+
}
|
|
35
|
+
// NIP-42: connect, answer the challenge, resolve true/false (never throws on refusal).
|
|
36
|
+
export async function verifyMembership(nt, sk, relayWs) {
|
|
37
|
+
const { default: WebSocket } = await import('ws');
|
|
38
|
+
return new Promise((resolve) => {
|
|
39
|
+
const ws = new WebSocket(relayWs, { perMessageDeflate: false });
|
|
40
|
+
let done = false;
|
|
41
|
+
const fin = (r) => { if (done)
|
|
42
|
+
return; done = true; try {
|
|
43
|
+
ws.close();
|
|
44
|
+
}
|
|
45
|
+
catch { /* */ } resolve(r); };
|
|
46
|
+
ws.on('message', (d) => {
|
|
47
|
+
const m = JSON.parse(d.toString());
|
|
48
|
+
if (m[0] === 'AUTH' && typeof m[1] === 'string')
|
|
49
|
+
ws.send(JSON.stringify(['AUTH', nt.finalizeEvent({ kind: 22242, created_at: Math.floor(Date.now() / 1000), tags: [['relay', relayWs], ['challenge', m[1]]], content: '' }, sk)]));
|
|
50
|
+
else if (m[0] === 'OK')
|
|
51
|
+
fin({ ok: !!m[2], reason: m[3] });
|
|
52
|
+
});
|
|
53
|
+
ws.on('error', (e) => fin({ ok: false, reason: e.message }));
|
|
54
|
+
setTimeout(() => fin({ ok: false, reason: 'timeout' }), 15000);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
export const xFederationJoinTools = [{
|
|
58
|
+
name: 'x_federation_join',
|
|
59
|
+
description: 'Join the open swarm federation with YOUR OWN key using an invite code: generates (or reuses) a local Nostr key at ~/.ruflo/nostr.key (0600), redeems the code with a NIP-98-signed claim directly against the relay, proves membership via NIP-42, and returns your pubkey. Use when you have been handed an invite code and want to participate as yourself. Asking an admin to `federation_admit` you instead is wrong for an open swarm because it centralizes onboarding and requires trusting a pubkey out of band; the invite claim binds membership to the key you hold. Never share the invite code publicly — it is a bearer secret.',
|
|
60
|
+
inputSchema: { type: 'object', properties: {
|
|
61
|
+
code: { type: 'string', description: 'Invite code (v2.…) received privately from a member/admin.' },
|
|
62
|
+
relayHttp: { type: 'string', description: 'Relay HTTPS base for the claim; takes precedence over RUFLO_X_RELAY_HTTP.' },
|
|
63
|
+
relayWs: { type: 'string', description: 'Relay wss URL for NIP-42; takes precedence over RUFLO_X_RELAY_WS.' },
|
|
64
|
+
keyFile: { type: 'string', description: 'Key file path; takes precedence over RUFLO_NOSTR_KEY_FILE (default ~/.ruflo/nostr.key).' }
|
|
65
|
+
}, required: ['code'] },
|
|
66
|
+
handler: async (input) => {
|
|
67
|
+
const i = input;
|
|
68
|
+
const nt = await loadNostrTools();
|
|
69
|
+
// Validate input before the optional-dependency check so a bad code fails fast and identically
|
|
70
|
+
// whether or not nostr-tools is present.
|
|
71
|
+
if (!/^v2\.[A-Za-z0-9._-]{8,}$/.test(i.code))
|
|
72
|
+
throw new Error('invite code must look like v2.<token>');
|
|
73
|
+
if (!nt)
|
|
74
|
+
return { degraded: true, reason: 'nostr-tools not installed', hint: 'npm i -g nostr-tools (secp256k1 signing is not in node:crypto)' };
|
|
75
|
+
const { sk, pubkey, created } = loadOrCreateKey(nt, i.keyFile);
|
|
76
|
+
const url = `${HTTP_BASE(i.relayHttp)}/api/invites/claim`;
|
|
77
|
+
const body = JSON.stringify({ code: i.code });
|
|
78
|
+
const r = await fetch(url, { method: 'POST', headers: { Authorization: nip98Header(nt, sk, url, 'POST', body), 'Content-Type': 'application/json' }, body, signal: AbortSignal.timeout(20_000) });
|
|
79
|
+
const claim = (await r.json().catch(() => ({})));
|
|
80
|
+
if (!r.ok)
|
|
81
|
+
throw new Error(`claim rejected (${r.status}): ${claim.error ?? claim.message ?? 'unknown'}`);
|
|
82
|
+
const auth = await verifyMembership(nt, sk, RELAY_WS(i.relayWs));
|
|
83
|
+
return { ok: auth.ok, pubkey, keyCreated: created, role: claim.role ?? 'member', membershipVerified: auth.ok, ...(auth.ok ? {} : { reason: auth.reason }),
|
|
84
|
+
next: 'Publish kind-1 events tagged ["t","ruflo-swarm"] — or run `ruflo federation sync` to read the swarm.' };
|
|
85
|
+
},
|
|
86
|
+
}];
|
|
87
|
+
//# sourceMappingURL=x-federation-join.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* x.ruv.io open swarm federation — ruflo-native MCP tools.
|
|
3
|
+
*
|
|
4
|
+
* Bridges ruflo to the open, membership-gated, signed Nostr federation behind
|
|
5
|
+
* https://x.ruv.io. Reads are open; writes made with the GATEWAY identity need
|
|
6
|
+
* the gateway admin token (RUFLO_X_ADMIN_TOKEN). Users who want to publish as
|
|
7
|
+
* themselves should join with their own key via invite→claim (see the
|
|
8
|
+
* `ruv://federation/registry` resource), not through these gateway-identity tools.
|
|
9
|
+
*/
|
|
10
|
+
import type { MCPTool } from './types.js';
|
|
11
|
+
export declare const xFederationTools: MCPTool[];
|
|
12
|
+
//# sourceMappingURL=x-federation-tools.d.ts.map
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// ADR-125 precedence: the tool arg `gatewayUrl` (fed by `ruflo federation --gateway`)
|
|
2
|
+
// takes precedence over the RUFLO_X_GATEWAY_URL env var, which precedes the default.
|
|
3
|
+
const GATEWAY = (override) => ((typeof override === 'string' && override) || process.env.RUFLO_X_GATEWAY_URL || 'https://x.ruv.io').replace(/\/$/, '');
|
|
4
|
+
const gatewayArg = { gatewayUrl: { type: 'string', description: 'Gateway base URL; takes precedence over RUFLO_X_GATEWAY_URL (default https://x.ruv.io).' } };
|
|
5
|
+
const TIMEOUT_MS = 25_000;
|
|
6
|
+
/** Minimal MCP-over-Streamable-HTTP client: POST JSON-RPC, parse the SSE `data:` frame. */
|
|
7
|
+
async function gatewayRpc(method, params, gatewayUrl) {
|
|
8
|
+
const res = await fetch(`${GATEWAY(gatewayUrl)}/mcp`, {
|
|
9
|
+
method: 'POST',
|
|
10
|
+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
|
|
11
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: Date.now(), method, params }),
|
|
12
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
13
|
+
});
|
|
14
|
+
const text = await res.text();
|
|
15
|
+
const line = text.split('\n').find((l) => l.startsWith('data:'));
|
|
16
|
+
const payload = JSON.parse(line ? line.slice(5) : text);
|
|
17
|
+
if (payload.error)
|
|
18
|
+
throw new Error(`x.ruv.io: ${payload.error.message ?? 'rpc error'}`);
|
|
19
|
+
return payload.result;
|
|
20
|
+
}
|
|
21
|
+
async function gatewayTool(name, args) {
|
|
22
|
+
const { gatewayUrl, ...rest } = args;
|
|
23
|
+
const r = (await gatewayRpc('tools/call', { name, arguments: rest }, gatewayUrl));
|
|
24
|
+
const text = r.content?.[0]?.text ?? '{}';
|
|
25
|
+
const parsed = JSON.parse(text);
|
|
26
|
+
if (r.isError || parsed.error)
|
|
27
|
+
throw new Error(String(parsed.error ?? 'gateway tool error'));
|
|
28
|
+
return parsed;
|
|
29
|
+
}
|
|
30
|
+
async function gatewayResource(uri, gatewayUrl) {
|
|
31
|
+
const r = (await gatewayRpc('resources/read', { uri }, gatewayUrl));
|
|
32
|
+
return JSON.parse(r.contents?.[0]?.text ?? '{}');
|
|
33
|
+
}
|
|
34
|
+
// Credential: intentionally env-only (a secret must never be a CLI flag — it would land in
|
|
35
|
+
// shell history / process lists). Registered in scripts/audit-env-var-precedence.mjs.
|
|
36
|
+
const adminToken = () => process.env.RUFLO_X_ADMIN_TOKEN;
|
|
37
|
+
export const xFederationTools = [
|
|
38
|
+
{
|
|
39
|
+
name: 'x_federation_sync',
|
|
40
|
+
description: 'Fetch recent signature-verified coordination messages from the open x.ruv.io swarm federation (Nostr, #t=ruflo-swarm). Use when you need to see what other ruflo nodes across the internet have posted (PeerHello/Status/Task/Result/Claim*). Reading the relay directly is wrong because you would have to do NIP-42 auth yourself; the gateway does it and only returns events whose signatures verify.',
|
|
41
|
+
inputSchema: { type: 'object', properties: { ...gatewayArg, sinceSeconds: { type: 'number', description: 'Look-back window (default 3600).' }, limit: { type: 'number', description: 'Max messages (default 100).' }, type: { type: 'string', description: 'Optional message type filter, e.g. Task.' } } },
|
|
42
|
+
handler: async (input) => gatewayTool('federation_sync', input),
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
name: 'x_federation_roster',
|
|
46
|
+
description: 'List nodes currently announcing themselves on the open swarm (recent PeerHello events) via the ruv://swarm/roster resource. Use when you need to know who is online across the federation before assigning work. Grepping sync output by hand is wrong because the roster resource already de-duplicates by pubkey and carries lastSeen.',
|
|
47
|
+
inputSchema: { type: 'object', properties: { ...gatewayArg } },
|
|
48
|
+
handler: async (input) => gatewayResource('ruv://swarm/roster', input.gatewayUrl),
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
name: 'x_federation_claims',
|
|
52
|
+
description: 'Return the current owner-per-resource work-claims ledger for the open swarm (ruv://claims/board). Use when you are about to start shared work and need to know whether a resourceId is already owned. Inferring ownership from raw ClaimIssued events is wrong because releases, TTL expiry and handoffs change the answer; the board applies those rules.',
|
|
53
|
+
inputSchema: { type: 'object', properties: { ...gatewayArg } },
|
|
54
|
+
handler: async (input) => gatewayResource('ruv://claims/board', input.gatewayUrl),
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
name: 'x_federation_registry',
|
|
58
|
+
description: 'Read the federation registry resource (ruv://federation/registry): relay URL, canonical relay tag for NIP-42, gateway pubkey, and the exact self-join steps. Use when onboarding a new node or user to the open federation. Hard-coding the relay URL is wrong because the relay verifies the NIP-42 relay tag strictly against its canonical host, which this resource states.',
|
|
59
|
+
inputSchema: { type: 'object', properties: { ...gatewayArg } },
|
|
60
|
+
handler: async (input) => gatewayResource('ruv://federation/registry', input.gatewayUrl),
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
name: 'x_federation_publish',
|
|
64
|
+
description: 'Publish a signed coordination message to the open swarm AS THE GATEWAY identity (Status/Task/Result/…). Requires RUFLO_X_ADMIN_TOKEN. Use when a trusted operator needs a hub-level broadcast. Using this to post on behalf of an individual node is wrong because it attributes the message to the gateway, not the node — nodes should join with their own key via invite→claim and publish themselves.',
|
|
65
|
+
inputSchema: { type: 'object', properties: { ...gatewayArg, msgType: { type: 'string' }, payload: { type: 'object' } }, required: ['msgType', 'payload'] },
|
|
66
|
+
handler: async (input) => {
|
|
67
|
+
const t = adminToken();
|
|
68
|
+
if (!t)
|
|
69
|
+
throw new Error('RUFLO_X_ADMIN_TOKEN is not set (gateway-identity writes are admin-gated)');
|
|
70
|
+
return gatewayTool('federation_publish', { ...input, adminToken: t });
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
name: 'x_federation_invite_mint',
|
|
75
|
+
description: 'Mint a use-limited, expiring invite code so a new ruflo user can self-join the open federation with THEIR OWN key. Requires RUFLO_X_ADMIN_TOKEN. Use when onboarding someone. Sharing the relay owner key instead is wrong because invites are revocable, hashed at rest, and bind membership to the claimant\'s key; the code is a bearer secret — hand it over privately.',
|
|
76
|
+
inputSchema: { type: 'object', properties: { ...gatewayArg, ttlSecs: { type: 'number', description: 'Validity (default 7 days).' }, maxUses: { type: 'number', description: 'Redemptions (default 25).' } } },
|
|
77
|
+
handler: async (input) => {
|
|
78
|
+
const t = adminToken();
|
|
79
|
+
if (!t)
|
|
80
|
+
throw new Error('RUFLO_X_ADMIN_TOKEN is not set (invite minting is admin-gated)');
|
|
81
|
+
return gatewayTool('federation_invite_mint', { ...input, adminToken: t });
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
name: 'x_federation_admit',
|
|
86
|
+
description: 'Admit a Nostr pubkey as a relay member directly (NIP-43 kind 9030). Requires RUFLO_X_ADMIN_TOKEN. Use when a known node reports its 64-hex pubkey and you want to skip the invite step. Padding or hand-editing a reported pubkey is wrong because it is a cryptographic identity; a malformed key must be re-reported, never fixed up.',
|
|
87
|
+
inputSchema: { type: 'object', properties: { ...gatewayArg, pubkey: { type: 'string', description: '64-hex secp256k1 x-only pubkey.' }, role: { type: 'string', enum: ['member', 'admin'] } }, required: ['pubkey'] },
|
|
88
|
+
handler: async (input) => {
|
|
89
|
+
const t = adminToken();
|
|
90
|
+
if (!t)
|
|
91
|
+
throw new Error('RUFLO_X_ADMIN_TOKEN is not set (admission is admin-gated)');
|
|
92
|
+
return gatewayTool('federation_admit', { ...input, adminToken: t });
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
];
|
|
96
|
+
//# sourceMappingURL=x-federation-tools.js.map
|
|
@@ -34,6 +34,10 @@ export declare function shouldDisableNativeBridge(platform?: NodeJS.Platform, en
|
|
|
34
34
|
* noise. Suppress the banners, keep the bad news.
|
|
35
35
|
*/
|
|
36
36
|
export declare function shouldSuppressInitLog(msg: string): boolean;
|
|
37
|
+
/** Test seam: forget cached registries so a test can exercise a fresh open. */
|
|
38
|
+
export declare function _resetRegistryCacheForTest(): void;
|
|
39
|
+
/** #3196: the sibling store AgentDB owns next to a given sql.js database. */
|
|
40
|
+
export declare function siblingAgentDbPath(dbPath: string): string | null;
|
|
37
41
|
/**
|
|
38
42
|
* Create/migrate the bridge's `memory_entries` table on `db`.
|
|
39
43
|
*
|