feat(tags): add auto-awarded profile tags and validation utilities.

This commit is contained in:
shay
2026-04-19 09:37:32 -04:00
parent ca74e91e3e
commit 58e794fd57
3 changed files with 206 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
// Per-username edit token issued by the backend at enrollment. Presented
// as `Authorization: Bearer` on mutating endpoints (PATCH settings,
// POST refresh). Stored in localStorage so a reload keeps the user in
// control of their own profile.
//
// Without this token the backend rejects mutations with HTTP 401. Token is
// only surfaced on the FIRST enroll for a given username — re-hitting the
// enroll path for an existing user returns no token, so we never blow away
// a previously-saved token.
const STORAGE_PREFIX = 'grs:edit_token:'
const keyFor = (username: string) => STORAGE_PREFIX + username.toLowerCase()
export function getEditToken(username: string): string | null {
if (!username) return null
try {
return window.localStorage.getItem(keyFor(username))
} catch {
return null
}
}
export function saveEditToken(username: string, token: string | null | undefined): void {
if (!username || !token) return
try {
window.localStorage.setItem(keyFor(username), token)
} catch {
// localStorage can throw in private mode — fall through silently.
}
}
export function authHeaders(username: string): Record<string, string> {
const t = getEditToken(username)
return t ? { Authorization: `Bearer ${t}` } : {}
}
+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
+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