SLOPSHOPPER

mod-firewall

A firewall for Claude Code mods: watches what every other mod does (network, processes, secret files, env vars) and asks, blocks or logs

panecommandtoaststatus
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · mod-firewall
│ ┃ Mod firewall ✕ › fix the failing auth test and add an audit log call │ ┃ mode: ask · 0 mods seen · 0 calls blocked · │ ┃ /config to change ⏺ Read(src/auth.ts) │ ┃ No other mods have done anything yet. ⎿ Read 6 lines │ ┃ Activity ⏺ Update(src/auth.ts) │ ┃ Nothing yet. ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /firewall │ ⎿ mod-firewall: Mod firewall opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Mod firewall
mode: ask · 0 mods seen · 0 calls blocked · /config to change No other mods have done anything yet. Activity Nothing yet.
README

mod-firewall

A firewall for Claude Code mods. Mods run inside Claude Code with your permissions and aren't sandboxed. This one watches what every other mod does and asks you, blocks the call, or logs it.

/plugin install mod-firewall --marketplace bbarney7/claude-code-mods

What it watches

Every engine call another mod makes passes through the firewall first, labelled with the mod that made it:

Kind of callInfo (logged, allowed)Sensitive (ask, or block in strict)Critical (asks; strict blocks unless you allowed that secret to that site)
Network (http.fetch)—any requesta request whose URL, headers or body contain a value from your .env files or a known token shape (Anthropic, OpenAI, OpenRouter, GitHub, AWS, Slack, Google keys, private keys)
Processes (process.run, process.spawn)—any program it starts—
File readsordinary filessecrets files: .env*, SSH keys, *.pem/*.key, .aws/credentials, .npmrc, .netrc, gh hosts, .docker/config.json, .kube/config, ~/.claude.json, Codex auth—
File writesinside the project, temp foldersoutside the project, shell rc files, LaunchAgents, git hooks, authorized_keys—
Environment variablesordinary namesnames with KEY, TOKEN, SECRET, PASSWORD, AUTH, COOKIE, SESSION…—
Transcript (session.messages)logged——

Calls made by Claude Code itself, by its built-in plugins, and by plugins your administrator manages aren't policed. The firewall never gets in Claude Code's own way.

Modes (/config)

SettingValuesDefault
Modeask: sensitive calls open a dialog (Allow once / Allow for this session / Always trust this mod / Block). strict: sensitive calls are blocked unless the mod is trusted. Critical calls offer Allow once / Allow for this session / Always allow sending this there / Block, where the last three cover only that secret going to that site. audit: allow everything and log it.ask
Trusted modscomma-separated names; trusted mods skip the dialog for sensitive calls, but critical ones still askempty
Refuse risky mods at loadrefuse to load an untrusted mod whose source pairs the network with processes, files, secret env vars or the transcriptoff

Mods you trust from the dialog or the pane are remembered across sessions, including sessions already open. Allow for this session is forgotten when the session ends. Always allow sending this there lets one mod send one secret to one site from then on (a mod that calls its own API with its own key, say); Block or Untrust in the pane forgets it. In a headless run (claude -p) nobody is there to answer, so ask behaves like strict. It fails closed.

The pane

/firewall opens it. It lists every mod the firewall has seen, with a risk level and badges for what its source uses (network, processes, reads files, secret env, reads transcript, hooks tool calls, rewrites prompts, watches other mods), its counts of allowed and blocked calls, and Trust / Block buttons. Below that is a live activity feed. Blocked calls also show as a toast and a count in the status line.

Limits

  • The load-time check only sees mods that load after the firewall. Mods that loaded earlier are still guarded on every call, but their source scan isn't shown. To make the firewall load first, run it from a folder: add its path to CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json. Mods loaded that way come before installed ones.
  • It guards what mods do through Claude Code's engine. A mod that starts a program (once you've allowed it) has handed control to that program, and anything the program does is outside the firewall's view. That's why every process start is treated as sensitive.
  • Hooks are watched, not stopped. A mod that hooks tool calls can auto-approve them or rewrite them. The firewall flags that capability in the pane ("hooks tool calls") but doesn't interfere with the hooks themselves.
  • Secret detection is pattern-based. It catches .env values (8 characters or more), their URL-encoded forms, and common token shapes. It doesn't catch secrets that have been encrypted, split or base64-encoded first.

Development

claude --plugin-dir plugins/mod-firewall
claude plugin validate plugins/mod-firewall
claude plugin test plugins/mod-firewall
Source 3 files
hooks/register.tsx 498 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Origin, PluginRegisterUses, Register, RenderInput } from 'claude-code'
3
4import type { Activity, Category, ModRecord, Risk, Severity, Verdict } from '../types'
5import { paneBody } from './pane'
6import type { PaneAction, PaneProps } from './pane'
7
8const SELF = 'mod-firewall'
9const PANE = 'mod-firewall'
10const ACTIVITY_CAP = 100
11
12const mods = atom({ plugin: 'mod-firewall', key: 'mods' } as const, [])
13const activity = atom({ plugin: 'mod-firewall', key: 'activity' } as const, [])
14const blockedCount = atom({ plugin: 'mod-firewall', key: 'blockedCount' } as const, 0)
15
16// ---------- what counts as sensitive ----------
17
18export type Mode = 'ask' | 'strict' | 'audit'
19export type Config = { mode: Mode; trusted: string[]; refuseRiskyAtLoad: boolean }
20export const DEFAULT_CONFIG: Config = { mode: 'ask', trusted: [], refuseRiskyAtLoad: false }
21
22export function readConfig(options: Readonly<Record<string, unknown>>): Config {
23  const mode = options.mode as Mode
24  return {
25    mode: mode === 'ask' || mode === 'strict' || mode === 'audit' ? mode : DEFAULT_CONFIG.mode,
26    trusted: String(options.trusted ?? '')
27      .split(',')
28      .map(name => name.trim())
29      .filter(Boolean),
30    refuseRiskyAtLoad: options.refuseRiskyAtLoad === true,
31  }
32}
33
34const SECRET_PATHS: readonly RegExp[] = [
35  /(^|\/)\.env(\.[\w.-]+)?$/i,
36  /\.(pem|key|p12|pfx|keystore|jks)$/i,
37  /(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i,
38  /(^|\/)\.ssh\//,
39  /(^|\/)\.aws\/credentials$/,
40  /(^|\/)\.(npmrc|netrc|pypirc|git-credentials)$/,
41  /(^|\/)\.config\/gh\/hosts\.ya?ml$/,
42  /(^|\/)\.docker\/config\.json$/,
43  /(^|\/)\.kube\/config$/,
44  /(^|\/)\.claude\.json$/,
45  /(^|\/)\.codex\/auth\.json$/,
46  /(^|\/)Library\/Keychains\//,
47]
48
49export function isSecretPath(path: string): boolean {
50  return SECRET_PATHS.some(pattern => pattern.test(path))
51}
52
53export function isSecretEnvName(name: string): boolean {
54  return /(KEY|TOKEN|SECRET|PASSW(OR)?D|PASS$|CREDENTIAL|AUTH|COOKIE|SESSION|PRIVATE)/i.test(name)
55}
56
57// Writes outside the project, or into places that run code later (shell rc files, launch agents, git hooks).
58export function isRiskyWrite(path: string, projectRoot: string, home: string): boolean {
59  if (/(^|\/)(\.zshrc|\.bashrc|\.bash_profile|\.profile|\.zprofile)$/.test(path)) return true
60  if (/Library\/LaunchAgents\/|\/\.git\/hooks\/|\/\.ssh\/authorized_keys$/.test(path)) return true
61  if (projectRoot && path.startsWith(`${projectRoot}/`)) return false
62  if (path.startsWith('/tmp/') || path.startsWith('/private/tmp/') || path.startsWith('/var/folders/')) return false
63  return path.startsWith('/') || (home !== '' && path.startsWith(home))
64}
65
66// Well-known token shapes, so a secret is caught even when it never sat in a .env file.
67const TOKEN_PATTERNS: readonly [string, RegExp][] = [
68  ['an Anthropic API key', /sk-ant-[A-Za-z0-9_-]{20,}/],
69  ['an OpenRouter API key', /sk-or-v1-[A-Za-z0-9]{32,}/],
70  ['an OpenAI API key', /sk-(?!ant-|or-)(proj-)?[A-Za-z0-9_-]{32,}/],
71  ['a GitHub token', /\b(gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/],
72  ['an AWS access key', /\bAKIA[0-9A-Z]{16}\b/],
73  ['a Slack token', /\bxox[abprs]-[A-Za-z0-9-]{10,}/],
74  ['a Google API key', /\bAIza[0-9A-Za-z_-]{35}\b/],
75  ['a private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
76]
77
78// Values from .env files worth watching for: long enough not to match by accident.
79export function parseDotenv(text: string): Map<string, string> {
80  const values = new Map<string, string>()
81  for (const raw of text.split('\n')) {
82    const line = raw.trim()
83    if (!line || line.startsWith('#')) continue
84    const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line)
85    if (!match) continue
86    const value = (match[2] ?? '').replace(/^(['"])(.*)\1$/, '$2').trim()
87    if (value.length >= 8) values.set(match[1] ?? '', value)
88  }
89  return values
90}
91
92// What secrets, if any, a piece of outgoing data carries: .env values by name, then token shapes.
93export function findSecrets(text: string, known: ReadonlyMap<string, string>): string[] {
94  if (!text) return []
95  const found: string[] = []
96  for (const [name, value] of known) {
97    if (text.includes(value) || text.includes(encodeURIComponent(value))) found.push(`${name} from .env`)
98  }
99  for (const [label, pattern] of TOKEN_PATTERNS) {
100    if (pattern.test(text)) found.push(label)
101  }
102  return found
103}
104
105// `grant` names what an "allow for this session" or "always allow" answer to a critical call covers:
106// these secrets to this destination, so the same mod sending another secret, or elsewhere, still asks.
107export type Check = { category: Category; severity: Severity; target: string; reason: string; grant?: string }
108
109export function checkFetch(url: string, init: { method?: string; headers?: Record<string, string>; body?: string; socketPath?: string } | undefined, known: ReadonlyMap<string, string>): Check {
110  const method = (init?.method ?? 'GET').toUpperCase()
111  let host = url
112  try {
113    host = new URL(url).host
114  } catch {}
115  const target = init?.socketPath ? `${method} ${url} (via socket ${init.socketPath})` : `${method} ${host}`
116  const destination = init?.socketPath ? 'a local socket' : host
117  const secrets = findSecrets([url, init?.body ?? '', ...Object.values(init?.headers ?? {})].join('\n'), known)
118  if (secrets.length) {
119    const sent = secrets.join(', ')
120    return { category: 'network', severity: 'critical', target, reason: `send ${sent} to ${destination}`, grant: `${sent} to ${init?.socketPath ?? host}` }
121  }
122  return { category: 'network', severity: 'sensitive', target, reason: `network request to ${destination}` }
123}
124
125export function checkRead(path: string): Check {
126  return isSecretPath(path)
127    ? { category: 'secret-file', severity: 'sensitive', target: path, reason: `read a secrets file (${path})` }
128    : { category: 'file-read', severity: 'info', target: path, reason: 'file read' }
129}
130
131export function checkWrite(path: string, projectRoot: string, home: string): Check {
132  return isRiskyWrite(path, projectRoot, home)
133    ? { category: 'file-write', severity: 'sensitive', target: path, reason: `write outside the project (${path})` }
134    : { category: 'file-write', severity: 'info', target: path, reason: 'file write in the project' }
135}
136
137export function checkEnv(name: string): Check {
138  return isSecretEnvName(name)
139    ? { category: 'secret-env', severity: 'sensitive', target: name, reason: `read the environment variable ${name}` }
140    : { category: 'env', severity: 'info', target: name, reason: 'environment variable read' }
141}
142
143export function checkProcess(argv: readonly string[]): Check {
144  const shown = argv.join(' ').slice(0, 160)
145  return { category: 'process', severity: 'sensitive', target: shown, reason: `run a program on your machine: ${shown}` }
146}
147
148// ---------- what a mod can do, from the engine's scan at load ----------
149
150export function badgesFor(uses: PluginRegisterUses): { badges: string[]; risk: Risk } {
151  const calls = new Set(uses.calls)
152  const events = uses.events
153  const has = (...names: string[]) => names.some(name => calls.has(name))
154  const badges: string[] = []
155  const network = has('http.fetch')
156  const process = has('process.run', 'process.spawn')
157  const files = has('fs.read', 'fs.list')
158  const writes = has('fs.write')
159  const secretEnv = (uses.env?.reads ?? []).filter(isSecretEnvName)
160  const transcript = has('session.messages', 'model.fork')
161  if (network) badges.push('network')
162  if (process) badges.push('processes')
163  if (files) badges.push('reads files')
164  if (writes) badges.push('writes files')
165  if (secretEnv.length) badges.push(`secret env: ${secretEnv.join(', ')}`)
166  else if (uses.env?.reads.length) badges.push('env vars')
167  if (transcript) badges.push('reads transcript')
168  if (events.some(e => e === 'tool.call' || e === 'tool.check' || e === '*' || e.startsWith('tool.'))) badges.push('hooks tool calls')
169  if (events.some(e => e === 'prompt.submit' || e === 'prompt.compose' || e === '*')) badges.push('rewrites prompts')
170  if (events.some(e => ['http.fetch', 'fs.read', 'process.run', 'process.spawn', 'plugin.register', '*'].includes(e))) badges.push('watches other mods')
171  const reach = process || files || writes || secretEnv.length > 0 || transcript
172  const risk: Risk = network && reach ? 'high' : network || process || writes || secretEnv.length ? 'medium' : 'low'
173  return { badges, risk }
174}
175
176// ---------- decisions ----------
177
178export type Decision = 'allow' | 'ask' | 'block' | 'flag'
179
180// `isSessionAllowed` is an answer given for this very call: the kind of call, or for a critical one the
181// secret and destination it was granted for. Trust alone never lets a secret out.
182export function decide(mode: Mode, severity: Severity, isTrusted: boolean, isBlockedMod: boolean, isSessionAllowed: boolean): Decision {
183  if (severity === 'info') return 'allow'
184  if (isBlockedMod) return 'block'
185  if (mode === 'audit') return 'flag'
186  if (severity === 'critical') return isSessionAllowed ? 'allow' : mode === 'strict' ? 'block' : 'ask'
187  if (isTrusted || isSessionAllowed) return 'allow'
188  return mode === 'strict' ? 'block' : 'ask'
189}
190
191// Calls Claude Code itself makes, or its bundled and admin-managed plugins, are not ours to police.
192export function isPoliced(origin: Origin): boolean {
193  if (origin.plugin === SELF || origin.plugin === 'engine' || origin.plugin === 'client') return false
194  return origin.tier === 'user'
195}
196
197// ---------- module state (starts over on a reload) ----------
198
199let config: Config = DEFAULT_CONFIG
200let projectRoot = ''
201let home = ''
202let known = new Map<string, string>()
203let rememberedTrust: string[] = []
204let rememberedGrants: string[] = []
205const sessionAllowed = new Set<string>()
206const blockedMods = new Set<string>()
207const pendingAsks = new Map<string, Promise<boolean>>()
208let seq = 0
209
210const ALLOW_ONCE = 'Allow once'
211const ALLOW_SESSION = 'Allow for this session'
212const ALWAYS = 'Always trust this mod'
213const ALWAYS_SEND = 'Always allow sending this there'
214const BLOCK = 'Block'
215
216async function loadSecrets($: EngineInterface) {
217  projectRoot = await $.session.root()
218  home = (await $.env.get('HOME')) ?? ''
219  const found = new Map<string, string>()
220  for (const name of ['.env', '.env.local', '.env.development', '.env.production']) {
221    try {
222      for (const [key, value] of parseDotenv(await $.fs.read(`${projectRoot}/${name}`))) found.set(key, value)
223    } catch {}
224  }
225  known = found
226  await reloadTrust($)
227  await reloadGrants($)
228}
229
230// The store is shared by every session of this plugin: read it fresh, so a trust given in another
231// open session counts here, and a write here keeps what the others added.
232async function reloadTrust($: EngineInterface): Promise<string[]> {
233  const stored = await $.store.get('trusted')
234  rememberedTrust = Array.isArray(stored) ? stored.filter((x): x is string => typeof x === 'string') : []
235  return rememberedTrust
236}
237
238async function reloadGrants($: EngineInterface): Promise<string[]> {
239  const stored = await $.store.get('secretGrants')
240  rememberedGrants = Array.isArray(stored) ? stored.filter((x): x is string => typeof x === 'string') : []
241  return rememberedGrants
242}
243
244// What an answer to this call is remembered under: the kind of call, or the secret and its destination.
245function grantKey(mod: string, check: Check): string {
246  return check.grant ? `${mod}:secret:${check.grant}` : `${mod}:${check.category}`
247}
248
249async function setGrants($: EngineInterface, fn: (grants: string[]) => string[]) {
250  rememberedGrants = fn(await reloadGrants($))
251  await $.store.set('secretGrants', rememberedGrants)
252}
253
254function isTrusted(mod: string): boolean {
255  return config.trusted.includes(mod) || rememberedTrust.includes(mod)
256}
257
258async function setTrust($: EngineInterface, mod: string, trusted: boolean) {
259  const stored = await reloadTrust($)
260  rememberedTrust = trusted ? [...new Set([...stored, mod])] : stored.filter(name => name !== mod)
261  if (trusted) blockedMods.delete(mod)
262  await $.store.set('trusted', rememberedTrust)
263  if (!trusted) await setGrants($, grants => grants.filter(key => !key.startsWith(`${mod}:`)))
264  await touchMod($, mod, m => m)
265}
266
267async function setBlocked($: EngineInterface, mod: string, blocked: boolean) {
268  if (blocked) {
269    blockedMods.add(mod)
270    rememberedTrust = (await reloadTrust($)).filter(name => name !== mod)
271    await $.store.set('trusted', rememberedTrust)
272    await setGrants($, grants => grants.filter(key => !key.startsWith(`${mod}:`)))
273  } else blockedMods.delete(mod)
274  await touchMod($, mod, m => m)
275}
276
277async function touchMod($: EngineInterface, name: string, fn: (mod: ModRecord) => ModRecord, provenance = '') {
278  await update($, mods, list => {
279    const at = list.findIndex(m => m.name === name)
280    const base: ModRecord = list[at] ?? { name, provenance, badges: [], risk: 'low', seenAt: 'runtime', allowed: 0, blocked: 0 }
281    const next = fn(base)
282    return at >= 0 ? list.map((m, i) => (i === at ? next : m)) : [...list, next]
283  })
284}
285
286async function record($: EngineInterface, mod: string, check: Check, verdict: Verdict) {
287  seq += 1
288  const entry: Activity = { id: `a${seq}`, at: await $.clock.now(), mod, category: check.category, target: check.target, verdict, reason: check.reason }
289  await update($, activity, list => [...list, entry].slice(-ACTIVITY_CAP))
290  if (verdict === 'info') return
291  await touchMod($, mod, m => ({
292    ...m,
293    allowed: m.allowed + (verdict === 'allowed' || verdict === 'asked-allowed' || verdict === 'flagged' ? 1 : 0),
294    blocked: m.blocked + (verdict === 'blocked' ? 1 : 0),
295  }))
296  if (verdict === 'blocked') {
297    const total = (await read($, blockedCount)) + 1
298    await update($, blockedCount, () => total)
299    $.ui.status(`🛡 mod firewall: ${total} blocked`)
300    $.ui.toast(`🛡 Blocked ${mod}: ${check.reason}`)
301  }
302  if (verdict === 'flagged' && check.severity === 'critical') $.ui.toast(`🛡 ${mod} sent a secret: ${check.reason}`)
303}
304
305// Asks once per mod and kind of call at a time: a burst of identical calls shares one dialog.
306async function ask($: EngineInterface, mod: string, check: Check): Promise<boolean> {
307  const key = `${grantKey(mod, check)}:${check.severity}`
308  const waiting = pendingAsks.get(key)
309  if (waiting) return waiting
310  const asking = (async () => {
311    const options = check.severity === 'critical' ? [ALLOW_ONCE, ALLOW_SESSION, ALWAYS_SEND, BLOCK] : [ALLOW_ONCE, ALLOW_SESSION, ALWAYS, BLOCK]
312    const warning = check.severity === 'critical' ? '⚠ ' : ''
313    try {
314      const answer = await $.ui.ask(`${warning}The mod "${mod}" wants to ${check.reason}. Allow it?`, { options, header: 'Mod firewall' })
315      if (answer === ALLOW_SESSION) sessionAllowed.add(grantKey(mod, check))
316      if (answer === ALWAYS) await setTrust($, mod, true)
317      if (answer === ALWAYS_SEND) await setGrants($, grants => [...new Set([...grants, grantKey(mod, check)])])
318      if (answer === BLOCK) await setBlocked($, mod, true)
319      return answer === ALLOW_ONCE || answer === ALLOW_SESSION || answer === ALWAYS || answer === ALWAYS_SEND
320    } catch {
321      // Dismissed, or nobody to ask (a -p run): the call does not go through.
322      return false
323    }
324  })()
325  pendingAsks.set(key, asking)
326  try {
327    return await asking
328  } finally {
329    pendingAsks.delete(key)
330  }
331}
332
333// The one place every guarded call is judged. Returns a deny reason, or undefined to let it through.
334async function judge($: EngineInterface, origin: Origin, check: Check): Promise<string | undefined> {
335  if (!isPoliced(origin)) return undefined
336  const mod = origin.plugin
337  const key = grantKey(mod, check)
338  const granted = () => sessionAllowed.has(key) || rememberedGrants.includes(key)
339  let decision = decide(config.mode, check.severity, isTrusted(mod), blockedMods.has(mod), granted())
340  if (decision === 'ask' && check.severity !== 'critical' && !isTrusted(mod) && (await reloadTrust($)).includes(mod)) decision = 'allow'
341  // Granted in another open session since this one last looked.
342  if (decision !== 'allow' && check.grant && !granted() && (await reloadGrants($)).includes(key)) {
343    decision = decide(config.mode, check.severity, isTrusted(mod), blockedMods.has(mod), true)
344  }
345  if (decision === 'allow') {
346    await record($, mod, check, check.severity === 'info' ? 'info' : 'allowed')
347    return undefined
348  }
349  if (decision === 'flag') {
350    await record($, mod, check, 'flagged')
351    return undefined
352  }
353  if (decision === 'ask' && (await ask($, mod, check))) {
354    await record($, mod, check, 'asked-allowed')
355    return undefined
356  }
357  await record($, mod, check, 'blocked')
358  return `mod firewall blocked ${mod}: ${check.reason}`
359}
360
361// ---------- drawing ----------
362
363const VERDICT_MARK: Record<Verdict, string> = { allowed: '✓', 'asked-allowed': '✓', blocked: '✕', flagged: '!', info: '·' }
364const VERDICT_COLOR: Record<Verdict, string> = { allowed: 'green', 'asked-allowed': 'green', blocked: 'red', flagged: 'yellow', info: 'gray' }
365const RISK_COLOR: Record<Risk, string> = { low: 'green', medium: 'yellow', high: 'red' }
366
367async function paneProps($: EngineInterface, rows: number): Promise<PaneProps> {
368  const list = await read($, mods)
369  const feed = await read($, activity)
370  const blocked = await read($, blockedCount)
371  const room = Math.max(5, rows - 8 - list.length * 3)
372  return {
373    header: `mode: ${config.mode} · ${list.length} mods seen · ${blocked} calls blocked · /config to change`,
374    mods: list.map(mod => {
375      const trusted = isTrusted(mod.name)
376      const isBlocked = blockedMods.has(mod.name)
377      const state = mod.refused ? `refused at load: ${mod.refused}` : isBlocked ? 'blocked' : trusted ? 'trusted' : 'watched'
378      return {
379        name: mod.name,
380        color: RISK_COLOR[mod.risk],
381        summary: `${mod.risk} risk · ${state} · ${mod.allowed} allowed, ${mod.blocked} blocked`,
382        badges: mod.badges,
383        trusted,
384        blocked: isBlocked,
385        refused: Boolean(mod.refused),
386      }
387    }),
388    feed: feed.slice(-room).map(entry => ({
389      id: entry.id,
390      color: VERDICT_COLOR[entry.verdict],
391      dim: entry.verdict === 'info',
392      text: `${VERDICT_MARK[entry.verdict]} ${entry.mod}  ${entry.category}  ${entry.target.slice(0, 90)}${entry.verdict === 'blocked' ? '  (blocked)' : ''}`,
393    })),
394  }
395}
396
397async function paneAction($: EngineInterface, a: PaneAction) {
398  if (a.type === 'clear') await update($, activity, () => [])
399  else if (a.type === 'trust' || a.type === 'untrust') await setTrust($, a.mod, a.type === 'trust')
400  else await setBlocked($, a.mod, a.type === 'block')
401}
402
403async function renderPane($: EngineInterface, e: RenderInput<'Pane'>) {
404  const elements = $.ui.resolve(e)
405  const props = await paneProps($, e.viewport?.rows ?? 30)
406  const Client = e.surface === 'desktop' && 'Client' in elements ? elements.Client : undefined
407  if (Client) return <Client key="firewall-pane" module="./pane.tsx" width="100%" props={props} />
408  return paneBody(elements, props, a => void paneAction($, a))
409}
410
411// ---------- registration ----------
412
413// Each command is also declared in commands/, so a host lists it as `/mod-firewall:<name>` before
414// any session exists (the desktop app's empty chat); the hooks answer both spellings.
415export const register: Register = (on, options) => {
416  config = readConfig(options)
417
418  on('session.start', async ($, e, next) => {
419    await loadSecrets($)
420    await $.command.register({ name: 'firewall', description: 'Open the mod firewall: what every mod is doing, and trust or block them' }).catch(
421      error => $.ui.toast(`mod-firewall: ${String(error)}`),
422    )
423    return next(e)
424  })
425
426  on('command.run', { command: ['firewall', 'mod-firewall:firewall'] }, async $ => {
427    await $.ui.open({ id: PANE, title: 'Mod firewall' })
428    return { text: 'Mod firewall opened.' }
429  })
430
431  // At load: record what each later mod uses, and refuse risky untrusted ones when asked to.
432  on('plugin.register', async ($, e, next) => {
433    if (e.name === SELF || e.tier !== 'user') return next(e)
434    const { badges, risk } = badgesFor(e.uses)
435    $.ui.log(`mod-firewall: saw ${e.name} (${e.provenance}) at load: ${risk} risk${badges.length ? `, ${badges.join(', ')}` : ''}`, { to: 'debug' })
436    const refuse = config.refuseRiskyAtLoad && risk === 'high' && !isTrusted(e.name) ? `uses ${badges.join(', ')}` : undefined
437    await touchMod($, e.name, m => ({ ...m, provenance: e.provenance, badges, risk, seenAt: 'load', refused: refuse }), e.provenance)
438    if (refuse) {
439      $.ui.toast(`🛡 Refused to load ${e.name}: ${refuse}`)
440      return { refuse: `mod firewall: ${refuse}` }
441    }
442    return next(e)
443  }).catch(($, e, next) => (next.called ? next(e) : undefined))
444
445  on('http.fetch', async ($, e, next) => {
446    const denied = await judge($, next.origin, checkFetch(e.url, e.init, known))
447    return denied ? ({ deny: denied } as never) : next(e)
448  }).catch(($, e, next) => (next.called ? next(e) : ({ deny: 'mod firewall could not judge this request' } as never)))
449
450  on('fs.read', async ($, e, next) => {
451    const denied = await judge($, next.origin, checkRead(e.path))
452    return denied ? ({ deny: denied } as never) : next(e)
453  }).catch(($, e, next) => (next.called ? next(e) : ({ deny: 'mod firewall could not judge this read' } as never)))
454
455  on('fs.write', async ($, e, next) => {
456    const denied = await judge($, next.origin, checkWrite(e.path, projectRoot, home))
457    return denied ? ({ deny: denied } as never) : next(e)
458  }).catch(($, e, next) => (next.called ? next(e) : ({ deny: 'mod firewall could not judge this write' } as never)))
459
460  on('env.get', async ($, e, next) => {
461    const denied = await judge($, next.origin, checkEnv(e.name))
462    return denied ? ({ deny: denied } as never) : next(e)
463  }).catch(($, e, next) => (next.called ? next(e) : ({ deny: 'mod firewall could not judge this read' } as never)))
464
465  on('process.run', async ($, e, next) => {
466    const denied = await judge($, next.origin, checkProcess(e.argv))
467    return denied ? ({ deny: denied } as never) : next(e)
468  }).catch(($, e, next) => (next.called ? next(e) : ({ deny: 'mod firewall could not judge this command' } as never)))
469
470  on('process.spawn', async function* ($, e, next) {
471    const denied = await judge($, next.origin, checkProcess(e.argv))
472    if (denied) return { deny: denied } as never
473    return yield* next(e)
474  }).catch(async function* ($, e, next) {
475    if (next.called) return yield* next(e)
476    return { deny: 'mod firewall could not judge this command' } as never
477  })
478
479  // Transcript access is logged, not gated: a mod reading the conversation is worth knowing about.
480  on('session.messages', async ($, e, next) => {
481    if (isPoliced(next.origin)) {
482      await record($, next.origin.plugin, { category: 'transcript', severity: 'info', target: 'session.messages', reason: 'read the conversation' }, 'info')
483    }
484    return next(e)
485  }).catch(($, e, next) => next(e))
486
487  // The desktop's pane module posts the button pressed.
488  on('ui.message', async ($, e, next) => {
489    if (e.element !== 'firewall-pane') return next(e)
490    const a = e.data as PaneAction | undefined
491    const isModAction = (a?.type === 'trust' || a?.type === 'untrust' || a?.type === 'block' || a?.type === 'unblock') && typeof a.mod === 'string'
492    if (a && (isModAction || a.type === 'clear')) await paneAction($, a)
493    return {}
494  })
495
496  on('ui.render', { component: 'Pane', requestId: 'mod-firewall' }, ($, e) => renderPane($, e))
497}
498
hooks/pane.tsx 74 lines
1import type { ClientElements, ClientModule } from 'claude-code'
2
3// The firewall pane's body, one layout for both surfaces. On the desktop this module draws it: a
4// Button the pane's render hook draws keeps its handle only until the next redraw, and the pane
5// redraws on every call a mod makes, so a click there can be lost ("ui_press not handled" in the
6// app's log); a Button here keeps its own handler, and what it does reaches the hooks as a post.
7// The terminal draws the same body from the render hook, its Buttons calling the hooks directly.
8
9export type PaneMod = { name: string; color: string; summary: string; badges: string[]; trusted: boolean; blocked: boolean; refused: boolean }
10export type PaneEntry = { id: string; color: string; dim: boolean; text: string }
11export type PaneProps = { header: string; mods: PaneMod[]; feed: PaneEntry[] }
12export type PaneAction = { type: 'trust' | 'untrust' | 'block' | 'unblock'; mod: string } | { type: 'clear' }
13// pressed: the action last pressed on each mod, shown until the hooks' next props say it took.
14export type PaneState = { pressed: Record<string, string> }
15
16export function paneBody(el: Pick<ClientElements, 'Box' | 'Text' | 'Button'>, p: PaneProps, act: (a: PaneAction) => void, pressed: Record<string, string> = {}) {
17  const { Box, Text, Button } = el
18  return (
19    <Box flexDirection="column">
20      <Text dimColor>{p.header}</Text>
21      {p.mods.length === 0 && <Text dimColor>No other mods have done anything yet.</Text>}
22      {p.mods.map(mod => (
23        <Box key={mod.name} flexDirection="column" marginTop={1}>
24          <Text>
25            <Text bold color={mod.color}>{mod.name}</Text>
26            <Text dimColor>{`  ${mod.summary}`}</Text>
27          </Text>
28          {mod.badges.length > 0 && <Text dimColor>{`  ${mod.badges.join(' · ')}`}</Text>}
29          {pressed[mod.name] ? (
30            <Text color="warning">{`  ${pressed[mod.name]}…`}</Text>
31          ) : (
32            !mod.refused && (
33              <Box>
34                {!mod.trusted && <Button key={`trust-${mod.name}`} label="Trust" onPress={() => act({ type: 'trust', mod: mod.name })} />}
35                {mod.trusted && <Button key={`untrust-${mod.name}`} label="Untrust" onPress={() => act({ type: 'untrust', mod: mod.name })} />}
36                {!mod.blocked && <Button key={`block-${mod.name}`} label="Block" onPress={() => act({ type: 'block', mod: mod.name })} />}
37                {mod.blocked && <Button key={`unblock-${mod.name}`} label="Unblock" onPress={() => act({ type: 'unblock', mod: mod.name })} />}
38              </Box>
39            )
40          )}
41        </Box>
42      ))}
43      <Text bold>{'\nActivity'}</Text>
44      {p.feed.length === 0 && <Text dimColor>Nothing yet.</Text>}
45      {p.feed.map(entry => (
46        <Text key={entry.id} color={entry.color} dimColor={entry.dim}>
47          {entry.text}
48        </Text>
49      ))}
50      {p.feed.length > 0 && <Button key="clear" label="Clear activity" onPress={() => act({ type: 'clear' })} />}
51    </Box>
52  )
53}
54
55const PRESSED: Record<PaneAction['type'], string> = { trust: 'Trusting', untrust: 'Untrusting', block: 'Blocking', unblock: 'Unblocking', clear: 'Clearing' }
56
57// What each mod showed when its button was pressed: a press is done once that changes.
58let shown: Record<string, string> = {}
59
60const Pane: ClientModule<PaneProps, PaneState> = (props, surface) => {
61  const now = Object.fromEntries(props.mods.map(m => [m.name, `${m.trusted}${m.blocked}`]))
62  const pressed = Object.fromEntries(Object.entries(surface.state?.pressed ?? {}).filter(([name]) => now[name] === shown[name]))
63  const act = (a: PaneAction) => {
64    if (a.type !== 'clear') {
65      shown = { ...shown, [a.mod]: now[a.mod] ?? '' }
66      surface.setState({ pressed: { ...pressed, [a.mod]: PRESSED[a.type] } })
67    }
68    surface.post(a)
69  }
70  return paneBody(surface.elements, props, act, pressed)
71}
72
73export default Pane
74
types/index.d.ts 32 lines
1export type Category = 'network' | 'process' | 'secret-file' | 'file-read' | 'file-write' | 'secret-env' | 'env' | 'transcript'
2export type Severity = 'info' | 'sensitive' | 'critical'
3export type Verdict = 'allowed' | 'asked-allowed' | 'blocked' | 'flagged' | 'info'
4export type Risk = 'low' | 'medium' | 'high'
5
6export type ModRecord = {
7  name: string
8  provenance: string
9  badges: string[]
10  risk: Risk
11  seenAt: 'load' | 'runtime'
12  allowed: number
13  blocked: number
14  refused?: string
15}
16
17export type Activity = {
18  id: string
19  at: number
20  mod: string
21  category: Category
22  target: string
23  verdict: Verdict
24  reason?: string
25}
26
27declare module 'claude-code' {
28  interface PluginState {
29    'mod-firewall': { mods: ModRecord[]; activity: Activity[]; blockedCount: number }
30  }
31}
32