SLOPSHOPPER

secret-guard

Keeps secrets out of the conversation: hides API keys and private keys before the model or the transcript sees them, and blocks reads of credential files and…

guardtoaststatusprompttool
★ 7v0.5.1MITupdated 2026-10-25arasovic/claude-code-mods/secret-guard
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · secret-guard
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(cat .env) ⎿ Denied by secret-guard: secret-guard: .env is a credential file. Do not try another way to read it. To lea ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ secret-guard: 🔴 secrets: none seen, 1 blocked · env scrub off
README

secret-guard

Keeps secrets out of the conversation. API keys and private keys are hidden before Claude reads them, credential files cannot be opened, and commands that print secrets do not run.

secret-guard's status light

What it does

  • Hides secrets in what tools return. Known key formats become [secret-guard: <rule>] before Claude reads the result, and the session transcript on disk keeps the hidden form too. Formats: AWS, GitHub, GitLab, Slack, Stripe, Google, Anthropic, OpenAI, OpenRouter, Groq, xAI, Hugging Face, npm, Shopify, SendGrid and HashiCorp Vault keys, private key blocks, age secret keys, JWTs, and secret-named values such as DB_PASSWORD=…, REDISCLI_AUTH=…, "client_secret": "…" or a YAML api_key: …, a string field named like a secret in a structured result, the password in a connection URL such as redis://:…@host, an Authorization: Bearer … or Basic … value, a URL credential such as ?access_token=… or X-Amz-Signature=…, and the authorization and cookie values in a HAR file. A file path with an extension, such as GOOGLE_APPLICATION_CREDENTIALS=/home/me/sa.json, stays.
  • Hides secrets you paste. A key in your own message reaches Claude and the transcript in the same hidden form.
  • Blocks credential files. Reading or editing .env files, .dev.vars, .envrc, SSH and GPG private keys, ~/.aws/credentials, gcloud, Azure, kube and Docker logins, ~/.config/gh/hosts.yml, .npmrc, .pypirc, .netrc, shell history (zsh session files too) and REPL history such as .rediscli_history, coding agents' auth.json logins under a dot folder (~/.codex, ~/.pi/agent), wrangler's default.toml, GitHub Copilot's apps.json and hosts.json, Terraform state, Chrome, Chromium, Brave, Edge and Firefox cookie and password stores (macOS, Linux and Windows profiles, quoted paths with spaces included), KeePass files, the pass store, 1Password and Bitwarden data on Linux, macOS and Windows (a whole vault folder too, and $APPDATA or %APPDATA% paths), a process's environ, and the macOS keychain. A link to one of these files is followed and blocked too. A file you add with @ is not attached either, and a toast says so. Templates (.env.example, .env.sample, .env.template, .env.defaults, .env.dist) and public keys (*.pub) stay readable.
  • Blocks commands that print secrets. printenv, env with no command (env -0, env FOO=bar), bare export, declare and typeset (and their -p), security find-generic-password, gh auth token, aws configure get, gcloud auth print-access-token, gcloud secrets versions access, az keyvault secret show, kubectl get secret, git credential fill, Bitwarden, 1Password and pass reads (bw get, bw list items, bw export, bw unlock, op read, op inject, op signin, op item get --reveal, pass show), decryption (sops -d, age -d, gpg -d, gpg --export-secret-keys, ansible-vault view), echo $SOME_TOKEN, <<< $SOME_TOKEN, a script that prints one such variable (node -p process.env.GITHUB_TOKEN), and any shell command that names a credential file, such as cat .dev.vars | curl …, or reaches one through a glob, a brace or a link (cat ~/.aw?/credentials, cat .{env,bak}, or cat notes where notes links to .env). A NAME=value or env before the command, or a full path such as /usr/bin/printenv, does not hide it.
  • Blocks sending a secret out. A command, web request or MCP call whose arguments carry a key is refused.
  • Checks an env file without showing it. Claude can call the env_check tool to ask whether .env or another env file sets a variable. The answer is set, empty or missing. It also says when the template, such as .env.example, does not list the name. The tool reads the file, but Claude never sees a value or its length. When the mod blocks a read or a command, the refusal names the tool.
  • Shows a status light. 🟢 nothing seen, 🟡 something was hidden, 🔴 something was blocked. env scrub off means Claude Code still passes your environment variables to the commands it runs (see below).

Turn on env scrubbing too

Set CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1 in the env block of ~/.claude/settings.json. Claude Code then removes its own credentials from the environment of the commands it runs, so there is nothing for a command to print. The mod cannot set this for you; the status light shows when it is off.

Limits

  • On some setups, Claude Code's built-in "Security default" plugin runs before the mod and sends some rows past it. Secrets in these rows reach Claude and the transcript unhidden:
  • files you add with @, and files Claude Code adds again after a summary
  • lines from a file that changed outside Claude
  • notes that other hooks add
  • conversation summaries
  • skill text
  • other attachments, such as an IDE selection

