Author SHA1 Message Date
shay 1d0fd3013e feat(streaks): persist streaks on refresh and pass to renderer
Phase 1 worker now reads the stored streak, computes an updated one via
processor.compute_streaks, persists it to the DB (preserving the all-time
max across settings changes), and includes it in widget_data. Phase 2
_render_widgets pre-reads the stored streak and passes it to the processor.
2026-04-20 11:52:22 -04:00
shay 788470cae0 feat(streaks): enable streaks widget by default 2026-04-20 11:49:43 -04:00
shayandClaude Opus 4.7 f23449a17e feat(streaks): render streaks widget in generate_widgets_from_github
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 11:48:09 -04:00
shay cb7a00d7c4 feat(streaks): add streaks widget renderer
Add render_streaks_widget() to generator/src/widgets/streaks.py with
flame/trophy icons, two-column layout, optional date display, and
export it from the widgets package; append 3 smoke tests (all 11 pass).
2026-04-20 11:45:51 -04:00
shayandClaude Sonnet 4.6 3b00a0aeac feat(streaks): compute current and max streak with grace day
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 11:42:59 -04:00
shayandClaude Sonnet 4.6 7fb1ba3e01 feat(streaks): add user_streaks table and get/put helpers
Adds the user_streaks table to settings.db schema and implements
get_user_streak / put_user_streak helpers with upsert semantics.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 11:40:13 -04:00
shay dd4a3d50d8 feat(streaks): add StreakData model 2026-04-20 11:36:45 -04:00
shay 5a2bc11840 feat(ui): enhance AuthButton styling and position for better UX. 2026-04-19 21:51:30 -04:00
shay fa96adb5d1 feat(docs): update instance URL and enhance README formatting. 2026-04-19 21:51:23 -04:00
Shay ManorandGitHub 728f3f038d Merge pull request #2 from ShayManor/oauth
Oauth
2026-04-19 21:02:25 -04:00
shayandClaude Opus 4.7 f9caa61c77 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 <noreply@anthropic.com>
2026-04-19 20:10:14 -04:00
shayandClaude Opus 4.7 9e837519cc 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 <noreply@anthropic.com>
2026-04-19 20:02:52 -04:00
shayandClaude Opus 4.7 be8823c4cf chore(frontend): delete lib/editToken.ts (replaced by OAuth)
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 19:18:32 -04:00
shay ccdd8231ce feat(frontend): gate WorkshopScreen edit UI on OAuth login match 2026-04-19 19:16:59 -04:00
shay cd927e686f feat(frontend): AuthButton — GitHub sign-in / avatar chip 2026-04-19 19:14:06 -04:00
shayandClaude Sonnet 4.6 8ccc0af1cf feat(frontend): App fetches /me, removes editToken plumbing
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 19:12:36 -04:00
shay b2baded94a feat(frontend): add lib/auth.ts with fetchMe, signInUrl, signOut 2026-04-19 19:10:05 -04:00
shay 8b7f999adc feat(api): per-login mutate rate limit layered on per-IP 2026-04-19 19:09:04 -04:00
shay 0cd7bf339d feat(api): remove public /enroll endpoint and auto-enroll on /data 2026-04-19 19:06:38 -04:00
shay 91f6328efd feat(api): /generate and /refresh use OAuth session; remove edit_token helpers 2026-04-19 19:03:16 -04:00
shay 4ee71e0b86 feat(api): PATCH /settings uses OAuth session + same-origin 2026-04-19 18:59:46 -04:00
shayandClaude Opus 4.7 eb4b68bf0d feat(api): OAuth callback — verify state, fetch profile, implicit enroll
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 18:57:20 -04:00
shayandClaude Opus 4.7 98c40ff993 feat(api): add /api/auth/github/login with CSRF state + local-only next
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 18:54:44 -04:00
shay a6356d4d1d feat(api): add /api/auth/me and /api/auth/logout 2026-04-19 18:53:12 -04:00
shay 232812b3a0 feat(api): configure Flask session + init OAuth client 2026-04-19 18:51:22 -04:00
shay 4602bb9494 test(auth): unit tests for require_github_owner and require_same_origin 2026-04-19 18:49:39 -04:00
shay ccd0f63fa8 feat(auth): add OAuth client + require_github_owner/require_same_origin decorators 2026-04-19 18:48:14 -04:00
shay ec9d4c3672 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.
2026-04-19 18:47:11 -04:00
shay 22483aea19 db: enroll() accepts github profile; no longer returns edit_token 2026-04-19 18:45:26 -04:00
shay 57b782ceaf db: add github_id and github_avatar_url columns + set_github_profile 2026-04-19 18:44:01 -04:00
shay 4822272b49 config: add GitHub OAuth + session env vars 2026-04-19 18:40:28 -04:00
shayandClaude Opus 4.7 1501139143 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 <noreply@anthropic.com>
2026-04-19 18:39:45 -04:00
shay 58e794fd57 feat(tags): add auto-awarded profile tags and validation utilities. 2026-04-19 09:37:32 -04:00
shay ca74e91e3e feat(readme): update README to describe new SVG widget features. 2026-04-19 09:34:40 -04:00
shay 016583c9f3 feat(api): implement per-user edit token for settings mutations 2026-04-19 09:34:26 -04:00
shay 3ecb6ad67b feat(tags): implement custom tag color merging and label support 2026-04-18 14:52:32 -04:00
shay 3e70e4b4ef feat(languages): add hidden languages picker and enrich language data 2026-04-18 13:39:44 -04:00
shay 5198eab86a feat(icons): replace inline SVGs with consistent JSX properties for icons 2026-04-18 13:17:00 -04:00
shay 12fb6c331b feat(worker): add achievements parameter to widget settings processing 2026-04-18 13:05:49 -04:00
shay 89a05f2a59 chore(WorkshopScreen): update ICONS type from JSX.Element to ReactNode 2026-04-18 12:51:48 -04:00
shay 3aebd40279 chore(favicon): replace old SVG with new design for favicon icon
chore(ResultScreen): simplify embed section layout and improve copy button
chore(WorkshopScreen): replace emoji icons with inline SVGs for consistency
chore(index.html): update page
2026-04-18 12:50:23 -04:00
shay eadd074402 chore(App): add PATCH request to sync user settings with backend before render 2026-04-18 12:40:16 -04:00
shay dd45d49c22 chore(ResultScreen): add copy functionality for embed snippet button 2026-04-18 12:35:27 -04:00
shay 8ac657b874 chore(ResultScreen): update props to reflect SVG generation process changes 2026-04-18 12:17:25 -04:00
shay 7b2301cec0 chore(api): rename test function for clarity on enrollment behavior 2026-04-18 11:58:02 -04:00
shay f9c59d934d chore(api): add asynchronous build kickoff for improved responsiveness 2026-04-18 11:26:25 -04:00
shay 3ffb2cfb6f chore(frontend): add demo data 2026-04-18 11:15:16 -04:00
shay 79b9c31197 feat(api): implement precomputed widget data storage and retrieval. 2026-04-18 11:13:43 -04:00
shay f0c6edacf6 feat(api): add endpoint for fetching computed widget data by username. 2026-04-18 10:54:41 -04:00
shay a63c1891a0 feat(deploy): change deployment runner from minipc to self-hosted. 2026-04-18 01:06:59 -04:00
shay 873ca512bd feat(readme): update Docker badge to reflect new deployment workflow. 2026-04-18 00:52:46 -04:00
shay 19a357d92b feat(readme): remove references to deleted production pipeline design. 2026-04-18 00:02:34 -04:00
Shay ManorandGitHub a96b0d0b3f Merge pull request #1 from ShayManor/smanor/production-pipeline
Split monolith into fetcher/generator/edge services + React SPA + CI
2026-04-17 18:38:38 -04:00
shay 181668a3b3 fix(generator): fix import paths + add service config constants 2026-04-17 18:37:44 -04:00
shay 83c4227d5f ci: add tests + docker build workflows with status badges
- tests.yml: matrix-run pytest for fetcher/generator/edge on push + PR
- docker.yml: matrix-build each service's Dockerfile with buildx cache
- README badges reflect both workflow statuses
2026-04-17 18:13:18 -04:00
shay 814bbf7d8d chore: final cleanup — gitignore editor caches, track plan + spec docs 2026-04-17 17:21:36 -04:00
shay 74047b28fc docs: top-level README + CLAUDE.md reflect three-service layout 2026-04-17 17:19:23 -04:00
shay a2e7a52169 docs(frontend): update README for new location + API contract 2026-04-17 17:17:36 -04:00
shay 2ff5d21b1c feat(generator): add multi-stage Dockerfile (node build -> python runtime) 2026-04-17 17:16:45 -04:00
shay 3e0b69cacd fix(gitignore): scope Python lib/ to project root so frontend src/lib is tracked 2026-04-17 17:15:59 -04:00
shay 917ad098f7 feat(generator): move frontend into generator + namespace API calls under /api/ 2026-04-17 17:14:32 -04:00
shay f93c39d022 docs(edge): add README 2026-04-17 17:09:00 -04:00
shay 4edc66d1bb feat(edge): add cache-first SVG proxy with Flask-Caching + Flask-Compress 2026-04-17 17:08:37 -04:00
shay 5ba5ec4f4b feat(edge): scaffold config, requirements, Dockerfile 2026-04-17 17:07:12 -04:00
shay a3c17a15da test(generator): add end-to-end integration test + README 2026-04-17 17:06:03 -04:00
shay c0401a8a28 feat(generator): add poll cron that enqueues on payload-hash change 2026-04-17 17:03:11 -04:00
shay c50393467e fix(generator): harden SPA path handler and cache patch_settings read
- Drop the os.path.isfile pre-check in the SPA catch-all; let
  send_from_directory be the only gatekeeper so raw user-supplied
  path segments never reach os.path.isfile on a joined path.
- Reuse the first db.get_settings result in patch_settings so a
  race-induced None doesn't raise an unhandled AttributeError.
