diff --git a/infra/github-backup/README.md b/infra/github-backup/README.md new file mode 100644 index 0000000000..0bfc24be2f --- /dev/null +++ b/infra/github-backup/README.md @@ -0,0 +1,67 @@ +# github-backup + +Mirrors of Drew's GitHub estate, kept on the laptop, updatable forever, +with a dedicated GitHub App for rate limits and webhook freshness. + +**This directory is the canonical home of the whole system** — scripts, +systemd units, the webhook Worker source, the config schema, and the +docs. Nothing load-bearing lives only on a machine: a fresh laptop plus +this repo plus Bitwarden rebuilds everything (see `docs/RUNBOOK.md`). + +## Layout of the backup tree (`~/backups/github` on the laptop) + +``` +/.git bare mirrors (git clone --mirror: all branches+tags) +plan.json generated by reconcile.py from config.json + GitHub +MANIFEST.json generated: what exists, sizes, HEADs, last fetch +FAMILIES.md generated: fork-family anchors (alternates pool) +state.json generated: fetch/drain bookkeeping +clone-status.jsonl clone pass log (append-only) +fetch.log fetch failures (append-only) +reconcile-YYYY-MM-DD.md weekly sweep reports +``` + +## Design + +- **Scope (config.json):** all non-fork repos + forks under 500 MB across + 17 owners, plus force-includes; 7 passive giants are excluded by Drew's + ruling 2026-10-31 (upstream is their backup). Edsebooks (HTTP 451) and + vertexinc (SAML) are recorded gaps, not silent misses. +- **Pool/dedupe:** forks sharing an upstream are cloned with git + alternates against a family anchor, so e.g. the three nixpkgs copies + store one shared history plus deltas. Members are NOT self-contained — + the tree is the unit. Cold copies use `git bundle` (materializes + objects), never a bare tar of a member `.git`. +- **Freshness:** a dedicated GitHub App (`hatch-repo-backup`, + metadata:read + contents:read, push+repository events) sends webhooks + to the Cloudflare Worker in `worker/`; the Worker verifies the HMAC + and queues events in KV; the laptop drains the queue every 5 min + (per-repo coalescing 15 min) and fetches just those mirrors. +- **Correctness floor:** a weekly reconciliation sweep re-inventories + GitHub, diffs against the tree, clones new repos matching the tier + rules, and flags new giant forks as `pending-drew-review` instead of + cloning them. Webhooks may be missed; the sweep may not. +- **Daily fetch:** every mirror is fetched daily regardless (12 h + coalescing), so even total webhook loss degrades to daily freshness. +- **Rate limits:** the App's installation tokens have their own pool + (5,000/hr base, scaling with installed repos toward 12,500/hr), + separate from Drew's personal token that the fleet uses. +- **Secrets:** by name only, in Bitwarden Secrets Manager — see + `config.json` → `app.bitwarden_secret_names`. Values never enter this + repo, the backup tree, or chat. + +## Components + +| Path | What | +|---|---| +| `config.json` | owners, tier rules, exclusions, gaps, App/Worker names | +| `bin/ghb_common.py` | shared inventory + plan builder | +| `bin/clone_all.py` | resumable parallel initial clone (from plan.json) | +| `bin/fetch_mirrors.py` | daily fetch / targeted fetch of named repos | +| `bin/reconcile.py` | weekly sweep: inventory → plan → clone new → report | +| `bin/manifest.py` | regenerate MANIFEST.json + FAMILIES.md | +| `bin/drain_queue.py` | drain Worker queue, fetch pushed repos | +| `bin/app_setup.py` | App manifest flow, credential storage, install report | +| `worker/` | Cloudflare Worker webhook receiver (wrangler) | +| `systemd/` | laptop user units + timers + installer | +| `docs/RUNBOOK.md` | copy-paste operations: install, add org, upgrade, DR | diff --git a/infra/github-backup/bin/app_setup.py b/infra/github-backup/bin/app_setup.py new file mode 100644 index 0000000000..2645d335ab --- /dev/null +++ b/infra/github-backup/bin/app_setup.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""app_setup.py — GitHub App (hatch-repo-backup) lifecycle helper. + +Subcommands: + manifest Print the App Manifest JSON + the exact click-path to create + the App (GitHub requires a human to submit the manifest form; + everything after the redirect is automated here). + convert CODE + Exchange the manifest-flow temporary code for the App's + credentials (POST /app-manifests//conversions) and store + them in Bitwarden Secrets Manager BY NAME (see config.json + app.bitwarden_secret_names). Values are never printed or + written to disk. + install-report + Using the App private key from Bitwarden (via bws env), mint a + JWT and list installations (GET /app/installations) so the + runbook's install checklist can be verified. + webhook-secret + Generate a webhook secret and store it in Bitwarden by name; + the same value must then be set on the App (GitHub UI) and on + the Worker (`wrangler secret put GITHUB_WEBHOOK_SECRET`). + Prints only the Bitwarden secret name, never the value. + +Bitwarden access goes through `bws` with BWS_ACCESS_TOKEN from the +environment (source ~/tools/bws-env.sh first). bws project: the one +~/tools/bws-env.sh defaults to. +""" +import json, os, secrets as secrets_mod, subprocess, sys, time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from ghb_common import load_config + +CFG = load_config() +NAMES = CFG["app"]["bitwarden_secret_names"] + + +def app_manifest(worker_url): + return { + "name": CFG["app"]["name"], + "url": "https://github.com/developing-today/code/tree/main/infra/github-backup", + "hook_attributes": {"url": worker_url.rstrip("/") + CFG["worker"]["webhook_path"]}, + "redirect_url": "http://localhost:8765/callback", + "public": False, + "default_permissions": {"metadata": "read", "contents": "read"}, + "default_events": CFG["app"]["events"], + } + + +def _bws_list(): + r = subprocess.run(["bws", "secret", "list"], capture_output=True, text=True, + env=dict(os.environ)) + if r.returncode != 0: + raise RuntimeError(f"bws secret list failed: {r.stderr[:200]}") + return json.loads(r.stdout or "[]") + + +def _project_id(): + if os.environ.get("GHB_BWS_PROJECT_ID"): + return os.environ["GHB_BWS_PROJECT_ID"] + r = subprocess.run(["bws", "project", "list"], capture_output=True, text=True, + env=dict(os.environ)) + projects = json.loads(r.stdout or "[]") + if not projects: + raise RuntimeError("no Bitwarden projects visible to this token") + return projects[0]["id"] + + +def bws_set(name, value): + """Create-or-update a Bitwarden secret by name.""" + sid = next((s["id"] for s in _bws_list() if s.get("key") == name), None) + if sid: + r = subprocess.run(["bws", "secret", "edit", sid, "--value", value], + capture_output=True, text=True, env=dict(os.environ)) + else: + r = subprocess.run(["bws", "secret", "create", name, value, _project_id()], + capture_output=True, text=True, env=dict(os.environ)) + if r.returncode != 0: + raise RuntimeError(f"bws store failed for {name}: {r.stderr[:200]}") + + +def bws_get(name): + sid = next((s["id"] for s in _bws_list() if s.get("key") == name), None) + if not sid: + raise KeyError(name) + r = subprocess.run(["bws", "secret", "get", sid], + capture_output=True, text=True, env=dict(os.environ)) + return json.loads(r.stdout)["value"] + + +def cmd_manifest(): + worker_url = os.environ.get("GHB_WORKER_URL", "https://") + m = app_manifest(worker_url) + print(json.dumps(m, indent=2)) + print(""" +CLICK PATH (one human step — GitHub requires it): + 1. Set GHB_WORKER_URL to the deployed Worker URL and re-run to bake it in. + 2. Open https://github.com/settings/apps/new as dezren39 and submit this + manifest via the manifest-flow form (the RUNBOOK §App has the exact + HTML snippet), OR paste it using GitHub's manifest flow page. + 3. GitHub redirects to the redirect_url with ?code=XXXX. + 4. Run: python3 app_setup.py convert XXXX + -> stores app id / client id / client secret / private key in + Bitwarden under the names in config.json. Nothing is printed. +""", file=sys.stderr) + + +def cmd_convert(code): + import urllib.request + req = urllib.request.Request( + f"https://api.github.com/app-manifests/{code}/conversions", + data=b"", method="POST") + req.add_header("Accept", "application/vnd.github+json") + with urllib.request.urlopen(req, timeout=60) as r: + conv = json.loads(r.read()) + bws_set(NAMES["app_id"], str(conv["id"])) + bws_set(NAMES["client_id"], conv["client_id"]) + bws_set(NAMES["client_secret"], conv["client_secret"]) + bws_set(NAMES["private_key"], conv["pem"]) + print(f"App created: id={conv['id']} slug={conv['slug']} — credentials stored " + f"in Bitwarden by name ({', '.join(NAMES.values())}).") + print("Next: app_setup.py webhook-secret, then install the App per RUNBOOK §App.") + + +def cmd_webhook_secret(): + value = secrets_mod.token_hex(32) + bws_set(NAMES["webhook_secret"], value) + print(f"Stored under Bitwarden name {NAMES['webhook_secret']}. " + "Set the same value on the App (GitHub UI > App settings > Webhook secret) " + "and on the Worker: wrangler secret put GITHUB_WEBHOOK_SECRET.") + + +def cmd_install_report(): + # JWT minting needs a JOSE lib; use PyJWT if present, else cryptography. + try: + import jwt as pyjwt + except ImportError: + print("PyJWT not installed (pip install pyjwt cryptography) — cannot mint App JWT here.") + return 1 + import urllib.request + app_id = bws_get(NAMES["app_id"]) + pem = bws_get(NAMES["private_key"]) + now = int(time.time()) + token = pyjwt.encode({"iat": now - 60, "exp": now + 540, "iss": app_id}, + pem, algorithm="RS256") + req = urllib.request.Request("https://api.github.com/app/installations") + req.add_header("Authorization", "Bearer " + token) + req.add_header("Accept", "application/vnd.github+json") + with urllib.request.urlopen(req, timeout=60) as r: + installs = json.loads(r.read()) + for i in installs: + acct = i["account"]["login"] + print(f"installed: {acct} (installation {i['id']}, repos: " + f"{i.get('repository_selection')})") + print(f"total installations: {len(installs)}") + return 0 + + +if __name__ == "__main__": + cmd = sys.argv[1] if len(sys.argv) > 1 else "" + if cmd == "manifest": + cmd_manifest() + elif cmd == "convert" and len(sys.argv) == 3: + cmd_convert(sys.argv[2]) + elif cmd == "webhook-secret": + cmd_webhook_secret() + elif cmd == "install-report": + sys.exit(cmd_install_report()) + else: + print(__doc__) + sys.exit(2) diff --git a/infra/github-backup/bin/clone_all.py b/infra/github-backup/bin/clone_all.py new file mode 100644 index 0000000000..db1668c00b --- /dev/null +++ b/infra/github-backup/bin/clone_all.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""clone_all.py — resumable parallel mirror-clone driver. + +Reads plan.json from the backup tree (build it with reconcile.py --plan-only +or copy from a previous run). Mirrors land at //.git. +Repos with a `reference` wait for their anchor; if the anchor failed they +fall back to a full clone. Status is appended to clone-status.jsonl; +re-running skips verified mirrors. +""" +import json, os, subprocess, sys, time +from concurrent.futures import ThreadPoolExecutor + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from ghb_common import load_config, backup_root, mirror_path, valid_mirror, disk_kb + +PAR = 4 +TIMEOUT = 5400 + + +def main(): + cfg = load_config() + root = backup_root(cfg) + plan = json.load(open(os.path.join(root, "plan.json"))) + status_path = os.path.join(root, "clone-status.jsonl") + + def log_status(rec): + rec["ts"] = time.strftime("%Y-%m-%dT%H:%M:%S%z") + with open(status_path, "a") as f: + f.write(json.dumps(rec) + "\n") + + ok_prev = set() + if os.path.exists(status_path): + for line in open(status_path): + try: + r = json.loads(line) + if r.get("status") == "ok": + ok_prev.add(r["repo"]) + except Exception: + pass + + def clone_one(item, ref_ok): + repo = item["repo"] + dest = mirror_path(root, repo) + if valid_mirror(dest): + return {"repo": repo, "status": "ok", "note": "already-present", + "disk_kb": disk_kb(dest)} + os.makedirs(os.path.dirname(dest), exist_ok=True) + cmd = ["git", "clone", "--mirror"] + ref = item.get("reference") + if ref and ref_ok and valid_mirror(mirror_path(root, ref)): + cmd += ["--reference", mirror_path(root, ref)] + cmd += [f"https://github.com/{repo}.git", dest] + t0 = time.time() + env = dict(os.environ, GIT_TERMINAL_PROMPT="0") + try: + r = subprocess.run(cmd, capture_output=True, text=True, + timeout=TIMEOUT, env=env) + except subprocess.TimeoutExpired: + return {"repo": repo, "status": "fail", "error": "timeout", + "seconds": round(time.time() - t0)} + dt = round(time.time() - t0) + if r.returncode == 0 and valid_mirror(dest): + return {"repo": repo, "status": "ok", "seconds": dt, + "disk_kb": disk_kb(dest), + "reference_used": ref if (ref and ref_ok) else None} + return {"repo": repo, "status": "fail", "seconds": dt, + "error": (r.stderr or r.stdout)[-400:]} + + state = {} + for p in plan: + if p["repo"] in ok_prev and valid_mirror(mirror_path(root, p["repo"])): + state[p["repo"]] = "ok" + pending = [p for p in plan if state.get(p["repo"]) != "ok"] + print(f"plan={len(plan)} already-ok={len(plan)-len(pending)} pending={len(pending)}", flush=True) + inflight = {} + with ThreadPoolExecutor(max_workers=PAR) as ex: + while pending or inflight: + for p in list(pending): + ref = p.get("reference") + if ref and state.get(ref) is None and any(q["repo"] == ref for q in pending): + continue + if len(inflight) >= PAR: + break + inflight[ex.submit(clone_one, p, state.get(ref) == "ok")] = p + pending.remove(p) + if not inflight: + if pending: + p = pending.pop(0) + inflight[ex.submit(clone_one, p, False)] = p + else: + break + done = [f for f in list(inflight) if f.done()] + if not done: + time.sleep(2) + continue + for f in done: + p = inflight.pop(f) + try: + rec = f.result() + except Exception as e: + rec = {"repo": p["repo"], "status": "fail", "error": str(e)[:300]} + state[p["repo"]] = "ok" if rec["status"] == "ok" else "fail" + log_status(rec) + print(rec["repo"], rec["status"], rec.get("seconds", ""), flush=True) + ok = sum(1 for s in state.values() if s == "ok") + print(f"DONE ok={ok} fail={len(state)-ok} of {len(plan)}", flush=True) + return 0 if ok == len(plan) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/infra/github-backup/bin/drain_queue.py b/infra/github-backup/bin/drain_queue.py new file mode 100644 index 0000000000..64e0bf889e --- /dev/null +++ b/infra/github-backup/bin/drain_queue.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""drain_queue.py — pull queued webhook events from the Worker and fetch. + +The Cloudflare Worker (../worker) receives GitHub App webhooks, validates +the HMAC, and stores events in KV. This drainer (timer: every 5 min): + GET /queue (Authorization: Bearer ) + -> {"events": [{"id", "repo", "event", "ts"}]} + POST /queue/ack {"ids": [...]} +Per-repo coalescing: a repo is fetched at most once per 15 min +(state.json key drain_last::) — hatch-personal pushes every ~2 min. +`repository` events with action=created are noted for the weekly sweep +(which owns mirror creation decisions) and also trigger an immediate +clone attempt through the normal plan if the repo is already planned. +Secrets come from the environment; the systemd unit sources them from +Bitwarden by name (see config.json app.bitwarden_secret_names). +""" +import json, os, sys, time, urllib.request + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from ghb_common import load_config, backup_root +import fetch_mirrors + +COALESCE_S = 15 * 60 + + +def worker_req(path, payload=None): + url = os.environ["GHB_WORKER_URL"].rstrip("/") + path + data = json.dumps(payload).encode() if payload is not None else None + req = urllib.request.Request(url, data=data, method="POST" if data else "GET") + req.add_header("Authorization", "Bearer " + os.environ["GHB_WORKER_BEARER"]) + if data: + req.add_header("Content-Type", "application/json") + with urllib.request.urlopen(req, timeout=60) as r: + return json.loads(r.read() or b"{}") + + +def main(): + cfg = load_config() + root = backup_root(cfg) + state_path = os.path.join(root, "state.json") + state = json.load(open(state_path)) if os.path.exists(state_path) else {} + q = worker_req(cfg["worker"]["queue_poll_path"]) + events = q.get("events", []) + if not events: + print("queue empty") + return 0 + now = time.time() + to_fetch, ack = [], [] + for ev in events: + repo = ev.get("repo") + ack.append(ev["id"]) + if not repo: + continue + key = f"drain_last::{repo}" + if now - state.get(key, 0) < COALESCE_S: + continue + state[key] = now + if repo not in to_fetch: + to_fetch.append(repo) + fetched = [] + for repo in to_fetch: + plan_path = os.path.join(root, "plan.json") + planned = {p["repo"] for p in json.load(open(plan_path))} if os.path.exists(plan_path) else set() + if repo in planned: + fetch_mirrors.fetch_repo(root, repo, state) + fetched.append(repo) + else: + with open(os.path.join(root, "fetch.log"), "a") as f: + f.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S%z')} {repo} " + f"webhook event for unplanned repo — left for weekly reconcile\n") + with open(state_path, "w") as f: + json.dump(state, f, indent=0) + worker_req(cfg["worker"]["queue_poll_path"] + "/ack", {"ids": ack}) + print(json.dumps({"events": len(events), "fetched": fetched})) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/infra/github-backup/bin/fetch_mirrors.py b/infra/github-backup/bin/fetch_mirrors.py new file mode 100644 index 0000000000..76efb9cf71 --- /dev/null +++ b/infra/github-backup/bin/fetch_mirrors.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""fetch_mirrors.py — daily fetch of every mirror in the tree. + +- `git fetch --all --prune` (+ tags are part of the mirror refspec) per repo. +- Coalescing: mirrors fetched <12h ago are skipped (state.json). +- Failures are appended to fetch.log. A repo failing on 3 distinct days in + a row makes the run exit non-zero (so systemd shows the failure). +- Repos named on the command line are fetched unconditionally (used by the + webhook drainer); no args = the daily full pass. +""" +import json, os, subprocess, sys, time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from ghb_common import load_config, backup_root, mirror_path, valid_mirror +import manifest as manifest_mod + +COALESCE_S = 12 * 3600 + + +def fetch_repo(root, repo, state): + path = mirror_path(root, repo) + if not valid_mirror(path): + return "missing" + env = dict(os.environ, GIT_TERMINAL_PROMPT="0") + r = subprocess.run(["git", "-C", path, "fetch", "--all", "--prune"], + capture_output=True, text=True, timeout=3600, env=env) + now = time.time() + st = state.setdefault(repo, {}) + if r.returncode == 0: + st["last_fetch"] = now + st["fail_days"] = [] + return "ok" + today = time.strftime("%Y-%m-%d") + days = st.setdefault("fail_days", []) + if today not in days: + days.append(today) + st["last_error"] = (r.stderr or r.stdout)[-300:] + return "fail" + + +def iter_plan_repos(root): + plan = json.load(open(os.path.join(root, "plan.json"))) + return [p["repo"] for p in plan] + + +def main(argv): + cfg = load_config() + root = backup_root(cfg) + state_path = os.path.join(root, "state.json") + state = json.load(open(state_path)) if os.path.exists(state_path) else {} + log_path = os.path.join(root, "fetch.log") + only = argv[1:] + repos = only if only else iter_plan_repos(root) + now = time.time() + results = {"ok": 0, "fail": 0, "skip": 0, "missing": 0} + failed = [] + for repo in repos: + st = state.get(repo) or {} + if not only and st.get("last_fetch") and now - st["last_fetch"] < COALESCE_S: + results["skip"] += 1 + continue + res = fetch_repo(root, repo, state) + results[res] += 1 + if res != "ok": + failed.append((repo, res)) + with open(log_path, "a") as f: + f.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S%z')} {repo} {res} " + f"{(state.get(repo) or {}).get('last_error', '')}\n") + with open(state_path, "w") as f: + json.dump(state, f, indent=0) + manifest_mod.build(root) + chronic = [r for r in repos + if len((state.get(r) or {}).get("fail_days", [])) >= 3] + print(json.dumps({"results": results, "chronic_failures": chronic})) + return 1 if chronic else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/infra/github-backup/bin/ghb_common.py b/infra/github-backup/bin/ghb_common.py new file mode 100644 index 0000000000..fd3bc190c7 --- /dev/null +++ b/infra/github-backup/bin/ghb_common.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""ghb_common.py — shared helpers for the github-backup system. + +Canonical home: developing-today/code, infra/github-backup/. +Config lives in ../config.json next to this file's parent directory. +The backup tree (default ~/backups/github) holds only data + generated +state (plan.json, MANIFEST.json, logs); all logic lives in the repo. +""" +import json, os, subprocess, sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +GB_DIR = os.path.dirname(HERE) +CONFIG_PATH = os.path.join(GB_DIR, "config.json") + + +def load_config(): + with open(CONFIG_PATH) as f: + return json.load(f) + + +def backup_root(cfg=None): + cfg = cfg or load_config() + return os.path.expanduser(cfg.get("backup_root", "~/backups/github")) + + +def mirror_path(root, repo): + return os.path.join(root, repo + ".git") + + +def run(cmd, **kw): + return subprocess.run(cmd, capture_output=True, text=True, **kw) + + +def valid_mirror(path): + if not os.path.isdir(path): + return False + r = run(["git", "-C", path, "rev-parse", "--is-bare-repository"]) + return r.returncode == 0 and r.stdout.strip() == "true" + + +def disk_kb(path): + r = run(["du", "-sk", path]) + try: + return int(r.stdout.split()[0]) + except Exception: + return -1 + + +# ---------------------------------------------------------------- inventory +_GQL = """ +query($login: String!, $after: String) { + repositoryOwner(login: $login) { + repositories(first: 100, after: $after) { + pageInfo { hasNextPage endCursor } + nodes { + nameWithOwner isFork isArchived diskUsage pushedAt + defaultBranchRef { name target { oid } } + parent { nameWithOwner } + } + } + } +} +""" + + +def inventory_owner(owner): + """All repos visible to the gh token under one owner, via GraphQL.""" + repos = [] + after = None + while True: + variables = {"login": owner} + if after: + variables["after"] = after + r = run(["gh", "api", "graphql", "-f", f"query={_GQL}", + "-f", f"login={owner}"] + + (["-f", f"after={after}"] if after else [])) + if r.returncode != 0: + raise RuntimeError(f"gh api graphql failed for {owner}: {r.stderr[:300]}") + data = json.loads(r.stdout) + conn = (data.get("data", {}).get("repositoryOwner") or {}).get("repositories") + if conn is None: + return repos + for n in conn["nodes"]: + repos.append({ + "repo": n["nameWithOwner"], + "fork": bool(n["isFork"]), + "archived": bool(n["isArchived"]), + "size_kb": n.get("diskUsage") or 0, + "parent": (n.get("parent") or {}).get("nameWithOwner"), + "branch": (n.get("defaultBranchRef") or {}).get("name"), + "head": ((n.get("defaultBranchRef") or {}).get("target") or {}).get("oid"), + "pushed_at": n.get("pushedAt"), + "empty": n.get("defaultBranchRef") is None, + }) + if conn["pageInfo"]["hasNextPage"]: + after = conn["pageInfo"]["endCursor"] + else: + return repos + + +def inventory(owners): + out = {} + errors = {} + for o in owners: + try: + for repo in inventory_owner(o): + out[repo["repo"]] = repo + except Exception as e: + errors[o] = str(e)[:300] + return out, errors + + +# ---------------------------------------------------------------- plan +def build_plan(repos, cfg): + """Apply config tier rules. Returns (plan, excluded, gaps, pending_review). + + plan: ordered list of {repo, reference|null, size_kb, fork, parent, + branch, head} — dependency order (anchors/parents before members). + """ + rules = cfg["tier_rules"] + cap_kb = int(rules.get("fork_max_size_mb", 500)) * 1024 + force = set(rules.get("force_include", [])) + excl = {e["repo"]: e["reason"] for e in cfg.get("exclusions", [])} + gaps = {g["repo"]: g["reason"] for g in cfg.get("gaps", [])} + included, excluded, gap, pending, skipped_empty = {}, [], [], [], [] + for name, v in sorted(repos.items()): + if name in gaps or (name.split("/")[0] + "/*") in gaps: + gap.append({"repo": name, "reason": gaps.get(name) or gaps.get(name.split("/")[0] + "/*")}) + continue + if name in excl: + excluded.append({"repo": name, "reason": excl[name]}) + continue + if rules.get("skip_zero_commit_repos") and v.get("empty"): + skipped_empty.append({"repo": name, "reason": "zero commits (empty repo)"}) + continue + if (not v["fork"] and rules.get("include_nonforks")) or name in force \ + or v["size_kb"] < cap_kb: + included[name] = v + else: + pending.append({"repo": name, + "reason": f"fork {v['size_kb']/1024:.0f} MB >= cap " + f"{rules.get('fork_max_size_mb')} MB — pending Drew review"}) + incset = set(included) + + def depth(k): + n, cur, guard = 0, k, set() + while True: + p = included.get(cur, {}).get("parent") + if p and p in incset and p not in guard: + guard.add(p); n += 1; cur = p + else: + return n + + plan, anchor_for = [], {} + for k in sorted(included, key=lambda k: (depth(k), k)): + v = included[k] + ref = None + if v["fork"] and v.get("parent"): + p = v["parent"] + if p in incset: + ref = p + elif p in anchor_for: + ref = anchor_for[p] + else: + anchor_for[p] = k + plan.append({"repo": k, "reference": ref, "size_kb": v["size_kb"], + "fork": v["fork"], "parent": v.get("parent"), + "branch": v.get("branch"), "head": v.get("head"), + "private": None}) + return plan, excluded, gap, pending, skipped_empty diff --git a/infra/github-backup/bin/manifest.py b/infra/github-backup/bin/manifest.py new file mode 100644 index 0000000000..eb53f96528 --- /dev/null +++ b/infra/github-backup/bin/manifest.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""manifest.py — regenerate MANIFEST.json + FAMILIES.md in the backup tree. + +MANIFEST.json is the disaster-recovery source: config.json (in the repo) +says WHAT should exist; MANIFEST.json records what DOES exist, where, and +its state. Together they rebuild the whole tree (see docs/RUNBOOK.md § DR). +""" +import json, os, subprocess, sys, time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from ghb_common import load_config, backup_root, mirror_path, valid_mirror, disk_kb + + +def head_sha(path, branch=None): + refs = ["refs/heads/" + branch] if branch else ["HEAD"] + for ref in refs: + r = subprocess.run(["git", "-C", path, "rev-parse", "--verify", "-q", ref], + capture_output=True, text=True) + if r.returncode == 0: + return r.stdout.strip() + return None + + +def last_fetch(path, state): + return state.get("last_fetch") + + +def build(root=None): + cfg = load_config() + root = root or backup_root(cfg) + plan_path = os.path.join(root, "plan.json") + plan = json.load(open(plan_path)) if os.path.exists(plan_path) else [] + state_path = os.path.join(root, "state.json") + state = json.load(open(state_path)) if os.path.exists(state_path) else {} + entries = {} + families = {} + for item in plan: + repo = item["repo"] + path = mirror_path(root, repo) + present = valid_mirror(path) + e = { + "status": "mirrored" if present else "missing", + "disk_kb": disk_kb(path) if present else 0, + "github_size_kb": item.get("size_kb"), + "last_fetch": (state.get(repo) or {}).get("last_fetch"), + "head": head_sha(path, item.get("branch")) if present else None, + "default_branch": item.get("branch"), + "reference": item.get("reference"), + "fork": item.get("fork"), + "parent": item.get("parent"), + } + entries[repo] = e + if item.get("reference"): + families.setdefault(item["reference"], []).append(repo) + manifest = { + "generated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"), + "config_version": cfg.get("version"), + "mirrors": entries, + "excluded": cfg.get("exclusions", []), + "gaps": cfg.get("gaps", []), + "totals": { + "mirrored": sum(1 for e in entries.values() if e["status"] == "mirrored"), + "missing": sum(1 for e in entries.values() if e["status"] != "mirrored"), + "disk_kb": sum(e["disk_kb"] for e in entries.values()), + }, + } + with open(os.path.join(root, "MANIFEST.json"), "w") as f: + json.dump(manifest, f, indent=1, sort_keys=True) + lines = ["# Fork families (git alternates pool)", "", + "Members below are NOT self-contained mirrors: their object stores", + "alternate into the anchor's objects. The backup TREE is the unit.", + "Cold exports must use `git bundle` (materializes all objects).", ""] + for anchor in sorted(families): + lines.append(f"## anchor: {anchor}") + for m in sorted(families[anchor]): + lines.append(f"- {m}") + lines.append("") + with open(os.path.join(root, "FAMILIES.md"), "w") as f: + f.write("\n".join(lines)) + return manifest + + +if __name__ == "__main__": + m = build() + print(json.dumps(m["totals"])) diff --git a/infra/github-backup/bin/reconcile.py b/infra/github-backup/bin/reconcile.py new file mode 100644 index 0000000000..3bddf6dca4 --- /dev/null +++ b/infra/github-backup/bin/reconcile.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""reconcile.py — weekly reconciliation sweep (the correctness floor). + +1. Fresh inventory of every owner in config.json via the GitHub GraphQL API. +2. Build the plan with the config tier rules; diff against the tree: + - new repos matching the rules -> cloned (clone_all logic via plan.json) + - new giant forks -> MANIFEST 'pending-drew-review', not cloned + - repos gone from GitHub -> reported, mirror kept + - inventory errors per owner -> reported (e.g. SAML-blocked orgs) +3. Write reconcile-YYYY-MM-DD.md into the backup tree and refresh + plan.json + MANIFEST.json. + +Webhooks (the App + Worker) are the freshness layer; this sweep is what +guarantees nothing is missed. Exit code is non-zero only on owner-level +inventory failure, so the timer unit surfaces it. +""" +import json, os, subprocess, sys, time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from ghb_common import load_config, backup_root, inventory, build_plan, valid_mirror, mirror_path +import manifest as manifest_mod + + +def main(): + cfg = load_config() + root = backup_root(cfg) + os.makedirs(root, exist_ok=True) + repos, errors = inventory(cfg["owners"]) + plan, excluded, gaps, pending, skipped_empty = build_plan(repos, cfg) + today = time.strftime("%Y-%m-%d") + old_plan_path = os.path.join(root, "plan.json") + old = [] + if os.path.exists(old_plan_path): + old = [p["repo"] for p in json.load(open(old_plan_path))] + new = [p["repo"] for p in plan] + added = sorted(set(new) - set(old)) + removed = sorted(set(old) - set(new)) + missing = [r for r in new if not valid_mirror(mirror_path(root, r))] + with open(old_plan_path, "w") as f: + json.dump(plan, f, indent=0) + lines = [f"# github-backup reconcile {today}", "", + f"- inventory: {len(repos)} repos across {len(cfg['owners'])} owners", + f"- plan: {len(plan)} mirrors ({len(added)} new, {len(removed)} no longer planned)", + f"- excluded by config: {len(excluded)}; gaps: {len(gaps)}; " + f"pending Drew review: {len(pending)}; zero-commit skipped: {len(skipped_empty)}", + f"- mirrors missing on disk before clone pass: {len(missing)}", ""] + if errors: + lines.append("## inventory errors") + for o, e in errors.items(): + lines.append(f"- {o}: {e}") + lines.append("") + if added: + lines.append("## newly planned") + lines += [f"- {r}" for r in added] + [""] + if removed: + lines.append("## no longer planned (mirrors kept on disk)") + lines += [f"- {r}" for r in removed] + [""] + if pending: + lines.append("## pending Drew review (giant forks, NOT cloned)") + lines += [f"- {p['repo']} — {p['reason']}" for p in pending] + [""] + report_path = os.path.join(root, f"reconcile-{today}.md") + with open(report_path, "w") as f: + f.write("\n".join(lines)) + print("\n".join(lines)) + if missing: + r = subprocess.run([sys.executable, + os.path.join(os.path.dirname(os.path.abspath(__file__)), + "clone_all.py")]) + if r.returncode != 0: + print("clone pass had failures; see clone-status.jsonl") + manifest_mod.build(root) + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/infra/github-backup/config.json b/infra/github-backup/config.json new file mode 100644 index 0000000000..6262c3b737 --- /dev/null +++ b/infra/github-backup/config.json @@ -0,0 +1,121 @@ +{ + "version": 1, + "description": "github-backup configuration: owners, tier rules, exclusions. Adding an owner/org is an edit to this file plus the commands in docs/RUNBOOK.md \u2014 never a code change.", + "backup_root": "~/backups/github", + "owners": [ + "3d0d", + "Cloistered", + "Clustered-Computing", + "IDEXX-UTDesign", + "NixOS", + "SpongeScribe", + "chip-rom", + "chiplox", + "developing-today", + "developing-today-fork", + "developing-today-forks", + "dezren3", + "dezren39", + "dezren39-dev", + "drewry-pope", + "sleep-atomic", + "twitter-base" + ], + "owner_notes": { + "vertexinc": "GAP: org enforces SAML SSO; the token cannot enumerate it. Nothing under it is mirrored.", + "NixOS": "Member-only org: mirrored by the sweep (readable), but the backup GitHub App cannot be installed here \u2014 no webhook coverage.", + "dezren39/edsebooks": "GAP: GitHub returns HTTP 451 (repository access blocked). Cannot be fetched." + }, + "tier_rules": { + "include_nonforks": true, + "fork_max_size_mb": 500, + "skip_zero_commit_repos": true, + "force_include": [ + "dezren39/opencode", + "dezren39/Quake_4_Alpha", + "dezren39/nixpkgs", + "developing-today-forks/nixpkgs", + "NixOS/nixpkgs" + ], + "force_include_reasons": { + "dezren39/opencode": "502 MB but the live chain parent of developing-today/opencode.", + "dezren39/Quake_4_Alpha": "1.35 GB, Drew's own recent work (not a passive mirror).", + "dezren39/nixpkgs": "nixpkgs family member (pool).", + "developing-today-forks/nixpkgs": "nixpkgs family member (pool).", + "NixOS/nixpkgs": "nixpkgs family ANCHOR (non-fork, included anyway)." + }, + "new_giant_forks": "pending-drew-review", + "families": "Forks sharing an upstream (parent) with >=2 included copies, or whose parent is itself included, are cloned with git alternates against the family anchor (first/full mirror of that history). Anchors are recorded in FAMILIES.md in the backup tree." + }, + "exclusions": [ + { + "repo": "developing-today-forks/nerd-fonts", + "reason": "Excluded by Drew's ruling 2026-10-31 \u2014 passive giant (21.2 GB), upstream is the backup." + }, + { + "repo": "Clustered-Computing/linux", + "reason": "Excluded by Drew's ruling 2026-10-31 \u2014 passive giant, upstream is the backup." + }, + { + "repo": "dezren39/cockroach", + "reason": "Excluded by Drew's ruling 2026-10-31 \u2014 passive giant, upstream is the backup." + }, + { + "repo": "dezren39/sipeed_wiki", + "reason": "Excluded by Drew's ruling 2026-10-31 \u2014 passive giant, upstream is the backup." + }, + { + "repo": "dezren39/weaviate", + "reason": "Excluded by Drew's ruling 2026-10-31 \u2014 passive giant, upstream is the backup." + }, + { + "repo": "dezren39/installer", + "reason": "Excluded by Drew's ruling 2026-10-31 \u2014 passive giant, upstream is the backup." + }, + { + "repo": "developing-today-forks/dgraph", + "reason": "Excluded by Drew's ruling 2026-10-31 \u2014 passive giant, upstream is the backup." + } + ], + "gaps": [ + { + "repo": "dezren39/edsebooks", + "reason": "HTTP 451 \u2014 repository access blocked by GitHub." + }, + { + "repo": "vertexinc/*", + "reason": "Org enforces SAML SSO; cannot enumerate or fetch." + } + ], + "app": { + "name": "hatch-repo-backup", + "owner": "dezren39", + "permissions": { + "metadata": "read", + "contents": "read" + }, + "events": [ + "push", + "repository" + ], + "bitwarden_secret_names": { + "app_id": "github-app.backup-app-id", + "client_id": "github-app.backup-client-id", + "client_secret": "github-app.backup-client-secret", + "private_key": "github-app.backup-private-key", + "webhook_secret": "github-app.backup-webhook-secret", + "worker_bearer": "github-app.backup-worker-bearer", + "worker_url": "github-app.backup-worker-url" + } + }, + "worker": { + "name": "hatch-repo-backup-webhook", + "queue_poll_path": "/queue", + "webhook_path": "/github" + }, + "timers": { + "fetch": "daily, mirrors fetched <12h ago are skipped", + "reconcile": "weekly", + "drain": "every 5 min, per-repo fetch coalescing 15 min" + } +} \ No newline at end of file diff --git a/infra/github-backup/docs/RUNBOOK.md b/infra/github-backup/docs/RUNBOOK.md new file mode 100644 index 0000000000..7b2260d34d --- /dev/null +++ b/infra/github-backup/docs/RUNBOOK.md @@ -0,0 +1,159 @@ +# github-backup RUNBOOK + +All commands are copy-paste. `$GB` = this directory in a checkout of +developing-today/code. On the laptop the checkout is `~/git/code`, so: + +```sh +GB=~/git/code/infra/github-backup +ROOT=~/backups/github # backup tree (config.json: backup_root) +``` + +Secrets are referenced BY NAME from Bitwarden Secrets Manager; source +`~/tools/bws-env.sh` in any shell that runs `bws` or `app_setup.py`. + +--- + +## 1. Initial install (a machine that already has the tree) + +```sh +cd ~/git/code && git pull +$GB/systemd/install-units.sh +systemctl --user list-timers 'github-backup-*' +``` + +## 2. Initial build of the tree (or rebuild from scratch) + +```sh +mkdir -p $ROOT +python3 $GB/bin/reconcile.py # writes plan.json, clones everything missing +python3 $GB/bin/manifest.py # writes MANIFEST.json + FAMILIES.md +du -sh $ROOT +python3 -c "import json;print(json.load(open('$ROOT/MANIFEST.json'))['totals'])" +``` + +`reconcile.py` is resumable: re-running skips verified mirrors and only +clones what is missing. The clone pass is parallel (4 workers) and takes +hours on first run for the full estate (~850 mirrors). + +Spot-verify a mirror end to end: + +```sh +git -C $ROOT/dezren39/hatch-personal.git fsck +git clone $ROOT/dezren39/hatch-personal.git /tmp/restore-test && \ + git -C /tmp/restore-test log -1 --oneline +``` + +## 3. The GitHub App (one-time) + +The App must be created by a human click (GitHub requires it); everything +after is scripted. + +```sh +source ~/tools/bws-env.sh +# 1. deploy the Worker first (§5) and set GHB_WORKER_URL to its URL. +export GHB_WORKER_URL="https://hatch-repo-backup-webhook..workers.dev" +# 2. store the Worker's URL + a drain bearer in Bitwarden (drainer reads them): +bws secret create github-app.backup-worker-url "$GHB_WORKER_URL" "$(bws project list | jq -r '.[0].id')" +python3 -c "import secrets;print(secrets.token_hex(32))" # <- put this value in BOTH: +bws secret create github-app.backup-worker-bearer "" "$(bws project list | jq -r '.[0].id')" # Bitwarden (this name) +# ...and the Worker: wrangler secret put DRAIN_BEARER +# 3. print the App manifest + click path: +python3 $GB/bin/app_setup.py manifest +# 4. submit the manifest as dezren39 at https://github.com/settings/apps/new +# (manifest flow). GitHub redirects with ?code=XXXX. Then: +python3 $GB/bin/app_setup.py convert XXXX # credentials -> Bitwarden by name +python3 $GB/bin/app_setup.py webhook-secret # webhook secret -> Bitwarden by name +# 5. set the SAME webhook secret on the App (GitHub UI) and the Worker: +cd $GB/worker && wrangler secret put GITHUB_WEBHOOK_SECRET +``` + +### Installing the App on an owner (do per owner) + +1. Open `https://github.com/settings/apps/hatch-repo-backup/installations` + (for an org: `https://github.com/organizations//settings/apps/hatch-repo-backup/installations`). +2. Install on the account/org, repository access = **All repositories** + (so next week's new repos are covered without a revisit). +3. Verify: + +```sh +python3 $GB/bin/app_setup.py install-report +``` + +Owners where Drew is only a member (NixOS, vertexinc) cannot install the +App — they stay sweep-only; that is expected and recorded in config.json. + +## 4. Adding a new owner/org to the mirror set + sweep + +```sh +# 1. config edit only — add the login to "owners" in: +$EDITOR $GB/config.json +# 2. commit + PR the config change (developing-today/code), merge, pull on laptop. +# 3. install the App on the new org (§3) if Drew is an admin there. +# 4. pick up the new owner immediately instead of waiting for Sunday: +python3 $GB/bin/reconcile.py +``` + +A new giant fork appearing anywhere is NOT auto-cloned: the sweep lists +it under "pending Drew review" in `reconcile-*.md`. To approve one, add +it to `force_include` (with a reason) in config.json and re-run reconcile. + +## 5. Worker deploy / upgrade + +```sh +cd $GB/worker +wrangler kv namespace create GHB_EVENTS # first time only; paste id into wrangler.toml +wrangler deploy # Worker versions track repo commits +curl https://hatch-repo-backup-webhook..workers.dev/health +``` + +## 6. Upgrade (machines) + +```sh +cd ~/git/code && git pull +$GB/systemd/install-units.sh # reinstalls units from the checkout +systemctl --user restart github-backup-drain.timer +``` + +## 7. Fresh-laptop reinstall + +```sh +# prerequisites: gh auth login (as dezren39), ~/tools/bws-env.sh present, +# code cloned to ~/git/code, laptop timers pattern available. +GB=~/git/code/infra/github-backup +# Option A — copy the tree from the old machine (fast, keeps alternates valid +# only if paths are identical; the tree root must stay ~/backups/github): +rsync -a old-laptop:~/backups/github/ ~/backups/github/ +# Option B — rebuild from GitHub (config + MANIFEST are the spec): +mkdir -p ~/backups/github +python3 $GB/bin/reconcile.py && python3 $GB/bin/manifest.py +# then: +$GB/systemd/install-units.sh +``` + +## 8. Restore from a mirror + +```sh +# normal repo: +git clone ~/backups/github//.git ./ +# cold/off-site copy of one repo (materializes alternates — safe to move): +git -C ~/backups/github//.git bundle create /tmp/.bundle --all +git bundle verify /tmp/.bundle +git clone /tmp/.bundle ./ +``` + +## 9. Disaster recovery (tree lost, GitHub intact) + +Config (this repo) + Bitwarden are the only inputs. §7 Option B rebuilds +the entire tree; MANIFEST.json regenerates at the end. Exclusions and +gaps in config.json reproduce exactly the intended non-coverage. + +## 10. Health checks + +```sh +systemctl --user list-timers 'github-backup-*' +tail -20 ~/backups/github/fetch.log +ls ~/backups/github/reconcile-*.md | tail -3 +python3 $GB/bin/manifest.py # refresh totals after any manual change +gh api rate_limit --jq '.resources.core' # personal-token pool (sweep) +python3 $GB/bin/app_setup.py install-report # App installations +``` diff --git a/infra/github-backup/systemd/drain-wrapper.sh b/infra/github-backup/systemd/drain-wrapper.sh new file mode 100755 index 0000000000..cb1a008a51 --- /dev/null +++ b/infra/github-backup/systemd/drain-wrapper.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Sources the Worker URL + bearer from Bitwarden BY NAME at runtime +# (names: github-app.backup-worker-url / github-app.backup-worker-bearer; +# see ../config.json). Values pass through the environment only and are +# never written to disk. +set -euo pipefail +source ~/tools/bws-env.sh +eval "$(python3 - <<'PY' +import json, subprocess +lst = json.loads(subprocess.run(["bws", "secret", "list"], + capture_output=True, text=True).stdout or "[]") +ids = {s["key"]: s["id"] for s in lst} +def get(name): + r = subprocess.run(["bws", "secret", "get", ids[name]], + capture_output=True, text=True) + return json.loads(r.stdout)["value"] +print(f"export GHB_WORKER_URL={get('github-app.backup-worker-url')!r}") +print(f"export GHB_WORKER_BEARER={get('github-app.backup-worker-bearer')!r}") +PY +)" +exec python3 "$(dirname "$0")/../bin/drain_queue.py" diff --git a/infra/github-backup/systemd/github-backup-drain.service b/infra/github-backup/systemd/github-backup-drain.service new file mode 100644 index 0000000000..9e6db92c7c --- /dev/null +++ b/infra/github-backup/systemd/github-backup-drain.service @@ -0,0 +1,9 @@ +[Unit] +Description=github-backup: drain webhook queue from the Worker and fetch +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=__GB_DIR__/systemd/drain-wrapper.sh +WorkingDirectory=%h/backups/github diff --git a/infra/github-backup/systemd/github-backup-drain.timer b/infra/github-backup/systemd/github-backup-drain.timer new file mode 100644 index 0000000000..a69a548a57 --- /dev/null +++ b/infra/github-backup/systemd/github-backup-drain.timer @@ -0,0 +1,10 @@ +[Unit] +Description=github-backup queue drain (every 5 min) + +[Timer] +OnBootSec=3min +OnUnitActiveSec=5min +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/infra/github-backup/systemd/github-backup-fetch.service b/infra/github-backup/systemd/github-backup-fetch.service new file mode 100644 index 0000000000..c96c7ef86c --- /dev/null +++ b/infra/github-backup/systemd/github-backup-fetch.service @@ -0,0 +1,9 @@ +[Unit] +Description=github-backup: daily fetch of all mirrors +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/bin/env python3 __GB_DIR__/bin/fetch_mirrors.py +WorkingDirectory=%h/backups/github diff --git a/infra/github-backup/systemd/github-backup-fetch.timer b/infra/github-backup/systemd/github-backup-fetch.timer new file mode 100644 index 0000000000..d99be81264 --- /dev/null +++ b/infra/github-backup/systemd/github-backup-fetch.timer @@ -0,0 +1,10 @@ +[Unit] +Description=github-backup fetch (daily) + +[Timer] +OnCalendar=daily +Persistent=true +RandomizedDelaySec=30m + +[Install] +WantedBy=timers.target diff --git a/infra/github-backup/systemd/github-backup-reconcile.service b/infra/github-backup/systemd/github-backup-reconcile.service new file mode 100644 index 0000000000..c67d163aab --- /dev/null +++ b/infra/github-backup/systemd/github-backup-reconcile.service @@ -0,0 +1,9 @@ +[Unit] +Description=github-backup: weekly reconciliation sweep +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/bin/env python3 __GB_DIR__/bin/reconcile.py +WorkingDirectory=%h/backups/github diff --git a/infra/github-backup/systemd/github-backup-reconcile.timer b/infra/github-backup/systemd/github-backup-reconcile.timer new file mode 100644 index 0000000000..0e8a15046b --- /dev/null +++ b/infra/github-backup/systemd/github-backup-reconcile.timer @@ -0,0 +1,10 @@ +[Unit] +Description=github-backup reconcile (weekly) + +[Timer] +OnCalendar=weekly +Persistent=true +RandomizedDelaySec=2h + +[Install] +WantedBy=timers.target diff --git a/infra/github-backup/systemd/install-units.sh b/infra/github-backup/systemd/install-units.sh new file mode 100755 index 0000000000..afe0489dc7 --- /dev/null +++ b/infra/github-backup/systemd/install-units.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Install the github-backup user units on this machine. +# Usage: GHB_CODE_DIR=~/git/code ./install-units.sh +# __GB_DIR__ in the unit templates is replaced with this directory's path +# inside the code checkout, so units always run the repo's scripts. +set -euo pipefail +GB_DIR="$(cd "$(dirname "$0")/.." && pwd)" +UNIT_DIR="$HOME/.config/systemd/user" +mkdir -p "$UNIT_DIR" +for u in github-backup-fetch.service github-backup-fetch.timer \ + github-backup-reconcile.service github-backup-reconcile.timer \ + github-backup-drain.service github-backup-drain.timer; do + sed "s#__GB_DIR__#$GB_DIR#g" "$GB_DIR/systemd/$u" > "$UNIT_DIR/$u" +done +systemctl --user daemon-reload +systemctl --user enable --now github-backup-fetch.timer \ + github-backup-reconcile.timer github-backup-drain.timer +systemctl --user list-timers 'github-backup-*' --no-pager diff --git a/infra/github-backup/worker/src/index.js b/infra/github-backup/worker/src/index.js new file mode 100644 index 0000000000..bdad5406c8 --- /dev/null +++ b/infra/github-backup/worker/src/index.js @@ -0,0 +1,71 @@ +// hatch-repo-backup-webhook — GitHub App webhook receiver + laptop queue. +// +// POST /github GitHub webhook. Verifies X-Hub-Signature-256 (HMAC +// SHA-256 with GITHUB_WEBHOOK_SECRET), stores +// {id, repo, event, action, ts} in KV (TTL 7 days). +// GET /queue Bearer DRAIN_BEARER. Returns pending events. +// POST /queue/ack Bearer DRAIN_BEARER. Body {"ids":[...]} deletes them. +// GET /health Liveness. +// +// Events are a freshness signal only; the weekly reconcile sweep in +// ../bin/reconcile.py is the correctness floor, so a lost event is not +// lost data. Source of truth: developing-today/code infra/github-backup. + +const enc = new TextEncoder(); + +async function hmacHex(secret, body) { + const key = await crypto.subtle.importKey( + "raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); + const sig = await crypto.subtle.sign("HMAC", key, enc.encode(body)); + return [...new Uint8Array(sig)].map(b => b.toString(16).padStart(2, "0")).join(""); +} + +function authed(req, env) { + const h = req.headers.get("Authorization") || ""; + return env.DRAIN_BEARER && h === `Bearer ${env.DRAIN_BEARER}`; +} + +export default { + async fetch(req, env) { + const url = new URL(req.url); + if (url.pathname === "/health") return new Response("ok"); + if (url.pathname === "/github" && req.method === "POST") { + const body = await req.text(); + const given = (req.headers.get("X-Hub-Signature-256") || "").replace("sha256=", ""); + const expect = await hmacHex(env.GITHUB_WEBHOOK_SECRET, body); + let diff = given.length ^ expect.length; + for (let i = 0; i < expect.length; i++) + diff |= (given.charCodeAt(i) || 0) ^ expect.charCodeAt(i); + if (diff !== 0) return new Response("bad signature", { status: 401 }); + let payload = {}; + try { payload = JSON.parse(body); } catch { /* ping has form encoding sometimes */ } + const event = req.headers.get("X-GitHub-Event") || "unknown"; + if (event === "ping") return new Response("pong"); + const repo = payload.repository && payload.repository.full_name; + if (!repo) return new Response("no repository in payload", { status: 202 }); + const id = `${Date.now()}-${crypto.randomUUID()}`; + await env.GHB_EVENTS.put("ev:" + id, JSON.stringify({ + id, repo, event, action: payload.action || null, + ts: new Date().toISOString(), + }), { expirationTtl: 7 * 24 * 3600 }); + return new Response("queued", { status: 202 }); + } + if (url.pathname === "/queue" && req.method === "GET") { + if (!authed(req, env)) return new Response("unauthorized", { status: 401 }); + const list = await env.GHB_EVENTS.list({ prefix: "ev:", limit: 500 }); + const events = []; + for (const k of list.keys) { + const v = await env.GHB_EVENTS.get(k.name); + if (v) events.push(JSON.parse(v)); + } + return Response.json({ events }); + } + if (url.pathname === "/queue/ack" && req.method === "POST") { + if (!authed(req, env)) return new Response("unauthorized", { status: 401 }); + const { ids } = await req.json(); + for (const id of ids || []) await env.GHB_EVENTS.delete("ev:" + id); + return Response.json({ acked: (ids || []).length }); + } + return new Response("not found", { status: 404 }); + }, +}; diff --git a/infra/github-backup/worker/wrangler.toml b/infra/github-backup/worker/wrangler.toml new file mode 100644 index 0000000000..d2a389079a --- /dev/null +++ b/infra/github-backup/worker/wrangler.toml @@ -0,0 +1,14 @@ +name = "hatch-repo-backup-webhook" +main = "src/index.js" +compatibility_date = "2024-11-01" + +# Queue of webhook events awaiting the laptop drainer. +# Create with: wrangler kv namespace create GHB_EVENTS +# then paste the id here (ids are not secrets; they name the namespace). +[[kv_namespaces]] +binding = "GHB_EVENTS" +id = "REPLACE_WITH_KV_NAMESPACE_ID" + +# Secrets (never in this file): +# wrangler secret put GITHUB_WEBHOOK_SECRET # same value as on the App +# wrangler secret put DRAIN_BEARER # laptop drainer authenticates with this