#!/usr/bin/env python3 """agent-secret-sweep.py - find secrets your coding agents wrote down. Looks where agents record what they ran or learned: Claude Code allow rules (.claude/settings.local.json, .claude/settings.json), memory files (MEMORY.md, ~/.claude/projects/*/memory), CLAUDE.md / AGENTS.md, handoff notes, chat transcripts (.specstory) and VS Code auto-approve settings. Checks provider key formats AND passwords inside commands (PGPASSWORD=, sshpass -p, mysql -p, bearer headers, *_PASSWORD=), the shapes generic scanners tend to miss. Never prints a value: only file, line, kind, length and git status. python3 agent-secret-sweep.py [PATH ...] # default: . and ~/.claude/projects python3 agent-secret-sweep.py --canaries # fake lines to test a memory server Exit code: 0 nothing found, 1 findings, 2 usage error. Stdlib only. """ import os, re, sys, json, random, string, subprocess NAMES = {"settings.local.json", "settings.json", "MEMORY.md", "CLAUDE.md", "CLAUDE.local.md", "AGENTS.md", "AGENTS.override.md"} NAME_RE = re.compile(r"(handoff|hand-off|deploy[-_]?notes?|session[-_]?notes?)[^/]*\.(md|txt)$", re.I) DIR_HINTS = ("/.claude/", "/.specstory/", "/.cursor/", "/.gemini/", "/memory/") SKIP_DIRS = {"node_modules", ".git", ".next", "dist", "build", ".venv", "venv", "__pycache__", "target"} MAX_BYTES = 2_000_000 V = r"""([^\s'"$`{}()|;&<>]{6,})""" # a literal value, not $VAR / ${VAR} RULES = [ ("provider-key", re.compile(r"\b(sk-(?:proj-|ant-|or-v1-)?[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{30,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,}|(?:sk|rk)_live_[A-Za-z0-9]{20,}|sbp_[a-f0-9]{30,})")), ("private-key", re.compile(r"(-----BEGIN [A-Z ]*PRIVATE KEY-----)")), ("url-credentials", re.compile(r"[a-z][a-z0-9+.-]*://[^\s/:@'\"]{1,64}:([^\s/@'\"$]{3,128})@[^\s'\"]+", re.I)), ("env-password-in-command", re.compile(r"\b(?:PGPASSWORD|MYSQL_PWD|REDISCLI_AUTH|SSHPASS)=['\"]?" + V)), ("sshpass -p", re.compile(r"\bsshpass\s+-p\s*['\"]?" + V)), ("mysql -p", re.compile(r"\b(?:mysql|mysqldump|mariadb)\b[^\n]*?\s-p(?!\s)['\"]?" + V)), ("password flag", re.compile(r"--(?:password|passwd|pass|token|api-key|apikey)[= ]['\"]?" + V, re.I)), ("bearer header", re.compile(r"(?:Authorization:\s*)?\bBearer\s+" + V)), ("assigned secret", re.compile(r"\b[A-Z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API_KEY|APIKEY|SERVICE_ROLE_KEY)\s*[=:]\s*['\"]?" + V)), ("prose password", re.compile(r"\b(?:password|passwd|senha)\b\s*(?:is|=|:|é)?\s*['\"]?" + V, re.I)), ] WORDY = ("prose password", "bearer header") # "password manager", "Bearer tokens" NOT_A_VALUE = ("$", "${", "%", "secrets.", "env.", "process.env", "os.environ") PLACEHOLDER = re.compile(r"^(x{3,}|\*{3,}|\.{3,}|<[^>]*>|changeme|password|passwd|secret|token|example|placeholder|redacted|\[redacted\]|your[_-].*|dummy|test|null|none|true|false)$", re.I) def looks_like_word(val): """A plain word ("authentication", "manager,"): no digit, no symbol, no inner capital.""" word = val.rstrip(".,;:!?") return word.isalpha() and not any(c.isupper() for c in word[1:]) def is_candidate(path): base = os.path.basename(path) p = path.replace("\\", "/") if base in ("settings.json",) and "/.claude/" not in p and "/.vscode/" not in p: return False if base in NAMES or NAME_RE.search(base): return True return any(h in p for h in DIR_HINTS) and base.endswith((".md", ".json", ".txt", ".jsonl")) def git(args, cwd): try: return subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, timeout=20) except Exception: return None def git_status(path): d = os.path.dirname(os.path.abspath(path)) top = git(["rev-parse", "--show-toplevel"], d) if not top or top.returncode != 0: return "not in a git repo" root = top.stdout.strip(); rel = os.path.relpath(os.path.abspath(path), root) tracked = git(["ls-files", "--error-unmatch", rel], root) if tracked and tracked.returncode == 0: return "TRACKED by git (it is in the next push)" hist = git(["log", "--all", "--oneline", "-1", "--", rel], root) if hist and hist.stdout.strip(): return "NOT tracked now, but IN GIT HISTORY" ign = git(["check-ignore", "-v", rel], root) if ign and ign.returncode == 0: src = ign.stdout.split(":", 1)[0].replace("\\", "/") if src == ".git/info/exclude" or src.endswith("/.git/info/exclude"): where = "this clone's .git/info/exclude only (another clone is not covered)" elif not os.path.isabs(src) and not src.startswith("~"): where = "a .gitignore in the repo" else: where = "your global ignore only (a clone elsewhere is not covered)" return f"ignored by {where}" return "UNTRACKED and NOT ignored (git add -A takes it)" def scan_file(path): try: if os.path.getsize(path) > MAX_BYTES: return [] text = open(path, encoding="utf-8", errors="replace").read() except OSError: return [] out, seen = [], set() for n, line in enumerate(text.splitlines(), 1): for kind, rx in RULES: for m in rx.finditer(line): val = m.group(1) if PLACEHOLDER.match(val.strip("'\"")) or val.startswith(NOT_A_VALUE): continue if kind in WORDY and looks_like_word(val): continue if kind in ("prose password", "assigned secret", "bearer header") and len(set(val)) < 5: continue key = (n, m.start(1)) if key in seen: continue seen.add(key) out.append((n, kind, len(val))) return out def walk(roots): for root in roots: root = os.path.expanduser(root) if not os.path.exists(root): continue if os.path.isfile(root): yield root; continue for d, dirs, files in os.walk(root): dirs[:] = [x for x in dirs if x not in SKIP_DIRS] for f in files: p = os.path.join(d, f) if is_candidate(p): yield p def canaries(): a = string.ascii_letters + string.digits r = lambda n: "".join(random.choice(a) for _ in range(n)) pw, host = r(11) + random.choice(string.digits), "db.canary.example.com" lines = [ f"PGPASSWORD={pw} psql -h {host} -U postgres -c 'select 1'", f"sshpass -p '{pw}' ssh root@{host} uptime", f"mysql -h {host} -u admin -p{pw} -e 'show tables'", f"curl -H 'Authorization: Bearer {r(20)}' https://api.canary.example.com/v1/orders", f"Staging DB: user postgres, password {pw} on {host}", f"DATABASE_PASSWORD={pw} (set before the migration)", f"psql postgresql://app:{pw}@{host}:5432/app", ] print("# Fake credentials, generated now, pointing at example.com. Store each line in your") print("# memory server as an agent would, read it back, and check what came back verbatim.") print(f"# Grep marker: {pw}") for l in lines: print(l) def main(argv): if "--canaries" in argv: canaries(); return 0 if any(a.startswith("-") for a in argv): print(__doc__); return 2 missing = [a for a in argv if not os.path.exists(os.path.expanduser(a))] if missing: print(f"No such file or folder: {', '.join(missing)}", file=sys.stderr); return 2 roots = argv or [".", "~/.claude/projects"] files = sorted(set(walk(roots))) total = 0 for f in files: hits = scan_file(f) if not hits: continue total += len(hits) print(f"\n{f}\n git: {git_status(f)}") for n, kind, ln in hits: print(f" line {n}: {kind} ({ln} chars)") print(f"\nScanned {len(files)} agent files, {total} possible secret(s).") if total: print("Rotate first, then delete the rule or line. Write $VAR in commands so the agent records the name, not the value.") return 1 if total else 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))