This happens on Team and Enterprise plans, on a machine with managed settings, and in the desktop app unless you use a personal Pro or Max plan. Your prompts, pasted text, Claude's replies and tool results are still hidden, and the blocks still hold.

  • The mod looks up the globs, braces and links of a shell command in the file system. This check has limits:
  • It reads only words with no quote or backslash. A quoted or escaped glob, or a quoted link, is not looked up. A credential file name in it is still blocked.
  • It does not look into heredoc bodies, bash -c "…" text, or what echo and printf print.
  • A relative path is looked up in the shell's current folder, so a cd in an earlier command counts. A plain cd <folder> earlier in the same command counts too, but a cd there with a quote or a $ sends the check to the wrong folder.
  • ** matches one folder level, like *. As in the shell, * skips a dotfile, so cat * does not check .env, but cat .* does. When the command may turn on dotglob (shopt, set, setopt, eval, source, GLOBIGNORE, or zsh's *(D)), * matches a dotfile too. The check assumes your shell profile does not turn dotglob on.
  • A path with $ or a backtick, other than a leading $HOME, is not looked up.
  • A command that needs more than 32 file system calls is refused. Split it, or name the files instead of a pattern.
  • A script Claude writes and runs (python -c …, node -e …) can open any file. The mod cannot see what it opens; it hides known key formats in the output, nothing more.
  • The mod does not read quoted text as commands. So grep -E "(export )?" file runs.
  • A backslash in quotes is part of a search pattern, so grep -rn '\.env' . runs. Outside quotes it escapes the next character, so cat \.env is still blocked. A backslash separates directories only in a Windows path (C:\…, \\server\…).
  • Punctuation right after a file name is not part of it, so git commit -m "copy .env.example, then edit" runs. After . or / it stays, so grep -r token ~/.ssh/. is still blocked.
  • The mod treats a heredoc as data when cat or tee writes it out with a quoted delimiter, as in cat > notes.py <<'EOF'. It does not check that body. This holds only when the opener line has nothing but && steps before it, and no {, ( or $( is still open.
  • The mod checks every other heredoc body. python3 - <<'EOF' runs its body as code. A <<EOF body runs any $(…) in it. So a credential file name (.env) in such a body is blocked.
  • The mod does not read quotes in a heredoc body that runs. So a quoted env or export there is blocked, as in grep -E "(export )?" f in a bash <<'EOF' body, or print('env') in a python3 <<'EOF' body.
  • The mod splits commands with a simple reader, not a full shell parser. A command built to fool it gets through. Examples:
  • a heredoc end line with extra spaces, or with a \ on the line before it
  • a delimiter such as <<$END or <<A-B!
  • a << inside a quote or a comment
  • nested escaped backticks, or $(( '$(…)' ))
  • a function that redefines cat or tee
  • a quoted bracket before an open { or (, as in { echo ")" && cat <<'EOF' … } | bash, because the mod counts brackets without reading quotes

The mod still hides known key formats in the output.

  • Secrets in a format it does not know pass through. Examples:
  • WireGuard's PrivateKey = …, Azure DevOps tokens, and PHP's define('DB_PASSWORD', '…')
  • a Cookie: header outside a HAR file
  • a Kubernetes Secret data: value whose key is not named like a secret (tls.key, .dockerconfigjson)
  • a password shorter than 8 characters, or another secret-named value shorter than 12
  • an unquoted YAML value with no digit (password: hunterhunter)
  • a Bearer or Basic credential with no Authorization header name before it, or shorter than 20 characters
  • A URL credential (?token=, ?api_key=, X-Amz-Signature=, sig=) is hidden in your messages too. So a signed download link you paste reaches Claude without its signature, and Claude cannot open it. Download the file yourself and give Claude its path.
  • A command that sends a variable, such as curl "https://api.test/?t=$TOKEN", runs. The mod sees only the name, not the value. Env scrubbing (above) is the defense here.
  • Commands are read in shell (sh, bash, zsh) form only. PowerShell and cmd forms that print secrets, such as echo $env:API_KEY, Get-ChildItem Env: or cmd /c set, run. A credential file name in them is still blocked.
  • If a check itself fails, the call is refused. When the tool had already started, it may have run, and only its output is withheld.
  • A connection URL password shorter than 8 characters, or with a raw / in it, is not hidden. A percent-encoded / (%2F) is fine. Dev passwords such as postgres:postgres@ are hidden, so a shell command that holds one is refused.
  • A name followed by ( is read as a function call, not a file, so grep "mock.env(" tests runs. A zsh glob qualifier on a credential file (cat .env(N)) gets through the same way; known key formats in its output are still hidden. Code names such as process.env, import.meta.env and c.env are not files either, but a script that prints the whole environment (console.log(process.env), print(os.environ)) is blocked. So is one that prints a secret-named variable in the same statement (print(os.getenv("API_KEY"))) in JavaScript, Python or Ruby; a test such as !process.env.GITHUB_TOKEN runs, and other languages are not read.
  • jq reads its first argument as a filter, so jq '.env.PATH' settings.json runs. The files it reads are still checked, including --rawfile and --slurpfile values, redirects, and the filter file of -f. Other tools with a filter argument, such as yq, are not read this way. A filter that uses jq's env or $ENV prints the environment, so it is blocked, jq -n 'env.HOME' included.
  • The quoted text of a git -m message and of a gh --title, --body or --notes is not read, so git commit -m "ignore .env files" runs. A message or body file (-F, --body-file) is still read, and so is quoted text with $ or a backtick in it.
  • Commands that touch a credential file without printing it still run: ls, stat, test / [, touch, chmod, chown, rm, ssh-keygen (but not -i, which prints a private key), ssh-add, and ssh, scp or sftp with a key given by -i or IdentityFile before the host (in GIT_SSH_COMMAND too). In a command with a pipe, $(…) or a backtick they are read like any other, because the file name they print can reach a command that opens it (ls .env | xargs cat). cp and mv run when the credential file is the target (cp .env.example .env), not when it is the source, so a file cannot be copied to a new name and read there.
  • env_check has these limits:
  • set means only that the line has a value. A placeholder copied from the template, such as API_KEY=your-key-here, is set too. The answer says this whenever a name is set. If a service fails, check the value yourself.
  • It does not compare values with the template. Otherwise Claude could guess a value by changing the template.
  • X="" and X=' ' are empty. A line without = is not read.
  • As in a shell, a # starts a comment only after a space: X= # note is empty, X=#abc is set. Node's dotenv reads X=#abc as empty.
  • When Claude gives no names, the tool lists the names in the file and in the template. It lists only names in capitals, such as API_KEY.
  • It reads only the env files that secret-guard blocks: .env, .env.*, *.env, .dev.vars, .envrc and .flaskenv. A template is one of these names with .example, .sample, .template, .defaults or .dist added. It is given as the template, not as the file.
  • The answer shows a path as Claude typed it, so ~/app/.env does not show your home folder.
  • It follows a link only to one of these files. When it cannot tell where a link leads, it does not read the file.
  • The screen can show a row for a moment before it is rewritten. Claude and the transcript only read the hidden form.
  • A value hidden in source code, such as a test token, is hidden from Claude as well. Claude can still edit the other lines of that file. A file write, shell command or MCP call that would put a [secret-guard: <rule>] tag back is refused, so the real value is never overwritten; Claude will ask you to change that line.

Install

claude plugin marketplace add arasovic/claude-code-mods
claude plugin install secret-guard@claude-code-mods

Restart Claude Code. The status light appears under the prompt.

Develop

claude plugin validate .
claude plugin test .
../typecheck.sh secret-guard
Source 3 files
hooks/register.ts 506 lines
1import type { EngineInterface, FsEntry, Register } from 'claude-code'
2import { ENV_CHECK_TOOL, ENV_PATHS, envCheck, envCheckSpec } from './env-check'
3import {
4  braceWords, commandSegments, globPart, isGlob, jqReadsEnvironment, pathWords, quotedWords, unquotedWords, withoutDataHeredocs,
5  withoutHeredocs, withoutJqFilter,
6} from './shell-read'
7
8// Derived from gitleaks' default rules, loosened where key formats change.
9const SECRET_RULES: readonly [string, RegExp][] = [
10  ['private-key', /-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----|$)/g],
11  ['aws-key', /\b(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16}\b/g],
12  ['github-token', /\b(?:gh[pousr]_[0-9A-Za-z]{36}|github_pat_\w{82})\b/g],
13  ['slack-token', /\bxox[abpers]-[0-9A-Za-z-]{10,}/g],
14  ['slack-webhook', /hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9+/]{43,56}/g],
15  ['stripe-key', /\b[sr]k_(?:test|live|prod)_[0-9A-Za-z]{10,99}\b/g],
16  ['google-api-key', /\bAIza[\w-]{35}(?![\w-])/g],
17  ['anthropic-key', /\bsk-ant-[\w-]{20,}/g],
18  ['openai-key', /\bsk-(?:proj|svcacct|admin)-[\w-]{20,}/g],
19  // OpenRouter, Groq and xAI follow trufflehog's detectors; gitleaks has no rule for them.
20  ['openrouter-key', /\bsk-or-v1-[0-9a-f]{64}\b/g],
21  ['groq-key', /\bgsk_[A-Za-z0-9]{52}\b/g],
22  ['xai-key', /\bxai-\w{80}\b/g],
23  ['huggingface-token', /\bhf_[A-Za-z]{34}\b/g],
24  ['npm-token', /\bnpm_[A-Za-z0-9]{36}\b/g],
25  ['gitlab-token', /\bglpat-[\w-]{20,}(?:\.[0-9a-z]{9}\b)?/g],
26  ['vault-token', /\bhvs\.[\w-]{90,}/g],
27  ['shopify-token', /\bshp(?:at|ca|pa|ss)_[a-fA-F0-9]{32}\b/g],
28  ['sendgrid-key', /\bSG\.[\w=.-]{66}/g],
29  ['age-key', /\bAGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}\b/g],
30  ['jwt',/\bey[A-Za-z0-9_-]{17,}\.ey[A-Za-z0-9_-]{17,}\.[A-Za-z0-9_-]{10,}/g],
31]
32
33// .env style: UPPER_CASE name, unquoted or quoted value, not a $reference or <placeholder>. A leading quote is a list item
34// (`"POSTGRES_PASSWORD=…",` in docker inspect). AUTH and PASS count only as the last whole word (REDISCLI_AUTH, DB_PASS),
35// so AUTHOR, BYPASS and GOOGLE_OAUTH stay; PWD needs a prefix, so the shell's PWD and OLDPWD stay.
36// Passwords are often short, so they hide from 8 characters and other secrets from 12.
37const envLine = (name: string, min: number) =>
38  new RegExp(String.raw`^(?<head>\s*["']?(?:export\s+)?(?:${name})\s*=\s*["']?)(?<value>[^\s"'#$<]{${min},})`, 'gm')
39// code, JSON: a quoted literal assigned to a secret-shaped name
40const quotedLiteral = (name: string, min: number) =>
41  new RegExp(String.raw`(?<head>["']?\b[\w.-]*(?:${name})["']?\s*[:=]\s*(["']))(?<value>[^"'\s$<{]{${min},})(?=\2)`, 'gi')
42
43// Only the value is hidden; the name stays so the model knows the key exists.
44const ASSIGNMENTS = [
45  envLine(String.raw`[A-Z0-9_]*(?:SECRET|TOKEN|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CREDENTIAL)[A-Z0-9_]*|(?:[A-Z0-9_]*_)?AUTH`, 12),
46  envLine(String.raw`[A-Z0-9_]*(?:PASSWORD|PASSWD)[A-Z0-9_]*|(?:[A-Z0-9_]*_)?PASS|[A-Z0-9_]*_PWD`, 8),
47  quotedLiteral('secret|token|api_?key|access_?key|private_?key', 12),
48  quotedLiteral('password|passwd', 8),
49  // YAML: an unquoted value that runs to the end of the line. It needs a digit, and code punctuation or a dotted name
50  // (`token: getToken(a),`, `password: config.db.password1`, `token: res.tokens[0]`) means it is code.
51  /^(?<head>[ \t]*(?:-[ \t]+)?[\w.-]*(?:secret|token|password|passwd|api_?key|access_?key|private_?key)[ \t]*:[ \t]+)(?<value>(?=\S*\d)(?![A-Za-z_]\w*(?:\.\w+)+[ \t\r]*$)[^\s(,;{[\]$<#"']{8,})(?=[ \t\r]*$)/gim,
52  // the password in a connection URL: redis://:pass@host, postgres://user:REDACTED@host; it runs to the last @
53  /(?<head>\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@]*:)(?<value>[^\s/$<{[][^\s/]{7,})(?=@)/gi,
54  // a HAR header or cookie value; it runs before Bearer so the whole value goes
55  /(?<head>"name"\s*:\s*"(?:authorization|proxy-authorization|cookie|set-cookie|x-api-key)"\s*,\s*"value"\s*:\s*")(?<value>(?:[^"\\]|\\.){8,})(?=")/gi,
56  // an Authorization header's credential, quoted or escaped in code and JSON; `Bearer YOUR_TOKEN` has no digit, so it
57  // stays, and "basic" or "bearer" in prose has no header name
58  /(?<head>\bauthorization[\\"'\x60]*\s*[:=]\s*[\\"'\x60]*(?:bearer|basic)\s+)(?<value>(?=[\w.~+/=-]*\d)(?=[\w.~+/=-]*[A-Za-z])[\w.~+/=-]{20,})/gi,
59  // a credential in a URL query
60  /(?<head>[?&](?:access_token|refresh_token|id_token|token|api_?key|client_secret|sig|signature|x-amz-signature|x-amz-security-token)=)(?<value>(?=[^\s&#"'<>$]*\d)[^\s&#"'<>$]{12,})/gi,
61]
62
63const tag = (rule: string) => `[secret-guard: ${rule}]`
64const isExample = (match: string) => /example|dummy|placeholder/i.test(match)
65// A file path is where a key lives, not the key (GOOGLE_APPLICATION_CREDENTIALS=/home/me/sa.json).
66const isPath = (value: string) => /^(?:~|\.{1,2})?\/\S*\.\w+$/.test(value)
67const hideable = (value: string) => !isExample(value) && !value.includes('[secret-guard') && !isPath(value)
68
69export const scrub = (text: string): { text: string; rules: string[] } => {
70  const rules: string[] = []
71  let out = text
72  for (const [rule, pattern] of SECRET_RULES) {
73    out = out.replace(pattern, match => {
74      // A cut-off private key runs to the end of the text, so the example check would read unrelated words.
75      if (rule !== 'private-key' && isExample(match)) return match
76      rules.push(rule)
77      return tag(rule)
78    })
79  }
80  for (const pattern of ASSIGNMENTS) {
81    out = out.replace(pattern, (match, ...args) => {
82      const { head, value } = args.at(-1) as { head: string; value: string }
83      if (!hideable(value)) return match
84      rules.push('secret-value')
85      return head + tag('secret-value')
86    })
87  }
88  return { text: out, rules }
89}
90
91// A string field named like a secret is hidden whole. Paging cursors are named like tokens but are not secrets.
92const SECRET_FIELD = /(?:secret|token|password|passwd|api_?key|access_?key|private_?key|credentials?|(?:^|[_-])auth|[_-]pwd)$/i
93const CURSOR_FIELD = /(?:page|pagination|next|sync|continuation)_?token$/i
94const secretField = (key: string, value: unknown) =>
95  typeof value === 'string' && SECRET_FIELD.test(key) && !CURSOR_FIELD.test(key) &&
96  /^[^\s$<{]{8,}$/.test(value) && !/^\d+$/.test(value) && hideable(value)
97
98// Rewrites every string inside a value, keeping its shape.
99export const scrubDeep = <T>(value: T, found: string[]): T => {
100  if (typeof value === 'string') {
101    const s = scrub(value)
102    found.push(...s.rules)
103    return s.text as T
104  }
105  if (Array.isArray(value)) return value.map(v => scrubDeep(v, found)) as T
106  if (value !== null && typeof value === 'object')
107    return Object.fromEntries(Object.entries(value).map(([k, v]) => {
108      if (!secretField(k, v)) return [k, scrubDeep(v, found)]
109      found.push('secret-value')
110      return [k, tag('secret-value')]
111    })) as T
112  return value
113}
114
115// When the scrub fails, a row keeps its blocks but none of its text. Only text and a tool result's content can be rewritten;
116// the engine puts back every other block.
117const WITHHELD = '[secret-guard: the check failed, so this text was withheld]'
118export const withheld = <T extends { type: string; [field: string]: unknown }>(content: T[]): T[] =>
119  content.map(block =>
120    block.type === 'text' ? { ...block, text: WITHHELD }
121    : block.type === 'tool_result' ? { ...block, content: typeof block.content === 'string' ? WITHHELD : [{ type: 'text', text: WITHHELD }] }
122    : block)
123
124// Browser profiles and password-manager data, whose paths can hold spaces (`Application Support`, `User Data`, `Login Data`,
125// `Group Containers`). Local State holds the key that decrypts Chromium's cookies and passwords.
126const SPACED_PATHS: readonly RegExp[] = [
127  /\/library\/(application support|cookies)\/.*\/(login data|cookies|cookies\.sqlite|key4\.db|logins\.json)$/,
128  /\/(google-chrome[^/]*|chromium|chrome|brave-browser|bravesoftware|microsoft-edge[^/]*|edge|firefox|mozilla)\/.*\/(login data[^/]*|(extension )?cookies(-journal)?|web data(-journal)?|local state|vpn tokens(-journal)?|cookies\.sqlite(-shm|-wal)?|key4\.db|logins(-backup)?\.(json|db)|formhistory\.sqlite)$/,
129  /\/(library\/application support|appdata\/roaming)\/bitwarden(\/|$)/, /\/appdata\/local\/1password\/data(\/|$)/,
130  /\/library\/group containers\/2bua8c4s2c\.com\.(1password|agilebits)(\/|$)/,
131]
132
133// Matched against the lowercased path with forward slashes and a leading slash.
134const SENSITIVE_PATHS: readonly RegExp[] = [
135  ...ENV_PATHS,
136  /\/\.(aws|gem|cargo|config\/git)\/credentials(\.toml)?$/, /\/credentials\.json$/, /\/service-account[^/]*\.json$/, /\/\.vault-token$/, /\/\.vault_pass$/,
137  // A bare `e.key` or `event.key` in a command is code reading a field (`store.get(e.key)`), not a key file; a path to one still counts.
138  /^(?!\/([a-z]|this|self|event|evt|entry|item|node|props|row|pair|kv|obj)\.key$).*\.(key|p12|pfx|jks|keystore|ppk)$/,
139  /\/id_(rsa|dsa|ecdsa|ed25519)(_sk)?$/,
140  /\/\.ssh\/(?!(known_hosts[^/]*|config|authorized_keys|[^/]+\.pub)$)[^/]+$/,
141  /\/\.(npmrc|pypirc|netrc|git-credentials|pgpass|my\.cnf|s3cfg)$/, /\/_netrc$/,
142  /\/\.(bash|zsh|sh|python|node_repl|psql|mysql|sqlite|rediscli)_history$/, /\/\.zhistory$/, /\/fish_history$/, /\/\.zsh_sessions\/[^/]+\.history(new)?$/,
143  /\/\.aws\/(sso|cli)\/cache\//, /\/\.config\/gcloud\/(credentials\.db|access_tokens\.db|application_default_credentials\.json|legacy_credentials\/)/,
144  /\/\.azure\/(accesstokens\.json|msal_token_cache[^/]*)$/, /\/\.kube\/config(-[^/]+)?$/, /\/\.docker\/config\.json$/,
145  /\/\.config\/gh\/hosts\.yml$/, /\/\.config\/glab-cli\/config\.yml$/, /\/\.config\/rclone\/rclone\.conf$/,
146  /\/\.gnupg\/[^/]+/, /\/\.terraform\.d\/credentials\.tfrc\.json$/,
147  /\.tfstate(\.backup)?$/, /\/terraform\.tfvars(\.json)?$/, /\.auto\.tfvars(\.json)?$/,
148  // Coding agents keep their logins in an auth.json under a dot folder (`~/.codex`, `~/.pi/agent`).
149  /\/\.claude\/\.credentials\.json$/, /\/\.[^/]+\/(?:[^/]+\/)*auth\.json$/, /\/\.gemini\/oauth_creds\.json$/,
150  /\/\.wrangler\/config\/default\.toml$/, /\/\.config\/github-copilot\/(apps|hosts)\.json$/,
151  /\/library\/keychains\//, ...SPACED_PATHS,
152  // A vault folder counts as a whole, so `tar` or `cp -r` of it is caught.
153  /\.kdbx$/, /\/(\.password-store|\.config\/(1password|bitwarden)|\.(lastpass|bitwarden)|\.var\/app\/com\.bitwarden\.desktop)(\/|$)/,
154  // Any `environ`: in `/proc/$(pgrep x)/environ` the `$(` splits the path, leaving `/environ`.
155  /\/environ$/, /\/run\/secrets\//, /\/etc\/shadow$/, /\/etc\/ssh\/ssh_host_[^/]+_key$/,
156]
157
158const withHome = (path: string, home: string) => path.replace(/^(~|\$HOME|\$\{HOME\})(?=\/|$)/, home)
159
160export const sensitivePath = (path: string, home: string, rules = SENSITIVE_PATHS): boolean => {
161  // `$APPDATA` and `$LOCALAPPDATA` (Git Bash) and their `%…%` forms (cmd) become Windows paths, so the AppData rules see them.
162  const expanded = withHome(path, home)
163    .replace(/^(?:\$\{?|%)(local)?appdata(?:\}|%)?(?=[\\/]|$)/i, (_, local) => `C:\\AppData\\${local ? 'Local' : 'Roaming'}`)
164  // A backslash separates directories only in a Windows path; elsewhere it is part of a search pattern (`grep '\.env'`).
165  const isWindowsPath = /^(?:[a-z]:\\|\\\\)/i.test(expanded)
166  const p = ('/' + (isWindowsPath ? expanded.replace(/\\/g, '/') : expanded)).replace(/\/+/g, '/').toLowerCase()
167  return rules.some(r => r.test(p))
168}
169
170const SECRET_NAME = String.raw`[A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CREDENTIAL)`
171
172const SECRET_COMMANDS: readonly RegExp[] = [
173  /^(printenv|compgen -v)\b/, /^(set|export|export -p)$/,
174  // declare and typeset print every variable when given no name, and a named one with -p (zsh's -m takes a name pattern).
175  /^(declare|typeset)(\s+-\S+)*$/, /^(declare|typeset)\b.*\s-[a-zA-Z]*[pm]/,
176  /^(sops\b.*\s(-d|--decrypt|decrypt)|age\b.*\s(-d|--decrypt)|gpg2?\b.*\s(-[a-zA-Z]*d|--decrypt|--export-secret-(sub)?keys))(\s|=|$)/,
177  /^ansible-vault (view|decrypt)\b/,
178  // pass prints an entry by default; listing, managing and copying to the clipboard do not.
179  /^pass(?=\s+\S)(?!\s+(ls|list|find|search|insert|add|rm|remove|delete|mv|rename|cp|copy|git|init|help|version|edit|--help|--version)(\s|$))(?!.*\s(-c\d*|--clip(=\d+)?)(\s|$))/,
180  /^gcloud secrets versions access\b/, /^az keyvault secret (show|download)\b/,
181  /^security (find-generic-password|find-internet-password|dump-keychain)\b/,
182  /^gh auth (token|status .*(-t|--show-token))\b/,
183  /^aws (configure (get|export-credentials)|sts get-session-token|secretsmanager get-secret-value|ssm get-parameters?\b.*--with-decryption)/,
184  /^gcloud auth (application-default )?print-(access|identity)-token\b/,
185  /^az account get-access-token\b/,
186  /^kubectl (config view .*--raw|get secrets?\b)/,
187  // credential.helper names the helper program, not a secret.
188  /^git (credential fill|config .*--get.*credential(?!\.helper\b))/,
189  /^(vault (read|kv get)|doppler secrets|heroku auth:token)\b/,
190  // Global options can come before the subcommand (`bw --session x get …`). A session key opens the whole vault, so the
191  // commands that print one count too.
192  /^bw\b(?=.*\s(get|export|receive|unlock)\b|.*\slist\s+items\b)/,
193  /^op\b(?=.*\s(read|inject|signin)\b|.*\sdocument\s+get\b|.*\sitems?\s+get\b.*\s--(reveal|otp|format)\b)/,
194  new RegExp(String.raw`^(echo|printf|print)\b.*\$\{?${SECRET_NAME}|<<<\s*["']?\$\{?${SECRET_NAME}`, 'i'),
195]
196
197// `env` with no command prints the environment, whatever options or assignments come with it.
198const ASSIGNMENT = String.raw`[A-Za-z_]\w*=(?:'[^']*'|"[^"]*"|[^\s'"])*`
199const ENV_ALONE = new RegExp(String.raw`^(?:${ASSIGNMENT}\s+)*(?:\S*\/)?env(?:\s+(?:-[uC]\s+\S+|-\S+|${ASSIGNMENT}))*$`)
200
201// A script that prints one secret-named variable (`node -p process.env.GITHUB_TOKEN`, `print(os.getenv("API_KEY"))`). The print
202// and the read sit in one statement; `!process.env.X` only tests it.
203const ENV_VALUE = String.raw`(?<!!)(?:process\.env(?:\.|\[\s*["'\x60])|os\.environ(?:\.get\(\s*|\[\s*)["']|os\.getenv\(\s*["']|ENV(?:\.fetch\(\s*|\[\s*)["'])${SECRET_NAME}(?:_\w*)?\b`
204const PRINTS_SECRET_VARIABLE = new RegExp(String.raw`\b(?:console\.\w+|print|puts|pp?|JSON\.stringify|json\.dumps|write)\b[^;&|\n]*?${ENV_VALUE}`, 'i')
205
206// Outside these, ls or stat print only a name; through a pipe, `$(…)` or a backtick that name reaches a command that reads it.
207const PASSES_OUTPUT = /(?<!\|)\|(?!\|)|\$\(|\x60/
208
209// The command a segment runs: without leading `NAME=value` assignments or `env` and its options, and without the directory of a
210// full path, so `AWS_PROFILE=x aws …`, `env -i printenv` and `/usr/bin/printenv` meet the rules above. Bare `env` stays.
211const commandHead = (segment: string) =>
212  segment.replace(/^(?:[A-Za-z_]\w*=(?:'[^']*'|"[^"]*"|\S)*\s+|env(?:\s+-[uC]\s+\S+|\s+-\S+)*\s+)+/, '').replace(/^\S*\/(?=\S)/, '')
213
214// Prose names files too (`copy .env.example, then`). Trailing punctuation after a name is dropped, but not after `.` or `/`,
215// so `~/.ssh/.` still names the folder.
216const withoutTrailingPunctuation = (word: string) => word.replace(/(?<=[^./])[.,;:!?)]+$/, '')
217
218// These touch a credential file without printing what is in it. ssh-keygen and ssh-add print a public key at most, except
219// `ssh-keygen -i`, which prints a converted private key.
220const NON_READING = new Set(['ls', 'stat', 'test', '[', 'touch', 'chmod', 'chown', 'rm', 'ssh-keygen', 'ssh-add'])
221
222// ssh, scp and sftp read the key given with -i or IdentityFile and print none of it, also in `GIT_SSH_COMMAND="ssh -i …"`. Only
223// their own options count, up to the destination: in `ssh host grep -i x .env` the -i is the remote grep's. The letters are the
224// options that take a value. Returns the indexes of the key words.
225const SSH_VALUE_OPTIONS = new Map([['ssh', 'BbcDEeFIiJLlmOoPpQRSWw'], ['scp', 'cDFiJloPSX'], ['sftp', 'BbcDFiJloPRSsX']])
226const sshKeys = (words: string[], commandIndex: number) => {
227  const keys = new Set<number>()
228  words.forEach((program, start) => {
229    const values = SSH_VALUE_OPTIONS.get(program.replace(/^\S*\//, ''))
230    if (!values || (start !== commandIndex && !(start < commandIndex && words[start - 1] === 'GIT_SSH_COMMAND'))) return
231    // The ssh in GIT_SSH_COMMAND ends where the real command starts.
232    const end = start === commandIndex ? words.length : commandIndex
233    for (let index = start + 1; index < end; index++) {
234      const word = words[index] ?? ''
235      if (!word.startsWith('-') || word === '--') break
236      const at = [...word].findIndex((letter, position) => position > 0 && values.includes(letter))
237      if (at === -1) continue
238      const value = at + 1 < word.length ? index : ++index
239      if (value >= end) break
240      if (word[at] === 'i') keys.add(value)
241      // pathWords splits `-o IdentityFile=key` at `=`, so an -o value is two words.
242      else if (word[at] === 'o' && /identityfile$/i.test(words[value] ?? '') && value + 1 < end) keys.add(++index)
243      else if (word[at] === 'o') index++
244    }
245  })
246  return keys
247}
248
249// A commit message, title or body names files without reading them, so its quoted text is not read. In git only -m takes
250// text (`-t` names a template file), and a message or body file (`-F`, `--body-file`) is still read.
251const QUOTED_TEXT = String.raw`("(?:[^"\\$\x60]|\\.)*"|'[^']*')`
252const GIT_MESSAGE = new RegExp(String.raw`(?<=\s(?:-[a-zA-Z]*m|--message)[\s=])${QUOTED_TEXT}`, 'g')
253const GH_TEXT = new RegExp(String.raw`(?<=\s(?:-[tbn]|--title|--body|--notes)[\s=])${QUOTED_TEXT}`, 'g')
254const withoutProse = (segment: string, head: string) =>
255  /^git (commit|tag|merge|stash)\b/.test(head) ? segment.replace(GIT_MESSAGE, '""')
256  : /^gh (issue|pr|release) /.test(head) ? segment.replace(GH_TEXT, '""')
257  : segment
258
259// The words a segment reads as files. Undefined when its command only names them; an ssh key or a cp or mv target is left out.
260const readWords = (seg: string, head: string, text: string, passesOutput: boolean): string[] | undefined => {
261  const words = pathWords(withoutJqFilter(text))
262  // The command comes from the head: pathWords splits `ls=1 cat .env` at `=`, so its first word is `ls`.
263  const cmd = head.split(/\s+/)[0] ?? ''
264  if (NON_READING.has(cmd) && !passesOutput && !(cmd === 'ssh-keygen' && /\s-[a-zA-Z]*i/.test(head))) return undefined
265  const keys = sshKeys(words, pathWords(seg).length - pathWords(head).length)
266  const read = words.filter((_, index) => !keys.has(index))
267  // cp and mv read only their sources: a credential file as the target is setup, as the source it could be copied out and read.
268  return cmd === 'cp' || cmd === 'mv' ? read.slice(1, -1) : read
269}
270
271export const secretCommand = (command: string, home: string): string | undefined => {
272  // A script that prints the whole environment is printenv by another name.
273  const runnable = withoutDataHeredocs(command)
274  if (/\b(console\.log|print|JSON\.stringify|json\.dumps)\(\s*(process\.env|os\.environ)\s*\)/.test(runnable)) return 'printing the whole environment prints secrets'
275  if (PRINTS_SECRET_VARIABLE.test(runnable)) return 'printing a secret-named variable prints its value'
276  const passesOutput = PASSES_OUTPUT.test(runnable)
277  for (const seg of commandSegments(runnable)) {
278    const head = commandHead(seg)
279    if (ENV_ALONE.test(seg)) return '`env` with no command prints the whole environment'
280    if (SECRET_COMMANDS.some(r => r.test(head))) return `\`${head.split(/\s+/).slice(0, 3).join(' ')}\` prints secrets`
281    if (jqReadsEnvironment(head)) return '`env` in a jq filter prints the whole environment'
282    const text = withoutProse(seg, head)
283    const sources = readWords(seg, head, text, passesOutput)
284    if (!sources) continue
285    const token = sources.find(w => sensitivePath(withoutTrailingPunctuation(w), home))
286    if (token) return `${token} is a credential file`
287    // A quoted sentence ends like many paths (`-m "~/.ssh/config: add a host"`), so a whole quoted word is held only to
288    // the rules for paths with spaces, the ones that need one.
289    const quotedPath = quotedWords(text).find(word => sensitivePath(word, home, SPACED_PATHS))
290    if (quotedPath) return `${quotedPath} is a credential file`
291  }
292  return undefined
293}
294
295const FILE_TOOLS: Record<string, string> = { Read: 'file_path', Edit: 'file_path', Write: 'file_path', NotebookEdit: 'notebook_path' }
296const LOCAL_WRITES = new Set(['Write', 'Edit', 'NotebookEdit'])
297
298const EMITTED_TAG = new RegExp(`\\[secret-guard${': '}(${[...SECRET_RULES.map(([rule]) => rule), 'secret-value'].join('|')})\\]`)
299
300// A tag in a file write, a shell command (`sed -i`, `>`) or an MCP call can replace the real value. Bash's description is only
301// shown, and an old_string holding a tag cannot match the file anyway, so checking every other field costs nothing.
302export const writesPlaceholder = (tool: string, args: Record<string, unknown>) =>
303  (LOCAL_WRITES.has(tool) || tool === 'Bash' || tool.startsWith('mcp__')) &&
304  EMITTED_TAG.test(JSON.stringify(tool === 'Bash' ? { ...args, description: undefined } : args))
305
306const READ_HINT = `Do not try another way to read it. To learn whether a .env-style file sets a variable, call ${ENV_CHECK_TOOL} (load it with ToolSearch first), which never shows the value. Otherwise use a template such as .env.example, or ask the user to run the step and share only what is safe.`
307const SEND_HINT = 'Take the secret out of the call. If the step needs it, ask the user to run it themselves.'
308const FAILED_HINT = 'Do not retry it the same way. Tell the user, who can run the step themselves.'
309const RAN_HINT = 'Do not run it again. Check its effect another way, or tell the user it may have run.'
310const WRITE_HINT = 'That would replace the real value with the tag. Change only what you need and leave hidden values untouched, or ask the user to make the change.'
311
312// Module state starts over on reload; the counts are this load's.
313const tally = { hidden: 0, blocked: 0, scrubOff: true }
314let home = ''
315
316export const statusText = (t: typeof tally) => {
317  const light = t.blocked > 0 ? '🔴' : t.hidden > 0 ? '🟡' : '🟢'
318  const parts = [t.hidden > 0 ? `${t.hidden} hidden` : 'none seen', t.blocked > 0 ? `${t.blocked} blocked` : '']
319  return `${light} secrets: ${parts.filter(Boolean).join(', ')}${t.scrubOff ? ' · env scrub off' : ''}`
320}
321
322function show($: EngineInterface) {
323  $.ui.status(statusText(tally))
324}
325
326// A link named like any file can lead to a credential file.
327const leadsToCredentialFile = async ($: EngineInterface, path: string) => {
328  const real = (await $.fs.stat(path, { resolve: true }).catch(() => undefined))?.realPath
329  return real !== undefined && sensitivePath(real, home)
330}
331
332const joinPath = (dir: string, path: string) => path.startsWith('/') || dir === '.' ? path : `${dir.replace(/\/$/, '')}/${path}`
333
334// The words outside quotes that a command reads, as paths: home spelled out, under a plain `cd` before them. A word with `$` or
335// a backtick is left out, an option too, and so is all that echo and printf get, since they open nothing.
336const fileWords = (command: string) => {
337  const runnable = withoutHeredocs(command)
338  const passesOutput = PASSES_OUTPUT.test(runnable)
339  const words: { word: string; path: string }[] = []
340  let dir = '.'
341  for (const seg of commandSegments(runnable)) {
342    const head = commandHead(seg)
343    const cd = /^cd\s+([^\s'"\\$`-][^\s'"\\$`]*)$/.exec(head)
344    if (cd) dir = joinPath(dir, withHome(cd[1] ?? '', home))
345    if (cd || /^(echo|printf)\b/.test(head)) continue
346    const unquoted = unquotedWords(seg)
347    let cmd: string | undefined = pathWords(head)[0]
348    for (const word of readWords(seg, head, withoutProse(seg, head), passesOutput) ?? []) {
349      const path = withHome(word, home)
350      if (word === cmd) cmd = undefined
351      else if (unquoted.has(word) && !word.startsWith('-') && !/[$`]/.test(path)) words.push({ word, path: joinPath(dir, path) })
352    }
353  }
354  return words
355}
356
357const FS_CALLS = 32
358const TOO_MANY = `the command needs more than ${FS_CALLS} file system checks`
359const TOO_MANY_HINT = 'Split it into smaller commands, or name the files instead of a pattern.'
360// What may let `*` match a dotfile: a command that can change shell options, whatever it sets (`shopt -s dotglob`, zsh's
361// `setopt globdots` or `set -4`, `eval`, a sourced file, or a command name that is not a plain word, after `then`, `{` or a
362// precommand such as `noglob` too), an option name anywhere, a GLOBIGNORE, or a zsh D qualifier such as `*(D)`. Names are matched
363// with quotes, backslashes and underscores taken out, since zsh ignores underscores and case in option names.
364const OPTION_COMMAND = new RegExp(String.raw`^(?:(?:if|then|else|elif|do|while|until|!|\{|noglob|nocorrect|-|command|exec|time|nohup|sudo)\s+)*`
365  + String.raw`(?:(?:set|setopt|unsetopt|shopt|emulate|eval|source|builtin)\b|\.\s|[$'"\\\x60])`)
366const DOT_GLOB = /dotglob|globdots|globignore|[*?\]]\([^()|]*D/i
367const dotGlob = (command: string) =>
368  DOT_GLOB.test(command.replace(/['"\\_]/g, '')) || commandSegments(command).some(seg => OPTION_COMMAND.test(commandHead(seg)))
369
370// After the name check: expands the globs and braces the shell would (`cat ~/.aw?/credentials`) and follows links (`cat notes`,
371// where notes leads to .env). The deny names the word typed, never where it leads.
372// ponytail: `**` is one level; past FS_CALLS calls it denies, a split command passes.
373const fileReason = async ($: EngineInterface, command: string): Promise<string | undefined> => {
374  const dots = dotGlob(command)
375  let calls = 0
376  const cache = <T>(map: Map<string, Promise<T | undefined>>, key: string, run: () => Promise<T>) => {
377    const hit = map.get(key)
378    if (hit) return hit
379    if (++calls > FS_CALLS) throw TOO_MANY
380    const made = run().catch(() => undefined)
381    map.set(key, made)
382    return made
383  }
384  const lists = new Map<string, Promise<FsEntry[] | undefined>>()
385  const reals = new Map<string, Promise<string | undefined>>()
386  const list = (dir: string) => cache(lists, dir, () => $.fs.list(dir))
387  const real = (path: string) => cache(reals, path, async () => (await $.fs.stat(path, { resolve: true })).realPath)
388
389  // Walks a glob a folder at a time. A match keeps its entry when the last part was a pattern.
390  const matches = async (pattern: string) => {
391    const parts = pattern.split('/')
392    const first = parts.findIndex(isGlob)
393    let found: { path: string; dir?: string; entry?: FsEntry }[] = [{ path: parts.slice(0, first).join('/') || (pattern.startsWith('/') ? '/' : '.') }]
394    for (const [at, part] of parts.entries()) {
395      if (at < first || part === '') continue
396      const re = isGlob(part) ? globPart(part, dots) : undefined
397      const isLast = at === parts.length - 1
398      const next: typeof found = []
399      for (const { path } of found) {
400        if (!re) next.push({ path: joinPath(path, part) })
401        else for (const entry of (await list(path)) ?? [])
402          if (re.test(entry.name) && (isLast || entry.kind === 'dir' || entry.isLink)) next.push({ path: joinPath(path, entry.name), dir: path, entry })
403      }
404      found = next
405    }
406    return found
407  }
408
409  try {
410    for (const { word, path } of fileWords(command)) {
411      const paths = braceWords(path)
412      if (!paths) return TOO_MANY
413      for (const each of paths) {
414        const isPattern = each !== path || isGlob(each)
415        if (sensitivePath(each, home)) return `${word} ${isPattern ? 'matches' : 'is'} a credential file`
416        for (const { path: found, dir, entry } of isGlob(each) ? await matches(each) : [{ path: each }]) {
417          if (sensitivePath(found, home)) return `${word} matches a credential file`
418          // A plain entry's own path is its folder's, so one stat per folder covers every match in it.
419          const base = entry && !entry.isLink && dir ? await real(dir) : undefined
420          const to = base !== undefined && entry ? joinPath(base, entry.name) : await real(found)
421          if (to !== undefined && sensitivePath(to, home)) return `${word} leads to a credential file`
422        }
423      }
424    }
425  } catch (error) {
426    if (error === TOO_MANY) return TOO_MANY
427    throw error
428  }
429  return undefined
430}
431
432export const register: Register = on => {
433  on('session.start', async ($, e, next) => {
434    home = (await $.env.get('HOME')) ?? ''
435    tally.scrubOff = (await $.env.get('CLAUDE_CODE_SUBPROCESS_ENV_SCRUB')) !== '1'
436    show($)
437    await $.tool.register(envCheckSpec)
438    return next(e)
439  })
440
441  on('tool.call', async ($, e, next) => {
442    const args = e as Record<string, unknown>
443    const deny = (reason: string, hint = READ_HINT) => {
444      tally.blocked++
445      show($)
446      return { deny: `secret-guard: ${reason}. ${hint}` }
447    }
448
449    const pathKey = FILE_TOOLS[e.tool]
450    const path = pathKey ? args[pathKey] : undefined
451    if (typeof path === 'string') {
452      if (sensitivePath(path, home)) return deny(`${path} is a credential file`)
453      if (await leadsToCredentialFile($, path)) return deny(`${path} leads to a credential file`)
454    }
455    if (e.tool === 'Bash' && typeof args.command === 'string') {
456      const reason = secretCommand(args.command, home) ?? await fileReason($, args.command)
457      if (reason) return deny(reason, reason === TOO_MANY ? TOO_MANY_HINT : READ_HINT)
458    }
459    if (!LOCAL_WRITES.has(e.tool) && scrub(JSON.stringify(args)).rules.length > 0) return deny('this call would send a secret', SEND_HINT)
460    if (writesPlaceholder(e.tool, args)) return deny('this call would write a hidden-value tag', WRITE_HINT)
461
462    const ran = await next(e)
463    if (ran.deny !== undefined || ran.isError) return ran
464    const found: string[] = []
465    const result = scrubDeep(ran.result, found)
466    if (found.length === 0) return ran
467    tally.hidden += found.length
468    show($)
469    return { result, context: ran.context }
470  }).catch(($, e, next) => {
471    // A failed hook is skipped, so the tool would run, or its raw result would stand. Refuse in both cases: replaying `next`
472    // here would hand back the unscrubbed result. The handler has one second, so it does nothing else.
473    tally.blocked++
474    if (next.error.kind !== 're-entry') show($)
475    // Once `next` was called the tool may have run (a push, a write), and a refusal undoes nothing, so the model must not
476    // read it as "did not run".
477    return next.called
478      ? { deny: `secret-guard: the check failed after the call started. It may have run; its output was withheld. ${RAN_HINT}` }
479      : { deny: `secret-guard: the check failed, so the call was refused before it ran. ${FAILED_HINT}` }
480  })
481
482  // Added after the hook above, so its argument check and result scrub run around this one.
483  on('tool.call', { tool: ENV_CHECK_TOOL }, ($, e) => envCheck($, home, e as Record<string, unknown>))
484    .catch(() => ({ isError: true as const, result: 'env_check failed. Ask the user to check the file.' }))
485
486  // A file added with `@` raises no tool.call. Its deny reason reaches only the debug log, so a toast tells the user.
487  on('prompt.mention', async ($, e, next) => {
488    if (!sensitivePath(e.path, home) && !(await leadsToCredentialFile($, e.path))) return next(e)
489    tally.blocked++
490    show($)
491    $.ui.toast(`@${e.mention} was not attached, because it is a credential file.`)
492    return { deny: 'secret-guard: a credential file' }
493  }).catch(($, e, next) => next.called ? next(e) : { deny: 'secret-guard: the check failed' })
494
495  // Every other row: prompts typed or pasted, model output, attachments, compaction summaries, error results.
496  // A seated cc-plugin-sec-default sends attachments, hook context, compaction summaries and Skill messages past this hook.
497  on('session.append', ($, e, next) => {
498    const found: string[] = []
499    const content = scrubDeep(e.message.content, found)
500    if (found.length === 0) return next(e)
501    tally.hidden += found.length
502    show($)
503    return next({ ...e, message: { ...e.message, content } })
504  }).catch(($, e, next) => next.called ? next(e) : next({ ...e, message: { ...e.message, content: withheld(e.message.content) } }))
505}
506
hooks/env-check.ts 115 lines
1import type { EngineInterface, ToolSpec } from 'claude-code'
2
3export const ENV_CHECK_TOOL = 'mcp__secret-guard__env_check'
4
5export const envCheckSpec: ToolSpec = {
6  name: 'env_check',
7  description: 'Says whether a .env-style file sets each variable (set, empty or missing) and whether its template lists it. ' +
8    'It never shows a value or its length. Use it instead of reading the file, which secret-guard blocks.',
9  inputSchema: {
10    type: 'object',
11    properties: {
12      names: { type: 'array', items: { type: 'string' }, description: 'The variables to check. Leave out to list the template\'s names and the file\'s own.' },
13      file: { type: 'string', description: 'The env file, .env by default: .env, .env.*, *.env, .dev.vars, .envrc or .flaskenv.' },
14      template: { type: 'string', description: 'The template to compare with. By default <file>.example, .sample or .template, then .env.example beside the file.' },
15    },
16    additionalProperties: false,
17  },
18}
19
20// secret-guard's env file rules, matched against the lowercased path with forward slashes and a leading slash.
21export const ENV_PATHS: readonly RegExp[] = [
22  // `name.env` files, but not the code spellings a search names (`grep -rn process.env src`).
23  /\/\.env$/, /\/\.env\.(?!(example|sample|template|defaults|dist)$)[^/]+$/, /\/(?!(process|import\.meta|c)\.env$)[^/\\]+\.env$/,
24  /\/\.envrc$/, /\/\.dev\.vars(\.[^/]+)?$/, /\/\.flaskenv$/,
25]
26
27const baseName = (path: string) => path.split(/[\\/]/).pop() ?? path
28export const isEnvFile = (path: string) => ENV_PATHS.some(r => r.test('/' + baseName(path).toLowerCase()))
29// A template such as .envrc.example is judged by the file it is named for.
30const isEnvTemplate = (path: string) => isEnvFile(path.replace(/\.(?:example|sample|template|defaults|dist)$/i, ''))
31
32// Dots and dashes are allowed in a name, so a quoted key after `my.key=` starts the skip below. The space after `=` is kept:
33// `X=#v` has a value, while in `X= #v` the `#` starts a comment.
34const ASSIGNMENT = /^\s*(?:export\s+)?([A-Za-z_][\w.-]*)\s*=(\s*)(.*)$/
35
36// In double quotes a backslash escapes the next character.
37const closingQuote = (text: string, quote: string) => {
38  for (let i = 0; i < text.length; i++) {
39    if (quote === '"' && text[i] === '\\') i++
40    else if (text[i] === quote) return i
41  }
42  return -1
43}
44
45// Each assigned name and whether it has a value; a later line wins. A quoted value can run over several lines (a PEM key):
46// those lines are skipped, so a key's base64 never reads as a name.
47export const envNames = (text: string): Map<string, 'set' | 'empty'> => {
48  const names = new Map<string, 'set' | 'empty'>()
49  const lines = text.split(/\r?\n/)
50  for (let i = 0; i < lines.length; i++) {
51    const m = ASSIGNMENT.exec(lines[i]!)
52    if (!m) continue
53    const name = m[1]!, gap = m[2]!, value = m[3]!
54    const quote = value[0]
55    if (quote === '"' || quote === "'" || quote === '`') {
56      const end = closingQuote(value.slice(1), quote)
57      if (end < 0) while (++i < lines.length && closingQuote(lines[i]!, quote) < 0);
58      names.set(name, end >= 0 && value.slice(1, end + 1).trim() === '' ? 'empty' : 'set')
59    } else names.set(name, (gap + value).replace(/\s#.*$/, '').trim() === '' ? 'empty' : 'set')
60  }
61  return names
62}
63
64// Unasked, names are listed only in capitals, the template's too: a key pasted unquoted over several lines can leave a
65// base64 line that parses as a mixed-case name.
66const LISTED_NAME = /^[A-Z_][A-Z0-9_]*$/
67
68export const SET_NOTE = '"set" means only that the line has a value, which can be a placeholder copied from the template. ' +
69  'env_check cannot tell whether the value is correct.'
70
71export const envReport = (fileName: string, text: string, template?: { name: string; text: string }, asked?: readonly string[]) => {
72  const values = envNames(text)
73  const listed = template && envNames(template.text)
74  const names = asked?.length ? asked : [...new Set([...(listed?.keys() ?? []), ...values.keys()])].filter(n => LISTED_NAME.test(n))
75  const head = `${fileName}, ${template ? `compared with ${template.name}` : 'no template found'}`
76  const rows = names.map(n => `${n}: ${values.get(n) ?? 'missing'}${listed && !listed.has(n) ? ', not in template' : ''}`)
77  const note = names.some(n => values.get(n) === 'set') ? [SET_NOTE] : []
78  return [head, ...(rows.length > 0 ? rows : ['no variables']), ...note].join('\n')
79}
80
81const ONLY_ENV_FILES = 'env_check reads only .env-style files: .env, .env.*, *.env, .dev.vars, .envrc and .flaskenv. ' +
82  'A template such as .env.example goes in template.'
83
84export async function envCheck($: EngineInterface, home: string, args: Record<string, unknown>) {
85  // Paths stay as typed in every result, so a `~` path does not show the home folder.
86  const expand = (path: string) => path.replace(/^~(?=\/|$)/, home)
87  const file = typeof args.file === 'string' ? args.file : '.env'
88  const given = typeof args.template === 'string' ? args.template : undefined
89  const asked = Array.isArray(args.names) ? args.names.filter((n): n is string => typeof n === 'string') : undefined
90  // Any other file, such as a key, could parse as names. The name is judged before the file is looked for, so the tool
91  // does not tell whether some other file exists.
92  if (!isEnvFile(file) || (given !== undefined && !isEnvTemplate(given))) return { isError: true as const, result: ONLY_ENV_FILES }
93  if (!(await $.fs.exists(expand(file)))) return { result: `${file} does not exist` }
94  const dir = file.slice(0, file.length - baseName(file).length)
95  const candidates = given !== undefined ? [given] : [`${file}.example`, `${file}.sample`, `${file}.template`, `${dir}.env.example`]
96  let template: string | undefined
97  for (const c of candidates) if (template === undefined && (await $.fs.exists(expand(c)))) template = c
98  if (given !== undefined && template === undefined) return { isError: true as const, result: `${given} does not exist` }
99  // A link is judged by the file it leads to. Without that real path the file is not read.
100  for (const [path, isAllowed] of [[file, isEnvFile], [template, isEnvTemplate]] as const) {
101    if (path === undefined) continue
102    const real = (await $.fs.stat(expand(path), { resolve: true }).catch(() => undefined))?.realPath
103    if (real === undefined) return { isError: true as const, result: `env_check could not read ${path}` }
104    if (!isAllowed(real)) return { isError: true as const, result: ONLY_ENV_FILES }
105  }
106  try {
107    const text = await $.fs.read(expand(file))
108    const shape = template === undefined ? undefined : { name: template, text: await $.fs.read(expand(template)) }
109    return { result: envReport(file, text, shape, asked) }
110  } catch {
111    // The engine's error text is not passed on.
112    return { isError: true as const, result: `env_check could not read ${file}${template ? ` or ${template}` : ''}` }
113  }
114}
115
hooks/shell-read.ts 276 lines
1// ponytail: split on shell operators outside quotes; sh -c, eval, quoted globs, scripts the model writes and a quote left open across
2// lines pass through. Output scrubbing is the net for those.
3// A name right before `(` is a function call (`mock.env(on)`), not a file. Quoted text stays one segment, so `grep "(export )?"` is not
4// read as `export`; `$(` and backticks still run a command inside double quotes, so they split there too.
5export const commandSegments = (command: string): string[] => {
6  const text = command.replace(/[\w.-]+\(/g, '(')
7  const parts: string[] = []
8  const resumeQuotes: ('"' | null)[] = []
9  let current = ''
10  let quote: '"' | "'" | "$'" | null = null
11  let isBacktickInQuote = false
12  const endSegment = () => {
13    parts.push(current)
14    current = ''
15  }
16  for (let index = 0; index < text.length; index++) {
17    const char = text[index] ?? ''
18    const pair = text.slice(index, index + 2)
19    if (quote === "'") {
20      if (char === "'") quote = null
21      current += char
22      continue
23    }
24    // In `$'…'` a backslash escapes the next character, so `$'it\'s'` closes on its last quote.
25    if (quote === "$'") {
26      if (char === "'") quote = null
27      current += char === '\\' ? pair : char
28      if (char === '\\') index++
29      continue
30    }
31    if (char === '\\') {
32      // A backslash-newline joins two lines into one, as bash does.
33      if (pair !== '\\\n') current += pair
34      index++
35      continue
36    }
37    if (quote === '"') {
38      if (pair === '$(') {
39        endSegment()
40        resumeQuotes.push('"')
41        quote = null
42        index++
43      } else if (char === '`') {
44        endSegment()
45        isBacktickInQuote = true
46        quote = null
47      } else {
48        if (char === '"') quote = null
49        current += char
50      }
51      continue
52    }
53    if (char === '#' && /^$|[\s;&|()`<>]/.test(text[index - 1] ?? '')) {
54      // A comment runs to the end of the line, so a quote in it (`# don't`) opens nothing.
55      const end = text.indexOf('\n', index)
56      const stop = end === -1 ? text.length : end
57      current += text.slice(index, stop)
58      index = stop - 1
59    } else if (pair === "$'") {
60      quote = "$'"
61      current += pair
62      index++
63    } else if (char === "'" || char === '"') {
64      quote = char
65      current += char
66    } else if (pair === '&&' || pair === '||') {
67      endSegment()
68      index++
69    } else if (pair === '$(' || char === '(') {
70      endSegment()
71      resumeQuotes.push(null)
72      if (pair === '$(') index++
73    } else if (char === ')') {
74      endSegment()
75      quote = resumeQuotes.pop() ?? null
76    } else if (char === '`') {
77      endSegment()
78      if (isBacktickInQuote) quote = '"'
79      isBacktickInQuote = false
80    } else if (';|\n'.includes(char)) {
81      endSegment()
82    } else {
83      current += char
84    }
85  }
86  endSegment()
87  return parts.map(part => part.trim().replace(/^(sudo|command|exec|time|nohup)\s+/, '')).filter(Boolean)
88}
89
90// `cat` or `tee` writing a heredoc out is data, but only with a quoted delimiter: in a `<<EOF` body `$(…)` and backticks still run.
91// The opener line holds that command alone, after plain `&&` steps at most, so in `echo tee; python3 - <<'EOF'` or
92// `cat <<'EOF' | sh` the body is still read as commands. A step or a file name may be quoted (`cd "/my dir"`, `"$DIR/a.md"`), but
93// not hold `$(` or a backtick, and a trailing `# comment` is allowed. `\x60` is a backtick, which String.raw cannot hold.
94const QUOTED = String.raw`'[^']*'|"(?:[^"\x60\\$]|\$(?!\())*"`
95const AND_STEP = String.raw`(?:[^<>|;&'"\x60\\()#]|${QUOTED})*`
96const FILE_NAME = String.raw`(?:[^\s<>|;&'"\x60\\()#]|${QUOTED})+`
97const DATA_HEREDOC = new RegExp(
98  String.raw`^(?:${AND_STEP}&&)*\s*(?:cat(?:\s*>>?\s*${FILE_NAME})?|tee\s+(?:-a\s+)?${FILE_NAME})\s*<<-?\s*(['"])([\w.-]+)\1(?:\s*>>?\s*${FILE_NAME})?(?:\s+#.*)?\s*$`,
99)
100const HEREDOC = /(?<!<)<<(?!<)-?\s*\\?(['"]?)([\w.-]+)\1/g
101// ponytail: counts brackets without reading quotes, so a stray `)` in an earlier quote can hide a group; a parser if that matters.
102const isGrouped = (text: string) => (text.match(/[({]/g)?.length ?? 0) > (text.match(/[)}]/g)?.length ?? 0)
103
104// Drops data heredoc bodies. Any other body is kept, and no line in it opens a data heredoc. Inside an open `{`, `(`, `<(` or `$(` the
105// output of `cat` can go to bash (`{ cat <<'EOF' … } | bash`), so a body there is not data.
106export const withoutDataHeredocs = (command: string): string => {
107  const kept: string[] = []
108  let endings: string[] = []
109  let isDataBody = false
110  for (const line of command.split('\n')) {
111    if (endings.length > 0) {
112      if (line.trim() === endings[0]) endings.shift()
113      else if (isDataBody) continue
114      // A body is not read with shell quotes: in `<<EOF` they are plain text around a running `$(…)`, and python's `'''it's'''`
115      // is an odd count. So quotes and `#` there must not hide what follows.
116      kept.push(line.replace(/['"#]/g, ' '))
117      continue
118    }
119    // After a trailing `\` the line continues the one before it, so its heredoc can belong to another command.
120    const opener = kept.at(-1)?.endsWith('\\') || isGrouped([...kept, line].join('\n')) ? null : DATA_HEREDOC.exec(line)
121    isDataBody = opener !== null
122    endings = opener ? [opener[2] ?? ''] : [...line.matchAll(HEREDOC)].map(match => match[2] ?? '')
123    kept.push(line)
124  }
125  return kept.join('\n')
126}
127
128// Drops every heredoc body, for the file system check: a body is data or a script, not paths to look up.
129export const withoutHeredocs = (command: string): string => {
130  const kept: string[] = []
131  let endings: string[] = []
132  for (const line of command.split('\n')) {
133    if (endings.length > 0) {
134      if (line.trim() === endings[0]) endings.shift()
135      continue
136    }
137    endings = [...line.matchAll(HEREDOC)].map(match => match[2] ?? '')
138    kept.push(line)
139  }
140  return kept.join('\n')
141}
142
143// Splits a segment into the words the path check reads. Whitespace, `<`, `>` and `=` split even inside quotes,
144// because a quoted string can hold a command (`bash -c "cat .env"`). Quotes are removed. A backslash outside
145// quotes escapes the next character, so `\.env` is `.env`; inside single quotes it stays, so `'\.env'` is a pattern.
146export const pathWords = (segment: string): string[] => {
147  const words: string[] = []
148  let current = ''
149  let quote: '"' | "'" | null = null
150  for (let index = 0; index < segment.length; index++) {
151    const char = segment[index] ?? ''
152    const next = segment[index + 1] ?? ''
153    if (/[\s<>=]/.test(char)) {
154      if (current) words.push(current)
155      current = ''
156    } else if (quote === null && (char === "'" || char === '"')) {
157      quote = char
158    } else if (char === quote) {
159      quote = null
160    } else if (char === '\\' && (quote === null || (quote === '"' && '$`"\\'.includes(next)))) {
161      current += next
162      index++
163    } else {
164      current += char
165    }
166  }
167  if (current) words.push(current)
168  return words
169}
170
171// Splits a segment into shell words, keeping their quotes. An operator such as `<`, `2>`, `<>` or `&` is a token of its own,
172// as it is in bash. Undefined when a quote is left open.
173const SHELL_TOKEN = /\d*[<>&|;()]+|(?:[^\s'"\\<>&|;()]|\\[\s\S]|'[^']*'|"(?:[^"\\]|\\[\s\S])*")+/g
174const OPERATOR = /^\d*[<>&|;()]/
175const shellTokens = (segment: string): string[] | undefined =>
176  segment.replace(SHELL_TOKEN, '').trim() === '' ? (segment.match(SHELL_TOKEN) ?? []) : undefined
177
178// The jq options that take values, and how many.
179const JQ_OPTION_VALUES = new Map([['--indent', 1], ['-L', 1], ['--arg', 2], ['--argjson', 2], ['--slurpfile', 2], ['--rawfile', 2]])
180
181// jq reads its first argument that is not an option as a filter. None is found with `-f` (the filter comes from a file), or
182// after an operator other than a redirect, such as a lone `&` that starts a second command.
183const jqFilter = (segment: string): { tokens: string[]; index: number } | undefined => {
184  if (!/^(\S*\/)?jq\s/.test(segment)) return undefined
185  const tokens = shellTokens(segment)
186  if (!tokens) return undefined
187  let isOptionsEnd = false
188  for (let index = 1; index < tokens.length; index++) {
189    const token = tokens[index] ?? ''
190    if (OPERATOR.test(token)) {
191      if (!/[<>]/.test(token)) return undefined
192      index++
193    } else if (!isOptionsEnd && token.startsWith('-')) {
194      if (token === '--') isOptionsEnd = true
195      else if (token === '--from-file' || /^-[a-zA-Z]*f/.test(token)) return undefined
196      else index += JQ_OPTION_VALUES.get(token) ?? 0
197    } else {
198      return { tokens, index }
199    }
200  }
201  return undefined
202}
203
204// A jq filter names a key, not a file (`jq '.env.PATH' settings.json`), so it is dropped and every other word is still read:
205// files, option values and redirect targets. A filter that imports a module reads a JSON file, so it is kept.
206export const withoutJqFilter = (segment: string): string => {
207  const filter = jqFilter(segment)
208  if (!filter || /\b(import|include)\b/.test(filter.tokens[filter.index] ?? '')) return segment
209  return filter.tokens.filter((_, index) => index !== filter.index).join(' ')
210}
211
212// jq's `env` and `$ENV` hold the whole environment. A key (`.env`) or a string (`"env"`) of that name is not the builtin.
213export const jqReadsEnvironment = (segment: string): boolean => {
214  const filter = jqFilter(segment)
215  const text = filter?.tokens[filter.index]?.replace(QUOTED_PART, (_, single, double) => single ?? double) ?? ''
216  return /(?<![\w.$"])env\b|\$ENV\b/.test(text)
217}
218
219const SHELL_WORD = /(?:[^\s'"\\]|\\[\s\S]|'[^']*'|"(?:[^"\\]|\\[\s\S])*")+/g
220const QUOTED_PART = /'([^']*)'|"((?:[^"\\]|\\[\s\S])*)"/g
221
222// The shell words whose quotes hold whitespace, quotes removed, as one string each: `"User Data/Default/Login Data"` is
223// one path, which a split on whitespace breaks up. A quoted command (`bash -c "cat 'a b/Login Data'"`) is read again for
224// its own words.
225export const quotedWords = (segment: string): string[] => {
226  const words: string[] = []
227  for (const token of segment.match(SHELL_WORD) ?? []) {
228    if (!/['"]/.test(token)) continue
229    const word = token.replace(QUOTED_PART, (_, single, double) => single ?? double)
230    if (/\s/.test(word)) words.push(word)
231    for (const [, single, double] of token.matchAll(QUOTED_PART)) words.push(...quotedWords(single ?? double ?? ''))
232  }
233  return words
234}
235
236// The words of a segment with no quote or backslash, split as pathWords splits them. Only in these does the shell expand
237// `*`, `?`, `[` and `{a,b}`.
238export const unquotedWords = (segment: string): Set<string> =>
239  new Set((segment.match(SHELL_WORD) ?? []).filter(token => !/['"\\]/.test(token)).flatMap(token => token.split(/[<>=]/)))
240
241export const isGlob = (word: string) => /[*?[]/.test(word)
242
243// `{a,b}` gives a word per choice, nested too, as bash does; `{1..3}` and a lone brace stay. Undefined past 64 words.
244export const braceWords = (word: string): string[] | undefined => {
245  const words: string[] = []
246  const expand = (text: string): boolean => {
247    for (let start = text.indexOf('{'); start !== -1; start = text.indexOf('{', start + 1)) {
248      const cuts = [start]
249      let depth = 0
250      for (let index = start; index < text.length; index++) {
251        if (text[index] === '{') depth++
252        else if (text[index] === ',' && depth === 1) cuts.push(index)
253        else if (text[index] === '}' && --depth === 0) {
254          if (cuts.length === 1) break
255          const choices = [...cuts, index].slice(1).map((cut, at) => text.slice((cuts[at] ?? 0) + 1, cut))
256          return choices.every(choice => expand(text.slice(0, start) + choice + text.slice(index + 1)))
257        }
258      }
259    }
260    words.push(text)
261    return words.length <= 64
262  }
263  return expand(word) ? words : undefined
264}
265
266// One path part of a glob as a regex. Like the shell, only a part that starts with a dot matches a dotfile, unless `dots` says
267// dotglob is on. `**` is `*`. Undefined for a `[` left open, which the shell reads as itself.
268export const globPart = (part: string, dots = false): RegExp | undefined => {
269  const source = part.replace(/[.+^$(){}|\\]/g, '\\$&').replace(/\*+/g, '.*').replace(/\?/g, '.').replace(/\[!/g, '[^')
270  try {
271    return new RegExp(`^${dots || part.startsWith('.') ? '' : '(?!\\.)'}${source}$`)
272  } catch {
273    return undefined
274  }
275}
276