Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(federation): verified event identity must win over publisher-controlled content (#3322)

rUv8008bc35621f
diff --git a/plugins/ruflo-core/scripts/escape-cmd-arg.test.cjs b/plugins/ruflo-core/scripts/escape-cmd-arg.test.cjs
new file mode 100644
index 0000000000..db585a75e0
--- /dev/null
+++ b/plugins/ruflo-core/scripts/escape-cmd-arg.test.cjs
@@ -0,0 +1,74 @@
+'use strict';
+/**
+ * Unit tests for ruflo-hook.cjs's escapeCmdArg() β€” the Windows cmd.exe
+ * argument escaper added for the shell:true argv-injection risk in
+ * invokeHook() (hook-derived values reach cmd.exe unescaped on win32).
+ *
+ * These assert the STRING TRANSFORM only β€” there is no Windows/cmd.exe
+ * available in this environment to execute the escaped output end-to-end.
+ * The properties checked below are the ones the algorithm
+ * (https://qntm.org/cmd, matching `cross-spawn`'s Windows escaping) exists
+ * to guarantee: every cmd.exe metacharacter is neutralized, and the
+ * CommandLineToArgvW quote/backslash rules are respected so the value
+ * round-trips as ONE literal argument. Real native-Windows execution
+ * remains a required follow-up gate before calling this closed.
+ */
+const test = require('node:test');
+const assert = require('node:assert/strict');
+// See ruflo-hook.cjs's own comment on this flag: requiring the file always
+// runs main() otherwise (hooks.json has no require.main === module boundary
+// to gate on), which would process.exit(0) before this test file's
+// assertions ever ran.
+process.env.RUFLO_HOOK_UNIT_TEST = '1';
+const { escapeCmdArg } = require('./ruflo-hook.cjs');
+
+const CMD_METACHARS = ['(', ')', '%', '!', '^', '"', '<', '>', '&', '|', ';', ','];
+
+test('escapeCmdArg: every cmd.exe metacharacter is caret-escaped', () => {
+ for (const ch of CMD_METACHARS) {
+ const out = escapeCmdArg(`a${ch}b`);
+ assert.ok(out.includes(`^${ch}`), `expected ^${ch} in ${JSON.stringify(out)} for input a${ch}b`);
+ }
+});
+
+test('escapeCmdArg: a plain value round-trips as one quoted argument', () => {
+ assert.equal(escapeCmdArg('hello'), '^"hello^"');
+ assert.equal(escapeCmdArg('echo hi'), '^"echo hi^"');
+});
+
+test('escapeCmdArg: command chaining metacharacters are neutralized, not left live', () => {
+ // The exact #667 threat model: a hook-derived value like `x & calc.exe` or
+ // `a | b` must not contain a bare, unescaped &/| after escaping.
+ for (const payload of ['a & calc.exe', 'a | b', 'a && b', 'a; rm -rf /', 'a > out.txt', 'a < in.txt']) {
+ const out = escapeCmdArg(payload);
+ assert.ok(!/(?<!\^)[&|;<>]/.test(out), `unescaped metachar survived in ${JSON.stringify(out)}`);
+ }
+});
+
+test('escapeCmdArg: embedded double quotes do not break out of the argument', () => {
+ const out = escapeCmdArg('a"b');
+ // Every quote in the output β€” including the wrapping ones, which the
+ // metachar pass caret-escapes too so they survive a .cmd shim's second
+ // cmd.exe parse β€” must be caret-escaped. No bare, unescaped `"` anywhere.
+ assert.ok(!/(?<!\^)"/.test(out), `bare quote survived in ${JSON.stringify(out)}`);
+});
+
+test('escapeCmdArg: percent (env-var expansion) and delayed-expansion bang are neutralized', () => {
+ assert.ok(escapeCmdArg('%PATH%').includes('^%'));
+ assert.ok(escapeCmdArg('!VAR!').includes('^!'));
+});
+
+test('escapeCmdArg: a trailing backslash does not consume the closing quote', () => {
+ const out = escapeCmdArg('C:\\some\\path\\');
+ // Must end with an escaped-quote sequence, not a bare trailing backslash
+ // eating the terminating quote (the classic CommandLineToArgvW footgun).
+ assert.ok(out.endsWith('\\\\^"') || out.endsWith('^"'), `unexpected ending in ${JSON.stringify(out)}`);
+});
+
+test('escapeCmdArg: empty string still produces a valid quoted-empty argument', () => {
+ assert.equal(escapeCmdArg(''), '^"^"');
+});
+
+test('escapeCmdArg: non-string input is coerced safely', () => {
+ assert.equal(escapeCmdArg(42), '^"42^"');
+});
diff --git a/plugins/ruflo-core/scripts/ruflo-hook.cjs b/plugins/ruflo-core/scripts/ruflo-hook.cjs
index c659ecb9e8..a939a8de5b 100644
--- a/plugins/ruflo-core/scripts/ruflo-hook.cjs
+++ b/plugins/ruflo-core/scripts/ruflo-hook.cjs
@@ -64,6 +64,32 @@ function commandExists(cmd) {
}
}
+/**
+ * Escape one argv element so it survives BOTH parsers a Windows shell:true
+ * spawn puts it through before the target CLI ever sees it:
+ * 1. cmd.exe's own line tokenizer, which still scans for & | < > ^ % ! " ( )
+ * even inside a per-argument quoted segment β€” quoting alone does not
+ * shield cmd.exe metacharacters, and this runs a SECOND time when the
+ * resolved binary is itself a .cmd shim (npm's `ruflo`/`claude-flow`/
+ * `npx` global installs on Windows), because launching a .cmd file is
+ * cmd.exe re-invoking itself on the command line.
+ * 2. The eventual CommandLineToArgvW argv parse in the target process,
+ * which needs backslash-before-quote sequences doubled and the value
+ * quoted so it lands as ONE argument.
+ * Without this, a hook-derived value (e.g. a Bash tool's `command`, or a
+ * file path) containing a shell metacharacter can be reinterpreted as a
+ * separate command / redirection instead of reaching the CLI as literal
+ * data β€” this is the class of bug in CVE-2024-27980 (Node's own .bat/.cmd
+ * argument-injection advisory). Algorithm: https://qntm.org/cmd, the same
+ * reference the `cross-spawn` package's Windows escaping is built from.
+ */
+function escapeCmdArg(arg) {
+ let s = String(arg);
+ s = s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, '$1$1');
+ s = `"${s}"`;
+ return s.replace(/[()%!^"<>&|;,]/g, '^$&');
+}
+
/**
* Spawn the CLI with the hook subcommand + args, forwarding stdinData.
* Returns true on success (exit 0), false otherwise. Never throws.
@@ -72,20 +98,17 @@ function invokeHook(bin, binArgs, hookSubcommand, hookArgs, stdinData) {
const args = [...binArgs, 'hooks', hookSubcommand, ...hookArgs];
// On Windows, shell: true is needed to resolve .cmd/.ps1 shims that npm
// creates for globally-installed bins (`ruflo`, `claude-flow`, `npx`) β€”
- // CreateProcess cannot execute those directly. BUT shell:true hands the
- // whole command line to cmd.exe, which re-tokenizes it (no automatic
- // quoting of array elements), corrupting any argument containing spaces
- // or shell metacharacters β€” e.g. a `post-command` value of "echo hi"
- // silently truncates to "echo", and a heredoc value containing `<<`
- // errors outright. `node` itself is always a real .exe (never a shim),
- // so skip the shell entirely there β€” CreateProcess gets the argv array
- // verbatim, byte-for-byte, no re-tokenization possible. This covers the
- // common `node <cli.js>` invocation (test harness, npx-resolved runs).
- // A real global `ruflo`/`claude-flow` install still goes through the
- // shim path below and inherits cmd.exe's pre-existing argv-mangling
- // limitation for complex values β€” not a regression from this change,
- // just not fully solved by it; tracked as a follow-up.
+ // CreateProcess cannot execute those directly. `node` itself is always a
+ // real .exe (never a shim), so skip the shell entirely there β€”
+ // CreateProcess gets the argv array verbatim, byte-for-byte, no
+ // cmd.exe involved at all. This covers the common `node <cli.js>`
+ // invocation (test harness, npx-resolved runs). A real global
+ // `ruflo`/`claude-flow` install still goes through the shim path below;
+ // every array element is escaped with escapeCmdArg() before it reaches
+ // cmd.exe so hook-derived values can't be reinterpreted as shell syntax.
const useShell = process.platform === 'win32' && bin !== 'node' && bin !== process.execPath;
+ const spawnBin = useShell ? escapeCmdArg(bin) : bin;
+ const spawnArgs = useShell ? args.map(escapeCmdArg) : args;
// Test-only: RUFLO_HOOK_DEBUG_STDOUT surfaces the invoked CLI's own
// stdout/stderr instead of swallowing them, so test-hooks.mjs can assert
// on the CLI's actual recorded value (e.g. catching #1859/#1862-style
@@ -93,7 +116,7 @@ function invokeHook(bin, binArgs, hookSubcommand, hookArgs, stdinData) {
// never leak CLI output into the host (Cursor's PreToolUse contract).
const debug = process.env.RUFLO_HOOK_DEBUG_STDOUT === '1';
try {
- const result = spawnSync(bin, args, {
+ const result = spawnSync(spawnBin, spawnArgs, {
shell: useShell,
input: stdinData || '',
encoding: 'utf8',
@@ -313,4 +336,14 @@ function main() {
done();
}
-main();
+// Test-only: RUFLO_HOOK_UNIT_TEST skips main() so a unit test can require()
+// this file for its pure helpers (escapeCmdArg) without triggering the real
+// hook flow / process.exit(0). hooks.json always invokes this file via a
+// plain require() inside a `node -e` wrapper (see the header comment) β€” there
+// is no `require.main === module` boundary to gate on β€” so main() must
+// default to running unconditionally in every other context.
+if (process.env.RUFLO_HOOK_UNIT_TEST !== '1') {
+ main();
+}
+
+module.exports = { escapeCmdArg };
diff --git a/plugins/ruflo-x-gateway/src/nostr-federation.mjs b/plugins/ruflo-x-gateway/src/nostr-federation.mjs
index 88720f7330..99083215cd 100644
--- a/plugins/ruflo-x-gateway/src/nostr-federation.mjs
+++ b/plugins/ruflo-x-gateway/src/nostr-federation.mjs
@@ -87,7 +87,12 @@ export async function fetchRecent(relayUrl, sk, { sinceSeconds = 3600, limit = 1
const m = JSON.parse(data.toString());
if (m[0] === 'EVENT' && verifyEvent(m[2])) {
let body; try { body = JSON.parse(m[2].content); } catch { body = { raw: m[2].content }; }
- out.push({ id: m[2].id, pubkey: m[2].pubkey, created_at: m[2].created_at, ...body });
+ // Verified envelope fields MUST win over anything the publisher put in
+ // their own (attacker-controlled) content β€” spreading body first, then
+ // overwriting id/pubkey/created_at, is the only order a publisher can't
+ // use to impersonate another member's identity downstream (reduceClaims
+ // trusts .pubkey for release/handoff authorization).
+ out.push({ ...body, id: m[2].id, pubkey: m[2].pubkey, created_at: m[2].created_at });
} else if (m[0] === 'EOSE') { clearTimeout(timer); try { ws.close(); } catch {} resolve(out); }
});
ws.send(JSON.stringify(['REQ', 'ruflo-sync', filter]));
@@ -105,7 +110,7 @@ export async function fetchManyOn(relayUrl, sk, filters) {
ws.on('message', (data) => {
const m = JSON.parse(data.toString());
const idx = typeof m[1] === 'string' && m[1].startsWith('q') ? Number(m[1].slice(1)) : -1;
- if (m[0] === 'EVENT' && idx >= 0 && verifyEvent(m[2])) { let body; try { body = JSON.parse(m[2].content); } catch { body = { raw: m[2].content }; } results[idx].push({ id: m[2].id, pubkey: m[2].pubkey, created_at: m[2].created_at, ...body }); }
+ if (m[0] === 'EVENT' && idx >= 0 && verifyEvent(m[2])) { let body; try { body = JSON.parse(m[2].content); } catch { body = { raw: m[2].content }; } results[idx].push({ ...body, id: m[2].id, pubkey: m[2].pubkey, created_at: m[2].created_at }); }
else if (m[0] === 'EOSE' && idx >= 0) { ws.send(JSON.stringify(['CLOSE', m[1]])); if (--open === 0) { clearTimeout(timer); finish(); } }
});
filters.forEach((f, i) => ws.send(JSON.stringify(['REQ', 'q' + i, { kinds: [SWARM_KIND], '#t': [SWARM_TAG], since: Math.floor(Date.now() / 1000) - (f.sinceSeconds ?? 3600), limit: f.limit ?? 100, ...(f.type ? { '#k': [String(f.type)] } : {}) }])));
@@ -158,7 +163,9 @@ export async function fetchChannel(relayUrl, sk, { channelId, sinceSeconds = 360
const k = e.tags.find((t) => t[0] === 'k')?.[1];
const rec = { id: e.id, pubkey: e.pubkey, created_at: e.created_at, channel: h, k };
if (k === 'enc') out.push({ ...rec, encrypted: true, content: e.content });
- else { let body; try { body = JSON.parse(e.content); } catch { body = { raw: e.content }; } out.push({ ...rec, ...body }); }
+ // Same override hazard as fetchRecent/fetchManyOn: rec's verified id/pubkey/
+ // created_at must be applied AFTER body, not before.
+ else { let body; try { body = JSON.parse(e.content); } catch { body = { raw: e.content }; } out.push({ ...body, ...rec }); }
} else if (m[0] === 'EOSE') { clearTimeout(timer); try { ws.close(); } catch {} resolve(out); }
});
ws.send(JSON.stringify(['REQ', 'ruflo-channel', filter]));
diff --git a/plugins/ruflo-x-gateway/test/gateway.test.mjs b/plugins/ruflo-x-gateway/test/gateway.test.mjs
index ea3642c341..ac9bb06d5d 100644
--- a/plugins/ruflo-x-gateway/test/gateway.test.mjs
+++ b/plugins/ruflo-x-gateway/test/gateway.test.mjs
@@ -148,6 +148,69 @@ test('hardening: publish bounds, bucket eviction, ws maxPayload/404, fetchManyOn
assert.equal(out.length, 3); assert.equal(handshakes, 1); assert.equal(reqs, 3);
});
+test('security: verified pubkey/id/created_at cannot be overridden by spoofed content (fetchRecent, fetchManyOn, fetchChannel)', async () => {
+ const { fetchRecent, fetchManyOn, fetchChannel } = await import('../src/nostr-federation.mjs');
+ const attacker = generateSecretKey(); const attackerPk = getPublicKey(attacker);
+ const victimPk = getPublicKey(generateSecretKey());
+ // Signed legitimately under the attacker's OWN key, but the JSON content
+ // claims to be a ClaimReleased from the victim β€” this is exactly what
+ // reduceClaims would need to see to let the attacker forge a release/handoff.
+ const spoofContent = JSON.stringify({ type: 'ClaimReleased', pubkey: victimPk, id: 'f'.repeat(64), created_at: 1, resourceId: 'r1' });
+
+ // fetchRecent
+ let wss = new WebSocketServer({ port: 0 });
+ await new Promise((r) => wss.once('listening', r));
+ wss.on('connection', (s) => { s.send(JSON.stringify(['AUTH', 'c'])); s.on('message', (d) => {
+ const m = JSON.parse(d);
+ if (m[0] === 'AUTH') s.send(JSON.stringify(['OK', m[1].id, true, '']));
+ if (m[0] === 'REQ') {
+ const ev = finalizeEvent({ kind: 1, created_at: 1000, tags: [], content: spoofContent }, attacker);
+ s.send(JSON.stringify(['EVENT', m[1], ev]));
+ s.send(JSON.stringify(['EOSE', m[1]]));
+ }
+ }); });
+ let out = await fetchRecent(`ws://127.0.0.1:${wss.address().port}`, generateSecretKey(), {});
+ wss.close();
+ assert.equal(out.length, 1);
+ assert.equal(out[0].pubkey, attackerPk, 'fetchRecent: verified pubkey must win over spoofed content.pubkey');
+ assert.notEqual(out[0].pubkey, victimPk);
+ assert.equal(out[0].created_at, 1000, 'fetchRecent: verified created_at must win over spoofed content.created_at');
+
+ // fetchManyOn (per-filter 'qN' REQ ids)
+ wss = new WebSocketServer({ port: 0 });
+ await new Promise((r) => wss.once('listening', r));
+ wss.on('connection', (s) => { s.send(JSON.stringify(['AUTH', 'c'])); s.on('message', (d) => {
+ const m = JSON.parse(d);
+ if (m[0] === 'AUTH') s.send(JSON.stringify(['OK', m[1].id, true, '']));
+ if (m[0] === 'REQ') {
+ const ev = finalizeEvent({ kind: 1, created_at: 1000, tags: [], content: spoofContent }, attacker);
+ s.send(JSON.stringify(['EVENT', m[1], ev]));
+ s.send(JSON.stringify(['EOSE', m[1]]));
+ }
+ }); });
+ const [many] = await fetchManyOn(`ws://127.0.0.1:${wss.address().port}`, generateSecretKey(), [{ limit: 1 }]);
+ wss.close();
+ assert.equal(many.length, 1);
+ assert.equal(many[0].pubkey, attackerPk, 'fetchManyOn: verified pubkey must win over spoofed content.pubkey');
+
+ // fetchChannel (plaintext branch)
+ wss = new WebSocketServer({ port: 0 });
+ await new Promise((r) => wss.once('listening', r));
+ wss.on('connection', (s) => { s.send(JSON.stringify(['AUTH', 'c'])); s.on('message', (d) => {
+ const m = JSON.parse(d);
+ if (m[0] === 'AUTH') s.send(JSON.stringify(['OK', m[1].id, true, '']));
+ if (m[0] === 'REQ') {
+ const ev = finalizeEvent({ kind: 1, created_at: 1000, tags: [['c', 'pub:ops'], ['k', 'ClaimReleased']], content: spoofContent }, attacker);
+ s.send(JSON.stringify(['EVENT', m[1], ev]));
+ s.send(JSON.stringify(['EOSE', m[1]]));
+ }
+ }); });
+ const chan = await fetchChannel(`ws://127.0.0.1:${wss.address().port}`, generateSecretKey(), { channelId: 'pub:ops' });
+ wss.close();
+ assert.equal(chan.length, 1);
+ assert.equal(chan[0].pubkey, attackerPk, 'fetchChannel: verified pubkey must win over spoofed content.pubkey');
+});
+
// ---- ADR-386 channels ----
test('channels: ids, seal/open, non-member cannot open, type hidden on private', async () => {
const c = await import('../src/channels.mjs');
diff --git a/scripts/audit-env-var-precedence.mjs b/scripts/audit-env-var-precedence.mjs
index ed47608605..67f50b2a53 100644
--- a/scripts/audit-env-var-precedence.mjs
+++ b/scripts/audit-env-var-precedence.mjs
@@ -61,6 +61,7 @@ const KNOWN_ESCAPE_HATCHES = new Set([
'RUFLO_HOOK_SKIP_NPX', // CI: suppress cold-install latency in smoke tests
'RUFLO_HOOK_CLI_OVERRIDE', // #2721 test-only: point plugins/ruflo-core/scripts/ruflo-hook.cjs at a local CLI build instead of the ruflo/claude-flow/npx PATH probe. Hook scripts have no CLI-flag surface (invoked by hooks.json, never a user-typed command)
'RUFLO_HOOK_DEBUG_STDOUT', // #2721 test-only: surface the invoked CLI's stdout/stderr from ruflo-hook.cjs instead of swallowing it, so test-hooks.mjs can assert on recorded values. Same no-CLI-surface reasoning as RUFLO_HOOK_CLI_OVERRIDE above β€” production never sets this
+ 'RUFLO_HOOK_UNIT_TEST', // test-only: skip main() when ruflo-hook.cjs is require()'d by escape-cmd-arg.test.cjs, so the unit test can reach escapeCmdArg() without triggering the real hook flow / process.exit(0). Same no-CLI-surface reasoning β€” hooks.json always require()s this file directly, there is no invocation to attach a flag to
'RUFLO_SUBLINEAR_NATIVE', // Manual override for native vs WASM sublinear β€” CI/perf knob
'RUFLO_METAHARNESS_CACHE_BASE', // CI/test seam: relocates the ~/.ruflo pinned-cache root in metaharness smoke tests β€” intentionally env-only, plugin scripts have no CLI-flag surface
'RUFLO_FUNNEL', // Read inside the generated hook-handler.cjs (ADR-312/313 rate-limit nudge), not a typed CLI invocation β€” no command surface to attach a flag to
diff --git a/scripts/ci-test-baseline.txt b/scripts/ci-test-baseline.txt
index 52e790597c..53ad170b45 100644
--- a/scripts/ci-test-baseline.txt
+++ b/scripts/ci-test-baseline.txt
@@ -7,6 +7,7 @@ plugins/ruflo-adr/scripts/__tests__/index-idempotency-2660.test.mjs
plugins/ruflo-adr/scripts/__tests__/parser-bullets-2659.test.mjs
plugins/ruflo-adr/scripts/__tests__/skip-brain-dir-2911.test.mjs
plugins/ruflo-business-pods/scripts/pod-tick.test.mjs
+plugins/ruflo-core/scripts/escape-cmd-arg.test.cjs
plugins/ruflo-core/scripts/mcp-launch.test.cjs
plugins/ruflo-workflows/scripts/gaia-audit.test.mjs
ruflo/src/ruvocal/src/lib/components/chat/MarkdownRenderer.svelte.test.ts
diff --git a/v3/@claude-flow/cli/src/mcp-tools/x-federation-channels.ts b/v3/@claude-flow/cli/src/mcp-tools/x-federation-channels.ts
index c513cd7c62..a5aad562c1 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/x-federation-channels.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/x-federation-channels.ts
@@ -28,6 +28,7 @@ export const CHANNEL_ID_RE = /^(pub:[a-z0-9][a-z0-9._-]{0,63}|prv:[0-9a-f]{16})$
type Nt = {
generateSecretKey: () => Uint8Array; getPublicKey: (sk: Uint8Array) => string;
finalizeEvent: (t: Record<string, unknown>, sk: Uint8Array) => Record<string, unknown> & { id: string };
+ verifyEvent: (e: Record<string, unknown>) => boolean;
};
type Nip44 = { v2: { encrypt: (p: string, k: Uint8Array) => string; decrypt: (c: string, k: Uint8Array) => string; utils: { getConversationKey: (sk: Uint8Array, pk: string) => Uint8Array } } };
async function loadTools(): Promise<{ nt: Nt; nip44: Nip44 } | null> {
@@ -87,12 +88,17 @@ function publishEvent(ws: WsLike, nt: Nt, sk: Uint8Array, tags: string[][], cont
ws.send(JSON.stringify(['EVENT', ev]));
});
}
-function reqEvents(ws: WsLike, filter: Record<string, unknown>): Promise<Array<Record<string, unknown>>> {
+function reqEvents(ws: WsLike, nt: Nt, filter: Record<string, unknown>): Promise<Array<Record<string, unknown>>> {
const out: Array<Record<string, unknown>> = [];
return new Promise((resolve) => {
const t = setTimeout(() => resolve(out), 12000);
ws.on('message', (d: Buffer) => { const m = JSON.parse(d.toString());
- if (m[0] === 'EVENT') out.push(m[2]);
+ // Only a signature-verified event can be trusted as evidence of who sent
+ // it. Without this check an unverified EVENT frame β€” relay bug, MITM, or
+ // a compromised relay β€” would reach callers that treat .pubkey/.id as
+ // authenticated (channel_accept's NIP-44 conversation-key derivation,
+ // channel_read's returned identity).
+ if (m[0] === 'EVENT' && nt.verifyEvent(m[2])) out.push(m[2]);
else if (m[0] === 'EOSE') { clearTimeout(t); resolve(out); } });
ws.send(JSON.stringify(['REQ', 'ruflo-ch', filter]));
});
@@ -153,7 +159,7 @@ export const xFederationChannelTools: MCPTool[] = [
const t = await loadTools(); if (!t) return degraded();
const { sk, pubkey } = loadOrCreateKey(t.nt as never, KEY_FILE());
const relay = RELAY_WS(i.relayWs);
- const evs = await relayCall(relay, sk, t.nt, (ws) => reqEvents(ws, {
+ const evs = await relayCall(relay, sk, t.nt, (ws) => reqEvents(ws, t.nt, {
kinds: [1], '#t': ['ruflo-swarm'], '#k': ['ChannelGrant'], '#p': [pubkey],
since: Math.floor(Date.now() / 1000) - (i.sinceSeconds ?? 7 * 86400), limit: 200,
}));
@@ -216,7 +222,7 @@ export const xFederationChannelTools: MCPTool[] = [
if (!CHANNEL_ID_RE.test(i.channel)) throw new Error('channel must be pub:<name> or prv:<16 hex>');
const t = await loadTools(); if (!t) return degraded();
const { sk } = loadOrCreateKey(t.nt as never, KEY_FILE());
- const evs = await relayCall(RELAY_WS(i.relayWs), sk, t.nt, (ws) => reqEvents(ws, {
+ const evs = await relayCall(RELAY_WS(i.relayWs), sk, t.nt, (ws) => reqEvents(ws, t.nt, {
kinds: [1], '#t': ['ruflo-swarm'], '#c': [i.channel],
since: Math.floor(Date.now() / 1000) - (i.sinceSeconds ?? 3600), limit: i.limit ?? 100,
}));
@@ -226,9 +232,12 @@ export const xFederationChannelTools: MCPTool[] = [
const ev = e as { id: string; pubkey: string; created_at: number; content: string; tags: string[][] };
const k = ev.tags.find((x) => x[0] === 'k')?.[1];
const base = { id: ev.id, pubkey: ev.pubkey, created_at: ev.created_at };
- if (k !== 'enc') { try { return { ...base, ...(JSON.parse(ev.content) as object) }; } catch { return { ...base, raw: ev.content }; } }
+ // base's verified id/pubkey/created_at must win over the parsed/decrypted
+ // body β€” spread body first so a stray id/pubkey/created_at key in the
+ // publisher's own content can't override the authenticated identity.
+ if (k !== 'enc') { try { return { ...(JSON.parse(ev.content) as object), ...base }; } catch { return { ...base, raw: ev.content }; } }
if (!key) return { ...base, encrypted: true, reason: 'no channel key held' };
- try { return { ...base, ...(JSON.parse(t.nip44.v2.decrypt(ev.content, key)) as object) }; }
+ try { return { ...(JSON.parse(t.nip44.v2.decrypt(ev.content, key)) as object), ...base }; }
catch { return { ...base, encrypted: true, reason: 'held key does not open this message' }; }
});
return { channel: i.channel, visibility: isPrivateChannel(i.channel) ? 'private' : 'public', count: messages.length, messages };