diff --git a/README.md b/README.md index 09e21f5..3b91f4c 100644 --- a/README.md +++ b/README.md @@ -345,7 +345,7 @@ Embed two widgets side by side with an HTML table: ``` - +U=findme; docker exec ghstats-generator python -c "import sqlite3; s=sqlite3.connect('/app/data/settings.db'); w=sqlite3.connect('/app/data/widgets.db'); [s.execute(f'DELETE FROM {t} WHERE username=?', ('$U',)) for t in ('users','jobs','user_streaks')]; [w.execute(f'DELETE FROM {t} WHERE username=?', ('$U',)) for t in ('widgets','current_widget','widget_data')]; s.commit(); w.commit(); print('generator: removed', '$U')" && docker exec ghstats-fetcher python -c "import sqlite3; c=sqlite3.connect('/app/data/fetcher.db'); c.execute('DELETE FROM users WHERE username=?', ('$U',)); c.commit(); print('fetcher: removed', '$U')" Stack a custom composite with only three widgets: ```md diff --git a/generator/src/api.py b/generator/src/api.py index a82a892..a905a38 100644 --- a/generator/src/api.py +++ b/generator/src/api.py @@ -618,6 +618,47 @@ def get_widget_named(username: str, widget: str): return _serve(username, widget_name=widget) +@app.route("/api/top-langs", methods=["GET"]) +@rate_limited("read") +def compat_top_langs(): + """Compatibility shim for upstream anuraghazra/github-readme-stats URLs. + + People copy `/api/top-langs?username=X&...` straight out of READMEs + that target the upstream Vercel-hosted service and just swap in + gh-stats.com. Without this route the request would fall through to + /api/ with username='top-langs', which is meaningless here. + + Routing precedence: Flask matches the literal '/api/top-langs' before + the '/api/' rule, so this can't shadow real users. + + Upstream-only query params (layout, title_color, text_color, + bg_color, hide_border, langs_count, hide, etc.) are deliberately + ignored — themeing in this fork is per-user, configured in the + workshop, not per-URL. The intent is that the embedded image + *renders something coherent* instead of 'user not found'. + """ + username = request.args.get("username", "") + if not isinstance(username, str) or not is_valid_username(username): + return jsonify({"error": "invalid_username"}), 400 + username = username.lower() + # Same auto-enroll path as GET /api//data so a first-time visitor + # doesn't sit on a placeholder forever. Daily cap is the abuse + # backstop; without it a botnet hitting random ?username= values + # could exhaust the GitHub PAT budget. + if db.get_settings(username) is None: + if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP: + return _placeholder_response("rate_limited", username) + defaults = { + "theme": "dark", + "enabled": config.ENABLED_WIDGETS, + "widget_order": config.WIDGET_ORDER, + } + db.enroll(username, defaults) + _request_fetch_async(username) + _kickoff_prefetch_async(username) + return _serve(username, widget_name="languages") + + @app.route("/api//data", methods=["GET"]) @rate_limited("read") def get_user_data(username: str): diff --git a/generator/tests/test_api.py b/generator/tests/test_api.py index e76dced..9c47802 100644 --- a/generator/tests/test_api.py +++ b/generator/tests/test_api.py @@ -313,6 +313,79 @@ def test_data_unknown_user_when_cap_reached_returns_429(client, monkeypatch): assert dbmod.get_settings("testuser") is None +# ---- /api/top-langs compat shim for upstream github-readme-stats URLs ---- + + +def test_top_langs_requires_username_query_param(client): + r = client.get("/api/top-langs") + assert r.status_code == 400 + assert r.get_json()["error"] == "invalid_username" + + +def test_top_langs_rejects_invalid_username(client): + r = client.get("/api/top-langs?username=../etc/passwd") + assert r.status_code == 400 + + +def test_top_langs_route_does_not_shadow_real_user_named_top(client): + """Sanity: Flask matches the literal '/api/top-langs' route before + falling through to '/api/', but a user literally named + 'top' should still resolve via the variable route.""" + dbmod.enroll("top", {"theme": "dark"}) + dbmod.put_widgets("top", "h1", {"composite": "top"}) + dbmod.point_current_widget("top", "h1") + r = client.get("/api/top") + assert r.status_code == 200 + assert b"top" in r.data + + +def test_top_langs_serves_languages_widget_for_existing_user(client): + """The shim's job is to map upstream's URL shape to this fork's + languages widget. Cached SVG should come back unchanged.""" + dbmod.enroll("alice", {"theme": "dark"}) + dbmod.put_widgets("alice", "h1", { + "composite": "composite", + "languages": "langs", + }) + dbmod.point_current_widget("alice", "h1") + r = client.get("/api/top-langs?username=alice") + assert r.status_code == 200 + assert r.headers.get("Content-Type", "").startswith("image/svg") + assert b"langs" in r.data + + +def test_top_langs_auto_enrolls_unknown_user(client): + """Visitor copy-pasting an upstream-style URL for a user we've never + seen should kick off the build pipeline, same as /data does.""" + r = client.get("/api/top-langs?username=newcomer") + assert r.status_code == 200 # placeholder SVG + assert dbmod.get_settings("newcomer") is not None + + +def test_top_langs_when_cap_reached_returns_placeholder(client, monkeypatch): + monkeypatch.setattr(cfg, "ENROLLMENT_DAILY_CAP", 0) + r = client.get("/api/top-langs?username=newcomer") + assert r.status_code == 200 + # Rate-limited placeholder, not enrolled. + assert dbmod.get_settings("newcomer") is None + + +def test_top_langs_ignores_upstream_specific_query_params(client): + """Upstream's layout/title_color/hide/langs_count/etc. params have + no equivalent in this fork. The shim should not crash on them — it + should just serve the cached widget and ignore the noise.""" + dbmod.enroll("alice", {"theme": "dark"}) + dbmod.put_widgets("alice", "h1", {"languages": "langs"}) + dbmod.point_current_widget("alice", "h1") + r = client.get( + "/api/top-langs?username=alice&layout=compact&hide_border=true" + "&title_color=58C4DD&text_color=58C4DD&bg_color=00000000" + "&langs_count=6&hide=html,css" + ) + assert r.status_code == 200 + assert b"langs" in r.data + + def test_enroll_endpoint_is_gone(client): r = client.post("/api/enroll", json={"username": "alice"}, headers={"Origin": "https://gh-stats.com"})