#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ scan_deepseek.py -- Responsible-disclosure scanner for leaked DeepSeek API keys in PUBLIC GitHub repositories. WHAT THIS TOOL IS FOR --------------------- Find API keys that developers committed by mistake, and produce a *disclosure report* you can send to (a) the repo owner, (b) GitHub Support, (c) DeepSeek. The goal is rotation and removal of the secret, not use of it. WHAT THIS TOOL DELIBERATELY DOES NOT DO --------------------------------------- * It never stores a full key on disk. Every key it finds is reduced to a fingerprint: sk-abcd...wxyz + sha256 prefix. The owner can locate their own key from the path + commit + fingerprint; nobody else can reuse it from your report. * It never calls the DeepSeek API. It does not authenticate with a third party's credential. Validating someone else's key against a live API is exactly the act that turns "reading a public repo" into "unauthorised access to a computer system" in most jurisdictions (CFAA 1030, UK CMA 1-3, EU Directive 2013/40, Iran's Computer Crimes Law art. 1 & 2). It also consumes the victim's quota. Proof of exposure = line + commit, and that is enough for any owner or platform to act on. USAGE ----- setx GITHUB_TOKEN "ghp_..." REM fine-grained, read-only, public repos python scan_deepseek.py --out out # cheap sanity check, no network: python scan_deepseek.py --selftest Requirements: Python 3.9+, no third-party packages. A GitHub token is mandatory -- GitHub's code search API refuses unauthenticated requests. Scopes needed on a fine-grained token: "Public repositories (read-only)". No write scope. Revoke it after you are done. """ from __future__ import annotations import argparse import csv import hashlib import json import math import os import re import sys import time import urllib.error import urllib.parse import urllib.request from collections import defaultdict from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path # -------------------------------------------------------------------------- # Config # -------------------------------------------------------------------------- API = "https://api.github.com" UA = "deepseek-leak-disclosure/1.0 (responsible disclosure; contact repo owner)" # DeepSeek's documented/public key shape: "sk-" + 32 alphanumerics. # The length is configurable because providers change formats. KEY_RE = re.compile(r"\bsk-[A-Za-z0-9_-]{16,80}\b") DEFAULT_KEY_LEN = 32 # Default GitHub code-search queries. Code search has no regex support, so we # cast a wide literal net and filter locally with KEY_RE. DEFAULT_QUERIES = [ '"api.deepseek.com" "sk-"', "DEEPSEEK_API_KEY", "deepseek sk- language:Python", "deepseek sk- language:JavaScript", "deepseek api key path:.env", '"DEEPSEEK_API_KEY" path:.env', '"deepseek" "sk-" path:config', 'deepseek_key', 'deepseek sk- extension:json', 'deepseek sk- extension:yaml', 'deepseek sk- extension:yml', 'deepseek sk- extension:ipynb', 'deepseek sk- in:file language:TypeScript', 'deepseek sk- language:PHP', 'deepseek sk- language:Go', 'deepseek sk- language:"Jupyter Notebook"', 'deepseek sk- language:Java', 'deepseek sk- language:C#', 'deepseek sk- language:Ruby', 'deepseek sk- language:Rust', 'deepseek sk- language:Shell', 'deepseek sk- language:Kotlin', 'deepseek sk- language:Swift', 'deepseek sk- language:Dart', '"deepseek" "api_key" path:.env', 'DEEPSEEK_KEY', 'deepseek_api_key', 'deepseek apikey extension:json', 'deepseek apikey extension:yaml', '"api.deepseek.com" extension:env', '"api.deepseek.com" path:docker', ] PLACEHOLDER_MARKERS = ( "xxx", "your_", "your-", "yourkey", "example", "placeholder", "changeme", "dummy", "redacted", "replace", "<", ">", "todo", "fake", "sample", "abcdef012345", "0000000000", "1234567890", "sk-test", "sk-demo", "insert_", "put_", "here", "notreal", "not_real", ) SENSITIVE_PATH_RE = re.compile( r"(^|/)(\.env[^/]*|\.envrc|secrets?\.(json|ya?ml|toml|ini)|" r"config\.(json|ya?ml|toml|ini|py|js|ts)|settings\.(py|json)|" r"credentials[^/]*|application\.(properties|ya?ml)|\.npmrc|docker-compose[^/]*)$", re.I, ) # -------------------------------------------------------------------------- # Data # -------------------------------------------------------------------------- @dataclass class Finding: repo: str path: str html_url: str fingerprint: str # sk-abcd...wxyz (never the real key) key_id: str # sha256 prefix, stable join key score: int reasons: list[str] = field(default_factory=list) snippet: str = "" # masked context line default_branch: str = "" private: bool = False contact: str = "" # resolved last-commit author, optional first_seen: str = "" # Activity signals come from PUBLIC repo metadata only. Nothing here is # derived from the key itself -- the scanner never authenticates with it. last_commit: str = "" # YYYY-MM-DD of the last commit touching the file repo_pushed: str = "" # YYYY-MM-DD of the last push to the repo stars: int = 0 archived: bool = False status: str = "NEW" # NEW | SEEN, relative to the state file @property def severity(self) -> str: if self.score >= 6: return "HIGH" if self.score >= 4: return "MEDIUM" return "LOW" @property def age_days(self) -> int | None: """Days since the file was last touched (falls back to repo push).""" return days_ago(self.last_commit) or days_ago(self.repo_pushed) @property def priority_rank(self) -> int: """0 = contact now, 1 = contact, 2 = low, 3 = skip.""" age = self.age_days if self.archived or (age is not None and age > 730): return 3 if age is not None and age > 365: return 2 if self.score >= 6: return 0 return 1 @property def recommended(self) -> str: return { 0: "contact now", 1: "contact", 2: "low priority - no activity in over a year", 3: "skip - archived or dormant repo", }[self.priority_rank] # -------------------------------------------------------------------------- # Helpers # -------------------------------------------------------------------------- def mask_key(key: str) -> str: """sk-abcdefgh... -> sk-abcd...wxyz. Never returns a usable secret.""" body = key[3:] if key.startswith("sk-") else key if len(body) <= 8: return "sk-" + "*" * len(body) return f"sk-{body[:4]}...{body[-4:]}" def key_id(key: str) -> str: return hashlib.sha256(key.encode()).hexdigest()[:16] def shannon(s: str) -> float: if not s: return 0.0 counts = defaultdict(int) for ch in s: counts[ch] += 1 n = len(s) return -sum((c / n) * math.log2(c / n) for c in counts.values()) def days_ago(iso_date: str) -> int | None: """'2026-03-01' -> number of days since. None if unparseable/empty.""" if not iso_date: return None try: d = datetime.strptime(iso_date[:10], "%Y-%m-%d").replace(tzinfo=timezone.utc) except ValueError: return None return max(0, (datetime.now(timezone.utc) - d).days) def _looks_placeholder(candidate: str, context: str) -> bool: low = candidate.lower() ctx = context.lower() body = low[3:] if low.startswith("sk-") else low if len(set(body)) <= 4: # sk-aaaaaaaa... / sk-12341234... return True for marker in PLACEHOLDER_MARKERS: if marker in low or marker in ctx: return True return False def score_candidate(candidate: str, path: str, snippet: str) -> tuple[int, list[str]]: """Heuristic confidence score. Cheap triage, no network calls.""" score = 0 reasons: list[str] = [] body = candidate[3:] if candidate.startswith("sk-") else candidate if SENSITIVE_PATH_RE.search(path): score += 3 reasons.append("secret-bearing filename") if re.search(r"(DEEPSEEK|DS)[A-Z_]*KEY", snippet, re.I): score += 2 reasons.append("assigned to a DEEPSEEK*_KEY variable") if "api.deepseek.com" in snippet.lower(): score += 1 reasons.append("next to the DeepSeek base URL") if re.search(r"(base_?url|endpoint|api_?key|token|secret)\s*[:=]\s*[\"']?sk-", snippet, re.I): score += 1 reasons.append("looks like an assignment, not prose") if candidate.startswith("sk-") and len(body) == DEFAULT_KEY_LEN: score += 1 reasons.append("exact sk-+32 shape") ent = shannon(body) if ent >= 3.5: score += 1 reasons.append(f"high entropy ({ent:.2f} bits/char)") elif ent < 2.8: score -= 2 reasons.append(f"low entropy ({ent:.2f}) - likely fake") # Strong signals that this is documentation, not a live secret. if re.search(r"(os\.environ|getenv|process\.env|ENV\[|env\(|secrets\.|vault)", snippet): score -= 1 reasons.append("read from env/secret store, value is a fallback") if re.search(r"(readme|\.md$|\.rst$|\.txt$|docs?/)", path, re.I): score -= 2 reasons.append("documentation file") if "example" in snippet.lower() or "your_" in snippet.lower(): score -= 2 reasons.append("example text") return score, reasons def mask_snippet(snippet: str) -> str: """Mask every key-like token inside a code fragment before storing it.""" def repl(m: re.Match) -> str: return mask_key(m.group(0)) out = KEY_RE.sub(repl, snippet or "") out = re.sub(r"[ \t]+", " ", out) return out.strip()[:300] # -------------------------------------------------------------------------- # HTTP # -------------------------------------------------------------------------- class GitHub: def __init__(self, token: str, verbose: bool = False): self.token = token self.verbose = verbose self.calls = 0 def get(self, url: str, params: dict | None = None, text_match: bool = False, retries: int = 4) -> dict: if params: url = f"{url}?{urllib.parse.urlencode(params)}" headers = { "Authorization": f"Bearer {self.token}", "Accept": ("application/vnd.github.text-match+json" if text_match else "application/vnd.github+json"), "X-GitHub-Api-Version": "2022-11-28", "User-Agent": UA, } for attempt in range(retries): req = urllib.request.Request(url, headers=headers) try: self.calls += 1 with urllib.request.urlopen(req, timeout=45) as resp: remaining = resp.headers.get("X-RateLimit-Remaining") if self.verbose: print(f" [http] {resp.status} remaining={remaining} {url[:90]}") return json.loads(resp.read().decode("utf-8", "replace")) except urllib.error.HTTPError as e: body = e.read().decode("utf-8", "replace")[:300] if e.code in (403, 429): reset = e.headers.get("X-RateLimit-Reset") retry_after = e.headers.get("Retry-After") wait = 60 if retry_after: wait = int(retry_after) + 1 elif reset: wait = max(5, min(120, int(reset) - int(time.time()) + 1)) if self.verbose: print(f" [http] {e.code} rate limited, sleeping {wait}s") if attempt == retries - 1: print(f" [warn] giving up on {url[:80]}: {e.code} {body}") return {} time.sleep(wait) continue if e.code == 422: # search query rejected print(f" [warn] query rejected (422): {body[:160]}") return {} if e.code == 401: raise SystemExit("401 from GitHub: GITHUB_TOKEN is invalid or expired.") print(f" [warn] HTTP {e.code}: {body[:160]}") if attempt == retries - 1: return {} time.sleep(2 ** attempt) except (urllib.error.URLError, TimeoutError) as e: print(f" [warn] network error: {e}") if attempt == retries - 1: return {} time.sleep(2 ** attempt) return {} # -------------------------------------------------------------------------- # Scanning # -------------------------------------------------------------------------- def search(g: GitHub, query: str, max_pages: int, public_only: bool, verbose: bool) -> list[dict]: items: list[dict] = [] for page in range(1, max_pages + 1): data = g.get(f"{API}/search/code", {"q": query, "per_page": 100, "page": page}, text_match=True) batch = data.get("items") or [] if not batch: break for it in batch: repo = it.get("repository") or {} if public_only and repo.get("private"): continue items.append(it) if verbose: print(f" [page {page}] {len(batch)} items " f"(total_count={data.get('total_count')})") if len(batch) < 100: break time.sleep(6.5) # code search: 10 requests/minute authenticated return items def extract(findings: dict, it: dict, key_len: int, min_score: int) -> None: repo_obj = it.get("repository") or {} repo = repo_obj.get("full_name") or "?" path = it.get("path") or "?" url = it.get("html_url") or "" frags = [m.get("fragment", "") for m in (it.get("text_matches") or [])] if not frags: return for frag in frags: snippet = mask_snippet(frag) for m in KEY_RE.finditer(frag): cand = m.group(0).rstrip(".,;:)]}'\"`") body = cand[3:] if cand.startswith("sk-") else cand if len(body) != key_len: continue if _looks_placeholder(cand, frag): continue score, reasons = score_candidate(cand, path, frag) if score < min_score: continue kid = key_id(cand) dedup = (repo, path, kid) if dedup in findings: continue findings[dedup] = Finding( repo=repo, path=path, html_url=url, fingerprint=mask_key(cand), key_id=kid, score=score, reasons=reasons, snippet=snippet, default_branch=repo_obj.get("default_branch") or "", private=bool(repo_obj.get("private")), first_seen=datetime.now(timezone.utc).strftime("%Y-%m-%d"), ) def resolve_contact(g: GitHub, repo: str, path: str, verbose: bool) -> tuple[str, str]: """Last commit touching the file -> (author contact, commit date). This is metadata on a public commit, not a request to anybody's account. """ data = g.get(f"{API}/repos/{repo}/commits", {"path": path, "per_page": 1}) if isinstance(data, list) and data: c = data[0] commit = c.get("commit") or {} author = commit.get("author") or {} gh_user = (c.get("author") or {}).get("login") or "" name = author.get("name") or "" email = author.get("email") or "" date = (author.get("date") or commit.get("committer", {}).get("date") or "")[:10] parts = [p for p in (gh_user and f"@{gh_user}", name, email) if p] return " | ".join(parts), date return "", "" def enrich(g: GitHub, findings: list[Finding], verbose: bool, skip_archived: bool = False) -> None: """Attach public repo-activity signals (push date, stars, archived flag). Why this and not a balance check: whether a person still has credit is private account data. Whether their repo is still maintained is public metadata, and it answers the same practical question -- is it worth writing to them. """ cache: dict[str, dict] = {} for f in findings: if f.repo not in cache: meta = g.get(f"{API}/repos/{f.repo}") cache[f.repo] = meta if isinstance(meta, dict) else {} time.sleep(0.2) meta = cache[f.repo] f.repo_pushed = (meta.get("pushed_at") or "")[:10] f.stars = int(meta.get("stargazers_count") or 0) f.archived = bool(meta.get("archived")) if verbose: print(f" [enrich] {len(cache)} repo(s) inspected") # -------------------------------------------------------------------------- # State -- so repeat runs only surface what is new # -------------------------------------------------------------------------- def load_state(path: Path) -> dict: if not path or not path.exists(): return {} try: return json.loads(path.read_text(encoding="utf-8")) except (json.JSONDecodeError, OSError): print(f" [warn] state file {path} unreadable, starting fresh") return {} def apply_state(findings: list[Finding], state: dict) -> list[Finding]: """Mark each finding NEW / SEEN / DUP against previous runs. Returns new ones. DUP means the same key id turned up again inside this same run (the same key committed to several repos). It is not new, and it is not a second incident -- it is one rotation task. """ today = datetime.now(timezone.utc).strftime("%Y-%m-%d") new: list[Finding] = [] seen_now: set[str] = set() for f in findings: prev = state.get(f.key_id) if f.key_id in seen_now: f.status = "DUP" elif prev: f.status = "SEEN" f.first_seen = prev.get("first_seen", f.first_seen) else: f.status = "NEW" new.append(f) seen_now.add(f.key_id) state[f.key_id] = { "first_seen": prev.get("first_seen", f.first_seen) if prev else (f.first_seen or today), "last_seen": today, "repo": f.repo, "path": f.path, "fingerprint": f.fingerprint, } return new def save_state(path: Path, state: dict) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(state, indent=2, ensure_ascii=False), encoding="utf-8") # -------------------------------------------------------------------------- # Reporting # -------------------------------------------------------------------------- def write_report(outdir: Path, findings: list[Finding], queries: list[str]) -> Path: outdir.mkdir(parents=True, exist_ok=True) findings = sorted(findings, key=lambda f: (f.priority_rank, -f.score, f.repo, f.path)) by_repo: dict[str, list[Finding]] = defaultdict(list) for f in findings: by_repo[f.repo].append(f) # Stable re-use: one real key committed to many repos is one incident. by_key: dict[str, list[Finding]] = defaultdict(list) for f in findings: by_key[f.key_id].append(f) active = [f for f in findings if f.priority_rank < 3] dormant = [f for f in findings if f.priority_rank >= 3] new = [f for f in findings if f.status == "NEW"] lines: list[str] = [] lines.append("# DeepSeek leaked-key disclosure report\n") lines.append(f"Generated: {datetime.now(timezone.utc):%Y-%m-%d %H:%M} UTC \n") lines.append(f"Candidates: **{len(findings)}** in **{len(by_repo)}** repositories \n") lines.append(f"Worth contacting: **{len(active)}** · dormant/archived: **{len(dormant)}** \n") lines.append(f"Distinct key fingerprints: **{len(by_key)}** · new since last run: **{len(new)}** \n\n") lines.append("> Keys are shown as `sk-abcd...wxyz` fingerprints only. " "This file is safe to attach to a report and safe to lose; " "it contains no usable credential.\n\n") lines.append("## Priority queue\n\n") lines.append("| # | Repository | Key | Confidence | Last activity | Status | Contact |\n") lines.append("|---|---|---|---|---|---|---|\n") queue = [f for f in findings if f.priority_rank < 3] for i, f in enumerate(queue, 1): age = f.age_days when = f"{age} d ago" if age is not None else "-" contact = (f.contact or "-").replace("|", "\\|") lines.append( f"| {i} | [{f.repo}](https://github.com/{f.repo}) | `{f.fingerprint}` | " f"{f.severity} ({f.score}) | {when} | {f.status} | {contact} |\n") if new and any(f.status == "SEEN" for f in findings): lines.append("\n## New since last run\n\n") for f in new: lines.append(f"- `{f.fingerprint}` in {f.repo} (`{f.path}`)\n") lines.append("\n## Findings\n") for repo, fs in sorted(by_repo.items(), key=lambda kv: (min(f.priority_rank for f in kv[1]), -max(f.score for f in kv[1]))): lines.append(f"\n### {repo}\n\n") for f in sorted(fs, key=lambda x: (x.priority_rank, -x.score)): lines.append(f"- **{f.severity}** (`{f.score}`, {f.status}) `{f.fingerprint}` " f"in [`{f.path}`]({f.html_url})\n") lines.append(f" - action: {f.recommended}\n") lines.append(f" - reasons: {', '.join(f.reasons)}\n") if f.snippet: lines.append(f" - context: `{f.snippet}`\n") if f.contact: lines.append(f" - last commit by: {f.contact}\n") if f.repo_pushed: lines.append(f" - repo last pushed: {f.repo_pushed}" + (f", {f.stars} stars" if f.stars else "") + (" · **archived**" if f.archived else "") + "\n") if dormant: lines.append("\n## Skip these\n\n") lines.append("Archived repos, or no commit in over two years. The key is " "most likely already revoked with the account; a message here " "mostly adds noise. Batch them to GitHub Support instead.\n\n") for f in dormant: lines.append(f"- `{f.fingerprint}` in [{f.repo}](https://github.com/{f.repo}) " f"`{f.path}` ({f.recommended})\n") dupes = {k: v for k, v in by_key.items() if len({f.repo for f in v}) > 1} if dupes: lines.append("\n## Same key leaked into several repositories\n\n") for kid, fs in dupes.items(): repos = sorted({f.repo for f in fs}) lines.append(f"- `{fs[0].fingerprint}` -> {len(repos)} repos: " + ", ".join(repos) + "\n") lines.append("\nThis is one rotation task, not N. Notify the owner once " "and mention every location.\n") lines.append("\n## Queries used\n\n") for q in queries: lines.append(f"- `{q}`\n") lines.append("\n## Next step\n\n") lines.append("Work through `DISCLOSURE-PLAYBOOK.md`. Per-repository outreach " "drafts are in `disclosures/`.\n") lines.append("\n## Caveats\n\n") lines.append("* Results are `incomplete_results` whenever GitHub caps the " "search window; this is a sample, not a census.\n") lines.append("* Confidence is a heuristic on the code around the string, not " "proof the key is live. Nothing here contacted the DeepSeek API.\n") lines.append("* \"Last activity\" is the last commit touching the file, from " "public repo metadata. It is a proxy for \"is this still in use\", " "not a statement about anyone's account balance.\n") report = outdir / "report.md" report.write_text("".join(lines), encoding="utf-8") with (outdir / "findings.csv").open("w", newline="", encoding="utf-8") as fh: w = csv.writer(fh) w.writerow(["repo", "path", "url", "fingerprint", "key_id", "score", "severity", "status", "recommended", "last_commit", "repo_pushed", "stars", "archived", "reasons", "contact"]) for f in findings: w.writerow([f.repo, f.path, f.html_url, f.fingerprint, f.key_id, f.score, f.severity, f.status, f.recommended, f.last_commit, f.repo_pushed, f.stars, f.archived, "; ".join(f.reasons), f.contact]) (outdir / "findings.json").write_text( json.dumps([{**f.__dict__, "severity": f.severity, "recommended": f.recommended, "status": f.status} for f in findings], indent=2, ensure_ascii=False), encoding="utf-8") write_drafts(outdir, by_repo) return report def write_drafts(outdir: Path, by_repo: dict[str, list[Finding]]) -> None: ddir = outdir / "disclosures" ddir.mkdir(exist_ok=True) for repo, fs in by_repo.items(): slug = repo.replace("/", "__") top = max(f.score for f in fs) contact = next((f.contact for f in fs if f.contact), "") body = [] body.append(f"Subject: Exposed DeepSeek API key committed to {repo}\n\n") body.append(f"To: {contact or 'repository owner (see commit author)'}\n\n") body.append("---\n\n") body.append("سلام / Hello,\n\n") body.append(f"I am doing secret-scanning research on publicly committed ") body.append(f"credentials. The repository {repo} contains what appears to be a ") body.append("DeepSeek API key committed in plain text:\n\n") for f in fs: body.append(f"* `{f.fingerprint}` -- `{f.path}` \n") body.append(f" {f.html_url} \n") if f.snippet: body.append(f" context: `{f.snippet}` \n") body.append("\n") body.append("I have not used the key and have not called the DeepSeek API with it. ") body.append("I am not including the full value; you can locate it at the path above.\n\n") body.append("Suggested actions:\n\n") body.append("1. Revoke the key in the DeepSeek console and issue a new one.\n") body.append("2. Remove it from the current tree and from git history " "(`git filter-repo` or BFG). Force-push and tell collaborators " "to re-clone; a normal commit leaves it readable in history.\n") body.append("3. Check usage/billing for calls you did not make.\n") body.append("4. Load the value from an environment variable or a secret " "manager, and add a pre-commit hook (gitleaks/trufflehog).\n\n") body.append(f"Happy to answer questions or re-scan after you rotate. ") body.append("If you would rather not be contacted again, say so and I will stop.\n\n") body.append("Regards,\n[your name] / [contact]\n") (ddir / f"{slug}.md").write_text("".join(body), encoding="utf-8") # -------------------------------------------------------------------------- # Selftest # -------------------------------------------------------------------------- def selftest() -> int: good = "sk-" + "a1b2c3d4e5f60718293a4b5c6d7e8f90" fake = "sk-" + "x" * 32 low = "sk-" + "1234123412341234123412341234123" cases = [ (good, ".env", 'DEEPSEEK_API_KEY="%s"' % good, True), (fake, "config.py", 'KEY = "%s"' % fake, False), (low, ".env", 'DEEPSEEK_API_KEY="%s"' % low, False), ] ok = True for cand, path, snippet, expect in cases: keep = (len(cand) - 3 == DEFAULT_KEY_LEN and not _looks_placeholder(cand, snippet) and score_candidate(cand, path, snippet)[0] >= 4) mark = "PASS" if keep == expect else "FAIL" ok = ok and keep == expect print(f"[{mark}] keep={keep} expected={expect} {mask_key(cand)} {path}") m = mask_key(good) print("mask:", m, "| leaks body:", "a1b2c3d4e5f60718293a4b5c6d7e8f90" in m) print("fingerprint stable:", key_id(good) == key_id(good)) print("snippet:", mask_snippet(f'x = "{good}" # deepseek')) return 0 if ok and not ("a1b2c3d4e5f60718293a4b5c6d7e8f90" in m) else 1 # -------------------------------------------------------------------------- # Main # -------------------------------------------------------------------------- def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser( description="Find leaked DeepSeek keys in public repos and build a " "masked disclosure report (no API calls against the keys).") p.add_argument("--out", type=Path, default=Path("out"), help="output directory") p.add_argument("--token-env", default="GITHUB_TOKEN", help="env var holding the GitHub token") p.add_argument("--token-file", type=Path, default=None, help="read the token from a file instead of the environment " "(for scheduled runs; keep it outside any repo)") p.add_argument("--query", action="append", default=None, help="override queries (repeatable)") p.add_argument("--queries-file", type=Path, default=None, help="file with one query per line") p.add_argument("--max-pages", type=int, default=3, help="pages per query (100 results each)") p.add_argument("--key-len", type=int, default=DEFAULT_KEY_LEN, help="characters after sk-") p.add_argument("--min-score", type=int, default=3, help="triage threshold (default 3)") p.add_argument("--include-private", action="store_true", help="also scan private repos the token can read (off by default)") p.add_argument("--resolve-contacts", action="store_true", help="one extra API call per finding to fetch the last commit author") p.add_argument("--no-enrich", action="store_true", help="skip repo activity metadata (push date, stars, archived)") p.add_argument("--skip-stale", action="store_true", help="drop archived repos and files untouched for 2+ years") p.add_argument("--state", type=Path, default=None, help="state file for delta runs (default: /state.json)") p.add_argument("--no-state", action="store_true", help="do not read or write state") p.add_argument("--new-only", action="store_true", help="report only findings not present in the state file") p.add_argument("--verbose", action="store_true") p.add_argument("--selftest", action="store_true", help="run offline checks and exit") args = p.parse_args(argv) if args.selftest: return selftest() queries = args.query or DEFAULT_QUERIES if args.queries_file: queries = [l.strip() for l in args.queries_file.read_text(encoding="utf-8").splitlines() if l.strip() and not l.startswith("#")] token = os.environ.get(args.token_env) or os.environ.get("GH_TOKEN") if not token and args.token_file: try: token = args.token_file.read_text(encoding="utf-8").strip() except OSError as e: print(f"error: cannot read --token-file: {e}", file=sys.stderr) return 2 if not token: print(f"error: set {args.token_env} to a read-only GitHub token.\n" " GitHub's code search endpoint rejects unauthenticated calls.\n" " Create a fine-grained token, Public repositories (read-only),\n" " no other scopes, and revoke it when finished.", file=sys.stderr) return 2 g = GitHub(token, verbose=args.verbose) findings: dict[tuple, Finding] = {} for i, q in enumerate(queries, 1): print(f"[{i}/{len(queries)}] {q}") items = search(g, q, args.max_pages, not args.include_private, args.verbose) print(f" {len(items)} results") for it in items: extract(findings, it, args.key_len, args.min_score) if args.resolve_contacts or not args.no_enrich: print(f"[enrich] {len(findings)} finding(s)") if args.resolve_contacts: cache: dict[tuple, tuple[str, str]] = {} for f in findings.values(): k = (f.repo, f.path) if k not in cache: cache[k] = resolve_contact(g, f.repo, f.path, args.verbose) time.sleep(0.4) f.contact, f.last_commit = cache[k] if not args.no_enrich: enrich(g, list(findings.values()), args.verbose) if args.skip_stale: before = len(findings) findings = {k: f for k, f in findings.items() if f.priority_rank < 3} if before != len(findings): print(f"[skip-stale] dropped {before - len(findings)} dormant finding(s)") state_path = None if args.no_state else (args.state or args.out / "state.json") state = load_state(state_path) if state_path else {} all_findings = list(findings.values()) new = apply_state(all_findings, state) if state_path else all_findings if state_path: save_state(state_path, state) print(f"[state] {len(new)} new / {len(all_findings)} total " f"({state_path})") report_findings = new if (args.new_only and state_path) else all_findings if not report_findings: print("\nNothing to report. Either no new candidates above threshold, or " "the queries need widening (see --query).") return 0 report = write_report(args.out, report_findings, queries) repos = {f.repo for f in report_findings} active = sum(1 for f in report_findings if f.priority_rank < 3) print(f"\n{len(report_findings)} candidate(s) in {len(repos)} repo(s) " f"({active} worth contacting)") print(f"report: {report}") print(f"drafts: {args.out / 'disclosures'}") print(f"API calls used: {g.calls}") print("\nRemember: do not test these keys against the API. Report and let the " "owner rotate.") return 0 if __name__ == "__main__": raise SystemExit(main())