SLOPSHOPPER

redact

Hides secrets (API keys, tokens, private keys) from the model in prompts and tool results

toastprompt
★ 4v0.1.0MITupdated 2026-10-13ThisaruGuruge/dotfiles/claude-mods/redact
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · redact
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ redact │ ⏺ Read(src/auth.ts) │ redact: hid 2 secret(s) from a tool result │ ⎿ Read 6 lines │ (stripe-key, url-password) │ ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Thisaru's Dotfiles

A macOS-focused developer workstation built around Zsh, Powerlevel10k, modern CLI tools, and battle-tested automation. Everything is wired together with bestow (a Go-based GNU Stow successor), encrypted secrets, and a centralized package manifest so each new machine behaves exactly like the last one.

Highlights

  • Fast Zsh environment – zinit-managed plugins, fzf-tab completion, syntax highlighting, autosuggestions, zoxide (via z command), Atuin history (Ctrl+R and up-arrow), and Ghostty compatible key bindings
  • Powerlevel10k prompt – pure-Zsh rendering (no binary subprocess per draw), instant prompt on startup, contextual Git state, Go/Java/Python/Ballerina indicators, transient prompt for clean scrollback, full Catppuccin Mocha theme matching the tmux status bar
  • Modern CLI stack – eza, bat, dust, ripgrep, fd, yazi (with inline image previews in Ghostty/iTerm2, chafa fallback for other terminals), jless, lazygit, lazydocker, tmux, direnv, atuin, gh, git-delta, gng (gw), uv (Python packages and projects), and curated helper aliases/functions (take, kill_by_port, show_tools, etc.)
  • Debugging in Neovim – nvim-dap with a DAP UI, inline variable values while stepping, and one keymap set (<leader>d… plus F5/F10/F11) shared by every language. Go (delve) supports debugging the test under the cursor, launching the program with arguments, and attaching to a remote dlv --headless; Python, Java, and Ballerina are wired in too. Adding another debugger is a single drop-in file: a module at nvim/.config/nvim/lua/thisarug/dap/<lang>.lua exporting setup(dap) is picked up automatically by lua/plugins/dap.lua
  • Go tooling in Neovim – gopls with inlay hints and codelenses, <leader>G… for code generation (if err != nil guards, struct tags, interface stubs, test and doc-comment generation), and <leader>T… to run tests from the buffer with a summary tree and watch mode (Go, plus pytest and Vitest via neotest adapters)
  • Sessions and branch review in Neovim – persistence.nvim restores a project's buffers and layout on demand (<leader>qs, or s on the dashboard), and diffview.nvim reviews a branch against the default branch (<leader>gv) or walks a file's history (<leader>gh)
  • Smart aliases – Single-letter shortcuts for modern tools (v for nvim, g for ripgrep, f for fd, z for zoxide) while keeping original commands for scripts
  • Suffix aliases – Automatically open files with the right tool based on extension (.md → mdcat, .json/.yaml → jless, .py/.bash/.zsh/.bal → $EDITOR)
  • Language runtimes – pyenv, rbenv, nvm, SDKMAN, and Ballerina (plus uv for Python packages and projects) with lazy-loading shell glue so heavy managers don't slow startup
  • Touch ID for sudo – Use your fingerprint instead of typing passwords in the terminal (works inside tmux too via pam-reattach)
  • Caps Lock remap – Hammerspoon + ControlEscape.spoon: tap Caps Lock for Escape, hold for Control — a Karabiner alternative that needs only Accessibility/Input Monitoring permissions, no blockable system extension
  • Claude Code, two accounts – ccp (personal) and cce (enterprise) run Claude Code against separate config dirs, with TypeScript mods for a status band, risk previews, secret redaction and a subagent pane (see Claude Code); tmux shows which windows are waiting on Claude
  • Project sessions in tmux – prefix + f opens a project with three windows ([Claude], [Nvim], [Shell])
  • Secrets handled correctly – SOPS + age encryption, edit_secrets workflow, and automatic .env handling inside init.sh
  • Brewfile-driven – Curated Brewfile with optional category files in packages/ for modular installation
  • Validation + profiling – bin/lint (shellcheck, shfmt, zsh -n, stylua, mod tests; also run by CI), test-zsh integration tests, dotdoctor health check, profile_startup quick timing, and bin/profile-zsh-startup for deep dives

Prerequisites

  1. macOS – Tested on Sonoma/Ventura (Apple Silicon friendly)
  2. Git – Already on macOS, confirm with git --version
  3. Homebrew – Install if missing:
   /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  1. Terminal – Ghostty (recommended and configured), iTerm2, or Terminal.app all work
  2. Nerd Font – Needed for icons in Powerlevel10k/lazygit:
   brew install --cask font-fira-code-nerd-font

