SLOPSHOPPER

redact

Secrets found by betterleaks reach the model as ‹secret:…› tokens; Write/Edit restore them, other tools refuse them

newguardtoaststatuspromptprocess
★ 2v0.1.1no licenseupdated 2026-10-08schreibse/claude-code-mods/redact
A shopper browsing a rack in a slop shop
README

claude-code-mods

Personal Claude Code mods: plugins of function hooks that restyle the transcript, add rows around the prompt and react to tool calls. Built and used on Claude Code 2.1.287+, Linux.

Mods

ModWhat it doesCommandsNeeds
quiet-bashOne-line tool rows (✓ <description>, red ✗ exit N on failure, +N −M on edits, duration for calls ≥10 s). Hides every tool's result block (Bash output, Edit diffs, WebFetch, MCP and Agent results; interactive tools, SendUserFile and image Reads keep theirs), finished read-only rows (Read/Grep/Glob, and calls the engine ran read-only like ls or git status, and every Claude in Chrome step but navigate), collapsed tool groups unless one failed, and timed-out GitLab pipeline-wait notices. Inline PNG thumbnails under rows that read, sent or wrote a PNG (at most 3 written ones per call), relative paths included; a group holding a thumbnail stays open, even under /quiet/quiet brings it all back; /thumb [big] <path> shows a PNG (relative to the session's directory) as thumb #N: <path>ImageMagick (magick) for thumbnails; a terminal with kitty graphics (see herdr)
quiet-spinnerPlain spinner words (thinking, writing, running, waiting, preparing) and Took 1m 4s instead of the whimsical ones––
usage-percentRow under the prompt: `ctx 34% \5h 41% \wk 86%, yellow from 80 %, red from 95 %. In Nx repos also memory in the middle (claude.slice usage + app.slice pressure, yellow from 20 %, red from 50 %) and on the right the session's own nx serve projects (▶ admin api; a bare nx serve or run-many -t serve shows ▶ serve) and the branch's pipeline (ci ⏳ test, ⏸` when it waits on a manual job or an approval; none for Azure remotes)–gh / glab logged in for the pipeline; systemd claude.slice for memory
reminder-logTallies the reminders Claude Code injects for the model, per session; drops the token counter and repeated commit attribution blocks (sent again after a compaction)/reminders prints the tally of the last 30 days–
mr-bannerColored card with a link under each MR/PR created, merged, approved or reviewed–GitLab MCP server named gitlab, or glab / gh
coderabbit-bandBand above the prompt with the open CodeRabbit threads (by severity) and nitpicks of the current branch's GitLab MR, with a link. Shows only when something is open/coderabbit hides it until the counts changeglab logged in; GitLab remote
redactSecrets in prompts and tool output reach the model as ‹secret:…› tokens; only Write/Edit turn them back into the real value. See redact–betterleaks on PATH
mem-guardBash commands that run Node tools go into a memory-capped claude-cmd.slice scope. Refused, with the fix in the message: nx affected/run-many without --parallel=1, a pnpm script that has a :lite twin, jest without a worker cap (--maxWorkers=N, -w N or --runInBand; a percentage doesn't count), pkill -f/pgrep -f with an unbracketed pattern, ci:local, heavy runs and dev-server starts while the slice is above 75 % or under pressure, a third heavy command or a third dev server at once, and writes by a check-runner subagent. See mem-guard–Linux with systemd: a user claude-cmd.slice, ps; see mem-guard
handoverSkill plus mod: the handover skill writes a one-sentence handover for a cold session to ~/.claude/handover.md; the mod files it per session under ~/.claude/handovers/<session id>.md, so parallel sessions in one repo never overwrite each other. A band above the prompt shows it; after /clear that session's sentence waits in the prompt (Tab takes it) and the next prompt spends it. A new terminal suggests nothing but lists the repo's open sentences (newest first, 14 days)/handover-copy copies it and hides the band; /handover lists, /handover N puts one in the prompt–
herdr-notifyGNOME popup when Claude waits for a permission, an answer or a new prompt (a Notification hook, not a plugin). Skipped while that pane is the focused one in herdr. Clicking it raises Ghostty and focuses that session's herdr pane. Hook: `"Notification": [{"matcher": "permission_prompt\idle_prompt\elicitation_dialog", "hooks": [{"type": "command", "command": "bash \"$HOME/.claude/skills/herdr-notify/notify.sh\""}]}]`–herdr, Ghostty, notify-send, jq
stack-downOn /clear and exit (also logout, a finished -p run, SIGINT/SIGTERM/SIGHUP), stops what the session left running in its repo: the nx processes it started (with their workers), and the repo's Docker Compose projects (compose down, volumes kept) unless another Claude session works in the same repo. Only for a session at a repo's top level (git rev-parse --show-toplevel); one started above the repos, such as ~/Dev, stops nothing–docker compose, git
review-walkSkill plus mod: /review-walk takes the findings of the reviews already run in the conversation (/code-review, a repo's own review skill, CodeRabbit threads, MR comments), merges and ranks them, and asks fix / issue / skip one finding at a time; fixes wait until every finding is decided. The mod puts Finding N/M, a progress bar and the decisions so far over each question, and a band above the prompt between them. Decisions you authorised up front ("apply every Fix") are recorded through its ReviewWalkDecide tool instead of a question. The walk starts only after the skill runs, so a review on its own draws no band/review-walkA review run first: it walks findings, it never reviews. Any review skill or source works

The model sees exactly what it would without them: the mods change what is drawn, except reminder-log, which drops two kinds of injected reminders, redact, which hides secrets, mem-guard, which runs Node commands inside a systemd scope and refuses some with a mem-guard: … error, and stack-down, which stops the session's own servers and, when no other session is in the repo, its Compose stacks when the session ends.

Three mods call out on their own:

  • mr-banner, when a GitLab MCP note or approval answers without the MR's link, calls get_merge_request on the gitlab MCP server for the link and title. gh/glab commands cost nothing extra.
  • coderabbit-band polls glab for GitLab origin remotes: a 60 s timer checks the branch, and a fetch (glab mr view plus all pages of the MR's discussions) runs every minute for 15 min after a git push, every 5 min while the band shows something, every 15 min otherwise, and once 5 s after a thread is resolved.
  • usage-percent, in Nx repos, polls every 10 s: ps and pwdx for nx serve processes, and docker inspect once per container a server runs in, to read its compose project directory. The pipeline (gh run list / glab ci get) is fetched when HEAD moves, 15 s after a git push, every minute while it runs and every 5 min otherwise.

Install

From the marketplace (gets updates; herdr-notify and herdr-link-toast are not in it):

claude plugin marketplace add schreibse/claude-code-mods
claude plugin install quiet-bash@schreibse-mods   # per mod

Then turn on updates: /plugin → Marketplaces → schreibse-mods → Enable auto-update. See Updates.

From a clone, to adapt a mod or work on it. Claude Code loads every plugin folder under ~/.claude/skills/ at session start. Don't install the same mod from the marketplace too: the installed copy silently replaces the folder.

New sessions pick them up; a running one needs /exit and claude --continue.

Leave a mod out: claude plugin uninstall <mod>@schreibse-mods, or delete or unlink its folder. Try one for a single session: claude --plugin-dir ~/src/claude-code-mods/<mod>.

Where they run. Built and used only in the terminal CLI on Fedora (Linux, systemd, cgroup v2). The engine also loads user-scope mods in the local session the desktop app starts for its Code tab, and draws them there (desktop surface); untested here. See Setting up for what each mod needs.

This repo is the skills folder itself, so .gitignore ignores everything and re-includes each mod: a new mod needs a !/<name>/ line or git won't see it. .claude-plugin/types/ is generated by the engine and stays untracked.

Updates

Each mod has its own version (plugin.json) and a CHANGELOG.md in its folder; each release is a git tag <mod>--v<version>.

  • Get them: with auto-update on, Claude Code updates the mods after a session's first message and says Plugin updated: <mod> · Run /reload-plugins to apply. Without it nothing tells you; check by hand: ``sh claude plugin marketplace update schreibse-mods claude plugin update quiet-bash@schreibse-mods # per mod; "already at the latest version" if none ``
  • What changed: the mod's CHANGELOG.md. Read every version you skipped: a major version means you have to act (a new hook in settings.json, a new dependency, a removed command).
  • Notified outside Claude Code: on GitHub, Watch → Custom → Releases. Each release carries the mod's changelog entry.
  • From a clone: git -C ~/.claude/skills pull --ff-only, then read the changelogs of the mods whose version moved (git -C ~/.claude/skills diff ORIG_HEAD -- '*/.claude-plugin/plugin.json').

redact: secrets as tokens

betterleaks scans every prompt and tool result before it reaches the model. Each value it flags becomes ‹secret:xxxxxxxx› and stays hidden wherever it appears later, even where the scanner would not recognise it again.

The model's callWhat happens
Write, Edit, NotebookEdit with a tokenthe real value is written to the file
Write that would drop a secret the file holdsrefused: use Edit
Agent, SendMessage, TodoWrite with a tokenpassed on as the token
Any other tool with a token (Bash, WebFetch, MCP …)refused, so the value never leaves
A token the mod no longer knows (after a restart)refused, never restored wrongly

Cut-short output. Before Bash or any tool with a file_path/path (Read, Grep, Edit …) runs, every file the call names (Bash: the first 10 words that could be paths, files up to 1 MB) is scanned whole, so cut -c1-60 .env, cut -d= -f2 or a Read of a few lines from a PEM key still come back as tokens. Multi-line secrets are hidden line by line. Bash words resolve against the directory each segment runs in (cd sub && cut -c1-40 .env), and ~/, $HOME/ and ${HOME}/ expand to the home directory.

Rules. betterleaks' defaults plus redact/betterleaks.toml: Sentry DSN keys, and client secrets too short for the generic rules. A client secret containing dev, local, test, example, changeme or placeholder stays visible, so local dev clients keep working in commands.

Not covered:

  • images; output with no file behind it, cut short (git show HEAD:.env | cut …, printenv | cut …); the transcript file's structured tool records, which keep real values (the model does not read them).
  • the cut-short pre-scan misses globs (cut -c1-40 *.env), quoted paths with spaces and a cd inside a subshell ((cd sub && cut -c1-40 .env)).
  • betterleaks' client-secret rule needs some entropy (≥ 3.0), so short, repetitive client secrets stay visible.
  • values shorter than 8 characters are never hidden.
  • a value restored into a file by Write/Edit can be read back transformed (base64, rev, xxd) or sent (curl -T file). redact keeps secrets out of the model's context by accident; it is not a sandbox against a model trying to get them.
  • a subagent's report that quotes a ‹secret:…› token is refused like any other tool call carrying one.

The vault lives in session memory: /exit forgets it.

The status line shows redacted N once a value is hidden: N counts vault entries, so a PEM key counts once per line. A toast per call names the rules that hid new values. Without betterleaks the status line says off (no betterleaks) and nothing is hidden. A betterleaks run that fails leaves that call unredacted (values already in the vault stay hidden): one toast per failure streak, the status says off (betterleaks), and the next call scans again.

mem-guard: memory rules for Bash

Every Bash command that names a Node tool (node, npx, pnpm, npm, npm exec, yarn, nx, jest, vitest, playwright, tsc, ngc) runs as systemd-run --user --scope --slice=claude-cmd.slice -p MemoryMax=30% -p MemorySwapMax=4% -- bash -c '…', so an overrun dies with exit 137 instead of taking the desktop down. Leading cd … && stay outside the wrapper, so the shell's directory still moves.

The rules read what each part of a command runs (after &&, |, ;, &, $( ), inside bash -c '…', following cd), never words it only mentions, so a commit message saying pkill -f passes. Not looked into: xargs, make, eval, scripts.

At once, counted per scope in claude-cmd.slice from one ps scan (skipped when ps fails):

  • at most 2 heavy commands (jest, vitest, Playwright, tsc, ngc, an nx task); the nx daemon and dev servers don't count;
  • at most 2 dev servers (nx serve, nx run x:serve, a serve* script): the API and one app.

A command counts as heavy for these checks when it runs one of those tools, docker compose up, or a test, build, lint, typecheck, e2e or serve* script.

check-runner subagents (an agent type of the owner's) only run checks: git commands that change the tree or history, sed -i, --write/--fix, starting or stopping servers or processes, and writes outside /tmp are refused with "Report the failure instead of fixing it".

Assumes this setup; the messages name it:

  • a claude-cmd.slice user unit. Without it systemd makes the slice with no limit of its own: each command is still capped at 30 % of RAM, but the headroom check has nothing to measure and stays off: ``ini # ~/.config/systemd/user/claude-cmd.slice [Slice] MemoryMax=30% MemorySwapMax=4% ` A full slice can livelock without ever reaching the OOM killer, so let systemd-oomd kill a scope in it under sustained pressure: systemctl --user set-property claude-cmd.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=50%. systemd turns a percentage into bytes of the machine's RAM (on 27 GiB: 8.2G and 1.1G), so the same unit fits any machine. Check what a machine gets: systemd-run --user --scope -q -p MemoryMax=30% -- sh -c 'cat /sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)/memory.max'`
  • a dev API served on port 4700: the refusal messages say fuser -k 4700/tcp.
  • repos whose heavy scripts have a :lite twin (lint:affected:lite, typecheck:lite, test:affected:lite) and a slow ci:local script.

usage-percent: not covered

  • On GitHub only the newest workflow run of the branch is shown.
  • A remote using an SSH host alias (git@work:org/repo) reads as ci no login (work) though you are logged in.
  • A server counts as the session's when it runs inside the session's root, or in a container whose compose project lives there. Two sessions on one checkout both see its servers.

herdr: images and links

Under herdr (here inside Ghostty), quiet-bash's thumbnails draw only their alt text, and links in mr-banner, coderabbit-band and Claude's own output aren't clickable.

Cause: Claude Code turns on kitty graphics only for terminals whose XTVERSION answer is kitty (≥ 0.28) or starts with ghostty, and hyperlinks only for terminals it recognises. herdr forwards both, but answers with its own name, so Claude Code turns both off.

Fix: force both on, inside herdr only, before Claude Code starts (it reads them at startup):

# ~/.bashrc.d/herdr-terminal.sh
if [ -n "$HERDR_ENV" ]; then
    export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1
    export FORCE_HYPERLINK=1
fi

Also turn on herdr's kitty graphics passthrough (off by default) in ~/.config/herdr/config.toml:

[experimental]
kitty_graphics = true

Then herdr server reload-config, open a new herdr pane (old panes keep the old environment) and start Claude Code there. Check it: /thumb /path/to/some.png should draw the picture.

herdr-link-toast (a herdr plugin, not a Claude Code mod)

herdr opens a ctrl+clicked link in the background with no feedback, and ignores file:// links altogether. herdr-link-toast opens http(s) links with xdg-open and shows a toast. It also opens the path in quiet-bash's thumbnail captions, which link to http://localhost/open-file/<path> because file:// isn't clickable in herdr. Such a link opens only when the path ends in .png; any other gets a "Could not open link" toast. Needs python3 ≥ 3.9. Install:

herdr plugin link ~/.claude/skills/herdr-link-toast

Without herdr, in plain kitty or Ghostty, none of this is needed. Terminals without the kitty graphics protocol show the thumbnail's alt text (its path).

Setting up on another machine (for AI agents)

Read before installing for someone. The mods were written for one machine; several carry its names and need Linux.

1. Check the host. Mods need Claude Code 2.1.287+. They load in the terminal CLI and, from ~/.claude/skills, in a desktop app's local Code-tab session. A desktop-app session can also be given a folder through CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json. Nothing here has been tried in the desktop app, VS Code, JetBrains, macOS, WSL or native Windows: say so to the person instead of promising it works.

2. Pick mods by platform.

Works anywhereNeeds LinuxNever on macOS or Windows
quiet-spinner, reminder-log, mr-banner, coderabbit-band, redact (with betterleaks), handover, review-walk; usage-percent's ctx/5h/wk and pipeline partsusage-percent's memory and dev-server parts (cgroup v2, /proc, pwdx; they stay empty elsewhere); stack-down (ps, /proc/<pid>/cwd, setsid)mem-guard: it wraps every Node command in systemd-run, so without systemd every node/pnpm/nx call fails. Leave it out. herdr-notify, herdr-link-toast: Linux, herdr, Ghostty, GNOME
  • Windows: quiet-bash, redact and handover read POSIX paths (/, ~). There, quiet-bash thumbnails and redact's Bash pre-scan find nothing, and handover leaves spent files behind.
  • Surfaces: quiet-bash thumbnails draw only in a terminal with kitty graphics (kitty, Ghostty). Bands and the usage row show in the terminal and the desktop app, not in VS Code or on mobile. /handover-copy can't copy from the desktop app.

3. Adapt to the OS you are on. The mods do not detect the OS; you are running on it, so adapt the person's copy and test it there. The plugin API has no OS call: on Windows $.env.get('OS') is Windows_NT, elsewhere uname -s says Darwin or Linux. Known gaps:

  • mem-guard off Linux: leave it out. To keep its command-only rules (jest worker cap, :lite, pkill -f, ci:local), skip scoped() and the ps/cgroup checks when systemd-run is missing.
  • handover on Windows: HOME may be unset (USERPROFILE), and spent sentences are removed with rm.
  • quiet-bash, redact on Windows: path parsing knows / and ~ only, not C:\….
  • usage-percent on macOS: no pwdx (lsof -a -d cwd -p <pid> instead); the memory zone needs cgroup v2 and stays empty.
  • herdr-notify, herdr-link-toast: Linux, herdr and GNOME only; another OS needs its own notifier, not a port.

Write each OS change as its own commit with a test, so it can come back upstream.

4. Replace the owner's names. Names in this README and in the messages are examples from the owner's repos; use the person's own. The API project there is ec-api, not api, and the dev-server rules only work with the real project names: read them from the repo (npx nx show projects).

ModOwner-specificWhere
mem-guardclaude-cmd.slice and its 30 % / 4 % limits; port 4700; :lite scripts; ci:local "~45 min"; the check-runner agent type; 2 heavy commands, 2 dev servershooks/rules.ts, hooks/register.ts
usage-percentclaude.slice (usage) and app.slice (pressure) under the user manager; Nx repos only (nx.json)hooks/register.tsx
stack-downanother session is a process whose command is claude (native install); an npm install runs as node …/cli.js, goes unseen, and its repo's Compose stacks go down anywayhooks/targets.ts
mr-banner, coderabbit-band, quiet-bashthe GitLab MCP server named gitlab (mcp__gitlab__…)hooks/*.ts(x)
coderabbit-band, usage-percentany remote that isn't GitHub (or Azure) is taken for GitLabhooks/register.tsx
herdr-notifyGhostty's desktop entry com.mitchellh.ghosttynotify.sh

5. Install and check. Install as above (from a clone when you adapted a mod: an update replaces a marketplace copy), then run claude plugin validate <mod> and claude plugin test <mod> for each mod you install. Start a new session and check what the person should now see: the usage row, a tool row with ✓, and for redact, nothing until it hides a value, then redacted N in the status line.

Developing

Each mod is .claude-plugin/plugin.json, hooks/hooks.json and hooks/register.ts(x), plus types/index.d.ts when it keeps session state. Per mod:

claude plugin validate <mod>   # what it hooks and calls, and what the engine would refuse
claude plugin test <mod>       # its *.test.ts(x)
tsc -p <mod>                   # once the engine has laid .claude-plugin/types/

Edits in ~/.claude/skills hot-reload into running sessions that loaded the mod.

Releasing a mod

Marketplace users only get a change once the mod's version moves, so a change meant for them bumps it in the same commit:

  1. Bump version in <mod>/.claude-plugin/plugin.json: major when users must act, minor for a feature, patch for a fix.
  2. Add ## <version> — <date> to <mod>/CHANGELOG.md, with an Action needed line on a major.
  3. claude plugin validate --strict . (the marketplace) and claude plugin validate --strict <mod>.
  4. Commit and push, then claude plugin tag --push <mod>.
  5. gh release create <mod>--v<version> --verify-tag --title "<mod> <version>" --notes-file <entry>, with the new changelog entry as the notes; links in it must be absolute.
Source 3 files
hooks/register.ts 158 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import { dropped, judge, parseReport, pathWords, seal, unsealFields } from './vault'
5import type { Finding } from './vault'
6
7const vault = atom({ plugin: 'redact', key: 'vault' } as const, {})
8
9const SEALED_DOORS = new Set(['prompt', 'command', 'tool-result', 'tool-message', 'delivery', 'attachment', 'hook-context'])
10const SCANNER = ['betterleaks', 'stdin', '--no-banner', '--log-level', 'error', '--report-format', 'json', '--report-path', '-', '--exit-code', '0']
11
12const MAX_SOURCE_FILES = 10
13const MAX_SOURCE_BYTES = 1_000_000
14
15let hasScanner = true
16let isScanFailing = false
17let home = ''
18
19async function findSecrets($: EngineInterface, text: string): Promise<Finding[]> {
20  if (!hasScanner || text.length === 0) {
21    return []
22  }
23  const run = await $.process.run([...SCANNER, '--config', `${$.plugin.root}/betterleaks.toml`], { stdin: text }).catch(() => null)
24  const findings = run?.exitCode === 0 ? reportOrNull(run.stdout) : null
25  if (findings === null) {
26    if (!isScanFailing) {
27      $.ui.toast('betterleaks failed, this output is NOT redacted')
28    }
29    isScanFailing = true
30    $.ui.status('off (betterleaks)')
31    return []
32  }
33  if (isScanFailing) {
34    isScanFailing = false
35    const count = Object.keys(await read($, vault)).length
36    $.ui.status(count > 0 ? `redacted ${count}` : undefined)
37  }
38  return findings
39}
40
41function reportOrNull(stdout: string): Finding[] | null {
42  try {
43    return parseReport(stdout)
44  } catch {
45    return null
46  }
47}
48
49async function sealText($: EngineInterface, text: string, findings?: readonly Finding[]): Promise<string> {
50  const found = findings ?? (await findSecrets($, text))
51  let sealed = text
52  let added: Finding[] = []
53  const count = Object.keys(
54    await update($, vault, current => {
55      const result = seal(text, current, found)
56      sealed = result.text
57      added = result.added
58      return result.vault
59    }),
60  ).length
61  for (const rule of new Set(added.map(finding => finding.rule))) {
62    $.ui.toast(`hid a ${rule} value from the model`)
63  }
64  if (count > 0 && !isScanFailing) {
65    $.ui.status(`redacted ${count}`)
66  }
67  return sealed
68}
69
70type Block = { type: string; text?: string; content?: string | Block[] }
71
72async function sealBlocks($: EngineInterface, blocks: readonly Block[]): Promise<Block[]> {
73  return Promise.all(
74    blocks.map(async block => {
75      if (block.type === 'text' && typeof block.text === 'string') {
76        return { ...block, text: await sealText($, block.text) }
77      }
78      if (block.type === 'tool_result' && typeof block.content === 'string') {
79        return { ...block, content: await sealText($, block.content) }
80      }
81      if (block.type === 'tool_result' && Array.isArray(block.content)) {
82        return { ...block, content: await sealBlocks($, block.content) }
83      }
84      return block
85    }),
86  )
87}
88
89// Output cut short (`cut -c1-60`, Read with a limit) loses the context a rule needs, so the
90// whole source file is scanned first and its values are hidden wherever they show up.
91async function sealSourceFiles($: EngineInterface, call: { tool: string }): Promise<void> {
92  const input = call as { tool: string; file_path?: unknown; path?: unknown; command?: unknown }
93  const candidates =
94    input.tool === 'Bash' && typeof input.command === 'string'
95      ? pathWords(input.command, await $.session.cwd(), home)
96      : [input.file_path, input.path].filter((path): path is string => typeof path === 'string')
97  let sealedFiles = 0
98  for (const path of candidates) {
99    if (sealedFiles === MAX_SOURCE_FILES) {
100      break
101    }
102    const stat = await $.fs.stat(path).catch(() => null)
103    if (stat?.kind === 'file' && stat.size <= MAX_SOURCE_BYTES) {
104      sealedFiles++
105      await sealText($, await $.fs.read(path).catch(() => ''))
106    }
107  }
108}
109
110export const register: Register = on => {
111  on('session.start', async ($, e, next) => {
112    home = (await $.env.get('HOME')) ?? ''
113    const probe = await $.process.run(['betterleaks', 'version']).catch(() => null)
114    hasScanner = probe?.exitCode === 0
115    isScanFailing = false
116    $.ui.status(undefined)
117    if (!hasScanner) {
118      $.ui.toast('betterleaks is not installed, secrets are NOT being hidden')
119      $.ui.status('off (no betterleaks)')
120    }
121    return next(e)
122  })
123
124  on('prompt.submit', async ($, e, next) => next({ ...e, text: await sealText($, e.text) }))
125
126  on('session.append', async ($, e, next) => {
127    if (!SEALED_DOORS.has(e.door)) {
128      return next(e)
129    }
130    const content = (await sealBlocks($, e.message.content as readonly Block[])) as typeof e.message.content
131    return next({ ...e, message: { ...e.message, content } })
132  })
133
134  on('tool.call', async ($, e, next) => {
135    const known = await read($, vault)
136    const verdict = judge(e.tool, JSON.stringify(e), known)
137    if ('deny' in verdict) {
138      return { deny: verdict.deny }
139    }
140    await sealSourceFiles($, e)
141    const call = verdict.restore ? unsealFields(e, known) : e
142
143    // A whole-file Write written from memory can silently leave out a value the model never saw.
144    if (call.tool === 'Write') {
145      const { file_path: path, content } = call as typeof call & { file_path: string; content: string }
146      const before = (await $.fs.stat(path).catch(() => null))?.kind === 'file' ? await $.fs.read(path).catch(() => '') : ''
147      const findings = await findSecrets($, before)
148      const secrets = [...Object.values(await read($, vault)).map(entry => entry.value), ...findings.map(finding => finding.secret)]
149      const lost = dropped(before, content, secrets)
150      if (lost.length > 0) {
151        const named = await sealText($, lost.join(', '), findings)
152        return { deny: `redact: this Write would drop ${named} from ${path}. Change the file with Edit instead; to remove a value on purpose, Edit with its token in old_string.` }
153      }
154    }
155    return next(call)
156  })
157}
158
hooks/vault.ts 148 lines
1import type { Vault } from '../types'
2
3export type Finding = { rule: string; secret: string }
4
5const TOKEN = /‹secret:([0-9a-f]{8})›/g
6const MIN_SECRET_LENGTH = 8
7
8export const PASS_THROUGH = new Set(['Agent', 'SendMessage', 'TodoWrite'])
9export const RESTORING = new Set(['Write', 'Edit', 'NotebookEdit'])
10
11function fnv1a(text: string): string {
12  let hash = 0x811c9dc5
13  for (let i = 0; i < text.length; i++) {
14    hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193)
15  }
16  return (hash >>> 0).toString(16).padStart(8, '0')
17}
18
19function idFor(vault: Vault, secret: string): string {
20  let id = fnv1a(secret)
21  while (vault[id] !== undefined && vault[id]?.value !== secret) {
22    id = fnv1a(id + secret)
23  }
24  return id
25}
26
27function tokenOf(id: string): string {
28  return `‹secret:${id}›`
29}
30
31type ReportItem = { RuleID?: string; Secret?: string; ComponentSets?: { components?: ReportItem[] }[] | null }
32
33// A composite finding (AWS key id + secret) carries its second value only as a component.
34export function parseReport(stdout: string): Finding[] {
35  const report = JSON.parse(stdout || '[]') as ReportItem[]
36  return report
37    .flatMap(item => [item, ...(item.ComponentSets ?? []).flatMap(set => set.components ?? [])])
38    .flatMap(item => [item, ...linesOf(item)])
39    .filter(item => (item.Secret ?? '').length >= MIN_SECRET_LENGTH)
40    .map(item => ({ rule: item.RuleID ?? 'secret', secret: item.Secret ?? '' }))
41}
42
43// A multi-line value (a PEM key) is also hidden line by line, since a partial read never holds it whole.
44function linesOf(item: ReportItem): ReportItem[] {
45  const lines = (item.Secret ?? '').split(/\r?\n/).map(line => line.trim())
46  return lines.length < 2 ? [] : lines.filter(line => !/^-----.*-----$/.test(line)).map(line => ({ RuleID: item.RuleID, Secret: line }))
47}
48
49// Known values are replaced wherever they show up: the scanner may only recognise one next to its name.
50export function seal(text: string, vault: Vault, findings: readonly Finding[]): { text: string; vault: Vault; added: Finding[] } {
51  let next = vault
52  const added: Finding[] = []
53  for (const finding of findings) {
54    if (!Object.values(next).some(entry => entry.value === finding.secret)) {
55      const id = idFor(next, finding.secret)
56      next = { ...next, [id]: { value: finding.secret, rule: finding.rule } }
57      added.push(finding)
58    }
59  }
60  const longestFirst = Object.entries(next).sort(([, a], [, b]) => b.value.length - a.value.length)
61  let sealed = text
62  for (const [id, entry] of longestFirst) {
63    sealed = sealed.replaceAll(entry.value, tokenOf(id))
64  }
65  return { text: sealed, vault: next, added }
66}
67
68export function tokensIn(text: string): string[] {
69  return [...new Set([...text.matchAll(TOKEN)].map(match => match[1] ?? ''))]
70}
71
72export function unseal(text: string, vault: Vault): string {
73  return text.replace(TOKEN, (token, id: string) => vault[id]?.value ?? token)
74}
75
76export function unsealFields<T extends Record<string, unknown>>(input: T, vault: Vault): T {
77  return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, typeof value === 'string' ? unseal(value, vault) : value])) as T
78}
79
80export type Verdict = { deny: string } | { restore: boolean }
81
82export function judge(tool: string, inputText: string, vault: Vault): Verdict {
83  const ids = tokensIn(inputText)
84  if (ids.length === 0) {
85    return { restore: false }
86  }
87  const unknown = ids.filter(id => vault[id] === undefined)
88  if (unknown.length > 0) {
89    return { deny: `redact: ${unknown.map(tokenOf).join(', ')} is no longer known (the session restarted or the mod reloaded), so it cannot be restored. Re-read the file, or leave that value untouched and edit around it.` }
90  }
91  if (RESTORING.has(tool)) {
92    return { restore: true }
93  }
94  if (PASS_THROUGH.has(tool)) {
95    return { restore: false }
96  }
97  return { deny: `redact: ${tool} input contains a ‹secret:…› token. Tokens stand for values you must not see; they are restored only in Write, Edit and NotebookEdit. Work on the file instead (e.g. Edit), or ask the user.` }
98}
99
100const CD = /^cd(?:\s+(\S+))?$/
101
102function expandHome(word: string): string {
103  return word.replace(/^\$(?:HOME|\{HOME\})(?=\/|$)/, '~')
104}
105
106function absolute(path: string, dir: string, home: string): string {
107  return path.startsWith('/') ? path : path === '~' || path.startsWith('~/') ? `${home}${path.slice(1)}` : `${dir}/${path}`
108}
109
110function chdir(dir: string, home: string, target = '~'): string {
111  const parts: string[] = []
112  for (const part of absolute(expandHome(target.replace(/^(['"])(.*)\1$/, '$2')), dir, home).split('/')) {
113    if (part === '..') {
114      parts.pop()
115    } else if (part !== '' && part !== '.') {
116      parts.push(part)
117    }
118  }
119  return `/${parts.join('/')}`
120}
121
122// Words of a shell command that could name a file: `cut -c1-9 a.env`, `jq . <cfg.json`, `--file=x`,
123// each resolved against the directory its segment runs in after any `cd` before it.
124export function pathWords(command: string, cwd: string, home: string): string[] {
125  let dir = cwd
126  let previous = cwd
127  const paths: string[] = []
128  for (const segment of command.split(/&&|\|\||[;|\n]/).map(part => part.trim())) {
129    const cd = CD.exec(segment)
130    if (cd !== null) {
131      const next = cd[1] === '-' ? previous : chdir(dir, home, cd[1])
132      previous = dir
133      dir = next
134      continue
135    }
136    const words = segment
137      .split(/[\s|;&<>()`]+/)
138      .map(word => expandHome(word.replace(/^['"]|['"]$/g, '').replace(/^-[^=]*=/, '')))
139      .filter(word => word.length > 0 && !word.startsWith('-') && !word.includes('$'))
140    paths.push(...words.map(word => absolute(word, dir, home)))
141  }
142  return [...new Set(paths)]
143}
144
145export function dropped(before: string, after: string, secrets: readonly string[]): string[] {
146  return secrets.filter(secret => before.includes(secret) && !after.includes(secret))
147}
148
types/index.d.ts 8 lines
1export type Vault = Record<string, { value: string; rule: string }>
2
3declare module 'claude-code' {
4  interface PluginState {
5    redact: { vault: Vault }
6  }
7}
8