diff --git a/docs/CODE_REVIEW_LENSES.md b/docs/CODE_REVIEW_LENSES.md new file mode 100644 index 00000000..9cfc5fc5 --- /dev/null +++ b/docs/CODE_REVIEW_LENSES.md @@ -0,0 +1,170 @@ +# Code review lenses + +A set of focused, threshold-driven review lenses an AI coding agent (or a human +reviewer) can apply to a diff. They are deliberately narrow and verifiable: each +lens reports concrete findings with `file:line`, a severity, and a fix — not vibes. + +These three lenses cover the **security and data-safety** surface that kit cares +about. They complement kit's other security docs: + +- `docs/OWASP_2025.md` — the threat catalogue the security lens maps to. +- `docs/THREAT_MODEL.md` — kit's own threat model. +- `docs/VERIFY.md` — how to verify a change actually works before claiming it does. + +Wire them into an agent with the templates in `examples/agent-hooks/` so the +agent self-reviews before it commits. Each lens is standalone — apply only the +ones a given change touches. + +--- + +## Lens: verified-security + +You review the change for security — **but every finding must be verified against +the actual source before you report it.** This lens has the worst false-positive +rate of any review lens. A speculative "this might be exploitable" without reading +the code is not a finding; it is noise that wastes the team's time. + +### Hard rule (the calibration) + +Before reporting any security finding, **read the actual handler, policy, query, +or config that backs it** and confirm the vulnerability is real. Cite `file:line`. +If you cannot point to the exact line that is exploitable, you do not have a +finding — note it as "to verify" at most. + +### Ask of the change + +1. **Authorization & data scoping.** Every read/write is scoped to the requesting + principal (tenant/org/owner), not global. Row-level / access policies are + tenant-scoped — no blanket-true policy (`USING (true)` / `WITH CHECK (true)`) + on user data. +2. **AuthN + AuthZ on every entry point.** Each route / endpoint / RPC checks + authentication AND that the caller may act on the specific object. No missing + check on a "secondary" handler. +3. **IDOR.** Object IDs from the client are re-checked against the caller's scope + server-side — you can't fetch/mutate another tenant's object by changing an ID. +4. **Privilege-escalation surfaces.** Elevated / `SECURITY DEFINER`-style + functions pin a safe search path / scope and don't leak elevated rights to the + caller. +5. **Input validation & injection.** Inputs validated server-side; parameterized + queries; no string-built SQL/commands; output encoded for its sink. +6. **Price/total integrity.** Amounts and totals are computed and trusted + server-side only — the client cannot manipulate what it pays. (Overlaps + revenue-recon; flag here if it's a security bypass, not just a reconciliation + gap.) +7. **Secrets.** No secrets/keys/tokens committed or sent to the client. + Signed/expiring URLs for file access, never public buckets. + +### Output + +For each VERIFIED finding: severity, `file:line` you read, the concrete exploit +(who can do what to whom), and the fix. Mark anything unverified explicitly as +"to verify" — do not inflate it to a finding. + +--- + +## Lens: db-safety + +You review the change for **database and migration discipline**. The schema is +shared, durable, and hard to roll back once data exists. The goal: every schema +change is forward-only-safe, reversible in principle, and can never destroy +production data. + +This lens fires whenever the change touches a migration, schema definition, or +data-mutating statement (DDL, seed, backfill, ad-hoc SQL). + +### Ask of the change + +1. **Migration naming & ordering.** New migrations use a timestamped naming + scheme (`YYYYMMDDHHMMSS_`, UTC) so they apply in a deterministic + order. No reused or out-of-order timestamps that collide with already-applied + migrations. +2. **Isolate fragile DDL.** Statements the engine refuses to run inside a + transaction or alongside other DDL (e.g. enum-value additions like + `ALTER TYPE ... ADD VALUE`, concurrent index builds) live in their **own** + migration file — not bundled with dependent changes. +3. **Additive & reversible.** Prefer additive changes (new nullable column, new + table) over destructive ones. A drop/rename/type-change is staged: add new → + backfill → switch reads → drop old in a later migration, so a deploy can be + rolled back without data loss. There is a down path or an explicit, documented + reason there isn't. +4. **Never auto-reset or destroy.** No command that wipes or recreates the + database (`db reset`, drop-and-recreate, truncate) in any dev/CI/automation + path that could reach a real environment. Migrations apply incrementally; data + is preserved. +5. **No unscoped destructive DML.** No `DELETE`/`UPDATE` without a `WHERE`, no + `DROP TABLE`/`TRUNCATE` against a populated table, in migrations or scripts. + Backfills are idempotent and bounded. +6. **Access control on by default.** New tables ship with row-level/access + policies enabled and tenant/owner-scoped from the first migration — never an + unprotected table left "to secure later", never a blanket-true policy on user + data. New privileged functions pin a safe search path / scope. (Overlaps + verified-security; flag here as a schema-level default gap.) +7. **Typecheck/build after schema change.** Generated DB types are regenerated + and the build / typecheck is run after a schema change, so renamed or dropped + columns surface as compile errors rather than runtime failures. + +### Failure modes to hunt + +- Enum value or concurrent index added in the same migration as code that depends + on it → fails to apply or half-applies. +- A column dropped/renamed in one migration with reads still pointing at the old + name → a rollback (or a slow rollout) breaks production. +- A `db reset` / drop-recreate hiding in a setup, seed, or CI script reachable + from prod creds. +- A backfill `UPDATE` with no `WHERE` that rewrites every row. +- New table created without access policies, or with `USING (true)`. +- Schema changed but generated types stale → silent runtime breakage. + +### Output + +For each finding: severity, file:line (the migration/script), the risk (what data +is lost or what deploy breaks), and the fix — ideally the additive/staged +alternative. + +--- + +## Lens: revenue-recon + +**Mandatory for any change touching money, payments, inventory, or stock.** Never +skip it for those flows — this is the single most-missed class of bug and a +generic reviewer rarely thinks to ask it. + +You are a reviewer whose only job is to confirm the change **reconciles**: every +unit of money and every unit of stock is accounted for, exactly once, and ends up +where downstream systems expect it. + +### Ask of the change + +1. **Does it create or move money?** A transaction/order/payment/refund record, a + balance change, a payout. If so: is the amount derived server-side (never + trusted from the client)? Is it recorded exactly once (idempotent against + retries/double-submit/webhook replay)? +2. **Does it move inventory/stock?** Is the decrement/increment atomic with the + sale, so a failure can't leave money taken but stock untouched (or vice versa)? + Can it go negative? +3. **Does it feed downstream reconciliation?** Totals, tax/VAT, daily + settlement/close-out, reporting, payouts, ledgers. If a number flows into any + aggregate, confirm it lands there with the right sign, currency, and rounding — + and isn't double-counted. +4. **Currency & rounding.** Single currency assumed? Integer minor units + (cents/öre) vs floats? Rounding applied once, consistently, at the documented + boundary? +5. **Reversibility.** Refund/void/cancel paths reverse both money AND stock + symmetrically. No path leaves the two out of sync. + +### Failure modes to hunt + +- Money charged but the record/stock update fails silently (no transaction + wrapping the two). +- Webhook or retry processed twice → double charge / double decrement (no + idempotency key). +- Total computed on the client and trusted by the server (price integrity). +- Float arithmetic on currency; rounding applied in two places. +- A sale that never reaches the settlement/reporting aggregate, or reaches it + twice. + +### Output + +For each finding: severity (blocker/high/med/low), file:line, the reconciliation +it breaks, and the fix. If the flow is fully reconciled, say so explicitly — +silence is not a pass. diff --git a/docs/HOST_OPS_CAPTURE.md b/docs/HOST_OPS_CAPTURE.md new file mode 100644 index 00000000..e429f48f --- /dev/null +++ b/docs/HOST_OPS_CAPTURE.md @@ -0,0 +1,65 @@ +# Host-ops Capture + +Any machine that runs unattended — a VPS, a bot host, a build box, a self-hosted +service — accumulates operational state that lives only on disk and in one +person's head. When that box dies, gets reimaged, or the person leaves, the config +is gone. The fix is simple and non-negotiable: **the server's governance lives in +the repo, not on the server.** If you can't rebuild the box from version control, +you don't control it. + +This pairs with kit's secret handling: capture the *config* in the repo, keep the +*values* in a vault. Names and structure are committed; secrets are referenced. + +## The rule + +Whenever you stand up or change an always-on host, commit the artifacts below to a +tracked `ops//` (or `infra//`) directory, and keep them in sync when +they change on the box. Secrets are referenced, never committed. + +## Capture checklist + +- [ ] **systemd units** (or equivalent supervisor config) — every `*.service`, + `*.timer`, and any drop-in overrides for daemons the box runs. Copy them from + `/etc/systemd/system/` (and `--user` units) into the repo verbatim. +- [ ] **Reverse-proxy / web-server config** — the nginx / Caddy / Traefik server + blocks, TLS settings, and upstream routing. Note where certs come from + (e.g. ACME issuer) — the renewal mechanism, not the private key. +- [ ] **Cron jobs / scheduled tasks** — crontab entries and any systemd timers, + with what they run and on what cadence. A scheduled job nobody remembers is a + future outage. +- [ ] **Backup scripts + schedule** — the backup command/script, what it backs up, + where it writes, retention, and how the schedule is wired (cron/timer). +- [ ] **Firewall / network rules** — open ports, allow-lists, and any VPN/overlay + network membership, enough to reproduce the network posture. +- [ ] **Env / config inventory** — the *names* and purpose of required env vars and + config files (e.g. an `.env.example`), and where each secret is sourced from + (which vault/secret store). Never the secret values. +- [ ] **Service inventory** — a short list of every long-running process on the box + and its purpose, so an outsider knows what is supposed to be running. + +## Restore runbook (the other half — write it) + +Committing config files is not enough; an operator under pressure needs the +*sequence*. Write `ops//RESTORE.md` covering, in order: + +1. **Provision** — OS/image, sizing, and where to get it (provider, region). +2. **Bootstrap** — install the runtimes/packages the services need. +3. **Place config** — copy the committed units/proxy/cron into their system paths, + reload the supervisor (`systemctl daemon-reload`, enable + start units). +4. **Inject secrets** — where each secret comes from and how it lands on the box + (secret manager/vault, manual placement) — referencing the env inventory above. +5. **Restore data** — how to recover from the latest backup, and how to verify it. +6. **Verify** — concrete checks that prove the box is healthy: services active, + proxy answering, a smoke request succeeding, backups running again. + +Keep it executable in spirit: each step should be a command or a precise pointer, +not a vague gesture. Prefer scripts the runbook invokes over prose the operator +must translate. + +## Sync discipline + +Drift kills this practice. When you change a unit, proxy block, cron entry, or +backup script *on the box*, mirror the change into the repo in the same work — the +committed copy is the source of truth, the box is a deployment of it. A periodic +diff between the live config and the committed copy catches silent drift before an +outage does. diff --git a/docs/SECRETS_LIFECYCLE.md b/docs/SECRETS_LIFECYCLE.md new file mode 100644 index 00000000..614ea0cf --- /dev/null +++ b/docs/SECRETS_LIFECYCLE.md @@ -0,0 +1,77 @@ +# Secrets Lifecycle + +A secret's *name* belongs in the repo; its *value* never does. Config references a +key (`DATABASE_URL`, `STRIPE_SECRET_KEY`); the value is resolved at runtime from a +secret store. If a value reaches git history, a script, a CI log, or a screenshot, +it is compromised — go to [Leak response](#leak-response). This guide is the decision +layer that pairs with kit's vault backends and its secret prescan (`kit prescan`, +backed by gitleaks): the scan and the vault enforce *where values live*; this doc +owns the part tooling can't — how you provision, rotate, and respond when a value +leaks. + +## Provision + +- Commit an `.env.example` of key **names + purpose only** — never a real value. + kit's `.env.template` follows this convention. +- Mint a fresh, scoped credential per service per environment (dev/staging/prod); + one leaked dev key must not unlock prod. +- **Never inline a secret in a script.** The classic anti-pattern is a backup + script with the DB password in the connection string so cron "just runs it" — + that value is now in git, in shell history, in every CI log, and in `ps`. Read + it from the environment instead: + + ```bash + # BAD — secret committed forever: + pg_dump "postgresql://admin:S3cr3tP@ss@db/app" > backup.sql + # GOOD — injected at runtime, file is safe to commit: + : "${DATABASE_URL:?DATABASE_URL not set}"; pg_dump "$DATABASE_URL" > backup.sql + ``` + +- Keep secrets off the command line (visible in `ps`/history); use env or a file. + +## Store + +- One source of truth: a managed **secret store / vault** — not a doc, chat, or + hand-passed `.env`. A vault gives you access control, audit logs, versioning, + and rotation in one place. kit supports a range of vault backends so the same + config resolves against whichever store a team already uses. +- Inject at runtime (a `run`/`exec` wrapper that loads the vault, a sidecar, or a + platform env binding); don't copy values around. Local dev uses a gitignored + `.env.local` sourced from the store. Scope least-privilege per environment. +- Defense at the boundary: a pre-commit secret scan (`kit prescan`) plus the host's + push protection; `.env*` gitignored except `.env.example`. + +## Rotate + +Rotate on a **cadence** (≈90 days for API/DB keys; 180 for signing/webhook +secrets) **and** on any trigger (leak, offboarding, vendor advisory). Zero-downtime +procedure: **issue** new → **store** it → **roll out** → **verify** → **revoke** +old → **record** the date so the next rotation is scheduled. Use a dual-key window +where the provider allows two live keys. + +## Leak response + +A secret is leaked the moment its value lands anywhere uncontrolled. Assume +compromise — don't debate it. **Revoke within minutes; fully rotated within the +hour.** Scrubbing git history does *not* un-leak it; revoking does. + +1. **Detect & contain** — which secret, where, exposure window. Start the clock. +2. **Revoke/rotate first** — invalidate the exposed value at the provider, then + issue + store + roll out a replacement. This is the action that closes the door. +3. **Rotate dependents** — anything derived from, sharing a key with, or reachable + *using* the leaked secret (session keys, downstream tokens). Map blast radius + from vault access scopes. +4. **Audit for abuse** — provider + store logs for the window: odd IPs, unusual + calls, data egress, new keys/grants. Escalate if abuse found. +5. **Document** — short post-incident note: what leaked, root cause, window, + actions + timestamps, and the prevention fix; feed it back into your runbook. + +| Step | Target | +|---|---| +| Detect → revoke | minutes | +| Replacement rolled out | < 1 hour | +| Dependents rotated | same incident | +| Abuse audit | < 24 hours | + +> Deleting the secret from a file or rewriting history is **not** remediation. +> Once exposed, the only fix is to make the value worthless by revoking it. diff --git a/docs/SECRETS_RUNBOOK.md b/docs/SECRETS_RUNBOOK.md new file mode 100644 index 00000000..50c1fd98 --- /dev/null +++ b/docs/SECRETS_RUNBOOK.md @@ -0,0 +1,126 @@ +# Secrets runbook + +A project-level template for handling secrets across their whole lifecycle — +provision, store, rotate, and respond to a leak. Copy it into a repo as +`SECRETS.md` (or `docs/secrets.md`) and fill the bracketed `[…]` slots for your +project. It pairs with kit's secret-scan (gitleaks-backed prescan), supply-chain +scan, and vault backends; this file covers the part tooling can't: the *values* +and what to do when one escapes. + +Core rule: **a secret's name lives in the repo; its value never does.** Config +references a key (`DATABASE_URL`, `API_KEY`); the value is resolved at runtime +from a secret store. If a value is in git history, a script, a CI log, or a +screenshot, treat it as compromised — see Leak response. + +## 1. Provisioning + +- **Values are not names.** Commit an `.env.example` listing every key and a + one-line purpose — names and shape only (`API_KEY=`), never a real value. Code + reads `process.env.X` / `os.environ["X"]`; it never contains the literal. +- **Generate, don't reuse.** Mint a fresh credential per service per environment + (dev / staging / prod). One leaked dev key must not unlock prod. Use the + provider's own key issuance (restricted/scoped keys where offered) rather than a + long-lived root key. +- **Never in scripts.** The classic failure is the convenience anti-pattern: a + backup or deploy script with the password inlined so it "just runs from cron": + + ```bash + # ANTI-PATTERN — do not do this. Secret is now in git, in shell history, + # in every CI log that echoes the command, and in the process table (`ps`). + pg_dump "postgresql://admin:S3cr3tP@ss@db.internal/app" > backup.sql + ``` + + The fix: the script reads the value from the environment, which is populated + from the secret store at run time — the literal appears nowhere in the repo: + + ```bash + # OK — value injected at runtime; the file is safe to commit. + : "${DATABASE_URL:?DATABASE_URL not set}" + pg_dump "$DATABASE_URL" > backup.sql + ``` + +- **No secrets on the command line.** Args are visible in `ps` and shell history; + prefer env vars or a file the tool reads. Don't `echo` secrets in CI. + +## 2. Storage + +- **One source of truth: a secret store / vault.** Keep values in a managed store + (e.g. Vault, AWS/GCP Secrets Manager, 1Password, Doppler, Infisical, or any of + kit's supported vault backends) — not in a shared doc, chat, or a `.env` passed + around by hand. The store gives you access control, audit logging, versioning, + and rotation in one place. +- **Inject, don't copy.** Runtime pulls from the store (sidecar, a vault CLI's + `run -- ` wrapper, platform-native env binding). Local dev uses a + per-developer `.env.local` that is gitignored and sourced from the store, never + emailed or pasted. +- **Scope and least-privilege.** Separate vault scopes per environment; grant each + human/service only the keys it needs. Production secrets are not readable from a + laptop by default. +- **Guard the boundary.** A pre-commit secret scan (e.g. gitleaks, as kit's + prescan runs) and a server-side push protection catch the literal before it + lands. `.env*` (except `.env.example`) is gitignored. + +## 3. Rotation + +Rotate on a cadence *and* on any trigger (leak, offboarding, vendor advisory). + +| Secret class | Cadence | Notes | +|---|---|---| +| App/API keys, tokens | every 90 days | scoped keys, dual-key window to avoid downtime | +| Database / infra creds | every 90–180 days | coordinate with connection pools | +| Signing / webhook secrets | every 180 days | overlap old+new during cutover | +| OAuth client secrets | per vendor policy | | +| Anything exposed in a leak | immediately | see Leak response | + +**Zero-downtime rotation procedure:** + +1. **Issue** a new credential in the provider (don't delete the old yet). +2. **Store** the new value in the vault as the active version. +3. **Roll out** — deploy/restart so running processes pick up the new value. + Where the provider supports two live keys, run both during the window. +4. **Verify** the new value works in each environment (a smoke call, a signed + webhook round-trip). +5. **Revoke** the old credential at the provider and prune it from the store. +6. **Record** the rotation date so the next cadence is scheduled. + +## 4. Leak response (incident runbook) + +A secret has leaked the moment its value lands anywhere uncontrolled — git +history, a public repo, a CI/build log, a paste, a screenshot, a client bundle, +or a third-party breach. Assume compromise; do not debate it. + +**Target time-to-restore: revoke within minutes, fully rotated within the hour.** +A live exposed credential is an open door — speed beats tidiness. + +1. **Detect & contain.** Confirm which secret, where it surfaced, and the window + it was exposed. Do **not** try to "scrub" git history first — that does not + un-leak it; revoking does. Start the clock. +2. **Revoke / rotate the leaked secret first.** Invalidate the exposed value at + the provider immediately, then issue + store + roll out a replacement + (the rotation procedure above). Revocation is the action that closes the door; + everything else follows. +3. **Rotate dependents.** Any secret derived from, sharing a key with, or reachable + *using* the leaked one is also suspect — session signing keys, downstream + service tokens, anything the exposed credential could have read. Rotate them + too. Map the blast radius from the vault's access scopes. +4. **Audit for abuse.** Pull provider + store access logs for the exposure window: + unexpected IPs, unusual calls, data egress, new keys/grants created with the + stolen credential. Escalate to an incident if abuse is found. +5. **Document.** Write a short post-incident note: what leaked, root cause (how the + value escaped), exposure window, actions + timestamps, and the prevention fix + (e.g. enable push protection, add the missed path to `.gitignore`, move the + value out of a script — section 1). Feed the fix back into this runbook. + +### Time-to-restore targets + +| Step | Target | +|---|---| +| Detect → revoke leaked secret | minutes | +| Replacement issued + rolled out | < 1 hour | +| Dependents rotated | same incident | +| Abuse audit complete | < 24 hours | +| Post-incident note written | < 48 hours | + +> Removing a secret from a file or rewriting git history is **not** remediation. +> Once a value is exposed, the only fix is to make that value worthless by +> revoking it. Rewrite history only as cleanup *after* rotation. diff --git a/docs/SECURITY_HEADERS.md b/docs/SECURITY_HEADERS.md new file mode 100644 index 00000000..d4297e27 --- /dev/null +++ b/docs/SECURITY_HEADERS.md @@ -0,0 +1,51 @@ +# Security headers + +Ship these on every response by default — they are cheap, broadly applicable +hardening that closes whole classes of attack (clickjacking, MIME-sniffing, +referrer leakage, downgrade). The example below wires them in Next.js via +`next.config.js`; the same header *values* apply to any framework or reverse +proxy — only the wiring differs. + +```js +// next.config.js +const securityHeaders = [ + // Force HTTPS for 2 years; preload-eligible. Only enable preload once you're + // sure every subdomain is HTTPS-only — it's hard to undo. + { key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' }, + // Disallow framing → clickjacking protection. Use a CSP frame-ancestors + // instead if you need to allow specific embedders. + { key: 'X-Frame-Options', value: 'DENY' }, + // Don't let browsers MIME-sniff responses. + { key: 'X-Content-Type-Options', value: 'nosniff' }, + // Send origin only on cross-origin; full URL same-origin. + { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, + // Deny powerful features by default; add what you actually use. + { key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=(), browsing-topics=()' }, +]; + +/** @type {import('next').NextConfig} */ +module.exports = { + async headers() { + return [{ source: '/:path*', headers: securityHeaders }]; + }, +}; +``` + +## Content-Security-Policy (add when you can) + +A CSP is the strongest single header but needs per-app tuning (inline scripts, +analytics, fonts). Start in report-only, watch violations, then enforce. + +```js +{ key: 'Content-Security-Policy-Report-Only', + value: "default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" } +``` + +## Verify + +```bash +curl -sI https://example.com/ | grep -iE 'strict-transport|x-frame|x-content-type|referrer-policy|permissions-policy' +``` + +Or scan with a public header checker such as https://securityheaders.com. Aim +for an A+ grade before release. diff --git a/examples/agent-hooks/claude-code/preflight/commit-preflight.sh b/examples/agent-hooks/claude-code/preflight/commit-preflight.sh new file mode 100755 index 00000000..f9e1a19f --- /dev/null +++ b/examples/agent-hooks/claude-code/preflight/commit-preflight.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# commit-preflight.sh — fast git-commit pre-flight (Claude Code: PreToolUse). +# +# Fires BEFORE the agent runs a bash action containing `git commit`. Blocks +# (exit 2) the cheap-to-check, high-value violations so they never reach the +# heavier native git hook: +# 1. `git commit --no-verify` / `-n` → bypassing the gate is forbidden. +# 2. Staged .env* files → never commit secrets. +# 3. Secret pattern in the staged diff → catch before it lands. +# +# Reads the harness PreToolUse JSON on stdin ({"tool_input":{"command":...}}). +# If jq is unavailable it parses with python3, then a grep fallback. +# Exit 0 = allow; exit 2 = deny. Non-commit commands pass through. +set -euo pipefail + +INPUT=$(cat 2>/dev/null || echo '{}') + +extract_cmd() { + if command -v jq >/dev/null 2>&1; then + printf '%s' "$INPUT" | jq -r '.tool_input.command // empty' 2>/dev/null && return + fi + printf '%s' "$INPUT" | python3 -c "import sys,json +try: print(json.load(sys.stdin).get('tool_input',{}).get('command','')) +except Exception: print('')" 2>/dev/null || printf '%s' "$INPUT" +} +COMMAND=$(extract_cmd) + +# Only intercept git commit. +printf '%s' "$COMMAND" | grep -q 'git commit' || exit 0 + +ERRORS="" + +# 1. Refuse --no-verify / -n — never bypass the gate. +if printf '%s' "$COMMAND" | grep -qE -- '--no-verify\b|(^| )-[a-zA-Z]*n([a-zA-Z]*)?( |$)'; then + ERRORS="${ERRORS}\n- 'git commit --no-verify/-n' is forbidden. Fix the underlying issue instead of skipping the gate." +fi + +PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}" +cd "$PROJECT_DIR" || exit 0 + +# 2. Refuse staged .env* files. +if git diff --cached --name-only 2>/dev/null | grep -qE '(^|/)\.env(\.|$)'; then + ERRORS="${ERRORS}\n- A staged file matches the .env* pattern. Unstage it: git restore --staged " +fi + +# 3. Secret pattern in the staged diff (same tight pattern as the START-gate). +staged=$(git diff --cached 2>/dev/null | grep '^+' | grep -v '^+++' || true) +if printf '%s\n' "$staged" | grep -qE \ + 'sk_live_[A-Za-z0-9]{8,}|sk-ant-[A-Za-z0-9_-]{8,}|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{20,}|xox[bap]-[A-Za-z0-9-]{8,}|-----BEGIN [A-Z ]*PRIVATE KEY-----' \ + || printf '%s\n' "$staged" | grep -qiE \ + '(STRIPE_SECRET_KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY|GITHUB_TOKEN|AWS_SECRET_ACCESS_KEY)[[:space:]]*[:=][[:space:]]*["'"'"']?[A-Za-z0-9+/=_-]{16,}'; then + ERRORS="${ERRORS}\n- Possible SECRET in the staged diff. Remove it and move the value to a secret store before committing." +fi + +if [ -n "$ERRORS" ]; then + printf "Commit pre-flight FAILED:%b\n" "$ERRORS" >&2 + exit 2 +fi +exit 0 diff --git a/examples/agent-hooks/claude-code/preflight/post-push-ci-watch.sh b/examples/agent-hooks/claude-code/preflight/post-push-ci-watch.sh new file mode 100755 index 00000000..98e3e7cd --- /dev/null +++ b/examples/agent-hooks/claude-code/preflight/post-push-ci-watch.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# post-push-ci-watch.sh — non-blocking CI watcher (Claude Code: PostToolUse). +# +# Fires AFTER a successful `git push`. If the GitHub CLI (`gh`) is available +# and authenticated, it kicks off a detached, background-safe watch of the +# latest CI run for the pushed branch and writes a one-line status note to a +# log the agent can read on a later turn. Purely advisory: +# - NEVER blocks (always exit 0). +# - No-ops cleanly when gh is missing, unauthenticated, or no run is found. +# +# The note lands in CI_WATCH_LOG (default .git/.kit/ci-watch.log). +set -euo pipefail + +INPUT=$(cat 2>/dev/null || echo '{}') +extract_cmd() { + if command -v jq >/dev/null 2>&1; then + printf '%s' "$INPUT" | jq -r '.tool_input.command // empty' 2>/dev/null && return + fi + printf '%s' "$INPUT" | python3 -c "import sys,json +try: print(json.load(sys.stdin).get('tool_input',{}).get('command','')) +except Exception: print('')" 2>/dev/null || printf '%s' "$INPUT" +} +COMMAND=$(extract_cmd) + +# Only act on a git push, and only if gh exists. +printf '%s' "$COMMAND" | grep -q 'git push' || exit 0 +command -v gh >/dev/null 2>&1 || exit 0 + +root=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0 +cd "$root" || exit 0 + +# Confirm gh is usable in this repo (auth + remote). No-op otherwise. +gh auth status >/dev/null 2>&1 || exit 0 + +LOG="${CI_WATCH_LOG:-.git/.kit/ci-watch.log}" +mkdir -p "$(dirname "$LOG")" 2>/dev/null || true +branch=$(git branch --show-current 2>/dev/null || echo "") +[ -z "$branch" ] && exit 0 + +# Detached watcher: poll the latest run for this branch, append one status +# line when it settles. Self-contained so it survives the hook returning. +( + set +e + ts() { date -u +%Y-%m-%dT%H:%M:%SZ; } + printf '[%s] CI watch started: branch=%s\n' "$(ts)" "$branch" >> "$LOG" + # Give the run a moment to register, then poll up to ~10 min. + for _ in $(seq 1 60); do + sleep 10 + json=$(gh run list --branch "$branch" --limit 1 \ + --json status,conclusion,displayTitle,url 2>/dev/null) || continue + [ -z "$json" ] || [ "$json" = "[]" ] && continue + status=$(printf '%s' "$json" | python3 -c "import sys,json;r=json.load(sys.stdin);print(r[0].get('status','') if r else '')" 2>/dev/null) + if [ "$status" = "completed" ]; then + printf '%s' "$json" | python3 -c "import sys,json +r=json.load(sys.stdin)[0] +print('[%s] CI %s: %s %s' % ('$(ts)', r.get('conclusion','?'), r.get('displayTitle',''), r.get('url','')))" \ + >> "$LOG" 2>/dev/null + exit 0 + fi + done + printf '[%s] CI watch timed out (run still in progress on %s)\n' "$(ts)" "$branch" >> "$LOG" +) >/dev/null 2>&1 & +disown 2>/dev/null || true + +exit 0 diff --git a/examples/agent-hooks/claude-code/preflight/push-preflight.sh b/examples/agent-hooks/claude-code/preflight/push-preflight.sh new file mode 100755 index 00000000..d78edba5 --- /dev/null +++ b/examples/agent-hooks/claude-code/preflight/push-preflight.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# push-preflight.sh — git-push pre-flight (Claude Code: PreToolUse). +# +# Fires BEFORE the agent runs a bash action containing `git push`. Catches the +# "passes locally, fails in CI" class of problems and the forbidden bypasses: +# 1. `git push --force/-f` to a protected branch → forbidden without approval. +# 2. `git push --no-verify` → never bypass the gate. +# 3. Build + test, IF package.json declares those scripts (else skipped). +# 4. Secret pattern in commits about to be pushed. +# 5. Untracked source files imported by tracked code (CI breaker). +# +# Exit 0 = allow; exit 2 = deny. Non-push commands pass through. +# Generic: source roots come from SOURCE_GLOBS, protected branches from +# PROTECTED_BRANCHES. Set PUSH_SKIP_BUILD=1 to skip the build/test step. +set -euo pipefail + +PROTECTED_BRANCHES="${PROTECTED_BRANCHES:-main master}" +# Space-separated git pathspecs for source files (any language). +SOURCE_GLOBS="${SOURCE_GLOBS:-src/**/*.ts src/**/*.tsx src/**/*.js src/**/*.jsx app/**/*.ts app/**/*.tsx lib/**/*.ts}" + +INPUT=$(cat 2>/dev/null || echo '{}') +extract_cmd() { + if command -v jq >/dev/null 2>&1; then + printf '%s' "$INPUT" | jq -r '.tool_input.command // empty' 2>/dev/null && return + fi + printf '%s' "$INPUT" | python3 -c "import sys,json +try: print(json.load(sys.stdin).get('tool_input',{}).get('command','')) +except Exception: print('')" 2>/dev/null || printf '%s' "$INPUT" +} +COMMAND=$(extract_cmd) + +printf '%s' "$COMMAND" | grep -q 'git push' || exit 0 + +PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}" +cd "$PROJECT_DIR" || exit 0 + +ERRORS="" + +# 1. Refuse --force to a protected branch. +if printf '%s' "$COMMAND" | grep -qE -- '--force\b|--force-with-lease\b|(^| )-f( |$)'; then + for pb in $PROTECTED_BRANCHES; do + if printf '%s' "$COMMAND" | grep -qE -- "\\b${pb}\\b"; then + ERRORS="${ERRORS}\n- 'git push --force' to protected branch '${pb}' is forbidden without explicit approval." + break + fi + done +fi + +# 2. Refuse --no-verify. +if printf '%s' "$COMMAND" | grep -qE -- '--no-verify\b'; then + ERRORS="${ERRORS}\n- 'git push --no-verify' is forbidden. Fix the underlying issue." +fi + +# 3. Build + test — only when package.json declares the scripts. +if [ "${PUSH_SKIP_BUILD:-}" != "1" ] && [ -f package.json ] && command -v node >/dev/null 2>&1; then + pm="npm" + if [ -f pnpm-lock.yaml ] && command -v pnpm >/dev/null 2>&1; then pm="pnpm" + elif [ -f yarn.lock ] && command -v yarn >/dev/null 2>&1; then pm="yarn" + fi + has_script() { node -e "process.exit(require('./package.json').scripts?.['$1']?0:1)" 2>/dev/null; } + + if has_script build; then + echo "Push pre-flight: $pm run build..." >&2 + if ! $pm run build >&2 2>&1; then + ERRORS="${ERRORS}\n- build FAILED (run: $pm run build)" + fi + fi + if has_script test; then + echo "Push pre-flight: $pm test..." >&2 + if ! CI=1 $pm test >&2 2>&1; then + ERRORS="${ERRORS}\n- tests FAILED (run: $pm test)" + fi + fi +fi + +# 4. Secret pattern in commits about to be pushed (vs upstream, else HEAD~1). +upstream=$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || echo "") +range="" +if [ -n "$upstream" ]; then range="${upstream}..HEAD"; fi +to_push=$(git diff ${range:-HEAD~1..HEAD} 2>/dev/null | grep '^+' | grep -v '^+++' || true) +if printf '%s\n' "$to_push" | grep -qE \ + 'sk_live_[A-Za-z0-9]{8,}|sk-ant-[A-Za-z0-9_-]{8,}|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{20,}|xox[bap]-[A-Za-z0-9-]{8,}|-----BEGIN [A-Z ]*PRIVATE KEY-----' \ + || printf '%s\n' "$to_push" | grep -qiE \ + '(STRIPE_SECRET_KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY|GITHUB_TOKEN|AWS_SECRET_ACCESS_KEY)[[:space:]]*[:=][[:space:]]*["'"'"']?[A-Za-z0-9+/=_-]{16,}'; then + ERRORS="${ERRORS}\n- Possible SECRET in commits about to be pushed. Rewrite history to remove it and rotate the value." +fi + +# 5. Untracked source files imported by tracked code (would break a clean CI). +# shellcheck disable=SC2086 +UNTRACKED=$(git ls-files --others --exclude-standard -- $SOURCE_GLOBS 2>/dev/null || true) +if [ -n "$UNTRACKED" ]; then + MISSING="" + while IFS= read -r f; do + [ -z "$f" ] && continue + base=$(basename "$f" | sed -E 's/\.(ts|tsx|js|jsx|mjs|cjs)$//') + dir=$(dirname "$f") + # Imported by a sibling via a relative path? + if git ls-files -- "$dir" 2>/dev/null \ + | xargs grep -lE "from ['\"]\\./${base}['\"]|require\\(['\"]\\./${base}['\"]\\)" 2>/dev/null \ + | head -1 >/dev/null 2>&1; then + MISSING="${MISSING}\n ${f}" + fi + # Re-exported from a tracked barrel (index)? + for idx in index.ts index.tsx index.js; do + if [ "$base" != "index" ] && [ -f "$dir/$idx" ] \ + && git ls-files --error-unmatch "$dir/$idx" >/dev/null 2>&1 \ + && grep -qE "from ['\"]\\./${base}['\"]" "$dir/$idx" 2>/dev/null; then + MISSING="${MISSING}\n ${f}" + fi + done + done <<< "$UNTRACKED" + MISSING=$(printf '%b' "$MISSING" | sort -u | grep -v '^$' || true) + if [ -n "$MISSING" ]; then + ERRORS="${ERRORS}\n- Untracked files imported by tracked code (will break CI):${MISSING}" + fi +fi + +if [ -n "$ERRORS" ]; then + printf "Push pre-flight FAILED:%b\n" "$ERRORS" >&2 + exit 2 +fi +exit 0 diff --git a/examples/agent-hooks/claude-code/preflight/sanity-preflight.sh b/examples/agent-hooks/claude-code/preflight/sanity-preflight.sh new file mode 100755 index 00000000..e72498d1 --- /dev/null +++ b/examples/agent-hooks/claude-code/preflight/sanity-preflight.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# sanity-preflight.sh — START-gate (Claude Code: UserPromptSubmit). +# +# Fast sanity + security check BEFORE the agent acts on each prompt. +# SILENT when clean; injects a short warning only on a real problem, and +# DEDUPLICATES via a marker file so the same state is not re-spammed prompt +# after prompt. FAIL-OPEN (always exit 0) — advisory, never blocks. +# +# Detects: +# 1. Likely secrets in the working diff (tight pattern, low false-positive). +# 2. Uncommitted changes on a protected branch (branch-first convention). +# +# Portable: no project-specific assumptions. Reads marker dir from +# SANITY_MARKER_DIR (default .git/.kit). Protected branches from +# PROTECTED_BRANCHES (default "main master"). +set -euo pipefail + +root=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0 +cd "$root" || exit 0 + +PROTECTED_BRANCHES="${PROTECTED_BRANCHES:-main master}" +marker_dir="${SANITY_MARKER_DIR:-.git/.kit}" +mkdir -p "$marker_dir" 2>/dev/null || true + +warn="" + +# --- 1. Secrets in diff --------------------------------------------------- +# Two signals, both tight enough for low false-positives: +# (a) provider-prefixed tokens (live keys, vendor tokens, PEM headers) +# (b) named env keys assigned a 16+ char value +diff=$(git diff HEAD 2>/dev/null | grep '^+' | grep -v '^+++' || true) + +prefixed=$(printf '%s\n' "$diff" | grep -nE \ + 'sk_live_[A-Za-z0-9]{8,}|sk-ant-[A-Za-z0-9_-]{8,}|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{20,}|xox[bap]-[A-Za-z0-9-]{8,}|-----BEGIN [A-Z ]*PRIVATE KEY-----' \ + | head -2 || true) + +named=$(printf '%s\n' "$diff" | grep -niE \ + '(STRIPE_SECRET_KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY|GITHUB_TOKEN|AWS_SECRET_ACCESS_KEY)[[:space:]]*[:=][[:space:]]*["'"'"']?[A-Za-z0-9+/=_-]{16,}' \ + | head -2 || true) + +if [ -n "$prefixed" ] || [ -n "$named" ]; then + warn="${warn}WARNING: possible SECRET in working diff — do NOT commit until verified / moved to a secret store.\n" +fi + +# --- 2. Uncommitted changes on a protected branch ------------------------- +# Deduplicated per change-set hash so it shows once per distinct state. +branch=$(git branch --show-current 2>/dev/null || echo "") +for pb in $PROTECTED_BRANCHES; do + if [ "$branch" = "$pb" ]; then + porcelain=$(git status --porcelain 2>/dev/null || true) + if [ -n "$porcelain" ]; then + st=$(printf '%s' "$porcelain" | (shasum 2>/dev/null || sha1sum 2>/dev/null) | cut -d' ' -f1) + marker="${marker_dir}/sanity-branch-${st}" + if [ ! -f "$marker" ]; then + n=$(printf '%s\n' "$porcelain" | grep -c . || echo "?") + warn="${warn}WARNING: ${n} uncommitted change(s) on protected branch '${branch}'. Create a feature branch before committing.\n" + rm -f "${marker_dir}"/sanity-branch-* 2>/dev/null || true + touch "$marker" 2>/dev/null || true + fi + fi + break + fi +done + +# Silent when nothing to flag. +[ -z "$warn" ] && exit 0 +printf "SANITY-PREFLIGHT (START-gate):\n%b" "$warn" +exit 0 diff --git a/examples/agent-hooks/claude-code/preflight/stop-review-gate.sh b/examples/agent-hooks/claude-code/preflight/stop-review-gate.sh new file mode 100755 index 00000000..6a8d1b3b --- /dev/null +++ b/examples/agent-hooks/claude-code/preflight/stop-review-gate.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# stop-review-gate.sh — END-gate (Claude Code: Stop hook). +# +# Forces a review of UNTOUCHED feature-zone changes before the agent is +# allowed to finish. Verification happens BEFORE the agent declares done, +# not after. +# +# Loop-guard (two layers): +# (1) stop_hook_active=true → release (already inside a block-chain). +# (2) marker file per change-set hash → release (already reviewed). +# +# Configure FEATURE_ZONES below (or via env). Defaults are cross-stack: +# common source roots + migrations. Output is a harness `block` decision +# (stdout JSON) instructing the agent to review the changed files. +set -euo pipefail + +# Cross-stack defaults — override by exporting FEATURE_ZONES (space-separated +# path prefixes, relative to repo root). +FEATURE_ZONES="${FEATURE_ZONES:-src/ app/ lib/ components/ packages/ migrations/}" + +marker_dir="${REVIEW_MARKER_DIR:-.git/.kit}" + +input=$(cat 2>/dev/null || echo '{}') + +# (1) Loop-guard: if this Stop already follows a hook block → release. +active=$(printf '%s' "$input" | python3 -c "import sys,json +try: print(str(json.load(sys.stdin).get('stop_hook_active', False))) +except Exception: print('False')" 2>/dev/null || echo False) +[ "$active" = "True" ] && exit 0 + +root=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0 +cd "$root" || exit 0 +mkdir -p "$marker_dir" 2>/dev/null || true + +# Build an alternation regex from FEATURE_ZONES: matches a porcelain line +# whose path begins with any configured zone prefix. +zone_re="" +for z in $FEATURE_ZONES; do + esc=$(printf '%s' "$z" | sed 's/[.[\*^$()+?{|]/\\&/g') + zone_re="${zone_re}${zone_re:+|}${esc}" +done +[ -z "$zone_re" ] && exit 0 + +# Untracked + unstaged + staged (not committed) changes inside feature zones. +changed=$(git status --porcelain 2>/dev/null \ + | grep -E "^.{1,2} (${zone_re})" \ + || true) +[ -z "$changed" ] && exit 0 # no feature changes → release + +# Marker per exact change-set → already reviewed? +hash=$(printf '%s' "$changed" | (shasum 2>/dev/null || sha1sum 2>/dev/null) | cut -d' ' -f1) +marker="${marker_dir}/reviewed-${hash}" +[ -f "$marker" ] && exit 0 # already reviewed → release + +# Otherwise: block + instruct the agent to review before finishing. +REASON="Feature zone changed but not reviewed. Review BEFORE you finish: +1. Re-read the changed files against these lenses: correctness/business-logic, UX consistency, project conventions, and security (run 'kit check --category security' if kit is installed). +2. Run the relevant test or end-to-end spec if a UI or behavioural flow changed. +3. Fix any blocker/high finding, or consciously acknowledge it in one line to the user. +4. Release the gate: touch \"${marker}\" + +Changed feature files: +${changed}" + +python3 -c "import json,sys +print(json.dumps({'decision':'block','reason':sys.argv[1]}))" "$REASON" +exit 0 diff --git a/examples/agent-hooks/git-hooks/no-internal-leaks.sh b/examples/agent-hooks/git-hooks/no-internal-leaks.sh new file mode 100755 index 00000000..9f7dc003 --- /dev/null +++ b/examples/agent-hooks/git-hooks/no-internal-leaks.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# no-internal-leaks.sh — keep private/internal references out of a +# public-bound repository. +# +# Scans content against a list of internal terms (private codenames, internal +# hostnames, non-public emails, not-for-publication markers). The term list is kept +# OUTSIDE the repo so the list itself never leaks into the public history. +# +# Audit lesson this encodes: a leak hides not only in files but in the COMMIT +# MESSAGE — a "scrub" commit whose own message named every codename it removed. +# So this guards staged content AND commit messages AND existing history. +# +# Modes: +# --staged scan the staged blob content (pre-commit) +# --msg scan a commit-message file (commit-msg) +# --tracked scan every tracked file (pre-push / manual) +# +# Term-list resolution (first existing file wins): +# 1. $INTERNAL_TERMS_FILE +# 2. /.internal-terms (keep gitignored — local only) +# 3. ~/.config/kit/internal-terms +# +# Term-list format: one term per line; blank lines and '#' comments ignored; +# each term matched case-insensitively as a FIXED string (not a regex), so +# special characters are safe and there are no surprise expansions. +# +# No term list found -> warn once to stderr, exit 0 (fail-open: a repo that +# hasn't configured a list is never blocked). +# Match found -> print location(s) + the offending line, exit 1. +# Clean -> silent, exit 0. +set -euo pipefail + +MODE="${1:-}" +MSG_FILE="${2:-}" + +die_usage() { + echo "usage: no-internal-leaks.sh (--staged | --msg | --tracked)" >&2 + exit 2 +} +[ -n "$MODE" ] || die_usage + +REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || true)" + +# --- resolve the term list --------------------------------------------------- +TERMS_FILE="" +for cand in \ + "${INTERNAL_TERMS_FILE:-}" \ + "${REPO_ROOT:+$REPO_ROOT/.internal-terms}" \ + "$HOME/.config/kit/internal-terms"; do + if [ -n "$cand" ] && [ -f "$cand" ]; then TERMS_FILE="$cand"; break; fi +done + +if [ -z "$TERMS_FILE" ]; then + echo "no-internal-leaks: no term list found — set INTERNAL_TERMS_FILE or create ~/.config/kit/internal-terms (skipping)" >&2 + exit 0 +fi + +# Strip comments/blank lines into a temp pattern file for grep -f. +PAT_FILE="$(mktemp)" +trap 'rm -f "$PAT_FILE"' EXIT +grep -vE '^[[:space:]]*(#|$)' "$TERMS_FILE" > "$PAT_FILE" || true +if [ ! -s "$PAT_FILE" ]; then exit 0; fi # empty list = nothing to enforce + +HITS=0 + +report() { # $1 = location label, $2 = matched lines (grep -ni output) + echo " x $1" >&2 + printf '%s\n' "$2" | sed 's/^/ /' >&2 + HITS=1 +} + +case "$MODE" in + --staged) + # Scan the STAGED blob of each added/copied/modified file (not the worktree), + # so what the hook checks is exactly what would be committed. + while IFS= read -r f; do + [ -n "$f" ] || continue + match="$(git show ":$f" 2>/dev/null | grep -niF -f "$PAT_FILE" || true)" + [ -n "$match" ] && report "$f" "$match" + done < <(git diff --cached --name-only --diff-filter=ACM) + ;; + --msg) + [ -n "$MSG_FILE" ] && [ -f "$MSG_FILE" ] || die_usage + match="$(grep -niF -f "$PAT_FILE" "$MSG_FILE" || true)" + [ -n "$match" ] && report "commit message" "$match" + ;; + --tracked) + match="$(git grep -nIiF -f "$PAT_FILE" -- . 2>/dev/null || true)" + [ -n "$match" ] && report "tracked files" "$match" + ;; + *) + die_usage + ;; +esac + +if [ "$HITS" -ne 0 ]; then + echo "" >&2 + echo "no-internal-leaks: blocked — internal term(s) found above (list: $TERMS_FILE)." >&2 + echo " Remove/generalize the reference, or if it is a false positive, scope the" >&2 + echo " term in the list. Bypassing this guard requires explicit approval." >&2 + exit 1 +fi +exit 0 diff --git a/examples/local-stack.sh b/examples/local-stack.sh new file mode 100755 index 00000000..48bcb686 --- /dev/null +++ b/examples/local-stack.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# local-stack.sh — idempotent local dev bring-up: docker-up -> migrate -> seed -> env skeleton. +# +# Goal: one command takes a fresh clone to a running local stack, and re-running +# it is safe (no data loss, no duplicate seeds). Edit the marked sections for +# your stack. NEVER reset/drop a shared or prod database from here — destructive +# ops on shared data require explicit human sign-off (see kit's TOTP elevation). +# +# Usage: ./local-stack.sh +set -euo pipefail + +cd "$(dirname "$0")" + +step() { printf '\n\033[1m==> %s\033[0m\n' "$1"; } + +# --- 1. Preconditions --------------------------------------------------------- +step "Checking prerequisites" +command -v docker >/dev/null 2>&1 || { echo "Docker not found. Install Docker and retry." >&2; exit 1; } +docker info >/dev/null 2>&1 || { echo "Docker daemon not running. Start Docker and retry." >&2; exit 1; } + +# --- 2. Env skeleton (idempotent: only writes if absent) ---------------------- +step "Ensuring local env file" +if [ ! -f .env.local ]; then + if [ -f .env.example ]; then + cp .env.example .env.local + echo "Created .env.local from .env.example — fill in any blanks." + else + cat > .env.local <<'EOF' +# Local development env — fill in real values. Do NOT commit this file. +NODE_ENV=development +# DATABASE_URL= +# NEXT_PUBLIC_API_URL=http://localhost:3000 +EOF + echo "Created a starter .env.local — fill in real values." + fi +else + echo ".env.local already present — leaving it untouched." +fi + +# --- 3. Bring up backing services (idempotent) -------------------------------- +# Compose `up -d` is idempotent: existing healthy containers are left running. +step "Starting backing services" +# EDIT: replace with your stack's bring-up. +# docker compose: docker compose up -d +# supabase: supabase start +docker compose up -d 2>/dev/null || echo "No docker-compose service to start (edit local-stack.sh)." + +# --- 4. Apply migrations (forward-only; never reset) -------------------------- +step "Applying migrations" +# EDIT: replace with your migration command. Use the FORWARD-only command. +# supabase: supabase migration up +# prisma: npx prisma migrate deploy +# drizzle: npx drizzle-kit migrate +echo "TODO: wire your forward-only migration command here." + +# --- 5. Seed dev data (must be idempotent: upsert, not insert) ---------------- +step "Seeding development data" +# EDIT: replace with your idempotent seed command. +# npm run db:seed-dev +echo "TODO: wire your idempotent seed command here." + +# --- 6. Verify required env -------------------------------------------------- +if [ -x ./verify-env.sh ]; then + step "Verifying environment" + set -a; [ -f .env.local ] && . ./.env.local; set +a + ./verify-env.sh || echo "WARN: some env keys are missing (see above)." +fi + +step "Local stack ready" +echo "Start the app with your dev command (e.g. npm run dev)." diff --git a/examples/verify-env.sh b/examples/verify-env.sh new file mode 100755 index 00000000..9888815f --- /dev/null +++ b/examples/verify-env.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# verify-env.sh — fail fast on missing required env keys. +# +# Run before `dev`, `build`, or `deploy` so a missing key fails loudly here +# instead of as a cryptic runtime error later. Reports *all* missing keys at +# once, not just the first. Checks presence only — it never prints values. +# +# Usage: +# ./verify-env.sh # check the keys listed below +# ./verify-env.sh KEY_A KEY_B # check the keys you pass instead +# source .env.local && ./verify-env.sh # check what's in a dotenv file +set -euo pipefail + +# --- Required keys: edit this list for your project --------------------------- +REQUIRED_DEFAULT=( + DATABASE_URL + # NEXT_PUBLIC_API_URL + # AUTH_SECRET +) + +# Keys required only outside local dev (e.g. live payment/email providers). +REQUIRED_PROD=( + # PAYMENT_API_KEY + # EMAIL_API_KEY +) +# ----------------------------------------------------------------------------- + +REQUIRED=("$@") +if [ ${#REQUIRED[@]} -eq 0 ]; then + REQUIRED=("${REQUIRED_DEFAULT[@]}") + if [ "${NODE_ENV:-development}" = "production" ]; then + REQUIRED+=("${REQUIRED_PROD[@]}") + fi +fi + +missing=() +for key in "${REQUIRED[@]}"; do + # Missing OR empty both count as not set. + if [ -z "${!key:-}" ]; then + missing+=("$key") + fi +done + +if [ ${#missing[@]} -gt 0 ]; then + echo "ERROR: missing required environment variables:" >&2 + for key in "${missing[@]}"; do + echo " - $key" >&2 + done + echo "" >&2 + echo "Set them in your environment or .env file. See .env.example." >&2 + exit 1 +fi + +echo "env OK — ${#REQUIRED[@]} required key(s) present." diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 00000000..9c3a512f --- /dev/null +++ b/scripts/README.md @@ -0,0 +1,63 @@ +# scripts + +Portable, harness-agnostic governance scripts. Pure `bash` (`#!/usr/bin/env bash`, +`set -euo pipefail`), no project-specific assumptions. They are **advisory** — +they report PASS/WARN/FAIL and exit non-zero on a finding, but never mutate the +project on their own. Wire them into hooks/CI or run by hand. + +## Scripts + +| Script | Purpose | Exit | +|---|---|---| +| `dep-add-check.sh` | Gate before adding a dependency: enforce **exact version pin**, **SHA-256 integrity** vs the registry (npm/PyPI/crates.io), and a **triage hook point** (license / maintenance / CVE). Hardens against supply-chain incidents — never install an unpinned range. | 0 pass / 1 needs-attention / 2 usage | +| `skills-hash-verify.sh` | Recompute the SHA-256 of each agent-skill directory and compare to `skills-lock.json`. Flags drift, missing, and unlocked (unreviewed) skills. `update` subcommand re-pins after an intentional change. | 0 match / 1 drift / 2 usage | +| `agent-config-version.sh` | Release command / upgrade path for a synced agent-config bundle: bump the bundle's semver, re-pin every skill hash (delegates to `skills-hash-verify.sh update`), stamp the version into `skills-lock.json`, and promote the `CHANGELOG.md` Unreleased section to a dated release. `--dry-run` previews. | 0 done / 1 refused / 2 usage | + +### `dep-add-check.sh` + +```bash +dep-add-check.sh npm left-pad@1.3.0 +dep-add-check.sh pip requests==2.32.3 +dep-add-check.sh cargo serde@1.0.210 +# Plug in your org triage command (runs as: ): +DEP_TRIAGE_CMD="your-org triage" dep-add-check.sh npm express@4.21.0 +``` + +Ecosystem is inferred from the spec (`==` → pip, `@` → npm, or pass `npm|pip|cargo`). +With no triage command configured it prints the manual triage checklist and WARNs +so a human decides. + +### `skills-hash-verify.sh` + +```bash +skills-hash-verify.sh # verify against ./skills-lock.json +skills-hash-verify.sh update # re-pin all skills after an intentional edit +skills-hash-verify.sh --skills-dir ./.agents/skills --lock ./skills-lock.json verify +``` + +Canonical skill hash = SHA-256 over the sorted `\n` of +every file in the skill dir (deterministic, follows symlinks). A starter lock +format lives at `templates/skills-lock.json`. + +### `agent-config-version.sh` + +```bash +agent-config-version.sh minor # bump, re-pin hashes, cut release +agent-config-version.sh --set 1.0.0 # release an explicit version +agent-config-version.sh --dry-run patch # preview without writing +agent-config-version.sh minor --skills-dir ./.agents/skills \ + --lock ./skills-lock.json --changelog ./CHANGELOG.md +``` + +The upgrade path for an agent-config bundle synced across machines: bumps the +semver, re-pins every skill's content hash (so consumers can detect drift after a +sync), stamps the version into the lock, and promotes the `CHANGELOG.md` +Unreleased notes into a dated release with a fresh stub. Refuses to release an +empty Unreleased section unless `--allow-empty`. Templates: +`templates/{skills-lock.json,CHANGELOG.md}`. + +## Requirements + +`bash`, `curl`, `python3` (json parsing), and `sha256sum` **or** `shasum`. +`dep-add-check.sh` additionally uses `npm` (node integrity) and `openssl` +(sha512 SRI compare) when present; missing tools degrade to a WARN, not a crash. diff --git a/scripts/agent-config-version.sh b/scripts/agent-config-version.sh new file mode 100755 index 00000000..faed2c54 --- /dev/null +++ b/scripts/agent-config-version.sh @@ -0,0 +1,164 @@ +#!/usr/bin/env bash +# agent-config-version.sh — cut a new version of your agent-config bundle. +# +# WHY: A portable agent-config bundle (skills + lock + changelog) synced across +# machines needs a deterministic upgrade path: bump a version, re-pin every +# skill's content hash so drift is detectable, and record what changed. This is +# the release command that ties skills-lock.json and CHANGELOG.md together so +# "which version is this machine on, and what moved?" always has an answer. +# +# WHAT IT DOES (in order): +# 1. Compute the next semver from the current skills-lock.json + the bump kind. +# 2. Re-pin content hashes by delegating to skills-hash-verify.sh update +# (single source of the hashing algorithm — never reimplemented here). +# 3. Stamp the new top-level version + generatedAt, and set each skill's +# `version` to the release version, into skills-lock.json. +# 4. Promote the CHANGELOG `Unreleased` section to a dated `[x.y.z]` release and +# open a fresh empty `Unreleased` stub above it. +# +# IDEMPOTENT-ish: re-running with the same bump after a release is a no-op on the +# changelog header (it refuses to release an empty Unreleased unless --allow-empty). +# +# Exit codes: 0 done · 1 refused (e.g. empty changelog, drift unresolved) · 2 usage. +# +# Usage: +# agent-config-version.sh +# agent-config-version.sh --set 1.2.0 +# agent-config-version.sh minor --lock ./skills-lock.json --changelog ./CHANGELOG.md \ +# --skills-dir ./.agents/skills [--allow-empty] [--dry-run] +# +set -euo pipefail + +PROG="$(basename "$0")" +HERE="$(cd "$(dirname "$0")" && pwd)" +LOCK="./skills-lock.json" +CHANGELOG="./CHANGELOG.md" +SKILLS_DIR="" +HASH_VERIFY="$HERE/skills-hash-verify.sh" +BUMP="" +SET_VERSION="" +ALLOW_EMPTY=0 +DRY_RUN=0 + +die() { printf '%s: error: %s\n' "$PROG" "$1" >&2; exit 2; } + +while [ $# -gt 0 ]; do + case "$1" in + major|minor|patch) BUMP="$1"; shift;; + --set) SET_VERSION="${2:?}"; shift 2;; + --lock) LOCK="${2:?}"; shift 2;; + --changelog) CHANGELOG="${2:?}"; shift 2;; + --skills-dir) SKILLS_DIR="${2:?}"; shift 2;; + --hash-verify) HASH_VERIFY="${2:?}"; shift 2;; + --allow-empty) ALLOW_EMPTY=1; shift;; + --dry-run) DRY_RUN=1; shift;; + -h|--help) sed -n '2,33p' "$0"; exit 0;; + *) die "unknown arg: $1";; + esac +done + +[ -n "$BUMP" ] || [ -n "$SET_VERSION" ] || die "specify a bump (major|minor|patch) or --set X.Y.Z" +[ -f "$LOCK" ] || die "lock file not found: $LOCK (copy templates/skills-lock.json)" +[ -f "$CHANGELOG" ] || die "changelog not found: $CHANGELOG (copy templates/CHANGELOG.md)" +[ -x "$HASH_VERIFY" ] || command -v bash >/dev/null 2>&1 || die "skills-hash-verify.sh not runnable: $HASH_VERIFY" +command -v python3 >/dev/null 2>&1 || die "python3 required" + +# ---- compute current + next version ------------------------------------------- +CUR="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("version","0.0.0"))' "$LOCK")" + +next_version() { + python3 - "$CUR" "$BUMP" "$SET_VERSION" <<'PY' +import re, sys +cur, bump, explicit = sys.argv[1], sys.argv[2], sys.argv[3] +if explicit: + if not re.fullmatch(r"\d+\.\d+\.\d+", explicit): + sys.exit("error: --set must be X.Y.Z") + print(explicit); raise SystemExit +m = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", cur or "0.0.0") +if not m: sys.exit(f"error: current version not semver: {cur!r}") +a, b, c = map(int, m.groups()) +if bump == "major": a, b, c = a + 1, 0, 0 +elif bump == "minor": b, c = b + 1, 0 +elif bump == "patch": c = c + 1 +else: sys.exit(f"error: unknown bump {bump!r}") +print(f"{a}.{b}.{c}") +PY +} +NEW="$(next_version)" +TODAY="$(date -u +%Y-%m-%d)" +NOW="$(date -u +%Y-%m-%dT%H:%M:%SZ)" +printf '== agent-config-version: %s -> %s (%s) ==\n' "$CUR" "$NEW" "$TODAY" + +if [ "$DRY_RUN" -eq 1 ]; then + echo "DRY-RUN: would re-pin hashes, set version=$NEW in $LOCK, and release [$NEW] in $CHANGELOG" + exit 0 +fi + +# ---- step 1: re-pin content hashes via the canonical hasher -------------------- +# Delegate hashing to skills-hash-verify so the algorithm lives in exactly one place. +HV_ARGS=(--lock "$LOCK") +[ -n "$SKILLS_DIR" ] && HV_ARGS+=(--skills-dir "$SKILLS_DIR") +echo "-- re-pinning skill hashes (skills-hash-verify update) --" +bash "$HASH_VERIFY" "${HV_ARGS[@]}" update + +# ---- step 2: stamp version (top-level + per-skill) into the lock --------------- +python3 - "$LOCK" "$NEW" "$NOW" <<'PY' +import json, sys +lock_path, new, now = sys.argv[1], sys.argv[2], sys.argv[3] +lock = json.load(open(lock_path)) +lock["version"] = new +lock["generatedAt"] = now +for entry in lock.get("skills", {}).values(): + entry.setdefault("version", new) + entry["version"] = new +json.dump(lock, open(lock_path, "w"), indent=2, ensure_ascii=False) +open(lock_path, "a").write("\n") +PY +echo "-- stamped version $NEW into $LOCK --" + +# ---- step 3: promote CHANGELOG Unreleased -> [NEW] - DATE, open fresh stub ------ +python3 - "$CHANGELOG" "$NEW" "$TODAY" "$ALLOW_EMPTY" <<'PY' +import re, sys +path, new, today, allow_empty = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] == "1" +text = open(path).read() + +m = re.search(r"(?im)^##\s*\[Unreleased\].*?$", text) +if not m: + sys.exit("error: no '## [Unreleased]' heading in changelog") +start = m.start() +# Body of Unreleased = everything up to the next '## ' heading (or EOF). +nxt = re.search(r"(?m)^##\s", text[m.end():]) +body_end = m.end() + (nxt.start() if nxt else len(text) - m.end()) +unreleased_body = text[m.end():body_end] + +# Refuse an empty release (only headings, no bullet content) unless allowed. +has_content = bool(re.search(r"(?m)^\s*[-*]\s+\S", unreleased_body)) +if not has_content and not allow_empty: + sys.exit("error: Unreleased section has no entries; add notes or pass --allow-empty") + +UNRELEASED_STUB = ( + "## [Unreleased]\n\n" + "### Added\n\n### Changed\n\n### Deprecated\n\n" + "### Removed\n\n### Fixed\n\n### Security\n\n" +) +released_header = f"## [{new}] - {today}\n" +new_block = UNRELEASED_STUB + released_header + unreleased_body +text = text[:start] + new_block + text[body_end:] + +# Maintain comparison links at the bottom if the template's pattern is present. +if re.search(r"(?m)^\[Unreleased\]:\s*\S+compare/\S+", text): + base = re.search(r"(?m)^\[Unreleased\]:\s*(\S+)compare/", text).group(1) + text = re.sub(r"(?m)^\[Unreleased\]:.*$", + f"[Unreleased]: {base}compare/v{new}...HEAD", text) + rel = f"[{new}]: {base}releases/tag/v{new}" + if f"\n[{new}]:" not in text: + text = re.sub(r"(?m)^(\[Unreleased\]:.*)$", r"\1\n" + rel, text, count=1) + +open(path, "w").write(text) +PY +echo "-- released [$NEW] in $CHANGELOG (fresh Unreleased stub opened) --" + +echo "------------------------------------------" +echo "DONE agent-config bundle is now v$NEW." +echo " review: git diff -- $LOCK $CHANGELOG" +echo " then tag: git commit -am \"chore(release): v$NEW\" && git tag v$NEW" diff --git a/scripts/dep-add-check.sh b/scripts/dep-add-check.sh new file mode 100755 index 00000000..91644ae8 --- /dev/null +++ b/scripts/dep-add-check.sh @@ -0,0 +1,184 @@ +#!/usr/bin/env bash +# dep-add-check.sh — gate before adding a third-party dependency. +# +# WHY: Real-world supply-chain incidents (a malicious/compromised package version +# pulled in via an unpinned range) show that "npm install " with a caret/ +# tilde range trusts whatever the registry serves at install time. This script +# forces three things BEFORE a dep lands in the manifest: +# 1. EXACT version pin (no ^, ~, *, latest, ranges). +# 2. SHA-256 integrity check of the resolved tarball against the registry. +# 3. A triage gate hook point (license / maintenance / known-CVE review). +# +# Portable: npm/yarn/pnpm (node), pip (python), cargo (rust). Detects ecosystem +# from the argument syntax or the --eco flag. +# +# ADVISORY by default: prints PASS/WARN/FAIL and a recommendation. It does NOT +# install anything. Wire it into a pre-add hook or run it by hand. Exit codes: +# 0 = PASS (pinned + integrity verified + triage clean-or-acknowledged) +# 1 = WARN (something needs human attention; do not auto-proceed) +# 2 = usage / environment error +# +# Usage: +# dep-add-check.sh npm left-pad@1.3.0 +# dep-add-check.sh pip requests==2.32.3 +# dep-add-check.sh cargo serde@1.0.210 +# dep-add-check.sh --eco npm express@4.21.0 +# +set -euo pipefail + +PROG="$(basename "$0")" + +die() { printf '%s: error: %s\n' "$PROG" "$1" >&2; exit 2; } +warn() { printf 'WARN %s\n' "$1"; } +ok() { printf 'PASS %s\n' "$1"; } +bad() { printf 'FAIL %s\n' "$1"; } +note() { printf ' %s\n' "$1"; } + +[ $# -ge 1 ] || die "usage: $PROG [--triage-cmd ]" + +ECO="" +SPEC="" +# Allow a project-supplied triage command (e.g. an org triage wrapper). +TRIAGE_CMD="${DEP_TRIAGE_CMD:-}" + +while [ $# -gt 0 ]; do + case "$1" in + --eco) ECO="${2:-}"; shift 2;; + --triage-cmd) TRIAGE_CMD="${2:-}"; shift 2;; + npm|yarn|pnpm) ECO="node"; shift;; + pip|pip3) ECO="python"; shift;; + cargo) ECO="rust"; shift;; + -h|--help) sed -n '2,40p' "$0"; exit 0;; + *) SPEC="$1"; shift;; + esac +done + +[ -n "$SPEC" ] || die "no package spec given" + +# ---- Parse name + version, infer ecosystem if not set -------------------------- +NAME=""; VERSION="" +case "$SPEC" in + *==*) NAME="${SPEC%%==*}"; VERSION="${SPEC##*==}"; ECO="${ECO:-python}";; + *@*) # last @ separates version (scoped npm names start with @) + VERSION="${SPEC##*@}"; NAME="${SPEC%@*}"; ECO="${ECO:-node}";; + *) NAME="$SPEC";; +esac +[ -n "$ECO" ] || die "could not infer ecosystem; pass npm|pip|cargo or --eco" + +printf '== dep-add-check: %s (%s) ==\n' "$SPEC" "$ECO" + +STATUS=0 # 0 pass, 1 warn + +# ---- Gate 1: exact pin --------------------------------------------------------- +if [ -z "$VERSION" ]; then + bad "no version pinned. Refusing an unpinned/range install." + note "Re-run as ${NAME}@ (npm/cargo) or ${NAME}== (pip)." + exit 1 +fi +case "$VERSION" in + *"^"*|*"~"*|*"*"*|*">"*|*"<"*|latest|"") + bad "version '$VERSION' is a range/floating tag. Pin an EXACT version." + STATUS=1;; + *) + ok "version pinned exactly: $VERSION";; +esac + +# ---- Gate 2: SHA-256 integrity vs registry ------------------------------------- +sha256() { + if command -v sha256sum >/dev/null 2>&1; then sha256sum | awk '{print $1}' + else shasum -a 256 | awk '{print $1}'; fi +} + +verify_integrity_node() { + command -v npm >/dev/null 2>&1 || { warn "npm not found; skipping integrity check"; return 1; } + # npm view returns the registry-published integrity (SRI) + tarball URL. + local sri url tmp got_b64 want_b64 + sri="$(npm view "${NAME}@${VERSION}" dist.integrity 2>/dev/null || true)" + url="$(npm view "${NAME}@${VERSION}" dist.tarball 2>/dev/null || true)" + if [ -z "$url" ]; then warn "registry has no tarball for ${NAME}@${VERSION}"; return 1; fi + tmp="$(mktemp)"; trap 'rm -f "$tmp"' RETURN + if ! curl -fsSL "$url" -o "$tmp"; then warn "could not download tarball to verify"; return 1; fi + if [ -n "$sri" ] && [ "${sri#sha512-}" != "$sri" ]; then + # Registry SRI is sha512; recompute sha512 of downloaded tarball and compare. + want_b64="${sri#sha512-}" + if command -v openssl >/dev/null 2>&1; then + got_b64="$(openssl dgst -sha512 -binary "$tmp" | openssl base64 -A)" + if [ "$got_b64" = "$want_b64" ]; then ok "tarball matches registry SRI (sha512)"; else + bad "tarball SHA mismatch vs registry SRI — possible tampering. ABORT."; return 1; fi + else warn "openssl missing; cannot verify sha512 SRI"; return 1; fi + fi + # Also surface the sha256 of the exact artifact so it can be recorded/pinned. + note "sha256(tarball)=$(sha256 < "$tmp")" + return 0 +} + +verify_integrity_python() { + command -v curl >/dev/null 2>&1 || { warn "curl not found; skipping"; return 1; } + local json digest + json="$(curl -fsSL "https://pypi.org/pypi/${NAME}/${VERSION}/json" 2>/dev/null || true)" + [ -n "$json" ] || { warn "PyPI has no ${NAME}==${VERSION}"; return 1; } + if command -v python3 >/dev/null 2>&1; then + digest="$(printf '%s' "$json" | python3 -c 'import sys,json; d=json.load(sys.stdin); print(next((u["digests"]["sha256"] for u in d.get("urls",[]) if u["digests"].get("sha256")),""))' 2>/dev/null || true)" + [ -n "$digest" ] && ok "PyPI publishes sha256=$digest for ${NAME}==${VERSION}" || { warn "no sha256 digest on PyPI record"; return 1; } + note "pin with a hash: pip install --require-hashes (add to requirements: ${NAME}==${VERSION} --hash=sha256:${digest})" + else warn "python3 missing; cannot parse PyPI json"; return 1; fi + return 0 +} + +verify_integrity_rust() { + command -v curl >/dev/null 2>&1 || { warn "curl not found; skipping"; return 1; } + local json cksum tmp + json="$(curl -fsSL "https://crates.io/api/v1/crates/${NAME}/${VERSION}" 2>/dev/null || true)" + [ -n "$json" ] || { warn "crates.io has no ${NAME}@${VERSION}"; return 1; } + if command -v python3 >/dev/null 2>&1; then + cksum="$(printf '%s' "$json" | python3 -c 'import sys,json; print(json.load(sys.stdin)["version"]["checksum"])' 2>/dev/null || true)" + fi + if [ -n "${cksum:-}" ]; then + tmp="$(mktemp)"; trap 'rm -f "$tmp"' RETURN + if curl -fsSL "https://crates.io/api/v1/crates/${NAME}/${VERSION}/download" -o "$tmp"; then + if [ "$(sha256 < "$tmp")" = "$cksum" ]; then ok ".crate matches crates.io sha256 checksum"; else + bad ".crate SHA mismatch vs crates.io — possible tampering. ABORT."; return 1; fi + else warn "could not download .crate to verify"; return 1; fi + else warn "no checksum on crates.io record"; return 1; fi + return 0 +} + +# Only attempt registry integrity once we have an exact, well-formed version. +if [ "$STATUS" -ne 0 ]; then + warn "skipping integrity check until an exact version is pinned" +else + case "$ECO" in + node) verify_integrity_node || STATUS=1;; + python) verify_integrity_python || STATUS=1;; + rust) verify_integrity_rust || STATUS=1;; + *) warn "no integrity verifier for ecosystem '$ECO'"; STATUS=1;; + esac +fi + +# ---- Gate 3: triage hook point ------------------------------------------------- +# Policy (see your project agent-config / CONTRIBUTING): run a triage command +# before installing anything new. If a triage command is configured, run it and +# honor its exit code. If none is configured, emit the manual checklist and WARN +# so a human decides. +if [ -n "$TRIAGE_CMD" ]; then + printf '== triage: %s %s %s ==\n' "$TRIAGE_CMD" "$ECO" "$NAME" + if "$TRIAGE_CMD" "$ECO" "$NAME"; then ok "triage gate passed"; else + bad "triage gate did NOT pass — stop and escalate before installing."; STATUS=1; fi +else + warn "no triage command configured (DEP_TRIAGE_CMD / --triage-cmd). Manual triage required:" + note "- License compatible with project? (no GPL surprise in a permissive codebase)" + note "- Maintained? (recent commits, >1 maintainer, not a typosquat of a popular name)" + note "- Known CVEs? (osv.dev / npm audit / pip-audit / cargo audit)" + note "- Footprint justified? (no 200-dep tree for a one-liner)" + STATUS=1 +fi + +# ---- Verdict ------------------------------------------------------------------- +echo "------------------------------------------" +if [ "$STATUS" -eq 0 ]; then + ok "OK to add ${NAME}@${VERSION} — pinned, integrity-verified, triage clean." + exit 0 +else + bad "NOT clear to auto-add ${NAME} — resolve the WARN/FAIL items above first." + exit 1 +fi diff --git a/scripts/skills-hash-verify.sh b/scripts/skills-hash-verify.sh new file mode 100755 index 00000000..097ffbb8 --- /dev/null +++ b/scripts/skills-hash-verify.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +# skills-hash-verify.sh — verify installed skills against skills-lock.json (SHA-256). +# +# WHY: Skills are executable instructions an agent will follow. A silently +# modified or swapped skill is a supply-chain risk equivalent to a tampered +# dependency. skills-lock.json pins a SHA-256 per skill; this script recomputes +# the hash of each skill directory and compares. Drift => investigate before use. +# +# Lock format (see templates/skills-lock.json): +# { "version": 1, "skills": { "": { "source": "...", +# "sourceType": "well-known|vendored|local", "computedHash": "" } } } +# +# Canonical hash = SHA-256 over the sorted list of "\n\n" +# for every regular file under the skill dir (deterministic across machines). +# +# Modes: +# verify (default) — compare each locked skill's current hash to the lock; report drift. +# update — recompute and rewrite computedHash for all skills (use after an +# intentional change; review the diff before committing). +# +# ADVISORY exit codes: +# 0 = all locked skills match +# 1 = drift detected (hash mismatch, missing dir, or unlocked skill present) +# 2 = usage / environment error +# +# Usage: +# skills-hash-verify.sh [--lock ] [--skills-dir ] [verify|update] +# Defaults: --lock ./skills-lock.json --skills-dir ./.agents/skills (fallback .claude/skills) +# +set -euo pipefail + +PROG="$(basename "$0")" +LOCK="./skills-lock.json" +SKILLS_DIR="" +MODE="verify" + +die() { printf '%s: error: %s\n' "$PROG" "$1" >&2; exit 2; } + +while [ $# -gt 0 ]; do + case "$1" in + --lock) LOCK="${2:?}"; shift 2;; + --skills-dir) SKILLS_DIR="${2:?}"; shift 2;; + verify|update) MODE="$1"; shift;; + -h|--help) sed -n '2,32p' "$0"; exit 0;; + *) die "unknown arg: $1";; + esac +done + +# Default skills dir: prefer .agents/skills (source of truth), else .claude/skills. +if [ -z "$SKILLS_DIR" ]; then + if [ -d "./.agents/skills" ]; then SKILLS_DIR="./.agents/skills" + elif [ -d "./.claude/skills" ]; then SKILLS_DIR="./.claude/skills" + else die "no skills dir found (.agents/skills or .claude/skills); pass --skills-dir"; fi +fi +command -v python3 >/dev/null 2>&1 || die "python3 required (json parse/edit)" +# verify needs an existing lock; update may create one from scratch. +if [ "$MODE" = "verify" ] && [ ! -f "$LOCK" ]; then die "lock file not found: $LOCK"; fi +if [ ! -f "$LOCK" ]; then printf '{\n "version": 1,\n "skills": {}\n}\n' > "$LOCK"; fi + +# ---- portable per-file sha256 -------------------------------------------------- +file_sha256() { + if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}' + else shasum -a 256 "$1" | awk '{print $1}'; fi +} + +# ---- canonical hash of a skill directory -------------------------------------- +# Follows symlinks (skills are often symlinked from .agents into .claude). +# Excludes VCS/OS noise so the hash reflects skill content only. +skill_dir_hash() { + local dir="$1" rel f h + local manifest; manifest="$(mktemp)" + while IFS= read -r f; do + rel="${f#"$dir"/}" + h="$(file_sha256 "$f")" + printf '%s\n%s\n' "$rel" "$h" >> "$manifest" + done < <(find -L "$dir" -type f \ + ! -path '*/.git/*' ! -name '.DS_Store' ! -name 'Thumbs.db' \ + | LC_ALL=C sort) + if command -v sha256sum >/dev/null 2>&1; then sha256sum "$manifest" | awk '{print $1}' + else shasum -a 256 "$manifest" | awk '{print $1}'; fi + rm -f "$manifest" +} + +# ---- list skill names from the lock ------------------------------------------- +locked_skills() { + python3 -c 'import json,sys; print("\n".join(json.load(open(sys.argv[1])).get("skills",{}).keys()))' "$LOCK" +} + +DRIFT=0 + +if [ "$MODE" = "verify" ]; then + printf '== skills-hash-verify (%s) ==\n' "$SKILLS_DIR" + # 1) every locked skill must exist and match + while IFS= read -r name; do + [ -n "$name" ] || continue + want="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["skills"][sys.argv[2]].get("computedHash",""))' "$LOCK" "$name")" + sdir="$SKILLS_DIR/$name" + if [ ! -d "$sdir" ]; then printf 'MISSING %-32s (locked but no directory)\n' "$name"; DRIFT=1; continue; fi + got="$(skill_dir_hash "$sdir")" + if [ "$got" = "$want" ]; then printf 'OK %-32s %s\n' "$name" "${got:0:12}…" + else printf 'DRIFT %-32s want %s got %s\n' "$name" "${want:0:12}…" "${got:0:12}…"; DRIFT=1; fi + done < <(locked_skills) + + # 2) flag installed skills that are NOT in the lock (unpinned = unreviewed) + while IFS= read -r d; do + [ -d "$d" ] || continue + n="$(basename "$d")" + if ! locked_skills | grep -qxF "$n"; then printf 'UNLOCKED %-32s (present but not in lock)\n' "$n"; DRIFT=1; fi + done < <(find -L "$SKILLS_DIR" -mindepth 1 -maxdepth 1 -type d | LC_ALL=C sort) + + echo "------------------------------------------" + if [ "$DRIFT" -eq 0 ]; then echo "PASS all locked skills match"; exit 0 + else echo "FAIL skill drift detected — review changes, then run '$PROG update' if intentional"; exit 1; fi + +elif [ "$MODE" = "update" ]; then + printf '== skills-hash-verify update (%s) ==\n' "$SKILLS_DIR" + TMP="$(mktemp)" + # Build name=hash pairs for every skill dir present, then merge into the lock. + PAIRS="$(mktemp)" + while IFS= read -r d; do + [ -d "$d" ] || continue + n="$(basename "$d")" + printf '%s\t%s\n' "$n" "$(skill_dir_hash "$d")" >> "$PAIRS" + done < <(find -L "$SKILLS_DIR" -mindepth 1 -maxdepth 1 -type d | LC_ALL=C sort) + + python3 - "$LOCK" "$PAIRS" > "$TMP" <<'PY' +import json, sys +lock_path, pairs_path = sys.argv[1], sys.argv[2] +lock = json.load(open(lock_path)) +lock.setdefault("version", 1) +skills = lock.setdefault("skills", {}) +for line in open(pairs_path): + name, h = line.rstrip("\n").split("\t", 1) + entry = skills.setdefault(name, {"source": "local", "sourceType": "local"}) + entry["computedHash"] = h +print(json.dumps(lock, indent=2, ensure_ascii=False)) +PY + mv "$TMP" "$LOCK"; rm -f "$PAIRS" + echo "PASS lock updated: $LOCK (review the diff before committing)" + exit 0 +fi