Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

feat(plugins): sensitive userConfig secrets + readSecret + secrets audit (ADR-506) (#4587)

rUv658f0e33bf48
diff --git a/.github/workflows/v3-ci.yml b/.github/workflows/v3-ci.yml
index 39e867cec7..eec8d6ef56 100644
--- a/.github/workflows/v3-ci.yml
+++ b/.github/workflows/v3-ci.yml
@@ -1731,7 +1731,8 @@ jobs:
# peer, (B) no bare-stable peer range that can't resolve a 3.x prerelease
# publish, (C) every main/module/exports path is covered by `files`,
# (D) after building each plugin, every main/module/exports path exists on
- # disk (#1904). The build step is what makes check D live.
+ # disk (#1904). The build step is what makes check D live. Also runs the
+ # ADR-506 plugin secrets audit (sensitive userConfig, no literal secrets).
name: Plugin package install-safety (#1902/#1903/#1904)
runs-on: ubuntu-latest
@@ -1784,6 +1785,12 @@ jobs:
shell: bash
run: node scripts/audit-plugin-packages.mjs
+ - name: Run plugin secrets audit (ADR-506)
+ # A credential-named userConfig option must be "sensitive": true (credential store, masked),
+ # and no plugin.json / hooks.json may carry a literal secret (the mods' screen shapes).
+ shell: bash
+ run: node scripts/audit-plugin-secrets.mjs
+
- name: Run package dep-overlap audit (#1147 / #2018)
# Static guard for the "Invalid Version: " npm 11.x crash. Any package
# declaring the same dep name in both optionalDependencies AND
diff --git a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
index bebe6cad12..8909764e1f 100644
--- a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
+++ b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-cost-tracker",
"description": "Token usage tracking, model cost attribution per agent, budget alerts, and optimization recommendations β€” uses memory_* (namespace-routed) for cost-tracking and cost-patterns; pairs with federation budget circuit breaker (ADR-097)",
- "version": "0.28.3",
+ "version": "0.29.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -55,5 +55,14 @@
"observability",
"federation",
"interop"
- ]
+ ],
+ "userConfig": {
+ "openrouterApiKey": {
+ "type": "string",
+ "title": "OpenRouter API key",
+ "description": "Lets cost-openrouter read your OpenRouter key usage and per-request cost. Kept in the credential store, never in settings; OPENROUTER_API_KEY still works when this is empty.",
+ "required": false,
+ "sensitive": true
+ }
+ }
}
diff --git a/plugins/ruflo-cost-tracker/CHANGELOG.md b/plugins/ruflo-cost-tracker/CHANGELOG.md
index feaad32ed2..1e106accb2 100644
--- a/plugins/ruflo-cost-tracker/CHANGELOG.md
+++ b/plugins/ruflo-cost-tracker/CHANGELOG.md
@@ -2,6 +2,9 @@
Newest first. One `## <version> β€” <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-cost-tracker`.
+## 0.29.0 β€” 2026-10-29
+- feat: `openrouterApiKey` is a `userConfig` option with `sensitive: true` (ADR-506, #4587): entered masked, kept in the platform credential store, read through `readSecret` before the `OPENROUTER_API_KEY` environment fallback; never logged or put on a command line.
+
## 0.28.3 β€” 2026-10-24
- fix: `ledger.mjs`, `advise.mjs` and `local-cost.mjs` do nothing on Windows: they ran only when `import.meta.url === "file://" + argv[1]`, which is never true there (`file:///C:/…` against `C:…`), so every call exited 0 with no output. They now compare against `pathToFileURL(argv[1])`.
- fix: `ledger.mjs --project` takes a drive-lettered path, and the project filter matches Windows paths ignoring separator style and drive-letter case, so the ruflo console's mission spend works on Windows.
diff --git a/plugins/ruflo-cost-tracker/README.md b/plugins/ruflo-cost-tracker/README.md
index 49337e45b7..2d0c35c823 100644
--- a/plugins/ruflo-cost-tracker/README.md
+++ b/plugins/ruflo-cost-tracker/README.md
@@ -39,7 +39,7 @@ claude --plugin-dir plugins/ruflo-cost-tracker
| `cost-health` | `/cost-health [--alert-acceleration 100] [--alert-outliers 1] [--skip burn,anomaly]` | **Composite CI gate** β€” runs budget+burn+anomaly+projection in parallel, returns `max(exit)`. One shell-out covers all four alert ladders. |
| `cost-ledger` | `/cost-ledger [--since 7d] [--provider claude\|codex\|grok\|all]` | **Multi-provider** spend, tokens and cache hit ratio from the local Claude Code, Codex and Grok logs; unpriced models flagged, USD and credits never mixed. |
| `cost-advise` | `/cost-advise [--since 7d]` | **Optimisation findings** from your own logs (cache discipline, 1h cache TTL, sub-agent tier, Codex reasoning share, context bloat) with what-if savings. |
-| `cost-openrouter` | `/cost-openrouter key\|generation <id>\|credits` | OpenRouter's own billed cost, key limits and credits. Network + key: asks first (`--yes`), key only from the environment. |
+| `cost-openrouter` | `/cost-openrouter key\|generation <id>\|credits` | OpenRouter's own billed cost, key limits and credits. Network + key: asks first (`--yes`); the key is `$OPENROUTER_API_KEY`, never an argument; a key stored as the sensitive option `openrouterApiKey` (credential store) is exported as `OPENROUTER_API_KEY` to the session's commands by the plugin's SessionStart hook when that variable is unset (ADR-506). |
| `cost-local` | `/cost-local --tok-per-s <n> [--busy 0.25] [--compare <model>]` | Cost per 1M tokens on your own hardware (fixed + marginal) and the utilisation at which it beats a hosted model. |
| `cost-conversation` | `/cost-conversation` | Per-conversation cost view (different lens from cost-report's per-agent / per-model) |
| `cost-export` | `/cost-export [--prometheus <path>] [--webhook <url>]` | Emit cost data as Prometheus textfile or POST to a webhook |
diff --git a/plugins/ruflo-cost-tracker/hooks/hooks.json b/plugins/ruflo-cost-tracker/hooks/hooks.json
index 203b2fa4ba..307851e911 100644
--- a/plugins/ruflo-cost-tracker/hooks/hooks.json
+++ b/plugins/ruflo-cost-tracker/hooks/hooks.json
@@ -1,6 +1,16 @@
{
- "description": "Stop hook auto-runs cost-track at session end so the cost-tracking namespace stays populated without users remembering to run `/cost-track` manually. TRACK_QUIET=1 suppresses the markdown summary. A track failure never blocks session end β€” analytics data is best-effort, not load-bearing (see scripts/ruflo-hook.cjs). The command is a `node -e` bootstrap: it resolves scripts/ruflo-hook.cjs from process.env.CLAUDE_PLUGIN_ROOT inside Node (no shell `${VAR}`/`%VAR%` expansion), so the exact same command string runs unchanged on Windows, macOS, and Linux β€” no bash or /dev/null redirection involved.",
+ "description": "Stop hook auto-runs cost-track at session end so the cost-tracking namespace stays populated without users remembering to run `/cost-track` manually. TRACK_QUIET=1 suppresses the markdown summary. A track failure never blocks session end β€” analytics data is best-effort, not load-bearing (see scripts/ruflo-hook.cjs). The command is a `node -e` bootstrap: it resolves scripts/ruflo-hook.cjs from process.env.CLAUDE_PLUGIN_ROOT inside Node (no shell `${VAR}`/`%VAR%` expansion), so the exact same command string runs unchanged on Windows, macOS, and Linux β€” no bash or /dev/null redirection involved. A SessionStart hook hands the sensitive option openrouterApiKey to the Bash tool as OPENROUTER_API_KEY through CLAUDE_ENV_FILE, only when that variable is not already set, so /cost-openrouter can use a key kept in the credential store (scripts/_secret-env.cjs, ADR-506).",
"hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node -e \"require(require('path').join(process.env.CLAUDE_PLUGIN_ROOT,'scripts','_secret-env.cjs')).bridge({openrouterApiKey:'OPENROUTER_API_KEY'})\""
+ }
+ ]
+ }
+ ],
"Stop": [
{
"hooks": [
diff --git a/plugins/ruflo-cost-tracker/scripts/_secret-env.cjs b/plugins/ruflo-cost-tracker/scripts/_secret-env.cjs
new file mode 100644
index 0000000000..63abf7faa5
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/scripts/_secret-env.cjs
@@ -0,0 +1,50 @@
+// Secret bridge (ADR-506): hand a sensitive `userConfig` option to the scripts a skill or command runs
+// through the Bash tool. Copied verbatim into each plugin that needs it (a test keeps the copies identical).
+//
+// Claude Code gives a plugin's option only to that plugin's hooks, as CLAUDE_PLUGIN_OPTION_<KEY>; the Bash
+// tool never sees it. A SessionStart hook, though, gets CLAUDE_ENV_FILE, and the lines it appends there are
+// loaded into every later Bash tool command of the session. So the plugin's SessionStart hook calls
+// bridge({ option: 'VARIABLE' }) and the script reads VARIABLE as it always did.
+//
+// Exposure: the value then sits in the session's environment file (under ~/.claude, owner-only) and in the
+// environment of the session's Bash commands, the same as exporting it in a shell profile. What the option
+// adds is masked entry and credential-store storage instead of a plain-text profile or .env file.
+//
+// Rules: a variable the user already exported wins and is never overwritten; the value is never printed,
+// logged or put in argv; a value with a newline or NUL is refused; any failure is silent and never blocks
+// the session.
+'use strict'
+const fs = require('fs')
+
+const optionEnvName = (name) => `CLAUDE_PLUGIN_OPTION_${String(name).replace(/[^A-Za-z0-9_]/g, '_').toUpperCase()}`
+const VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/
+const quote = (value) => `'${value.replace(/'/g, `'\\''`)}'`
+
+/** The env-file lines for the options that are set and whose variable is not. Never contains a value that was not asked for. */
+function bridgeLines(map, env = process.env) {
+ const lines = []
+ for (const [option, variable] of Object.entries(map || {})) {
+ if (!VARIABLE.test(variable)) continue
+ if (typeof env[variable] === 'string' && env[variable].trim() !== '') continue
+ const value = env[optionEnvName(option)]
+ if (typeof value !== 'string' || value.trim() === '' || /[\n\r\0]/.test(value)) continue
+ lines.push(`export ${variable}=${quote(value)}`)
+ }
+ return lines
+}
+
+/** Append the lines to CLAUDE_ENV_FILE (owner-only). Returns the variable NAMES written, never values. */
+function bridge(map, env = process.env) {
+ try {
+ const file = env.CLAUDE_ENV_FILE
+ if (!file) return []
+ const lines = bridgeLines(map, env)
+ if (lines.length === 0) return []
+ fs.appendFileSync(file, lines.join('\n') + '\n', { mode: 0o600 })
+ return lines.map((line) => line.slice('export '.length, line.indexOf('=')))
+ } catch {
+ return []
+ }
+}
+
+module.exports = { bridge, bridgeLines, optionEnvName }
diff --git a/plugins/ruflo-cost-tracker/scripts/_secret.mjs b/plugins/ruflo-cost-tracker/scripts/_secret.mjs
new file mode 100644
index 0000000000..d5f4fde716
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/scripts/_secret.mjs
@@ -0,0 +1,35 @@
+// readSecret: one way to read a plugin credential (ADR-506). Copied verbatim into each plugin that
+// needs it, since a plugin may not import from another plugin's folder; keep the copies identical
+// (a test compares them).
+//
+// Order: CLAUDE_PLUGIN_OPTION_<NAME>, which Claude Code sets for a plugin's hooks when the
+// `userConfig` option (declared with "sensitive": true, kept in the credential store) is filled in;
+// then the environment variables the plugin always read, for standalone CLI use and backward
+// compatibility. The value is never logged, echoed, or placed in an error message.
+
+/** The environment variable Claude Code sets for a `userConfig` key (non-identifier characters to `_`, upper-cased). */
+export const optionEnvName = (name) => `CLAUDE_PLUGIN_OPTION_${String(name).replace(/[^A-Za-z0-9_]/g, '_').toUpperCase()}`
+
+/** The secret, or undefined when neither the option nor any fallback variable holds a non-empty value. Read at call time. */
+export function readSecret(name, envFallbacks = [], env = process.env) {
+ for (const variable of [optionEnvName(name), ...envFallbacks]) {
+ const value = env[variable]
+ if (typeof value === 'string' && value.trim() !== '') return value
+ }
+ return undefined
+}
+
+/** Where the secret was found (a variable NAME, never the value), or undefined. */
+export function secretSource(name, envFallbacks = [], env = process.env) {
+ for (const variable of [optionEnvName(name), ...envFallbacks]) {
+ const value = env[variable]
+ if (typeof value === 'string' && value.trim() !== '') return variable
+ }
+ return undefined
+}
+
+/** Error text for a missing secret: names the option and the variables, never a value. */
+export function secretHint(name, envFallbacks = []) {
+ const vars = envFallbacks.length ? ` or export ${envFallbacks.join(' / ')} in your shell` : ''
+ return `no ${name} configured: set the plugin option "${name}" with /plugin (it is stored in the credential store)${vars}. Never paste a key into a prompt or a file.`
+}
diff --git a/plugins/ruflo-cost-tracker/scripts/openrouter.mjs b/plugins/ruflo-cost-tracker/scripts/openrouter.mjs
index 874719ae7c..f992c4e8e2 100644
--- a/plugins/ruflo-cost-tracker/scripts/openrouter.mjs
+++ b/plugins/ruflo-cost-tracker/scripts/openrouter.mjs
@@ -6,18 +6,21 @@
// OPENROUTER_MANAGEMENT_KEY=… node openrouter.mjs credits --yes account credits (management key only)
//
// Rules: without --yes nothing is sent (the command prints what it WOULD call);
-// the only host is openrouter.ai; the key is read from the environment and is
+// the only host is openrouter.ai; the key is the plugin option `openrouterApiKey`
+// (sensitive, kept in the credential store, ADR-506) or $OPENROUTER_API_KEY, and is
// never printed, logged or written. `usage.cost` / `total_cost` from OpenRouter is
// the authoritative figure: do not recompute it from a price list.
+import { readSecret, secretHint } from './_secret.mjs';
+
const HOST = 'https://openrouter.ai/api/v1';
const [command, ...rest] = process.argv.slice(2);
const yes = process.argv.includes('--yes');
const id = rest.find(item => !item.startsWith('--'));
const PLAN = {
- key: { path: '/key', env: 'OPENROUTER_API_KEY', pick: ['label', 'limit', 'limit_remaining', 'limit_reset', 'usage', 'usage_daily', 'usage_weekly', 'usage_monthly', 'byok_usage', 'is_free_tier', 'free_model_daily_requests'] },
- generation: { path: `/generation?id=${encodeURIComponent(id ?? '')}`, env: 'OPENROUTER_API_KEY', pick: ['id', 'model', 'provider_name', 'router', 'total_cost', 'usage', 'upstream_inference_cost', 'cache_discount', 'is_byok', 'tokens_prompt', 'tokens_completion', 'native_tokens_prompt', 'native_tokens_completion', 'native_tokens_reasoning', 'native_tokens_cached', 'service_tier', 'cancelled', 'finish_reason', 'session_id', 'created_at'] },
+ key: { path: '/key', env: 'OPENROUTER_API_KEY', option: 'openrouterApiKey', pick: ['label', 'limit', 'limit_remaining', 'limit_reset', 'usage', 'usage_daily', 'usage_weekly', 'usage_monthly', 'byok_usage', 'is_free_tier', 'free_model_daily_requests'] },
+ generation: { path: `/generation?id=${encodeURIComponent(id ?? '')}`, env: 'OPENROUTER_API_KEY', option: 'openrouterApiKey', pick: ['id', 'model', 'provider_name', 'router', 'total_cost', 'usage', 'upstream_inference_cost', 'cache_discount', 'is_byok', 'tokens_prompt', 'tokens_completion', 'native_tokens_prompt', 'native_tokens_completion', 'native_tokens_reasoning', 'native_tokens_cached', 'service_tier', 'cancelled', 'finish_reason', 'session_id', 'created_at'] },
credits: { path: '/credits', env: 'OPENROUTER_MANAGEMENT_KEY', pick: ['total_credits', 'total_usage'] },
};
@@ -30,8 +33,12 @@ if (!yes) {
console.log(`Would GET ${HOST}${plan.path} using $${plan.env}. Nothing was sent. Re-run with --yes to allow this one request.`);
process.exit(0);
}
-const key = process.env[plan.env];
-if (!key) { console.error(`${plan.env} is not set; export it in your shell (never paste a key into a prompt or a file).`); process.exit(2); }
+// `credits` needs a management key: it has no plugin option and stays environment-only.
+const key = plan.option ? readSecret(plan.option, [plan.env]) : process.env[plan.env];
+if (!key) {
+ console.error(plan.option ? secretHint(plan.option, [plan.env]) : `${plan.env} is not set; export it in your shell (never paste a key into a prompt or a file).`);
+ process.exit(2);
+}
try {
const response = await fetch(`${HOST}${plan.path}`, { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(15_000) });
diff --git a/plugins/ruflo-cost-tracker/scripts/smoke.sh b/plugins/ruflo-cost-tracker/scripts/smoke.sh
index 0f1078b1cb..a873812cf0 100755
--- a/plugins/ruflo-cost-tracker/scripts/smoke.sh
+++ b/plugins/ruflo-cost-tracker/scripts/smoke.sh
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
-# Structural smoke test for ruflo-cost-tracker v0.28.3.
+# Structural smoke test for ruflo-cost-tracker v0.29.0.
set -u
# `pwd -W` (Git Bash on Windows) gives C:/Users/...; plain pwd gives /c/Users/..., which a Windows node cannot open. Elsewhere -W fails and pwd answers.
ROOT="$(cd "$(dirname "$0")/.." && { pwd -W 2>/dev/null || pwd; })"
@@ -9,10 +9,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.28.3 with new keywords"
+step "1. plugin.json declares 0.29.0 with new keywords"
v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [[ "$v" != "0.28.3" ]]; then
- bad "expected 0.28.3, got '$v'"
+if [[ "$v" != "0.29.0" ]]; then
+ bad "expected 0.29.0, got '$v'"
else
miss=""
for k in namespace-routing mcp agentic-flow agent-booster tier1-routing model-routing benchmarking verified telemetry budget projection forecast counterfactual drift-detection trend-alert anomaly-detection outlier-detection health-check composite-gate auto-track stop-hook snapshot-diff pr-regression git-context traceability drill-down per-message; do
diff --git a/plugins/ruflo-cost-tracker/skills/cost-openrouter/SKILL.md b/plugins/ruflo-cost-tracker/skills/cost-openrouter/SKILL.md
index 6ed2f0488a..8de1434cd9 100644
--- a/plugins/ruflo-cost-tracker/skills/cost-openrouter/SKILL.md
+++ b/plugins/ruflo-cost-tracker/skills/cost-openrouter/SKILL.md
@@ -18,7 +18,7 @@ node ${CLAUDE_PLUGIN_ROOT}/scripts/openrouter.mjs credits --yes
## Rules
- Without `--yes` the script prints the call it would make and sends nothing.
-- The key comes from `OPENROUTER_API_KEY` (credits: `OPENROUTER_MANAGEMENT_KEY`). Never ask the user to paste a key, never print, log or write one.
+- The key comes from `OPENROUTER_API_KEY` (credits: `OPENROUTER_MANAGEMENT_KEY`). A key the user stored as the plugin option `openrouterApiKey` arrives as `OPENROUTER_API_KEY` too: the plugin's SessionStart hook puts it there for this session's commands when the variable is not already set (ADR-506). Never ask the user to paste a key, never print, log or write one.
- OpenRouter's `usage.cost` / `total_cost` is **authoritative**; do not recompute it from list prices.
- `credits` needs a management key (a normal key returns 403). A fresh generation can 404 briefly: retry.
- BYOK rows carry the 5% OpenRouter fee in `usage`, the provider's charge in `upstream_inference_cost`: show both, labelled.
diff --git a/plugins/ruflo-metaharness/.claude-plugin/plugin.json b/plugins/ruflo-metaharness/.claude-plugin/plugin.json
index dc71e01218..a48a2a3570 100644
--- a/plugins/ruflo-metaharness/.claude-plugin/plugin.json
+++ b/plugins/ruflo-metaharness/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-metaharness",
"description": "MetaHarness integration for ruflo β€” surfaces score/genome/mint/mcp-scan/threat-model via skills; pairs with @metaharness/router (ADR-148/149) for cost-optimal model routing; honors ADR-150's architectural constraint that MetaHarness remains an optional augmentation, never a required runtime dependency. As a mod (ADR-445): confirms flywheel promotion, keeps secrets out of inputs, /metaharness-mod, and a status file the console shows",
- "version": "0.2.6",
+ "version": "0.3.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -43,6 +43,13 @@
"on",
"off"
]
+ },
+ "openrouterApiKey": {
+ "type": "string",
+ "title": "OpenRouter API key",
+ "description": "Key for the real model judge in redblue runs (--mock-judge needs none). Kept in the credential store, never in settings; OPENROUTER_API_KEY still works when this is empty.",
+ "required": false,
+ "sensitive": true
}
}
}
diff --git a/plugins/ruflo-metaharness/CHANGELOG.md b/plugins/ruflo-metaharness/CHANGELOG.md
index deccd58482..7a865bb2a0 100644
--- a/plugins/ruflo-metaharness/CHANGELOG.md
+++ b/plugins/ruflo-metaharness/CHANGELOG.md
@@ -2,6 +2,9 @@
Newest first. One `## <version> β€” <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; this is the whole history.
+## 0.3.0 β€” 2026-10-29
+- feat: `openrouterApiKey` is a `userConfig` option with `sensitive: true` (ADR-506, #4587), read through `readSecret` before the `OPENROUTER_API_KEY` environment fallback.
+
## 0.2.6 β€” 2026-10-12
- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)
diff --git a/plugins/ruflo-metaharness/README.md b/plugins/ruflo-metaharness/README.md
index a3f06a406d..505c5ce73e 100644
--- a/plugins/ruflo-metaharness/README.md
+++ b/plugins/ruflo-metaharness/README.md
@@ -79,6 +79,6 @@ This plugin ships a function-hook mod (ADR-445, `hooks/register.ts`). It makes n
- **`/metaharness-mod`**: `status`, `recent`, `tools` (which of this plugin's tools are connected) and `scan <text>` (would the guard refuse it). Answered locally.
- **Status file**: `.claude-flow/metaharness-mod/status.json` (`{version: 1, updatedMs, guard, calls, total, blocked, recent}`, counters only, never tool input), written at session start and after every call to this plugin's tools.
-Options (`userConfig`): `guard` (on).
+Options (`userConfig`): `guard` (on); `openrouterApiKey` (sensitive, empty by default): the key for redblue's real model judge, kept in the credential store. A classic SessionStart hook exports it as `OPENROUTER_API_KEY` to the session's Bash commands when that variable is unset, so a redblue run started from a skill uses it; it never goes in argv. The `metaharness_redblue` MCP tool runs inside ruflo-core's MCP server, which does not see it: export `OPENROUTER_API_KEY` before starting Claude Code for that path (ADR-506).
Test it: `claude plugin validate plugins/ruflo-metaharness`, `claude plugin test plugins/ruflo-metaharness`, `bash plugins/ruflo-metaharness/scripts/smoke.sh`.
diff --git a/plugins/ruflo-metaharness/hooks/hooks.json b/plugins/ruflo-metaharness/hooks/hooks.json
index fdb2721f3f..9b1e8c6e71 100644
--- a/plugins/ruflo-metaharness/hooks/hooks.json
+++ b/plugins/ruflo-metaharness/hooks/hooks.json
@@ -1,4 +1,18 @@
{
- "description": "MetaHarness as a mod (ADR-445): a tighten-only guard on the metaharness tools (promotion needs an explicit confirm, no secrets in inputs), a status file the console reads, and /metaharness-mod.",
- "modules": ["./register.ts"]
+ "description": "MetaHarness as a mod (ADR-445): a tighten-only guard on the metaharness tools (promotion needs an explicit confirm, no secrets in inputs), a status file the console reads, and /metaharness-mod. The classic SessionStart hook hands the sensitive option openrouterApiKey to the Bash tool as OPENROUTER_API_KEY through CLAUDE_ENV_FILE, only when that variable is not already set, so a redblue run started from a skill can use a key kept in the credential store (scripts/_secret-env.cjs, ADR-506).",
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node -e \"require(require('path').join(process.env.CLAUDE_PLUGIN_ROOT,'scripts','_secret-env.cjs')).bridge({openrouterApiKey:'OPENROUTER_API_KEY'})\""
+ }
+ ]
+ }
+ ]
+ },
+ "modules": [
+ "./register.ts"
+ ]
}
diff --git a/plugins/ruflo-metaharness/scripts/_redblue.mjs b/plugins/ruflo-metaharness/scripts/_redblue.mjs
index dcea41ac00..ae6cc8a34e 100644
--- a/plugins/ruflo-metaharness/scripts/_redblue.mjs
+++ b/plugins/ruflo-metaharness/scripts/_redblue.mjs
@@ -54,7 +54,9 @@
// (no real creds, no live targets, no shell, no eval, no arbitrary network).
// This wrapper does NOT relax those β€” it only forwards argv with shell:false.
// `--mock-judge` is the $0 CI path; the real model judge gates on
-// $OPENROUTER_API_KEY which we never inject.
+// $OPENROUTER_API_KEY. The wrapper never puts a key in argv. When that
+// variable is unset but the plugin option `openrouterApiKey` (sensitive,
+// ADR-506) is, the child gets it as OPENROUTER_API_KEY in its environment.
import { spawnSync } from 'node:child_process';
import { realpathSync } from 'node:fs';
@@ -67,6 +69,7 @@ import {
makeDegradedEmitter,
resolvePackageBin,
} from './_invoke.mjs';
+import { readSecret } from './_secret.mjs';
const DEFAULT_TIMEOUT_MS = 120_000;
@@ -78,6 +81,13 @@ const REDBLUE_PIN = `${REDBLUE_PKG}@${REDBLUE_PIN_VERSION}`;
const REASON_PREFIX = 'metaharness-redblue';
+/** The child environment, with OPENROUTER_API_KEY filled from the plugin option when the variable is unset (ADR-506). */
+export function judgeEnv(env) {
+ if (env.OPENROUTER_API_KEY) return env;
+ const key = readSecret('openrouterApiKey', [], env);
+ return key ? { ...env, OPENROUTER_API_KEY: key } : env;
+}
+
// Cache dir is versioned by the pin so bumping REDBLUE_PIN_VERSION
// invalidates stale installs (handled inside ensureCachedInstall). The
// resolved layout matches the pre-consolidation helper so existing caches
@@ -133,7 +143,7 @@ export function runRedblue(args, opts = {}) {
encoding: 'utf-8',
timeout: timeoutMs,
cwd: opts.cwd,
- env: { ...process.env, ...(opts.env || {}) },
+ env: judgeEnv({ ...process.env, ...(opts.env || {}) }),
shell: false,
});
const durationMs = Date.now() - start;
diff --git a/plugins/ruflo-metaharness/scripts/_secret-env.cjs b/plugins/ruflo-metaharness/scripts/_secret-env.cjs
new file mode 100644
index 0000000000..63abf7faa5
--- /dev/null
+++ b/plugins/ruflo-metaharness/scripts/_secret-env.cjs
@@ -0,0 +1,50 @@
+// Secret bridge (ADR-506): hand a sensitive `userConfig` option to the scripts a skill or command runs
+// through the Bash tool. Copied verbatim into each plugin that needs it (a test keeps the copies identical).
+//
+// Claude Code gives a plugin's option only to that plugin's hooks, as CLAUDE_PLUGIN_OPTION_<KEY>; the Bash
+// tool never sees it. A SessionStart hook, though, gets CLAUDE_ENV_FILE, and the lines it appends there are
+// loaded into every later Bash tool command of the session. So the plugin's SessionStart hook calls
+// bridge({ option: 'VARIABLE' }) and the script reads VARIABLE as it always did.
+//
+// Exposure: the value then sits in the session's environment file (under ~/.claude, owner-only) and in the
+// environment of the session's Bash commands, the same as exporting it in a shell profile. What the option
+// adds is masked entry and credential-store storage instead of a plain-text profile or .env file.
+//
+// Rules: a variable the user already exported wins and is never overwritten; the value is never printed,
+// logged or put in argv; a value with a newline or NUL is refused; any failure is silent and never blocks
+// the session.
+'use strict'
+const fs = require('fs')
+
+const optionEnvName = (name) => `CLAUDE_PLUGIN_OPTION_${String(name).replace(/[^A-Za-z0-9_]/g, '_').toUpperCase()}`
+const VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/
+const quote = (value) => `'${value.replace(/'/g, `'\\''`)}'`
+
+/** The env-file lines for the options that are set and whose variable is not. Never contains a value that was not asked for. */
+function bridgeLines(map, env = process.env) {
+ const lines = []
+ for (const [option, variable] of Object.entries(map || {})) {
+ if (!VARIABLE.test(variable)) continue
+ if (typeof env[variable] === 'string' && env[variable].trim() !== '') continue
+ const value = env[optionEnvName(option)]
+ if (typeof value !== 'string' || value.trim() === '' || /[\n\r\0]/.test(value)) continue
+ lines.push(`export ${variable}=${quote(value)}`)
+ }
+ return lines
+}
+
+/** Append the lines to CLAUDE_ENV_FILE (owner-only). Returns the variable NAMES written, never values. */
+function bridge(map, env = process.env) {
+ try {
+ const file = env.CLAUDE_ENV_FILE
+ if (!file) return []
+ const lines = bridgeLines(map, env)
+ if (lines.length === 0) return []
+ fs.appendFileSync(file, lines.join('\n') + '\n', { mode: 0o600 })
+ return lines.map((line) => line.slice('export '.length, line.indexOf('=')))
+ } catch {
+ return []
+ }
+}
+
+module.exports = { bridge, bridgeLines, optionEnvName }
diff --git a/plugins/ruflo-metaharness/scripts/_secret.mjs b/plugins/ruflo-metaharness/scripts/_secret.mjs
new file mode 100644
index 0000000000..d5f4fde716
--- /dev/null
+++ b/plugins/ruflo-metaharness/scripts/_secret.mjs
@@ -0,0 +1,35 @@
+// readSecret: one way to read a plugin credential (ADR-506). Copied verbatim into each plugin that
+// needs it, since a plugin may not import from another plugin's folder; keep the copies identical
+// (a test compares them).
+//
+// Order: CLAUDE_PLUGIN_OPTION_<NAME>, which Claude Code sets for a plugin's hooks when the
+// `userConfig` option (declared with "sensitive": true, kept in the credential store) is filled in;
+// then the environment variables the plugin always read, for standalone CLI use and backward
+// compatibility. The value is never logged, echoed, or placed in an error message.
+
+/** The environment variable Claude Code sets for a `userConfig` key (non-identifier characters to `_`, upper-cased). */
+export const optionEnvName = (name) => `CLAUDE_PLUGIN_OPTION_${String(name).replace(/[^A-Za-z0-9_]/g, '_').toUpperCase()}`
+
+/** The secret, or undefined when neither the option nor any fallback variable holds a non-empty value. Read at call time. */
+export function readSecret(name, envFallbacks = [], env = process.env) {
+ for (const variable of [optionEnvName(name), ...envFallbacks]) {
+ const value = env[variable]
+ if (typeof value === 'string' && value.trim() !== '') return value
+ }
+ return undefined
+}
+
+/** Where the secret was found (a variable NAME, never the value), or undefined. */
+export function secretSource(name, envFallbacks = [], env = process.env) {
+ for (const variable of [optionEnvName(name), ...envFallbacks]) {
+ const value = env[variable]
+ if (typeof value === 'string' && value.trim() !== '') return variable
+ }
+ return undefined
+}
+
+/** Error text for a missing secret: names the option and the variables, never a value. */
+export function secretHint(name, envFallbacks = []) {
+ const vars = envFallbacks.length ? ` or export ${envFallbacks.join(' / ')} in your shell` : ''
+ return `no ${name} configured: set the plugin option "${name}" with /plugin (it is stored in the credential store)${vars}. Never paste a key into a prompt or a file.`
+}
diff --git a/plugins/ruflo-metaharness/scripts/smoke.sh b/plugins/ruflo-metaharness/scripts/smoke.sh
index 4fd6cb0d19..f730afa610 100755
--- a/plugins/ruflo-metaharness/scripts/smoke.sh
+++ b/plugins/ruflo-metaharness/scripts/smoke.sh
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
-# Structural smoke test for ruflo-metaharness v0.2.6 (ADR-150 Phase 1).
+# Structural smoke test for ruflo-metaharness v0.3.0 (ADR-150 Phase 1).
set -u
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PASS=0
@@ -32,10 +32,10 @@ else
bad "extraction-regex-rot: EXPECTED_TOOLS=$EXPECTED_TOOLS EXPECTED_SUBS=$EXPECTED_SUBS"
fi
-step "1. plugin.json declares 0.2.6 with adr-150 keywords"
+step "1. plugin.json declares 0.3.0 with adr-150 keywords"
v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [[ "$v" != "0.2.6" ]]; then
- bad "expected 0.2.6, got '$v'"
+if [[ "$v" != "0.3.0" ]]; then
+ bad "expected 0.3.0, got '$v'"
else
miss=""
for k in ruflo metaharness harness scorecard genome mcp-scan threat-model router adr-150 adr-148 adr-149 optional-dependency graceful-degradation subprocess phase-1-mvp; do
diff --git a/scripts/audit-plugin-secrets.mjs b/scripts/audit-plugin-secrets.mjs
new file mode 100644
index 0000000000..e3e956d234
--- /dev/null
+++ b/scripts/audit-plugin-secrets.mjs
@@ -0,0 +1,129 @@
+#!/usr/bin/env node
+// audit-plugin-secrets β€” ADR-506 regression guard for plugin credentials.
+//
+// A. A `userConfig` key whose name looks like a credential (/(key|token|secret|password|jwt)/i)
+// must be declared "sensitive": true, so Claude Code keeps it in the credential store and
+// masks it, instead of writing it in plain text under `pluginConfigs` in settings.
+// B. No `.claude-plugin/plugin.json`, `hooks/hooks.json`, `.mcp.json` or `.lsp.json` may carry a
+// literal value shaped like a secret. The shapes are the mods' secret screen (COMMON_SECRETS in
+// plugins/ruflo-agentdb/hooks/screen.ts, parsed from that file so there is one list) plus
+// LOCAL_SECRETS below (OpenRouter keys, which the screen has no shape for).
+// C. Under an `env` or `headers` object, a credential-named entry (key, token, secret, password,
+// jwt, authorization, cookie, credential) must not hold a literal of 16+ characters: it must
+// reference `${VAR}` or `${user_config.KEY}`. This catches admin, gateway and other tokens that
+// no shape knows.
+// D. `${user_config.` must never appear in a hook or server `command`, `headersHelper` or `args`
+// entry: a substituted secret in argv is visible in `ps` (ADR-506 section 2.3). The server's
+// `env` block, or the hook's CLAUDE_PLUGIN_OPTION_<KEY> variable, is the place for it.
+//
+// Findings name the plugin, file and JSON path, and the rule. A matched value is never printed, and an
+// object key that is itself shaped like a secret is shown as <redacted-key> in every path.
+//
+// node scripts/audit-plugin-secrets.mjs # audits plugins/
+// node scripts/audit-plugin-secrets.mjs --root <dir> # audits <dir>/*/ (tests use fixtures)
+// node scripts/audit-plugin-secrets.mjs --screen <file> # alternative screen.ts
+
+import { existsSync, readdirSync, readFileSync } from 'node:fs'
+import { dirname, join, resolve } from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+
+const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '..')
+export const CREDENTIAL_NAME = /(key|token|secret|password|jwt)/i
+export const DEFAULT_SCREEN = join(REPO, 'plugins', 'ruflo-agentdb', 'hooks', 'screen.ts')
+/** Shapes the mods' screen does not know, kept here because that screen is shared by every mod. */
+export const LOCAL_SECRETS = [
+ ['openrouter key', /\bsk-or-v1-[A-Za-z0-9]{32,}/],
+]
+export const SCANNED_FILES = ['.claude-plugin/plugin.json', 'hooks/hooks.json', '.mcp.json', '.lsp.json']
+export const REDACTED_KEY = '<redacted-key>'
+const CREDENTIAL_ENTRY = /(key|token|secret|password|jwt|authorization|cookie|credential)/i
+const SECRET_CONTAINERS = new Set(['env', 'headers'])
+const ARGV_KEYS = new Set(['command', 'headersHelper'])
+const MIN_LITERAL = 16
+
+/** The COMMON_SECRETS rules of the mods' screen, as [name, RegExp] pairs. Throws when none parse. */
+export function loadSecretRules(screenPath = DEFAULT_SCREEN) {
+ const source = readFileSync(screenPath, 'utf8')
+ const start = source.indexOf('export const COMMON_SECRETS')
+ const end = start < 0 ? -1 : source.indexOf('\n]', start)
+ if (start < 0 || end < 0) throw new Error(`COMMON_SECRETS not found in ${screenPath}`)
+ const rules = []
+ for (const line of source.slice(start, end).split('\n')) {
+ const m = line.match(/^\s*\['([^']+)',\s*\/(.*)\/([a-z]*)\],?\s*$/)
+ if (m) rules.push([m[1], new RegExp(m[2], m[3])])
+ }
+ if (rules.length === 0) throw new Error(`no rules parsed from ${screenPath}: the audit would check nothing`)
+ return rules
+}
+
+/**
+ * Every string in a JSON value, object keys included. `keys` is the chain of object keys above the
+ * string (array indices skipped) and `inArray` says whether its nearest container is an array.
+ * `segment` renders a key for a path, so a key shaped like a secret never reaches a printed path.
+ */
+function* strings(value, path, segment, keys = [], inArray = false) {
+ if (typeof value === 'string') yield { path, text: value, keys, inArray, isKey: false }
+ else if (Array.isArray(value)) for (let i = 0; i < value.length; i++) yield* strings(value[i], `${path}[${i}]`, segment, keys, true)
+ else if (value && typeof value === 'object') for (const [k, v] of Object.entries(value)) {
+ const seg = segment(k)
+ yield { path: `${path}.${seg}#key`, text: k, keys, inArray: false, isKey: true }
+ yield* strings(v, `${path}.${seg}`, segment, [...keys, k], false)
+ }
+}
+
+/** Findings for one plugin directory. */
+export function auditPlugin(dir, rules) {
+ const findings = []
+ const plugin = dir.split(/[\\/]/).filter(Boolean).pop()
+ const shapes = [...rules, ...LOCAL_SECRETS]
+ const segment = (k) => (shapes.some(([, re]) => re.test(k)) ? REDACTED_KEY : k)
+ for (const rel of SCANNED_FILES) {
+ const file = join(dir, rel)
+ if (!existsSync(file)) continue
+ let json
+ try { json = JSON.parse(readFileSync(file, 'utf8')) } catch { findings.push({ plugin, file: rel, path: '$', rule: 'invalid JSON' }); continue }
+ if (rel.endsWith('plugin.json')) {
+ for (const [key, option] of Object.entries(json.userConfig ?? {})) {
+ if (CREDENTIAL_NAME.test(key) && option?.sensitive !== true) {
+ findings.push({ plugin, file: rel, path: `$.userConfig.${segment(key)}`, rule: 'credential-named option without "sensitive": true' })
+ }
+ }
+ }
+ for (const { path, text, keys, inArray, isKey } of strings(json, '$', segment)) {
+ for (const [name, re] of shapes) if (re.test(text)) findings.push({ plugin, file: rel, path, rule: `literal ${name}` })
+ if (isKey) continue
+ const own = keys[keys.length - 1]
+ const container = keys[keys.length - 2]
+ if (!inArray && SECRET_CONTAINERS.has(container) && CREDENTIAL_ENTRY.test(own) && !text.includes('${') && text.length >= MIN_LITERAL) {
+ findings.push({ plugin, file: rel, path, rule: `literal credential under ${container} (reference \${VAR} or \${user_config.KEY})` })
+ }
+ if (text.includes('${user_config.') && ((!inArray && ARGV_KEYS.has(own)) || (inArray && own === 'args'))) {
+ findings.push({ plugin, file: rel, path, rule: '${user_config.*} in a command line (use the env block or CLAUDE_PLUGIN_OPTION_<KEY>)' })
+ }
+ }
+ }
+ return findings
+}
+
+/** Findings for every plugin directory directly under root. */
+export function auditRoot(root, rules) {
+ const dirs = readdirSync(root, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => join(root, d.name))
+ return { checked: dirs.filter(d => existsSync(join(d, '.claude-plugin', 'plugin.json'))).length, findings: dirs.flatMap(d => auditPlugin(d, rules)) }
+}
+
+function main(argv) {
+ const arg = (flag) => { const i = argv.indexOf(flag); return i >= 0 ? argv[i + 1] : undefined }
+ const root = resolve(arg('--root') ?? join(REPO, 'plugins'))
+ const rules = loadSecretRules(arg('--screen') ? resolve(arg('--screen')) : DEFAULT_SCREEN)
+ const { checked, findings } = auditRoot(root, rules)
+ if (checked === 0) { console.error(`audit-plugin-secrets: no plugin manifests under ${root}; a check that inspects nothing must not pass`); return 1 }
+ for (const f of findings) console.error(`FAIL ${f.plugin}/${f.file} ${f.path}: ${f.rule}`)
+ if (findings.length) {
+ console.error(`audit-plugin-secrets: ${findings.length} finding(s). Declare credential options with "sensitive": true and keep secrets out of manifests and command lines (ADR-506).`)
+ return 1
+ }
+ console.log(`audit-plugin-secrets: ${checked} plugin manifest(s), ${rules.length + LOCAL_SECRETS.length} secret shapes, clean`)
+ return 0
+}
+
+if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) process.exit(main(process.argv.slice(2)))
diff --git a/v3/@claude-flow/cli/__tests__/adr-506-plugin-secrets.test.ts b/v3/@claude-flow/cli/__tests__/adr-506-plugin-secrets.test.ts
new file mode 100644
index 0000000000..45aeeaf0d2
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/adr-506-plugin-secrets.test.ts
@@ -0,0 +1,311 @@
+/**
+ * ADR-506: plugin credentials through `userConfig` with `sensitive: true`.
+ *
+ * - scripts/audit-plugin-secrets.mjs: a credential-named option without `sensitive`, literal secrets
+ * in plugin.json / hooks.json / .mcp.json (shapes, OpenRouter keys, credential entries under env or
+ * headers), `${user_config.*}` in argv, a secret used as an object key that must never be printed,
+ * and the real plugins/ tree must be clean.
+ * - readSecret (scripts/_secret.mjs) and the SessionStart bridge (scripts/_secret-env.cjs), each copied
+ * into ruflo-cost-tracker and ruflo-metaharness: behaviour, and the copies stay identical.
+ * - the consumers: cost-tracker openrouter.mjs and the metaharness redblue child environment, and the
+ * SessionStart hooks that wire the bridge.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync, statSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { spawnSync } from 'node:child_process'
+import { pathToFileURL } from 'node:url'
+import { createRequire } from 'node:module'
+
+const REPO = resolve(__dirname, '../../../..')
+const AUDIT = join(REPO, 'scripts', 'audit-plugin-secrets.mjs')
+const PLUGINS = ['ruflo-cost-tracker', 'ruflo-metaharness']
+const HELPERS = PLUGINS.map((p) => join(REPO, 'plugins', p, 'scripts', '_secret.mjs'))
+const BRIDGES = PLUGINS.map((p) => join(REPO, 'plugins', p, 'scripts', '_secret-env.cjs'))
+// Built at runtime so this test file never holds a literal secret shape.
+const FAKE_GITHUB_TOKEN = ['gh', 'p_', 'A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8'].join('')
+const FAKE_OPENROUTER_KEY = ['sk', 'or', 'v1', 'a1b2c3d4'.repeat(8)].join('-')
+const FAKE_ADMIN_TOKEN = ['adm', 'Zq8Wv3Lx9Tk2Rp7Ns4'].join('')
+const PROBE = 'probe-value-not-a-real-secret-7f3a'
+
+const runAudit = (root: string) => spawnSync(process.execPath, [AUDIT, '--root', root], { encoding: 'utf8' })
+
+function writePlugin(root: string, name: string, manifest: object, hooks?: object, mcp?: object) {
+ const dir = join(root, name)
+ mkdirSync(join(dir, '.claude-plugin'), { recursive: true })
+ writeFileSync(join(dir, '.claude-plugin', 'plugin.json'), JSON.stringify({ name, version: '0.0.1', ...manifest }, null, 2))
+ if (hooks) {
+ mkdirSync(join(dir, 'hooks'), { recursive: true })
+ writeFileSync(join(dir, 'hooks', 'hooks.json'), JSON.stringify(hooks, null, 2))
+ }
+ if (mcp) writeFileSync(join(dir, '.mcp.json'), JSON.stringify(mcp, null, 2))
+}
+
+describe('ADR-506 audit-plugin-secrets', () => {
+ let tmp: string
+ beforeAll(() => { tmp = mkdtempSync(join(tmpdir(), 'adr506-')) })
+ afterAll(() => { rmSync(tmp, { recursive: true, force: true }) })
+
+ it('passes a clean manifest with a sensitive credential option', () => {
+ const root = join(tmp, 'clean')
+ writePlugin(root, 'p', { userConfig: {
+ apiKey: { type: 'string', title: 'Key', description: 'A key.', required: false, sensitive: true },
+ guard: { type: 'string', title: 'Guard', description: 'on/off', required: false, default: 'on' },
+ } }, { hooks: { Stop: [{ hooks: [{ type: 'command', command: 'node -e "1"' }] }] } })
+ const r = runAudit(root)
+ expect(r.status, r.stderr).toBe(0)
+ expect(r.stdout).toMatch(/1 plugin manifest/)
+ })
+
+ it('fails a credential-named option declared without sensitive: true', () => {
+ const root = join(tmp, 'notsensitive')
+ writePlugin(root, 'p', { userConfig: { adminToken: { type: 'string', title: 'T', description: 'd', required: false } } })
+ const r = runAudit(root)
+ expect(r.status).toBe(1)
+ expect(r.stderr).toContain('p/.claude-plugin/plugin.json $.userConfig.adminToken')
+ expect(r.stderr).toContain('without "sensitive": true')
+ })
+
+ it('treats sensitive: "true" (a string) as not sensitive', () => {
+ const root = join(tmp, 'stringtrue')
+ writePlugin(root, 'p', { userConfig: { dbPassword: { type: 'string', title: 'P', description: 'd', sensitive: 'true' } } })
+ expect(runAudit(root).status).toBe(1)
+ })
+
+ it('fails a literal secret in plugin.json or hooks.json and never prints it', () => {
+ const root = join(tmp, 'literal')
+ writePlugin(root, 'a', { description: `uses ${FAKE_GITHUB_TOKEN}` })
+ writePlugin(root, 'b', {}, { hooks: { Stop: [{ hooks: [{ type: 'command', command: `curl -H "x: ${FAKE_GITHUB_TOKEN}"` }] }] } })
+ const r = runAudit(root)
+ expect(r.status).toBe(1)
+ expect(r.stderr).toContain('a/.claude-plugin/plugin.json $.description: literal github token')
+ expect(r.stderr).toContain('b/hooks/hooks.json')
+ expect(r.stderr + r.stdout).not.toContain(FAKE_GITHUB_TOKEN)
+ })
+
+ it('a secret used as an object KEY is reported with a redacted path and never printed', () => {
+ // The first version built paths from raw key text and printed the token itself (review finding 2).
+ const root = join(tmp, 'keypos')
+ writePlugin(root, 'k', { mcpServers: { x: { command: 'node', headers: { [FAKE_GITHUB_TOKEN]: 'v' }, env: { [FAKE_GITHUB_TOKEN]: { nested: 'x' } } } } })
+ const r = runAudit(root)
+ expect(r.status).toBe(1)
+ expect(r.stderr).toContain('$.mcpServers.x.headers.<redacted-key>#key: literal github token')
+ expect(r.stderr).toContain('$.mcpServers.x.env.<redacted-key>#key: literal github token')
+ expect(r.stderr + r.stdout).not.toContain(FAKE_GITHUB_TOKEN)
+ expect(r.stderr + r.stdout).not.toContain(FAKE_GITHUB_TOKEN.slice(4, 20))
+ })
+
+ it('scans .mcp.json: a literal bearer token in a header fails', () => {
+ const root = join(tmp, 'mcpjson')
+ writePlugin(root, 'm', {}, undefined, { mcpServers: { x: { type: 'http', url: 'https://example.test/mcp', headers: { Authorization: `Bearer ${FAKE_GITHUB_TOKEN}` } } } })
+ const r = runAudit(root)
+ expect(r.status).toBe(1)
+ expect(r.stderr).toContain('m/.mcp.json $.mcpServers.x.headers.Authorization')
+ expect(r.stderr + r.stdout).not.toContain(FAKE_GITHUB_TOKEN)
+ })
+
+ it('fails a literal OpenRouter key, which the mods screen has no shape for', () => {
+ const root = join(tmp, 'openrouter')
+ writePlugin(root, 'o', { mcpServers: { x: { command: 'node', env: { OPENROUTER_API_KEY: FAKE_OPENROUTER_KEY } } } })
+ const r = runAudit(root)
+ expect(r.status).toBe(1)
+ expect(r.stderr).toContain('$.mcpServers.x.env.OPENROUTER_API_KEY: literal openrouter key')
+ expect(r.stderr + r.stdout).not.toContain(FAKE_OPENROUTER_KEY)
+ })
+
+ it('fails a credential-named env or header entry holding any literal of 16+ characters', () => {
+ const root = join(tmp, 'structural')
+ writePlugin(root, 's', {}, undefined, { mcpServers: {
+ a: { command: 'node', env: { RUFLO_ADMIN_TOKEN: FAKE_ADMIN_TOKEN } },
+ b: { type: 'http', url: 'https://example.test', headers: { 'X-Api-Key': FAKE_ADMIN_TOKEN } },
+ } })
+ const r = runAudit(root)
+ expect(r.status).toBe(1)
+ expect(r.stderr).toContain('$.mcpServers.a.env.RUFLO_ADMIN_TOKEN: literal credential under env')
+ expect(r.stderr).toContain('$.mcpServers.b.headers.X-Api-Key: literal credential under headers')
+ expect(r.stderr + r.stdout).not.toContain(FAKE_ADMIN_TOKEN)
+ })
+
+ it('negative controls: references, short or non-credential values under env/headers pass', () => {
+ const root = join(tmp, 'references')
+ writePlugin(root, 'r', { userConfig: { openrouterApiKey: { type: 'string', title: 'k', description: 'd', sensitive: true } } }, undefined, { mcpServers: {
+ a: { command: 'node', args: ['${CLAUDE_PLUGIN_ROOT}/server.mjs'], env: { OPENROUTER_API_KEY: '${user_config.openrouterApiKey}', CGF_CALLER_TOKEN: '${CGF_CALLER_TOKEN}', TOKEN_MODE: 'readonly', CLAUDE_FLOW_MCP_TRANSPORT: 'stdio-transport-long-value' } },
+ b: { type: 'http', url: 'https://example.test', headers: { Authorization: 'Bearer ${user_config.openrouterApiKey}' } },
+ } })
+ const r = runAudit(root)
+ expect(r.status, r.stderr).toBe(0)
+ })
+
+ it('fails ${user_config.*} in a hook command, an MCP command, or args', () => {
+ const root = join(tmp, 'argv')
+ writePlugin(root, 'v', { userConfig: { apiKey: { type: 'string', title: 'k', description: 'd', sensitive: true } } },
+ { hooks: { Stop: [{ hooks: [{ type: 'command', command: 'node', args: ['x.cjs', '--key', '${user_config.apiKey}'] }] }] } },
+ { mcpServers: { a: { command: 'node ${user_config.apiKey}' } } })
+ const r = runAudit(root)
+ expect(r.status).toBe(1)
+ expect(r.stderr).toContain('v/hooks/hooks.json $.hooks.Stop[0].hooks[0].args[2]: ${user_config.*} in a command line')
+ expect(r.stderr).toContain('v/.mcp.json $.mcpServers.a.command: ${user_config.*} in a command line')
+ })
+
+ it('refuses to pass when it inspects nothing', () => {
+ const root = join(tmp, 'empty')
+ mkdirSync(root, { recursive: true })
+ expect(runAudit(root).status).toBe(1)
+ })
+
+ it('loads every COMMON_SECRETS rule from the mods screen', async () => {
+ const mod = await import(pathToFileURL(AUDIT).href)
+ const screen = readFileSync(mod.DEFAULT_SCREEN, 'utf8')
+ const block = screen.slice(screen.indexOf('export const COMMON_SECRETS'), screen.indexOf('\n]', screen.indexOf('export const COMMON_SECRETS')))
+ const expected = block.split('\n').filter((l) => /^\s*\['/.test(l)).length
+ expect(expected).toBeGreaterThan(10)
+ expect(mod.loadSecretRules()).toHaveLength(expected)
+ expect(mod.SCANNED_FILES).toEqual(expect.arrayContaining(['.claude-plugin/plugin.json', 'hooks/hooks.json', '.mcp.json']))
+ })
+
+ it('the real plugins/ tree is clean', () => {
+ const r = spawnSync(process.execPath, [AUDIT], { encoding: 'utf8' })
+ expect(r.status, r.stderr).toBe(0)
+ })
+
+ it('the two ADR-506 options are declared sensitive and optional; x-gateway declares none', () => {
+ for (const plugin of PLUGINS) {
+ const m = JSON.parse(readFileSync(join(REPO, 'plugins', plugin, '.claude-plugin', 'plugin.json'), 'utf8'))
+ expect(m.userConfig?.openrouterApiKey, plugin).toMatchObject({ type: 'string', sensitive: true, required: false })
+ expect(m.userConfig.openrouterApiKey).not.toHaveProperty('default')
+ }
+ // The gateway runs as a deployed server, never as a Claude Code child, so an option could not reach it.
+ const gw = JSON.parse(readFileSync(join(REPO, 'plugins', 'ruflo-x-gateway', '.claude-plugin', 'plugin.json'), 'utf8'))
+ expect(gw.userConfig ?? {}).not.toHaveProperty('adminToken')
+ })
+})
+
+describe('ADR-506 readSecret helper', () => {
+ it('the per-plugin copies are byte-identical', () => {
+ const [first, ...rest] = HELPERS.map((f) => readFileSync(f, 'utf8'))
+ for (const copy of rest) expect(copy).toBe(first)
+ })
+
+ for (const file of HELPERS) {
+ describe(file.slice(REPO.length + 1), () => {
+ it('reads the option over the environment fallbacks, then the fallbacks in order', async () => {
+ const { readSecret, optionEnvName, secretSource } = await import(pathToFileURL(file).href)
+ expect(optionEnvName('openrouterApiKey')).toBe('CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY')
+ expect(optionEnvName('a-b')).toBe('CLAUDE_PLUGIN_OPTION_A_B')
+ const env = { CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: 'from-option', OPENROUTER_API_KEY: 'from-env', SECOND: 'second' }
+ expect(readSecret('openrouterApiKey', ['OPENROUTER_API_KEY'], env)).toBe('from-option')
+ expect(secretSource('openrouterApiKey', ['OPENROUTER_API_KEY'], env)).toBe('CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY')
+ expect(readSecret('openrouterApiKey', ['OPENROUTER_API_KEY'], { ...env, CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: ' ' })).toBe('from-env')
+ expect(readSecret('x', ['MISSING', 'SECOND'], env)).toBe('second')
+ expect(readSecret('x', ['MISSING'], env)).toBeUndefined()
+ expect(secretSource('x', ['MISSING'], env)).toBeUndefined()
+ })
+
+ it('the hint names the option and variables, never a value', async () => {
+ const { secretHint } = await import(pathToFileURL(file).href)
+ const hint = secretHint('openrouterApiKey', ['OPENROUTER_API_KEY'])
+ expect(hint).toContain('openrouterApiKey')
+ expect(hint).toContain('OPENROUTER_API_KEY')
+ expect(hint).not.toContain(PROBE)
+ })
+ })
+ }
+})
+
+describe('ADR-506 SessionStart bridge (_secret-env.cjs)', () => {
+ const req = createRequire(import.meta.url)
+ let tmp: string
+ beforeAll(() => { tmp = mkdtempSync(join(tmpdir(), 'adr506-env-')) })
+ afterAll(() => { rmSync(tmp, { recursive: true, force: true }) })
+
+ it('the per-plugin copies are byte-identical', () => {
+ const [first, ...rest] = BRIDGES.map((f) => readFileSync(f, 'utf8'))
+ for (const copy of rest) expect(copy).toBe(first)
+ })
+
+ it('writes the variable only when the option is set and the variable is not, quoted for the shell', () => {
+ const { bridgeLines } = req(BRIDGES[0])
+ const map = { openrouterApiKey: 'OPENROUTER_API_KEY' }
+ expect(bridgeLines(map, { CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: PROBE })).toEqual([`export OPENROUTER_API_KEY='${PROBE}'`])
+ expect(bridgeLines(map, { CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: PROBE, OPENROUTER_API_KEY: 'mine' })).toEqual([])
+ expect(bridgeLines(map, {})).toEqual([])
+ expect(bridgeLines(map, { CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: ' ' })).toEqual([])
+ expect(bridgeLines(map, { CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: "a'b; rm x" })).toEqual([`export OPENROUTER_API_KEY='a'\\''b; rm x'`])
+ expect(bridgeLines(map, { CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: 'a\nexport EVIL=1' })).toEqual([])
+ expect(bridgeLines({ openrouterApiKey: 'BAD NAME' }, { CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: PROBE })).toEqual([])
+ })
+
+ it.skipIf(process.platform === 'win32')('a quoted value round-trips through bash unchanged', () => {
+ const { bridgeLines } = req(BRIDGES[0])
+ const tricky = `p'q"r$HOME\`id\` ;|&`
+ const [line] = bridgeLines({ k: 'OUT' }, { CLAUDE_PLUGIN_OPTION_K: tricky })
+ const r = spawnSync('bash', ['-c', `${line}; printf %s "$OUT"`], { encoding: 'utf8' })
+ expect(r.stdout).toBe(tricky)
+ })
+
+ it('appends to CLAUDE_ENV_FILE owner-only, returns names only, and is a no-op without it', () => {
+ const { bridge } = req(BRIDGES[0])
+ const file = join(tmp, 'session.env')
+ expect(bridge({ openrouterApiKey: 'OPENROUTER_API_KEY' }, { CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: PROBE })).toEqual([])
+ expect(existsSync(file)).toBe(false)
+ const written = bridge({ openrouterApiKey: 'OPENROUTER_API_KEY' }, { CLAUDE_ENV_FILE: file, CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: PROBE })
+ expect(written).toEqual(['OPENROUTER_API_KEY'])
+ expect(JSON.stringify(written)).not.toContain(PROBE)
+ expect(readFileSync(file, 'utf8')).toBe(`export OPENROUTER_API_KEY='${PROBE}'\n`)
+ if (process.platform !== 'win32') expect(statSync(file).mode & 0o077).toBe(0)
+ })
+
+ it.skipIf(process.platform === 'win32')('the SessionStart hook of each plugin runs the bridge, prints nothing, and fills the env file', () => {
+ for (const plugin of PLUGINS) {
+ const root = join(REPO, 'plugins', plugin)
+ const hooks = JSON.parse(readFileSync(join(root, 'hooks', 'hooks.json'), 'utf8'))
+ const command: string = hooks.hooks?.SessionStart?.[0]?.hooks?.[0]?.command
+ expect(command, plugin).toContain("'_secret-env.cjs'")
+ expect(command).toContain("bridge({openrouterApiKey:'OPENROUTER_API_KEY'})")
+ expect(command).not.toContain('user_config')
+ const file = join(tmp, `${plugin}.env`)
+ const r = spawnSync('bash', ['-c', command], { encoding: 'utf8', env: {
+ PATH: process.env.PATH ?? '', CLAUDE_PLUGIN_ROOT: root, CLAUDE_ENV_FILE: file, CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: PROBE,
+ } })
+ expect(r.status, r.stderr).toBe(0)
+ expect(r.stdout + r.stderr).toBe('')
+ expect(readFileSync(file, 'utf8')).toBe(`export OPENROUTER_API_KEY='${PROBE}'\n`)
+ }
+ })
+})
+
+describe('ADR-506 consumers read the option', () => {
+ const clean = (extra: Record<string, string>) => {
+ const env: Record<string, string> = {}
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !/OPENROUTER|CLAUDE_PLUGIN_OPTION_|RUFLO_ADMIN_TOKEN/.test(k)) env[k] = v
+ return { ...env, ...extra }
+ }
+ const openrouter = join(REPO, 'plugins/ruflo-cost-tracker/scripts/openrouter.mjs')
+ const blockFetch = 'data:text/javascript,globalThis.fetch=async()=>{throw new TypeError("blocked")}'
+
+ it('cost-tracker openrouter.mjs: missing key names the option and variable, and exits 2 before any request', () => {
+ const r = spawnSync(process.execPath, [openrouter, 'key', '--yes'], { encoding: 'utf8', env: clean({}) })
+ expect(r.status).toBe(2)
+ expect(r.stderr).toContain('openrouterApiKey')
+ expect(r.stderr).toContain('OPENROUTER_API_KEY')
+ })
+
+ it('cost-tracker openrouter.mjs: the variable the bridge writes is enough to pass the key gate, and is never printed', () => {
+ // fetch is replaced by a stub that throws, so nothing reaches the network: with a key present the
+ // script gets past the missing-key gate (exit 2) to the request and fails there (exit 1).
+ for (const extra of [{ OPENROUTER_API_KEY: PROBE }, { CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: PROBE }]) {
+ const r = spawnSync(process.execPath, ['--import', blockFetch, openrouter, 'key', '--yes'], { encoding: 'utf8', env: clean(extra) })
+ expect(r.status).toBe(1)
+ expect(r.stderr).toContain('request failed: TypeError')
+ expect(r.stdout + r.stderr).not.toContain(PROBE)
+ }
+ })
+
+ it('metaharness redblue: the child gets OPENROUTER_API_KEY from the option, an explicit variable wins', async () => {
+ const { judgeEnv } = await import(pathToFileURL(join(REPO, 'plugins/ruflo-metaharness/scripts/_redblue.mjs')).href)
+ expect(judgeEnv({ CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: PROBE }).OPENROUTER_API_KEY).toBe(PROBE)
+ expect(judgeEnv({ CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY: PROBE, OPENROUTER_API_KEY: 'explicit' }).OPENROUTER_API_KEY).toBe('explicit')
+ expect(judgeEnv({ PATH: '/bin' })).not.toHaveProperty('OPENROUTER_API_KEY')
+ })
+})
diff --git a/v3/docs/adr/ADR-506-plugin-userconfig-secrets.md b/v3/docs/adr/ADR-506-plugin-userconfig-secrets.md
index 252f7cd76f..fe96eb62d1 100644
--- a/v3/docs/adr/ADR-506-plugin-userconfig-secrets.md
+++ b/v3/docs/adr/ADR-506-plugin-userconfig-secrets.md
@@ -1,6 +1,6 @@
# ADR 506: plugin secrets through `userConfig` with `sensitive: true`
-Status: Proposed (2026-10-29)
+Status: Accepted (implemented in PR #4587, 2026-10-29)
Issue: #4581 follow-up 1.
@@ -31,41 +31,64 @@ The Claude Code plugin reference describes what `userConfig` with `sensitive: tr
### 2.1 Declare the keys
-Each plugin that needs a credential declares it as a `userConfig` option with `"sensitive": true` and `"required": false`:
+Each plugin that needs a credential, and has a path that can deliver it (2.2), declares it as a `userConfig` option with `"sensitive": true` and `"required": false`:
- ruflo-cost-tracker: `openrouterApiKey`;
-- ruflo-x-gateway: `adminToken`;
- ruflo-metaharness: `openrouterApiKey`.
-The description says what the key is for and that it is stored in the credential store.
+The description says what the key is for and that it is stored in the credential store. An option that no Claude Code process of the declaring plugin can receive is not declared: it would ask users for a secret that never arrives.
-### 2.2 Read it through one helper
+### 2.2 Deliver it to the code that uses it
+
+Claude Code hands an option only to the declaring plugin's own hooks and MCP servers. The OpenRouter consumers are scripts that a skill or command runs through the Bash tool, which gets no `CLAUDE_PLUGIN_OPTION_*` variable. So each of the two plugins carries a SessionStart command hook that runs `scripts/_secret-env.cjs`. The hook appends `export OPENROUTER_API_KEY='…'` to `CLAUDE_ENV_FILE`, the file whose lines Claude Code loads into every later Bash command of the session. It does so only when the option is filled in and `OPENROUTER_API_KEY` is not already set. The scripts then read `OPENROUTER_API_KEY` as before.
+
+The trade-off is stated plainly: the key then sits in the session's environment file under `~/.claude` (the bridge creates it owner-only when it is absent; a file Claude Code created keeps Claude Code's mode) and in the environment of that session's Bash commands, the same exposure as exporting it in a shell profile. What the option adds is masked entry and credential-store storage in place of a plain-text profile or `.env` file.
+
+### 2.3 Read it through one helper
A shared helper, `readSecret(name, envFallbacks)`, is copied into each plugin's scripts folder; plugins may not import across folders. It reads, in order:
-1. `CLAUDE_PLUGIN_OPTION_<NAME>`, which is set when the plugin runs under Claude Code with the option filled in;
-2. the existing environment variables, kept for backward compatibility and for standalone CLI use.
+1. `CLAUDE_PLUGIN_OPTION_<NAME>`, which is set when the code runs as one of the plugin's own hooks or servers with the option filled in;
+2. the existing environment variables, kept for backward compatibility, for standalone CLI use, and for the variable the bridge (2.2) writes.
It never logs or echoes the value. Its error text names the option and the variable, never the value.
-### 2.3 Never put a secret in a command line
+### 2.4 Never put a secret in a command line
+
+Plugin hooks and MCP entries that need a secret take it from the environment. They never use `${user_config.KEY}` substitution into argv: the value would be visible in `ps`, and the shell forms refuse it anyway.
-Plugin hooks and MCP entries that need a secret take it from the environment variable. They never use `${user_config.KEY}` substitution into argv: the value would be visible in `ps`, and the shell forms refuse it anyway.
+### 2.5 Guard against regressions
-### 2.4 Guard against regressions
+A new audit, `scripts/audit-plugin-secrets.mjs`, runs in the existing `plugin-package-audit` CI job. It reads `.claude-plugin/plugin.json`, `hooks/hooks.json`, `.mcp.json` and `.lsp.json`, and fails when:
-A new audit, `scripts/audit-plugin-secrets.mjs`, runs in the existing `plugin-package-audit` CI job:
+- a plugin declares a `userConfig` key whose name matches `/(key|token|secret|password|jwt)/i` without `sensitive: true`;
+- any string, object keys included, matches a secret shape: the mods' secret screen patterns plus an OpenRouter key shape;
+- a credential-named entry under an `env` or `headers` object holds a literal of 16 or more characters instead of a `${…}` reference;
+- `${user_config.` appears in a `command`, `headersHelper` or `args` entry.
-- It fails when a plugin declares a `userConfig` key whose name matches `/(key|token|secret|password|jwt)/i` without `sensitive: true`.
-- It fails when a `.claude-plugin/plugin.json` or `hooks.json` carries a literal value that matches a secret shape. It uses the same patterns as the mods' secret screen.
+It never prints a matched value. A key shaped like a secret is shown as `<redacted-key>` in every path.
## 3. What does not change
- The npm publish token and the helpers signing key stay in GCP Secret Manager. They belong to maintainer tooling, not to plugins.
-- Environment variables keep working, so no user is broken.
+- Environment variables keep working, so no user is broken. A variable the user exported always wins over the option.
+- ruflo-x-gateway keeps `RUFLO_ADMIN_TOKEN` from the environment of the deployed gateway (see 5).
## 4. Verification
-- The audit is unit-tested with three fixtures: a key declared without `sensitive`, a literal secret, and a clean manifest.
-- The helper is unit-tested: option over environment, fallback order, and no value in error text.
-- Live: with `openrouterApiKey` set through `/plugin` configuration, a cost-tracker script receives it as `CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY` and nothing else in the process sees it.
+- The audit is unit-tested with fixtures for each rule, including negative controls (`${user_config.…}` and `${VAR}` references, short and non-credential values) and a secret in key position whose output must not contain it.
+- The helper and the bridge are unit-tested: option over environment, fallback order, no value in error text, shell quoting that round-trips through bash, refusal of multi-line values, owner-only env file, and byte-identical copies.
+- Live: with `openrouterApiKey` supplied as a plugin option, a Bash tool command in the same session resolves the key from `OPENROUTER_API_KEY`.
+
+## 5. Implementation notes
+
+- **Review fix (PR #4587).** The first version declared the options and read `CLAUDE_PLUGIN_OPTION_*` in the scripts, but no consumer was launched in a way that receives it: the Bash tool gets no plugin options, the `metaharness_redblue` MCP tool runs inside ruflo-core's server (another plugin), and the gateway runs as a deployed service. The SessionStart bridge (2.2) was added, and the x-gateway `adminToken` option was removed.
+- **x-gateway.** The gateway reads `RUFLO_ADMIN_TOKEN` in a server started from its Dockerfile and reached at `https://x.ruv.io` over HTTP MCP. No Claude Code process of the plugin ever runs that server, so no option can reach it. Its admin token stays an environment variable of the deployment.
+- **Where the helpers live.** `scripts/_secret.mjs` (`readSecret`, `secretSource`, `secretHint`, `optionEnvName`) and `scripts/_secret-env.cjs` (`bridge`, `bridgeLines`) in ruflo-cost-tracker and ruflo-metaharness. Tests keep each pair of copies byte-identical.
+- **Env var name.** Claude Code 2.1.289 derives the variable as `CLAUDE_PLUGIN_OPTION_` + the key with non-identifier characters replaced by `_` and upper-cased, so `openrouterApiKey` arrives as `CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY`. `optionEnvName` does the same.
+- **Consumers.** cost-tracker `openrouter.mjs` uses `readSecret('openrouterApiKey', ['OPENROUTER_API_KEY'])` for `key` and `generation`. Through the Bash tool it finds the bridged `OPENROUTER_API_KEY`. `credits` needs a management key, which has no option, and stays environment-only. metaharness `_redblue.mjs` hands the option to the redblue child as `OPENROUTER_API_KEY` in its environment (never argv) only when that variable is not already set. A redblue run started from a skill gets the bridged variable.
+- **What the bridge does not reach.** `CLAUDE_ENV_FILE` feeds the Bash tool only; MCP servers do not load it. So the `metaharness_redblue` MCP tool (ruflo-core's server) still needs `OPENROUTER_API_KEY` exported before Claude Code starts. A plugin-owned stdio MCP server with `env: {"OPENROUTER_API_KEY": "${user_config.openrouterApiKey}"}` would be the confined alternative. It would also keep the key out of the Bash environment. It is left for a follow-up because it adds a server and a tool surface. The bridge was verified on Linux only; where the Bash tool does not load `CLAUDE_ENV_FILE`, the environment variable remains the path.
+- **Bridge rules.** The hook command is a `node -e` bootstrap (no shell expansion, no `${user_config}`), prints nothing, and never fails the session. Values are single-quoted with `'\''` escaping; a value containing a newline, carriage return or NUL is refused rather than written. When the bridge creates the file it uses mode `0600`; it does not change the mode of a file Claude Code already created.
+- **Audit patterns.** The audit parses `COMMON_SECRETS` out of `plugins/ruflo-agentdb/hooks/screen.ts` instead of copying it (a `.mjs` cannot import the `.ts`), and fails when it parses no rules or finds no manifests. `LOCAL_SECRETS` adds `sk-or-v1-…` (OpenRouter), which the shared screen does not know. The env/headers rule covers tokens with no recognisable shape (admin, CGF, Seraphina). Its 16-character floor mirrors the screen's `key assignment` rule and leaves values like `"TOKEN_MODE": "readonly"` alone.
+- **Name rule false positives.** `/(key|token|secret|password|jwt)/i` will also match future non-secret option names such as a token budget (`maxTokens`). No current option matches; such an option must be renamed or declared sensitive.
+- **Live checks.** Two haiku runs (Claude Code 2.1.289), each with the option supplied through `--settings` `pluginConfigs` and `OPENROUTER_API_KEY` unset. The first used a probe plugin with this SessionStart hook. The second used the real `plugins/ruflo-cost-tracker`. In both, a Bash tool command resolved the key with `secretSource` = `OPENROUTER_API_KEY`, and the value matched. An earlier run showed `CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY` in the SessionStart and Stop hook environments. Storing the value in the credential store needs the interactive `/plugin` prompt, which a headless run cannot drive.