SLOPSHOPPER

secret-guard

Add a gitleaks pre-commit hook to each Git project you open in Claude Code, with pre-commit, Lefthook or Husky

guardcommandtoastprocesstimer
v1.1.5MITupdated 2026-10-19AnnihilationWizard/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(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /secret-guard-use ⎿ secret-guard: Usage: /secret-guard-use pre-commit|lefthook [--remove-other]. Picks the hook manager secret-guard sets up; -- ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

secret-guard

<strong>Secrets stop at the commit.</strong><br> A Claude Code mod that adds a gitleaks pre-commit hook to each Git project you open.

<a href="CHANGELOG.md"><img src="https://img.shields.io/badge/Version-1.1.5-green.svg" alt="Version 1.1.5"></a> <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="MIT License"></a> <a href="https://code.claude.com/docs"><img src="https://img.shields.io/badge/Platform-Claude%20Code-D97757.svg" alt="Platform: Claude Code"></a> <a href="hooks/register.ts"><img src="https://img.shields.io/badge/Type-Function%20hooks%20mod-6E7681.svg" alt="Function hooks mod"></a> <a href="tests/guard.test.ts"><img src="https://img.shields.io/badge/Tests-56%20passing-3FB950.svg" alt="56 tests passing"></a>

<a href="#features">Features</a> · <a href="#install">Install</a> · <a href="#usage">Usage</a> · <a href="#configuration">Configuration</a> · <a href="#development">Development</a> · <a href="CONTRIBUTING.md">Contributing</a> · <a href="CHANGELOG.md">Changelog</a>

Side-by-side terminal: on the left a fresh clone has no hook and a commit with a GitHub token lands in history; on the right secret-guard sets up a gitleaks hook when Claude Code starts and the same commit is stopped

Illustration of a commit before and after.

Installing gitleaks and a hook manager on your machine does not protect a repository until that repository has a hook config and someone installs the hook. On a fresh clone, that step is easy to forget. secret-guard does it for you: when a Claude Code session starts in a Git project, it checks for a gitleaks pre-commit hook and adds one if it is missing. From then on, a commit that contains an API key, token or private key stops before it reaches history.

RunsWhen a session starts, and when Claude enters a worktree
Needsgitleaks, plus pre-commit or Lefthook (Husky for JS/TS projects that use it)
Writes.pre-commit-config.yaml, lefthook.yml, or .husky/pre-commit
NeverRewrites an existing config, or adds dependencies unless you opt in

[!NOTE] secret-guard is built on Claude Code's function-hooks mod API, which is in early access and may change between releases.

Features

  • Set up once per project: A project that already has a gitleaks hook is left alone, and the check never delays your first prompt.
  • pre-commit or Lefthook: Writes a .pre-commit-config.yaml or a lefthook.yml that runs your installed gitleaks, then installs the hook. A project keeps the manager its config already uses, in any file name and format Lefthook reads.
  • Husky for JS/TS: Puts the gitleaks step at the top of .husky/pre-commit in projects that use Husky. A JS/TS project without Husky gets Lefthook when it is installed, so no dependency is added.
  • One manager, your pick: When both pre-commit and Lefthook are installed, secret-guard asks you to pick one with /secret-guard-use, switches the projects it set up, and can remove the other.
  • Worktrees work too: A worktree shares the repository's installed hook but not an uncommitted config. Its commits would be blocked (pre-commit) or skip the scan (Lefthook), so secret-guard adds the config there and reminds you to commit it.
  • Respects your setup: An existing config without gitleaks, or a core.hooksPath set by another tool, gets a notice instead of a change.
  • No surprise dependencies: Husky is added to package.json only when you turn on autoInstallHusky, and a prepare script it adds is husky || true.
ProjectWhat secret-guard does
Not a Git repository, or gitleaks not installedNothing
No hook configCreates .pre-commit-config.yaml or lefthook.yml (your pick, else pre-commit) and installs the hook
Config with gitleaks, hook not installedInstalls the hook
Hook installed but no config, as in a new worktreeCreates the config
Set up, but the config is not committedShows a notice with the git add command
Config without gitleaksShows a notice and leaves the file as it is
Both lefthook.yml and .pre-commit-config.yamlUses your pick and says which file to delete
package.json with HuskyAdds gitleaks to .husky/pre-commit and turns Husky on
package.json without HuskyUses Lefthook if installed, else shows the Husky install command (or installs it with autoInstallHusky)

Install

Install gitleaks and one hook manager:

brew install gitleaks pre-commit

Or, for Lefthook instead of pre-commit:

brew install gitleaks lefthook

Then, in a Claude Code terminal session, run:

/plugin install secret-guard --marketplace AnnihilationWizard/secret-guard
  1. Answer y to add the github:AnnihilationWizard/secret-guard marketplace.
  2. Choose a scope. The user scope loads the mod in every session.
  3. Claude Code confirms Installed secret-guard. Plugin is now active. The check runs in each session started after that.

To update later, run claude plugin update, then /reload-plugins.

git clone https://github.com/AnnihilationWizard/secret-guard.git
claude --plugin-dir ./secret-guard

To load a clone in every session, add it to the env block of ~/.claude/settings.json:

{
  "env": { "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/secret-guard" }
}

Usage

Start Claude Code in a Git project. If the project has no gitleaks hook, a notice says what secret-guard added. Then commit as usual. When gitleaks finds a secret in the staged changes, the commit stops and gitleaks prints the file, line and rule, with the secret redacted.

CommandEffect
/secret-guard-use lefthookUse Lefthook from now on and switch this project if secret-guard set it up with pre-commit
/secret-guard-use pre-commitThe same, the other way round
/secret-guard-use <manager> --remove-otherAlso uninstall the other manager: with Homebrew on macOS and Linux when it was installed that way, otherwise it says how (uv, pipx, pip, npm, Scoop or winget)

Without --remove-other, nothing is uninstalled: the command first says which repositories could be affected, so you can switch them before removing anything. A pick of a manager that is not installed is refused, with how to install it, so --remove-other can never remove the only manager you have.

The configs secret-guard writes:

# .pre-commit-config.yaml
repos:
  - repo: local
    hooks:
      - id: gitleaks
        name: gitleaks
        entry: gitleaks git --pre-commit --redact --staged --verbose
        language: system
        pass_filenames: false
# lefthook.yml
pre-commit:
  commands:
    gitleaks:
      run: gitleaks git --pre-commit --redact --staged --verbose

With gitleaks older than 8.19, the command is gitleaks protect --staged --redact --verbose.

To allow a false positive, add its fingerprint to a .gitleaksignore file in the project, or set an allowlist in .gitleaks.toml.

Configuration

OptionDefaultEffect
autoInstallHuskyfalseIn a JS/TS project without Husky, adds it as a dev dependency with the package manager the lockfile points to: pnpm, yarn, bun or npm. Changes package.json and the lockfile.

Change it from the /config menu, or in ~/.claude/settings.json:

{
  "pluginConfigs": {
    "secret-guard@secret-guard": {
      "options": { "autoInstallHusky": true }
    }
  }
}

In a pnpm workspace root, secret-guard installs with pnpm add -w. The pick from /secret-guard-use is kept across sessions.

Limitations

  • secret-guard sets up every Git project you open, including repositories you cloned only to read. Each project is set up once, and a notice names the change.
  • A worktree is checked when a session starts in it or Claude enters it with EnterWorktree. Moving into one with a shell cd is not detected; commit the config once and every worktree has it.
  • Only configs secret-guard wrote are switched to the other manager. A project's own config keeps its manager.
  • Teammates need gitleaks and the same hook manager.
  • Husky sets core.hooksPath, so hooks in .git/hooks stop running in that project, and pre-commit or Lefthook cannot install there.
  • Yarn Plug'n'Play projects have no node_modules/husky. secret-guard writes the hook and asks you to turn Husky on.
  • On Windows, a project folder whose path is longer than about 260 characters stops commands from starting there. secret-guard shows a notice that the project is not protected; move it to a shorter path.
  • The /plugin install command is available in terminal sessions only. A user-scope install also loads in the desktop app's Code tab.

Development

claude plugin validate .   # manifest, marketplace file and hooks module
claude plugin test .       # tests/*.test.ts against the engine

After Claude Code first loads the mod, it writes the API types to .claude-plugin/types/ (git-ignored). Type-check against them with TypeScript 5.4 or newer:

npx -p typescript@5 tsc -p .

Run claude --plugin-dir . to try changes. In an interactive session the folder is watched, and saving a file reloads the mod.

Project Structure

.claude-plugin/   plugin.json manifest and marketplace.json
hooks/            hooks.json, the session hooks, /secret-guard-use and the setup logic
tests/            tests for the setup logic
docs/images/      README illustration

Contributing

Bug reports and ideas are welcome. Read CONTRIBUTING.md before opening an issue or pull request, and follow SECURITY.md for security reports.

License

MIT License. Copyright © 2026 AnnihilationWizard.

Source 2 files
hooks/register.ts 147 lines
1import type { EngineInterface, Register } from 'claude-code'
2import {
3  BOTH_INSTALLED,
4  ensureGuard,
5  hostFrom,
6  isInstalled,
7  other,
8  locateProject,
9  notInstalledPick,
10  parseUseArgs,
11  removalWarning,
12  removeManager,
13  UNREACHABLE,
14  USE_USAGE,
15  type Manager,
16} from './guard.ts'
17
18const MANAGER_KEY = 'manager'
19
20// Repositories already checked in this session, so moving around one repository does not repeat a notice.
21const checked = new Set<string>()
22let isBothNoticeShown = false
23
24// Checks and /secret-guard-use run one at a time, so a switch never interleaves with a check's file
25// writes. Each pick bumps the generation, and a check that started before it drops its notice,
26// which describes the project as it was before the switch.
27let queue: Promise<unknown> = Promise.resolve()
28let generation = 0
29
30function inTurn<T>(work: () => Promise<T>): Promise<T> {
31  const run = queue.then(work, work)
32  queue = run.catch(() => undefined)
33  return run
34}
35
36async function preferredManager($: EngineInterface): Promise<Manager | undefined> {
37  const value = await $.store.get(MANAGER_KEY)
38  return value === 'pre-commit' || value === 'lefthook' ? value : undefined
39}
40
41async function check($: EngineInterface, cwd: string, autoInstallHusky: boolean): Promise<void> {
42  const startedIn = generation
43  const host = hostFrom($)
44  const location = await locateProject(host, cwd)
45  if (location.kind === 'none') return
46  // A folder where commands cannot start has no root to key on; its own path stands in.
47  const key = location.kind === 'repo' ? location.root : cwd
48  if (checked.has(key)) return
49  checked.add(key)
50  if (location.kind === 'unreachable') {
51    $.ui.toast(UNREACHABLE)
52    return
53  }
54  const preferred = await preferredManager($)
55  if (preferred === undefined && !isBothNoticeShown) {
56    if ((await isInstalled(host, 'pre-commit')) && (await isInstalled(host, 'lefthook'))) {
57      isBothNoticeShown = true
58      $.ui.toast(BOTH_INSTALLED)
59    }
60  }
61  const outcome = await ensureGuard(host, cwd, { autoInstallHusky, preferredManager: preferred })
62  if (startedIn !== generation) return
63  // Claude Code already heads each toast with the mod's name, so the text carries no prefix of its own.
64  if (outcome.kind === 'added' || outcome.kind === 'warn') $.ui.toast(outcome.message)
65}
66
67/** Runs the check after the current event, so it never holds up the session. */
68function inBackground($: EngineInterface, cwd: string, autoInstallHusky: boolean): void {
69  $.clock.after(0, () => {
70    void inTurn(() => check($, cwd, autoInstallHusky)).catch(error => $.ui.toast(`The check failed: ${String(error)}`))
71  })
72}
73
74/** /secret-guard-use: saves the pick, sets up this project with it, and removes the other manager on request. */
75async function use($: EngineInterface, args: string, autoInstallHusky: boolean): Promise<string> {
76  const parsed = parseUseArgs(args)
77  if (parsed === undefined) return USE_USAGE
78  const host = hostFrom($)
79  if (!(await isInstalled(host, parsed.manager))) return notInstalledPick(host, parsed.manager)
80  generation += 1
81  return inTurn(() => switchTo($, parsed.manager, parsed.removeOther, autoInstallHusky))
82}
83
84async function switchTo($: EngineInterface, manager: Manager, removeOther: boolean, autoInstallHusky: boolean): Promise<string> {
85  const parsed = { manager, removeOther }
86  await $.store.set(MANAGER_KEY, parsed.manager)
87  const host = hostFrom($)
88  const cwd = await $.session.cwd()
89
90  // Switch this project now, while the other manager is still installed to remove its hook.
91  const location = await locateProject(host, cwd)
92  let project = ''
93  if (location.kind !== 'none') {
94    checked.add(location.kind === 'repo' ? location.root : cwd)
95    const outcome = await ensureGuard(host, cwd, { autoInstallHusky, preferredManager: parsed.manager })
96    project = outcome.kind === 'added' || outcome.kind === 'warn' ? ` This project: ${outcome.message}` : ''
97  }
98
99  const unpicked = other(parsed.manager)
100  const machine = parsed.removeOther
101    ? await removeManager(host, unpicked)
102    : (await isInstalled(host, unpicked))
103      ? removalWarning(unpicked, parsed.manager)
104      : ''
105  // Claude Code heads the command's output with the mod's name, so the text does not repeat it.
106  return [`Picked ${parsed.manager}: new projects get it from now on.${project}`, machine].filter(s => s !== '').join('\n')
107}
108
109/** The worktree an EnterWorktree result names, if any. */
110export function worktreePath(result: unknown): string | undefined {
111  const path = (result as { result?: { worktreePath?: unknown } } | undefined)?.result?.worktreePath
112  return typeof path === 'string' && path !== '' ? path : undefined
113}
114
115export const register: Register = (on, options) => {
116  const autoInstallHusky = options.autoInstallHusky === true
117
118  on('session.start', async ($, e, next) => {
119    const started = await next(e)
120    await $.command.register({
121      name: 'secret-guard-use',
122      description: 'Pick pre-commit or Lefthook for secret-guard, and optionally remove the other',
123      argumentHint: 'pre-commit|lefthook [--remove-other]',
124    })
125    inBackground($, e.cwd, autoInstallHusky)
126    return started
127  })
128
129  on('command.run', { command: 'secret-guard-use' }, async ($, e) => ({ text: await use($, e.args, autoInstallHusky) }))
130    .catch(() => ({ text: 'secret-guard-use failed; nothing else was changed after the error.' }))
131
132  // A worktree shares the repository's installed hook but not an uncommitted config, so its commits
133  // would be blocked or skip the scan. Check it before the result goes back, so the config is there when work starts.
134  on('tool.call', { tool: 'EnterWorktree' }, async ($, e, next) => {
135    const result = await next(e)
136    const path = worktreePath(result)
137    if (path !== undefined) {
138      try {
139        await inTurn(() => check($, path, autoInstallHusky))
140      } catch (error) {
141        $.ui.toast(`The check failed: ${String(error)}`)
142      }
143    }
144    return result
145  }).catch(($, e, next) => next(e)) // never stand in the way of EnterWorktree: replay its own result
146}
147
hooks/guard.ts 642 lines
1import type { EngineInterface, ProcessRunResult } from 'claude-code'
2
3/** What the mod needs from the host: built from `$` in register, an in-memory fake in tests. */
4export type Host = {
5  /** Resolves undefined when the command cannot start (not installed) or times out. */
6  run: (argv: readonly string[], cwd: string, timeoutMs?: number) => Promise<ProcessRunResult | undefined>
7  exists: (path: string) => Promise<boolean>
8  read: (path: string) => Promise<string>
9  write: (path: string, text: string) => Promise<void>
10  /**
11   * A short folder of the mod's own to check tools from. Run from a project folder, a tool can
12   * fail to start for reasons of that folder (a Windows path past 260 characters), which must not
13   * read as the tool missing.
14   */
15  toolDir: string
16}
17
18export type Outcome =
19  | { kind: 'skip'; reason: string }
20  | { kind: 'ok' }
21  | { kind: 'added'; message: string }
22  | { kind: 'warn'; message: string }
23
24/** The two hook managers secret-guard sets up outside JS/TS projects. */
25export type Manager = 'pre-commit' | 'lefthook'
26
27export type GuardOptions = {
28  autoInstallHusky: boolean
29  /** The manager the user picked with /secret-guard-use, if any. */
30  preferredManager?: Manager
31}
32
33const MARK = '# secret-guard'
34
35export const PREPARE_SCRIPT = 'husky || true'
36
37const PRE_COMMIT_CONFIG = '.pre-commit-config.yaml'
38const HUSKY_HOOK = '.husky/pre-commit'
39const LEFTHOOK_CONFIG = 'lefthook.yml'
40
41/** Every main config name Lefthook reads, relative to the repository root. */
42const LEFTHOOK_CONFIGS = ['yml', 'yaml', 'toml', 'json', 'jsonc'].flatMap(ext => [
43  `lefthook.${ext}`,
44  `.lefthook.${ext}`,
45  `.config/lefthook.${ext}`,
46])
47
48/** Whether `path` (relative to the repository root) is committed or staged. */
49async function isTracked(host: Host, root: string, path: string): Promise<boolean> {
50  return succeeded(await host.run(['git', 'ls-files', '--error-unmatch', '--', path], root))
51}
52
53/** An uncommitted hook file exists only in this folder: other worktrees and fresh clones lack it. */
54const commitHint = (path: string): string =>
55  ` Commit ${path} so other worktrees and clones get it: git add ${path} && git commit`
56
57export function hostFrom($: EngineInterface): Host {
58  return {
59    run: async (argv, cwd, timeoutMs = 30_000) => {
60      try {
61        return await $.process.run(argv, { cwd, timeoutMs })
62      } catch {
63        return undefined
64      }
65    },
66    exists: path => $.fs.exists(path),
67    read: async path => (await $.fs.read(path)) as string,
68    write: (path, text) => $.fs.write(path, text),
69    toolDir: $.plugin.root,
70  }
71}
72
73const succeeded = (r: ProcessRunResult | undefined): r is ProcessRunResult =>
74  r !== undefined && r.exitCode === 0
75
76const failure = (r: ProcessRunResult | undefined): string =>
77  (r === undefined ? 'could not run' : r.stderr || r.stdout || `exit ${r.exitCode}`).trim().slice(0, 300)
78
79/**
80 * A file's text, or undefined when it is missing or cannot be read. Claude Code refuses some paths
81 * (a network location, a device) by throwing rather than answering false, and one such path must
82 * not stop the whole check.
83 */
84async function readText(host: Host, path: string): Promise<string | undefined> {
85  try {
86    return (await host.exists(path)) ? await host.read(path) : undefined
87  } catch {
88    return undefined
89  }
90}
91
92/** Whether a file exists, false when Claude Code refuses to look at the path. */
93async function fileExists(host: Host, path: string): Promise<boolean> {
94  try {
95    return await host.exists(path)
96  } catch {
97    return false
98  }
99}
100
101/** Whether a hook manager's command is installed and runs, checked from the mod's own folder. */
102export async function isInstalled(host: Host, manager: Manager): Promise<boolean> {
103  return succeeded(await host.run(manager === 'lefthook' ? ['lefthook', 'version'] : ['pre-commit', '--version'], host.toolDir))
104}
105
106/** Where `cwd` stands: in a repository, outside any, or in a folder where commands cannot start. */
107export type Location = { kind: 'repo'; root: string } | { kind: 'none' } | { kind: 'unreachable' }
108
109export async function locateProject(host: Host, cwd: string): Promise<Location> {
110  const top = await host.run(['git', 'rev-parse', '--show-toplevel'], cwd)
111  if (top === undefined) {
112    // git could not start here: either it is missing, or this folder stops it starting.
113    const git = await host.run(['git', '--version'], host.toolDir)
114    return succeeded(git) ? { kind: 'unreachable' } : { kind: 'none' }
115  }
116  return top.exitCode === 0 ? { kind: 'repo', root: top.stdout.trim() } : { kind: 'none' }
117}
118
119export const UNREACHABLE =
120  'secret-guard could not run commands in this folder, so this project is not protected. On Windows this happens when the folder path is longer than about 260 characters; move the project to a shorter path.'
121
122/** gitleaks 8.19 introduced `gitleaks git`; older releases only have `protect`. */
123export function scanCommand(versionOutput: string): string {
124  const m = /(\d+)\.(\d+)/.exec(versionOutput)
125  const isLegacy = m !== null && (Number(m[1]) < 8 || (Number(m[1]) === 8 && Number(m[2]) < 19))
126  return isLegacy
127    ? 'gitleaks protect --staged --redact --verbose'
128    : 'gitleaks git --pre-commit --redact --staged --verbose'
129}
130
131export function preCommitConfig(scan: string): string {
132  return `${MARK}: scan staged changes with the installed gitleaks before each commit
133repos:
134  - repo: local
135    hooks:
136      - id: gitleaks
137        name: gitleaks
138        entry: ${scan}
139        language: system
140        pass_filenames: false
141`
142}
143
144export function lefthookConfig(scan: string): string {
145  return `${MARK}: scan staged changes with the installed gitleaks before each commit
146pre-commit:
147  commands:
148    gitleaks:
149      run: ${scan}
150`
151}
152
153export function huskyBlock(scan: string): string {
154  return `${MARK}: scan staged changes for secrets before each commit
155if command -v gitleaks >/dev/null 2>&1; then
156  ${scan} || exit 1
157else
158  echo "gitleaks is not installed; skipping the secret scan (brew install gitleaks)" >&2
159fi
160`
161}
162
163/** Puts the block right after the hook's shebang, so it runs before any other command (an exit included). */
164export function prependBlock(existing: string | undefined, block: string): string {
165  if (existing === undefined || existing.trim() === '') return block
166  const lines = existing.split('\n')
167  if (lines[0]?.startsWith('#!')) {
168    return [lines[0], block.trimEnd(), ...lines.slice(1)].join('\n')
169  }
170  return `${block}${existing}`
171}
172
173type PackageManager = { name: string; add: string[] }
174
175async function packageManager(host: Host, root: string): Promise<PackageManager> {
176  if (await fileExists(host, `${root}/pnpm-lock.yaml`)) {
177    // pnpm refuses to add to a workspace root unless -w is given.
178    const workspaceRoot = (await fileExists(host, `${root}/pnpm-workspace.yaml`)) ? ['-w'] : []
179    return { name: 'pnpm', add: ['pnpm', 'add', ...workspaceRoot, '-D', 'husky'] }
180  }
181  if (await fileExists(host, `${root}/yarn.lock`)) return { name: 'yarn', add: ['yarn', 'add', '-D', 'husky'] }
182  if ((await fileExists(host, `${root}/bun.lockb`)) || (await fileExists(host, `${root}/bun.lock`))) {
183    return { name: 'bun', add: ['bun', 'add', '-d', 'husky'] }
184  }
185  return { name: 'npm', add: ['npm', 'install', '--save-dev', 'husky'] }
186}
187
188/**
189 * The core.hooksPath set in the project's own config files (local, worktree, global, system), from
190 * `git config --show-scope --get-all` output. Claude Code runs a mod's git with
191 * `-c core.hooksPath=/dev/null`, which shows up with the `command` scope and applies only to that
192 * one call, so it is ignored.
193 */
194export function configuredHooksPath(showScopeOutput: string): string | undefined {
195  let found: string | undefined
196  for (const line of showScopeOutput.split('\n')) {
197    const tab = line.indexOf('\t')
198    if (tab < 0) continue
199    const scope = line.slice(0, tab)
200    const value = line.slice(tab + 1).trim()
201    if (scope !== 'command' && value !== '') found = value
202  }
203  return found
204}
205
206async function hooksPathSetting(host: Host, root: string): Promise<string | undefined> {
207  const r = await host.run(['git', 'config', '--show-scope', '--get-all', 'core.hooksPath'], root)
208  return succeeded(r) ? configuredHooksPath(r.stdout) : undefined
209}
210
211/**
212 * The pre-commit hook in the repository's shared hooks folder, which worktrees and the main
213 * checkout share. Found from `--git-common-dir`, not `--git-path hooks/pre-commit`: the latter
214 * follows core.hooksPath, which Claude Code sets to the null device for a mod's git, and so names
215 * `/dev/null/pre-commit` or `\\.\NUL\pre-commit` instead of the real hook. A project that sets
216 * core.hooksPath itself never gets here: both managers stop on it first.
217 */
218async function installedHook(host: Host, root: string): Promise<string | undefined> {
219  const commonDir = await host.run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], root)
220  return succeeded(commonDir) ? readText(host, `${commonDir.stdout.trim()}/hooks/pre-commit`) : undefined
221}
222
223const isPreCommitHook = (hook: string | undefined): boolean => hook !== undefined && /generated by pre-commit/i.test(hook)
224const isLefthookHook = (hook: string | undefined): boolean => hook !== undefined && /lefthook/.test(hook)
225
226async function ensurePreCommit(host: Host, root: string, scan: string): Promise<Outcome> {
227  if (!(await isInstalled(host, 'pre-commit'))) {
228    return { kind: 'skip', reason: 'pre-commit is not installed' }
229  }
230
231  const configPath = `${root}/${PRE_COMMIT_CONFIG}`
232  const config = await readText(host, configPath)
233  if (config !== undefined && !/gitleaks/.test(config)) {
234    return {
235      kind: 'warn',
236      message: `${PRE_COMMIT_CONFIG} has no gitleaks hook. It was left as it is; add the hook yourself.`,
237    }
238  }
239
240  const hooksPath = await hooksPathSetting(host, root)
241  if (hooksPath !== undefined) {
242    return {
243      kind: 'warn',
244      message: `core.hooksPath is set to ${hooksPath}, so pre-commit install would refuse to run. Nothing was changed.`,
245    }
246  }
247
248  const isHookInstalled = isPreCommitHook(await installedHook(host, root))
249  if (config !== undefined && isHookInstalled) {
250    return (await isTracked(host, root, PRE_COMMIT_CONFIG))
251      ? { kind: 'ok' }
252      : { kind: 'warn', message: `${PRE_COMMIT_CONFIG} is not committed.${commitHint(PRE_COMMIT_CONFIG)}` }
253  }
254
255  if (config === undefined) await host.write(configPath, preCommitConfig(scan))
256
257  if (!isHookInstalled) {
258    const install = await host.run(['pre-commit', 'install'], root, 60_000)
259    if (!succeeded(install)) {
260      return { kind: 'warn', message: `pre-commit install failed: ${failure(install)}` }
261    }
262  }
263  const done = config !== undefined
264    ? 'Ran pre-commit install. The gitleaks hook is active.'
265    : isHookInstalled
266      ? `The pre-commit hook was installed but ${PRE_COMMIT_CONFIG} was missing, so commits were blocked. Created it with gitleaks.`
267      : `Created ${PRE_COMMIT_CONFIG} (gitleaks) and ran pre-commit install.`
268  const hint = (await isTracked(host, root, PRE_COMMIT_CONFIG)) ? '' : commitHint(PRE_COMMIT_CONFIG)
269  return { kind: 'added', message: `${done}${hint}` }
270}
271
272async function ensureLefthook(host: Host, root: string, scan: string, existing: string | undefined): Promise<Outcome> {
273  if (!(await isInstalled(host, 'lefthook'))) {
274    return existing === undefined
275      ? { kind: 'skip', reason: 'lefthook is not installed' }
276      : {
277          kind: 'warn',
278          message: `This project uses Lefthook (${existing}), but lefthook is not installed. Install it, then run lefthook install.`,
279        }
280  }
281
282  const file = existing ?? LEFTHOOK_CONFIG
283  const configPath = `${root}/${file}`
284  const config = existing === undefined ? undefined : await host.read(configPath)
285  if (config !== undefined && !/gitleaks/.test(config)) {
286    return {
287      kind: 'warn',
288      message: `${file} has no gitleaks command. It was left as it is; add one under pre-commit yourself.`,
289    }
290  }
291
292  const hooksPath = await hooksPathSetting(host, root)
293  if (hooksPath !== undefined) {
294    return {
295      kind: 'warn',
296      message: `core.hooksPath is set to ${hooksPath}, so Lefthook would install its hooks there. Nothing was changed.`,
297    }
298  }
299
300  const isHookInstalled = isLefthookHook(await installedHook(host, root))
301  if (config !== undefined && isHookInstalled) {
302    return (await isTracked(host, root, file))
303      ? { kind: 'ok' }
304      : { kind: 'warn', message: `${file} is not committed.${commitHint(file)}` }
305  }
306
307  // Written before lefthook install, which otherwise creates an empty lefthook.yml of its own.
308  if (config === undefined) await host.write(configPath, lefthookConfig(scan))
309
310  if (!isHookInstalled) {
311    const install = await host.run(['lefthook', 'install'], root, 60_000)
312    if (!succeeded(install)) {
313      return { kind: 'warn', message: `lefthook install failed: ${failure(install)}` }
314    }
315  }
316  const done = config !== undefined
317    ? 'Ran lefthook install. The gitleaks command is active.'
318    : isHookInstalled
319      ? `The Lefthook hook was installed but ${file} was missing, so commits ran without a secret scan. Created it with gitleaks.`
320      : `Created ${file} (gitleaks) and ran lefthook install.`
321  const hint = (await isTracked(host, root, file)) ? '' : commitHint(file)
322  return { kind: 'added', message: `${done}${hint}` }
323}
324
325type PackageJson = {
326  dependencies?: Record<string, string>
327  devDependencies?: Record<string, string>
328  scripts?: Record<string, string>
329}
330
331async function ensureHusky(host: Host, root: string, scan: string, options: GuardOptions): Promise<Outcome> {
332  const hookPath = `${root}/${HUSKY_HOOK}`
333  const hook = await readText(host, hookPath)
334  const hooksPath = await hooksPathSetting(host, root)
335  const isHuskyActive = hooksPath !== undefined && /\.husky/.test(hooksPath)
336
337  if (hook !== undefined && /gitleaks/.test(hook)) {
338    if (isHuskyActive) {
339      return (await isTracked(host, root, HUSKY_HOOK))
340        ? { kind: 'ok' }
341        : { kind: 'warn', message: `${HUSKY_HOOK} is not committed.${commitHint(HUSKY_HOOK)}` }
342    }
343    return {
344      kind: 'warn',
345      message: '.husky/pre-commit already runs gitleaks, but Husky is not active. Run the project install, which runs the prepare script.',
346    }
347  }
348
349  let pkg: PackageJson
350  try {
351    pkg = JSON.parse(await host.read(`${root}/package.json`)) as PackageJson
352  } catch {
353    return { kind: 'warn', message: 'package.json could not be parsed. Nothing was changed.' }
354  }
355
356  const pm = await packageManager(host, root)
357  const hasHusky = hasHuskyDependency(pkg)
358  if (!hasHusky) {
359    if (!options.autoInstallHusky) {
360      return {
361        kind: 'warn',
362        message: `This JS/TS project has no Husky. Run \`${pm.add.join(' ')}\`, or turn on secret-guard's Auto-install Husky option.`,
363      }
364    }
365    const added = await runPackageManager(host, pm.add, root, 600_000)
366    if (!succeeded(added)) {
367      return { kind: 'warn', message: `Installing Husky with ${pm.name} failed: ${failure(added)}` }
368    }
369  }
370
371  const prepare = pkg.scripts?.prepare
372  if (prepare === undefined) {
373    // `|| true`: installs without dev dependencies (npm ci --omit=dev, Docker) have no husky, and prepare must not fail them.
374    // Read again: installing Husky above has just changed package.json.
375    const updated = withPrepareScript(await host.read(`${root}/package.json`))
376    if (updated === undefined) return { kind: 'warn', message: 'package.json could not be parsed. Nothing was changed.' }
377    await host.write(`${root}/package.json`, updated)
378  }
379
380  await host.write(hookPath, prependBlock(hook, huskyBlock(scan)))
381
382  if (!isHuskyActive) {
383    const huskyBin = await huskyEntry(host, root)
384    const activated = huskyBin === undefined ? undefined : await host.run(['node', huskyBin], root)
385    if (!succeeded(activated)) {
386      return {
387        kind: 'warn',
388        message: 'Wrote .husky/pre-commit, but could not turn Husky on (are node_modules installed?). Run the project install.',
389      }
390    }
391  }
392
393  const notes = [
394    hasHusky ? undefined : `Installed Husky with ${pm.name}`,
395    prepare === undefined
396      ? 'added a prepare script'
397      : /husky/.test(prepare) ? undefined : `the prepare script does not run husky (${prepare}), so teammates must turn it on after cloning`,
398    'added gitleaks to .husky/pre-commit',
399  ].filter((n): n is string => n !== undefined)
400  const sentence = notes.join('; ')
401  const hint = (await isTracked(host, root, HUSKY_HOOK)) ? '' : commitHint(HUSKY_HOOK)
402  return { kind: 'added', message: `${sentence.charAt(0).toUpperCase()}${sentence.slice(1)}.${hint}` }
403}
404
405/**
406 * package.json with `scripts.prepare` set to PREPARE_SCRIPT, keeping its indentation, key order,
407 * line endings and final newline; undefined when it is not a JSON object. Written by the mod
408 * itself rather than through `npm pkg set`, which on Windows is a `.cmd` launcher.
409 */
410export function withPrepareScript(text: string): string | undefined {
411  let data: unknown
412  try {
413    data = JSON.parse(text)
414  } catch {
415    return undefined
416  }
417  if (typeof data !== 'object' || data === null || Array.isArray(data)) return undefined
418  const manifest = data as Record<string, unknown>
419  const scripts = typeof manifest.scripts === 'object' && manifest.scripts !== null ? manifest.scripts : {}
420  manifest.scripts = { ...scripts, prepare: PREPARE_SCRIPT }
421  const indent = /^[ \t]+(?=")/m.exec(text)?.[0] ?? '  '
422  const eol = text.includes('\r\n') ? '\r\n' : '\n'
423  const body = JSON.stringify(manifest, null, indent).replace(/\n/g, eol)
424  return /\r?\n$/.test(text) ? `${body}${eol}` : body
425}
426
427/**
428 * Runs a Node package manager. On Windows npm, pnpm and yarn are `.cmd` launchers that a process
429 * cannot start without a shell, so a run that could not start is tried again through cmd.
430 */
431async function runPackageManager(
432  host: Host,
433  argv: readonly string[],
434  cwd: string,
435  timeoutMs: number,
436): Promise<ProcessRunResult | undefined> {
437  return (await host.run(argv, cwd, timeoutMs)) ?? host.run(['cmd', '/d', '/s', '/c', ...argv], cwd, timeoutMs)
438}
439
440const hasHuskyDependency = (pkg: PackageJson): boolean =>
441  pkg.devDependencies?.husky !== undefined || pkg.dependencies?.husky !== undefined
442
443async function readPackageJson(host: Host, root: string): Promise<PackageJson | undefined> {
444  try {
445    return JSON.parse(await host.read(`${root}/package.json`)) as PackageJson
446  } catch {
447    return undefined
448  }
449}
450
451async function findLefthookConfig(host: Host, root: string): Promise<string | undefined> {
452  for (const name of LEFTHOOK_CONFIGS) {
453    if (await fileExists(host, `${root}/${name}`)) return name
454  }
455  return undefined
456}
457
458/**
459 * The script Husky's package names as its `husky` command, run with `node`. Going through the
460 * package rather than `node_modules/.bin/husky` works on Windows too, where that is a `.cmd`
461 * launcher a process cannot start without a shell.
462 */
463async function huskyEntry(host: Host, root: string): Promise<string | undefined> {
464  const manifest = await readText(host, `${root}/node_modules/husky/package.json`)
465  if (manifest === undefined) return undefined
466  try {
467    const bin = (JSON.parse(manifest) as { bin?: string | Record<string, string> }).bin
468    const entry = typeof bin === 'string' ? bin : bin?.husky
469    return entry === undefined ? undefined : `${root}/node_modules/husky/${entry.replace(/^\.\//, '')}`
470  } catch {
471    return undefined
472  }
473}
474
475/** A config secret-guard wrote itself, which it may replace when the user picks the other manager. */
476const isOwn = (config: string | undefined): boolean => config !== undefined && config.startsWith(MARK)
477
478/** Removes the other manager's hook before switching, while that manager is still installed. */
479async function uninstallHook(host: Host, root: string, manager: Manager): Promise<void> {
480  const hook = await installedHook(host, root)
481  const isTheirs = manager === 'lefthook' ? isLefthookHook(hook) : isPreCommitHook(hook)
482  if (isTheirs && (await isInstalled(host, manager))) await host.run([manager, 'uninstall'], root, 60_000)
483}
484
485const configName = (manager: Manager, lefthookFile: string | undefined): string =>
486  manager === 'lefthook' ? (lefthookFile ?? LEFTHOOK_CONFIG) : PRE_COMMIT_CONFIG
487
488/** Adds a note to an outcome, ahead of any commit hint so the `git add` command stays last. */
489function withNote(outcome: Outcome, note: string | undefined): Outcome {
490  if (note === undefined || outcome.kind === 'skip') return outcome
491  if (outcome.kind === 'ok') return { kind: 'warn', message: note }
492  const hintAt = outcome.message.indexOf(' Commit ')
493  const message = hintAt < 0
494    ? `${outcome.message} ${note}`
495    : `${outcome.message.slice(0, hintAt)} ${note}${outcome.message.slice(hintAt)}`
496  return { ...outcome, message }
497}
498
499export async function ensureGuard(host: Host, cwd: string, options: GuardOptions): Promise<Outcome> {
500  const gitleaks = await host.run(['gitleaks', 'version'], host.toolDir)
501  if (!succeeded(gitleaks)) return { kind: 'skip', reason: 'gitleaks is not installed' }
502
503  const location = await locateProject(host, cwd)
504  if (location.kind === 'unreachable') return { kind: 'warn', message: UNREACHABLE }
505  if (location.kind === 'none') return { kind: 'skip', reason: 'not a Git repository' }
506  const root = location.root
507
508  const scan = scanCommand(gitleaks.stdout)
509  const lefthookFile = await findLefthookConfig(host, root)
510  const lefthookText = lefthookFile === undefined ? undefined : await readText(host, `${root}/${lefthookFile}`)
511  const preCommitText = await readText(host, `${root}/${PRE_COMMIT_CONFIG}`)
512  const available: Record<Manager, boolean> = {
513    'pre-commit': await isInstalled(host, 'pre-commit'),
514    lefthook: await isInstalled(host, 'lefthook'),
515  }
516  // A pick only counts while that manager is installed; otherwise projects keep what they have.
517  const preferred = options.preferredManager !== undefined && available[options.preferredManager]
518    ? options.preferredManager
519    : undefined
520
521  // A project that already has a hook config keeps its manager, unless secret-guard wrote that
522  // config itself and the user picked the other manager.
523  let manager: Manager | 'husky' | undefined
524  let note: string | undefined
525  if (lefthookFile !== undefined && preCommitText !== undefined) {
526    manager = preferred ?? (available.lefthook || !available['pre-commit'] ? 'lefthook' : 'pre-commit')
527    const other = manager === 'lefthook' ? PRE_COMMIT_CONFIG : lefthookFile
528    note = `This project has both ${lefthookFile} and ${PRE_COMMIT_CONFIG}; secret-guard used ${manager}. Keep one and delete ${other}.`
529  } else if (lefthookFile !== undefined) {
530    manager = preferred === 'pre-commit' && isOwn(lefthookText) ? 'pre-commit' : 'lefthook'
531  } else if (preCommitText !== undefined) {
532    manager = preferred === 'lefthook' && isOwn(preCommitText) ? 'lefthook' : 'pre-commit'
533  } else {
534    const pkg = await readPackageJson(host, root)
535    const isJs = await fileExists(host, `${root}/package.json`)
536    const usesHusky = pkg !== undefined && hasHuskyDependency(pkg)
537    if (isJs && (usesHusky || options.autoInstallHusky || !available.lefthook || preferred === 'pre-commit')) {
538      manager = 'husky'
539    } else if (isJs) {
540      manager = 'lefthook' // a global binary: no dependency to add to the project
541    } else {
542      manager = preferred ?? (available['pre-commit'] ? 'pre-commit' : available.lefthook ? 'lefthook' : undefined)
543    }
544  }
545
546  if (manager === undefined) return { kind: 'skip', reason: 'neither pre-commit nor lefthook is installed' }
547  if (manager === 'husky') return ensureHusky(host, root, scan, options)
548
549  // Switching away from a config secret-guard wrote: remove the old manager's hook first.
550  const switchedFrom: Manager | undefined =
551    manager === 'lefthook' && isOwn(preCommitText) && lefthookFile === undefined ? 'pre-commit'
552      : manager === 'pre-commit' && isOwn(lefthookText) && preCommitText === undefined ? 'lefthook'
553        : undefined
554  if (switchedFrom !== undefined) {
555    await uninstallHook(host, root, switchedFrom)
556    note = `Switched this project from ${switchedFrom} to ${manager}; delete ${configName(switchedFrom, lefthookFile)}, which secret-guard wrote.`
557  }
558
559  const outcome = manager === 'lefthook'
560    ? await ensureLefthook(host, root, scan, switchedFrom === 'lefthook' ? undefined : lefthookFile)
561    : await ensurePreCommit(host, root, scan)
562  return withNote(outcome, note)
563}
564
565/** Shown once per session when both managers are installed and the user has not picked one. */
566export const BOTH_INSTALLED =
567  'Both pre-commit and Lefthook are installed. Pick one hook manager with /secret-guard-use pre-commit or /secret-guard-use lefthook; secret-guard can then help remove the other.'
568
569/** How each manager is removed by hand, listed for the platform first: Homebrew does not exist on Windows. */
570const REMOVE_BY_HAND: Record<'unix' | 'windows', Record<Manager, string>> = {
571  unix: {
572    'pre-commit': 'brew uninstall pre-commit, uv tool uninstall pre-commit, pipx uninstall pre-commit or pip uninstall pre-commit',
573    lefthook: 'brew uninstall lefthook or npm uninstall -g lefthook',
574  },
575  windows: {
576    'pre-commit': 'uv tool uninstall pre-commit, pipx uninstall pre-commit or pip uninstall pre-commit',
577    lefthook: 'scoop uninstall lefthook, winget uninstall evilmartians.lefthook or npm uninstall -g lefthook',
578  },
579}
580
581/** Whether the mod runs on Windows, told from its own folder's path (a drive letter, or backslashes). */
582export const isWindows = (host: Host): boolean => /^[A-Za-z]:[\\/]/.test(host.toolDir) || host.toolDir.includes('\\')
583
584export const other = (manager: Manager): Manager => (manager === 'lefthook' ? 'pre-commit' : 'lefthook')
585
586export function parseUseArgs(args: string): { manager: Manager; removeOther: boolean } | undefined {
587  const words = args.trim().split(/\s+/).filter(w => w !== '')
588  const manager = words.find(w => w === 'pre-commit' || w === 'lefthook') as Manager | undefined
589  const rest = words.filter(w => w !== manager)
590  if (manager === undefined || rest.some(w => w !== '--remove-other')) return undefined
591  return { manager, removeOther: rest.includes('--remove-other') }
592}
593
594/** How each manager is installed, listed for the platform first. */
595const INSTALL: Record<'unix' | 'windows', Record<Manager, string>> = {
596  unix: {
597    'pre-commit': 'brew install pre-commit, uv tool install pre-commit or pipx install pre-commit',
598    lefthook: 'brew install lefthook or npm install -g lefthook',
599  },
600  windows: {
601    'pre-commit': 'uv tool install pre-commit, pipx install pre-commit or pip install pre-commit',
602    lefthook: 'scoop install lefthook, winget install evilmartians.lefthook or npm install -g lefthook',
603  },
604}
605
606/**
607 * Why a pick of a manager that is not installed is refused. Kept, it would not count (a pick
608 * only counts while installed), and with --remove-other it would uninstall the only manager left.
609 */
610export function notInstalledPick(host: Host, manager: Manager): string {
611  const ways = INSTALL[isWindows(host) ? 'windows' : 'unix'][manager]
612  return `${manager} is not installed, so the pick was not kept and nothing was changed. Install it with one of: ${ways}; then run /secret-guard-use ${manager} again.`
613}
614
615export const USE_USAGE =
616  'Usage: /secret-guard-use pre-commit|lefthook [--remove-other]. Picks the hook manager secret-guard sets up; --remove-other then uninstalls the other one.'
617
618/**
619 * Removes the manager the user did not pick from this machine: with Homebrew when it was installed
620 * that way, otherwise says how to remove it by hand.
621 */
622export async function removeManager(host: Host, manager: Manager): Promise<string> {
623  if (!(await isInstalled(host, manager))) return `${manager} is not installed, so there is nothing to remove.`
624  const cwd = host.toolDir
625  if (isWindows(host)) {
626    return `${manager} was left in place: on Windows secret-guard does not uninstall tools itself. Remove it with one of: ${REMOVE_BY_HAND.windows[manager]}.`
627  }
628  const brew = await host.run(['brew', 'list', '--versions', manager], cwd)
629  if (!succeeded(brew) || brew.stdout.trim() === '') {
630    return `${manager} was not installed with Homebrew, so it was left in place. Remove it with one of: ${REMOVE_BY_HAND.unix[manager]}.`
631  }
632  const removed = await host.run(['brew', 'uninstall', manager], cwd, 300_000)
633  return succeeded(removed)
634    ? `Removed ${manager} with Homebrew.`
635    : `brew uninstall ${manager} failed: ${failure(removed)}`
636}
637
638/** What happens to other repositories once a manager is removed, said before the user confirms. */
639export function removalWarning(manager: Manager, picked: Manager): string {
640  return `${manager} is still installed. Hooks it installed in other repositories may fail or stop scanning once it is removed. Open a Claude session in each of them first: secret-guard switches the ones it set up to ${picked}, and tells you about the rest. When ready, run /secret-guard-use ${picked} --remove-other.`
641}
642