Set the font once inside your terminal profile (Appearance/Text settings).

Installation

Option 1 – Automated (init.sh)

git clone https://github.com/ThisaruGuruge/dotfiles.git ~/dotfiles
cd ~/dotfiles
./init.sh

The checkout can live anywhere (the script finds the repo from its own path). The rest of the setup hard-codes ~/dotfiles, so when the checkout is elsewhere init.sh creates a ~/dotfiles symlink pointing at it (and stops with a clear message if ~/dotfiles is already something else). ./init.sh --dry-run is a preflight only: it checks the checkout and ~/dotfiles and changes nothing; ./init.sh --help lists the steps.

The script is interactive; it will:

  • Validate macOS + Xcode CLT, install Homebrew, jq, Go (needed to install bestow)
  • Install core packages from Brewfile with Brew
  • Offer opt-in categories (development, terminals, editors, etc.)
  • Install SDKMAN + Java 21 (optional) and brew-based Ballerina
  • Enable Touch ID for sudo (with tmux support via pam-reattach, loaded from a root-owned copy in /opt/pam)
  • Configure Atuin, direnv, tmux, git delta, lazygit, lazydocker, aliases, and helper functions
  • Generate/restore encrypted .env with SOPS + age (keys stored at ~/.config/sops/age/keys.txt, per-machine ~/.sops.yaml)
  • Create Nerd Font + terminal integrations
  • Back up existing dotfiles and symlink everything via bestow
  • Install TPM (pinned release) and the tmux plugins
  • Check that the SSH commit-signing key exists (offers to create it)
  • Verify the install and show next steps (run dotdoctor for a full health check; the final output also lists the manual steps: the Hammerspoon spoon and permissions, the ~/.claude symlink, tmux plugins)

Option 2 – Manual setup

git clone https://github.com/ThisaruGuruge/dotfiles.git ~/dotfiles
cd ~/dotfiles

# Install everything that is currently enabled in Brewfile
brew bundle --file=Brewfile

# Install bestow (requires Go)
go install github.com/redpierrot/bestow@latest

# Bootstrap bestow's own config (source: this repo, destination: $HOME)
bestow init --source ~/dotfiles --destination ~/

# Symlink the packages you need (add/remove as desired)
bestow stow zsh git tmux direnv bash
bestow stow bin -d ~/bin   # bin links into ~/bin, not ~

# Secrets: an age key and this machine's own sops config (not tracked)
mkdir -p ~/.config/sops/age && age-keygen -o ~/.config/sops/age/keys.txt
sed "s/AGE_PUBLIC_KEY/$(grep '^# public key:' ~/.config/sops/age/keys.txt | cut -d' ' -f4)/g" \
  bash/.sops.yaml.example > ~/.sops.yaml

# Reload configuration, then create the encrypted ~/.env
source ~/.zshrc
edit_secrets

Git signs every commit with SSH (gpgSign = true), so set user.signingkey in ~/.gitconfig.local (see git/.gitconfig.local.example) and create the key it names (ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_signing) before your first commit.

Edit the Brewfile directly or use category Brewfiles in packages/ before running brew bundle if you want to customize packages.

Option 3 – Brewfile only

Already have a preferred dotfiles strategy but want the curated tools? Run brew bundle --file=Brewfile and manually pick pieces (aliases, functions, etc.). Edit the Brewfile directly or use the category files in packages/ to customize your installation.

Package Management

The main Brewfile contains core packages that are always installed. Optional packages are organized into category files in packages/:

packages/
├── cloud.brewfile       # aws-vault, gcloud CLI
├── containers.brewfile  # colima, Docker CLI + Compose + credential helper
├── development.brewfile # pyenv, rbenv, nvm, flutter
├── editors.brewfile     # VS Code
├── productivity.brewfile # Raycast, Rectangle, Alfred, Caffeine, etc.
└── terminals.brewfile   # iTerm2

Installing optional categories

brew bundle --file=Brewfile                      # Core packages
brew bundle --file=packages/development.brewfile # Add dev tools
brew bundle --file=packages/editors.brewfile     # Add editors

Categories available

  • core – powerlevel10k, zoxide, eza, bat, ripgrep, lazygit, lazydocker, tmux, direnv, atuin, gh, etc.
  • security – sops + age for encrypted secrets (always enabled)
  • development – pyenv, rbenv, nvm, flutter (optional)
  • cloud – aws-vault and the gcloud CLI
  • editors – VS Code
  • terminals – iTerm2 (casks)
  • containers – colima (container runtime), Docker CLI + Compose + credential helper
  • productivity – Raycast, Rectangle, TablePlus, Alfred, Postman, Caffeine