2026-04-17 17:01:56 -04:00
shay d448825bed feat(generator): add Flask API with SPA static, auth stub, rate limit 2026-04-17 16:59:25 -04:00
shay 961a3330e1 fix(generator): invalidate composite cache on not_found + drop unused import
Cache entry for widget:composite:{username} was not invalidated when a
user's fetcher payload transitioned to not_found, serving stale SVGs.
2026-04-17 16:56:45 -04:00
shayandClaude Opus 4.7 07221a1329 feat(generator): add build worker with retries and placeholder fallback
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-17 16:53:17 -04:00
shayandClaude Opus 4.7 97ad1c2b39 feat(generator): add typed HTTP client to the fetcher service
Implements thin wrapper over fetcher's two main endpoints: GET /data/<user>
and POST /fetch. Used by worker.py (rebuilds), api.py (user lookups), and
cron.py (bulk refresh). Includes authentication via X-Internal-Token header.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-17 16:47:38 -04:00
shayandClaude Sonnet 4.6 540d172011 feat(generator): add three placeholder SVG variants
Adds placeholder.py with building/rate_limited/not_found variants that use the same card_wrapper + theme system as real widgets, plus pytest coverage for all three variants and the unknown-variant error path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 16:46:12 -04:00
shay a0c5e8a86e feat(generator): add no-op cache wrapper (enables Redis later via env) 2026-04-17 16:44:38 -04:00
shayandClaude Sonnet 4.6 361c938985 feat(generator): add settings+widgets db with jobs, enrollment, LRU
Implements generator/src/db.py with two WAL-mode SQLite databases (settings.db for
users/jobs/enrollments, widgets.db for SVG cache with current_widget pointer) and
generator/tests/test_db.py covering all 10 TDD scenarios.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 16:42:43 -04:00
shayandClaude Sonnet 4.6 3525144aeb feat(generator): scaffold + move widgets/themes/models/utils/processor/config
- Add generator/requirements.txt and generator/pytest.ini
- git mv src/widgets, themes, models, utils, data/processor.py, config.py into generator/src/
- Fix relative imports in processor.py (moved up one level: .. → .)
- Append service-specific env vars (PORT, DB paths, FETCHER_URL, etc.) to generator/src/config.py
- git rm retired src/db, src/data/__init__.py, src/__init__.py

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 16:39:29 -04:00
shayandClaude Sonnet 4.6 cb3ace8dcd feat(fetcher): add cron refresh + GC and service README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 16:34:52 -04:00
shayandClaude Sonnet 4.6 d77dea20bc feat(fetcher): add Flask API with auth, auto-fetch, avatar
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 16:32:59 -04:00
shayandClaude Sonnet 4.6 1a3caff269 feat(fetcher): move GitHub client into fetcher service
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 16:30:52 -04:00
shay 15ad9c81aa chore(cleanup): remove stale widget_shaymanor.svg build artifact 2026-04-17 16:26:19 -04:00
shayandClaude Sonnet 4.6 832f94c1b9 feat(fetcher): add SQLite db module with WAL, payload hashing, GC
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 16:25:05 -04:00
shay f0e6d9439e feat(fetcher): scaffold config, requirements, pytest, Dockerfile 2026-04-17 16:22:46 -04:00
shay 7aa5f9d5a0 chore(cleanup): remove retired entry points and build artifacts 2026-04-17 16:22:04 -04:00
shay 9feae9ff35 chore(scaffold): create fetcher/generator/edge service folders 2026-04-17 16:21:26 -04:00
118 changed files with 9897 additions and 984 deletions
+87
View File
@@ -0,0 +1,87 @@
name: build and deploy
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
REGISTRY: ghcr.io
jobs:
build:
name: build ${{ matrix.service }}
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
strategy:
fail-fast: false
matrix:
service: [fetcher, generator, edge]
outputs:
image_tag: ${{ steps.tag.outputs.value }}
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
if: github.event_name == 'push'
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Compute image tag (sha-<short>)
id: tag
env:
SHA: ${{ github.sha }}
run: echo "value=sha-${SHA:0:7}" >> "$GITHUB_OUTPUT"
- name: Compute image name (lowercase)
id: img
env:
OWNER: ${{ github.repository_owner }}
SERVICE: ${{ matrix.service }}
run: echo "name=${REGISTRY}/${OWNER,,}/ghstats-${SERVICE}" >> "$GITHUB_OUTPUT"
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ steps.img.outputs.name }}
tags: |
type=raw,value=${{ steps.tag.outputs.value }}
type=raw,value=latest,enable={{is_default_branch}}
- name: Build ${{ matrix.service }} image
uses: docker/build-push-action@v6
with:
context: ./${{ matrix.service }}
push: ${{ github.event_name == 'push' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha,scope=${{ matrix.service }}
cache-to: type=gha,mode=max,scope=${{ matrix.service }}
deploy:
name: deploy to mini PC
needs: build
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: self-hosted
steps:
- uses: actions/checkout@v4
- name: Deploy compose stack
env:
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
+33
View File
@@ -0,0 +1,33 @@
name: tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
pytest:
name: ${{ matrix.service }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
service: [fetcher, generator, edge]
defaults:
run:
working-directory: ${{ matrix.service }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
cache-dependency-path: ${{ matrix.service }}/requirements.txt
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run pytest
run: pytest -v
+38 -2
View File
@@ -14,8 +14,8 @@ dist/
downloads/ downloads/
eggs/ eggs/
.eggs/ .eggs/
lib/ /lib/
lib64/ /lib64/
parts/ parts/
sdist/ sdist/
var/ var/
@@ -205,3 +205,39 @@ cython_debug/
marimo/_static/ marimo/_static/
marimo/_lsp/ marimo/_lsp/
__marimo__/ __marimo__/
# Per-service SQLite databases (runtime data)
fetcher/data/*.db
fetcher/data/*.db-wal
fetcher/data/*.db-shm
generator/data/*.db
generator/data/*.db-wal
generator/data/*.db-shm
# Built frontend bundle
generator/src/static/
generator/frontend/dist/
generator/frontend/node_modules/
# Python build artifacts
**/__pycache__/
**/*.pyc
.pytest_cache/
# Widget build artifacts at repo root (retired)
/widget_*.svg
/data/ghstats.db
# Editor / tooling caches
.idea/
.claude/
.superpowers/
.playwright-mcp/
screenshots/
# Kept locally, not tracked
/CLAUDE.md
/docs/
**/*.md
!README.md
!**/README.md
+192 -63
View File
@@ -1,90 +1,219 @@
# GitHub README Stats # github-readme-stats
Generate polished SVG profile cards from your GitHub data. Fetches your repos, contributions, languages, and collaborators, then renders them into composable widgets you can drop into your profile README. [![tests](https://github.com/ShayManor/github-readme-stats/actions/workflows/tests.yml/badge.svg)](https://github.com/ShayManor/github-readme-stats/actions/workflows/tests.yml)
[![build and deploy](https://github.com/ShayManor/github-readme-stats/actions/workflows/deploy.yml/badge.svg)](https://github.com/ShayManor/github-readme-stats/actions/workflows/deploy.yml)
<p align="center"> A single SVG widget you drop into your GitHub profile README. It scores
<img src="widget_shaymanor.svg" width="420" alt="Example composite widget" /> your account, charts your contribution timeline, highlights your top
</p> collaborators, breaks down your languages, and earns you tags like
`Backend`, `ML`, or `Founder #42`.
## Widgets ![hero widget](https://gh-stats.com/ShayManor)
| Widget | What it shows | ---
|--------|--------------|
| **Grade** | Letter grade (S through F) with score breakdown, stats, and inferred role tags |
| **Impact** | Contribution timeline over the last 6 months |
| **Collaborators** | Top people you've committed alongside, ranked by shared commits |
| **Focus** | Where your recent work falls (Backend, Frontend, ML, DevOps, etc.) |
| **Languages** | Donut chart of your most-used languages by LOC |
| **Achievements** | Custom badges you define (hackathons, awards, milestones) |
Each widget is also saved individually as `widget_<name>.svg`. ## Get your widget in 30 seconds
## Quick Start 1. Open `https://gh-stats.com/` in a browser.
2. Type your GitHub username and hit **Continue**.
3. Pick a theme, reorder widgets, add custom tags / achievements.
4. Click **Generate** — the SVG is built on the server and cached.
5. Copy the one-liner and paste it into your profile README:
```bash ```markdown
# Basic (public data only) ![my stats](https://gh-stats.com/YOUR_USERNAME)
python run.py <username>
# With a GitHub token for full commit/contribution data
GITHUB_PAT=<your-token> python run.py <username>
# Choose a theme
python run.py <username> nord
``` ```
Output lands in the repo root as `widget_<username>.svg`. That's it. Every push of GitHub activity is picked up by a 15-minute
refresh cron, so the image stays current without you doing anything.
---
## What's in the widget
| Widget | What it shows |
|---|---|
| **Grade** | Overall score (0–100) + letter grade + top tags |
| **Impact Timeline** | Smooth contribution curve over the last 6 months |
| **Top Collaborators** | Avatars + shared-repo + commit bars |
| **Recent Focus** | What you've actually been working on lately |
| **Languages** | Your language mix, weighted by active code |
| **Achievements** | Hand-entered credentials — hackathons, talks, awards |
Widgets are composed into a single card, or you can embed any one of
them on its own — see [Individual widgets](#individual-widgets).
---
## Themes ## Themes
Five built-in themes: Pass `?theme=<name>` or pick in the Workshop. Five built-ins:
| Theme | Style | | Theme | Tone |
|-------|-------| |---|---|
| `midnight` / `dark` | Dark blue-gray (default) | | `midnight` *(default)* | dark, soft blue accents |
| `onyx` | High-contrast on near-black | | `onyx` | deep black, neon violet |
| `nord` | Muted pastels on slate | | `nord` | muted pastel on slate |
| `clean` / `light` | White background | | `clean` | white, understated |
| `paper` | Warm off-white, sepia accents | | `paper` | warm off-white |
## Web UI ```markdown
![my stats](https://gh-stats.com/YOUR_USERNAME?theme=onyx)
```
A React frontend lets you customize widgets interactively with live preview and per-widget advanced settings (colors, counts, etc.). ---
## Individual widgets
Don't want the full composite? Embed exactly one:
```markdown
![grade](https://gh-stats.com/YOUR_USERNAME/grade.svg)
![impact](https://gh-stats.com/YOUR_USERNAME/impact.svg)
![collaborators](https://gh-stats.com/YOUR_USERNAME/collaborators.svg)
![focus](https://gh-stats.com/YOUR_USERNAME/focus.svg)
![languages](https://gh-stats.com/YOUR_USERNAME/languages.svg)
![achievements](https://gh-stats.com/YOUR_USERNAME/achievements.svg)
```
Put two side-by-side with an HTML table:
```html
<table><tr>
<td><img src="https://gh-stats.com/YOUR_USERNAME/grade.svg"/></td>
<td><img src="https://gh-stats.com/YOUR_USERNAME/languages.svg"/></td>
</tr></table>
```
---
## Customization
Everything is editable from the Workshop UI — the settings are saved
against your username, so re-embedding picks them up automatically.
- **Custom tags** — add role labels like `ML`, `Systems`, `Cloud`. The
grade widget will fit them into its tag cloud.
- **Hidden languages** — exclude languages you don't want counted
(e.g. `HTML`, `CSS`, `Makefile`).
- **Widget colors** — per-widget accent overrides for the impact line
and collaborator bars (hex, `#RRGGBB`).
- **Widget limits** — cap the number of tags, collaborators, or
languages shown.
- **Achievements** — up to 10 hand-entered lines with icon
(`trophy`, `medal`, `star`, `hackathon`), title, subtitle, and date.
**Auto-awarded tags** fire from real activity — no way to fake them:
- `Founder #N` — one of the first N enrolled users, with your number
- (plus anything your languages / topics map to: `Backend`, `Frontend`,
`ML`, `Mobile`, `DevOps`, `Cloud`, …)
---
## Refreshing
Your data refreshes automatically every 15 minutes. If you just merged
something big and want it to show up immediately, click **Refresh now**
in the Workshop (one-shot per account; requires the edit token that was
issued to your browser on first visit).
---
## Status states
The SVG endpoint advertises its state via the `X-Widget-Status` header:
| Status | Meaning | Your README shows |
|---|---|---|
| `ready` | Built and cached | the real widget |
| `building` | Enrolled, first render in progress | a placeholder card |
| `rate_limited` | Daily enrollment cap hit | a placeholder card |
| `not_found` | GitHub username doesn't exist | a 404-style card |
GitHub caches the image aggressively; if a just-enrolled widget shows
the placeholder for a minute or two, that's expected.
---
## Self-hosting
If you want your own instance, it runs as three Docker services plus a
Vite-built React SPA served by the generator. You'll need a GitHub
Personal Access Token (classic, `read:user` + `repo:public_repo` is
enough).
```bash ```bash
# Terminal 1 — start the generator API # 1) fetcher — owns the PAT, talks to GitHub
python -m src.generator_api # :5002 (cd fetcher && pip install -r requirements.txt &&
FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=<your-pat> python -m src.api) &
# Terminal 2 — start the frontend # 2) generator — API + worker + refresh cron
cd frontend && npm install && npm run dev # :3000 cd generator && pip install -r requirements.txt
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.api &
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.worker &
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.cron &
# 3) edge — cache-first SVG proxy (this is what you put behind your domain)
(cd ../edge && pip install -r requirements.txt &&
GENERATOR_URL=http://localhost:5002 python -m src.api) &
# 4) frontend (dev only — production builds are baked into the generator image)
cd ../generator/frontend && npm install && npm run dev
``` ```
Open `http://localhost:3000`, enter a GitHub username, tweak settings, and hit Generate. Per-service READMEs cover Docker, tests, and env vars:
## Configuration - [`fetcher/`](./fetcher/README.md) — port 5001
- [`generator/`](./generator/README.md) — port 5002
- [`edge/`](./edge/README.md) — port 5003
All tuning lives in `src/config.py` and can be overridden with environment variables. Key knobs: The generator image serves both the API and the pre-built frontend, so
after deploying edge + generator + fetcher you can point a domain at
the edge and you're done.
| Variable | Default | What it does | ### Capacity knobs
|----------|---------|-------------|
| `GITHUB_PAT` | — | GitHub personal access token |
| `COMMIT_MAX_REPOS` | 10 | Max repos to scan for commits |
| `COMMIT_PER_REPO` | 30 | Max commits per repo |
| `COLLABORATOR_MIN_COMMITS` | 3 | Minimum shared commits to show a collaborator |
| `API_TIMEOUT` | 5 | Per-request timeout in seconds |
See [CONFIGURATION.md](CONFIGURATION.md) for the full list. Sensible defaults; all overridable via env:
## Project Structure | Env | Default | What it bounds |
|---|---|---|
| `GENERATE_CONCURRENCY` | `2` | Simultaneous SVG renders |
| `PREFETCH_MAX_WORKERS` | `2` | Background prefetch threads |
| `PENDING_JOB_QUEUE_CAP` | `200` | Build queue depth before new enrolls 429 |
| `ENROLLMENT_DAILY_CAP` | `50` | New users per day |
| `RATE_LIMIT_READ_MAX` | `3000` per 60s | Per-IP README embeds |
| `RATE_LIMIT_MUTATE_MAX` | `120` per 60s | Per-IP settings edits / generates |
| `RATE_LIMIT_ENROLL_MAX` | `60` per 300s | Per-IP new enrollments |
| `EDGE_RATE_LIMIT_MAX` | `3000` per 60s | Per-IP at the edge |
---
## Running tests
```bash
(cd fetcher && pytest) && (cd generator && pytest) && (cd edge && pytest)
``` ```
src/
data/ # GitHub API fetching + data processing ---
widgets/ # One SVG renderer per widget
themes/ # Color palettes ## FAQ
models/ # Typed data structures
utils/ # SVG helpers **Can I use a private GitHub account?**
config.py # All tunables No — the fetcher only sees public activity. Private repos and private
generate.py # CLI entry point contribution counts aren't included.
generator_api.py # Flask API for the web UI
frontend/ # React + TypeScript + Vite **How fresh is the data?**
``` The refresh cron ticks every 15 minutes. You can also click **Refresh
now** in the Workshop once per account.
**Someone else already enrolled my username — can I edit it?**
The first browser to visit your username gets the edit token. If that
was you but you've lost the token (cleared localStorage, switched
browsers), there's no recovery path today — an OAuth-based reclaim
flow is on the roadmap.
**Can I change the widget without re-embedding?**
Yes. The image URL is stable. Edit settings in the Workshop, click
Generate, and the next time the image is fetched it's the new version
(GitHub's image cache may delay that by a few minutes).
BIN
View File
Binary file not shown.
+82
View File
@@ -0,0 +1,82 @@
name: ghstats
services:
fetcher:
image: ghcr.io/shaymanor/ghstats-fetcher:${IMAGE_TAG:-latest}
container_name: ghstats-fetcher
restart: unless-stopped
environment:
GITHUB_PAT: ${GITHUB_PAT:?missing GITHUB_PAT}
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
volumes:
- ${HOME}/ghstats/data/fetcher:/app/data
ports:
- "127.0.0.1:5001:5001"
fetcher-cron:
image: ghcr.io/shaymanor/ghstats-fetcher:${IMAGE_TAG:-latest}
container_name: ghstats-fetcher-cron
restart: unless-stopped
command: ["python", "-m", "src.cron"]
environment:
GITHUB_PAT: ${GITHUB_PAT:?missing GITHUB_PAT}
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
volumes:
- ${HOME}/ghstats/data/fetcher:/app/data
depends_on:
- fetcher
generator:
image: ghcr.io/shaymanor/ghstats-generator:${IMAGE_TAG:-latest}
container_name: ghstats-generator
restart: unless-stopped
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:
- "5002:5002"
depends_on:
- fetcher
generator-worker:
image: ghcr.io/shaymanor/ghstats-generator:${IMAGE_TAG:-latest}
container_name: ghstats-generator-worker
restart: unless-stopped
command: ["python", "-m", "src.worker"]
environment:
FETCHER_URL: http://fetcher:5001
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
volumes:
- ${HOME}/ghstats/data/generator:/app/data
depends_on:
- generator
generator-cron:
image: ghcr.io/shaymanor/ghstats-generator:${IMAGE_TAG:-latest}
container_name: ghstats-generator-cron
restart: unless-stopped
command: ["python", "-m", "src.cron"]
environment:
FETCHER_URL: http://fetcher:5001
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
volumes:
- ${HOME}/ghstats/data/generator:/app/data
depends_on:
- generator
edge:
image: ghcr.io/shaymanor/ghstats-edge:${IMAGE_TAG:-latest}
container_name: ghstats-edge
restart: unless-stopped
environment:
GENERATOR_URL: http://generator:5002
ports:
- "5003:5003"
depends_on:
- generator
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Pulls the current image tag and brings up the compose stack.
# Expects GITHUB_PAT, FETCHER_INTERNAL_TOKEN, and IMAGE_TAG to be present in
# the environment (exported by the GitHub Actions deploy job).
set -euo pipefail
cd "$(dirname "$0")"
mkdir -p "$HOME/ghstats/data/fetcher" "$HOME/ghstats/data/generator"
docker compose pull
docker compose up -d --remove-orphans
docker compose ps
+10
View File
@@ -0,0 +1,10 @@
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY src ./src
EXPOSE 5003
# Bind to $PORT when set (e.g. Cloud Run injects PORT=8080); default to 5003.
CMD ["sh", "-c", "exec gunicorn -b 0.0.0.0:${PORT:-5003} -w 2 src.api:app"]
+35
View File
@@ -0,0 +1,35 @@
# Edge Service
Cache-first SVG proxy in front of the generator. Deploy many instances
around the world. No DB of its own; optional Redis for shared cache.
## Run locally
cd edge
pip install -r requirements.txt
GENERATOR_URL=http://localhost:5002 python -m src.api
## Test
cd edge && pytest
## Docker
docker build -t ghstats-edge .
docker run --rm -e GENERATOR_URL=http://host.docker.internal:5002 -p 5003:5003 ghstats-edge
## Endpoints
| Method | Path | Description |
|---|---|---|
| GET | /health | cache type + upstream reachability |
| GET | /<u> | composite SVG (cached on X-Widget-Status: ready) |
| GET | /<u>/<w>.svg | individual widget SVG |
## Env
- `GENERATOR_URL` — origin (required)
- `CACHE_TYPE` — `SimpleCache` (default) or `RedisCache`
- `CACHE_REDIS_URL` — if using RedisCache
- `CACHE_DEFAULT_TIMEOUT` — seconds, default 86400
- `CACHE_THRESHOLD` — max entries (SimpleCache only), default 10000
+5
View File
@@ -0,0 +1,5 @@
[pytest]
testpaths = tests
python_files = test_*.py
pythonpath = .
addopts = -ra --strict-markers
+7
View File
@@ -0,0 +1,7 @@
flask==3.0.3
flask-caching==2.3.0
flask-compress==1.15
requests==2.32.3
pytest==8.3.3
responses==0.25.3
gunicorn==23.0.0
View File
+144
View File
@@ -0,0 +1,144 @@
"""Edge service — cache-first SVG proxy in front of the generator."""
import logging
import re
import time
from collections import defaultdict, deque
from threading import Lock
import requests
from flask import Flask, Response, jsonify, request
from flask_compress import Compress
from . import cache as cache_mod, config
app = Flask(__name__)
Compress(app)
cache_ext = cache_mod.build_cache(app)
log = logging.getLogger("edge")
# GitHub usernames: 1-39 chars, alnum, single hyphens. Keep the regex in
# sync with generator/src/utils/validate.py so invalid paths get rejected
# before they waste an upstream round-trip.
_USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
_ALLOWED_WIDGETS = {"grade", "impact", "collaborators", "focus", "languages", "achievements", "composite"}
def _valid_username(u: str) -> bool:
return bool(u) and bool(_USERNAME_RE.match(u))
# ---- Per-IP rate limiter ---------------------------------------------------
# The edge is the mini PC's front door. Cache hits are cheap, but a hostile
# cache-miss storm (unique usernames, unique widget names) would funnel into
# the generator's render path. Bound it here so the generator's own limiter
# isn't the only layer. Operators who run behind a CDN / nginx should prefer
# the upstream limiter and raise these env vars.
_rate_lock = Lock()
_rate_hits: dict[str, deque] = defaultdict(deque)
def _client_ip() -> str:
fwd = request.headers.get("X-Forwarded-For", "")
if fwd:
return fwd.split(",")[-1].strip()
return request.remote_addr or "unknown"
def _allow(ip: str) -> bool:
now = time.time()
cutoff = now - config.RATE_LIMIT_WINDOW
with _rate_lock:
q = _rate_hits[ip]
while q and q[0] < cutoff:
q.popleft()
if len(q) >= config.RATE_LIMIT_MAX:
return False
q.append(now)
return True
def _cache_key(path: str) -> str:
return f"edge:{path}"
def _fetch_origin(path: str, client_ip: str) -> requests.Response:
url = f"{config.GENERATOR_URL}/api/{path}"
# Forward the caller's IP so the generator's rate limiter can
# discriminate per user rather than treating the edge's single IP as
# one client — otherwise the first 300 requests/min exhaust the bucket
# for everyone behind the edge.
headers = {"X-Forwarded-For": client_ip}
return requests.get(url, headers=headers, timeout=config.UPSTREAM_TIMEOUT)
@app.route("/health", methods=["GET"])
def health():
ok = True
try:
r = requests.get(f"{config.GENERATOR_URL}/api/health", timeout=config.UPSTREAM_TIMEOUT)
ok = r.status_code == 200
except Exception:
ok = False
return jsonify({"service": "edge", "cache_type": config.CACHE_TYPE, "upstream_ok": ok})
@app.route("/<username>", methods=["GET"])
def serve(username: str):
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
return _serve(username, path=username)
@app.route("/<username>/<widget>.svg", methods=["GET"])
def serve_widget(username: str, widget: str):
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
if widget not in _ALLOWED_WIDGETS:
return jsonify({"error": "unknown_widget"}), 400
return _serve(f"{username}/{widget}", path=f"{username}/{widget}.svg")
def _serve(key_suffix: str, path: str) -> Response:
ip = _client_ip()
if not _allow(ip):
return jsonify({"error": "rate_limited"}), 429
ck = _cache_key(key_suffix)
cached = cache_ext.get(ck)
if cached is not None:
body, content_type = cached
return Response(body, mimetype=content_type, headers={
"X-Widget-Status": "ready",
"X-Cache": "HIT",
"Cache-Control": "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400",
})
try:
r = _fetch_origin(path, ip)
except Exception as e:
log.warning("origin unreachable for %s: %s", path, e)
return jsonify({"error": "origin unreachable"}), 503
if r.status_code >= 500:
return jsonify({"error": "origin error"}), 503
status = r.headers.get("X-Widget-Status", "ready")
content_type = r.headers.get("Content-Type", "image/svg+xml")
if status == "ready" and r.status_code == 200:
cache_ext.set(ck, (r.content, content_type), timeout=config.CACHE_DEFAULT_TIMEOUT)
cc = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400"
else:
cc = "no-store"
return Response(r.content, status=r.status_code, mimetype=content_type, headers={
"X-Widget-Status": status,
"X-Cache": "MISS",
"Cache-Control": cc,
})
def main():
app.run(host="0.0.0.0", port=config.PORT)
if __name__ == "__main__":
main()
+16
View File
@@ -0,0 +1,16 @@
"""Flask-Caching config. v1 = SimpleCache (in-process). Swap to RedisCache via env."""
from flask_caching import Cache
from . import config
def build_cache(app) -> Cache:
cfg = {
"CACHE_TYPE": config.CACHE_TYPE,
"CACHE_DEFAULT_TIMEOUT": config.CACHE_DEFAULT_TIMEOUT,
"CACHE_THRESHOLD": config.CACHE_THRESHOLD,
}
if config.CACHE_TYPE == "RedisCache" and config.CACHE_REDIS_URL:
cfg["CACHE_REDIS_URL"] = config.CACHE_REDIS_URL
c = Cache(config=cfg)
c.init_app(app)
return c
+16
View File
@@ -0,0 +1,16 @@
import os
PORT = int(os.getenv("EDGE_PORT", "5003"))
GENERATOR_URL = os.getenv("GENERATOR_URL", "http://localhost:5002")
CACHE_TYPE = os.getenv("CACHE_TYPE", "SimpleCache")
CACHE_REDIS_URL = os.getenv("CACHE_REDIS_URL", "")
CACHE_DEFAULT_TIMEOUT = int(os.getenv("CACHE_DEFAULT_TIMEOUT", "86400"))
CACHE_THRESHOLD = int(os.getenv("CACHE_THRESHOLD", "10000"))
UPSTREAM_TIMEOUT = int(os.getenv("EDGE_UPSTREAM_TIMEOUT", "10"))
# Per-IP rate limit at the edge. Anti-abuse only — cache hits are cheap
# and cache misses are already bounded by the generator's global
# semaphore, so normal traffic should never notice this. Generous by
# default; tighten via env if a specific IP misbehaves.
RATE_LIMIT_MAX = int(os.getenv("EDGE_RATE_LIMIT_MAX", "3000"))
RATE_LIMIT_WINDOW = int(os.getenv("EDGE_RATE_LIMIT_WINDOW", "60"))
View File
+49
View File
@@ -0,0 +1,49 @@
import pytest
import responses
from src import api as apimod
@pytest.fixture
def client(monkeypatch):
monkeypatch.setattr(apimod.config, "GENERATOR_URL", "http://gen:5002")
apimod.cache_ext.clear()
apimod.app.config["TESTING"] = True
with apimod.app.test_client() as c:
yield c
@responses.activate
def test_miss_then_hit_serves_from_cache(client):
responses.add(responses.GET, "http://gen:5002/api/alice",
body=b"<svg>ready</svg>", status=200,
headers={"X-Widget-Status": "ready", "Content-Type": "image/svg+xml"})
r1 = client.get("/alice")
assert r1.status_code == 200
assert r1.data == b"<svg>ready</svg>"
responses.reset()
r2 = client.get("/alice")
assert r2.status_code == 200
assert r2.data == b"<svg>ready</svg>"
@responses.activate
def test_placeholder_not_cached(client):
responses.add(responses.GET, "http://gen:5002/api/alice",
body=b"<svg>building</svg>", status=200,
headers={"X-Widget-Status": "building", "Content-Type": "image/svg+xml"})
r1 = client.get("/alice")
assert r1.status_code == 200
r2 = client.get("/alice")
assert len(responses.calls) == 2
@responses.activate
def test_origin_error_returns_503(client):
responses.add(responses.GET, "http://gen:5002/api/alice", status=500)
r = client.get("/alice")
assert r.status_code == 503
def test_health(client):
r = client.get("/health")
assert r.status_code == 200
+14
View File
@@ -0,0 +1,14 @@
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY src ./src
RUN mkdir -p /app/data
EXPOSE 5001
ENV FETCHER_DB_PATH=/app/data/fetcher.db
# Default is the API. Override CMD for cron: ["python", "-m", "src.cron"]
CMD ["gunicorn", "-b", "0.0.0.0:5001", "-w", "2", "src.api:app"]
+37
View File
@@ -0,0 +1,37 @@
# Fetcher Service
Owns every GitHub API interaction. Holds the PAT. Exposes cached payloads
over an internal-only HTTP API protected by a shared secret.
## Run locally
cd fetcher
pip install -r requirements.txt
FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=ghp_xxx python -m src.api
Cron (separate process):
FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=ghp_xxx python -m src.cron
## Test
cd fetcher && pytest
## Docker
docker build -t ghstats-fetcher .
docker run -e GITHUB_PAT=ghp_xxx -e FETCHER_INTERNAL_TOKEN=dev -p 5001:5001 -v $(pwd)/data:/app/data ghstats-fetcher
# cron: override CMD to ["python","-m","src.cron"]
## Endpoints
| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /health | none | health check |
| GET | /data/<u> | X-Internal-Token | return stored payload; auto-fetches on miss |
| POST | /fetch | X-Internal-Token | force re-fetch (body: {username}) |
| GET | /avatar/<u> | X-Internal-Token | proxied avatar bytes |
## Env
See `src/config.py`.
View File
+5
View File
@@ -0,0 +1,5 @@
[pytest]
testpaths = tests
python_files = test_*.py
pythonpath = .
addopts = -ra --strict-markers
+5
View File
@@ -0,0 +1,5 @@
flask==3.0.3
requests==2.32.3
pytest==8.3.3
responses==0.25.3
gunicorn==23.0.0
View File
+125
View File
@@ -0,0 +1,125 @@
"""Flask app for the fetcher service. All endpoints require X-Internal-Token."""
import hmac
import logging
import re
import requests
from flask import Flask, jsonify, request, Response
from functools import wraps
from . import config, db, github
app = Flask(__name__)
log = logging.getLogger("fetcher.api")
# Must stay in sync with github.py's _USERNAME_RE. Trust boundary: the
# fetcher is called only by the generator over the internal network, but
# a compromised/bugged generator must not be able to turn us into an
# arbitrary GitHub URL fetcher.
_USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
def _valid_username(u) -> bool:
return isinstance(u, str) and bool(_USERNAME_RE.match(u))
def require_internal_token(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
token = request.headers.get("X-Internal-Token", "")
if not config.INTERNAL_TOKEN or not hmac.compare_digest(token, config.INTERNAL_TOKEN):
return jsonify({"error": "unauthorized"}), 401
return fn(*args, **kwargs)
return wrapper
@app.route("/health", methods=["GET"])
def health():
return jsonify({"status": "ok", "service": "fetcher", "users": len(db.list_usernames())})
@app.route("/data/<username>", methods=["GET"])
@require_internal_token
def get_data(username: str):
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
row = db.get_user(username)
if row is None:
# Auto-fetch path
try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
except Exception:
log.exception("github fetch failed for %s", username)
return jsonify({"error": "fetch_failed"}), 502
if _is_github_not_found(data):
data = {"error": "not_found"}
h = db.upsert_user(username, data)
return jsonify({"data": data, "payload_hash": h, "fetched": True})
return jsonify({
"data": row["data"],
"payload_hash": row["payload_hash"],
"fetched_at": row["fetched_at"],
"fetched": False,
})
@app.route("/fetch", methods=["POST"])
@require_internal_token
def force_fetch():
body = request.get_json(silent=True) or {}
username = body.get("username")
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
except Exception:
# Previously returned f"fetch failed: {e}" which leaks internal
# exception text (URLs, stack fragments) across the trust boundary.
log.exception("github fetch failed for %s", username)
return jsonify({"error": "fetch_failed"}), 502
if _is_github_not_found(data):
data = {"error": "not_found"}
old = db.get_user(username)
old_hash = old["payload_hash"] if old else None
new_hash = db.upsert_user(username, data)
return jsonify({"stored": True, "payload_hash": new_hash, "changed": old_hash != new_hash})
@app.route("/avatar/<username>", methods=["GET"])
@require_internal_token
def avatar(username: str):
# SSRF surface: we build https://github.com/<u>.png from path input. The
# <username> Flask converter already refuses slashes, but allowlist the
# shape anyway so any future change to the proxy path can't turn into a
# URL-smuggling primitive.
if not _valid_username(username):
return jsonify({"error": "invalid_username"}), 400
try:
r = requests.get(
f"https://github.com/{username}.png",
timeout=config.API_TIMEOUT,
allow_redirects=True,
)
except Exception:
log.exception("avatar fetch failed for %s", username)
return jsonify({"error": "avatar_unavailable"}), 502
if r.status_code != 200:
return jsonify({"error": "avatar unavailable"}), 404
return Response(r.content, mimetype=r.headers.get("Content-Type", "image/png"))
def _is_github_not_found(data: dict) -> bool:
user = data.get("user")
if user is None:
return True
if isinstance(user, dict) and user.get("message") == "Not Found":
return True
return False
def main():
db.init_db()
app.run(host="0.0.0.0", port=config.PORT)
if __name__ == "__main__":
main()
+25
View File
@@ -0,0 +1,25 @@
"""Fetcher service configuration, overridable via env vars."""
import os
PORT = int(os.getenv("FETCHER_PORT", "5001"))
DB_PATH = os.getenv("FETCHER_DB_PATH", "./data/fetcher.db")
GITHUB_PAT = os.getenv("GITHUB_PAT", "")
INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
REFRESH_INTERVAL_HOURS = int(os.getenv("FETCHER_REFRESH_INTERVAL_HOURS", "24"))
TRIAL_GC_DAYS = int(os.getenv("FETCHER_TRIAL_GC_DAYS", "7"))
API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15"))
# Collaborator-detection tuning
COLLABORATOR_MAX_REPO_SIZE = int(os.getenv("COLLABORATOR_MAX_REPO_SIZE", "150"))
COLLABORATOR_TOP_REPOS = int(os.getenv("COLLABORATOR_TOP_REPOS", "30"))
SMALL_OWNED_REPO_SIZE = int(os.getenv("SMALL_OWNED_REPO_SIZE", "10"))
COLLABORATOR_LOOKBACK_DAYS = int(os.getenv("COLLABORATOR_LOOKBACK_DAYS", "365"))
MEANINGFUL_MIN_COMMITS = int(os.getenv("MEANINGFUL_MIN_COMMITS", "3"))
FORK_MIN_COMMITS = int(os.getenv("FORK_MIN_COMMITS", "10"))
OWNER_BOOST = float(os.getenv("OWNER_BOOST", "1.5"))
MIN_SHARED_REPOS = int(os.getenv("MIN_SHARED_REPOS", "2"))
DEEP_COLLAB_THRESHOLD = int(os.getenv("DEEP_COLLAB_THRESHOLD", "25"))
# Commit-fetching caps
COMMIT_MAX_REPOS = int(os.getenv("COMMIT_MAX_REPOS", "10"))
COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30"))
+48
View File
@@ -0,0 +1,48 @@
"""Scheduled refresh + GC loop. Run as its own container (CMD override)."""
import logging
import time
from . import config, db, github
log = logging.getLogger("fetcher.cron")
def tick(hours: int, active_within_days: int, gc_days: int) -> dict:
"""Refresh due users, then GC abandoned ones. Returns counts."""
refreshed = 0
failed = 0
due = db.users_due_for_refresh(hours=hours, active_within_days=active_within_days)
for username in due:
try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
user = data.get("user")
if user is None or (isinstance(user, dict) and user.get("message") == "Not Found"):
data = {"error": "not_found"}
db.upsert_user(username, data)
refreshed += 1
except Exception as e:
log.warning("refresh failed for %s: %s", username, e)
failed += 1
gc_removed = db.delete_stale(days=gc_days)
return {"refreshed": refreshed, "failed": failed, "gc_removed": gc_removed}
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
db.init_db()
interval = 3600 # 1h between ticks
while True:
try:
stats = tick(
hours=config.REFRESH_INTERVAL_HOURS,
active_within_days=config.TRIAL_GC_DAYS,
gc_days=config.TRIAL_GC_DAYS,
)
log.info("tick complete: %s", stats)
except Exception:
log.exception("tick failed")
time.sleep(interval)
if __name__ == "__main__":
main()
+121
View File
@@ -0,0 +1,121 @@
"""SQLite repository for the fetcher service.
Single table: users (raw GitHub payloads keyed by username).
Uses WAL mode so concurrent readers don't block the writer.
"""
import hashlib
import json
import os
import sqlite3
from contextlib import contextmanager
from datetime import datetime, timedelta
from typing import Optional
from . import config
DB_PATH = config.DB_PATH
SCHEMA_SQL = """
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
data_json TEXT NOT NULL,
payload_hash TEXT NOT NULL,
fetched_at TEXT NOT NULL,
last_requested_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_users_fetched_at ON users(fetched_at);
CREATE INDEX IF NOT EXISTS idx_users_last_requested_at ON users(last_requested_at);
"""
def _now() -> str:
return datetime.utcnow().isoformat(timespec="seconds") + "Z"
@contextmanager
def _connect():
os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True)
conn = sqlite3.connect(DB_PATH, timeout=10)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA foreign_keys=ON")
conn.execute("PRAGMA busy_timeout=5000")
try:
yield conn
conn.commit()
finally:
conn.close()
def init_db() -> None:
with _connect() as c:
c.executescript(SCHEMA_SQL)
c.commit()
def payload_hash(data: dict) -> str:
canonical = json.dumps(data, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def upsert_user(username: str, data: dict) -> str:
h = payload_hash(data)
now = _now()
with _connect() as c:
c.execute(
"""INSERT INTO users(username, data_json, payload_hash, fetched_at, last_requested_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(username) DO UPDATE SET
data_json = excluded.data_json,
payload_hash = excluded.payload_hash,
fetched_at = excluded.fetched_at""",
(username, json.dumps(data), h, now, now),
)
c.commit()
return h
def get_user(username: str) -> Optional[dict]:
"""Returns {data, payload_hash, fetched_at, last_requested_at} or None. Updates last_requested_at."""
now = _now()
with _connect() as c:
row = c.execute(
"SELECT data_json, payload_hash, fetched_at, last_requested_at FROM users WHERE username=?",
(username,),
).fetchone()
if row is None:
return None
c.execute("UPDATE users SET last_requested_at=? WHERE username=?", (now, username))
c.commit()
return {
"data": json.loads(row["data_json"]),
"payload_hash": row["payload_hash"],
"fetched_at": row["fetched_at"],
"last_requested_at": now,
}
def delete_stale(days: int) -> int:
cutoff = (datetime.utcnow() - timedelta(days=days)).isoformat(timespec="seconds") + "Z"
with _connect() as c:
cur = c.execute("DELETE FROM users WHERE last_requested_at < ?", (cutoff,))
c.commit()
return cur.rowcount
def users_due_for_refresh(hours: int, active_within_days: int) -> list[str]:
"""Return usernames with fetched_at older than `hours` and last_requested_at within `active_within_days`."""
stale_before = (datetime.utcnow() - timedelta(hours=hours)).isoformat(timespec="seconds") + "Z"
active_after = (datetime.utcnow() - timedelta(days=active_within_days)).isoformat(timespec="seconds") + "Z"
with _connect() as c:
rows = c.execute(
"SELECT username FROM users WHERE fetched_at < ? AND last_requested_at > ?",
(stale_before, active_after),
).fetchall()
return [r["username"] for r in rows]
def list_usernames() -> list[str]:
with _connect() as c:
return [r["username"] for r in c.execute("SELECT username FROM users ORDER BY username").fetchall()]
+153 -71
View File
@@ -1,25 +1,41 @@
"""GitHub data fetching functions.""" """GitHub data fetching functions."""
import re
import requests import requests
import base64 import base64
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Optional, Protocol from typing import Optional, Protocol
from ..config import ( from . import config
COLLABORATOR_MAX_REPO_SIZE,
COLLABORATOR_TOP_REPOS,
COLLABORATOR_LOOKBACK_DAYS, # GitHub's own username rules: alphanumerics and hyphens, 1–39 chars, no
MEANINGFUL_MIN_COMMITS, # leading/trailing hyphen, no double-hyphens. The fetcher hard-refuses
FORK_MIN_COMMITS, # anything else before it reaches URL construction or GraphQL interpolation —
OWNER_BOOST, # the generator validates too, but this is the last line of defense before
MIN_SHARED_REPOS, # we talk to GitHub on a caller's behalf.
DEEP_COLLAB_THRESHOLD, _USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
SMALL_OWNED_REPO_SIZE,
COMMIT_MAX_REPOS, # Repo full names: owner/repo. Owner matches the username rule; repo allows the
COMMIT_PER_REPO, # same chars plus dot and underscore (matches GitHub's repo-name regex).
API_TIMEOUT, _REPO_FULL_NAME_RE = re.compile(
r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}"
r"/[A-Za-z0-9_.-]{1,100}$"
) )
def _assert_username(name: str) -> str:
if not isinstance(name, str) or not _USERNAME_RE.match(name):
raise ValueError(f"invalid github username: {name!r}")
return name
def _assert_repo_full_name(name: str) -> str:
if not isinstance(name, str) or not _REPO_FULL_NAME_RE.match(name):
raise ValueError(f"invalid github repo name: {name!r}")
return name
class GitHubDataSource(Protocol): class GitHubDataSource(Protocol):
"""Protocol for GitHub data sources - allows swapping implementations.""" """Protocol for GitHub data sources - allows swapping implementations."""
@@ -59,6 +75,10 @@ class GitHubDataSource(Protocol):
"""Fetch and encode avatar as base64.""" """Fetch and encode avatar as base64."""
... ...
def fetch_repo_languages(self, full_name: str) -> dict:
"""Return {language: bytes} for a single repo, or {} on failure."""
...
class DirectAPISource: class DirectAPISource:
"""Direct GitHub API implementation - for immediate requests.""" """Direct GitHub API implementation - for immediate requests."""
@@ -91,7 +111,7 @@ class DirectAPISource:
"https://api.github.com/graphql", "https://api.github.com/graphql",
json=payload, json=payload,
headers=headers, headers=headers,
timeout=API_TIMEOUT, timeout=config.API_TIMEOUT,
) )
except Exception as e: except Exception as e:
print(f" GraphQL request failed: {e}") print(f" GraphQL request failed: {e}")
@@ -109,18 +129,22 @@ class DirectAPISource:
def fetch_user_data(self, username: str) -> dict: def fetch_user_data(self, username: str) -> dict:
"""Fetch user profile data.""" """Fetch user profile data."""
_assert_username(username)
return requests.get( return requests.get(
f"{self.base}/users/{username}", f"{self.base}/users/{username}",
headers=self.headers headers=self.headers,
timeout=config.API_TIMEOUT,
).json() ).json()
def fetch_repos(self, username: str) -> list: def fetch_repos(self, username: str) -> list:
"""Fetch user repositories (owned + contributed to).""" """Fetch user repositories (owned + contributed to)."""
_assert_username(username)
# Fetch owned repos # Fetch owned repos
owned = requests.get( owned = requests.get(
f"{self.base}/users/{username}/repos", f"{self.base}/users/{username}/repos",
headers=self.headers, headers=self.headers,
params={"per_page": 100, "sort": "pushed", "type": "owner"}, params={"per_page": 100, "sort": "pushed", "type": "owner"},
timeout=config.API_TIMEOUT,
).json() ).json()
# Fetch all repos (includes collabs, orgs) # Fetch all repos (includes collabs, orgs)
@@ -128,6 +152,7 @@ class DirectAPISource:
f"{self.base}/users/{username}/repos", f"{self.base}/users/{username}/repos",
headers=self.headers, headers=self.headers,
params={"per_page": 100, "sort": "pushed", "type": "all"}, params={"per_page": 100, "sort": "pushed", "type": "all"},
timeout=config.API_TIMEOUT,
).json() ).json()
# Combine and deduplicate # Combine and deduplicate
@@ -144,10 +169,12 @@ class DirectAPISource:
def fetch_events(self, username: str) -> list: def fetch_events(self, username: str) -> list:
"""Fetch user events.""" """Fetch user events."""
_assert_username(username)
resp = requests.get( resp = requests.get(
f"{self.base}/users/{username}/events", f"{self.base}/users/{username}/events",
headers=self.headers, headers=self.headers,
params={"per_page": 100}, params={"per_page": 100},
timeout=config.API_TIMEOUT,
).json() ).json()
return resp if isinstance(resp, list) else [] return resp if isinstance(resp, list) else []
@@ -168,28 +195,33 @@ class DirectAPISource:
from datetime import datetime from datetime import datetime
try: try:
_assert_username(username)
# Get the last year of contribution data # Get the last year of contribution data
now = datetime.now() now = datetime.now()
one_year_ago = now.replace(year=now.year - 1) one_year_ago = now.replace(year=now.year - 1)
from_date = one_year_ago.strftime("%Y-%m-%dT%H:%M:%SZ") from_date = one_year_ago.strftime("%Y-%m-%dT%H:%M:%SZ")
to_date = now.strftime("%Y-%m-%dT%H:%M:%SZ") to_date = now.strftime("%Y-%m-%dT%H:%M:%SZ")
query = f''' # Parameterize username + date range — interpolating username into
query {{ # the query lets a malicious name break out of the string literal
user(login: "{username}") {{ # and smuggle additional GraphQL fields. GitHub's PAT scopes bound
contributionsCollection(from: "{from_date}", to: "{to_date}") {{ # the damage, but the injection is still worth shutting down.
contributionCalendar {{ query = """
weeks {{ query($login: String!, $from: DateTime!, $to: DateTime!) {
contributionDays {{ user(login: $login) {
contributionsCollection(from: $from, to: $to) {
contributionCalendar {
weeks {
contributionDays {
date date
contributionCount contributionCount
}} }
}} }
}} }
}} }
}} }
}} }
''' """
headers = { headers = {
**self.headers, **self.headers,
@@ -201,9 +233,12 @@ class DirectAPISource:
resp = requests.post( resp = requests.post(
'https://api.github.com/graphql', 'https://api.github.com/graphql',
json={'query': query}, json={
'query': query,
'variables': {'login': username, 'from': from_date, 'to': to_date},
},
headers=headers, headers=headers,
timeout=API_TIMEOUT timeout=config.API_TIMEOUT
) )
if not resp.ok: if not resp.ok:
@@ -266,6 +301,7 @@ class DirectAPISource:
"""Fetch all-time contribution count using GraphQL.""" """Fetch all-time contribution count using GraphQL."""
from datetime import datetime from datetime import datetime
_assert_username(username)
# First, get account creation date # First, get account creation date
query = ''' query = '''
query($username: String!) { query($username: String!) {
@@ -287,7 +323,7 @@ class DirectAPISource:
'https://api.github.com/graphql', 'https://api.github.com/graphql',
json={'query': query, 'variables': {'username': username}}, json={'query': query, 'variables': {'username': username}},
headers=headers, headers=headers,
timeout=API_TIMEOUT timeout=config.API_TIMEOUT
) )
if not resp.ok or 'data' not in resp.json(): if not resp.ok or 'data' not in resp.json():
@@ -305,24 +341,28 @@ class DirectAPISource:
# Fetch year by year # Fetch year by year
total_contributions = 0 total_contributions = 0
print(f" Fetching contributions from {created_year} to {current_year}...") print(f" Fetching contributions from {created_year} to {current_year}...")
year_query = """
query($login: String!, $from: DateTime!, $to: DateTime!) {
user(login: $login) {
contributionsCollection(from: $from, to: $to) {
contributionCalendar { totalContributions }
}
}
}
"""
for year in range(created_year, current_year + 1): for year in range(created_year, current_year + 1):
year_query = f'''
query {{
user(login: "{username}") {{
contributionsCollection(from: "{year}-01-01T00:00:00Z", to: "{year}-12-31T23:59:59Z") {{
contributionCalendar {{
totalContributions
}}
}}
}}
}}
'''
year_resp = requests.post( year_resp = requests.post(
'https://api.github.com/graphql', 'https://api.github.com/graphql',
json={'query': year_query}, json={
'query': year_query,
'variables': {
'login': username,
'from': f"{year}-01-01T00:00:00Z",
'to': f"{year}-12-31T23:59:59Z",
},
},
headers=headers, headers=headers,
timeout=API_TIMEOUT timeout=config.API_TIMEOUT,
) )
if year_resp.ok: if year_resp.ok:
@@ -343,21 +383,20 @@ class DirectAPISource:
"""Fetch contribution count for a specific date range using GraphQL.""" """Fetch contribution count for a specific date range using GraphQL."""
from datetime import datetime from datetime import datetime
_assert_username(username)
# Convert since_date to proper format # Convert since_date to proper format
from_date = f"{since_date}T00:00:00Z" from_date = f"{since_date}T00:00:00Z"
to_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ") to_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
query = f''' query = """
query {{ query($login: String!, $from: DateTime!, $to: DateTime!) {
user(login: "{username}") {{ user(login: $login) {
contributionsCollection(from: "{from_date}", to: "{to_date}") {{ contributionsCollection(from: $from, to: $to) {
contributionCalendar {{ contributionCalendar { totalContributions }
totalContributions }
}} }
}} }
}} """
}}
'''
headers = { headers = {
**self.headers, **self.headers,
@@ -369,9 +408,12 @@ class DirectAPISource:
resp = requests.post( resp = requests.post(
'https://api.github.com/graphql', 'https://api.github.com/graphql',
json={'query': query}, json={
'query': query,
'variables': {'login': username, 'from': from_date, 'to': to_date},
},
headers=headers, headers=headers,
timeout=API_TIMEOUT timeout=config.API_TIMEOUT,
) )
if resp.ok: if resp.ok:
@@ -401,7 +443,7 @@ class DirectAPISource:
f"{self.base}/search/issues", f"{self.base}/search/issues",
headers=self.headers, headers=self.headers,
params={"q": query, "per_page": 1}, params={"q": query, "per_page": 1},
timeout=API_TIMEOUT timeout=config.API_TIMEOUT
) )
if resp.ok: if resp.ok:
@@ -428,7 +470,7 @@ class DirectAPISource:
f"{self.base}/repos/{repo_name}/contributors", f"{self.base}/repos/{repo_name}/contributors",
headers=self.headers, headers=self.headers,
params={"per_page": 100}, params={"per_page": 100},
timeout=API_TIMEOUT timeout=config.API_TIMEOUT
) )
if resp.ok: if resp.ok:
@@ -508,13 +550,29 @@ class DirectAPISource:
def fetch_avatar(self, avatar_url: str) -> str: def fetch_avatar(self, avatar_url: str) -> str:
"""Fetch and encode avatar as base64.""" """Fetch and encode avatar as base64."""
try: try:
resp = requests.get(avatar_url + "&s=64", timeout=API_TIMEOUT) resp = requests.get(avatar_url + "&s=64", timeout=config.API_TIMEOUT)
if resp.ok: if resp.ok:
return base64.b64encode(resp.content).decode("ascii") return base64.b64encode(resp.content).decode("ascii")
except Exception: except Exception:
pass pass
return "" return ""
def fetch_repo_languages(self, full_name: str) -> dict:
"""Return {language: bytes} for a repo. REST returns exactly this
shape — total is summed client-side."""
try:
resp = requests.get(
f"{self.base}/repos/{full_name}/languages",
headers=self.headers,
timeout=config.API_TIMEOUT,
)
if resp.ok:
data = resp.json()
return data if isinstance(data, dict) else {}
except Exception:
pass
return {}
# TODO: Future implementation for queue-based batching # TODO: Future implementation for queue-based batching
# class QueuedAPISource: # class QueuedAPISource:
@@ -555,6 +613,12 @@ def fetch_github_data(
events = source.fetch_events(username) events = source.fetch_events(username)
commits = source.fetch_commits(username) commits = source.fetch_commits(username)
# Attach per-repo language byte breakdown. Without this, the languages
# widget falls back to a primary-language repo-count tally, which
# heavily under-represents repos whose primary language has small files
# (e.g. HTML, Jupyter Notebook).
_enrich_repo_languages(repos, source)
# Fetch contribution counts (commits + PRs + issues + reviews) # Fetch contribution counts (commits + PRs + issues + reviews)
print(" Fetching all-time contribution count...") print(" Fetching all-time contribution count...")
total_commits = source.fetch_commit_count(username, repos) total_commits = source.fetch_commit_count(username, repos)
@@ -591,6 +655,24 @@ def fetch_github_data(
} }
def _enrich_repo_languages(repos: list, source: GitHubDataSource) -> None:
"""Mutates `repos` in-place, attaching `language_bytes: {lang: bytes}` to
each repo. Uses a small thread pool — one REST call per repo is cheap
individually, but sequentially N repos would block the fetch noticeably."""
if not repos:
return
names = [(i, r["full_name"]) for i, r in enumerate(repos) if r.get("full_name")]
print(f" Fetching language byte breakdown for {len(names)} repos...")
with ThreadPoolExecutor(max_workers=10) as pool:
futures = {pool.submit(source.fetch_repo_languages, fn): i for i, fn in names}
for fut in as_completed(futures):
i = futures[fut]
try:
repos[i]["language_bytes"] = fut.result() or {}
except Exception:
repos[i]["language_bytes"] = {}
def _fetch_collaborators_data( def _fetch_collaborators_data(
username: str, username: str,
repos: list, repos: list,
@@ -627,7 +709,7 @@ def _fetch_collaborators_data(
low = login.lower() low = login.lower()
return low in BOT_LOGINS or low.endswith("[bot]") or low.endswith("-bot") return low in BOT_LOGINS or low.endswith("[bot]") or low.endswith("-bot")
since = (datetime.now() - timedelta(days=COLLABORATOR_LOOKBACK_DAYS)).strftime("%Y-%m-%d") since = (datetime.now() - timedelta(days=config.COLLABORATOR_LOOKBACK_DAYS)).strftime("%Y-%m-%d")
commit_repos = source.fetch_user_commit_repos(username, since) commit_repos = source.fetch_user_commit_repos(username, since)
if not commit_repos: if not commit_repos:
return [] return []
@@ -636,15 +718,15 @@ def _fetch_collaborators_data(
qualifying = [] qualifying = []
for r in commit_repos: for r in commit_repos:
user_commits = r.get("user_commits", 0) user_commits = r.get("user_commits", 0)
if user_commits < MEANINGFUL_MIN_COMMITS: if user_commits < config.MEANINGFUL_MIN_COMMITS:
continue continue
if r.get("is_fork") and user_commits < FORK_MIN_COMMITS: if r.get("is_fork") and user_commits < config.FORK_MIN_COMMITS:
continue continue
qualifying.append(r) qualifying.append(r)
# Rank user's repos by their own commit count, scan top N # Rank user's repos by their own commit count, scan top N
qualifying.sort(key=lambda r: -r.get("user_commits", 0)) qualifying.sort(key=lambda r: -r.get("user_commits", 0))
qualifying = qualifying[:COLLABORATOR_TOP_REPOS] qualifying = qualifying[:config.COLLABORATOR_TOP_REPOS]
print(f" Scoring collaborators across {len(qualifying)} qualifying repos") print(f" Scoring collaborators across {len(qualifying)} qualifying repos")
# Step 3+4: fetch contributors and score # Step 3+4: fetch contributors and score
@@ -652,17 +734,17 @@ def _fetch_collaborators_data(
for r in qualifying: for r in qualifying:
full_name = r["full_name"] full_name = r["full_name"]
user_commits = r["user_commits"] user_commits = r["user_commits"]
boost = OWNER_BOOST if r["is_owner"] else 1.0 boost = config.OWNER_BOOST if r["is_owner"] else 1.0
contributors = source.fetch_repo_contributors(full_name, min_commits=1) contributors = source.fetch_repo_contributors(full_name, min_commits=1)
# Drop huge OSS projects # Drop huge OSS projects
if len(contributors) >= COLLABORATOR_MAX_REPO_SIZE: if len(contributors) >= config.COLLABORATOR_MAX_REPO_SIZE:
print(f" skipping {full_name}: too many contributors ({len(contributors)})") print(f" skipping {full_name}: too many contributors ({len(contributors)})")
continue continue
# A "tight" repo: one the user owns with few contributors — hackathon # A "tight" repo: one the user owns with few contributors — hackathon
# and side-project partners qualify from a single such repo. # and side-project partners qualify from a single such repo.
is_tight_owned = r["is_owner"] and len(contributors) <= SMALL_OWNED_REPO_SIZE is_tight_owned = r["is_owner"] and len(contributors) <= config.SMALL_OWNED_REPO_SIZE
for c in contributors: for c in contributors:
login = c.get("login", "") login = c.get("login", "")
@@ -705,8 +787,8 @@ def _fetch_collaborators_data(
# or a partner in a tight user-owned project (hackathon/side-project). # or a partner in a tight user-owned project (hackathon/side-project).
filtered = [ filtered = [
s for s in scored s for s in scored
if s["shared_repos"] >= MIN_SHARED_REPOS if s["shared_repos"] >= config.MIN_SHARED_REPOS
or s["raw_score"] >= DEEP_COLLAB_THRESHOLD or s["raw_score"] >= config.DEEP_COLLAB_THRESHOLD
or s["tight_owned_partner"] or s["tight_owned_partner"]
] ]
View File
+73
View File
@@ -0,0 +1,73 @@
import os
import tempfile
import pytest
import responses as resp_lib
from src import db as dbmod
from src import api as apimod
@pytest.fixture
def client(monkeypatch):
with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db"))
monkeypatch.setattr(apimod.config, "INTERNAL_TOKEN", "secret")
monkeypatch.setattr(apimod.config, "GITHUB_PAT", "ghp_test")
dbmod.init_db()
app = apimod.app
app.config["TESTING"] = True
with app.test_client() as c:
yield c
def test_health_no_auth_required(client):
r = client.get("/health")
assert r.status_code == 200
assert r.get_json()["service"] == "fetcher"
def test_endpoints_require_internal_token(client):
r = client.get("/data/alice")
assert r.status_code == 401
@resp_lib.activate
def test_data_auto_fetches_on_miss(client, monkeypatch):
# fetch_commits: contributionCalendar/weeks
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, status=200)
# fetch_commit_count (alltime) — first call: get createdAt
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}}, status=200)
# fetch_commit_count (alltime) — per-year contribution totals (2020–2026, 7 years)
for _ in range(7):
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}},
status=200)
# fetch_commit_count (recent, last 6 months)
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}},
status=200)
# fetch_user_commit_repos (for collaborators)
resp_lib.add(resp_lib.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}},
status=200)
# PR count search
resp_lib.add(resp_lib.GET, "https://api.github.com/search/issues",
json={"total_count": 0, "items": []}, status=200)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice",
json={"login": "alice", "public_repos": 1, "followers": 0, "avatar_url": "https://avatars.example/a"}, status=200)
# fetch_repos: two calls (owner + all)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200)
resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/events", json=[], status=200)
r = client.get("/data/alice", headers={"X-Internal-Token": "secret"})
assert r.status_code == 200
body = r.get_json()
assert body["payload_hash"]
assert body["data"]["user"]["login"] == "alice"
def test_force_fetch_requires_auth(client):
r = client.post("/fetch", json={"username": "alice"})
assert r.status_code == 401
+35
View File
@@ -0,0 +1,35 @@
import os
import tempfile
import pytest
from unittest.mock import patch
from src import db as dbmod
from src import cron as cronmod
@pytest.fixture
def tmp_db(monkeypatch):
with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db"))
dbmod.init_db()
yield
def test_refresh_tick_calls_github_for_due_users(tmp_db):
dbmod.upsert_user("alice", {"user": {"login": "alice"}})
# Backdate
with dbmod._connect() as c:
c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z', last_requested_at=? WHERE username='alice'",
(dbmod._now(),))
with patch("src.cron.github.fetch_github_data", return_value={"user": {"login": "alice", "updated": True}}) as gh:
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
assert gh.called
assert stats["refreshed"] == 1
def test_tick_runs_gc_for_abandoned_trial_users(tmp_db):
dbmod.upsert_user("ghost", {"user": {"login": "ghost"}})
with dbmod._connect() as c:
c.execute("UPDATE users SET last_requested_at='2020-01-01T00:00:00Z' WHERE username='ghost'")
stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7)
assert stats["gc_removed"] == 1
assert dbmod.get_user("ghost") is None
+65
View File
@@ -0,0 +1,65 @@
import os
import tempfile
import pytest
from src import db as dbmod
@pytest.fixture
def tmp_db(monkeypatch):
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "t.db")
monkeypatch.setattr(dbmod, "DB_PATH", path)
dbmod.init_db()
yield path
def test_init_creates_schema_with_wal(tmp_db):
with dbmod._connect() as c:
mode = c.execute("PRAGMA journal_mode").fetchone()[0]
assert mode.lower() == "wal"
cols = [r[1] for r in c.execute("PRAGMA table_info(users)").fetchall()]
assert set(cols) == {"username", "data_json", "payload_hash",
"fetched_at", "last_requested_at"}
def test_upsert_and_get_round_trip(tmp_db):
dbmod.upsert_user("alice", {"user": {"login": "alice"}, "repos": []})
row = dbmod.get_user("alice")
assert row["data"]["user"]["login"] == "alice"
assert row["payload_hash"]
assert row["fetched_at"]
def test_payload_hash_is_deterministic_and_changes_on_diff():
h1 = dbmod.payload_hash({"a": 1, "b": 2})
h2 = dbmod.payload_hash({"b": 2, "a": 1})
h3 = dbmod.payload_hash({"a": 1, "b": 3})
assert h1 == h2
assert h1 != h3
def test_get_updates_last_requested_at(tmp_db):
dbmod.upsert_user("alice", {"user": {"login": "alice"}})
first = dbmod.get_user("alice")["last_requested_at"]
import time; time.sleep(1.1)
second = dbmod.get_user("alice")["last_requested_at"]
assert second > first
def test_delete_stale_removes_old_rows(tmp_db):
dbmod.upsert_user("ghost", {"user": {"login": "ghost"}})
# Manually backdate last_requested_at
with dbmod._connect() as c:
c.execute("UPDATE users SET last_requested_at='2020-01-01T00:00:00Z' WHERE username='ghost'")
removed = dbmod.delete_stale(days=7)
assert removed == 1
assert dbmod.get_user("ghost") is None
def test_users_due_for_refresh(tmp_db):
dbmod.upsert_user("alice", {"user": {"login": "alice"}})
# Backdate fetched_at so alice is due
with dbmod._connect() as c:
c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z' WHERE username='alice'")
due = dbmod.users_due_for_refresh(hours=24, active_within_days=7)
assert "alice" in due
+88
View File
@@ -0,0 +1,88 @@
import responses
import pytest
from src import github
@responses.activate
def test_fetch_user_data_returns_user_payload():
# fetch_commits: contributionCalendar/weeks
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}},
status=200,
)
# fetch_commit_count (alltime) — first call: get createdAt
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}},
status=200,
)
# fetch_commit_count (alltime) — per-year contribution totals (2020–2026)
for _ in range(7):
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}},
status=200,
)
# fetch_commit_count (recent, last 6 months)
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}},
status=200,
)
# fetch_user_commit_repos (for collaborators)
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}},
status=200,
)
# PR count search
responses.add(
responses.GET, "https://api.github.com/search/issues",
json={"total_count": 0, "items": []},
status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/alice",
json={"login": "alice", "public_repos": 3, "followers": 5, "avatar_url": "https://avatars.example/1"},
status=200,
)
# fetch_repos: two calls (owner + all)
responses.add(
responses.GET, "https://api.github.com/users/alice/repos",
json=[], status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/alice/repos",
json=[], status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/alice/events",
json=[], status=200,
)
data = github.fetch_github_data("alice", token="t")
assert data["user"]["login"] == "alice"
assert "repos" in data
assert "events" in data
@responses.activate
def test_fetch_handles_404():
responses.add(
responses.GET, "https://api.github.com/users/nope",
json={"message": "Not Found"}, status=404,
)
responses.add(
responses.POST, "https://api.github.com/graphql",
json={"data": {"user": None}}, status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/nope/repos",
json={"message": "Not Found"}, status=404,
)
responses.add(
responses.GET, "https://api.github.com/users/nope/events",
json={"message": "Not Found"}, status=404,
)
data = github.fetch_github_data("nope", token="t")
assert data["user"].get("message") == "Not Found" or data["user"] is None
+27
View File
@@ -0,0 +1,27 @@
# --- stage 1: build the React SPA ---
FROM node:20-alpine AS frontend-build
WORKDIR /app/frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
ARG VITE_GENERATOR_URL=""
ARG VITE_EDGE_URL=""
ENV VITE_GENERATOR_URL=$VITE_GENERATOR_URL
ENV VITE_EDGE_URL=$VITE_EDGE_URL
RUN npm run build
# --- stage 2: python runtime ---
FROM python:3.11-slim AS runtime
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY src ./src
RUN mkdir -p /app/src/static /app/data
COPY --from=frontend-build /app/frontend/dist/ /app/src/static/
EXPOSE 5002
ENV GENERATOR_SETTINGS_DB_PATH=/app/data/settings.db
ENV GENERATOR_WIDGETS_DB_PATH=/app/data/widgets.db
CMD ["gunicorn", "-b", "0.0.0.0:5002", "-w", "2", "src.api:app"]
+56
View File
@@ -0,0 +1,56 @@
# Generator Service
Serves precomputed SVGs to the public internet. Holds user settings and
the widgets cache. Runs a build worker + cron in the background. Also
serves the React SPA (frontend sources live under `frontend/`).
## Run locally (3 processes)
cd generator
pip install -r requirements.txt
# API
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.api
# Build worker
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.worker
# Poll cron
FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.cron
## Frontend (dev)
cd generator/frontend && npm install && npm run dev
# Vite dev server proxies /api to the Flask app.
## Test
cd generator && pytest
## Docker
Multi-stage (builds the frontend with node, serves everything from Python):
docker build -t ghstats-generator .
docker run --rm -e FETCHER_URL=http://fetcher:5001 -e FETCHER_INTERNAL_TOKEN=dev \
-p 5002:5002 -v $(pwd)/data:/app/data ghstats-generator
# Worker: override CMD to ["python","-m","src.worker"]
# Cron: override CMD to ["python","-m","src.cron"]
## Endpoints
All API endpoints are under `/api/`. The root and `/assets/*` serve the SPA.
| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /api/health | none | health |
| GET | /api/<u> | none | composite SVG; auto-enrolls unknown users |
| GET | /api/<u>/<w>.svg | none | individual widget SVG |
| POST | /api/enroll | none | explicit enroll (body: {username}) |
| GET | /api/<u>/settings | stub | current settings |
| PATCH | /api/<u>/settings | stub | update settings (enqueues rebuild) |
| POST | /api/<u>/refresh | stub | one-shot re-fetch + rebuild |
Responses carry `X-Widget-Status: ready | building | rate_limited | not_found`.
## Env
See `src/config.py`.
View File
+2
View File
@@ -0,0 +1,2 @@
VITE_GENERATOR_URL=http://localhost:5002
VITE_EDGE_URL=http://localhost:5003
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+17
View File
@@ -0,0 +1,17 @@
# Frontend (Vite + React)
Part of the generator service. Sources live here; the production build
is served as static files by the generator's Flask app (at `/`) and
produced by the generator's Dockerfile.
## Dev
npm install
VITE_GENERATOR_URL=http://localhost:5002 VITE_EDGE_URL=http://localhost:5003 npm run dev
Vite proxies `/api/*` to the Flask app at :5002.
## Build
npm run build
# produces dist/ which is copied into generator/src/static/ by the Docker build
+23
View File
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>GitHub Widgets</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+34
View File
@@ -0,0 +1,34 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"dompurify": "^3.4.0",
"react": "^19.2.4",
"react-dom": "^19.2.4"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@tailwindcss/vite": "^4.2.2",
"@types/dompurify": "^3.0.5",
"@types/node": "^24.12.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"tailwindcss": "^4.2.2",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.0",
"vite": "^8.0.4"
}
}
+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
<rect width="64" height="64" rx="14" ry="14" fill="#121820"/>
<text x="32" y="47"
text-anchor="middle"
font-family="'Instrument Serif', Georgia, 'Times New Roman', serif"
font-size="46"
font-style="italic"
fill="#f5f1e8">G</text>
</svg>

After

Width:  |  Height:  |  Size: 365 B

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+1
View File
@@ -0,0 +1 @@
/* Intentionally empty — all styles use Tailwind */
+238
View File
@@ -0,0 +1,238 @@
import { useState, useRef, useCallback, useEffect } from 'react'
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'
export type Achievement = {
title: string
subtitle: string
event_date: string
icon: string
}
export type PerWidgetSettings = {
grade?: { max_tags?: number }
impact?: { line_color?: string }
collaborators?: { max_count?: number; bar_color?: string }
focus?: { max_categories?: number }
languages?: { max_languages?: number }
achievements?: { max_items?: number }
}
export type WidgetSettings = {
theme: string
widgets: string[]
impactPeriod: string
customTags: string[]
hiddenLanguages: string[]
achievements: Achievement[]
widgetSettings: PerWidgetSettings
}
const DEFAULT_SETTINGS: WidgetSettings = {
theme: 'midnight',
widgets: ['grade', 'impact', 'collaborators', 'focus', 'languages'],
impactPeriod: '6mo',
customTags: [],
hiddenLanguages: [],
achievements: [],
widgetSettings: {},
}
type Step = 'search' | 'workshop' | 'result'
const POLL_INTERVAL_MS = 2000
const POLL_TIMEOUT_MS = 120_000
export default function App() {
const [me, setMe] = useState<Me>({ login: null })
const [step, setStep] = useState<Step>('search')
const [username, setUsername] = useState('')
const [settings, setSettings] = useState<WidgetSettings>({ ...DEFAULT_SETTINGS })
const [widgetData, setWidgetData] = useState<WidgetData | null>(null)
const [fetchDone, setFetchDone] = useState(false)
const [fetchError, setFetchError] = useState<string | null>(null)
// Final SVG produced by POST /api/<u>/generate. Rendered on the Result
// screen so the user sees the actual backend output, not demo data.
const [generatedSvg, setGeneratedSvg] = useState<string | null>(null)
const [generateError, setGenerateError] = useState<string | null>(null)
const [generating, setGenerating] = useState(false)
const pollTimer = useRef<number | null>(null)
const pollStart = useRef<number>(0)
const aborted = useRef(false)
const stopPolling = useCallback(() => {
if (pollTimer.current != null) {
window.clearTimeout(pollTimer.current)
pollTimer.current = null
}
}, [])
useEffect(() => stopPolling, [stopPolling])
useEffect(() => { fetchMe().then(setMe) }, [])
const startFetch = useCallback((user: string) => {
stopPolling()
aborted.current = false
pollStart.current = Date.now()
setFetchDone(false)
setFetchError(null)
// Show demo data immediately so Workshop is interactive while the worker builds.
setWidgetData(DEMO_WIDGET_DATA)
const poll = async () => {
if (aborted.current) return
try {
const r = await fetch(`/api/${encodeURIComponent(user)}/data`)
if (aborted.current) return
const body = await r.json().catch(
() => ({} as { status?: string; data?: WidgetData })
)
const status = body.status
if (r.status === 200 && status === 'ready' && body.data) {
setWidgetData(body.data)
setFetchDone(true)
return
}
if (r.status === 404 || status === 'not_found') {
setFetchError('User not found')
setFetchDone(true)
return
}
if (r.status === 429 || status === 'rate_limited') {
setFetchError('Enrollment limit reached — try again tomorrow')
setFetchDone(true)
return
}
// 202 building (or any non-terminal) — poll again until timeout.
if (Date.now() - pollStart.current > POLL_TIMEOUT_MS) {
setFetchError('Still building — refresh to keep waiting')
setFetchDone(true)
return
}
pollTimer.current = window.setTimeout(poll, POLL_INTERVAL_MS)
} catch (e) {
if (aborted.current) return
console.warn('Data poll failed:', e)
setFetchError('Network error')
setFetchDone(true)
}
}
poll()
}, [stopPolling])
const handleSearch = (user: string) => {
setUsername(user)
startFetch(user)
setStep('workshop')
}
const handleGenerate = async () => {
setStep('result')
setGenerating(true)
setGeneratedSvg(null)
setGenerateError(null)
try {
// Push the user's Workshop choices to the backend BEFORE rendering.
// The backend's /generate endpoint re-reads settings from SQLite and
// renders with them, so without this PATCH the SVG would reflect
// whatever was last persisted (usually the enroll-time defaults)
// rather than the user's current selections.
const backendSettings = {
theme: settings.theme,
enabled: settings.widgets,
custom_tags: settings.customTags,
hidden_languages: settings.hiddenLanguages,
widget_settings: settings.widgetSettings,
achievements: settings.achievements.filter(a => a.title.trim()),
}
const patchRes = await fetch(`/api/${encodeURIComponent(username)}/settings`, {
method: 'PATCH',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(backendSettings),
})
if (!patchRes.ok && patchRes.status !== 404) {
setGenerateError(`Settings sync failed (HTTP ${patchRes.status})`)
return
}
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')
return
}
if (!r.ok) {
setGenerateError(`Generate failed (HTTP ${r.status})`)
return
}
// Fetch the backend-rendered composite SVG. Cache-bust so regenerate
// after settings change shows the new version, not a stale browser copy.
const svgRes = await fetch(`/api/${encodeURIComponent(username)}?t=${Date.now()}`)
if (!svgRes.ok) {
setGenerateError(`SVG fetch failed (HTTP ${svgRes.status})`)
return
}
setGeneratedSvg(await svgRes.text())
} catch (e) {
console.warn('generate call failed:', e)
setGenerateError('Network error')
} finally {
setGenerating(false)
}
}
const handleBack = () => {
if (step === 'result') setStep('workshop')
else if (step === 'workshop') {
aborted.current = true
stopPolling()
setStep('search')
}
}
return (
<div className="min-h-screen bg-gray-50">
<div className="fixed right-4 top-4 z-50">
<AuthButton me={me} onChange={setMe} />
</div>
{step === 'search' && (
<SearchScreen onSearch={handleSearch} />
)}
{step === 'workshop' && (
<WorkshopScreen
username={username}
settings={settings}
onSettingsChange={setSettings}
onGenerate={handleGenerate}
onBack={handleBack}
fetchDone={fetchDone}
fetchError={fetchError}
widgetData={widgetData}
me={me}
onAuthChange={setMe}
/>
)}
{step === 'result' && (
<ResultScreen
username={username}
generating={generating}
generatedSvg={generatedSvg}
generateError={generateError}
onBack={handleBack}
/>
)}
</div>
)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

@@ -0,0 +1,36 @@
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 (
<a
href={signInUrl()}
className="inline-flex items-center gap-2 rounded-full bg-gray-900 px-4 py-1.5 text-sm font-medium text-white shadow-sm transition hover:bg-gray-800"
>
<svg viewBox="0 0 16 16" fill="currentColor" aria-hidden="true" className="h-4 w-4">
<path d="M8 0C3.58 0 0 3.58 0 8a8 8 0 0 0 5.47 7.59c.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.42 7.42 0 0 1 4 0c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8Z" />
</svg>
Sign in with GitHub
</a>
)
}
return (
<div className="inline-flex items-center gap-2 rounded-full border border-gray-200 bg-white py-1 pr-1 pl-3 text-sm shadow-sm">
{me.avatar_url && (
<img
src={me.avatar_url}
alt=""
className="h-6 w-6 rounded-full object-cover"
/>
)}
<span className="font-medium text-gray-900">{me.login}</span>
<button
onClick={async () => { await signOut(); onChange({ login: null }) }}
className="rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700 transition hover:bg-gray-200"
>
Sign out
</button>
</div>
)
}
+36
View File
@@ -0,0 +1,36 @@
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,100..1000;1,9..40,100..1000&family=Instrument+Serif:ital@0;1&family=JetBrains+Mono:wght@400;500;600&display=swap');
@import "tailwindcss";
@theme {
--font-sans: 'DM Sans', system-ui, sans-serif;
--font-serif: 'Instrument Serif', Georgia, serif;
--font-mono: 'JetBrains Mono', monospace;
}
::-webkit-scrollbar { display: none; }
* { -ms-overflow-style: none; scrollbar-width: none; }
body {
margin: 0;
font-family: 'DM Sans', system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@keyframes fade-in-up {
from { opacity: 0; transform: translateY(16px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-fade-in-up {
animation: fade-in-up 0.5s ease-out both;
}
@keyframes spin-slow {
to { transform: rotate(360deg); }
}
.animate-spin-slow {
animation: spin-slow 1s linear infinite;
}
+20
View File
@@ -0,0 +1,20 @@
export type Me = { login: string | null; avatar_url?: string }
export async function fetchMe(): Promise<Me> {
const r = await fetch('/api/auth/me', { credentials: 'include' })
if (!r.ok) return { login: null }
return r.json() as Promise<Me>
}
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<void> {
await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
})
}
+39
View File
@@ -0,0 +1,39 @@
import type { WidgetData } from './renderWidgets'
// Used to show a fully-populated Workshop preview instantly while the real
// data is building asynchronously on the server. Swapped out when the
// /data endpoint returns status=ready.
export const DEMO_WIDGET_DATA: WidgetData = {
grade: {
grade: 'A',
score: 78,
stats: { commits: 842, prs: 47, stars: 156, repos: 28, followers: 92 },
tags: [
{ tag: 'backend', source: 'earned', confidence: 0.7 },
{ tag: 'frontend', source: 'earned', confidence: 0.55 },
{ tag: 'devops', source: 'earned', confidence: 0.3 },
],
breakdown: {},
},
impact: Array.from({ length: 24 }, (_, i) => ({
week_start: new Date(Date.now() - (23 - i) * 7 * 86400000).toISOString().slice(0, 10),
commits: Math.max(0, Math.round(14 + Math.sin(i * 0.5) * 9 + (i % 3) * 2)),
})),
collaborators: [
{ username: 'alex', shared_repos: 4, shared_commits: 87 },
{ username: 'jordan', shared_repos: 2, shared_commits: 54 },
{ username: 'sam', shared_repos: 3, shared_commits: 31 },
],
focus: [
{ category: 'Backend', percentage: 45, commit_count: 379 },
{ category: 'Frontend', percentage: 30, commit_count: 252 },
{ category: 'DevOps', percentage: 15, commit_count: 126 },
{ category: 'ML', percentage: 10, commit_count: 84 },
],
languages: [
{ language: 'Python', percentage: 42, loc: 12 },
{ language: 'TypeScript', percentage: 28, loc: 8 },
{ language: 'Go', percentage: 18, loc: 5 },
{ language: 'Rust', percentage: 12, loc: 3 },
],
}
+364
View File
@@ -0,0 +1,364 @@
import { THEMES, TAG_COLORS, GRADE_COLORS, FOCUS_COLORS, LANG_COLORS, type Theme } from './themes'
// --- Types matching the API `format=data` response ---
export type GradeData = {
grade: string; score: number
stats: Record<string, number>
tags: { tag: string; source: string; confidence: number; label?: string | null }[]
breakdown: Record<string, number>
}
export type ImpactWeek = { week_start: string; commits: number }
export type CollaboratorData = { username: string; shared_repos: number; shared_commits: number }
export type FocusCategory = { category: string; percentage: number; commit_count: number }
export type LanguageData = { language: string; percentage: number; loc: number }
export type AchievementInput = { title: string; subtitle: string; event_date: string; icon: string }
export type WidgetData = {
grade?: GradeData
impact?: ImpactWeek[]
collaborators?: CollaboratorData[]
focus?: FocusCategory[]
languages?: LanguageData[]
}
export type PerWidgetSettings = {
grade?: { max_tags?: number }
impact?: { line_color?: string }
collaborators?: { max_count?: number; bar_color?: string }
focus?: { max_categories?: number }
languages?: { max_languages?: number }
achievements?: { max_items?: number }
}
// --- Helpers ---
const esc = (s: string) => s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;')
const font = '-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif'
const TAG_ACRONYMS = new Set(['ml','ai','ui','ux','api','cli','sql','css','html','js','ios'])
function formatTagLabel(tag: string): string {
return tag.split('-')
.map(w => TAG_ACRONYMS.has(w.toLowerCase())
? w.toUpperCase()
: w.charAt(0).toUpperCase() + w.slice(1))
.join(' ')
}
function cardWrapper(inner: string, w: number, h: number, t: Theme, title: string, prefix = '') {
const sid = `${prefix}shadow`
return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" fill="none">
<defs><filter id="${sid}" x="-2%" y="-2%" width="104%" height="104%"><feDropShadow dx="0" dy="1" stdDeviation="2" flood-color="#000" flood-opacity="0.15"/></filter></defs>
<rect x="1" y="1" width="${w-2}" height="${h-2}" rx="10" ry="10" fill="${t.card_bg}" stroke="${t.card_border}" stroke-width="1" filter="url(#${sid})"/>
${title ? `<text x="20" y="30" font-family="${font}" font-size="11" font-weight="600" fill="${t.text_secondary}" letter-spacing="0.8" opacity="0.7">${esc(title.toUpperCase())}</text>` : ''}
<g transform="translate(0, ${title ? 36 : 0})">${inner}</g>
</svg>`
}
function iconSvg(kind: string, color: string): string {
const icons: Record<string, string> = {
commits: `<circle cx="7" cy="7" r="3" fill="none" stroke="${color}" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="${color}"/><line x1="7" y1="10" x2="7" y2="14" stroke="${color}" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="${color}" stroke-width="1.4"/>`,
prs: `<circle cx="4" cy="4" r="2" fill="none" stroke="${color}" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="${color}" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="${color}" stroke-width="1.2"/>`,
stars: `<path d="M7 1l1.8 3.6 4 .6-2.9 2.8.7 4L7 10.2 3.4 12l.7-4L1.2 5.2l4-.6z" fill="none" stroke="${color}" stroke-width="1.2" stroke-linejoin="round"/>`,
repos: `<rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="${color}" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="${color}" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="${color}" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="${color}" stroke-width="1"/>`,
followers: `<circle cx="5" cy="4" r="2.5" fill="none" stroke="${color}" stroke-width="1.2"/><path d="M0.5 12c0-2.5 2-4 4.5-4s4.5 1.5 4.5 4" fill="none" stroke="${color}" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="${color}" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="${color}" stroke-width="1"/>`,
}
return `<g>${icons[kind] ?? ''}</g>`
}
// --- Widget renderers ---
function renderGrade(data: GradeData, t: Theme, s?: { max_tags?: number }): string {
const tags = s?.max_tags ? data.tags.slice(0, s.max_tags) : data.tags
const base = data.grade[0]
const color = GRADE_COLORS[base] ?? t.accent
const radius = 36
const circ = 2 * Math.PI * radius
const offset = circ * (1 - data.score / 100)
const gf = data.grade.length <= 2 ? 30 : 22
const statLabels: Record<string, string> = { commits:'Commits', prs:'PRs', stars:'Stars', repos:'Repos', followers:'Followers' }
const statKeys = ['commits','prs','stars','repos','followers'].filter(k => k in data.stats)
const sw = 340 / Math.max(statKeys.length, 1)
let statsSvg = ''
for (let i = 0; i < statKeys.length; i++) {
const k = statKeys[i], v = data.stats[k]
const sx = i * sw + sw / 2
const vs = v < 100000 ? v.toLocaleString() : `${Math.round(v/1000)}k`
statsSvg += `<g transform="translate(${sx}, 0)"><g transform="translate(-7, 0)">${iconSvg(k, t.text_secondary)}</g><text x="0" y="28" text-anchor="middle" font-family="${font}" font-size="14" font-weight="700" fill="${t.text}">${vs}</text><text x="0" y="41" text-anchor="middle" font-family="${font}" font-size="9" fill="${t.text_secondary}">${statLabels[k]??k}</text></g>`
}
let tagsSvg = '', tx = 0, ty = 0
for (const tag of tags) {
const tc = TAG_COLORS[tag.tag] ?? t.accent
const label = tag.label || formatTagLabel(tag.tag)
const tw = Math.round(label.length * 6.6 + 18)
const po = tag.source === 'earned' ? 0.9 : 0.55
if (tx + tw > 340) { tx = 0; ty += 30 }
tagsSvg += `<g transform="translate(${tx}, ${ty})" opacity="${po}"><rect width="${tw}" height="24" rx="12" fill="${tc}" opacity="0.12"/><rect width="${tw}" height="24" rx="12" fill="none" stroke="${tc}" stroke-width="1" opacity="0.3"/><text x="${Math.round(tw/2)}" y="16" text-anchor="middle" font-family="${font}" font-size="10" font-weight="500" fill="${tc}">${esc(label)}</text></g>`
tx += tw + 6
}
const tagsH = tags.length ? ty + 24 : 0
const statsY = 100, tagsY = statsY + 54
const tagPad = tagsH > 24 ? 18 : 14
const cardH = tags.length ? tagsY + tagsH + tagPad : statsY + 54
let inner = `<g transform="translate(52, 48)"><circle cx="0" cy="0" r="${radius}" fill="none" stroke="${t.grid}" stroke-width="5"/><circle cx="0" cy="0" r="${radius}" fill="none" stroke="${color}" stroke-width="5" stroke-dasharray="${circ.toFixed(1)}" stroke-dashoffset="${offset.toFixed(1)}" stroke-linecap="round" transform="rotate(-90)"/><text x="0" y="-4" text-anchor="middle" dominant-baseline="middle" font-family="${font}" font-size="${gf}" font-weight="800" fill="${color}">${esc(data.grade)}</text><text x="0" y="18" text-anchor="middle" font-family="${font}" font-size="11" fill="${t.text_secondary}">${data.score.toFixed(0)} / 100</text></g>
<line x1="100" y1="16" x2="100" y2="80" stroke="${t.grid}" stroke-width="1"/>
<g transform="translate(114, 26)"><text x="0" y="10" font-family="${font}" font-size="16" font-weight="700" fill="${t.text}">Developer Profile</text><text x="0" y="28" font-family="${font}" font-size="11" fill="${t.text_secondary}">Grade <tspan fill="${color}" font-weight="700">${esc(data.grade)}</tspan> · ${data.score.toFixed(0)}/100</text></g>
<line x1="20" y1="${statsY-4}" x2="360" y2="${statsY-4}" stroke="${t.grid}" stroke-width="0.5"/>
<g transform="translate(20, ${statsY})">${statsSvg}</g>`
if (tags.length) {
inner += `<line x1="20" y1="${tagsY-6}" x2="360" y2="${tagsY-6}" stroke="${t.grid}" stroke-width="0.5"/><g transform="translate(20, ${tagsY})">${tagsSvg}</g>`
}
return cardWrapper(inner, 380, cardH, t, '')
}
function renderImpact(weeks: ImpactWeek[], t: Theme, s?: { line_color?: string }): string {
const w = 380, h = 200, cx = 40, cy = 8, cw = 316, ch = 82
const lineColor = s?.line_color ?? t.accent
if (!weeks.length) {
const inner = `<line x1="${cx}" y1="${cy+ch}" x2="${cx+cw}" y2="${cy+ch}" stroke="${t.grid}" stroke-width="0.5"/>
<text x="${cx+cw/2}" y="${cy+ch/2+4}" text-anchor="middle" font-family="${font}" font-size="11" fill="${t.text_secondary}">No contribution data yet</text>
<g transform="translate(20, ${cy+ch+46})"><text x="0" y="0" font-family="${font}" font-size="13" font-weight="700" fill="${t.text}">0</text><text x="0" y="14" font-family="${font}" font-size="9" fill="${t.text_secondary}">commits over 6mo</text></g>`
return cardWrapper(inner, w, h, t, 'Impact Timeline')
}
const maxC = Math.max(...weeks.map(w => w.commits), 1)
const n = weeks.length
const pts = weeks.map((wk, i) => ({
x: cx + (i / Math.max(n-1, 1)) * cw,
y: cy + ch - (wk.commits / maxC) * ch,
}))
let pathD = `M ${pts[0].x.toFixed(1)} ${pts[0].y.toFixed(1)}`
for (let i = 1; i < pts.length; i++) {
const mx = (pts[i-1].x + pts[i].x) / 2
pathD += ` C ${mx.toFixed(1)} ${pts[i-1].y.toFixed(1)}, ${mx.toFixed(1)} ${pts[i].y.toFixed(1)}, ${pts[i].x.toFixed(1)} ${pts[i].y.toFixed(1)}`
}
const areaD = pathD + ` L ${pts[n-1].x.toFixed(1)} ${cy+ch} L ${pts[0].x.toFixed(1)} ${cy+ch} Z`
let yLabels = ''
for (let i = 0; i < 3; i++) {
const v = Math.round(maxC * (1 - i/2))
const yy = cy + (i/2) * ch
yLabels += `<text x="${cx-6}" y="${yy+4}" text-anchor="end" font-family="${font}" font-size="9" fill="${t.text_secondary}">${v}</text><line x1="${cx}" y1="${yy}" x2="${cx+cw}" y2="${yy}" stroke="${t.grid}" stroke-width="0.5" stroke-dasharray="3,3"/>`
}
let xLabels = ''
const li = n > 2 ? [0, Math.floor(n/2), n-1] : Array.from({length: n}, (_, i) => i)
for (const idx of li) {
if (idx < weeks.length) {
const px = cx + (idx / Math.max(n-1,1)) * cw
xLabels += `<text x="${px.toFixed(1)}" y="${cy+ch+14}" text-anchor="middle" font-family="${font}" font-size="9" fill="${t.text_secondary}">${weeks[idx].week_start.slice(0,7)}</text>`
}
}
const total = weeks.reduce((a, w) => a + w.commits, 0)
const sy = cy + ch + 46
const inner = `<defs><linearGradient id="areaGrad" x1="0" y1="${cy}" x2="0" y2="${cy+ch}" gradientUnits="userSpaceOnUse"><stop offset="0%" stop-color="${lineColor}" stop-opacity="0.35"/><stop offset="100%" stop-color="${lineColor}" stop-opacity="0.02"/></linearGradient></defs>
${yLabels}${xLabels}
<path d="${areaD}" fill="url(#areaGrad)"/>
<path d="${pathD}" fill="none" stroke="${lineColor}" stroke-width="2" stroke-linecap="round"/>
<g transform="translate(20, ${sy})"><text x="0" y="0" font-family="${font}" font-size="13" font-weight="700" fill="${t.text}">${total.toLocaleString()}</text><text x="0" y="14" font-family="${font}" font-size="9" fill="${t.text_secondary}">commits over 6mo</text></g>`
return cardWrapper(inner, w, h, t, 'Impact Timeline')
}
function renderCollaborators(collabs: CollaboratorData[], t: Theme, s?: { max_count?: number; bar_color?: string }): string {
const maxCount = Math.min(Math.max(s?.max_count ?? 5, 1), 10)
const barColor = s?.bar_color ?? t.purple
const shown = collabs.slice(0, maxCount)
const barMax = Math.max(...shown.map(c => c.shared_commits), 1)
let items = ''
for (let i = 0; i < shown.length; i++) {
const c = shown[i], y = i * 50
const hue = [...c.username].reduce((h, ch) => h + ch.charCodeAt(0), 0) % 360
const avatar = `<circle cx="0" cy="0" r="18" fill="hsl(${hue}, 50%, 40%)"/><text x="0" y="1" text-anchor="middle" dominant-baseline="middle" font-family="${font}" font-size="14" font-weight="600" fill="white">${esc(c.username[0].toUpperCase())}</text>`
const bw = (c.shared_commits / barMax * 120).toFixed(1)
items += `<g transform="translate(36, ${y+20})">${avatar}<text x="28" y="-2" font-family="${font}" font-size="13" font-weight="600" fill="${t.text}">${esc(c.username)}</text><text x="28" y="14" font-family="${font}" font-size="10" fill="${t.text_secondary}">${c.shared_repos} repos · ${c.shared_commits} commits</text><rect x="200" y="-6" width="130" height="8" rx="4" fill="${t.grid}"/><rect x="200" y="-6" width="${bw}" height="8" rx="4" fill="${barColor}" opacity="0.8"/></g>`
}
return cardWrapper(items, 380, shown.length * 50 + 48, t, 'Top Collaborators')
}
function renderFocus(cats: FocusCategory[], t: Theme, s?: { max_categories?: number }): string {
const maxCats = Math.min(Math.max(s?.max_categories ?? 6, 1), 10)
const sorted = [...cats].sort((a, b) => b.percentage - a.percentage).slice(0, maxCats)
if (!sorted.length) return ''
const maxPct = Math.max(sorted[0].percentage, 1)
const barMaxW = 210
let items = ''
for (let i = 0; i < sorted.length; i++) {
const cat = sorted[i], y = i * 36
const color = FOCUS_COLORS[i % FOCUS_COLORS.length]
const bw = (cat.percentage / maxPct * barMaxW).toFixed(1)
items += `<g transform="translate(16, ${y})"><text x="0" y="14" font-family="${font}" font-size="12" font-weight="600" fill="${t.text}">${esc(cat.category)}</text><rect x="90" y="4" width="${barMaxW}" height="14" rx="7" fill="${t.grid}"/><rect x="90" y="4" width="${bw}" height="14" rx="7" fill="${color}" opacity="0.8"/><text x="90" y="32" font-family="${font}" font-size="9" fill="${t.text_secondary}">${cat.commit_count} commits</text><text x="${90+barMaxW+8}" y="15" font-family="${font}" font-size="12" font-weight="700" fill="${color}">${Math.round(cat.percentage)}%</text></g>`
}
const subY = sorted.length * 36 + 8
items += `<text x="16" y="${subY}" font-family="${font}" font-size="9" fill="${t.text_secondary}" opacity="0.7">Recent activity · last year</text>`
return cardWrapper(items, 380, sorted.length * 36 + 54, t, 'Recent Focus')
}
function renderLanguages(languages: LanguageData[], t: Theme, s?: { max_languages?: number }): string {
const maxLangs = Math.min(Math.max(s?.max_languages ?? 5, 1), 10)
const topLangs = [...languages].sort((a, b) => b.percentage - a.percentage).slice(0, maxLangs)
if (!topLangs.length) return ''
const totalPct = topLangs.reduce((a, l) => a + l.percentage, 0)
const langs = [...topLangs]
if (totalPct < 99.9 && languages.length > maxLangs) {
langs.push({ language: 'Other', percentage: Math.round((100 - totalPct) * 10) / 10, loc: 0 })
} else if (totalPct < 99.9 && totalPct > 0) {
const f = 100 / totalPct
for (const l of langs) l.percentage = Math.round(l.percentage * f * 10) / 10
}
const legendStart = 20, legendH = langs.length * 22
const ccy = legendStart + legendH / 2, ccx = 60, r = 44, innerR = 28
const circ = 2 * Math.PI * r
let arcs = '', legend = '', offset = 0
for (let i = 0; i < langs.length; i++) {
const lang = langs[i]
const color = lang.language === 'Other' ? t.text_secondary : (LANG_COLORS[lang.language] ?? FOCUS_COLORS[i % FOCUS_COLORS.length])
const dash = circ * lang.percentage / 100
const gap = circ - dash
arcs += `<circle cx="${ccx}" cy="${ccy}" r="${r}" fill="none" stroke="${color}" stroke-width="16" stroke-dasharray="${dash.toFixed(1)} ${gap.toFixed(1)}" stroke-dashoffset="${(-offset).toFixed(1)}" transform="rotate(-90 ${ccx} ${ccy})" opacity="0.85"/>`
offset += dash
const ly = i * 22
legend += `<g transform="translate(140, ${ly + legendStart})"><rect width="10" height="10" rx="2" fill="${color}"/><text x="16" y="9" font-family="${font}" font-size="12" fill="${t.text}">${esc(lang.language)}</text><text x="210" y="9" text-anchor="end" font-family="${font}" font-size="11" font-weight="600" fill="${t.text_secondary}">${Math.round(lang.percentage)}%</text></g>`
}
const center = `<circle cx="${ccx}" cy="${ccy}" r="${innerR}" fill="${t.card_bg}"/><text x="${ccx}" y="${ccy+1}" text-anchor="middle" dominant-baseline="middle" font-family="${font}" font-size="11" font-weight="700" fill="${t.text}">${esc(langs[0].language)}</text>`
const inner = `<g transform="translate(16, 0)">${arcs}${center}${legend}</g>`
const rowsH = Math.max(langs.length * 22 + 40, 120)
return cardWrapper(inner, 380, rowsH + 36, t, 'Languages')
}
function achievementIconSvg(iconType: string, color: string): string {
// Mirrors generator/src/widgets/achievements.py::_achievement_icon_svg so
// the Workshop client preview matches the backend-rendered composite.
const icons: Record<string, string> = {
trophy: `<svg viewBox="0 0 24 24" width="24" height="24"><path d="M7 2h10v2h2.5c.8 0 1.5.7 1.5 1.5V8c0 1.7-1.3 3-3 3h-.5c-.5 1.5-1.8 2.7-3.5 3v2.5h3c.6 0 1 .4 1 1s-.4 1-1 1H7c-.6 0-1-.4-1-1s.4-1 1-1h3V14c-1.7-.3-3-1.5-3.5-3H6c-1.7 0-3-1.3-3-3V5.5C3 4.7 3.7 4 4.5 4H7V2zm0 4H4.5v2c0 .8.7 1.5 1.5 1.5h1V6zm12.5 0H17v3.5h1c.8 0 1.5-.7 1.5-1.5V6z" fill="${color}" opacity="0.85"/></svg>`,
medal: `<svg viewBox="0 0 24 24" width="24" height="24"><circle cx="12" cy="14" r="5" fill="${color}" opacity="0.2"/><circle cx="12" cy="14" r="4" fill="none" stroke="${color}" stroke-width="1.5"/><path d="M12 11.5l1 2 2.2.3-1.6 1.5.4 2.2-2-1-2 1 .4-2.2-1.6-1.5 2.2-.3z" fill="${color}"/><path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="${color}" stroke-width="1.5" fill="none" stroke-linecap="round"/></svg>`,
star: `<svg viewBox="0 0 24 24" width="24" height="24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" fill="none" stroke="${color}" stroke-width="1.5" stroke-linejoin="round"/></svg>`,
hackathon: `<svg viewBox="0 0 24 24" width="24" height="24"><rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="${color}" stroke-width="1.5"/><rect x="3" y="16" width="18" height="1.5" rx="0.5" fill="${color}" opacity="0.85"/><path d="M9 9l-2 3 2 3m6-6l2 3-2 3" stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>`,
}
return icons[iconType] ?? icons.trophy
}
function renderAchievements(achievements: AchievementInput[], t: Theme, s?: { max_items?: number }): string {
const maxItems = Math.min(Math.max(s?.max_items ?? 5, 1), 10)
const shown = achievements.filter(a => a.title.trim()).slice(0, maxItems)
if (!shown.length) return ''
const accentColors = [t.orange, t.green, t.accent, t.purple, t.pink]
let items = ''
for (let i = 0; i < shown.length; i++) {
const ach = shown[i], y = i * 56
const color = accentColors[i % accentColors.length]
const icon = achievementIconSvg(ach.icon, color)
items += `<g transform="translate(16, ${y+8})"><rect width="348" height="48" rx="8" fill="${color}" opacity="0.06"/><rect width="348" height="48" rx="8" fill="none" stroke="${color}" stroke-width="0.5" opacity="0.3"/><g transform="translate(12, 12)">${icon}</g><text x="48" y="20" font-family="${font}" font-size="13" font-weight="600" fill="${t.text}">${esc(ach.title)}</text><text x="48" y="36" font-family="${font}" font-size="10" fill="${t.text_secondary}">${esc(ach.subtitle)}${ach.event_date ? ' · ' + ach.event_date : ''}</text></g>`
}
return cardWrapper(items, 380, shown.length * 56 + 50, t, 'Achievements')
}
// --- Composite ---
function extractInner(svg: string, key: string): { inner: string; h: number } {
const hm = svg.match(/height="(\d+)"/)
const h = hm ? parseInt(hm[1]) : 160
// Prefix IDs
const ids = [...svg.matchAll(/id="([^"]+)"/g)].map(m => m[1])
let inner = svg
for (const id of ids) {
const nid = `${key}_${id}`
inner = inner.replaceAll(`id="${id}"`, `id="${nid}"`)
inner = inner.replaceAll(`url(#${id})`, `url(#${nid})`)
inner = inner.replaceAll(`href="#${id}"`, `href="#${nid}"`)
}
inner = inner.replace(/<svg[^>]*>/, '').replace(/<\/svg>\s*$/, '')
return { inner, h }
}
// --- Main export ---
export function renderAllWidgets(opts: {
data: WidgetData
theme: string
widgets: string[]
widgetOrder: string[]
achievements: AchievementInput[]
widgetSettings: PerWidgetSettings
hiddenLanguages?: string[]
username: string
}): string {
const t = THEMES[opts.theme] ?? THEMES.dark
const enabled = new Set(opts.widgets)
const widgetSvgs: Record<string, string> = {}
if (enabled.has('grade') && opts.data.grade)
widgetSvgs.grade = renderGrade(opts.data.grade, t, opts.widgetSettings.grade)
if (enabled.has('impact') && opts.data.impact)
widgetSvgs.impact = renderImpact(opts.data.impact, t, opts.widgetSettings.impact)
if (enabled.has('collaborators') && opts.data.collaborators)
widgetSvgs.collaborators = renderCollaborators(opts.data.collaborators, t, opts.widgetSettings.collaborators)
if (enabled.has('focus') && opts.data.focus)
widgetSvgs.focus = renderFocus(opts.data.focus, t, opts.widgetSettings.focus)
if (enabled.has('languages') && opts.data.languages) {
// Apply hidden_languages client-side too so the Workshop preview reflects
// the user's choice instantly — backend filtering only kicks in on the
// next prefetch or on POST /generate.
const hiddenSet = new Set(opts.hiddenLanguages ?? [])
const filtered = opts.data.languages.filter(l => !hiddenSet.has(l.language))
const total = filtered.reduce((a, l) => a + l.percentage, 0) || 1
const rescaled = filtered.map(l => ({ ...l, percentage: Math.round(l.percentage / total * 1000) / 10 }))
widgetSvgs.languages = renderLanguages(rescaled, t, opts.widgetSettings.languages)
}
if (enabled.has('achievements'))
widgetSvgs.achievements = renderAchievements(opts.achievements, t, opts.widgetSettings.achievements)
// Compose
const totalW = 420, headerH = 60, padding = 20, gap = 16
const ordered = opts.widgetOrder.filter(k => enabled.has(k) && widgetSvgs[k])
const parts = ordered.map(key => {
const { inner, h } = extractInner(widgetSvgs[key], key)
return { key, inner, h }
})
const contentH = parts.reduce((a, p) => a + p.h, 0) + gap * Math.max(parts.length - 1, 0)
const totalH = headerH + contentH + padding * 2 + 10
const avatar = `<circle cx="30" cy="30" r="16" fill="${t.accent}" opacity="0.3"/>`
const header = `${avatar}<text x="54" y="38" font-family="${font}" font-size="16" font-weight="700" fill="${t.text}">${esc(opts.username || 'Developer')}</text><line x1="${padding}" y1="${headerH}" x2="${totalW-padding}" y2="${headerH}" stroke="${t.card_border}" stroke-width="0.5"/>`
let yOffset = headerH + padding
let embedded = ''
for (const { inner, h } of parts) {
embedded += `<svg x="${padding}" y="${yOffset}" width="380" height="${h}" viewBox="0 0 380 ${h}">${inner}</svg>`
yOffset += h + gap
}
return `<svg xmlns="http://www.w3.org/2000/svg" width="${totalW}" height="${totalH}" viewBox="0 0 ${totalW} ${totalH}">
<rect width="${totalW}" height="${totalH}" rx="16" fill="${t.bg}"/>
<rect x="0.5" y="0.5" width="${totalW-1}" height="${totalH-1}" rx="16" fill="none" stroke="${t.card_border}" stroke-width="1"/>
${header}${embedded}
<text x="${totalW/2}" y="${totalH-8}" text-anchor="middle" font-family="${font}" font-size="9" fill="${t.text_secondary}" opacity="0.5">Generated with gh-stats</text>
</svg>`
}
+37
View File
@@ -0,0 +1,37 @@
export type Theme = {
bg: string; card_bg: string; card_border: string
text: string; text_secondary: string; accent: string
green: string; orange: string; red: string
purple: string; pink: string; grid: string
}
export const THEMES: Record<string, Theme> = {
dark: { bg:"#121820",card_bg:"#1a2230",card_border:"#2a3444",text:"#d1d9e0",text_secondary:"#7d8895",accent:"#58a6ff",green:"#3fb950",orange:"#d29922",red:"#f85149",purple:"#bc8cff",pink:"#f778ba",grid:"#1e2836" },
onyx: { bg:"#09090b",card_bg:"#18181b",card_border:"#27272a",text:"#fafafa",text_secondary:"#a1a1aa",accent:"#a78bfa",green:"#4ade80",orange:"#fb923c",red:"#f87171",purple:"#c084fc",pink:"#f472b6",grid:"#27272a" },
nord: { bg:"#1e2433",card_bg:"#2a3142",card_border:"#3d4659",text:"#e5e9f0",text_secondary:"#8892a4",accent:"#88c0d0",green:"#a3be8c",orange:"#ebcb8b",red:"#bf616a",purple:"#b48ead",pink:"#d08770",grid:"#333d50" },
light: { bg:"#ffffff",card_bg:"#f6f8fa",card_border:"#d8dee4",text:"#24292f",text_secondary:"#656d76",accent:"#0969da",green:"#1a7f37",orange:"#9a6700",red:"#cf222e",purple:"#8250df",pink:"#bf3989",grid:"#eaeef2" },
paper: { bg:"#faf8f5",card_bg:"#f5f0eb",card_border:"#e0d8cf",text:"#3d3529",text_secondary:"#7a7062",accent:"#b45309",green:"#4d7c0f",orange:"#a16207",red:"#b91c1c",purple:"#7e22ce",pink:"#be185d",grid:"#ebe5dd" },
}
THEMES.midnight = THEMES.dark
THEMES.clean = THEMES.light
export const TAG_COLORS: Record<string, string> = {
"ml-engineer":"#bc8cff","frontend":"#58a6ff","backend":"#3fb950","fullstack":"#d29922",
"devops":"#f0883e","database":"#f778ba","mobile":"#ff6b9d","security":"#f85149",
"data-science":"#79c0ff","systems":"#7ee787","cloud":"#58a6ff","open-source":"#3fb950",
}
export const GRADE_COLORS: Record<string, string> = {
S:"#ff6b9d", A:"#3fb950", B:"#58a6ff", C:"#d29922", D:"#f0883e", F:"#f85149",
}
export const FOCUS_COLORS = [
"#58a6ff","#3fb950","#bc8cff","#d29922","#f0883e","#f778ba","#f85149","#79c0ff",
]
export const LANG_COLORS: Record<string, string> = {
Python:"#3572A5",JavaScript:"#f1e05a",TypeScript:"#3178c6",Go:"#00ADD8",
Rust:"#dea584",Java:"#b07219","C++":"#f34b7d",C:"#555555",Ruby:"#701516",
Shell:"#89e051",HTML:"#e34c26",CSS:"#563d7c",Kotlin:"#A97BFF",Swift:"#F05138",
"Jupyter Notebook":"#DA5B0B",Dockerfile:"#384d54",
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
@@ -0,0 +1,111 @@
import DOMPurify from 'dompurify'
import { useMemo, useState } from 'react'
function sanitizeSvg(raw: string): string {
return DOMPurify.sanitize(raw, {
USE_PROFILES: { svg: true, svgFilters: true },
ADD_TAGS: ['image', 'use', 'clipPath', 'defs', 'style', 'animate', 'animateTransform', 'feDropShadow', 'filter', 'linearGradient', 'stop'],
ADD_ATTR: ['xlink:href', 'href', 'clip-path', 'viewBox', 'preserveAspectRatio', 'xmlns', 'xmlns:xlink', 'rx', 'ry', 'attributeName', 'from', 'to', 'dur', 'fill', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'dominant-baseline', 'letter-spacing', 'opacity', 'filter', 'flood-color', 'flood-opacity', 'stdDeviation'],
})
}
type Props = {
username: string
generating: boolean
generatedSvg: string | null
generateError: string | null
onBack: () => void
}
export function ResultScreen({ username, generating, generatedSvg, generateError, onBack }: Props) {
const safeSvg = useMemo(() => (generatedSvg ? sanitizeSvg(generatedSvg) : ''), [generatedSvg])
const [copied, setCopied] = useState(false)
const embedUrl = `${window.location.origin}/api/${encodeURIComponent(username)}`
const embedSnippet = `![${username}](${embedUrl})`
const copy = async () => {
try {
await navigator.clipboard.writeText(embedSnippet)
setCopied(true)
setTimeout(() => setCopied(false), 1500)
} catch {
/* ignore */
}
}
return (
<div className="min-h-screen flex flex-col items-center animate-fade-in-up">
<div className="w-full max-w-3xl px-6 pt-6">
<button
onClick={onBack}
className="flex items-center gap-1.5 text-xs text-gray-400 hover:text-gray-600 transition-colors"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M19 12H5M12 19l-7-7 7-7" />
</svg>
Back
</button>
</div>
<div className="flex-1 flex flex-col items-center justify-center px-6 pb-12 w-full max-w-3xl">
<h2 className="font-serif text-3xl text-gray-800 tracking-tight mb-2">
Your Widget
</h2>
{generating && (
<div className="mt-10 flex flex-col items-center gap-3">
<div className="w-6 h-6 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin-slow" />
<p className="text-xs text-gray-400">Generating with real data…</p>
</div>
)}
{!generating && generateError && (
<div className="mt-10 flex flex-col items-center gap-3">
<p className="text-sm text-red-500">{generateError}</p>
</div>
)}
{!generating && !generateError && safeSvg && (
<>
<div className="w-full mt-6 rounded-2xl bg-white shadow-lg ring-1 ring-gray-200 p-6 flex justify-center">
{/*
Force the inline SVG to scale up to the card width. The
composite is authored at 380px wide — without this the
preview looked tiny on wide screens.
*/}
<div
className="w-full max-w-xl [&_svg]:w-full [&_svg]:h-auto"
dangerouslySetInnerHTML={{ __html: safeSvg }}
/>
</div>
<div className="w-full mt-8">
<p className="text-xs uppercase tracking-wider text-gray-500 mb-2">Embed in your README</p>
<div className="relative">
<pre className="bg-gray-900 text-gray-100 text-xs p-4 pr-12 rounded-lg overflow-x-auto">
{embedSnippet}
</pre>
<button
onClick={copy}
title={copied ? 'Copied!' : 'Copy'}
className="absolute top-2 right-2 p-1.5 rounded-md text-gray-400 hover:text-gray-100 hover:bg-gray-800 transition-colors"
>
{copied ? (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="20 6 9 17 4 12" />
</svg>
) : (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
)}
</button>
</div>
</div>
</>
)}
</div>
</div>
)
}
@@ -0,0 +1,45 @@
import { useState } from 'react'
type Props = {
onSearch: (username: string) => void
}
export function SearchScreen({ onSearch }: Props) {
const [value, setValue] = useState('')
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
const trimmed = value.trim()
if (trimmed) onSearch(trimmed)
}
return (
<div className="min-h-screen flex items-center justify-center animate-fade-in-up">
<div className="text-center w-full max-w-md px-6">
<h1 className="font-serif text-4xl text-gray-800 tracking-tight mb-2">
GitHub Stats
</h1>
<p className="text-sm text-gray-400 mb-8">
Generate your profile widget
</p>
<form onSubmit={handleSubmit} className="flex gap-2">
<input
type="text"
value={value}
onChange={e => setValue(e.target.value)}
placeholder="Enter GitHub username..."
autoFocus
className="flex-1 px-4 py-3 rounded-xl border border-gray-200 bg-white text-sm text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 transition-colors"
/>
<button
type="submit"
disabled={!value.trim()}
className="px-6 py-3 rounded-xl bg-gray-800 text-white text-sm font-medium hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
>
Go
</button>
</form>
</div>
</div>
)
}
@@ -0,0 +1,582 @@
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
// GitHub-sourced strings (collaborator logins, repo names) and user-typed
// achievement text. renderWidgets escapes known fields, but one missed
// interpolation anywhere upstream would turn into HTML in the preview.
// DOMPurify neutralises that without affecting normal SVG shapes/styles.
const SVG_SANITIZE_CONFIG = {
USE_PROFILES: { svg: true, svgFilters: true },
ADD_TAGS: [
'image', 'use', 'clipPath', 'defs', 'style', 'animate', 'animateTransform',
'feDropShadow', 'filter', 'linearGradient', 'stop',
],
ADD_ATTR: [
'xlink:href', 'href', 'clip-path', 'viewBox', 'preserveAspectRatio',
'xmlns', 'xmlns:xlink', 'rx', 'ry', 'attributeName', 'from', 'to', 'dur',
'fill', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap',
'stroke-linejoin', 'dominant-baseline', 'letter-spacing', 'opacity',
'filter', 'flood-color', 'flood-opacity', 'stdDeviation',
],
}
const THEMES = [
{ id: 'midnight', label: 'Midnight', color: '#121820' },
{ id: 'onyx', label: 'Onyx', color: '#09090b' },
{ id: 'nord', label: 'Nord', color: '#1e2433' },
{ id: 'clean', label: 'Clean', color: '#ffffff', border: true },
{ id: 'paper', label: 'Paper', color: '#faf8f5', border: true },
]
const ALL_WIDGETS = [
{ id: 'grade', label: 'Grade' },
{ id: 'impact', label: 'Impact Timeline' },
{ id: 'collaborators', label: 'Top Collaborators' },
{ id: 'focus', label: 'Recent Focus' },
{ id: 'languages', label: 'Languages' },
{ id: 'achievements', label: 'Achievements' },
]
// Lucide-style hollow glyphs: consistent stroke-weight + viewBox so the 4
// buttons line up and read as one icon family. Kept as JSX so they inherit
// currentColor from the surrounding button's text color.
const ICON_SVG_PROPS = {
width: 16,
height: 16,
viewBox: '0 0 24 24',
fill: 'none',
stroke: 'currentColor',
strokeWidth: 1.75,
strokeLinecap: 'round' as const,
strokeLinejoin: 'round' as const,
}
const ICONS: { id: string; svg: ReactNode }[] = [
{
id: 'trophy',
svg: (
<svg {...ICON_SVG_PROPS}>
<path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6" />
<path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18" />
<path d="M4 22h16" />
<path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22" />
<path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22" />
<path d="M18 2H6v7a6 6 0 0 0 12 0V2z" />
</svg>
),
},
{
id: 'medal',
svg: (
<svg {...ICON_SVG_PROPS}>
<circle cx="12" cy="8" r="6" />
<path d="m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526" />
</svg>
),
},
{
id: 'star',
svg: (
<svg {...ICON_SVG_PROPS}>
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26" />
</svg>
),
},
{
id: 'hackathon',
svg: (
<svg {...ICON_SVG_PROPS}>
<polyline points="16 18 22 12 16 6" />
<polyline points="8 6 2 12 8 18" />
</svg>
),
},
]
const COLOR_PRESETS = [
'#58a6ff', '#a78bfa', '#4ade80', '#fb923c', '#f472b6',
'#ff6b6b', '#38bdf8', '#facc15', '#34d399', '#c084fc',
]
function ChevronIcon({ open }: { open: boolean }) {
return (
<svg
width="12" height="12" viewBox="0 0 24 24" fill="none"
stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
className={`transition-transform ${open ? 'rotate-90' : ''}`}
>
<path d="M9 18l6-6-6-6" />
</svg>
)
}
function NumberStepper({ value, min, max, onChange }: {
value: number; min: number; max: number; onChange: (v: number) => void
}) {
return (
<div className="flex items-center gap-1.5">
<button
onClick={() => onChange(Math.max(min, value - 1))}
className="w-6 h-6 rounded bg-gray-100 text-gray-500 hover:bg-gray-200 text-xs font-medium flex items-center justify-center"
>-</button>
<span className="text-xs text-gray-700 w-5 text-center tabular-nums">{value}</span>
<button
onClick={() => onChange(Math.min(max, value + 1))}
className="w-6 h-6 rounded bg-gray-100 text-gray-500 hover:bg-gray-200 text-xs font-medium flex items-center justify-center"
>+</button>
</div>
)
}
// Common "noise" languages users typically want to hide — shown even when
// the account-level detection hasn't surfaced them yet (e.g., first load).
const COMMON_HIDE_LANGS = ['HTML', 'CSS', 'SCSS', 'Jupyter Notebook', 'TeX', 'Shell', 'Dockerfile', 'Makefile', 'Batchfile']
function HiddenLanguagesPicker({
detected, hidden, onChange,
}: {
detected: { language: string }[]
hidden: string[]
onChange: (next: string[]) => void
}) {
const seen = new Set<string>()
const options: string[] = []
for (const d of detected) if (d.language && !seen.has(d.language)) { seen.add(d.language); options.push(d.language) }
for (const c of COMMON_HIDE_LANGS) if (!seen.has(c)) { seen.add(c); options.push(c) }
// Preserve any user-set hidden that we haven't otherwise seen.
for (const h of hidden) if (!seen.has(h)) { seen.add(h); options.push(h) }
const toggle = (lang: string) => {
onChange(hidden.includes(lang) ? hidden.filter(h => h !== lang) : [...hidden, lang])
}
return (
<div>
<div className="flex items-center justify-between mb-1.5">
<span className="text-[10px] text-gray-500">Hide languages</span>
{hidden.length > 0 && (
<button
onClick={() => onChange([])}
className="text-[10px] text-gray-400 hover:text-gray-600 transition-colors"
>
Clear
</button>
)}
</div>
<div className="flex flex-wrap gap-1">
{options.map(lang => {
const active = hidden.includes(lang)
return (
<button
key={lang}
onClick={() => toggle(lang)}
className={`px-2 py-0.5 rounded-md text-[10px] transition-colors ${
active
? 'bg-gray-800 text-white border border-gray-800'
: 'bg-white text-gray-500 border border-gray-200 hover:text-gray-800 hover:border-gray-300'
}`}
>
{lang}
</button>
)
})}
</div>
</div>
)
}
function ColorPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) {
return (
<div className="flex gap-1.5 flex-wrap">
{COLOR_PRESETS.map(c => (
<button
key={c}
onClick={() => onChange(c)}
className={`w-5 h-5 rounded-full transition-all ${
value === c ? 'ring-2 ring-offset-1 ring-blue-500' : 'hover:ring-1 hover:ring-gray-300'
}`}
style={{ backgroundColor: c }}
/>
))}
</div>
)
}
type Props = {
username: string
settings: WidgetSettings
onSettingsChange: (s: WidgetSettings) => void
onGenerate: () => void
onBack: () => void
fetchDone: boolean
fetchError: string | null
widgetData: WidgetData | null
me: Me
onAuthChange?: (m: Me) => void
}
export function WorkshopScreen({
username,
settings,
onSettingsChange,
onGenerate,
onBack,
fetchDone,
fetchError,
widgetData,
me,
}: Props) {
const canEdit = !!me.login && me.login.toLowerCase() === username.toLowerCase()
const [expandedWidget, setExpandedWidget] = useState<string | null>(null)
const updateSetting = <K extends keyof WidgetSettings>(key: K, val: WidgetSettings[K]) => {
onSettingsChange({ ...settings, [key]: val })
}
const updateWidgetSetting = (widget: keyof PerWidgetSettings, key: string, val: unknown) => {
const current = settings.widgetSettings[widget] || {}
const next = { ...settings.widgetSettings, [widget]: { ...current, [key]: val } }
updateSetting('widgetSettings', next)
}
const getWidgetSetting = <T,>(widget: keyof PerWidgetSettings, key: string, fallback: T): T => {
const ws = settings.widgetSettings[widget] as Record<string, unknown> | undefined
return (ws?.[key] as T) ?? fallback
}
const toggleWidget = (id: string) => {
const next = settings.widgets.includes(id)
? settings.widgets.filter(w => w !== id)
: [...settings.widgets, id]
updateSetting('widgets', next)
}
const toggleAdvanced = (id: string) => {
setExpandedWidget(expandedWidget === id ? null : id)
}
const addAchievement = () => {
updateSetting('achievements', [
...settings.achievements,
{ title: '', subtitle: '', event_date: '', icon: 'trophy' },
])
}
const updateAchievement = (idx: number, field: keyof Achievement, val: string) => {
const next = settings.achievements.map((a, i) =>
i === idx ? { ...a, [field]: val } : a
)
updateSetting('achievements', next)
}
const removeAchievement = (idx: number) => {
updateSetting('achievements', settings.achievements.filter((_, i) => i !== idx))
}
// Render SVG client-side whenever settings change (instant, no API call)
const svgContent = useMemo(() => {
if (!widgetData) return ''
const raw = renderAllWidgets({
data: widgetData,
theme: settings.theme,
widgets: settings.widgets,
widgetOrder: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'],
achievements: settings.achievements,
widgetSettings: settings.widgetSettings,
hiddenLanguages: settings.hiddenLanguages,
username,
})
return DOMPurify.sanitize(raw, SVG_SANITIZE_CONFIG)
}, [widgetData, settings, username])
return (
<div className="min-h-screen animate-fade-in-up">
<div className="flex min-h-screen">
{/* Left settings panel */}
<div className="w-80 flex-shrink-0 border-r border-gray-200 bg-white p-6 flex flex-col overflow-y-auto">
{/* Back */}
<button
onClick={onBack}
className="flex items-center gap-1.5 text-xs text-gray-400 hover:text-gray-600 mb-6 transition-colors self-start"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M19 12H5M12 19l-7-7 7-7"/>
</svg>
Back
</button>
<div className="text-sm font-semibold text-gray-800 mb-6">{username}</div>
{fetchError && (
<div className="flex items-center gap-1.5 text-[10px] text-red-500 mb-6">
<div className="w-1.5 h-1.5 rounded-full bg-red-400" />
{fetchError}
</div>
)}
{!canEdit && (
<div className="banner">
{me.login
? `Signed in as ${me.login}. You can only edit your own widget.`
: <a href={signInUrl()}>Sign in with GitHub to edit your widget</a>}
</div>
)}
{/* Theme, Widgets, Achievements editor, Generate — owner-only */}
{canEdit && (
<>
{/* Theme */}
<div className="mb-5">
<div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Theme</div>
<div className="flex gap-2 flex-wrap">
{THEMES.map(t => (
<button
key={t.id}
onClick={() => updateSetting('theme', t.id)}
title={t.label}
className={`w-9 h-9 rounded-lg transition-all ${
settings.theme === t.id
? 'ring-2 ring-blue-500 ring-offset-2'
: t.border
? 'border border-gray-200 hover:border-gray-300'
: 'hover:ring-1 hover:ring-gray-300 hover:ring-offset-1'
}`}
style={{ backgroundColor: t.color }}
/>
))}
</div>
<div className="text-[10px] text-gray-400 mt-1.5">
{THEMES.find(t => t.id === settings.theme)?.label}
</div>
</div>
{/* Widgets with inline advanced settings */}
<div className="mb-5">
<div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Widgets</div>
<div className="flex flex-col gap-0.5">
{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 (
<div key={w.id}>
<div className="flex items-center">
<button
onClick={() => toggleWidget(w.id)}
className={`flex-1 flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs transition-colors text-left ${
enabled
? 'text-gray-800 bg-gray-50'
: 'text-gray-400 hover:text-gray-500 hover:bg-gray-50/50'
}`}
>
<div className={`w-3.5 h-3.5 rounded flex-shrink-0 transition-colors ${enabled ? 'bg-blue-500' : 'bg-gray-200'}`} />
{w.label}
</button>
{hasAdvanced && enabled && (
<button
onClick={() => toggleAdvanced(w.id)}
className="p-1.5 text-gray-400 hover:text-gray-600 transition-colors"
title="Advanced settings"
>
<ChevronIcon open={isExpanded} />
</button>
)}
</div>
{isExpanded && (
<div className="ml-6 mt-1 mb-2 p-2.5 rounded-lg bg-gray-50/80 border border-gray-100 flex flex-col gap-2.5">
{w.id === 'grade' && (
<div className="flex items-center justify-between">
<span className="text-[10px] text-gray-500">Max tags</span>
<NumberStepper
value={getWidgetSetting('grade', 'max_tags', 6)}
min={1} max={20}
onChange={v => updateWidgetSetting('grade', 'max_tags', v)}
/>
</div>
)}
{w.id === 'impact' && (
<div>
<span className="text-[10px] text-gray-500 block mb-1.5">Line color</span>
<ColorPicker
value={getWidgetSetting('impact', 'line_color', '#58a6ff')}
onChange={v => updateWidgetSetting('impact', 'line_color', v)}
/>
</div>
)}
{w.id === 'collaborators' && (
<div className="flex flex-col gap-2.5">
<div className="flex items-center justify-between">
<span className="text-[10px] text-gray-500">Max shown</span>
<NumberStepper
value={getWidgetSetting('collaborators', 'max_count', 5)}
min={1} max={10}
onChange={v => updateWidgetSetting('collaborators', 'max_count', v)}
/>
</div>
<div>
<span className="text-[10px] text-gray-500 block mb-1.5">Bar color</span>
<ColorPicker
value={getWidgetSetting('collaborators', 'bar_color', '#a78bfa')}
onChange={v => updateWidgetSetting('collaborators', 'bar_color', v)}
/>
</div>
</div>
)}
{w.id === 'focus' && (
<div className="flex items-center justify-between">
<span className="text-[10px] text-gray-500">Max categories</span>
<NumberStepper
value={getWidgetSetting('focus', 'max_categories', 6)}
min={1} max={10}
onChange={v => updateWidgetSetting('focus', 'max_categories', v)}
/>
</div>
)}
{w.id === 'languages' && (
<div className="flex flex-col gap-2.5">
<div className="flex items-center justify-between">
<span className="text-[10px] text-gray-500">Max languages</span>
<NumberStepper
value={getWidgetSetting('languages', 'max_languages', 5)}
min={1} max={10}
onChange={v => updateWidgetSetting('languages', 'max_languages', v)}
/>
</div>
<HiddenLanguagesPicker
detected={widgetData?.languages ?? []}
hidden={settings.hiddenLanguages}
onChange={next => updateSetting('hiddenLanguages', next)}
/>
</div>
)}
{w.id === 'achievements' && (
<div className="flex items-center justify-between">
<span className="text-[10px] text-gray-500">Max shown</span>
<NumberStepper
value={getWidgetSetting('achievements', 'max_items', 5)}
min={1} max={10}
onChange={v => updateWidgetSetting('achievements', 'max_items', v)}
/>
</div>
)}
</div>
)}
</div>
)
})}
</div>
</div>
{/* Achievements editor */}
{settings.widgets.includes('achievements') && (
<div className="mb-5">
<div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Achievements</div>
<div className="flex flex-col gap-2">
{settings.achievements.map((ach, idx) => (
<div key={idx} className="p-2.5 rounded-lg border border-gray-100 bg-gray-50/50">
<div className="flex items-center gap-1.5 mb-2">
{ICONS.map(ic => {
const selected = ach.icon === ic.id
return (
<button
key={ic.id}
onClick={() => updateAchievement(idx, 'icon', ic.id)}
className={`w-8 h-8 rounded-md flex items-center justify-center transition-colors ${
selected
? 'bg-gray-800 text-white border border-gray-800'
: 'bg-white text-gray-500 border border-gray-200 hover:text-gray-800 hover:border-gray-300'
}`}
title={ic.id}
aria-pressed={selected}
>
{ic.svg}
</button>
)
})}
<div className="flex-1" />
<button
onClick={() => removeAchievement(idx)}
className="text-gray-300 hover:text-red-400 transition-colors text-xs px-1"
title="Remove"
>
✕
</button>
</div>
<input
type="text"
value={ach.title}
onChange={e => 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"
/>
<input
type="text"
value={ach.subtitle}
onChange={e => 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"
/>
<input
type="text"
value={ach.event_date}
onChange={e => 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"
/>
</div>
))}
<button
onClick={addAchievement}
className="w-full py-2 rounded-lg border border-dashed border-gray-200 text-xs text-gray-400 hover:text-gray-600 hover:border-gray-300 transition-colors"
>
+ Add achievement
</button>
</div>
</div>
)}
{/* Spacer */}
<div className="flex-1 min-h-4" />
{/* Generate button */}
<button
onClick={onGenerate}
className="w-full py-3 rounded-xl bg-gray-800 text-white text-sm font-medium hover:bg-gray-700 transition-colors"
>
Generate →
</button>
</>
)}
</div>
{/* Right preview area */}
<div className="flex-1 flex items-start justify-center p-8 overflow-auto">
<div className="relative">
{svgContent ? (
<div dangerouslySetInnerHTML={{ __html: svgContent }} />
) : (
<div className="w-[420px] h-[600px] rounded-2xl border border-gray-200 bg-white flex items-center justify-center">
{!fetchDone ? (
<div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin-slow" />
) : (
<p className="text-xs text-gray-400">No data available</p>
)}
</div>
)}
</div>
</div>
</div>
</div>
)
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [react(), tailwindcss()],
server: {
port: 3000,
proxy: {
'/api': 'http://localhost:5002',
},
},
})
+5
View File
@@ -0,0 +1,5 @@
[pytest]
testpaths = tests
python_files = test_*.py
pythonpath = .
addopts = -ra --strict-markers
+8
View File
@@ -0,0 +1,8 @@
flask==3.0.3
flask-caching==2.3.0
flask-compress==1.15
requests==2.32.3
pytest==8.3.3
responses==0.25.3
gunicorn==23.0.0
authlib>=1.3,<2
View File
+641
View File
@@ -0,0 +1,641 @@
"""Flask app for the generator service.
Serves:
/ -> React SPA (static/index.html)
/assets/<p> -> SPA bundles
/api/* -> JSON/SVG API
Two-phase pipeline:
* Enrollment / settings change enqueues a prefetch job and kicks it off
in a background thread so the fetcher starts pulling GitHub data the
instant the user submits a username. The thread only hydrates
widget_data for the client-side Workshop preview — it does not render
SVGs.
* POST /api/<u>/generate synchronously renders and persists the composite
SVG. This is what the user's "Generate" button calls.
"""
import logging
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, session
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
log = logging.getLogger("generator.api")
# Bounded pool for prefetch kickoffs. The old code spawned an unbounded
# Thread() per request, so a burst of PATCH /settings would fork hundreds
# of threads each doing a GitHub fetch + SVG compute — easily enough to
# swamp a mini PC. The pool's workqueue absorbs spikes; excess kickoffs
# wait rather than executing in parallel.
_PREFETCH_POOL = ThreadPoolExecutor(
max_workers=max(1, config.PREFETCH_MAX_WORKERS),
thread_name_prefix="prefetch",
)
# Global cap on concurrent SVG renders. A render is the single most
# expensive user-facing operation; capping it makes the worst-case CPU
# load predictable regardless of how many callers pile on.
_GENERATE_SEMAPHORE = BoundedSemaphore(max(1, config.GENERATE_CONCURRENCY))
def _kickoff_prefetch(username: str):
"""Run one prefetch cycle in the bounded pool. Starts the fetcher
soon after enrollment / settings-change so the raw GitHub payload
is hot by the time the user clicks Generate, but never runs more
than PREFETCH_MAX_WORKERS at once."""
log.info("prefetch kickoff started for %s", username)
try:
from . import worker
worker.process_one()
log.info("prefetch kickoff finished for %s", username)
except Exception:
log.exception("prefetch kickoff failed for %s", username)
def _kickoff_prefetch_async(username: str):
try:
_PREFETCH_POOL.submit(_kickoff_prefetch, username)
except RuntimeError:
# Pool was shut down (process exiting). Dropping the kickoff is
# safe: the cron loop will pick the job up on its next tick.
log.warning("prefetch pool shut down; skipping kickoff for %s", username)
# ---- Per-IP rate limiter -----------------------------------------------------
# In-process sliding-window limiter. Good enough for v1; behind a reverse proxy
# we read X-Forwarded-For (trusting only the last hop set by the proxy). For a
# multi-node deploy, swap this for a Redis-backed limiter.
_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),
"read": (config.RATE_LIMIT_READ_MAX, config.RATE_LIMIT_READ_WINDOW),
}
_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:
fwd = request.headers.get("X-Forwarded-For", "")
if fwd:
# Last value is the closest trusted proxy's client.
return fwd.split(",")[-1].strip()
return request.remote_addr or "unknown"
def _rate_limit(bucket: str) -> bool:
"""Return True if the request is allowed; False if it should be rejected."""
limit, window = _RATE_LIMITS[bucket]
ip = _client_ip()
now = time.time()
key = (bucket, ip)
with _rate_lock:
q = _rate_hits[key]
cutoff = now - window
while q and q[0] < cutoff:
q.popleft()
if len(q) >= limit:
return False
q.append(now)
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
_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
# ---- Settings shape validator -----------------------------------------------
# Settings flow from the public PATCH endpoint into SQLite and then into widget
# renderers. Unvalidated input means an attacker can DoS the render pipeline by
# storing an object that makes `int(settings["widget_settings"]["collaborators"]
# ["max_count"])` raise, or by ballooning the DB with unbounded fields.
# We normalize to an explicit allow-list of fields and coerce/trim types.
_ALLOWED_WIDGETS = {"grade", "impact", "collaborators", "focus", "languages", "achievements"}
_ALLOWED_ICONS = {"trophy", "medal", "star", "hackathon"}
_MAX_ACHIEVEMENTS = 10
_TITLE_MAX = 80
_SUBTITLE_MAX = 160
_EVENT_DATE_MAX = 32
_MAX_CUSTOM_TAGS = 10
_MAX_HIDDEN_LANGS = 40
_TAG_MAX = 40
_LANG_MAX = 40
def _clip_str(v, max_len: int) -> str:
if v is None:
return ""
s = v if isinstance(v, str) else str(v)
return s[:max_len]
def _coerce_achievement(a) -> dict | None:
if not isinstance(a, dict):
return None
title = _clip_str(a.get("title"), _TITLE_MAX).strip()
if not title:
return None
icon = a.get("icon") or "trophy"
if not isinstance(icon, str) or icon not in _ALLOWED_ICONS:
icon = "trophy"
return {
"title": title,
"subtitle": _clip_str(a.get("subtitle"), _SUBTITLE_MAX),
"event_date": _clip_str(a.get("event_date"), _EVENT_DATE_MAX),
"icon": icon,
}
def _coerce_str_list(v, max_items: int, max_item_len: int) -> list[str]:
if not isinstance(v, list):
return []
out = []
for x in v[:max_items]:
if isinstance(x, str) and x:
out.append(x[:max_item_len])
return out
def _coerce_widget_settings(v) -> dict:
"""Whitelist per-widget settings down to the shape each renderer expects.
Anything else is silently dropped — callers cannot smuggle arbitrary keys
into the SVG renderers this way."""
if not isinstance(v, dict):
return {}
out: dict[str, dict] = {}
allowed = {
"grade": {"max_tags": "int"},
"impact": {"line_color": "color"},
"collaborators": {"max_count": "int", "bar_color": "color"},
"focus": {"max_categories": "int"},
"languages": {"max_languages": "int"},
"achievements": {"max_items": "int"},
}
for widget, schema in allowed.items():
raw = v.get(widget)
if not isinstance(raw, dict):
continue
clean = {}
for key, kind in schema.items():
if key not in raw:
continue
val = raw[key]
if kind == "int":
try:
clean[key] = int(val)
except (TypeError, ValueError):
continue
elif kind == "color":
# Deep color validation happens in the widget renderer
# (safe_color). Here we only reject obviously wrong types
# and length-bomb strings.
if isinstance(val, str) and len(val) <= 32:
clean[key] = val
if clean:
out[widget] = clean
return out
def sanitize_settings(body: dict) -> dict:
"""Project an untrusted JSON object down to the fields we accept.
This is the ONLY place that decides what the settings schema is. Anything
not listed here is dropped. Widget renderers can assume the shape holds."""
if not isinstance(body, dict):
return {}
out: dict = {}
theme = body.get("theme")
if isinstance(theme, str) and theme in THEMES:
out["theme"] = theme
if "enabled" in body:
out["enabled"] = [w for w in _coerce_str_list(body["enabled"], 20, 32)
if w in _ALLOWED_WIDGETS]
if "widget_order" in body:
out["widget_order"] = [w for w in _coerce_str_list(body["widget_order"], 20, 32)
if w in _ALLOWED_WIDGETS]
if "custom_tags" in body:
out["custom_tags"] = _coerce_str_list(body["custom_tags"], _MAX_CUSTOM_TAGS, _TAG_MAX)
if "hidden_languages" in body:
out["hidden_languages"] = _coerce_str_list(
body["hidden_languages"], _MAX_HIDDEN_LANGS, _LANG_MAX
)
if "widget_settings" in body:
ws = _coerce_widget_settings(body["widget_settings"])
if ws:
out["widget_settings"] = ws
if "achievements" in body:
raw = body["achievements"] if isinstance(body["achievements"], list) else []
cleaned = []
for a in raw[:_MAX_ACHIEVEMENTS]:
ca = _coerce_achievement(a)
if ca:
cleaned.append(ca)
out["achievements"] = cleaned
return out
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def spa(path: str):
if path.startswith("api/"):
return jsonify({"error": "not found"}), 404
if path:
# send_from_directory enforces that `path` cannot escape _STATIC_DIR.
try:
return send_from_directory(_STATIC_DIR, path)
except Exception:
pass
index = os.path.join(_STATIC_DIR, "index.html")
if os.path.isfile(index):
return send_from_directory(_STATIC_DIR, "index.html")
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/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"
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"})
@app.route("/api/<username>", methods=["GET"])
@rate_limited("read")
def get_widget(username: str):
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
return _serve(username, widget_name="composite")
@app.route("/api/<username>/<widget>.svg", methods=["GET"])
@rate_limited("read")
def get_widget_named(username: str, widget: str):
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
if widget not in _ALLOWED_WIDGETS and widget != "composite":
return jsonify({"error": "unknown_widget"}), 400
return _serve(username, widget_name=widget)
@app.route("/api/<username>/data", methods=["GET"])
@rate_limited("read")
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. 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:
return jsonify({"status": "not_found"}), 404
db.touch_last_requested(username)
row = db.get_current_widget_data(username)
if row is None:
return jsonify({"status": "building"}), 202
if row["settings_hash"] == "not_found":
return jsonify({"status": "not_found"}), 404
return jsonify({"status": "ready", "data": row["data"]})
def _serve(username: str, widget_name: str) -> Response:
"""Serves a cached SVG for README embeds.
SVGs are only produced by POST /api/<u>/generate. Before that the
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:
return _placeholder_response("building", username)
db.touch_last_requested(username)
current_hash = db.get_current_widget_hash(username)
raw_theme = settings_row["settings"].get("theme", "dark")
theme = raw_theme if isinstance(raw_theme, str) and raw_theme in THEMES else "dark"
headers_common = {
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:",
"X-Content-Type-Options": "nosniff",
}
if current_hash == "not_found":
svg = db.get_current_widget(username, widget_name) or placeholder.render("not_found", username, theme=theme)
headers = {"X-Widget-Status": "not_found", "Cache-Control": "no-store", **headers_common}
return Response(svg, mimetype="image/svg+xml", headers=headers)
svg = db.get_current_widget(username, widget_name)
if svg is None:
return _placeholder_response("building", username, theme=theme)
headers = {"X-Widget-Status": "ready",
"Cache-Control": "public, max-age=3600",
**headers_common}
return Response(svg, mimetype="image/svg+xml", headers=headers)
def _placeholder_response(variant: str, username: str, theme: str = "dark") -> Response:
svg = placeholder.render(variant, username, theme=theme)
return Response(svg, mimetype="image/svg+xml",
headers={"X-Widget-Status": variant, "Cache-Control": "no-store",
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:",
"X-Content-Type-Options": "nosniff"})
@app.route("/api/<username>/settings", methods=["GET"])
@rate_limited("read")
def get_settings(username: str):
s = db.get_settings(username)
if s is None:
return jsonify({"error": "not_enrolled"}), 404
# Strip internal-only fields before returning.
return jsonify({
"settings": s["settings"],
"settings_hash": s["settings_hash"],
"manual_refresh_used": s["manual_refresh_used"],
"enrolled_at": s["enrolled_at"],
})
@app.route("/api/<username>/settings", methods=["PATCH"])
@rate_limited("mutate")
@auth.require_same_origin
@auth.require_github_owner
def patch_settings(username: str):
current = db.get_settings(username)
if current is None:
return jsonify({"error": "not_enrolled"}), 404
body = request.get_json(silent=True) or {}
clean = sanitize_settings(body)
merged = {**current["settings"], **clean}
# Defense in depth: reject after-the-fact if the merged blob is pathological.
if not settings_size_ok(_json.dumps(merged)):
return jsonify({"error": "settings_too_large"}), 413
job_id = db.update_settings(username, merged)
_kickoff_prefetch_async(username)
return jsonify({"updated": True, "job_id": job_id})
@app.route("/api/<username>/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). Requires OAuth session with matching login.
Capacity:
* Per-IP rate limit (mutate bucket) caps how fast any one caller can
trigger renders.
* Global semaphore caps how many renders run in parallel across all
callers — the mini PC backstop. Callers that can't acquire the
slot within GENERATE_SEMAPHORE_WAIT_S get 503 + Retry-After so the
frontend can back off cleanly.
"""
from . import worker
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
if db.get_settings(username) is None:
return jsonify({"error": "not_enrolled"}), 404
acquired = _GENERATE_SEMAPHORE.acquire(timeout=config.GENERATE_SEMAPHORE_WAIT_S)
if not acquired:
resp = jsonify({"error": "busy"})
resp.status_code = 503
resp.headers["Retry-After"] = "5"
return resp
try:
widgets = worker.render_widgets_now(username)
except LookupError:
return jsonify({"error": "not_enrolled"}), 404
except Exception:
log.exception("generate failed for %s", username)
return jsonify({"error": "render_failed"}), 502
finally:
_GENERATE_SEMAPHORE.release()
current_hash = db.get_current_widget_hash(username)
if current_hash == "not_found":
return jsonify({"status": "not_found"}), 404
return jsonify({
"status": "ready",
"composite_url": f"/api/{username}",
"widgets": list(widgets.keys()),
})
@app.route("/api/<username>/refresh", methods=["POST"])
@rate_limited("mutate")
@auth.require_same_origin
@auth.require_github_owner
def refresh(username: str):
s = db.get_settings(username)
if s is None:
return jsonify({"error": "not_enrolled"}), 404
if not db.mark_manual_refresh(username):
return jsonify({"error": "already_used"}), 409
try:
fetcher_client.force_fetch(username)
except Exception:
log.exception("refresh fetcher call failed for %s", username)
return jsonify({"error": "fetch_failed"}), 502
job_id = db.enqueue_build(username)
_kickoff_prefetch_async(username)
return jsonify({"refreshed": True, "job_id": job_id})
@app.errorhandler(413)
def _too_large(_e):
return jsonify({"error": "payload_too_large"}), 413
def main():
db.init_dbs()
app.run(host="0.0.0.0", port=config.PORT)
if __name__ == "__main__":
main()
+80
View File
@@ -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
+37
View File
@@ -0,0 +1,37 @@
"""Tiny cache wrapper. v1 = no-op (REDIS_URL empty). v2 = real Redis."""
from typing import Optional
from . import config
class Cache:
def __init__(self):
self.enabled = bool(config.REDIS_URL)
self._client = None
if self.enabled:
import redis # local import so v1 doesn't require redis in runtime path
self._client = redis.from_url(config.REDIS_URL, decode_responses=True)
def get(self, key: str) -> Optional[str]:
if not self.enabled:
return None
try:
return self._client.get(key)
except Exception:
return None
def set(self, key: str, value: str, ttl_seconds: int) -> None:
if not self.enabled:
return
try:
self._client.setex(key, ttl_seconds, value)
except Exception:
pass
def delete(self, *keys: str) -> None:
if not self.enabled or not keys:
return
try:
self._client.delete(*keys)
except Exception:
pass
+61 -2
View File
@@ -47,10 +47,10 @@ DATA_SOURCE_TYPE = os.getenv("DATA_SOURCE", "direct")
"""Data source type: 'direct' for immediate API calls, 'queued' for batch processing.""" """Data source type: 'direct' for immediate API calls, 'queued' for batch processing."""
# Widget settings # Widget settings
WIDGET_ORDER = ["grade", "impact", "collaborators", "focus", "languages", "achievements"] WIDGET_ORDER = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"]
"""Default order of widgets. Customize by reordering this list.""" """Default order of widgets. Customize by reordering this list."""
ENABLED_WIDGETS = ["grade", "impact", "collaborators", "focus", "languages", "achievements"] ENABLED_WIDGETS = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"]
"""Which widgets to display. Remove any you don't want to show.""" """Which widgets to display. Remove any you don't want to show."""
# Language filtering # Language filtering
@@ -103,3 +103,62 @@ TAG_TOPIC_MAP = {
"gcp": "Cloud", "gcp": "Cloud",
} }
"""Map repository topics to developer role categories.""" """Map repository topics to developer role categories."""
# --- Service-specific additions (v2 of config) ---
PORT = int(os.getenv("GENERATOR_PORT", "5002"))
SETTINGS_DB_PATH = os.getenv("GENERATOR_SETTINGS_DB_PATH", "./data/settings.db")
WIDGETS_DB_PATH = os.getenv("GENERATOR_WIDGETS_DB_PATH", "./data/widgets.db")
FETCHER_URL = os.getenv("FETCHER_URL", "http://localhost:5001")
FETCHER_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "")
REDIS_URL = os.getenv("REDIS_URL", "")
ENROLLMENT_DAILY_CAP = int(os.getenv("ENROLLMENT_DAILY_CAP", "50"))
WIDGET_LRU_PER_USER = int(os.getenv("WIDGET_LRU_PER_USER", "10"))
POLL_INTERVAL_MINUTES = int(os.getenv("GENERATOR_POLL_INTERVAL_MINUTES", "15"))
# --- Mini-PC capacity controls ---
# The generator runs on a single mini PC, so the constraining resources are
# CPU (SVG render) and the GitHub PAT (fetch). Everything here is tunable via
# env so the operator can loosen limits after measuring real load.
# Per-IP sliding-window rate limits: (max_hits, window_seconds). These are
# anti-abuse ceilings, not capacity controls — the mini PC is actually
# protected by the global semaphore + worker pool + queue cap below, so
# per-IP numbers stay lenient. Tighten via env only if you see a specific
# abuser.
RATE_LIMIT_READ_MAX = int(os.getenv("RATE_LIMIT_READ_MAX", "3000"))
RATE_LIMIT_READ_WINDOW = int(os.getenv("RATE_LIMIT_READ_WINDOW", "60"))
RATE_LIMIT_MUTATE_MAX = int(os.getenv("RATE_LIMIT_MUTATE_MAX", "120"))
RATE_LIMIT_MUTATE_WINDOW = int(os.getenv("RATE_LIMIT_MUTATE_WINDOW", "60"))
RATE_LIMIT_ENROLL_MAX = int(os.getenv("RATE_LIMIT_ENROLL_MAX", "60"))
RATE_LIMIT_ENROLL_WINDOW = int(os.getenv("RATE_LIMIT_ENROLL_WINDOW", "300"))
# Global across-all-IPs caps. These are the mini-PC backstop: even a
# thousand-IP botnet can't induce more than this much work at once.
GENERATE_CONCURRENCY = int(os.getenv("GENERATE_CONCURRENCY", "2"))
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 ---
# 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", "")
# 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"))
+66
View File
@@ -0,0 +1,66 @@
"""Generator cron: poll fetcher for payload-hash changes, enqueue rebuilds.
Run as its own container: CMD python -m src.cron
"""
import logging
import os
import time
from . import config, db, fetcher_client
log = logging.getLogger("generator.cron")
# Pacing between users in a single tick. On a mini PC with N enrolled
# users, a tight loop would fire N fetcher calls back-to-back, each of
# which can become a GitHub call — trivially enough to spike CPU and
# burn PAT budget. Default 0.25s keeps 1000 users inside a ~4-minute
# tick while leaving headroom in the 15-minute window.
_TICK_INTER_USER_SLEEP_S = float(os.getenv("GENERATOR_CRON_INTER_USER_SLEEP_S", "0.25"))
# Queue-depth backstop. If the build worker is already behind, don't
# enqueue more: let it drain. Keeps SQLite from swelling when a burst of
# GitHub changes arrives at once.
_TICK_QUEUE_CAP = int(os.getenv("GENERATOR_CRON_QUEUE_CAP", str(config.PENDING_JOB_QUEUE_CAP)))
def tick() -> dict:
enqueued = 0
failed = 0
skipped_queue_full = 0
for username in db.list_enrolled():
try:
if db.pending_job_count() >= _TICK_QUEUE_CAP:
skipped_queue_full += 1
# Don't hammer the fetcher either when the queue is full.
time.sleep(_TICK_INTER_USER_SLEEP_S)
continue
info = db.get_settings(username)
current = info.get("last_fetcher_payload_hash")
r = fetcher_client.get_data(username)
latest = r.get("payload_hash")
if latest and latest != current:
db.enqueue_build(username)
db.set_last_fetcher_hash(username, latest)
enqueued += 1
except Exception as e:
log.warning("poll failed for %s: %s", username, e)
failed += 1
if _TICK_INTER_USER_SLEEP_S > 0:
time.sleep(_TICK_INTER_USER_SLEEP_S)
return {"enqueued": enqueued, "failed": failed, "skipped_queue_full": skipped_queue_full}
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
db.init_dbs()
interval_s = config.POLL_INTERVAL_MINUTES * 60
while True:
try:
log.info("tick: %s", tick())
except Exception:
log.exception("tick failed")
time.sleep(interval_s)
if __name__ == "__main__":
main()
+500
View File
@@ -0,0 +1,500 @@
"""Generator's two SQLite DBs: settings.db (settings + jobs + enrollments) and widgets.db (svg cache).
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 json
import os
import sqlite3
from contextlib import contextmanager
from datetime import datetime, timedelta
from typing import Optional
from . import config
SETTINGS_DB_PATH = config.SETTINGS_DB_PATH
WIDGETS_DB_PATH = config.WIDGETS_DB_PATH
_SETTINGS_SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
settings_json TEXT NOT NULL,
settings_hash TEXT NOT NULL,
enrolled_at TEXT NOT NULL,
last_fetcher_payload_hash TEXT,
manual_refresh_used INTEGER DEFAULT 0,
last_requested_at TEXT NOT NULL,
edit_token_hash TEXT,
github_id INTEGER,
github_avatar_url TEXT
);
CREATE TABLE IF NOT EXISTS enrollments_daily (
day TEXT PRIMARY KEY,
count INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL,
username TEXT NOT NULL,
status TEXT NOT NULL,
attempts INTEGER DEFAULT 0,
last_error TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_jobs_pending ON jobs(status, created_at);
CREATE TABLE IF NOT EXISTS user_streaks (
username TEXT PRIMARY KEY,
current_streak INTEGER NOT NULL DEFAULT 0,
current_start TEXT NOT NULL DEFAULT '',
last_active_date TEXT NOT NULL DEFAULT '',
max_streak INTEGER NOT NULL DEFAULT 0,
max_start TEXT NOT NULL DEFAULT '',
max_end TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL
);
"""
_WIDGETS_SCHEMA = """
CREATE TABLE IF NOT EXISTS widgets (
username TEXT NOT NULL,
settings_hash TEXT NOT NULL,
widget_name TEXT NOT NULL,
svg TEXT NOT NULL,
built_at TEXT NOT NULL,
PRIMARY KEY (username, settings_hash, widget_name)
);
CREATE TABLE IF NOT EXISTS current_widget (
username TEXT PRIMARY KEY,
settings_hash TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS widget_data (
username TEXT NOT NULL,
settings_hash TEXT NOT NULL,
data_json TEXT NOT NULL,
built_at TEXT NOT NULL,
PRIMARY KEY (username, settings_hash)
);
CREATE INDEX IF NOT EXISTS idx_widgets_username ON widgets(username);
CREATE INDEX IF NOT EXISTS idx_widget_data_username ON widget_data(username);
"""
def _now() -> str:
return datetime.utcnow().isoformat(timespec="seconds") + "Z"
def _today() -> str:
return datetime.utcnow().strftime("%Y-%m-%d")
def _open(path: str) -> sqlite3.Connection:
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
conn = sqlite3.connect(path, timeout=10)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA foreign_keys=ON")
conn.execute("PRAGMA busy_timeout=5000")
return conn
@contextmanager
def _settings_conn():
conn = _open(SETTINGS_DB_PATH)
try:
yield conn
finally:
conn.close()
@contextmanager
def _widgets_conn():
conn = _open(WIDGETS_DB_PATH)
try:
yield conn
finally:
conn.close()
def init_dbs() -> None:
with _settings_conn() as c:
c.executescript(_SETTINGS_SCHEMA)
# Additive migration for DBs created before the auth rollout.
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)
c.commit()
def settings_hash(settings: dict) -> str:
canonical = json.dumps(settings, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
# ---- settings / enrollment ----
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.
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()
with _settings_conn() as c:
cur_ins = c.execute(
"""INSERT INTO users(username, settings_json, settings_hash, enrolled_at,
last_requested_at, github_id, github_avatar_url)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(username) DO NOTHING""",
(username, json.dumps(defaults), sh, now, now, github_id, github_avatar_url),
)
inserted = cur_ins.rowcount == 1
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}
def enrollments_today() -> int:
with _settings_conn() as c:
row = c.execute("SELECT count FROM enrollments_daily WHERE day=?", (_today(),)).fetchone()
return row["count"] if row else 0
def enrollment_rank(username: str) -> Optional[int]:
"""1-based position in overall enrollment order by enrolled_at. Used by
tag rules that reward early users (e.g. the 'founder' tag)."""
with _settings_conn() as c:
row = c.execute("SELECT enrolled_at FROM users WHERE username=?", (username,)).fetchone()
if row is None:
return None
return c.execute(
"SELECT COUNT(*) FROM users WHERE enrolled_at <= ?", (row["enrolled_at"],)
).fetchone()[0]
def get_settings(username: str) -> Optional[dict]:
with _settings_conn() as c:
row = c.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone()
if row is None:
return None
return {
"settings": json.loads(row["settings_json"]),
"settings_hash": row["settings_hash"],
"manual_refresh_used": row["manual_refresh_used"],
"last_fetcher_payload_hash": row["last_fetcher_payload_hash"],
"enrolled_at": row["enrolled_at"],
}
def update_settings(username: str, new_settings: dict) -> int:
"""Updates settings + enqueues rebuild. Returns job_id."""
sh = settings_hash(new_settings)
now = _now()
with _settings_conn() as c:
c.execute(
"UPDATE users SET settings_json=?, settings_hash=? WHERE username=?",
(json.dumps(new_settings), sh, username),
)
cur = c.execute(
"""INSERT INTO jobs(kind, username, status, created_at, updated_at)
VALUES ('build', ?, 'pending', ?, ?)""",
(username, now, now),
)
c.commit()
return cur.lastrowid
def mark_manual_refresh(username: str) -> bool:
"""Sets manual_refresh_used=1 only if it was 0. Returns True if successfully flipped."""
with _settings_conn() as c:
cur = c.execute(
"UPDATE users SET manual_refresh_used=1 WHERE username=? AND manual_refresh_used=0",
(username,),
)
c.commit()
return cur.rowcount == 1
def touch_last_requested(username: str) -> None:
with _settings_conn() as c:
c.execute("UPDATE users SET last_requested_at=? WHERE username=?", (_now(), username))
c.commit()
def list_enrolled() -> list[str]:
with _settings_conn() as c:
return [r["username"] for r in c.execute("SELECT username FROM users").fetchall()]
def set_last_fetcher_hash(username: str, h: str) -> None:
with _settings_conn() as c:
c.execute("UPDATE users SET last_fetcher_payload_hash=? WHERE username=?", (h, username))
c.commit()
def get_user_streak(username: str) -> Optional[dict]:
"""Return the persisted streak row for a user, or None if never written."""
with _settings_conn() as c:
row = c.execute(
"SELECT * FROM user_streaks WHERE username=?", (username,)
).fetchone()
if row is None:
return None
return {
"current_streak": row["current_streak"],
"current_start": row["current_start"],
"last_active_date": row["last_active_date"],
"max_streak": row["max_streak"],
"max_start": row["max_start"],
"max_end": row["max_end"],
"updated_at": row["updated_at"],
}
def put_user_streak(username: str, streak: dict) -> None:
"""UPSERT the streak row for a user. Caller supplies the merged values."""
now = _now()
with _settings_conn() as c:
c.execute(
"""INSERT INTO user_streaks(
username, current_streak, current_start, last_active_date,
max_streak, max_start, max_end, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(username) DO UPDATE SET
current_streak=excluded.current_streak,
current_start=excluded.current_start,
last_active_date=excluded.last_active_date,
max_streak=excluded.max_streak,
max_start=excluded.max_start,
max_end=excluded.max_end,
updated_at=excluded.updated_at""",
(
username,
int(streak.get("current_streak", 0)),
streak.get("current_start", ""),
streak.get("last_active_date", ""),
int(streak.get("max_streak", 0)),
streak.get("max_start", ""),
streak.get("max_end", ""),
now,
),
)
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:
now = _now()
with _settings_conn() as c:
cur = c.execute(
"""INSERT INTO jobs(kind, username, status, created_at, updated_at)
VALUES ('build', ?, 'pending', ?, ?)""",
(username, now, now),
)
c.commit()
return cur.lastrowid
def pending_job_count() -> int:
"""Depth of the build queue. Used as backpressure so bursts of
enroll/PATCH don't blow up SQLite when the worker is behind."""
with _settings_conn() as c:
row = c.execute("SELECT COUNT(*) AS n FROM jobs WHERE status='pending'").fetchone()
return int(row["n"]) if row else 0
def claim_next_job() -> Optional[dict]:
now = _now()
with _settings_conn() as c:
row = c.execute(
"SELECT * FROM jobs WHERE status='pending' ORDER BY created_at LIMIT 1"
).fetchone()
if row is None:
return None
c.execute("UPDATE jobs SET status='running', updated_at=?, attempts=attempts+1 WHERE id=?",
(now, row["id"]))
c.commit()
return {"id": row["id"], "username": row["username"], "kind": row["kind"],
"status": "running", "attempts": row["attempts"] + 1}
def complete_job(job_id: int) -> None:
with _settings_conn() as c:
c.execute("UPDATE jobs SET status='done', updated_at=? WHERE id=?", (_now(), job_id))
c.commit()
def fail_job(job_id: int, err: str, retry: bool) -> None:
status = "pending" if retry else "failed"
with _settings_conn() as c:
c.execute("UPDATE jobs SET status=?, last_error=?, updated_at=? WHERE id=?",
(status, err, _now(), job_id))
c.commit()
def reclaim_stuck_jobs(older_than_minutes: int) -> int:
cutoff = (datetime.utcnow() - timedelta(minutes=older_than_minutes)).isoformat(timespec="seconds") + "Z"
with _settings_conn() as c:
cur = c.execute(
"UPDATE jobs SET status='pending', updated_at=? WHERE status='running' AND updated_at < ?",
(_now(), cutoff),
)
c.commit()
return cur.rowcount
# ---- widgets ----
def put_widgets(username: str, hash_: str, widgets: dict[str, str]) -> None:
"""Insert widget rows for this (user, hash) and flip current_widget to point at it."""
now = _now()
with _widgets_conn() as c:
for name, svg in widgets.items():
c.execute(
"""INSERT INTO widgets(username, settings_hash, widget_name, svg, built_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(username, settings_hash, widget_name) DO UPDATE SET
svg = excluded.svg, built_at = excluded.built_at""",
(username, hash_, name, svg, now),
)
c.execute(
"""INSERT INTO current_widget(username, settings_hash, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash, updated_at=excluded.updated_at""",
(username, hash_, now),
)
c.commit()
def get_current_widget_hash(username: str) -> Optional[str]:
"""The settings_hash that current_widget points at (or None if nothing
has been prefetched/rendered yet). Distinct from users.settings_hash,
which is the hash of the *currently configured* settings."""
with _widgets_conn() as c:
row = c.execute(
"SELECT settings_hash FROM current_widget WHERE username=?",
(username,),
).fetchone()
return row["settings_hash"] if row else None
def point_current_widget(username: str, hash_: str) -> None:
"""Flip the current_widget pointer to a settings_hash. Used by the
prefetch worker (which writes only widget_data, not SVG rows) and by
the render path (which writes both, but calls this too for clarity)."""
now = _now()
with _widgets_conn() as c:
c.execute(
"""INSERT INTO current_widget(username, settings_hash, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash, updated_at=excluded.updated_at""",
(username, hash_, now),
)
c.commit()
def get_current_widget(username: str, widget_name: str) -> Optional[str]:
with _widgets_conn() as c:
row = c.execute(
"""SELECT w.svg FROM widgets w
JOIN current_widget cw ON cw.username=w.username AND cw.settings_hash=w.settings_hash
WHERE w.username=? AND w.widget_name=?""",
(username, widget_name),
).fetchone()
return row["svg"] if row else None
def put_widget_data(username: str, hash_: str, data: dict) -> None:
"""Store computed widget data for client-side rendering. Keyed to the
same (username, settings_hash) that widgets are — the worker writes both
in the same build pass."""
now = _now()
with _widgets_conn() as c:
c.execute(
"""INSERT INTO widget_data(username, settings_hash, data_json, built_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(username, settings_hash) DO UPDATE SET
data_json = excluded.data_json, built_at = excluded.built_at""",
(username, hash_, json.dumps(data, separators=(",", ":")), now),
)
c.commit()
def get_current_widget_data(username: str) -> Optional[dict]:
"""Returns {'data': <dict>, 'settings_hash': str} for the pointer in
current_widget, or None if nothing is built yet."""
with _widgets_conn() as c:
row = c.execute(
"""SELECT wd.data_json, wd.settings_hash FROM widget_data wd
JOIN current_widget cw ON cw.username=wd.username AND cw.settings_hash=wd.settings_hash
WHERE wd.username=?""",
(username,),
).fetchone()
if row is None:
return None
return {"data": json.loads(row["data_json"]), "settings_hash": row["settings_hash"]}
def lru_trim(username: str, keep: int) -> int:
"""Keep only the N newest settings_hashes per user; delete older rows."""
with _widgets_conn() as c:
hashes = [r["settings_hash"] for r in c.execute(
"""SELECT settings_hash, MAX(built_at) AS latest FROM widgets
WHERE username=? GROUP BY settings_hash ORDER BY latest DESC""",
(username,),
).fetchall()]
to_delete = hashes[keep:]
if not to_delete:
return 0
placeholders = ",".join("?" * len(to_delete))
cur = c.execute(
f"DELETE FROM widgets WHERE username=? AND settings_hash IN ({placeholders})",
(username, *to_delete),
)
c.execute(
f"DELETE FROM widget_data WHERE username=? AND settings_hash IN ({placeholders})",
(username, *to_delete),
)
c.commit()
return cur.rowcount
+21
View File
@@ -0,0 +1,21 @@
"""HTTP client to the fetcher service. Used by api.py, worker.py, cron.py."""
import requests
from . import config
def _headers() -> dict:
return {"X-Internal-Token": config.FETCHER_INTERNAL_TOKEN}
def get_data(username: str) -> dict:
r = requests.get(f"{config.FETCHER_URL}/data/{username}", headers=_headers(), timeout=30)
r.raise_for_status()
return r.json()
def force_fetch(username: str) -> dict:
r = requests.post(f"{config.FETCHER_URL}/fetch", headers=_headers(),
json={"username": username}, timeout=30)
r.raise_for_status()
return r.json()
@@ -8,6 +8,7 @@ from .types import (
FocusCategory, FocusCategory,
LanguageData, LanguageData,
AchievementData, AchievementData,
StreakData,
) )
__all__ = [ __all__ = [
@@ -18,4 +19,5 @@ __all__ = [
"FocusCategory", "FocusCategory",
"LanguageData", "LanguageData",
"AchievementData", "AchievementData",
"StreakData",
] ]
@@ -17,6 +17,7 @@ class TagData:
tag: str tag: str
source: str = "earned" # "earned" | "chosen" source: str = "earned" # "earned" | "chosen"
confidence: float = 1.0 confidence: float = 1.0
label: str | None = None # optional display override (e.g. "Founder #42")
@dataclass @dataclass
@@ -55,3 +56,13 @@ class AchievementData:
subtitle: str = "" subtitle: str = ""
event_date: str = "" event_date: str = ""
icon: str = "trophy" # trophy, medal, star, hackathon icon: str = "trophy" # trophy, medal, star, hackathon
@dataclass
class StreakData:
current: int = 0 # consecutive days ending today (or yesterday under grace)
max: int = 0 # all-time longest observed streak
current_start: str = "" # ISO date the current streak started, "" if current == 0
last_active_date: str = "" # most recent date with contributions in the window
max_start: str = "" # ISO date the max streak started (best-effort)
max_end: str = "" # ISO date the max streak ended (best-effort)
+28
View File
@@ -0,0 +1,28 @@
"""Placeholder SVG renderer — three variants for unknown / rate-limited / not-found users.
Uses the same card wrapper + theme system as real widgets so they look consistent.
"""
from .themes.themes import THEMES
from .utils.svg_helpers import card_wrapper, escape
_MESSAGES = {
"building": ("Building @{u}'s widget\u2026", "This usually takes under a minute."),
"rate_limited": ("Too many new users today", "Try again tomorrow."),
"not_found": ("GitHub user @{u} doesn't exist", "Check the spelling of the username."),
}
def render(variant: str, username: str, theme: str = "dark") -> str:
if variant not in _MESSAGES:
raise ValueError(f"unknown placeholder variant: {variant}")
title_tpl, subtitle = _MESSAGES[variant]
title = title_tpl.format(u=username)
palette = THEMES.get(theme, THEMES["dark"])
inner = (
f'<text x="24" y="56" font-family="-apple-system,Segoe UI,sans-serif" '
f'font-size="18" font-weight="600" fill="{palette["text"]}">{escape(title)}</text>'
f'<text x="24" y="82" font-family="-apple-system,Segoe UI,sans-serif" '
f'font-size="13" fill="{palette["text_secondary"]}">{escape(subtitle)}</text>'
)
return card_wrapper(inner, width=400, height=120, theme=palette)
@@ -3,20 +3,24 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
from collections import defaultdict from collections import defaultdict
from ..models import ( from .models import (
GradeData, GradeData,
TagData, TagData,
ImpactWeek, ImpactWeek,
CollaboratorData, CollaboratorData,
FocusCategory, FocusCategory,
LanguageData, LanguageData,
AchievementData,
StreakData,
) )
from ..widgets import ( from .widgets import (
render_grade_widget, render_grade_widget,
render_impact_widget, render_impact_widget,
render_collaborators_widget, render_collaborators_widget,
render_focus_widget, render_focus_widget,
render_languages_widget, render_languages_widget,
render_achievements_widget,
render_streaks_widget,
) )
@@ -150,7 +154,7 @@ def _compute_tags(github_data: dict, max_tags: int = None, custom_tags: list[str
Returns: Returns:
List of TagData objects with inferred developer roles List of TagData objects with inferred developer roles
""" """
from ..config import TAG_MAX_COUNT, TAG_LANGUAGE_MAP, TAG_TOPIC_MAP, HIDDEN_LANGUAGES from .config import TAG_MAX_COUNT, TAG_LANGUAGE_MAP, TAG_TOPIC_MAP, HIDDEN_LANGUAGES
if max_tags is None: if max_tags is None:
max_tags = TAG_MAX_COUNT max_tags = TAG_MAX_COUNT
@@ -189,6 +193,7 @@ def _compute_tags(github_data: dict, max_tags: int = None, custom_tags: list[str
# Apply threshold rules # Apply threshold rules
awarded_tags = [] awarded_tags = []
tag_label_overrides: dict[str, str] = {}
# Fullstack: >25% frontend AND >25% backend # Fullstack: >25% frontend AND >25% backend
if category_percentages.get("Frontend", 0) > 0.25 and category_percentages.get("Backend", 0) > 0.25: if category_percentages.get("Frontend", 0) > 0.25 and category_percentages.get("Backend", 0) > 0.25:
@@ -235,9 +240,22 @@ def _compute_tags(github_data: dict, max_tags: int = None, custom_tags: list[str
for tag in custom_tags: for tag in custom_tags:
awarded_tags.append((tag, 1.0)) awarded_tags.append((tag, 1.0))
# Auto-awarded tags (username-specific + rule-based; see src/tag_rules.py).
from . import tag_rules
username = (github_data.get("user") or {}).get("login", "")
for auto_tag, label in tag_rules.evaluate(username, github_data):
awarded_tags.append((auto_tag, 1.0))
if label:
tag_label_overrides[auto_tag] = label
# Sort by confidence and limit to max_tags # Sort by confidence and limit to max_tags
for tag, conf in sorted(awarded_tags, key=lambda x: -x[1])[:max_tags]: for tag, conf in sorted(awarded_tags, key=lambda x: -x[1])[:max_tags]:
tags.append(TagData(tag=tag, source="earned" if conf < 1.0 else "custom", confidence=round(conf, 2))) tags.append(TagData(
tag=tag,
source="earned" if conf < 1.0 else "custom",
confidence=round(conf, 2),
label=tag_label_overrides.get(tag),
))
return tags return tags
@@ -372,7 +390,7 @@ def compute_focus(github_data: dict, hidden_languages: list[str] = None) -> list
github_data: GitHub profile data github_data: GitHub profile data
hidden_languages: Optional list of languages to exclude hidden_languages: Optional list of languages to exclude
""" """
from ..config import HIDDEN_LANGUAGES from .config import HIDDEN_LANGUAGES
if hidden_languages is None: if hidden_languages is None:
hidden_languages = HIDDEN_LANGUAGES hidden_languages = HIDDEN_LANGUAGES
@@ -461,20 +479,49 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) ->
""" """
Compute language distribution from repos. Compute language distribution from repos.
Prefers per-repo byte breakdowns (`repo["language_bytes"]`) when present —
that matches GitHub's own "Most Used Languages" widget. Falls back to a
primary-language repo-count tally for payloads fetched before the
enrichment step landed.
Args: Args:
github_data: GitHub profile data github_data: GitHub profile data
hidden_languages: Optional list of languages to exclude (e.g., ["HTML", "CSS"]) hidden_languages: Optional list of languages to exclude (e.g., ["HTML", "CSS"])
""" """
from ..config import HIDDEN_LANGUAGES from .config import HIDDEN_LANGUAGES
if hidden_languages is None: if hidden_languages is None:
hidden_languages = HIDDEN_LANGUAGES hidden_languages = HIDDEN_LANGUAGES
hidden_set = {h for h in hidden_languages}
repos = github_data["repos"] repos = github_data["repos"]
lang_counts = defaultdict(int) byte_totals: dict[str, int] = defaultdict(int)
have_bytes = False
for r in repos:
lb = r.get("language_bytes") or {}
if not isinstance(lb, dict) or not lb:
continue
have_bytes = True
for lang, n in lb.items():
if lang and lang not in hidden_set:
byte_totals[lang] += int(n or 0)
if have_bytes and byte_totals:
total = sum(byte_totals.values()) or 1
return [
LanguageData(
language=lang,
percentage=round(size / total * 100, 1),
loc=size,
)
for lang, size in sorted(byte_totals.items(), key=lambda x: -x[1])
]
# Legacy fallback: repo-count by primary language.
lang_counts: dict[str, int] = defaultdict(int)
for r in repos: for r in repos:
lang = r.get("language") lang = r.get("language")
if lang and lang not in hidden_languages: if lang and lang not in hidden_set:
lang_counts[lang] += 1 lang_counts[lang] += 1
total = sum(lang_counts.values()) or 1 total = sum(lang_counts.values()) or 1
@@ -488,6 +535,115 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) ->
] ]
def compute_streaks(github_data: dict, stored: dict | None) -> StreakData:
"""
Compute the user's current and longest contribution streaks.
Current streak: starts at today if today has contributions; else at
yesterday if yesterday has contributions (1-day grace for end-of-UTC).
Walks backward while consecutive days are all active.
Max streak: scans the contribution window for the longest consecutive run,
then merges with `stored["max_streak"]`. The greater value wins; when the
stored value wins, its start/end dates are preserved.
Args:
github_data: Raw fetcher payload; reads "commits" as a list of
{"date": "YYYY-MM-DD", "count": N}. Zero-count entries are ignored.
stored: Optional dict from db.get_user_streak(username). None on first
observation.
"""
entries = github_data.get("commits") or []
active = set()
for e in entries:
if not isinstance(e, dict):
continue
d = e.get("date")
n = e.get("count") or 0
if d and n > 0:
active.add(d)
stored = stored or {}
prior_max = int(stored.get("max_streak", 0) or 0)
prior_max_start = stored.get("max_start", "") or ""
prior_max_end = stored.get("max_end", "") or ""
stored_last = stored.get("last_active_date", "") or ""
if not active:
return StreakData(
current=0,
max=prior_max,
current_start="",
last_active_date=stored_last,
max_start=prior_max_start,
max_end=prior_max_end,
)
today = datetime.utcnow().date()
yesterday = today - timedelta(days=1)
if today.isoformat() in active:
cursor = today
elif yesterday.isoformat() in active:
cursor = yesterday
else:
cursor = None
current = 0
current_start = ""
if cursor is not None:
start = cursor
while start.isoformat() in active:
current += 1
start -= timedelta(days=1)
current_start = (start + timedelta(days=1)).isoformat()
sorted_dates = sorted(active)
from datetime import date as _date
max_len = 0
max_start_iso = ""
max_end_iso = ""
run_start = sorted_dates[0]
run_len = 1
prev = _date.fromisoformat(run_start)
for ds in sorted_dates[1:]:
cur = _date.fromisoformat(ds)
if (cur - prev).days == 1:
run_len += 1
else:
if run_len > max_len:
max_len = run_len
max_start_iso = run_start
max_end_iso = prev.isoformat()
run_start = ds
run_len = 1
prev = cur
if run_len > max_len:
max_len = run_len
max_start_iso = run_start
max_end_iso = prev.isoformat()
if max_len > prior_max:
merged_max = max_len
merged_start = max_start_iso
merged_end = max_end_iso
else:
merged_max = prior_max
merged_start = prior_max_start
merged_end = prior_max_end
last_active = sorted_dates[-1]
return StreakData(
current=current,
max=merged_max,
current_start=current_start,
last_active_date=last_active,
max_start=merged_start,
max_end=merged_end,
)
def generate_widgets_from_github( def generate_widgets_from_github(
github_data: dict, github_data: dict,
theme: str = "dark", theme: str = "dark",
@@ -495,6 +651,8 @@ def generate_widgets_from_github(
hidden_languages: list[str] = None, hidden_languages: list[str] = None,
enabled: list[str] = None, enabled: list[str] = None,
widget_settings: dict[str, dict] | None = None, widget_settings: dict[str, dict] | None = None,
achievements: list[dict] | None = None,
stored_streak: dict | None = None,
) -> dict[str, str]: ) -> dict[str, str]:
""" """
Takes raw GitHub API data and returns rendered SVG strings Takes raw GitHub API data and returns rendered SVG strings
@@ -509,8 +667,10 @@ def generate_widgets_from_github(
Defaults to ENABLED_WIDGETS from config. Defaults to ENABLED_WIDGETS from config.
widget_settings: Optional per-widget settings dict, keyed by widget name. widget_settings: Optional per-widget settings dict, keyed by widget name.
Each value is a dict of settings for that widget's renderer. Each value is a dict of settings for that widget's renderer.
stored_streak: Optional dict from db.get_user_streak(username); carries
the all-time longest streak forward across refreshes.
""" """
from ..config import ENABLED_WIDGETS from .config import ENABLED_WIDGETS
if enabled is None: if enabled is None:
enabled = ENABLED_WIDGETS enabled = ENABLED_WIDGETS
@@ -539,4 +699,23 @@ def generate_widgets_from_github(
languages = compute_languages(github_data, hidden_languages=hidden_languages) languages = compute_languages(github_data, hidden_languages=hidden_languages)
widgets["languages"] = render_languages_widget(languages, theme, settings=ws.get("languages")) widgets["languages"] = render_languages_widget(languages, theme, settings=ws.get("languages"))
if "streaks" in enabled_set:
streak = compute_streaks(github_data, stored_streak)
widgets["streaks"] = render_streaks_widget(streak, theme, settings=ws.get("streaks"))
if "achievements" in enabled_set:
# User-authored content — no GitHub data involved.
raw = [a for a in (achievements or []) if (a.get("title") or "").strip()]
items = [
AchievementData(
title=a.get("title", ""),
subtitle=a.get("subtitle", ""),
event_date=a.get("event_date", ""),
icon=a.get("icon", "trophy"),
)
for a in raw
]
if items:
widgets["achievements"] = render_achievements_widget(items, theme, settings=ws.get("achievements"))
return widgets return widgets
+108
View File
@@ -0,0 +1,108 @@
"""Auto-awarded profile tags.
This is the single place to add new custom tags. Three pieces plug together:
TAG_DEFS — display metadata (color, label) for each tag ID.
USER_TAGS — hardcoded tags by username. Great for VIP/creator badges.
TAG_RULES — predicate-driven awards based on account signals.
To add a new tag:
1. Add its color + label to TAG_DEFS below.
2. Award it either by listing the username in USER_TAGS, or by appending
a (tag_id, predicate) pair to TAG_RULES.
Predicates receive (username, github_data) and return one of:
False / None — not awarded
True — awarded with the default TAG_DEFS label
str — awarded with this string as a custom label (e.g. "Founder #42")
Any exception inside a predicate is swallowed — a broken rule can't break the
whole tag pipeline.
"""
from typing import Callable, Union
# ---- Display metadata -------------------------------------------------------
TAG_DEFS: dict[str, dict] = {
"creator": {"color": "#f472b6", "label": "Creator"},
"open-source": {"color": "#3fb950", "label": "Open Source"},
"founder": {"color": "#facc15", "label": "Founder"},
"hackathon-winner": {"color": "#fb923c", "label": "Hackathon Winner"},
"early-adopter": {"color": "#a78bfa", "label": "Early Adopter"},
}
# ---- Username → tags --------------------------------------------------------
# Usernames are compared case-insensitively.
USER_TAGS: dict[str, list[str]] = {
"shaymanor": ["creator"],
}
# ---- Rule predicates --------------------------------------------------------
PredicateResult = Union[bool, str, None]
def _open_source_maintainer(username: str, data: dict) -> PredicateResult:
"""At least 3 non-fork repos with ≥10 stars, OR ≥50 total stars."""
repos = data.get("repos") or []
non_fork = [r for r in repos if not r.get("fork")]
popular = sum(1 for r in non_fork if (r.get("stargazers_count") or 0) >= 10)
total_stars = sum((r.get("stargazers_count") or 0) for r in non_fork)
return popular >= 3 or total_stars >= 50
def _first_n_enrolled(n: int) -> Callable[[str, dict], PredicateResult]:
"""Returns a predicate that fires for users in the first N enrollments.
When it fires, the label includes the rank (e.g. "Founder #42").
"""
def predicate(username: str, _data: dict) -> PredicateResult:
from .db import enrollment_rank
rank = enrollment_rank(username)
if rank is None or rank > n:
return False
return f"Founder #{rank}"
return predicate
TAG_RULES: list[tuple[str, Callable[[str, dict], PredicateResult]]] = [
("open-source", _open_source_maintainer),
("founder", _first_n_enrolled(1000)),
]
# ---- Entry point ------------------------------------------------------------
def evaluate(username: str, github_data: dict) -> list[tuple[str, str | None]]:
"""Return ordered (tag_id, label_override) pairs awarded to this user.
label_override is None unless the predicate returned a string, in which
case that string replaces the default TAG_DEFS label for this user.
"""
awarded: list[tuple[str, str | None]] = []
seen: set[str] = set()
key = (username or "").lower()
for tag in USER_TAGS.get(key, []):
if tag not in seen:
awarded.append((tag, None))
seen.add(tag)
for tag, predicate in TAG_RULES:
if tag in seen:
continue
try:
result = predicate(username, github_data)
except Exception:
continue
if not result:
continue
label = result if isinstance(result, str) else None
awarded.append((tag, label))
seen.add(tag)
return awarded
@@ -94,6 +94,21 @@ TAG_COLORS = {
"open-source": "#3fb950", "open-source": "#3fb950",
} }
# Pick up colors for custom/auto-awarded tags defined in src/tag_rules.py so
# adding a new tag there is a single-file change.
def _merge_custom_tag_colors() -> None:
try:
from .. import tag_rules
except Exception:
return
for tag_id, meta in tag_rules.TAG_DEFS.items():
color = meta.get("color")
if color and tag_id not in TAG_COLORS:
TAG_COLORS[tag_id] = color
_merge_custom_tag_colors()
GRADE_COLORS = { GRADE_COLORS = {
"S": "#ff6b9d", "S": "#ff6b9d",
"A": "#3fb950", "A": "#3fb950",
+17
View File
@@ -0,0 +1,17 @@
"""Utility functions for SVG generation."""
from .svg_helpers import escape, card_wrapper, icon_svg
from .validate import (
is_valid_username,
is_valid_color,
safe_color,
validate_theme_name,
clip_text,
settings_size_ok,
)
__all__ = [
"escape", "card_wrapper", "icon_svg",
"is_valid_username", "is_valid_color", "safe_color",
"validate_theme_name", "clip_text", "settings_size_ok",
]
@@ -36,7 +36,7 @@ def icon_svg(kind: str, color: str) -> str:
icons = { icons = {
"commits": f'<circle cx="7" cy="7" r="3" fill="none" stroke="{color}" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="{color}"/><line x1="7" y1="10" x2="7" y2="14" stroke="{color}" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="{color}" stroke-width="1.4"/>', "commits": f'<circle cx="7" cy="7" r="3" fill="none" stroke="{color}" stroke-width="1.4"/><circle cx="7" cy="7" r="1" fill="{color}"/><line x1="7" y1="10" x2="7" y2="14" stroke="{color}" stroke-width="1.4"/><line x1="7" y1="0" x2="7" y2="4" stroke="{color}" stroke-width="1.4"/>',
"prs": f'<circle cx="4" cy="4" r="2" fill="none" stroke="{color}" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="{color}" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="{color}" stroke-width="1.2"/>', "prs": f'<circle cx="4" cy="4" r="2" fill="none" stroke="{color}" stroke-width="1.2"/><circle cx="10" cy="10" r="2" fill="none" stroke="{color}" stroke-width="1.2"/><path d="M4 6v4c0 1.1.9 2 2 2h2" fill="none" stroke="{color}" stroke-width="1.2"/>',
"stars": f'<path d="M7 1l1.8 3.6 4 .6-2.9 2.8.7 4L7 10.2 3.4 12l.7-4L1.2 5.2l4-.6z" fill="{color}" opacity="0.85"/>', "stars": f'<path d="M7 1l1.8 3.6 4 .6-2.9 2.8.7 4L7 10.2 3.4 12l.7-4L1.2 5.2l4-.6z" fill="none" stroke="{color}" stroke-width="1.2" stroke-linejoin="round"/>',
"repos": f'<rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="{color}" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="{color}" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="{color}" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="{color}" stroke-width="1"/>', "repos": f'<rect x="2" y="1" width="10" height="12" rx="1.5" fill="none" stroke="{color}" stroke-width="1.2"/><line x1="5" y1="4" x2="9" y2="4" stroke="{color}" stroke-width="1"/><line x1="5" y1="6.5" x2="9" y2="6.5" stroke="{color}" stroke-width="1"/><line x1="5" y1="9" x2="7" y2="9" stroke="{color}" stroke-width="1"/>',
"followers": f'<circle cx="5" cy="4" r="2.5" fill="none" stroke="{color}" stroke-width="1.2"/><path d="M0.5 12c0-2.5 2-4 4.5-4s4.5 1.5 4.5 4" fill="none" stroke="{color}" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="{color}" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="{color}" stroke-width="1"/>', "followers": f'<circle cx="5" cy="4" r="2.5" fill="none" stroke="{color}" stroke-width="1.2"/><path d="M0.5 12c0-2.5 2-4 4.5-4s4.5 1.5 4.5 4" fill="none" stroke="{color}" stroke-width="1.2"/><circle cx="11" cy="3.5" r="1.8" fill="none" stroke="{color}" stroke-width="1"/><path d="M10 7.5c1.5 0 3.5 1 3.5 3" fill="none" stroke="{color}" stroke-width="1"/>',
} }
+62
View File
@@ -0,0 +1,62 @@
"""Input validation helpers shared across API, worker, and widget renderers.
These sit at the trust boundary between user input and anything that flows
into (a) outbound URLs to GitHub, (b) SVG markup, or (c) persisted settings.
Anything that crosses that boundary must be validated here first.
"""
from __future__ import annotations
import re
# GitHub usernames: 1–39 chars, alphanumeric or single hyphens, cannot start/end
# with a hyphen and cannot have consecutive hyphens. This matches GitHub's own
# signup regex — anything outside it is not a real account and should not be
# forwarded to the fetcher or embedded in URLs / GraphQL.
_USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
# CSS color accepted by the widget renderers: #rgb, #rrggbb, #rrggbbaa, or a
# short allow-list of named colors that we actually use in themes. Permissive
# parsers let an attacker smuggle quote chars into SVG attribute context.
_COLOR_HEX_RE = re.compile(r"^#[0-9a-fA-F]{3,8}$")
_COLOR_NAMES = {
"transparent", "currentcolor", "none",
"white", "black", "red", "green", "blue",
}
_MAX_SETTINGS_BYTES = 64 * 1024 # 64 KB — plenty for theme + achievements
def is_valid_username(name: str) -> bool:
return isinstance(name, str) and bool(_USERNAME_RE.match(name))
def is_valid_color(value: str) -> bool:
if not isinstance(value, str) or len(value) > 32:
return False
return bool(_COLOR_HEX_RE.match(value)) or value.lower() in _COLOR_NAMES
def safe_color(value, fallback: str) -> str:
"""Return `value` if it's a valid color string, else `fallback`."""
return value if is_valid_color(value) else fallback
def validate_theme_name(name, allowed: set[str], fallback: str = "dark") -> str:
"""Return name if it's in `allowed`, else `fallback`. Prevents KeyError DoS
on THEMES[name] when a user patches in an unknown theme."""
if isinstance(name, str) and name in allowed:
return name
return fallback
def clip_text(value, max_len: int) -> str:
"""Coerce `value` to a string and truncate. Used for user-authored fields
that flow into SVG text (title, subtitle, event_date)."""
if value is None:
return ""
s = value if isinstance(value, str) else str(value)
return s[:max_len]
def settings_size_ok(raw_json: str) -> bool:
return len(raw_json.encode("utf-8")) <= _MAX_SETTINGS_BYTES
@@ -6,6 +6,7 @@ from .collaborators import render_collaborators_widget
from .focus import render_focus_widget from .focus import render_focus_widget
from .languages import render_languages_widget from .languages import render_languages_widget
from .achievements import render_achievements_widget from .achievements import render_achievements_widget
from .streaks import render_streaks_widget
from .composite import compose_widget from .composite import compose_widget
__all__ = [ __all__ = [
@@ -15,5 +16,6 @@ __all__ = [
"render_focus_widget", "render_focus_widget",
"render_languages_widget", "render_languages_widget",
"render_achievements_widget", "render_achievements_widget",
"render_streaks_widget",
"compose_widget", "compose_widget",
] ]
@@ -18,7 +18,8 @@ def _achievement_icon_svg(icon_type: str, color: str) -> str:
<path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="{color}" stroke-width="1.5" fill="none" stroke-linecap="round"/> <path d="M9 3l3 8m0-8l3 8m-6-8h6" stroke="{color}" stroke-width="1.5" fill="none" stroke-linecap="round"/>
</svg>''', </svg>''',
"star": f'''<svg viewBox="0 0 24 24" width="24" height="24"> "star": f'''<svg viewBox="0 0 24 24" width="24" height="24">
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" fill="{color}" opacity="0.85"/> <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"
fill="none" stroke="{color}" stroke-width="1.5" stroke-linejoin="round"/>
</svg>''', </svg>''',
"hackathon": f'''<svg viewBox="0 0 24 24" width="24" height="24"> "hackathon": f'''<svg viewBox="0 0 24 24" width="24" height="24">
<rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="{color}" stroke-width="1.5"/> <rect x="4" y="5" width="16" height="11" rx="1" fill="none" stroke="{color}" stroke-width="1.5"/>
@@ -65,7 +66,7 @@ def render_achievements_widget(
<text x="48" y="20" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" <text x="48" y="20" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="13" font-weight="600" fill="{t["text"]}">{escape(ach.title)}</text> font-size="13" font-weight="600" fill="{t["text"]}">{escape(ach.title)}</text>
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" <text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="10" fill="{t["text_secondary"]}">{escape(ach.subtitle)}{(" · " + ach.event_date) if ach.event_date else ""}</text> font-size="10" fill="{t["text_secondary"]}">{escape(ach.subtitle)}{(" · " + escape(ach.event_date)) if ach.event_date else ""}</text>
</g>''' </g>'''
total_h = len(shown) * 56 + 50 total_h = len(shown) * 56 + 50
@@ -2,7 +2,7 @@
from ..models import CollaboratorData from ..models import CollaboratorData
from ..themes import THEMES from ..themes import THEMES
from ..utils import escape, card_wrapper from ..utils import escape, card_wrapper, safe_color
def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str = "dark", settings: dict | None = None) -> str: def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str = "dark", settings: dict | None = None) -> str:
@@ -15,7 +15,7 @@ def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str
t = THEMES[theme_name] t = THEMES[theme_name]
s = settings or {} s = settings or {}
max_count = min(max(int(s.get("max_count", 5)), 1), 10) max_count = min(max(int(s.get("max_count", 5)), 1), 10)
bar_color = s.get("bar_color") or t["purple"] bar_color = safe_color(s.get("bar_color"), t["purple"])
items = "" items = ""
for i, c in enumerate(collabs[:max_count]): for i, c in enumerate(collabs[:max_count]):
@@ -96,5 +96,5 @@ def compose_widget(
{embedded} {embedded}
<text x="{total_w // 2}" y="{total_h - 8}" text-anchor="middle" <text x="{total_w // 2}" y="{total_h - 8}" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="{t["text_secondary"]}" opacity="0.5">Generated with ♥</text> font-size="9" fill="{t["text_secondary"]}" opacity="0.5">Generated with gh-stats</text>
</svg>''' </svg>'''
@@ -5,6 +5,25 @@ from ..models import GradeData
from ..themes import THEMES, TAG_COLORS, GRADE_COLORS from ..themes import THEMES, TAG_COLORS, GRADE_COLORS
from ..utils import escape, card_wrapper, icon_svg from ..utils import escape, card_wrapper, icon_svg
# Tokens that should render uppercase instead of title-cased (e.g. "ml-engineer"
# → "ML Engineer", not "Ml Engineer").
_TAG_ACRONYMS = {"ml", "ai", "ui", "ux", "api", "cli", "sql", "css", "html", "js", "ios"}
def _format_tag_label(tag: str) -> str:
# Custom tags may define an explicit label in src/tag_rules.py::TAG_DEFS.
try:
from .. import tag_rules
meta = tag_rules.TAG_DEFS.get(tag)
if meta and meta.get("label"):
return meta["label"]
except Exception:
pass
return " ".join(
w.upper() if w.lower() in _TAG_ACRONYMS else w.capitalize()
for w in tag.split("-")
)
def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dict | None = None) -> str: def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dict | None = None) -> str:
"""Renders the developer grade widget with stats and tags. """Renders the developer grade widget with stats and tags.
@@ -63,7 +82,7 @@ def render_grade_widget(data: GradeData, theme_name: str = "dark", settings: dic
for tag in (data.tags or []): for tag in (data.tags or []):
tag_color = TAG_COLORS.get(tag.tag, t["accent"]) tag_color = TAG_COLORS.get(tag.tag, t["accent"])
label = tag.tag.replace("-", " ").title() label = getattr(tag, "label", None) or _format_tag_label(tag.tag)
tw = int(len(label) * 6.6 + 18) tw = int(len(label) * 6.6 + 18)
pill_opacity = 0.9 if tag.source == "earned" else 0.55 pill_opacity = 0.9 if tag.source == "earned" else 0.55
@@ -2,7 +2,7 @@
from ..models import ImpactWeek from ..models import ImpactWeek
from ..themes import THEMES from ..themes import THEMES
from ..utils import card_wrapper from ..utils import card_wrapper, safe_color
def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", period: str = "6mo", settings: dict | None = None) -> str: def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", period: str = "6mo", settings: dict | None = None) -> str:
@@ -13,7 +13,7 @@ def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", peri
""" """
t = THEMES[theme_name] t = THEMES[theme_name]
s = settings or {} s = settings or {}
line_color = s.get("line_color") or t["accent"] line_color = safe_color(s.get("line_color"), t["accent"])
w, h = 380, 200 w, h = 380, 200
chart_x, chart_y = 40, 8 chart_x, chart_y = 40, 8
chart_w, chart_h = 316, 82 chart_w, chart_h = 316, 82
+96
View File
@@ -0,0 +1,96 @@
"""Streaks widget rendering."""
from datetime import date
from ..models import StreakData
from ..themes import THEMES
from ..utils import escape, card_wrapper
_FLAME_SVG = (
'<path d="M12 2c1 4 5 5 5 10a5 5 0 1 1-10 0c0-2 1-3 2-4 0 1 1 2 2 2 '
'-1-2 0-5 1-8z" fill="{color}" opacity="0.95"/>'
)
_TROPHY_SVG = (
'<path d="M6 3h12v3a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V3z" fill="none" '
'stroke="{color}" stroke-width="1.6"/>'
'<path d="M4 4h2v2a2 2 0 0 1-2 2H3V5a1 1 0 0 1 1-1zM20 4h-2v2a2 2 0 0 0 2 '
'2h1V5a1 1 0 0 0-1-1z" fill="none" stroke="{color}" stroke-width="1.4"/>'
'<rect x="9" y="11" width="6" height="3" fill="{color}"/>'
'<rect x="7" y="14" width="10" height="2" rx="0.5" fill="{color}"/>'
)
def _fmt_date(iso: str) -> str:
if not iso:
return ""
try:
d = date.fromisoformat(iso)
except ValueError:
return ""
return d.strftime("%b %d, %Y")
def _fmt_range(start: str, end: str) -> str:
s = _fmt_date(start)
e = _fmt_date(end)
if s and e:
return f"{s} – {e}"
return s or e
def render_streaks_widget(
data: StreakData,
theme_name: str = "dark",
settings: dict | None = None,
) -> str:
"""Render the streaks widget.
Settings:
show_dates (bool): Show date captions below each number. Default True.
"""
t = THEMES[theme_name]
s = settings or {}
show_dates = bool(s.get("show_dates", True))
width = 380
height = 170
col_w = width / 2
current_color = t["accent"]
max_color = t.get("text", "#e6e6e6")
current_sub = _fmt_date(data.current_start) if data.current_start else "—"
max_sub = _fmt_range(data.max_start, data.max_end) if (data.max_start or data.max_end) else ""
date_lines = ""
if show_dates:
date_lines = f'''
<text x="{col_w / 2}" y="130" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="{t["text_secondary"]}">{escape("since " + current_sub) if data.current > 0 else ""}</text>
<text x="{col_w + col_w / 2}" y="130" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="9" fill="{t["text_secondary"]}">{escape(max_sub)}</text>'''
inner = f'''
<g transform="translate({col_w / 2 - 12}, 14)">{_FLAME_SVG.format(color=current_color)}</g>
<text x="{col_w / 2}" y="78" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="{current_color}">{data.current}</text>
<text x="{col_w / 2}" y="108" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="{t["text_secondary"]}" letter-spacing="0.5">Current Streak</text>
<line x1="{col_w}" y1="24" x2="{col_w}" y2="{height - 24 - 36}" stroke="{t["grid"]}" stroke-width="1"/>
<g transform="translate({col_w + col_w / 2 - 12}, 14)">{_TROPHY_SVG.format(color=max_color)}</g>
<text x="{col_w + col_w / 2}" y="78" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="40" font-weight="800" fill="{max_color}">{data.max}</text>
<text x="{col_w + col_w / 2}" y="108" text-anchor="middle"
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
font-size="11" fill="{t["text_secondary"]}" letter-spacing="0.5">Longest Streak</text>
{date_lines}'''
return card_wrapper(inner, width, height, t, "")
+154
View File
@@ -0,0 +1,154 @@
"""Prefetch worker. Pulls pending jobs and populates widget data.
Two-phase pipeline:
* Phase 1 (this module): on enroll/settings-change, fetch the raw GitHub
payload from the fetcher and compute widget data for the client-side
Workshop preview. No SVG rendering.
* Phase 2 (render_widgets_now, called from the API's Generate endpoint):
synchronously render composite SVG from the cached raw + current
settings and persist to widgets.db.
This split keeps the fetcher hot while the user edits settings and defers
expensive SVG composition until the user clicks Generate.
Run as its own container: CMD python -m src.worker
"""
import logging
import time
from dataclasses import asdict
from . import cache, config, db, fetcher_client, placeholder, processor
from .widgets import compose_widget
log = logging.getLogger("generator.worker")
MAX_ATTEMPTS = 3
def _compute_widget_data(payload: dict, settings: dict, username: str) -> dict:
"""Compute raw widget data dict for client-side rendering.
Also persists the user's streak state as a side effect — the longest streak
must survive settings-hash rotations, so it lives outside widget_data.
"""
custom_tags = settings.get("custom_tags")
hidden_languages = settings.get("hidden_languages")
stored_streak = db.get_user_streak(username)
streak = processor.compute_streaks(payload, stored_streak)
db.put_user_streak(username, {
"current_streak": streak.current,
"current_start": streak.current_start,
"last_active_date": streak.last_active_date,
"max_streak": streak.max,
"max_start": streak.max_start,
"max_end": streak.max_end,
})
return {
"grade": asdict(processor.compute_grade(payload, custom_tags=custom_tags)),
"impact": [asdict(w) for w in processor.compute_impact_timeline(payload)],
"collaborators": [asdict(c) for c in processor.compute_collaborators(payload)],
"focus": [asdict(f) for f in processor.compute_focus(payload, hidden_languages=hidden_languages)],
"languages": [asdict(l) for l in processor.compute_languages(payload, hidden_languages=hidden_languages)],
"streaks": asdict(streak),
}
def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, str]:
enabled = settings.get("enabled") or config.ENABLED_WIDGETS
order = settings.get("widget_order") or config.WIDGET_ORDER
theme = settings.get("theme", "dark")
stored_streak = db.get_user_streak(username)
widgets = processor.generate_widgets_from_github(
payload,
theme=theme,
custom_tags=settings.get("custom_tags"),
hidden_languages=settings.get("hidden_languages"),
enabled=enabled,
widget_settings=settings.get("widget_settings") or {},
achievements=settings.get("achievements") or [],
stored_streak=stored_streak,
)
ordered = [w for w in order if w in enabled and w in widgets and widgets[w]]
composite = compose_widget(
widgets=widgets, enabled=ordered, theme_name=theme,
username=username, avatar_b64=payload.get("avatar_b64", ""),
)
out = {name: svg for name, svg in widgets.items() if svg}
out["composite"] = composite
return out
def process_one() -> bool:
"""Phase 1: claim a pending job and populate widget data (no SVG)."""
job = db.claim_next_job()
if job is None:
return False
username = job["username"]
try:
result = fetcher_client.get_data(username)
payload = result.get("data") or {}
if payload.get("error") == "not_found":
db.put_widget_data(username, "not_found", {"not_found": True})
db.point_current_widget(username, "not_found")
db.complete_job(job["id"])
log.info("not_found marker persisted for %s", username)
return True
settings_row = db.get_settings(username)
if settings_row is None:
db.fail_job(job["id"], "settings missing", retry=False)
return True
widget_data = _compute_widget_data(payload, settings_row["settings"], username)
db.put_widget_data(username, settings_row["settings_hash"], widget_data)
db.point_current_widget(username, settings_row["settings_hash"])
db.set_last_fetcher_hash(username, result.get("payload_hash", ""))
db.lru_trim(username, config.WIDGET_LRU_PER_USER)
db.complete_job(job["id"])
log.info("prefetched data for %s", username)
return True
except Exception as e:
retry = job["attempts"] < MAX_ATTEMPTS
db.fail_job(job["id"], str(e)[:500], retry=retry)
log.warning("prefetch failed for %s (retry=%s): %s", username, retry, e)
return True
def render_widgets_now(username: str) -> dict[str, str]:
"""Phase 2: synchronously render composite SVG and persist it.
Called from POST /api/<u>/generate. Reuses the fetcher's cached payload
(a cheap internal HTTP lookup) so the user-facing render is fast even
if the prefetch job hasn't drained from the queue yet.
"""
settings_row = db.get_settings(username)
if settings_row is None:
raise LookupError("not_enrolled")
result = fetcher_client.get_data(username)
payload = result.get("data") or {}
if payload.get("error") == "not_found":
svg = placeholder.render("not_found", username, theme=settings_row["settings"].get("theme", "dark"))
db.put_widgets(username, "not_found", {"composite": svg})
db.point_current_widget(username, "not_found")
cache.Cache().delete(f"widget:composite:{username}")
return {"composite": svg}
widgets = _render_widgets(username, payload, settings_row["settings"])
db.put_widgets(username, settings_row["settings_hash"], widgets)
db.point_current_widget(username, settings_row["settings_hash"])
c = cache.Cache()
c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets])
log.info("rendered widgets on-demand for %s", username)
return widgets
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
db.init_dbs()
while True:
db.reclaim_stuck_jobs(older_than_minutes=10)
if not process_one():
time.sleep(0.5)
if __name__ == "__main__":
main()
View File
@@ -0,0 +1,68 @@
"""End-to-end: api + worker in-process + mocked fetcher HTTP."""
import os, tempfile, time
import pytest
import responses
from src import api as apimod, db as dbmod, worker
@pytest.fixture
def env(monkeypatch):
with tempfile.TemporaryDirectory() as d:
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
monkeypatch.setattr(apimod.config, "FETCHER_URL", "http://fetcher-mock")
monkeypatch.setattr(apimod.config, "FETCHER_INTERNAL_TOKEN", "t")
dbmod.init_dbs()
yield
@responses.activate
def test_full_flow_data_then_generate_then_serve(env):
"""End-to-end of the new two-phase pipeline:
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/<u> serves the stored SVG to README consumers
"""
responses.add(
responses.GET, "http://fetcher-mock/data/alice",
json={"data": {"user": {"login": "alice"}, "repos": [], "events": [],
"commits": [], "total_commits": 0, "recent_commits": 0,
"total_prs": 0, "collaborators_data": [], "avatar_b64": ""},
"payload_hash": "h1"}, status=200,
)
client = apimod.app.test_client()
# 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
# Drain any residual job synchronously in case the kickoff thread lost
# the race (and to make the assertion deterministic).
for _ in range(5):
if not worker.process_one():
break
# Widget data should now be available for client-side preview.
deadline = time.time() + 2.0
while time.time() < deadline:
r = client.get("/api/alice/data")
if r.status_code == 200 and r.get_json().get("status") == "ready":
break
time.sleep(0.05)
assert r.status_code == 200 and r.get_json()["status"] == "ready"
# 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"
# Phase 3: SVG is served from DB.
r_svg = client.get("/api/alice")
assert r_svg.headers["X-Widget-Status"] == "ready"
assert r_svg.data.startswith(b"<svg") or r_svg.data.startswith(b"<?xml")
+268
View File
@@ -0,0 +1,268 @@
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
def client(monkeypatch):
# No-op the kickoff so tests don't spawn background threads that
# would try to reach the (unmocked) fetcher and race tempdir teardown.
monkeypatch.setattr(apimod, "_kickoff_prefetch_async", lambda *_a, **_kw: None)
with tempfile.TemporaryDirectory() as d:
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
# Clear rate limit state after each test to prevent pollution.
apimod._rate_hits.clear()
apimod._rate_hits_per_login.clear()
def test_health(client):
r = client.get("/api/health")
assert r.status_code == 200
assert r.get_json()["service"] == "generator"
def test_get_unknown_user_returns_building_placeholder_without_enrolling(client):
"""The SVG endpoint is for README embeds — enrollment is frontend-driven
through /data or /api/enroll, so GET /api/<u> does not auto-enroll."""
r = client.get("/api/alice")
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "building"
assert "Building" in r.data.decode()
assert dbmod.get_settings("alice") is None
def test_enrolled_but_not_generated_returns_building(client):
"""After enrollment (via /data) but before /generate is clicked the SVG
endpoint returns a building placeholder."""
dbmod.enroll("alice", {"theme": "dark"})
r = client.get("/api/alice")
assert r.headers["X-Widget-Status"] == "building"
def test_enrolled_user_with_built_widget_returns_ready(client):
dbmod.enroll("alice", {"theme": "dark"})
dbmod.put_widgets("alice", "h1", {"composite": "<svg>ready</svg>"})
dbmod.point_current_widget("alice", "h1")
r = client.get("/api/alice")
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "ready"
assert b"ready" in r.data
def test_settings_patch_enqueues_rebuild(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
assert dbmod.get_settings("alice")["settings"]["theme"] == "light"
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 == 403
# Settings must not be mutated when the origin check fails.
assert dbmod.get_settings("alice")["settings"]["theme"] == "dark"
def test_patch_settings_without_session_is_401(client):
dbmod.enroll("alice", {"theme": "dark"})
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):
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={"Origin": "https://gh-stats.com"})
assert r1.status_code == 200
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", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
def test_not_found_status_header(client):
dbmod.enroll("ghost", {"theme": "dark"})
dbmod.put_widgets("ghost", "not_found", {"composite": "<svg>404</svg>"})
dbmod.point_current_widget("ghost", "not_found")
r = client.get("/api/ghost")
assert r.headers["X-Widget-Status"] == "not_found"
def test_generate_endpoint_renders_and_stores_svg(client):
"""POST /api/<u>/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": "<svg>r</svg>", "grade": "<svg>g</svg>"}):
# Simulate the render path also updating current_widget so the
# follow-up GET sees ready.
def fake_render(username):
dbmod.put_widgets(username, "h1", {"composite": "<svg>r</svg>"})
dbmod.point_current_widget(username, "h1")
return {"composite": "<svg>r</svg>"}
with patch("src.worker.render_widgets_now", side_effect=fake_render):
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"
assert body["composite_url"] == "/api/alice"
r2 = client.get("/api/alice")
assert r2.headers["X-Widget-Status"] == "ready"
assert b"<svg>r</svg>" in r2.data
def test_generate_endpoint_rejects_unenrolled(client):
"""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
# ---- GET /api/<username>/data: precomputed widget data for client-side rendering ----
# Pure DB lookup — fetcher is never touched on the hot path.
def test_data_endpoint_enrolled_but_unbuilt_returns_building(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.get("/api/alice/data")
assert r.status_code == 202
assert r.get_json() == {"status": "building"}
def test_data_endpoint_returns_ready_after_build(client):
dbmod.enroll("alice", {"theme": "dark"})
sample = {"grade": {"grade": "A", "score": 80, "stats": {}, "tags": [], "breakdown": {}}}
dbmod.put_widget_data("alice", "h1", sample)
with dbmod._widgets_conn() as c:
c.execute(
"""INSERT INTO current_widget(username, settings_hash, updated_at)
VALUES ('alice', 'h1', '2026-04-18T00:00:00Z')
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash""")
c.commit()
r = client.get("/api/alice/data")
assert r.status_code == 200
body = r.get_json()
assert body["status"] == "ready"
assert body["data"] == sample
def test_data_endpoint_returns_not_found_for_unknown_github_user(client):
dbmod.enroll("ghost", {"theme": "dark"})
dbmod.put_widget_data("ghost", "not_found", {"not_found": True})
with dbmod._widgets_conn() as c:
c.execute(
"""INSERT INTO current_widget(username, settings_hash, updated_at)
VALUES ('ghost', 'not_found', '2026-04-18T00:00:00Z')
ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash""")
c.commit()
r = client.get("/api/ghost/data")
assert r.status_code == 404
assert r.get_json()["status"] == "not_found"
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
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
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
+173
View File
@@ -0,0 +1,173 @@
"""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/<username>", 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 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
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") == "/"
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
+15
View File
@@ -0,0 +1,15 @@
from src import cache
def test_noop_when_redis_url_empty(monkeypatch):
monkeypatch.setattr(cache.config, "REDIS_URL", "")
c = cache.Cache()
assert c.get("k") is None
c.set("k", "v", 60)
c.delete("k")
assert c.get("k") is None # still None because no-op
def test_enabled_flag_reflects_config(monkeypatch):
monkeypatch.setattr(cache.config, "REDIS_URL", "")
assert cache.Cache().enabled is False

Some files were not shown because too many files have changed in this diff Show More