diff --git a/.claude/settings.json b/.claude/settings.json index d0e7b53..dfa13b0 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -16,7 +16,11 @@ "Read(~/.aws/**)", "Read(~/.gnupg/**)", "Edit(.claude/settings.json)", - "Edit(.claude/settings.local.json)" + "Edit(.claude/settings.local.json)", + "Bash(git push origin main:*)", + "Bash(git push origin HEAD:main:*)", + "Bash(git push * main:*)", + "Bash(git push *:main:*)" ], "blockReadsOutsideWorkingDirectories": true, "ask": [ diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..cf89b42 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,10 @@ +#!/bin/sh +# Refuse commits (and, via pre-merge-commit, merge commits) while main is checked out. +# Cherry-pick, revert and fast-forward merges don't run these hooks; pre-push still stops +# their result from reaching the remote. +name=${1:-pre-commit} +if [ "$(git symbolic-ref --short -q HEAD)" = "main" ]; then + echo "$name: committing on main is not allowed; create a branch first." >&2 + exit 1 +fi +exit 0 diff --git a/.githooks/pre-merge-commit b/.githooks/pre-merge-commit new file mode 100755 index 0000000..e0d9152 --- /dev/null +++ b/.githooks/pre-merge-commit @@ -0,0 +1,2 @@ +#!/bin/sh +exec sh "$(dirname "$0")/pre-commit" pre-merge-commit diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100755 index 0000000..91b085a --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,11 @@ +#!/bin/sh +# Reject any push that would create, update or delete main on the remote, however the +# command is spelled (bare `git push`, HEAD:main, +main, refs/heads/main, --all, --mirror). +# Only a human merges into main, through a PR in Gitea. +while read -r local_ref local_sha remote_ref remote_sha; do + if [ "$remote_ref" = "refs/heads/main" ]; then + echo "pre-push: pushing to main is not allowed; push a branch and open a PR instead." >&2 + exit 1 + fi +done +exit 0 diff --git a/CLAUDE.md b/CLAUDE.md index 2117ff2..88e2965 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3,7 +3,8 @@ A tiny zero-dependency Node.js todo CLI, used as a sandbox for trying Claude Code features. ## Commands -- `npm test` — run the test suite (built-in `node:test`, no install needed) +- `npm install` — once per clone (no dependencies): installs the git hooks that block commits and pushes to `main`. If it fails in the sandbox, ask the human to run it. +- `npm test` — run the test suite (built-in `node:test`) - `npm start -- add "something"` / `npm start -- ls` — run the CLI (data in `todos.json`, override with `TODO_FILE`) ## Conventions diff --git a/README.md b/README.md index ce35e50..5b21e72 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ A tiny todo CLI that exists to try out [Claude Code](https://docs.claude.com/en/docs/claude-code) features. ```sh +npm install # once per clone, and after changing .githooks/: installs the git hooks npm test npm start -- add "try Claude Code" npm start -- done 1 @@ -18,6 +19,14 @@ npm start -- ls | `.claude/skills/changelog/` | A custom skill — run `/changelog` | | `.claude/agents/test-writer.md` | A custom subagent — "use the test-writer agent to…" | +### Protecting `main` +Changes reach `main` only through a PR that a human merges. Three layers, strongest first: +1. **Gitea branch protection** on `main` (set in the repo settings on code.westerkam.org): the only layer that can't be bypassed from a clone. +2. **Git hooks** from `.githooks/`, copied into `.git/hooks` by `npm install` (`scripts/install-hooks.sh`). `pre-push` rejects any push that would update `main`, however it's spelled. `pre-commit` / `pre-merge-commit` refuse ordinary and merge commits while `main` is checked out; cherry-pick, revert and fast-forwards skip them, but pre-push still stops the result leaving the machine. The hooks are copied, not linked with `core.hooksPath`, because Claude Code's sandbox can't write inside `.git/`: a sandboxed command can't rewrite the installed hooks, which matters because `git commit` / `git push` run outside the sandbox. Anyone can still skip them with `--no-verify`. +3. **Claude Code deny rules** in `.claude/settings.json` for `git push … main`: a quick early stop, but they match command text, so they're easy to get around. + +Layers 2 and 3 live on your machine and can be bypassed by whoever runs the commands; only layer 1 can't. + ## Things to try - *"There's a bug in how ids are assigned after removing a todo — find it and fix it with a test."* diff --git a/package.json b/package.json index 150c342..63ec3fc 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,8 @@ "bin": { "todo": "./src/cli.js" }, "scripts": { "start": "node src/cli.js", - "test": "node --test" + "test": "node --test", + "prepare": "sh scripts/install-hooks.sh" }, "engines": { "node": ">=20" }, "license": "MIT" diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.sh new file mode 100755 index 0000000..4aad880 --- /dev/null +++ b/scripts/install-hooks.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# Copy the hooks in .githooks/ into git's own hooks directory. They are copied rather than +# enabled with core.hooksPath on purpose: Claude Code's sandbox can't write inside .git/, so +# a sandboxed command can't rewrite the installed hooks, even though git commit and git push +# (and so their hooks) run outside the sandbox. Re-run after changing anything in .githooks/. +set -e +cd "$(dirname "$0")/.." +# Use the repo's own hooks directory, not `git rev-parse --git-path hooks`: that follows a +# (possibly global) core.hooksPath and would install these hooks for every repo. +if ! common=$(git rev-parse --git-common-dir 2>/dev/null); then + echo "install-hooks: not a git checkout; skipping." >&2 + exit 0 +fi +hooks="$common/hooks" +mkdir -p "$hooks" +for hook in .githooks/*; do + cp "$hook" "$hooks/" + chmod +x "$hooks/$(basename "$hook")" +done +echo "install-hooks: installed $(ls .githooks | tr '\n' ' ')into $hooks" diff --git a/test/hooks.test.js b/test/hooks.test.js new file mode 100644 index 0000000..e49d8b3 --- /dev/null +++ b/test/hooks.test.js @@ -0,0 +1,98 @@ +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, cpSync, statSync, writeFileSync, existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const ROOT = fileURLToPath(new URL("../", import.meta.url)); +const HOOKS = join(ROOT, ".githooks"); +const SHA = "1".repeat(40); +const ZERO = "0".repeat(40); + +// Run git and the hooks without inheriting GIT_DIR & co, e.g. when tests run from inside a hook. +const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith("GIT_"))); +const run = (cmd, args, opts = {}) => spawnSync(cmd, args, { env, encoding: "utf8", ...opts }); + +const dirs = []; +after(() => dirs.forEach((d) => rmSync(d, { recursive: true, force: true }))); + +function repoOn(branch) { + const dir = mkdtempSync(join(tmpdir(), "todo-hooks-")); + dirs.push(dir); + const init = run("git", ["init", "-q", "-b", branch, dir]); + assert.equal(init.status, 0, `git init failed: ${init.stderr}`); + return dir; +} + +function prePush(...lines) { + return run("sh", [join(HOOKS, "pre-push"), "origin", "git@example:repo.git"], { + input: lines.map((l) => l + "\n").join(""), + }); +} + +for (const [label, line] of [ + ["an update", `refs/heads/fix/x ${SHA} refs/heads/main ${SHA}`], + ["a new ref", `refs/heads/fix/x ${SHA} refs/heads/main ${ZERO}`], + ["a deletion", `(delete) ${ZERO} refs/heads/main ${SHA}`], +]) { + test(`pre-push rejects ${label} of main`, () => { + const res = prePush(line); + assert.equal(res.status, 1); + assert.match(res.stderr, /pushing to main is not allowed/); + }); +} + +test("pre-push rejects --all style pushes that include main", () => { + const res = prePush(`refs/heads/fix/x ${SHA} refs/heads/fix/x ${SHA}`, `refs/heads/main ${SHA} refs/heads/main ${SHA}`); + assert.equal(res.status, 1); +}); + +test("pre-push allows other branches, including ones named like main", () => { + const res = prePush(`refs/heads/fix/x ${SHA} refs/heads/fix/x ${ZERO}`, `refs/heads/maintenance ${SHA} refs/heads/maintenance ${SHA}`); + assert.equal(res.status, 0); +}); + +for (const hook of ["pre-commit", "pre-merge-commit"]) { + test(`${hook} rejects main, names itself, and allows other branches`, () => { + const onMain = run("sh", [join(HOOKS, hook)], { cwd: repoOn("main") }); + assert.equal(onMain.status, 1); + assert.match(onMain.stderr, new RegExp(`^${hook}: committing on main is not allowed`)); + assert.equal(run("sh", [join(HOOKS, hook)], { cwd: repoOn("fix/x") }).status, 0); + }); +} + +test("install-hooks copies every hook into .git/hooks as an executable", () => { + const repo = repoOn("fix/x"); + cpSync(join(ROOT, "scripts"), join(repo, "scripts"), { recursive: true }); + cpSync(HOOKS, join(repo, ".githooks"), { recursive: true }); + const res = run("sh", [join(repo, "scripts", "install-hooks.sh")]); + assert.equal(res.status, 0, res.stderr); + for (const hook of ["pre-push", "pre-commit", "pre-merge-commit"]) { + assert.ok(statSync(join(repo, ".git", "hooks", hook)).mode & 0o100, `${hook} is not executable`); + } +}); + +test("install-hooks ignores a global core.hooksPath", () => { + const repo = repoOn("fix/x"); + const elsewhere = mkdtempSync(join(tmpdir(), "todo-hooks-")); + dirs.push(elsewhere); + const globalConfig = join(elsewhere, "gitconfig"); + writeFileSync(globalConfig, `[core]\n\thooksPath = ${elsewhere}\n`); + cpSync(join(ROOT, "scripts"), join(repo, "scripts"), { recursive: true }); + cpSync(HOOKS, join(repo, ".githooks"), { recursive: true }); + const res = run("sh", [join(repo, "scripts", "install-hooks.sh")], { env: { ...env, GIT_CONFIG_GLOBAL: globalConfig } }); + assert.equal(res.status, 0, res.stderr); + assert.ok(existsSync(join(repo, ".git", "hooks", "pre-push"))); + assert.equal(existsSync(join(elsewhere, "pre-push")), false); +}); + +test("install-hooks skips cleanly outside a git checkout", () => { + const dir = mkdtempSync(join(tmpdir(), "todo-hooks-")); + dirs.push(dir); + cpSync(join(ROOT, "scripts"), join(dir, "scripts"), { recursive: true }); + const res = run("sh", [join(dir, "scripts", "install-hooks.sh")], { env: { ...env, GIT_CEILING_DIRECTORIES: tmpdir() } }); + assert.equal(res.status, 0); + assert.match(res.stderr, /not a git checkout; skipping/); +});