From 15011391439010bb4f085318c20371558577a83c Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:39:45 -0400 Subject: [PATCH 01/22] deps: add authlib for GitHub OAuth Pins authlib>=1.3,<2 so the generator can register a GitHub OAuth client for the upcoming login flow. Co-Authored-By: Claude Opus 4.7 --- generator/requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/generator/requirements.txt b/generator/requirements.txt index 2a644ec..1eac3be 100644 --- a/generator/requirements.txt +++ b/generator/requirements.txt @@ -5,3 +5,4 @@ requests==2.32.3 pytest==8.3.3 responses==0.25.3 gunicorn==23.0.0 +authlib>=1.3,<2 From 4822272b4900446469c225e00fe3d33153f4ca23 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:40:28 -0400 Subject: [PATCH 02/22] config: add GitHub OAuth + session env vars --- generator/src/config.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/generator/src/config.py b/generator/src/config.py index ee78d31..fcc3f83 100644 --- a/generator/src/config.py +++ b/generator/src/config.py @@ -140,3 +140,23 @@ PREFETCH_MAX_WORKERS = int(os.getenv("PREFETCH_MAX_WORKERS", "2")) PENDING_JOB_QUEUE_CAP = int(os.getenv("PENDING_JOB_QUEUE_CAP", "200")) # How long a /generate caller will wait for the semaphore before giving up. GENERATE_SEMAPHORE_WAIT_S = float(os.getenv("GENERATE_SEMAPHORE_WAIT_S", "15")) + +# --- GitHub OAuth --- +GITHUB_OAUTH_CLIENT_ID = os.getenv("GITHUB_OAUTH_CLIENT_ID", "") +GITHUB_OAUTH_CLIENT_SECRET = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "") +GITHUB_OAUTH_REDIRECT_URI = os.getenv("GITHUB_OAUTH_REDIRECT_URI", "") + +# Flask session secret. Generate once: python -c "import secrets; print(secrets.token_hex(32))" +SECRET_KEY = os.getenv("GENERATOR_SECRET_KEY", "") + +# Dev-only override; defaults to True so production HTTPS cookies work. +SESSION_COOKIE_SECURE = os.getenv("SESSION_COOKIE_SECURE", "true").lower() != "false" + +# CSRF defense-in-depth: Origin/Referer allowlist for state-changing routes. +ALLOWED_ORIGINS = tuple( + o.strip() for o in os.getenv("ALLOWED_ORIGINS", "https://gh-stats.com").split(",") if o.strip() +) + +# Per-login rate limit on mutate routes, layered on top of per-IP limits. +RATE_LIMIT_MUTATE_PER_LOGIN_MAX = int(os.getenv("RATE_LIMIT_MUTATE_PER_LOGIN_MAX", "120")) +RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW = int(os.getenv("RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW", "60")) From 57b782ceaf5e07b84511d288d1247c020140c85a Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:44:01 -0400 Subject: [PATCH 03/22] db: add github_id and github_avatar_url columns + set_github_profile --- generator/src/db.py | 17 ++++++++++++++++- generator/tests/test_db.py | 9 +++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/generator/src/db.py b/generator/src/db.py index bbb121f..5ce8969 100644 --- a/generator/src/db.py +++ b/generator/src/db.py @@ -27,7 +27,9 @@ CREATE TABLE IF NOT EXISTS users ( last_fetcher_payload_hash TEXT, manual_refresh_used INTEGER DEFAULT 0, last_requested_at TEXT NOT NULL, - edit_token_hash TEXT + edit_token_hash TEXT, + github_id INTEGER, + github_avatar_url TEXT ); CREATE TABLE IF NOT EXISTS enrollments_daily ( day TEXT PRIMARY KEY, @@ -116,6 +118,10 @@ def init_dbs() -> None: cols = {r["name"] for r in c.execute("PRAGMA table_info(users)").fetchall()} if "edit_token_hash" not in cols: c.execute("ALTER TABLE users ADD COLUMN edit_token_hash TEXT") + if "github_id" not in cols: + c.execute("ALTER TABLE users ADD COLUMN github_id INTEGER") + if "github_avatar_url" not in cols: + c.execute("ALTER TABLE users ADD COLUMN github_avatar_url TEXT") c.commit() with _widgets_conn() as c: c.executescript(_WIDGETS_SCHEMA) @@ -264,6 +270,15 @@ def set_last_fetcher_hash(username: str, h: str) -> None: c.commit() +def set_github_profile(username: str, github_id: int, github_avatar_url: str) -> None: + with _settings_conn() as c: + c.execute( + "UPDATE users SET github_id=?, github_avatar_url=? WHERE username=?", + (github_id, github_avatar_url, username), + ) + c.commit() + + # ---- jobs ---- def enqueue_build(username: str) -> int: diff --git a/generator/tests/test_db.py b/generator/tests/test_db.py index 12f7a2f..36ee1e7 100644 --- a/generator/tests/test_db.py +++ b/generator/tests/test_db.py @@ -100,3 +100,12 @@ def test_reclaim_stuck_running_jobs(tmp_dbs): dbmod.reclaim_stuck_jobs(older_than_minutes=10) job = dbmod.claim_next_job() assert job["id"] == jid + + +def test_set_github_profile_round_trip(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + dbmod.set_github_profile("alice", github_id=42, github_avatar_url="https://example.com/a.png") + with dbmod._settings_conn() as c: + row = c.execute("SELECT github_id, github_avatar_url FROM users WHERE username='alice'").fetchone() + assert row["github_id"] == 42 + assert row["github_avatar_url"] == "https://example.com/a.png" From 22483aea199affae65db0a2e32c07d4439e269a9 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:45:26 -0400 Subject: [PATCH 04/22] db: enroll() accepts github profile; no longer returns edit_token --- generator/src/db.py | 46 ++++++++++++++++++++------------------ generator/tests/test_db.py | 27 +++++++++++----------- 2 files changed, 38 insertions(+), 35 deletions(-) diff --git a/generator/src/db.py b/generator/src/db.py index 5ce8969..4436c59 100644 --- a/generator/src/db.py +++ b/generator/src/db.py @@ -152,44 +152,46 @@ def settings_hash(settings: dict) -> str: # ---- settings / enrollment ---- -def enroll(username: str, defaults: dict) -> dict: - """Insert a settings row + increment daily counter + enqueue build. +def enroll(username: str, defaults: dict, + github_id: int | None = None, + github_avatar_url: str | None = None) -> dict: + """Insert a settings row if missing, bump the daily counter, enqueue a build. - Returns {"job_id", "edit_token"}. The edit_token is the bearer token the - caller must present on future settings mutations for this user. We only - store its SHA-256 hash, so the plaintext here is the one and only chance - to surface it to the client. Subsequent enroll() calls for an existing - user return `edit_token=None` to avoid leaking tokens issued to earlier - registrants — settings cannot be taken over by re-enrolling. + Idempotent: calling again for an existing user refreshes github_avatar_url + (so login keeps the avatar fresh) and enqueues a rebuild. Always returns + {"job_id": int}. No token is returned — auth is handled by the signed + session cookie. """ sh = settings_hash(defaults) now = _now() - token = secrets.token_urlsafe(32) - token_hash = _hash_edit_token(token) with _settings_conn() as c: cur_ins = c.execute( """INSERT INTO users(username, settings_json, settings_hash, enrolled_at, - last_requested_at, edit_token_hash) - VALUES (?, ?, ?, ?, ?, ?) + last_requested_at, github_id, github_avatar_url) + VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(username) DO NOTHING""", - (username, json.dumps(defaults), sh, now, now, token_hash), + (username, json.dumps(defaults), sh, now, now, github_id, github_avatar_url), ) inserted = cur_ins.rowcount == 1 - c.execute( - """INSERT INTO enrollments_daily(day, count) VALUES (?, 1) - ON CONFLICT(day) DO UPDATE SET count = count + 1""", - (_today(),), - ) + if not inserted and (github_id is not None or github_avatar_url is not None): + c.execute( + "UPDATE users SET github_id=COALESCE(?, github_id), " + "github_avatar_url=COALESCE(?, github_avatar_url) WHERE username=?", + (github_id, github_avatar_url, username), + ) + if inserted: + c.execute( + """INSERT INTO enrollments_daily(day, count) VALUES (?, 1) + ON CONFLICT(day) DO UPDATE SET count = count + 1""", + (_today(),), + ) cur = c.execute( """INSERT INTO jobs(kind, username, status, created_at, updated_at) VALUES ('build', ?, 'pending', ?, ?)""", (username, now, now), ) c.commit() - return { - "job_id": cur.lastrowid, - "edit_token": token if inserted else None, - } + return {"job_id": cur.lastrowid} def enrollments_today() -> int: diff --git a/generator/tests/test_db.py b/generator/tests/test_db.py index 36ee1e7..6063899 100644 --- a/generator/tests/test_db.py +++ b/generator/tests/test_db.py @@ -19,23 +19,24 @@ def test_settings_hash_is_deterministic(): assert h1 == h2 -def test_enroll_and_get_settings(tmp_dbs): - defaults = {"theme": "dark", "widgets": ["grade"]} - result = dbmod.enroll("alice", defaults) - assert result["job_id"] > 0 - assert result["edit_token"] # first enrollment surfaces a token - s = dbmod.get_settings("alice") - assert s["settings"] == defaults - assert s["manual_refresh_used"] == 0 +def test_enroll_returns_job_id(tmp_dbs): + r = dbmod.enroll("alice", {"theme": "dark"}) + assert r["job_id"] > 0 + assert "edit_token" not in r -def test_enroll_twice_does_not_reissue_token(tmp_dbs): +def test_enroll_twice_noops(tmp_dbs): r1 = dbmod.enroll("alice", {"theme": "dark"}) r2 = dbmod.enroll("alice", {"theme": "dark"}) - assert r1["edit_token"] - assert r2["edit_token"] is None - assert dbmod.verify_edit_token("alice", r1["edit_token"]) is True - assert dbmod.verify_edit_token("alice", "wrong") is False + assert r1["job_id"] > 0 and r2["job_id"] > 0 + + +def test_enroll_with_github_profile(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}, github_id=1, github_avatar_url="https://x/a.png") + with dbmod._settings_conn() as c: + row = c.execute("SELECT github_id, github_avatar_url FROM users WHERE username='alice'").fetchone() + assert row["github_id"] == 1 + assert row["github_avatar_url"] == "https://x/a.png" def test_enrollments_daily_counter(tmp_dbs): From ec9d4c367276d4afb92f936117acad4358bf0142 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:47:11 -0400 Subject: [PATCH 05/22] db: remove dead _hash_edit_token; convert verify_edit_token to stub _hash_edit_token was only called by verify_edit_token and has no remaining callers in db.py (enroll no longer hashes tokens). Remove it along with the unused 'secrets' and 'hmac' imports. Keep verify_edit_token as a NotImplementedError stub since api.py's require_edit_token decorator still references it. Task 12 will remove both the decorator and this function together when switching to session-based auth. --- generator/src/db.py | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/generator/src/db.py b/generator/src/db.py index 4436c59..b424427 100644 --- a/generator/src/db.py +++ b/generator/src/db.py @@ -4,10 +4,8 @@ All access goes through this module so a future Postgres swap is local to here. Both DBs are opened with WAL mode. """ import hashlib -import hmac as _hmac import json import os -import secrets import sqlite3 from contextlib import contextmanager from datetime import datetime, timedelta @@ -128,21 +126,15 @@ def init_dbs() -> None: c.commit() -def _hash_edit_token(token: str) -> str: - return hashlib.sha256(token.encode("utf-8")).hexdigest() - - def verify_edit_token(username: str, presented: str) -> bool: - """Constant-time check of the caller's edit token against the stored hash.""" - if not username or not presented: - return False - with _settings_conn() as c: - row = c.execute( - "SELECT edit_token_hash FROM users WHERE username=?", (username,) - ).fetchone() - if row is None or not row["edit_token_hash"]: - return False - return _hmac.compare_digest(row["edit_token_hash"], _hash_edit_token(presented)) + """Constant-time check of the caller's edit token against the stored hash. + + DEPRECATED: This function is dead code as of Task 5 (edit tokens are no longer + hashed during enrollment). It remains here temporarily while api.py's + require_edit_token decorator is still being used. Task 12 will remove both + this function and the decorator consumer in api.py. + """ + raise NotImplementedError("verify_edit_token is deprecated; will be removed in Task 12") def settings_hash(settings: dict) -> str: From ccd0f63fa8b5dde4fd55212404d01bfc63cebc77 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:48:14 -0400 Subject: [PATCH 06/22] feat(auth): add OAuth client + require_github_owner/require_same_origin decorators --- generator/src/auth.py | 80 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 generator/src/auth.py diff --git a/generator/src/auth.py b/generator/src/auth.py new file mode 100644 index 0000000..376c055 --- /dev/null +++ b/generator/src/auth.py @@ -0,0 +1,80 @@ +"""GitHub OAuth integration for the generator service. + +Owns: + - OAuth client registration (authlib) + - `current_login()` — lowercase GitHub login from session, or None + - `require_github_owner` — decorator: 401 if no session, 403 if mismatch + - `require_same_origin` — decorator: 403 if Origin/Referer not in allowlist +""" +from functools import wraps +from urllib.parse import urlparse + +from authlib.integrations.flask_client import OAuth +from flask import jsonify, request, session + +from . import config + +_oauth: OAuth | None = None + + +def init_oauth(app) -> OAuth: + """Register the `github` provider. Safe to call once at app startup.""" + global _oauth + oauth = OAuth(app) + oauth.register( + name="github", + client_id=config.GITHUB_OAUTH_CLIENT_ID, + client_secret=config.GITHUB_OAUTH_CLIENT_SECRET, + access_token_url="https://github.com/login/oauth/access_token", + authorize_url="https://github.com/login/oauth/authorize", + api_base_url="https://api.github.com/", + client_kwargs={"scope": "read:user"}, + ) + _oauth = oauth + return oauth + + +def github_client(): + if _oauth is None: + raise RuntimeError("OAuth not initialized — call init_oauth(app) first.") + return _oauth.github + + +def current_login() -> str | None: + v = session.get("gh_login") + return v.lower() if isinstance(v, str) else None + + +def _origin_ok() -> bool: + origin = request.headers.get("Origin") or request.headers.get("Referer") or "" + if not origin: + return False + try: + o = urlparse(origin) + normalized = f"{o.scheme}://{o.netloc}" + except Exception: + return False + return normalized in config.ALLOWED_ORIGINS + + +def require_github_owner(fn): + """401 if no session; 403 if session login != url username (case-insensitive).""" + @wraps(fn) + def wrapper(username: str, *args, **kwargs): + me = current_login() + if me is None: + return jsonify({"error": "login_required"}), 401 + if me != (username or "").lower(): + return jsonify({"error": "forbidden"}), 403 + return fn(username, *args, **kwargs) + return wrapper + + +def require_same_origin(fn): + """Defense in depth beyond SameSite=Lax. Rejects cross-site mutate attempts.""" + @wraps(fn) + def wrapper(*args, **kwargs): + if not _origin_ok(): + return jsonify({"error": "bad_origin"}), 403 + return fn(*args, **kwargs) + return wrapper From 4602bb9494cb4f061e84f17e8638c6acb4c30ac7 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:49:39 -0400 Subject: [PATCH 07/22] test(auth): unit tests for require_github_owner and require_same_origin --- generator/tests/test_auth.py | 69 ++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 generator/tests/test_auth.py diff --git a/generator/tests/test_auth.py b/generator/tests/test_auth.py new file mode 100644 index 0000000..1efa0bb --- /dev/null +++ b/generator/tests/test_auth.py @@ -0,0 +1,69 @@ +"""Unit tests for auth helpers (no network).""" +import pytest +from flask import Flask, jsonify + +from src import auth, config + + +@pytest.fixture +def app(monkeypatch): + monkeypatch.setattr(config, "ALLOWED_ORIGINS", ("https://gh-stats.com",)) + app = Flask(__name__) + app.secret_key = "test-secret" + + @app.route("/protected/", methods=["POST"]) + @auth.require_same_origin + @auth.require_github_owner + def protected(username): + return jsonify({"ok": True, "you": auth.current_login()}) + + return app + + +def _good_hdrs(): + return {"Origin": "https://gh-stats.com"} + + +def test_current_login_none_by_default(app): + with app.test_request_context("/"): + assert auth.current_login() is None + + +def test_require_github_owner_401_without_session(app): + with app.test_client() as c: + r = c.post("/protected/alice", headers=_good_hdrs()) + assert r.status_code == 401 + assert r.get_json()["error"] == "login_required" + + +def test_require_github_owner_403_on_mismatch(app): + with app.test_client() as c: + with c.session_transaction() as s: + s["gh_login"] = "bob" + r = c.post("/protected/alice", headers=_good_hdrs()) + assert r.status_code == 403 + + +def test_require_github_owner_passes_with_matching_login(app): + with app.test_client() as c: + with c.session_transaction() as s: + s["gh_login"] = "Alice" # stored mixed-case on purpose + r = c.post("/protected/alice", headers=_good_hdrs()) + assert r.status_code == 200 + assert r.get_json()["you"] == "alice" + + +def test_require_same_origin_rejects_bad_origin(app): + with app.test_client() as c: + with c.session_transaction() as s: + s["gh_login"] = "alice" + r = c.post("/protected/alice", headers={"Origin": "https://evil.example"}) + assert r.status_code == 403 + + +def test_require_same_origin_rejects_missing_origin(app): + with app.test_client() as c: + with c.session_transaction() as s: + s["gh_login"] = "alice" + r = c.post("/protected/alice") + assert r.status_code == 403 From 232812b3a0482a0649f0ea46711395249fed8143 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:51:22 -0400 Subject: [PATCH 08/22] feat(api): configure Flask session + init OAuth client --- generator/src/api.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/generator/src/api.py b/generator/src/api.py index f4be8f5..81ee86f 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -19,11 +19,12 @@ import os import time from collections import defaultdict, deque from concurrent.futures import ThreadPoolExecutor +from datetime import timedelta from functools import wraps from threading import BoundedSemaphore, Lock from flask import Flask, jsonify, request, Response, send_from_directory -from . import config, db, fetcher_client, placeholder +from . import auth, config, db, fetcher_client, placeholder from .themes import THEMES from .utils import is_valid_username, settings_size_ok import json as _json @@ -151,6 +152,23 @@ def require_edit_token(fn): _STATIC_DIR = os.path.join(os.path.dirname(__file__), "static") app = Flask(__name__, static_folder=None) + +if config.SECRET_KEY: + app.secret_key = config.SECRET_KEY +else: + # In tests and local dev we allow a weak default; production must set the env. + app.secret_key = "dev-insecure-secret-do-not-use-in-prod" + +app.config.update( + SESSION_COOKIE_NAME="gh_session", + SESSION_COOKIE_SECURE=config.SESSION_COOKIE_SECURE, + SESSION_COOKIE_HTTPONLY=True, + SESSION_COOKIE_SAMESITE="Lax", + PERMANENT_SESSION_LIFETIME=timedelta(days=30), +) + +auth.init_oauth(app) + # Reject oversized bodies before they reach the DB. 128 KB is generous for our # settings shape and still caps the memory footprint of a flood of PATCHes. app.config["MAX_CONTENT_LENGTH"] = 128 * 1024 From a6356d4d1d43e4d4bf7577b66f762ee63d326a3d Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:53:12 -0400 Subject: [PATCH 09/22] feat(api): add /api/auth/me and /api/auth/logout --- generator/src/api.py | 20 +++++++++++++- generator/tests/test_auth.py | 51 ++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/generator/src/api.py b/generator/src/api.py index 81ee86f..e1389e5 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -22,7 +22,7 @@ from concurrent.futures import ThreadPoolExecutor from datetime import timedelta from functools import wraps from threading import BoundedSemaphore, Lock -from flask import Flask, jsonify, request, Response, send_from_directory +from flask import Flask, jsonify, request, Response, send_from_directory, session from . import auth, config, db, fetcher_client, placeholder from .themes import THEMES @@ -334,6 +334,24 @@ def spa(path: str): return jsonify({"error": "frontend not built"}), 503 +@app.route("/api/auth/me", methods=["GET"]) +def auth_me(): + login = auth.current_login() + if login is None: + return jsonify({"login": None}) + return jsonify({ + "login": login, + "avatar_url": session.get("gh_avatar_url"), + }) + + +@app.route("/api/auth/logout", methods=["POST"]) +@auth.require_same_origin +def auth_logout(): + session.clear() + return ("", 204) + + @app.route("/api/health", methods=["GET"]) def health(): return jsonify({"status": "ok", "service": "generator"}) diff --git a/generator/tests/test_auth.py b/generator/tests/test_auth.py index 1efa0bb..ac48b67 100644 --- a/generator/tests/test_auth.py +++ b/generator/tests/test_auth.py @@ -67,3 +67,54 @@ def test_require_same_origin_rejects_missing_origin(app): s["gh_login"] = "alice" r = c.post("/protected/alice") assert r.status_code == 403 + + +from src import api as api_module + + +@pytest.fixture +def api_client(monkeypatch, tmp_path): + # Point DBs at tmp + configure origins. + from src import db as dbmod, config as cfg + monkeypatch.setattr(cfg, "SETTINGS_DB_PATH", str(tmp_path / "s.db")) + monkeypatch.setattr(cfg, "WIDGETS_DB_PATH", str(tmp_path / "w.db")) + monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", str(tmp_path / "s.db")) + monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", str(tmp_path / "w.db")) + dbmod.init_dbs() + monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",)) + api_module.app.config["TESTING"] = True + api_module.app.config["SESSION_COOKIE_SECURE"] = False + return api_module.app.test_client() + + +def test_me_unauthed_returns_null(api_client): + r = api_client.get("/api/auth/me") + assert r.status_code == 200 + assert r.get_json() == {"login": None} + + +def test_me_authed_returns_login(api_client): + with api_client.session_transaction() as s: + s["gh_login"] = "alice" + s["gh_avatar_url"] = "https://x/a.png" + r = api_client.get("/api/auth/me") + assert r.status_code == 200 + j = r.get_json() + assert j["login"] == "alice" + assert j["avatar_url"] == "https://x/a.png" + + +def test_logout_clears_session(api_client): + with api_client.session_transaction() as s: + s["gh_login"] = "alice" + r = api_client.post("/api/auth/logout", headers={"Origin": "https://gh-stats.com"}) + assert r.status_code == 204 + r = api_client.get("/api/auth/me") + assert r.get_json()["login"] is None + + +def test_logout_rejects_bad_origin(api_client): + with api_client.session_transaction() as s: + s["gh_login"] = "alice" + r = api_client.post("/api/auth/logout", headers={"Origin": "https://evil.example"}) + assert r.status_code == 403 From 98c40ff99301ff6870451d1ae75478264fdedf1d Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:54:44 -0400 Subject: [PATCH 10/22] feat(api): add /api/auth/github/login with CSRF state + local-only next Co-Authored-By: Claude Opus 4.7 --- generator/src/api.py | 21 +++++++++++++++++++++ generator/tests/test_auth.py | 17 +++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/generator/src/api.py b/generator/src/api.py index e1389e5..7cb2428 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -352,6 +352,27 @@ def auth_logout(): return ("", 204) +@app.route("/api/auth/github/login", methods=["GET"]) +def auth_github_login(): + import secrets as _secrets + nxt = request.args.get("next", "/") + # Only accept local relative paths to prevent open-redirect. + if not isinstance(nxt, str) or not nxt.startswith("/"): + nxt = "/" + state = _secrets.token_urlsafe(32) + session["oauth_state"] = state + session["oauth_next"] = nxt + redirect_uri = config.GITHUB_OAUTH_REDIRECT_URI or _derived_redirect_uri() + return auth.github_client().authorize_redirect(redirect_uri, state=state) + + +def _derived_redirect_uri() -> str: + # Works behind cloudflared: the X-Forwarded-Proto/Host headers are set. + proto = request.headers.get("X-Forwarded-Proto") or request.scheme + host = request.headers.get("X-Forwarded-Host") or request.host + return f"{proto}://{host}/api/auth/github/callback" + + @app.route("/api/health", methods=["GET"]) def health(): return jsonify({"status": "ok", "service": "generator"}) diff --git a/generator/tests/test_auth.py b/generator/tests/test_auth.py index ac48b67..d9474df 100644 --- a/generator/tests/test_auth.py +++ b/generator/tests/test_auth.py @@ -118,3 +118,20 @@ def test_logout_rejects_bad_origin(api_client): s["gh_login"] = "alice" r = api_client.post("/api/auth/logout", headers={"Origin": "https://evil.example"}) assert r.status_code == 403 + + +def test_login_stashes_state_and_redirects(api_client): + """Don't depend on authlib's exact redirect URL — just confirm the route + stashes a random state, records the next path, and returns a 3xx.""" + r = api_client.get("/api/auth/github/login?next=/workshop") + assert r.status_code in (302, 303) + with api_client.session_transaction() as s: + assert s.get("oauth_state") + assert s.get("oauth_next") == "/workshop" + + +def test_login_rejects_external_next(api_client): + r = api_client.get("/api/auth/github/login?next=https://evil.example/foo") + assert r.status_code in (302, 303) + with api_client.session_transaction() as s: + assert s.get("oauth_next") == "/" From eb4b68bf0d7124f70b4faae88715f908bac309ee Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:57:20 -0400 Subject: [PATCH 11/22] =?UTF-8?q?feat(api):=20OAuth=20callback=20=E2=80=94?= =?UTF-8?q?=20verify=20state,=20fetch=20profile,=20implicit=20enroll?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.7 --- generator/src/api.py | 60 ++++++++++++++++++++++++++++++++++++ generator/tests/test_auth.py | 36 ++++++++++++++++++++++ 2 files changed, 96 insertions(+) diff --git a/generator/src/api.py b/generator/src/api.py index 7cb2428..2a2710c 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -373,6 +373,66 @@ def _derived_redirect_uri() -> str: return f"{proto}://{host}/api/auth/github/callback" +def _gh_api_get(token: str, path: str) -> dict: + """Thin wrapper over requests.get so tests can monkeypatch one function.""" + import requests + r = requests.get( + f"https://api.github.com/{path.lstrip('/')}", + headers={"Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json"}, + timeout=config.API_TIMEOUT, + ) + if r.status_code >= 400: + raise RuntimeError(f"github {path} {r.status_code}") + return r.json() + + +@app.route("/api/auth/github/callback", methods=["GET"]) +def auth_github_callback(): + from flask import redirect + state = request.args.get("state", "") + expected = session.pop("oauth_state", None) + nxt = session.pop("oauth_next", "/") or "/" + if not expected or state != expected: + return jsonify({"error": "bad_state"}), 400 + try: + token_resp = auth.github_client().authorize_access_token() + except Exception: + log.exception("token exchange failed") + return redirect("/?auth_error=exchange") + access_token = token_resp.get("access_token") if token_resp else None + if not access_token: + return redirect("/?auth_error=exchange") + try: + user = _gh_api_get(access_token, "user") + except Exception: + log.exception("github /user failed") + return redirect("/?auth_error=profile") + + login_raw = user.get("login") + gh_id = user.get("id") + avatar_url = user.get("avatar_url") or "" + if not isinstance(login_raw, str) or not is_valid_username(login_raw) or not isinstance(gh_id, int): + return redirect("/?auth_error=profile") + + login = login_raw.lower() + session.permanent = True + session["gh_login"] = login + session["gh_id"] = gh_id + session["gh_avatar_url"] = avatar_url + + # Implicit enrollment. Idempotent; refreshes github_avatar_url on return logins. + defaults = { + "theme": "dark", + "enabled": config.ENABLED_WIDGETS, + "widget_order": config.WIDGET_ORDER, + } + db.enroll(login, defaults, github_id=gh_id, github_avatar_url=avatar_url) + _kickoff_prefetch_async(login) + + return redirect(nxt) + + @app.route("/api/health", methods=["GET"]) def health(): return jsonify({"status": "ok", "service": "generator"}) diff --git a/generator/tests/test_auth.py b/generator/tests/test_auth.py index d9474df..e221e28 100644 --- a/generator/tests/test_auth.py +++ b/generator/tests/test_auth.py @@ -135,3 +135,39 @@ def test_login_rejects_external_next(api_client): assert r.status_code in (302, 303) with api_client.session_transaction() as s: assert s.get("oauth_next") == "/" + + +def test_callback_state_mismatch_400(api_client): + with api_client.session_transaction() as s: + s["oauth_state"] = "correct" + r = api_client.get("/api/auth/github/callback?code=abc&state=wrong") + assert r.status_code == 400 + + +def test_callback_happy_path_sets_session(api_client, monkeypatch): + """End-to-end callback: stub token exchange + /user, verify session state.""" + from src import auth as authmod, db as dbmod + # Pre-populate session with matching state + with api_client.session_transaction() as s: + s["oauth_state"] = "good-state" + s["oauth_next"] = "/" + + # Stub authlib's token exchange + def fake_authorize_access_token(**_kwargs): + return {"access_token": "ghs_abc", "token_type": "bearer"} + monkeypatch.setattr(authmod.github_client(), "authorize_access_token", fake_authorize_access_token) + + # Stub the GitHub /user call + import src.api as apimod + monkeypatch.setattr(apimod, "_gh_api_get", + lambda token, path: {"id": 123, "login": "Alice", "avatar_url": "https://x/a.png"}) + + r = api_client.get("/api/auth/github/callback?code=abc&state=good-state") + assert r.status_code in (302, 303) + assert r.headers["Location"].endswith("/") + with api_client.session_transaction() as s: + assert s["gh_login"] == "alice" + assert s["gh_id"] == 123 + assert s["gh_avatar_url"] == "https://x/a.png" + # Row should now exist with github profile populated. + assert dbmod.get_settings("alice") is not None From 4ee71e0b8633ca4df327a2dc0cbcdc3eb1680d49 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:59:46 -0400 Subject: [PATCH 12/22] feat(api): PATCH /settings uses OAuth session + same-origin --- generator/src/api.py | 4 +-- generator/tests/test_api.py | 54 +++++++++++++++++++++++++++++-------- 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/generator/src/api.py b/generator/src/api.py index 2a2710c..f8d1657 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -575,7 +575,6 @@ def enroll_endpoint(): @app.route("/api//settings", methods=["GET"]) @rate_limited("read") -@require_edit_token def get_settings(username: str): s = db.get_settings(username) if s is None: @@ -591,7 +590,8 @@ def get_settings(username: str): @app.route("/api//settings", methods=["PATCH"]) @rate_limited("mutate") -@require_edit_token +@auth.require_same_origin +@auth.require_github_owner def patch_settings(username: str): current = db.get_settings(username) if current is None: diff --git a/generator/tests/test_api.py b/generator/tests/test_api.py index f75274d..c364133 100644 --- a/generator/tests/test_api.py +++ b/generator/tests/test_api.py @@ -2,6 +2,7 @@ import os, tempfile, pytest from unittest.mock import patch from src import db as dbmod from src import api as apimod +from src import config as cfg @pytest.fixture @@ -13,8 +14,11 @@ def client(monkeypatch): monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) dbmod.init_dbs() + # Configure OAuth fixture with allowed origins and insecure cookies for testing. + monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",)) app = apimod.app app.config["TESTING"] = True + app.config["SESSION_COOKIE_SECURE"] = False with app.test_client() as c: yield c @@ -54,34 +58,62 @@ def test_enrolled_user_with_built_widget_returns_ready(client): def test_settings_patch_enqueues_rebuild(client): - token = dbmod.enroll("alice", {"theme": "dark"})["edit_token"] + dbmod.enroll("alice", {"theme": "dark"}) + with client.session_transaction() as s: + s["gh_login"] = "alice" r = client.patch( "/api/alice/settings", json={"theme": "light"}, - headers={"Authorization": f"Bearer {token}"}, + headers={"Origin": "https://gh-stats.com"}, ) assert r.status_code == 200 assert dbmod.get_settings("alice")["settings"]["theme"] == "light" -def test_settings_patch_without_token_is_unauthorized(client): +def test_settings_patch_without_origin_is_unauthorized(client): dbmod.enroll("alice", {"theme": "dark"}) + with client.session_transaction() as s: + s["gh_login"] = "alice" r = client.patch("/api/alice/settings", json={"theme": "light"}) - assert r.status_code == 401 - # Settings must not be mutated when the token check fails. + assert r.status_code == 403 + # Settings must not be mutated when the origin check fails. assert dbmod.get_settings("alice")["settings"]["theme"] == "dark" -def test_settings_patch_with_wrong_token_is_unauthorized(client): +def test_patch_settings_without_session_is_401(client): dbmod.enroll("alice", {"theme": "dark"}) - r = client.patch( - "/api/alice/settings", - json={"theme": "light"}, - headers={"Authorization": "Bearer not-the-real-token"}, - ) + r = client.patch("/api/alice/settings", json={"theme": "light"}, + headers={"Origin": "https://gh-stats.com"}) assert r.status_code == 401 +def test_patch_settings_wrong_login_is_403(client): + dbmod.enroll("alice", {"theme": "dark"}) + with client.session_transaction() as s: + s["gh_login"] = "bob" + r = client.patch("/api/alice/settings", json={"theme": "light"}, + headers={"Origin": "https://gh-stats.com"}) + assert r.status_code == 403 + + +def test_patch_settings_matching_login_succeeds(client): + dbmod.enroll("alice", {"theme": "dark"}) + with client.session_transaction() as s: + s["gh_login"] = "alice" + r = client.patch("/api/alice/settings", json={"theme": "light"}, + headers={"Origin": "https://gh-stats.com"}) + assert r.status_code == 200 + + +def test_patch_settings_bad_origin_is_403(client): + dbmod.enroll("alice", {"theme": "dark"}) + with client.session_transaction() as s: + s["gh_login"] = "alice" + r = client.patch("/api/alice/settings", json={"theme": "light"}, + headers={"Origin": "https://evil.example"}) + assert r.status_code == 403 + + def test_refresh_is_one_shot(client): token = dbmod.enroll("alice", {"theme": "dark"})["edit_token"] headers = {"Authorization": f"Bearer {token}"} From 91f6328efdceead9b1eb55096617cc4855519a05 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 19:03:16 -0400 Subject: [PATCH 13/22] feat(api): /generate and /refresh use OAuth session; remove edit_token helpers --- generator/src/api.py | 38 ++++-------------------------- generator/src/db.py | 11 --------- generator/tests/test_api.py | 46 +++++++++++++++++++++++++++++-------- 3 files changed, 41 insertions(+), 54 deletions(-) diff --git a/generator/src/api.py b/generator/src/api.py index f8d1657..ccf619c 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -123,30 +123,6 @@ def rate_limited(bucket: str): return deco -def _extract_bearer() -> str: - """Read the caller-presented edit token. Accepts either - `Authorization: Bearer ` or `X-Edit-Token: `.""" - hdr = request.headers.get("Authorization", "") - if hdr.startswith("Bearer "): - return hdr[len("Bearer "):].strip() - return request.headers.get("X-Edit-Token", "").strip() - - -def require_edit_token(fn): - """Enforce per-user bearer token on mutating endpoints. - - The token is issued once at enrollment (see db.enroll) and hashed at rest. - Without it, anyone could overwrite any registrant's settings — these - endpoints used to live behind a no-op decorator.""" - @wraps(fn) - def wrapper(username: str, *args, **kwargs): - if not is_valid_username(username): - return jsonify({"error": "invalid_username"}), 400 - presented = _extract_bearer() - if not presented or not db.verify_edit_token(username, presented): - return jsonify({"error": "unauthorized"}), 401 - return fn(username, *args, **kwargs) - return wrapper _STATIC_DIR = os.path.join(os.path.dirname(__file__), "static") @@ -311,12 +287,6 @@ def sanitize_settings(body: dict) -> dict: return out -def require_auth(fn): - """Deprecated passthrough retained for back-compat. New code should use - require_edit_token above, which actually authenticates.""" - return fn - - @app.route("/", defaults={"path": ""}) @app.route("/") def spa(path: str): @@ -609,12 +579,13 @@ def patch_settings(username: str): @app.route("/api//generate", methods=["POST"]) @rate_limited("mutate") +@auth.require_same_origin +@auth.require_github_owner def generate(username: str): """Render the composite SVG from the cached fetcher payload + current settings, persist it to widgets.db, and return status. Called by the Generate button; safe to call repeatedly (each call re-renders with - the latest settings). Unauth'd — anyone can trigger a render of a - previously-enrolled user's public widget. + the latest settings). Requires OAuth session with matching login. Capacity: * Per-IP rate limit (mutate bucket) caps how fast any one caller can @@ -658,7 +629,8 @@ def generate(username: str): @app.route("/api//refresh", methods=["POST"]) @rate_limited("mutate") -@require_edit_token +@auth.require_same_origin +@auth.require_github_owner def refresh(username: str): s = db.get_settings(username) if s is None: diff --git a/generator/src/db.py b/generator/src/db.py index b424427..5150b34 100644 --- a/generator/src/db.py +++ b/generator/src/db.py @@ -126,17 +126,6 @@ def init_dbs() -> None: c.commit() -def verify_edit_token(username: str, presented: str) -> bool: - """Constant-time check of the caller's edit token against the stored hash. - - DEPRECATED: This function is dead code as of Task 5 (edit tokens are no longer - hashed during enrollment). It remains here temporarily while api.py's - require_edit_token decorator is still being used. Task 12 will remove both - this function and the decorator consumer in api.py. - """ - raise NotImplementedError("verify_edit_token is deprecated; will be removed in Task 12") - - def settings_hash(settings: dict) -> str: canonical = json.dumps(settings, sort_keys=True, separators=(",", ":")) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() diff --git a/generator/tests/test_api.py b/generator/tests/test_api.py index c364133..aa1d51c 100644 --- a/generator/tests/test_api.py +++ b/generator/tests/test_api.py @@ -115,18 +115,20 @@ def test_patch_settings_bad_origin_is_403(client): def test_refresh_is_one_shot(client): - token = dbmod.enroll("alice", {"theme": "dark"})["edit_token"] - headers = {"Authorization": f"Bearer {token}"} + dbmod.enroll("alice", {"theme": "dark"}) + with client.session_transaction() as s: + s["gh_login"] = "alice" with patch("src.api.fetcher_client.force_fetch", return_value={"changed": True, "payload_hash": "x", "stored": True}): - r1 = client.post("/api/alice/refresh", headers=headers) + r1 = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"}) assert r1.status_code == 200 - r2 = client.post("/api/alice/refresh", headers=headers) + r2 = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"}) assert r2.status_code == 409 def test_refresh_without_token_is_unauthorized(client): + """Old test name; now tests without session but with proper Origin.""" dbmod.enroll("alice", {"theme": "dark"}) - r = client.post("/api/alice/refresh") + r = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"}) assert r.status_code == 401 @@ -142,6 +144,8 @@ def test_generate_endpoint_renders_and_stores_svg(client): """POST /api//generate invokes the on-demand render path and caches the composite SVG for subsequent README embeds.""" dbmod.enroll("alice", {"theme": "dark"}) + with client.session_transaction() as s: + s["gh_login"] = "alice" with patch("src.worker.render_widgets_now", return_value={"composite": "r", "grade": "g"}): # Simulate the render path also updating current_widget so the @@ -151,7 +155,7 @@ def test_generate_endpoint_renders_and_stores_svg(client): dbmod.point_current_widget(username, "h1") return {"composite": "r"} with patch("src.worker.render_widgets_now", side_effect=fake_render): - r = client.post("/api/alice/generate") + r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"}) assert r.status_code == 200 body = r.get_json() assert body["status"] == "ready" @@ -162,7 +166,10 @@ def test_generate_endpoint_renders_and_stores_svg(client): def test_generate_endpoint_rejects_unenrolled(client): - r = client.post("/api/bob/generate") + """With OAuth, unenrolled means having a session but no profile.""" + with client.session_transaction() as s: + s["gh_login"] = "bob" + r = client.post("/api/bob/generate", headers={"Origin": "https://gh-stats.com"}) assert r.status_code == 404 @@ -175,9 +182,8 @@ def test_data_endpoint_unknown_user_enrolls_and_returns_building(client): assert r.status_code == 202 body = r.get_json() assert body["status"] == "building" - # Auto-enroll path surfaces the edit token so the browser can mutate - # the freshly-created profile without a separate claim flow. - assert "edit_token" in body and body["edit_token"] + # Auto-enroll path no longer surfaces edit token; auth is now session-based. + assert "edit_token" not in body assert dbmod.get_settings("alice") is not None # auto-enrolled @@ -224,3 +230,23 @@ def test_data_endpoint_rate_limited_before_enroll(client, monkeypatch): r = client.get("/api/newbie/data") assert r.status_code == 429 assert r.get_json()["status"] == "rate_limited" + + +def test_generate_without_session_is_401(client): + dbmod.enroll("alice", {"theme": "dark"}) + r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"}) + assert r.status_code == 401 + + +def test_generate_wrong_login_is_403(client): + dbmod.enroll("alice", {"theme": "dark"}) + with client.session_transaction() as s: + s["gh_login"] = "bob" + r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"}) + assert r.status_code == 403 + + +def test_refresh_without_session_is_401(client): + dbmod.enroll("alice", {"theme": "dark"}) + r = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"}) + assert r.status_code == 401 From 0cd7bf339de4a6d1a8d81d16303559790e924a19 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 19:06:38 -0400 Subject: [PATCH 14/22] feat(api): remove public /enroll endpoint and auto-enroll on /data --- generator/src/api.py | 56 ++----------------- .../tests/integration/test_end_to_end.py | 18 ++++-- generator/tests/test_api.py | 28 ++++------ 3 files changed, 27 insertions(+), 75 deletions(-) diff --git a/generator/src/api.py b/generator/src/api.py index ccf619c..34c0e03 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -80,7 +80,6 @@ _RATE_LIMITS = { # (endpoint_key): (max_hits, window_seconds). Defaults set in config.py # lean toward the mini PC — tighten further via env without redeploying. "mutate": (config.RATE_LIMIT_MUTATE_MAX, config.RATE_LIMIT_MUTATE_WINDOW), - "enroll": (config.RATE_LIMIT_ENROLL_MAX, config.RATE_LIMIT_ENROLL_WINDOW), "read": (config.RATE_LIMIT_READ_MAX, config.RATE_LIMIT_READ_WINDOW), } _rate_lock = Lock() @@ -432,37 +431,13 @@ def get_user_data(username: str): """Precomputed widget data for client-side SVG rendering. Pure DB lookup — never touches the fetcher or runs compute on the hot - path. On miss: auto-enroll (queues an async build) and return - `{status: "building"}` with HTTP 202 so the client can show demo data - and poll until ready. + path. Enrollment is now OAuth-driven only. """ if not is_valid_username(username): return jsonify({"error": "invalid_username"}), 400 settings_row = db.get_settings(username) if settings_row is None: - if not _rate_limit("enroll"): - return jsonify({"status": "rate_limited"}), 429 - if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP: - return jsonify({"status": "rate_limited"}), 429 - # Queue-depth backpressure: if the worker is already behind, stop - # accepting new enrollments until it catches up. Prevents a burst - # of auto-enrolls from filling the jobs table faster than a mini - # PC can drain it. - if db.pending_job_count() >= config.PENDING_JOB_QUEUE_CAP: - return jsonify({"status": "rate_limited"}), 429 - defaults = { - "theme": "dark", - "enabled": config.ENABLED_WIDGETS, - "widget_order": config.WIDGET_ORDER, - } - result = db.enroll(username, defaults) - _kickoff_prefetch_async(username) - # Token is surfaced on this auto-enroll path so the browser UI can - # edit the freshly-created profile without a separate claim step. - resp = {"status": "building"} - if result.get("edit_token"): - resp["edit_token"] = result["edit_token"] - return jsonify(resp), 202 + return jsonify({"status": "not_found"}), 404 db.touch_last_requested(username) @@ -480,9 +455,8 @@ def _serve(username: str, widget_name: str) -> Response: """Serves a cached SVG for README embeds. SVGs are only produced by POST /api//generate. Before that the - endpoint returns a "building" placeholder; enrollment is frontend- - driven (via /api//data or /api/enroll) so this path never auto- - enrolls on its own. + endpoint returns a "building" placeholder; enrollment is now OAuth-driven + so this path never auto-enrolls on its own. """ settings_row = db.get_settings(username) if settings_row is None: @@ -521,28 +495,6 @@ def _placeholder_response(variant: str, username: str, theme: str = "dark") -> R "X-Content-Type-Options": "nosniff"}) -@app.route("/api/enroll", methods=["POST"]) -@rate_limited("enroll") -def enroll_endpoint(): - body = request.get_json(silent=True) or {} - username = body.get("username") - if not is_valid_username(username): - return jsonify({"error": "invalid_username"}), 400 - if db.get_settings(username) is not None: - return jsonify({"error": "already_enrolled"}), 409 - if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP: - return jsonify({"error": "rate_limited"}), 429 - if db.pending_job_count() >= config.PENDING_JOB_QUEUE_CAP: - return jsonify({"error": "rate_limited"}), 429 - defaults = {"theme": "dark", "enabled": config.ENABLED_WIDGETS, "widget_order": config.WIDGET_ORDER} - result = db.enroll(username, defaults) - _kickoff_prefetch_async(username) - body = {"enrolled": True, "job_id": result["job_id"]} - if result.get("edit_token"): - body["edit_token"] = result["edit_token"] - return jsonify(body) - - @app.route("/api//settings", methods=["GET"]) @rate_limited("read") def get_settings(username: str): diff --git a/generator/tests/integration/test_end_to_end.py b/generator/tests/integration/test_end_to_end.py index be4c8fc..bd8ece4 100644 --- a/generator/tests/integration/test_end_to_end.py +++ b/generator/tests/integration/test_end_to_end.py @@ -19,9 +19,10 @@ def env(monkeypatch): @responses.activate def test_full_flow_data_then_generate_then_serve(env): """End-to-end of the new two-phase pipeline: - 1. /data enrolls + kicks off prefetch (worker populates widget_data) - 2. /generate renders SVG from the cached payload + settings - 3. /api/ serves the stored SVG to README consumers + 1. OAuth callback enrolls user + kicks off prefetch (worker populates widget_data) + 2. /data endpoint returns widget data + 3. /generate renders SVG from the cached payload + settings + 4. /api/ serves the stored SVG to README consumers """ responses.add( responses.GET, "http://fetcher-mock/data/alice", @@ -32,7 +33,10 @@ def test_full_flow_data_then_generate_then_serve(env): ) client = apimod.app.test_client() - # Phase 1: prefetch via /data (enrolls + kicks off background thread). + # Phase 1: OAuth callback enrolls user (simulated via db.enroll). + dbmod.enroll("alice", {"theme": "dark"}) + + # Widget data should be building right after enrollment. r_data = client.get("/api/alice/data") assert r_data.status_code == 202 @@ -51,8 +55,10 @@ def test_full_flow_data_then_generate_then_serve(env): time.sleep(0.05) assert r.status_code == 200 and r.get_json()["status"] == "ready" - # Phase 2: Generate button → render SVG. - r_gen = client.post("/api/alice/generate") + # Phase 2: Generate button → render SVG (with session). + with client.session_transaction() as s: + s["gh_login"] = "alice" + r_gen = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"}) assert r_gen.status_code == 200 assert r_gen.get_json()["status"] == "ready" diff --git a/generator/tests/test_api.py b/generator/tests/test_api.py index aa1d51c..d31618a 100644 --- a/generator/tests/test_api.py +++ b/generator/tests/test_api.py @@ -177,16 +177,6 @@ def test_generate_endpoint_rejects_unenrolled(client): # Pure DB lookup — fetcher is never touched on the hot path. -def test_data_endpoint_unknown_user_enrolls_and_returns_building(client): - r = client.get("/api/alice/data") - assert r.status_code == 202 - body = r.get_json() - assert body["status"] == "building" - # Auto-enroll path no longer surfaces edit token; auth is now session-based. - assert "edit_token" not in body - assert dbmod.get_settings("alice") is not None # auto-enrolled - - def test_data_endpoint_enrolled_but_unbuilt_returns_building(client): dbmod.enroll("alice", {"theme": "dark"}) r = client.get("/api/alice/data") @@ -225,13 +215,6 @@ def test_data_endpoint_returns_not_found_for_unknown_github_user(client): assert r.get_json()["status"] == "not_found" -def test_data_endpoint_rate_limited_before_enroll(client, monkeypatch): - monkeypatch.setattr(apimod.config, "ENROLLMENT_DAILY_CAP", 0) - r = client.get("/api/newbie/data") - assert r.status_code == 429 - assert r.get_json()["status"] == "rate_limited" - - def test_generate_without_session_is_401(client): dbmod.enroll("alice", {"theme": "dark"}) r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"}) @@ -250,3 +233,14 @@ def test_refresh_without_session_is_401(client): dbmod.enroll("alice", {"theme": "dark"}) r = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"}) assert r.status_code == 401 + + +def test_data_unknown_user_returns_404(client): + r = client.get("/api/testuser/data") + assert r.status_code == 404 + + +def test_enroll_endpoint_is_gone(client): + r = client.post("/api/enroll", json={"username": "alice"}, + headers={"Origin": "https://gh-stats.com"}) + assert r.status_code == 405 From 8b7f999adc689ac927295e8d65d2cdf44864f3a0 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 19:09:04 -0400 Subject: [PATCH 15/22] feat(api): per-login mutate rate limit layered on per-IP --- generator/src/api.py | 28 ++++++++++++++++++++++++++++ generator/tests/test_api.py | 22 ++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/generator/src/api.py b/generator/src/api.py index 34c0e03..3837c85 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -84,6 +84,7 @@ _RATE_LIMITS = { } _rate_lock = Lock() _rate_hits: dict[tuple[str, str], deque] = defaultdict(deque) +_rate_hits_per_login: dict[tuple[str, str], deque] = defaultdict(deque) def _client_ip() -> str: @@ -111,12 +112,39 @@ def _rate_limit(bucket: str) -> bool: return True +def _rate_limit_per_login(bucket: str, login: str) -> bool: + """Per-login rate limit layered on top of per-IP limit. + + Returns True if allowed; False if the login has exceeded the limit. + If no login (unauthenticated), returns True (per-IP already covers it). + """ + if not login: + return True # per-IP already covers the unauth path + if bucket == "mutate": + limit, window = config.RATE_LIMIT_MUTATE_PER_LOGIN_MAX, config.RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW + else: + return True + now = time.time() + cutoff = now - window + key = (bucket, login) + with _rate_lock: + q = _rate_hits_per_login[key] + while q and q[0] < cutoff: + q.popleft() + if len(q) >= limit: + return False + q.append(now) + return True + + def rate_limited(bucket: str): def deco(fn): @wraps(fn) def wrapper(*args, **kwargs): if not _rate_limit(bucket): return jsonify({"error": "rate_limited"}), 429 + if not _rate_limit_per_login(bucket, auth.current_login() or ""): + return jsonify({"error": "rate_limited"}), 429 return fn(*args, **kwargs) return wrapper return deco diff --git a/generator/tests/test_api.py b/generator/tests/test_api.py index d31618a..94da851 100644 --- a/generator/tests/test_api.py +++ b/generator/tests/test_api.py @@ -21,6 +21,9 @@ def client(monkeypatch): app.config["SESSION_COOKIE_SECURE"] = False with app.test_client() as c: yield c + # Clear rate limit state after each test to prevent pollution. + apimod._rate_hits.clear() + apimod._rate_hits_per_login.clear() def test_health(client): @@ -244,3 +247,22 @@ def test_enroll_endpoint_is_gone(client): r = client.post("/api/enroll", json={"username": "alice"}, headers={"Origin": "https://gh-stats.com"}) assert r.status_code == 405 + + +def test_per_login_mutate_rate_limit(client, monkeypatch): + """Per-login rate limit on mutate routes allows up to MAX requests, + then rejects with 429.""" + monkeypatch.setattr(cfg, "RATE_LIMIT_MUTATE_PER_LOGIN_MAX", 2) + monkeypatch.setattr(cfg, "RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW", 60) + dbmod.enroll("alice", {"theme": "dark"}) + with client.session_transaction() as s: + s["gh_login"] = "alice" + h = {"Origin": "https://gh-stats.com"} + # First two requests should succeed. + r1 = client.patch("/api/alice/settings", json={}, headers=h) + assert r1.status_code == 200 + r2 = client.patch("/api/alice/settings", json={}, headers=h) + assert r2.status_code == 200 + # Third request should be rate-limited. + r3 = client.patch("/api/alice/settings", json={}, headers=h) + assert r3.status_code == 429 From b2baded94a548cf5c9fb6fc674ccb7ce7c3a6f3b Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 19:10:05 -0400 Subject: [PATCH 16/22] feat(frontend): add lib/auth.ts with fetchMe, signInUrl, signOut --- generator/frontend/src/lib/auth.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 generator/frontend/src/lib/auth.ts diff --git a/generator/frontend/src/lib/auth.ts b/generator/frontend/src/lib/auth.ts new file mode 100644 index 0000000..a9a8802 --- /dev/null +++ b/generator/frontend/src/lib/auth.ts @@ -0,0 +1,20 @@ +export type Me = { login: string | null; avatar_url?: string } + +export async function fetchMe(): Promise { + const r = await fetch('/api/auth/me', { credentials: 'include' }) + if (!r.ok) return { login: null } + return r.json() as Promise +} + +export function signInUrl(next?: string): string { + const n = next ?? (window.location.pathname + window.location.search) + return `/api/auth/github/login?next=${encodeURIComponent(n)}` +} + +export async function signOut(): Promise { + await fetch('/api/auth/logout', { + method: 'POST', + credentials: 'include', + headers: { 'Content-Type': 'application/json' }, + }) +} From 8ccc0af1cf6534b05ec5116418eb81219f8d20a6 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 19:12:36 -0400 Subject: [PATCH 17/22] feat(frontend): App fetches /me, removes editToken plumbing Co-Authored-By: Claude Sonnet 4.6 --- generator/frontend/src/App.tsx | 18 ++++++++---------- .../frontend/src/screens/WorkshopScreen.tsx | 3 +++ 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/generator/frontend/src/App.tsx b/generator/frontend/src/App.tsx index 6cc64fe..1a4fe9a 100644 --- a/generator/frontend/src/App.tsx +++ b/generator/frontend/src/App.tsx @@ -5,7 +5,7 @@ import { WorkshopScreen } from './screens/WorkshopScreen' import { ResultScreen } from './screens/ResultScreen' import type { WidgetData } from './lib/renderWidgets' import { DEMO_WIDGET_DATA } from './lib/demoData' -import { authHeaders, saveEditToken } from './lib/editToken' +import { fetchMe, type Me } from './lib/auth' export type Achievement = { title: string @@ -49,6 +49,7 @@ const POLL_INTERVAL_MS = 2000 const POLL_TIMEOUT_MS = 120_000 export default function App() { + const [me, setMe] = useState({ login: null }) const [step, setStep] = useState('search') const [username, setUsername] = useState('') const [settings, setSettings] = useState({ ...DEFAULT_SETTINGS }) @@ -72,6 +73,7 @@ export default function App() { }, []) useEffect(() => stopPolling, [stopPolling]) + useEffect(() => { fetchMe().then(setMe) }, []) const startFetch = useCallback((user: string) => { stopPolling() @@ -88,12 +90,8 @@ export default function App() { const r = await fetch(`/api/${encodeURIComponent(user)}/data`) if (aborted.current) return const body = await r.json().catch( - () => ({} as { status?: string; data?: WidgetData; edit_token?: string }) + () => ({} as { status?: string; data?: WidgetData }) ) - // The 202 auto-enroll response surfaces an edit_token exactly once - // per fresh username. Persist it so PATCH /settings and POST - // /refresh can authenticate this browser as the profile owner. - if (body.edit_token) saveEditToken(user, body.edit_token) const status = body.status if (r.status === 200 && status === 'ready' && body.data) { @@ -156,10 +154,8 @@ export default function App() { } const patchRes = await fetch(`/api/${encodeURIComponent(username)}/settings`, { method: 'PATCH', - headers: { - 'Content-Type': 'application/json', - ...authHeaders(username), - }, + credentials: 'include', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(backendSettings), }) if (!patchRes.ok && patchRes.status !== 404) { @@ -217,6 +213,8 @@ export default function App() { fetchDone={fetchDone} fetchError={fetchError} widgetData={widgetData} + me={me} + onAuthChange={setMe} /> )} {step === 'result' && ( diff --git a/generator/frontend/src/screens/WorkshopScreen.tsx b/generator/frontend/src/screens/WorkshopScreen.tsx index f3d77dc..916a41f 100644 --- a/generator/frontend/src/screens/WorkshopScreen.tsx +++ b/generator/frontend/src/screens/WorkshopScreen.tsx @@ -2,6 +2,7 @@ import { useState, useMemo, type ReactNode } from 'react' import DOMPurify from 'dompurify' import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App' import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets' +import type { Me } from '../lib/auth' // Defense-in-depth: the client-rendered preview assembles SVG from // GitHub-sourced strings (collaborator logins, repo names) and user-typed @@ -214,6 +215,8 @@ type Props = { fetchDone: boolean fetchError: string | null widgetData: WidgetData | null + me: Me + onAuthChange?: (m: Me) => void } export function WorkshopScreen({ From cd927e686fd6ead8d44f7a9cbf67a2e51164a5cd Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 19:14:06 -0400 Subject: [PATCH 18/22] =?UTF-8?q?feat(frontend):=20AuthButton=20=E2=80=94?= =?UTF-8?q?=20GitHub=20sign-in=20/=20avatar=20chip?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- generator/frontend/src/App.tsx | 4 ++++ .../frontend/src/components/AuthButton.tsx | 21 +++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 generator/frontend/src/components/AuthButton.tsx diff --git a/generator/frontend/src/App.tsx b/generator/frontend/src/App.tsx index 1a4fe9a..c2b40d3 100644 --- a/generator/frontend/src/App.tsx +++ b/generator/frontend/src/App.tsx @@ -3,6 +3,7 @@ import './index.css' import { SearchScreen } from './screens/SearchScreen' import { WorkshopScreen } from './screens/WorkshopScreen' import { ResultScreen } from './screens/ResultScreen' +import { AuthButton } from './components/AuthButton' import type { WidgetData } from './lib/renderWidgets' import { DEMO_WIDGET_DATA } from './lib/demoData' import { fetchMe, type Me } from './lib/auth' @@ -200,6 +201,9 @@ export default function App() { return (
+
+ +
{step === 'search' && ( )} diff --git a/generator/frontend/src/components/AuthButton.tsx b/generator/frontend/src/components/AuthButton.tsx new file mode 100644 index 0000000..be2fa91 --- /dev/null +++ b/generator/frontend/src/components/AuthButton.tsx @@ -0,0 +1,21 @@ +import type { Me } from '../lib/auth' +import { signInUrl, signOut } from '../lib/auth' + +export function AuthButton({ me, onChange }: { me: Me; onChange: (m: Me) => void }) { + if (!me.login) { + return ( + + Sign in with GitHub + + ) + } + return ( +
+ {me.avatar_url && } + {me.login} + +
+ ) +} From ccdd8231cea3b0cc02db3b9fe8512ad074a499f2 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 19:16:59 -0400 Subject: [PATCH 19/22] feat(frontend): gate WorkshopScreen edit UI on OAuth login match --- .../frontend/src/screens/WorkshopScreen.tsx | 462 +++++++++--------- 1 file changed, 239 insertions(+), 223 deletions(-) diff --git a/generator/frontend/src/screens/WorkshopScreen.tsx b/generator/frontend/src/screens/WorkshopScreen.tsx index 916a41f..b754a4b 100644 --- a/generator/frontend/src/screens/WorkshopScreen.tsx +++ b/generator/frontend/src/screens/WorkshopScreen.tsx @@ -2,6 +2,7 @@ import { useState, useMemo, type ReactNode } from 'react' import DOMPurify from 'dompurify' import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App' import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets' +import { signInUrl } from '../lib/auth' import type { Me } from '../lib/auth' // Defense-in-depth: the client-rendered preview assembles SVG from @@ -228,7 +229,9 @@ export function WorkshopScreen({ fetchDone, fetchError, widgetData, + me, }: Props) { + const canEdit = !!me.login && me.login.toLowerCase() === username.toLowerCase() const [expandedWidget, setExpandedWidget] = useState(null) const updateSetting = (key: K, val: WidgetSettings[K]) => { @@ -315,233 +318,246 @@ export function WorkshopScreen({
)} - {/* Theme */} -
-
Theme
-
- {THEMES.map(t => ( -
-
- {THEMES.find(t => t.id === settings.theme)?.label} -
-
- - {/* Widgets with inline advanced settings */} -
-
Widgets
-
- {ALL_WIDGETS.map(w => { - const enabled = settings.widgets.includes(w.id) - const hasAdvanced = ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'].includes(w.id) - const isExpanded = expandedWidget === w.id && enabled - - return ( -
-
- - {hasAdvanced && enabled && ( - - )} -
- - {isExpanded && ( -
- {w.id === 'grade' && ( -
- Max tags - updateWidgetSetting('grade', 'max_tags', v)} - /> -
- )} - - {w.id === 'impact' && ( -
- Line color - updateWidgetSetting('impact', 'line_color', v)} - /> -
- )} - - {w.id === 'collaborators' && ( -
-
- Max shown - updateWidgetSetting('collaborators', 'max_count', v)} - /> -
-
- Bar color - updateWidgetSetting('collaborators', 'bar_color', v)} - /> -
-
- )} - - {w.id === 'focus' && ( -
- Max categories - updateWidgetSetting('focus', 'max_categories', v)} - /> -
- )} - - {w.id === 'languages' && ( -
-
- Max languages - updateWidgetSetting('languages', 'max_languages', v)} - /> -
-
- )} - - {w.id === 'achievements' && ( -
- Max shown - updateWidgetSetting('achievements', 'max_items', v)} - /> -
- )} -
- )} -
- ) - })} -
-
- - {/* Achievements editor */} - {settings.widgets.includes('achievements') && ( -
-
Achievements
-
- {settings.achievements.map((ach, idx) => ( -
-
- {ICONS.map(ic => { - const selected = ach.icon === ic.id - return ( - - ) - })} -
- -
- updateAchievement(idx, 'title', e.target.value)} - placeholder="Title (e.g. Hackathon Winner)" - className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5" - /> - updateAchievement(idx, 'subtitle', e.target.value)} - placeholder="Subtitle (e.g. 1st Place · AI Track)" - className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5" - /> - updateAchievement(idx, 'event_date', e.target.value)} - placeholder="Date (e.g. 2025-01)" - className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300" - /> -
- ))} - -
+ {!canEdit && ( +
+ {me.login + ? `Signed in as ${me.login}. You can only edit your own widget.` + : Sign in with GitHub to edit your widget}
)} - {/* Spacer */} -
+ {/* Theme, Widgets, Achievements editor, Generate — owner-only */} + {canEdit && ( + <> + {/* Theme */} +
+
Theme
+
+ {THEMES.map(t => ( +
+
+ {THEMES.find(t => t.id === settings.theme)?.label} +
+
- {/* Generate button */} - + {/* Widgets with inline advanced settings */} +
+
Widgets
+
+ {ALL_WIDGETS.map(w => { + const enabled = settings.widgets.includes(w.id) + const hasAdvanced = ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'].includes(w.id) + const isExpanded = expandedWidget === w.id && enabled + + return ( +
+
+ + {hasAdvanced && enabled && ( + + )} +
+ + {isExpanded && ( +
+ {w.id === 'grade' && ( +
+ Max tags + updateWidgetSetting('grade', 'max_tags', v)} + /> +
+ )} + + {w.id === 'impact' && ( +
+ Line color + updateWidgetSetting('impact', 'line_color', v)} + /> +
+ )} + + {w.id === 'collaborators' && ( +
+
+ Max shown + updateWidgetSetting('collaborators', 'max_count', v)} + /> +
+
+ Bar color + updateWidgetSetting('collaborators', 'bar_color', v)} + /> +
+
+ )} + + {w.id === 'focus' && ( +
+ Max categories + updateWidgetSetting('focus', 'max_categories', v)} + /> +
+ )} + + {w.id === 'languages' && ( +
+
+ Max languages + updateWidgetSetting('languages', 'max_languages', v)} + /> +
+
+ )} + + {w.id === 'achievements' && ( +
+ Max shown + updateWidgetSetting('achievements', 'max_items', v)} + /> +
+ )} +
+ )} +
+ ) + })} +
+
+ + {/* Achievements editor */} + {settings.widgets.includes('achievements') && ( +
+
Achievements
+
+ {settings.achievements.map((ach, idx) => ( +
+
+ {ICONS.map(ic => { + const selected = ach.icon === ic.id + return ( + + ) + })} +
+ +
+ updateAchievement(idx, 'title', e.target.value)} + placeholder="Title (e.g. Hackathon Winner)" + className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5" + /> + updateAchievement(idx, 'subtitle', e.target.value)} + placeholder="Subtitle (e.g. 1st Place · AI Track)" + className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5" + /> + updateAchievement(idx, 'event_date', e.target.value)} + placeholder="Date (e.g. 2025-01)" + className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300" + /> +
+ ))} + +
+
+ )} + + {/* Spacer */} +
+ + {/* Generate button */} + + + )}
{/* Right preview area */} From be8823c4cf53ba5f9f3b88e896ccd9b3a48326b6 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 19:18:32 -0400 Subject: [PATCH 20/22] chore(frontend): delete lib/editToken.ts (replaced by OAuth) Co-Authored-By: Claude Opus 4.7 --- generator/frontend/src/lib/editToken.ts | 36 ------------------------- 1 file changed, 36 deletions(-) delete mode 100644 generator/frontend/src/lib/editToken.ts diff --git a/generator/frontend/src/lib/editToken.ts b/generator/frontend/src/lib/editToken.ts deleted file mode 100644 index 2ec73f7..0000000 --- a/generator/frontend/src/lib/editToken.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Per-username edit token issued by the backend at enrollment. Presented -// as `Authorization: Bearer` on mutating endpoints (PATCH settings, -// POST refresh). Stored in localStorage so a reload keeps the user in -// control of their own profile. -// -// Without this token the backend rejects mutations with HTTP 401. Token is -// only surfaced on the FIRST enroll for a given username — re-hitting the -// enroll path for an existing user returns no token, so we never blow away -// a previously-saved token. - -const STORAGE_PREFIX = 'grs:edit_token:' - -const keyFor = (username: string) => STORAGE_PREFIX + username.toLowerCase() - -export function getEditToken(username: string): string | null { - if (!username) return null - try { - return window.localStorage.getItem(keyFor(username)) - } catch { - return null - } -} - -export function saveEditToken(username: string, token: string | null | undefined): void { - if (!username || !token) return - try { - window.localStorage.setItem(keyFor(username), token) - } catch { - // localStorage can throw in private mode — fall through silently. - } -} - -export function authHeaders(username: string): Record { - const t = getEditToken(username) - return t ? { Authorization: `Bearer ${t}` } : {} -} From 9e837519ccdb1c7907231c6aef342e7f2983ea35 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 20:02:52 -0400 Subject: [PATCH 21/22] feat(deploy): wire OAuth secrets; rename env vars off GITHUB_ prefix GitHub Actions rejects secret names starting with GITHUB_. Rename the OAuth env vars to GH_OAUTH_* in config.py, compose.yml, and the deploy workflow so the values can flow through Actions secrets into the generator container. Co-Authored-By: Claude Opus 4.7 --- .github/workflows/deploy.yml | 4 ++++ deploy/compose.yml | 4 ++++ generator/src/config.py | 8 +++++--- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 20019a2..a0f7ace 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -80,4 +80,8 @@ jobs: IMAGE_TAG: ${{ needs.build.outputs.image_tag }} GITHUB_PAT: ${{ secrets.FETCHER_GITHUB_PAT }} FETCHER_INTERNAL_TOKEN: ${{ secrets.FETCHER_INTERNAL_TOKEN }} + GH_OAUTH_CLIENT_ID: ${{ secrets.GH_OAUTH_CLIENT_ID }} + GH_OAUTH_CLIENT_SECRET: ${{ secrets.GH_OAUTH_CLIENT_SECRET }} + GENERATOR_SECRET_KEY: ${{ secrets.GENERATOR_SECRET_KEY }} + ALLOWED_ORIGINS: ${{ secrets.ALLOWED_ORIGINS }} run: ./deploy/deploy.sh diff --git a/deploy/compose.yml b/deploy/compose.yml index 657d70c..cf821d0 100644 --- a/deploy/compose.yml +++ b/deploy/compose.yml @@ -33,6 +33,10 @@ services: environment: FETCHER_URL: http://fetcher:5001 FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN} + GH_OAUTH_CLIENT_ID: ${GH_OAUTH_CLIENT_ID:?missing GH_OAUTH_CLIENT_ID} + GH_OAUTH_CLIENT_SECRET: ${GH_OAUTH_CLIENT_SECRET:?missing GH_OAUTH_CLIENT_SECRET} + GENERATOR_SECRET_KEY: ${GENERATOR_SECRET_KEY:?missing GENERATOR_SECRET_KEY} + ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://gh-stats.com} volumes: - ${HOME}/ghstats/data/generator:/app/data ports: diff --git a/generator/src/config.py b/generator/src/config.py index fcc3f83..e84fe02 100644 --- a/generator/src/config.py +++ b/generator/src/config.py @@ -142,9 +142,11 @@ PENDING_JOB_QUEUE_CAP = int(os.getenv("PENDING_JOB_QUEUE_CAP", "200")) GENERATE_SEMAPHORE_WAIT_S = float(os.getenv("GENERATE_SEMAPHORE_WAIT_S", "15")) # --- GitHub OAuth --- -GITHUB_OAUTH_CLIENT_ID = os.getenv("GITHUB_OAUTH_CLIENT_ID", "") -GITHUB_OAUTH_CLIENT_SECRET = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "") -GITHUB_OAUTH_REDIRECT_URI = os.getenv("GITHUB_OAUTH_REDIRECT_URI", "") +# Env names avoid the reserved GITHUB_ prefix so they can be stored as GitHub +# Actions secrets (which reject GITHUB_* names). +GITHUB_OAUTH_CLIENT_ID = os.getenv("GH_OAUTH_CLIENT_ID", "") +GITHUB_OAUTH_CLIENT_SECRET = os.getenv("GH_OAUTH_CLIENT_SECRET", "") +GITHUB_OAUTH_REDIRECT_URI = os.getenv("GH_OAUTH_REDIRECT_URI", "") # Flask session secret. Generate once: python -c "import secrets; print(secrets.token_hex(32))" SECRET_KEY = os.getenv("GENERATOR_SECRET_KEY", "") From f9caa61c77344d09c914f19b59be19a9729202b5 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 20:10:14 -0400 Subject: [PATCH 22/22] fix(frontend): send cookies on /generate POST Without credentials: 'include', the session cookie isn't attached and the OAuth-guarded endpoint returns 401. Co-Authored-By: Claude Opus 4.7 --- generator/frontend/src/App.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/generator/frontend/src/App.tsx b/generator/frontend/src/App.tsx index c2b40d3..72f01ec 100644 --- a/generator/frontend/src/App.tsx +++ b/generator/frontend/src/App.tsx @@ -164,7 +164,10 @@ export default function App() { return } - const r = await fetch(`/api/${encodeURIComponent(username)}/generate`, { method: 'POST' }) + const r = await fetch(`/api/${encodeURIComponent(username)}/generate`, { + method: 'POST', + credentials: 'include', + }) if (r.status === 404) { const body = await r.json().catch(() => ({} as { status?: string })) setGenerateError(body.status === 'not_found' ? 'User not found' : 'Not enrolled')