Comment out what you do not need in the Brewfile, then rerun brew bundle.

brew-sync (or ./bin/sync-brewfile) is a read-only drift report: it lists formulae and casks that are installed but in no Brewfile, and declared packages that are not installed. It never rewrites a Brewfile; add or remove lines by hand. brew-check verifies the core Brewfile is satisfied.

Repository Layout & Symlink Packages

PathNotes
zsh/.zshrc, .zshrc.d/ (modular shell config), .functions.d/ (modular functions), aliases, paths
zsh/.zshrc.d/6 modules: plugins, completion, keybindings, history, integrations, environment
zsh/.functions.d/9 modules: colors, core, navigation, archives, git, system, dotfiles, docs, packages
<tool>/.config/<tool>/XDG configs, one stow package per tool (ghostty, lazygit, nvim, yazi, ripgrep, typos)
zsh/.p10k.zshPowerlevel10k prompt config (Catppuccin Mocha, stowed to ~/.p10k.zsh)
git/.gitconfig, ignore rules, delta settings
tmux/Modern tmux config + keybinds, project session layout, Claude state in status bar
claude/Per-account Claude Code settings.json and status line, stowed to ~/.claude-personal and ~/.claude-enterprise
claude-mods/Claude Code mods (not a stow package; loaded through CLAUDE_CODE_PLUGIN_DIRS)
tests/Golden-output and behaviour tests for the Claude Code helpers (tests/claude/check.sh, run by test-zsh)
direnv/Project-specific environment automation
packages/Optional category Brewfiles (cloud, containers, development, etc.)
bin/Helper scripts (lint, dotdoctor, test-zsh-config, profile-zsh-startup, audit-configs, adopt-config; see bin/README.md)
docs/Additional documentation (prompt guide, tmux keybindings, config management)

Ghostty Configuration

