cyberdeck-urt/scripts/git-hooks/pre-commit
orca 0a99c4d0a8 cyberdeck-urt: endless Urban Terror bot arena (server image, companion, deploy)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:22:54 -05:00

73 lines
3.3 KiB
Python
Executable file

#!/usr/bin/env python3
"""Refuse a commit that contains any secret from the plugin credential files.
Every value in the credential files under ~/.config/herdr/plugins/config
(credentials*.json, kasa.json, token files) and every secret-named field
(password, token, client id, username, ...) in the other settings files there
is compared against the staged diff. If one
appears anywhere, even pasted into a comment, the commit is blocked. Nothing
is printed except the file it came from. Bypass (don't): git commit --no-verify.
"""
import json
import os
import re
import subprocess
import sys
SECRETS_DIR = os.path.expanduser("~/.config/herdr/plugins/config")
# files whose every value is secret, and key names that mark a secret in other settings files
CREDENTIAL_FILES = re.compile(r"^(credentials[^/]*\.json|kasa\.json|ring\.json|site\.json|token(\.json)?|[^/]*\.secret)$", re.I)
SECRET_KEYS = re.compile(r"pass|secret|token|api.?key|client.?id|refresh|user(name)?$|email|cookie|session", re.I)
BLOCKED_NAMES = re.compile(r"(^|/)(credentials[^/]*\.json|kasa\.json|ring\.json|site\.json|token(\.json)?|[^/]*\.secret|\.env)$", re.I)
def secret_values():
found = {}
for root, _, files in os.walk(SECRETS_DIR):
for name in files:
path = os.path.join(root, name)
try:
text = open(path, errors="ignore").read()
except OSError:
continue
values = []
whole_file = bool(CREDENTIAL_FILES.search(name))
try:
data = json.loads(re.sub(r'([{,]\s*)([A-Za-z_]\w*)(\s*:)', r'\1"\2"\3', text))
stack = [("", data)]
while stack:
key, v = stack.pop()
if isinstance(v, dict):
stack.extend(v.items())
elif isinstance(v, list):
stack.extend((key, x) for x in v)
elif isinstance(v, str) and (whole_file or SECRET_KEYS.search(key)):
values.append(v) # every value of a credential file; secret-named keys elsewhere
except ValueError:
values = [text.strip()] # a bare token file
for v in values:
if len(v) >= 6 and not re.fullmatch(r"[a-z]+|https?://[^\s]*|[\d.:]+", v):
found.setdefault(v, os.path.relpath(path, SECRETS_DIR))
return found
def main():
staged = subprocess.run(["git", "diff", "--cached", "--name-only", "--diff-filter=ACMR"],
capture_output=True, text=True).stdout.split()
bad = [f for f in staged if BLOCKED_NAMES.search(f)]
diff = subprocess.run(["git", "diff", "--cached", "-U0", "--no-color"], capture_output=True,
text=True, errors="ignore").stdout
added = "\n".join(l[1:] for l in diff.splitlines() if l.startswith("+") and not l.startswith("+++"))
leaks = sorted({src for value, src in secret_values().items() if value in added})
if bad or leaks:
print("pre-commit: refusing to commit secrets", file=sys.stderr)
for f in bad:
print(f" credential-like file staged: {f}", file=sys.stderr)
for src in leaks:
print(f" staged changes contain a value from plugins/config/{src}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())