#!/usr/bin/env python3
"""Find Claude Code settings files that hold secrets or are tracked by git.

Usage: python3 claude-secret-check.py [folder]   (default: your home folder)
Read-only. Secret values are masked. It matches patterns, so a clean result is not proof of safety.
By chalkesahil.ai
"""
import json, os, re, subprocess, sys

ROOT = os.path.expanduser(sys.argv[1] if len(sys.argv) > 1 else "~")
SKIP = {"Library", ".Trash", "node_modules", ".git", ".cache", ".npm", ".cargo", ".rustup", "Pictures", "Music", "Movies",
        ".venv", "venv", ".pyenv", ".nvm", ".gradle", ".m2", "site-packages", ".docker", ".orbstack"}
NAMES = ("settings.local.json", "settings.json")
PATTERNS = [
    ("password in command", r"(?i)(--?pass(?:word|wd)?|pwd|passwd)[=\s:]+['\"]?([^\s'\")]+)"),
    ("user:pass@ in URL", r"://[^/\s:@]+:([^@\s/]+)@"),
    ("token or secret value", r"(?i)(token|secret|api[_-]?key)[=:\s]+['\"]?([A-Za-z0-9_\-\.]{8,})"),
    ("bearer header", r"(?i)bearer\s+([A-Za-z0-9_\-\.=]{8,})"),
    ("AWS key id", r"\b(AKIA[0-9A-Z]{16})\b"),
    ("GitHub token", r"\b(gh[pousr]_[A-Za-z0-9]{20,})\b"),
    ("API key (sk-...)", r"\b(sk-[A-Za-z0-9_\-]{20,})\b"),
    ("Slack token", r"\b(xox[abprs]-[A-Za-z0-9\-]{10,})\b"),
]


def mask(v):
    return v[:2] + "***" if len(v) > 2 else "***"


SAFE = ["-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "core.pager=cat", "-c", "diff.external="]


def git(d, *a):
    # Repos found on disk are untrusted: switch off config that can run programs.
    if not os.path.exists(os.path.join(d, ".git")):
        return subprocess.CompletedProcess([], 1, "", "")
    return subprocess.run(["git", "--no-optional-locks", *SAFE, "-C", d, *a], capture_output=True, text=True)


found = []
for dp, dn, fn in os.walk(ROOT):
    dn[:] = [d for d in dn if d not in SKIP]
    if os.path.basename(dp) == ".claude":
        for n in NAMES:
            if n in fn:
                found.append(os.path.join(dp, n))

if not found:
    print("No Claude Code settings files found under", ROOT)
    sys.exit(0)

bad = 0
for f in sorted(found):
    repo = os.path.dirname(os.path.dirname(f))
    rel = os.path.relpath(f, repo)
    try:
        rules = json.load(open(f)).get("permissions", {}).get("allow", [])
    except Exception:
        rules = []
    hits = []
    for r in rules:
        for label, p in PATTERNS:
            m = re.search(p, r)
            if m:
                hits.append((label, mask(m.group(m.lastindex or 0))))
                break
    local = rel.endswith("settings.local.json")
    tracked = local and git(repo, "ls-files", "--error-unmatch", rel).returncode == 0
    hist = git(repo, "log", "--all", "--oneline", "--", rel).stdout.strip().splitlines() if local else []
    flag = hits or tracked or hist
    bad += bool(flag)
    print(("RISK  " if flag else "ok    ") + f.replace(os.path.expanduser("~"), "~"))
    print(f"      {len(rules)} saved rules")
    for label, m in hits:
        print(f"      secret-like: {label}  ({m})")
    if tracked:
        print("      TRACKED by git. Fix: git rm --cached " + rel + " && echo '" + rel + "' >> .gitignore")
    if hist and not tracked:
        print(f"      in git history ({len(hist)} commits). Rotate anything it held.")

print()
print(f"{len(found)} files checked, {bad} need attention.")
if bad:
    print("Change every credential these files ever held, then untrack them.")