Ghostty is configured with:

  • Cmd+Left/Right sent as Home/End (ESC [ H / ESC [ F), which 03-keybindings.zsh binds to start/end of line (a raw Ctrl+a would be eaten as the tmux prefix)
  • Option+Left/Right for word navigation (sent as Alt+b / Alt+f, so it works inside tmux too) and Cmd+Delete for delete-to-end-of-line (sent as Alt+k)
  • Catppuccin Mocha theme
  • FiraCode Nerd Font with ligatures
  • Tmux-aware keybindings for window/pane navigation (they send the tmux prefix Ctrl+a; test-zsh fails if the prefix changes)

Containers (colima)

The optional containers category (packages/containers.brewfile) installs colima as the local container runtime, paired with the plain docker, docker-compose, and docker-credential-helper CLI formulae — no Docker Desktop app/VM required.

brew bundle --file=packages/containers.brewfile  # colima + docker CLI + compose + credential helper
colima-start                                     # boots the VM, sets the `colima` docker context
docker ps                                        # talks to colima automatically
lzd                                               # lazydocker also works unchanged — it just follows the active docker context

Colima lifecycle aliases (zsh/.aliases.sh, only defined if colima is installed):

AliasCommand
colima-startcolima start
colima-stopcolima stop
colima-restartcolima restart
colima-statuscolima status
colima-listcolima list
colima-sshcolima ssh

Homebrew's docker-compose formula installs as a CLI plugin, and docker-credential-helper installs docker-credential-osxkeychain to store registry credentials in the macOS Keychain instead of plaintext — but Docker only picks either up if ~/.docker/config.json says so:

{
  "cliPluginsExtraDirs": ["/opt/homebrew/lib/docker/cli-plugins"],
  "credsStore": "osxkeychain"
}

init.sh does not currently write these keys automatically — add them by hand (or merge into an existing ~/.docker/config.json) after installing docker-compose / docker-credential-helper.

Symlink Management (bestow)

Day-to-day package management (adding/removing symlinks after the initial install) uses bestow — a Go-based successor to GNU Stow — instead of stow directly. It replicates stow --no-folding behavior (always on, no flag needed) but is idempotent and conflict-safe with pre-existing absolute symlinks.

bestow stow zsh                    # Shell config (includes .p10k.zsh)
bestow stow nvim ghostty lazygit ripgrep yazi typos  # Per-tool packages
bestow stow git tmux direnv        # Git/Tmux/Direnv packages

# Remove a package
bestow unstow zsh

init.sh (the fresh-machine installer) installs bestow with go install github.com/redpierrot/bestow@latest and runs the same bestow stow commands per package. @latest resolves to bestow's newest tagged release once it publishes tags (until then, the newest commit on its default branch).

bin is the exception: it links into ~/bin, so always stow it as bestow stow bin -d ~/bin. Don't run a bare bestow stow across every package — with the single $HOME destination in bestow's config it would link bin/* straight into ~.

Quick Start Commands

test-zsh                                   # Full validation (tools, PATH, runtimes)
./bin/lint                                 # Lint everything, as CI does (./bin/lint --file <path> for one file)
./bin/profile-zsh-startup                  # Deep component timing (zinit plugins, SDKMAN, p10k, etc.)
help                                       # Alias documentation entry point
docs                                       # Interactive alias browser (alias_docs)
show_tools                                 # Overview of installed CLI upgrades
alias_search git                           # Search for aliases by keyword
edit_secrets                               # Safely edit encrypted ~/.env via SOPS
take my-service && code .                  # Smart project bootstrap / clone helper
kill_by_port 3000                          # Stop the process LISTENING on port 3000 (TERM, then KILL); clients are left alone
awake                                      # Keep the Mac from idle-sleeping (awake stop | status | for 2h | screen | ac)
dotdoctor                                  # Health check (changes nothing): unlinked files, dangling links, secrets, mods (--full adds brew + plugin validation)
prs                                        # Browse PRs with fzf: enter=checkout, ctrl-o=browser, ctrl-d=diff via delta
prw                                        # Watch the current PR's checks, then notify with the result
envrc work|personal|status|off             # Pin the Claude Code + gws account for this directory via direnv
lg                                         # Launch lazygit with our config (arguments are forwarded, e.g. lg log)
lzd                                        # Launch lazydocker for Docker management
gw build                                   # Run Gradle build from any subdirectory
gwt                                        # Alias for: gw test
gwc                                        # Alias for: gw clean
gwcb                                       # Alias for: gw clean build
Ctrl+R                                     # Atuin search UI (fuzzy search all history; Ctrl+R again narrows the filter)
Up arrow                                   # Atuin prefix search (as you type)
Ctrl+T / Alt+C                             # fzf file / directory picker with a preview (Ctrl+/ toggles it)

Claude Code

Two accounts, each with its own config directory (claude/ is the stow package that links settings.json and statusline-command.sh into both; history, sessions and auth stay local, auth in the macOS Keychain):

CommandAccountConfig dir
ccp, ccpr, ccpcpersonal: start, --resume, --continue~/.claude-personal
cce, ccer, ccecenterprise: start, --resume, --continue~/.claude-enterprise
  • ~/.claude must be a symlink to ~/.claude-personal (ln -s ~/.claude-personal ~/.claude), so plain claude outside a pinned directory is the personal account. dotdoctor checks it.
  • ccp/ccpr/ccpc also load ~/.claude-personal/projects.d/<repo>.json with --settings when the current git repo has one. That is where a project's own autoMode rules go, since Claude Code ignores autoMode in a project's .claude/settings*.json and they must not live in this public repo. <repo> is the main checkout's directory name, so linked worktrees share it.
  • Mods in claude-mods/ (statusbar, blast-radius, redact, agents, rabe, session-wrapped, conventions) load straight from the repo via CLAUDE_CODE_PLUGIN_DIRS in both settings.json files, with nothing to link. The band above the prompt (context bar, rate limits) is the statusbar mod, the line below it is bin/claude-statusline, and conventions runs bin/lint --file after each edit Claude makes in this repo. See claude-mods/README.md.
  • Hooks call bin/claude-tmux-state, so tmux windows show when Claude is working, waiting or done (prefix + A jumps to the next waiting window).
  • Hooks also call bin/claude-notify, which shows a macOS notification when a session finishes (Stop), asks you something (AskUserQuestion) or needs you (permission prompt, idle: Notification). It stays quiet while the terminal and the tmux window are in view. CLAUDE_NOTIFY=0 turns it off, CLAUDE_NOTIFY_SUBAGENTS=1 adds subagent completions, CLAUDE_NOTIFY_ALWAYS=1 disables the in-view suppression, CLAUDE_NOTIFY_SOUND=<name> changes the sound. One-time setup: allow banners and sounds for Script Editor under System Settings > Notifications (osascript notifications are attributed to it); Focus modes silence them. Details in bin/README.md.
  • Pin an account to a directory with envrc (below).

tmux project sessions

prefix + f (sessionizer) and prefix + S (new session) create a session with three windows: [Claude] (runs claude with the directory's .envrc applied), [Nvim] (nvim over a small shell, the window the session opens on) and [Shell] (plain shell). SESSIONIZER_LAYOUT=bare gives a single shell instead. After pulling, run bestow stow tmux if a new helper script is missing. Key reference: docs/TMUX_KEYBINDINGS.md.

Per-project accounts (envrc)

envrc work (enterprise) or envrc personal writes a .envrc in the current directory that pins CLAUDE_CONFIG_DIR and GOOGLE_WORKSPACE_CLI_CONFIG_DIR (plus the gws file keyring backend), creates the account's gws directory with mode 700, runs direnv allow and applies the pin to the current shell straight away. Plain claude and gws then use the right account anywhere under that directory, including subdirectories and new shells or tmux panes opened inside the tree (direnv stays lazy-loaded: it is only loaded once a .envrc exists in the current directory or any parent). The file is added to the repo's local exclude (info/exclude, also from a linked worktree; envrc confirms with git check-ignore) and inherits parent pins through source_up_if_exists.

  • envrc status shows which pin applies (and whether it is inherited from a parent directory)
  • envrc off removes a pin written by envrc (it never touches a .envrc it did not write)
  • Replacing an existing .envrc (not written by envrc, or edited by hand since) asks first and keeps a copy as .envrc.bak; a symlinked .envrc is refused rather than written through

What overrides what

CommandCLAUDE_CONFIG_DIRGOOGLE_WORKSPACE_CLI_CONFIG_DIR
plain claude in a pinned treepinned accountpinned account (inherited)
ccp/ccpr/ccpc, cce/ccer/ccecthe account you typedblanked for that claude, so a pin never leaks the other account's gws into it
gwsp/gwseunchangedthe account you typed
bare gws in a pinned treeunchangedpinned account: the bin/gws guard lets it through because the pin supplies the account context
bare gws anywhere elseunchangedblocked (exit 64)

Inside a pinned tree a bare gws therefore acts on the pinned account instead of being refused; that is the point of the pin. Plain claude outside any pinned directory uses ~/.claude, which should be a symlink to ~/.claude-personal (dotdoctor checks this: ln -s ~/.claude-personal ~/.claude).

GitHub PR helpers (prs, prw)

  • prs [gh pr list flags] – fzf over the repo's PRs with a gh pr view preview. enter checks the PR out, ctrl-o opens it in the browser, ctrl-d shows the full diff through delta. Example: prs --author @me
  • prw [pr] – gh pr checks --watch for the current branch's PR (or the given number/URL), then a macOS notification with the result; the exit status mirrors gh pr checks

Both need gh and jq; prs also needs fzf. PR titles are untrusted text: control characters (including ESC) are replaced with spaces before they are shown, and prw prints titles verbatim (no backslash interpretation). prw says whether the checks failed, were cancelled or are still pending, or that gh reported no result (no checks, or gh could not be reached), instead of calling every non-zero exit "failed".

Shell behaviour worth knowing

  • cp / mv are small functions, not aliases: they prompt before overwriting (-i, verbose) only when a human is at the terminal, and run the plain command otherwise (scripts, agents, pipes). They do not force -r; copy directories with cp -R. sudo cp / sudo mv run the plain commands (sudo runs the binary, not the shell function), so pass -i yourself there.
  • awake keeps the Mac from idle-sleeping in the background (caffeinate -i: the display may still sleep or lock, and it works on AC and battery). awake screen also keeps the display on, awake ac
Source 2 files
hooks/register.ts 49 lines
1import type { Register } from 'claude-code'
2
3import { redactBlocks, redactText, summary, total, withhold } from './patterns'
4import type { Counts } from './patterns'
5
6/**
7 * The rows scanned before they are stored and sent, by the door they come in
8 * by, and what the toast calls each. `command` is a slash command's record and
9 * output and, for `!` bash mode, the `<bash-input>`, `<bash-stdout>` and
10 * `<bash-stderr>` rows.
11 */
12const DOORS = ['tool-result', 'attachment', 'hook-context', 'command'] as const
13const WHAT: Record<string, string> = {
14  'tool-result': 'a tool result',
15  attachment: 'an attachment',
16  'hook-context': 'hook context',
17  command: 'command output',
18}
19
20export const register: Register = on => {
21  // The prompt, and context attached to it, before the model reads them.
22  on('prompt.submit', ($, e, next) => {
23    const counts: Counts = {}
24    const text = redactText(e.text, counts)
25    const context = e.context?.map(c => redactText(c, counts))
26
27    if (total(counts) === 0) {
28      return next(e)
29    }
30    $.ui.toast(`redact: hid ${total(counts)} secret(s) from your prompt (${summary(counts)})`)
31    return next({ ...e, text, ...(context ? { context } : {}) })
32  }).catch(($, e, next) =>
33    next.called ? next(e) : { drop: 'redact: could not scan the prompt, so it was not sent.' },
34  )
35
36  // Tool results, injected attachments, hook context and command output, before they are
37  // stored and sent. A scan that throws or runs out of time withholds the row's text
38  // rather than letting it through unscanned.
39  on('session.append', { door: DOORS }, ($, e, next) => {
40    const counts: Counts = {}
41    const content = redactBlocks(e.message.content, counts)
42    if (total(counts) === 0) return next(e)
43    $.ui.toast(`redact: hid ${total(counts)} secret(s) from ${WHAT[e.door] ?? 'a row'} (${summary(counts)})`)
44    return next({ ...e, message: { ...e.message, content } })
45  }).catch(($, e, next) =>
46    next.called ? next(e) : next({ ...e, message: { ...e.message, content: withhold(e.message.content) } }),
47  )
48}
49
hooks/patterns.ts 224 lines
1export type Counts = Record<string, number>
2
3/**
4 * A rule hides its whole match, or, with `prefix`, only what follows the
5 * text group 1 matched (group 2), and only when `check` says it looks like a
6 * secret (isSecretLike by default). `check` also sees group 1 and the text
7 * right after the match.
8 */
9type Rule = { kind: string; re: RegExp; prefix?: true; check?: (v: string, head: string, after: string) => boolean }
10
11const PLACEHOLDER = /^(\$|\{|<|%|\[REDACTED|ENC\[|\*+$|x+$|\.+$)/i
12const LOOKS_RANDOM = /^[A-Za-z0-9!@#$%^&*_+\-=/.~]+$/
13
14// A code word: letters and underscores, with up to 3 trailing digits (apiKey, SECRET_KEY, password2).
15const WORDY = /^[A-Za-z_][A-Za-z_]*\d{0,3}$/
16
17/**
18 * Code that names a value rather than holding it: member access whose every
19 * part is a code word (`process.env.API_KEY2`, `config.apiKey`), or one
20 * camelCase or snake_case code word (`secretKey`, `db_password`).
21 */
22export function looksLikeCode(v: string): boolean {
23  const parts = v.split('.')
24  if (parts.length > 1) return parts.every(p => WORDY.test(p))
25  return WORDY.test(v) && (/[a-z][A-Z]/.test(v) || /[A-Za-z]_[A-Za-z]/.test(v))
26}
27
28/**
29 * A value after a credential's name that looks like the secret itself. Hex
30 * runs count (a 40- or 64-character hex string is a common session or webhook
31 * secret); a commit hash is only hidden when a credential's name comes first.
32 */
33export function isSecretLike(v: string): boolean {
34  return !PLACEHOLDER.test(v) && LOOKS_RANDOM.test(v) && /[0-9]/.test(v) && /[A-Za-z]/.test(v) && !looksLikeCode(v)
35}
36
37/**
38 * A whole quoted value after a credential's name (a quoted password holding `&` and `()`):
39 * as isSecretLike, but any printable characters but a space count, since a
40 * quoted password may hold `&`, `(` or `|`.
41 */
42export function isQuotedSecret(v: string): boolean {
43  return v.length >= 8 && !PLACEHOLDER.test(v) && /[0-9]/.test(v) && /[A-Za-z]/.test(v) && !looksLikeCode(v)
44}
45
46/** A file path (`/home/x1`, `~/.secrets/db2`, `./x1`): what a name ending in `_pwd` may hold. */
47const isPath = (v: string) => /^(?:~|\.{1,2})?\//.test(v)
48
49/**
50 * A value in a URL or an Authorization header that could be a real
51 * credential: not a placeholder, not a capitalised word like YOUR_TOKEN_HERE,
52 * and either letters with digits (6+), letters with symbols (8+), or long
53 * (16+). Demo passwords like `guest`, `postgres` or `changeme` pass through,
54 * so files that hold them can still be read and written back.
55 */
56export function isCredentialValue(v: string): boolean {
57  if (PLACEHOLDER.test(v) || /^[A-Z_-]+$/.test(v) || v.length < 6) return false
58  const letters = /[A-Za-z]/.test(v)
59  return v.length >= 16 || (letters && /[0-9]/.test(v)) || (letters && v.length >= 8 && /[^A-Za-z0-9]/.test(v))
60}
61
62const LOCAL_HOST = /^(?:localhost|127\.\d+\.\d+\.\d+|0\.0\.0\.0|\[::1\])(?:[:/?#]|$)/i
63
64/** A URL password worth hiding: a credential, not the user name again, not on this machine. */
65function isUrlPassword(v: string, head: string, after: string): boolean {
66  const user = /\/\/([^:]*):$/.exec(head)?.[1]
67  return isCredentialValue(v) && v !== user && !LOCAL_HOST.test(after.replace(/^@/, ''))
68}
69
70// What follows a credential's name: an optional closing quote, `:` or `=`, an optional opening
71// quote. A quote may be escaped, up to three backslashes deep (`{\"token\":\"...\"}`, and JSON
72// held in a JSON string, as in an AWS SecretString), so the value also stops at a backslash,
73// and at a `<` (`<bash-stdout>TOKEN=...</bash-stdout>`, the rows of `!` bash mode).
74const QUOTE = String.raw`\\{0,3}["']`
75const ASSIGN = String.raw`(?:${QUOTE})?\s*[:=]\s*(?:${QUOTE})?`
76const VALUE = "([^\\s\"'`,;\\\\<]{8,})"
77// A quoted value is taken whole up to its closing quote (a quoted password holding `&` and `()`), up to 200
78// characters and with no space in it; longer or spaced ones fall back to VALUE.
79const OPEN = String.raw`(?:${QUOTE})?\s*[:=]\s*\\{0,3}`
80const QUOTED = (q: '"' | "'") => String.raw`${q})([^\s${q}\\]{1,200})(?=\\{0,3}${q})`
81
82/**
83 * The value after a credential's name, in three rules: a whole double-quoted
84 * value, a whole single-quoted one, then an unquoted (or space-holding) one.
85 * Quoted ones run first; what they hide is a placeholder the last one skips.
86 */
87function named(kind: string, name: string, flags: string, opts: { notPath?: true } = {}): Rule[] {
88  const ok = (v: string) => !opts.notPath || !isPath(v)
89  return [
90    { kind, re: new RegExp(`(${name}${OPEN}${QUOTED('"')}`, flags), prefix: true, check: v => isQuotedSecret(v) && ok(v) },
91    { kind, re: new RegExp(`(${name}${OPEN}${QUOTED("'")}`, flags), prefix: true, check: v => isQuotedSecret(v) && ok(v) },
92    { kind, re: new RegExp(`(${name}${ASSIGN})${VALUE}`, flags), prefix: true, check: v => isSecretLike(v) && ok(v) },
93  ]
94}
95
96// Conservative: each rule needs a distinctive prefix or shape.
97const RULES: Rule[] = [
98  {
99    kind: 'private-key',
100    re: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----/g,
101  },
102  { kind: 'age-key', re: /AGE-SECRET-KEY-1[A-Z0-9]{50,}/g },
103  { kind: 'aws-access-key', re: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g },
104  { kind: 'github-token', re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\b/g },
105  { kind: 'github-token', re: /\bgithub_pat_[A-Za-z0-9_]{40,}\b/g },
106  { kind: 'gitlab-token', re: /\bglpat-[A-Za-z0-9_-]{20,}/g },
107  { kind: 'npm-token', re: /\bnpm_[A-Za-z0-9]{36,}\b/g },
108  { kind: 'huggingface-token', re: /\bhf_[A-Za-z0-9]{30,}\b/g },
109  { kind: 'stripe-key', re: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}\b/g },
110  { kind: 'anthropic-key', re: /\bsk-ant-[A-Za-z0-9_-]{20,}/g },
111  { kind: 'api-key', re: /\bsk-(?:proj-|live-|test-)?[A-Za-z0-9_-]{32,}/g },
112  { kind: 'slack-token', re: /\bxox[abprs]-[A-Za-z0-9-]{10,}/g },
113  { kind: 'google-api-key', re: /\bAIza[0-9A-Za-z_-]{35}\b/g },
114  {
115    kind: 'jwt',
116    re: /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
117  },
118  {
119    // Authorization: Basic|Bearer|Token|Digest <value>
120    kind: 'auth-header',
121    re: /(\bAuthorization["']?\s*:\s*["']?(?:Basic|Bearer|Token|Digest)\s+)([^\s"'`,;]{8,})/gi,
122    prefix: true,
123    check: isCredentialValue,
124  },
125  {
126    kind: 'bearer',
127    re: /(\bBearer\s+)([A-Za-z0-9._~+/-]{16,}=*)/gi,
128    prefix: true,
129    check: v => !PLACEHOLDER.test(v) && /[0-9]/.test(v) && /[A-Za-z]/.test(v),
130  },
131  {
132    // scheme://user:password@host (user may be empty): only the password.
133    // The lookbehind and the bounded scheme keep a long run like `a.a.a.a...` linear.
134    kind: 'url-password',
135    re: /((?<![A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]{0,31}:\/\/[^\s:@/]*:)([^\s@/]+)(?=@)/g,
136    prefix: true,
137    check: isUrlPassword,
138  },
139  // name = value: only the value is replaced, and only when it looks random. Names stay
140  // narrow: a blanket `*_KEY` would hide CACHE_KEY=v2-abc123, and a file read with a value
141  // hidden is written back with the placeholder in it.
142  ...named(
143    'password',
144    '(?<![A-Za-z0-9])(?:password|passwd|passphrase|secret(?:[_-]?key)?|api[_-]?key|access[_-]?key|auth[_-]?token|client[_-]?secret|(?:encryption|signing|master|session)[_-]key)',
145    'gi',
146  ),
147  // DB_PASS=, MYSQL_PWD=: only after another word, and not a path (`OLD_PWD=/home/x1`)
148  ...named('password', '(?<=[A-Za-z0-9][_-])(?:pass|pwd)', 'gi', { notPath: true }),
149  // GITHUB_TOKEN=, NPM_AUTH_TOKEN:, packagePAT=, githubToken:, "private_key": ...
150  // Starting only at the head of a name, with a bounded prefix, keeps `a-a-a-...` linear.
151  ...named('credential', '(?<![A-Za-z0-9_-])(?:[A-Za-z0-9]+[_-]){0,10}(?:token|pat|private[_-]?key|credentials?)', 'gi'),
152  ...named(
153    'credential',
154    '(?<![A-Za-z0-9_])[A-Za-z0-9_]*(?:PAT|TOKEN|SECRET|PASSWORD|PASSWD|APIKEY|API_KEY|Token|Secret|Password|ApiKey|Pat)',
155    'g',
156  ),
157]
158
159export function redactText(text: string, counts: Counts): string {
160  let out = text
161  for (const rule of RULES) {
162    out = out.replace(rule.re, (...m: unknown[]) => {
163      const whole = m[0] as string
164      if (!rule.prefix) {
165        counts[rule.kind] = (counts[rule.kind] ?? 0) + 1
166        return `[REDACTED:${rule.kind}]`
167      }
168      const head = m[1] as string
169      const value = m[2] as string
170      // replace() passes the offset and the whole input last (no named groups here)
171      const end = (m[m.length - 2] as number) + whole.length
172      const after = (m[m.length - 1] as string).slice(end, end + 64)
173      if (!(rule.check ?? isSecretLike)(value, head, after)) return whole
174      counts[rule.kind] = (counts[rule.kind] ?? 0) + 1
175      return `${head}[REDACTED:${rule.kind}]${whole.slice(head.length + value.length)}`
176    })
177  }
178  return out
179}
180
181type Block = { type: string; [k: string]: unknown }
182
183/** Redacts text blocks and tool_result content (string or nested blocks). */
184export function redactBlocks(blocks: Block[], counts: Counts): Block[] {
185  return blocks.map(b => {
186    if (b.type === 'text' && typeof b.text === 'string') {
187      return { ...b, text: redactText(b.text, counts) }
188    }
189    if (b.type === 'tool_result') {
190      const c = b.content
191      if (typeof c === 'string') return { ...b, content: redactText(c, counts) }
192      if (Array.isArray(c)) return { ...b, content: redactBlocks(c as Block[], counts) }
193    }
194    return b
195  })
196}
197
198export const WITHHELD = '[redact: scan failed, content withheld]'
199
200/**
201 * What a row keeps when it could not be scanned: each text block and each
202 * tool_result's content become WITHHELD, every tool_result keeping its id and
203 * error flag; media and the blocks the engine pins stay as they were. Never
204 * throws, whatever the content.
205 */
206export function withhold(content: unknown): Block[] {
207  const text = (): Block => ({ type: 'text', text: WITHHELD })
208  if (!Array.isArray(content)) return [text()]
209  const out = content.flatMap((b: unknown): Block[] => {
210    if (b === null || typeof b !== 'object' || typeof (b as Block).type !== 'string') return []
211    const block = b as Block
212    if (block.type === 'text') return [text()]
213    if (block.type === 'tool_result') return [{ ...block, content: [text()] }]
214    return [block]
215  })
216  return out.length > 0 ? out : [text()]
217}
218
219export const total = (c: Counts) => Object.values(c).reduce((a, n) => a + n, 0)
220export const summary = (c: Counts) =>
221  Object.entries(c)
222    .map(([k, n]) => (n > 1 ? `${k} x${n}` : k))
223    .join(', ')
224