diff --git a/generator/frontend/src/App.tsx b/generator/frontend/src/App.tsx index fd02524..f3486ac 100644 --- a/generator/frontend/src/App.tsx +++ b/generator/frontend/src/App.tsx @@ -7,6 +7,7 @@ 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' +import { buildEmbedUrl } from './lib/settingsQuery' export type Achievement = { title: string @@ -38,8 +39,8 @@ export type WidgetSettings = { const DEFAULT_SETTINGS: WidgetSettings = { theme: 'midnight', - widgets: ['grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages'], - widgetOrder: ['grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages', 'achievements'], + widgets: ['name', 'grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages'], + widgetOrder: ['name', 'grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages', 'achievements'], impactPeriod: '6mo', customTags: [], hiddenLanguages: [], @@ -65,6 +66,11 @@ export default function App() { const [generatedSvg, setGeneratedSvg] = useState(null) const [generateError, setGenerateError] = useState(null) const [generating, setGenerating] = useState(false) + // The URL we actually fetched for the preview — also the one we show as + // the embed snippet. For owners this is /api/ (backed by stored + // settings). For visitors it's /api/?, which round-trips their + // Workshop edits without touching the owner's saved widget. + const [embedUrl, setEmbedUrl] = useState('') const pollTimer = useRef(null) const pollStart = useRef(0) const aborted = useRef(false) @@ -185,53 +191,76 @@ export default function App() { setGenerating(true) setGeneratedSvg(null) setGenerateError(null) + const isOwner = !!me.login && me.login.toLowerCase() === username.toLowerCase() 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, - widget_order: settings.widgetOrder, - 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 - } + if (isOwner) { + // Owner path: persist settings, then force a server-side render + // against the stored payload. The resulting /api/ is the embed. + const backendSettings = { + theme: settings.theme, + enabled: settings.widgets, + widget_order: settings.widgetOrder, + 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 + 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 + } + const cleanUrl = `${window.location.origin}/api/${encodeURIComponent(username)}` + // Cache-bust so regenerate after settings change shows the new + // version, not a stale browser copy. The cache-busting `t` param + // is not read server-side (not in the allow-list) so the render + // stays cacheable at the edge. + const svgRes = await fetch(`${cleanUrl}?t=${Date.now()}`) + if (!svgRes.ok) { + setGenerateError(`SVG fetch failed (HTTP ${svgRes.status})`) + return + } + setGeneratedSvg(await svgRes.text()) + setEmbedUrl(cleanUrl) + } else { + // Visitor path: encode Workshop edits into a query string and hit + // the same URL we'll hand the user for their README. No owner + // settings are written. The backend renders ad-hoc against the + // fetcher's cached payload for this user. + const url = buildEmbedUrl(window.location.origin, username, settings) + // Same cache-bust trick — unknown query params are ignored by the + // sanitizer, so this doesn't alter the rendered output. + const svgRes = await fetch(`${url}${url.includes('?') ? '&' : '?'}t=${Date.now()}`) + if (svgRes.status === 404) { + setGenerateError('User not enrolled — ask them to sign in and generate first') + return + } + if (!svgRes.ok) { + setGenerateError(`SVG fetch failed (HTTP ${svgRes.status})`) + return + } + setGeneratedSvg(await svgRes.text()) + setEmbedUrl(url) } - 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') @@ -277,6 +306,7 @@ export default function App() { generating={generating} generatedSvg={generatedSvg} generateError={generateError} + embedUrl={embedUrl} onBack={handleBack} onRegenerate={handleGenerate} /> diff --git a/generator/frontend/src/lib/renderWidgets.ts b/generator/frontend/src/lib/renderWidgets.ts index 2ad025a..9aa8cc6 100644 --- a/generator/frontend/src/lib/renderWidgets.ts +++ b/generator/frontend/src/lib/renderWidgets.ts @@ -426,8 +426,10 @@ export function renderAllWidgets(opts: { 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 showName = enabled.has('name') + const totalW = 420, headerH = showName ? 60 : 0, padding = 20, gap = 16 + // "name" is a pseudo-widget — it controls the header, not a rendered svg. + const ordered = opts.widgetOrder.filter(k => k !== 'name' && enabled.has(k) && widgetSvgs[k]) const parts = ordered.map(key => { const { inner, h } = extractInner(widgetSvgs[key], key) @@ -437,8 +439,21 @@ export function renderAllWidgets(opts: { 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 = `` - const header = `${avatar}${esc(opts.username || 'Developer')}` + // Header (avatar + username). Only drawn when "name" is enabled. The + // avatar pulls from github.com/.png which redirects to + // avatars.githubusercontent.com; the accent circle underneath is a + // fallback for missing users / slow loads. + let header = '' + if (showName) { + const avatarUrl = opts.username + ? `https://github.com/${encodeURIComponent(opts.username)}.png?size=64` + : '' + const avatarImg = avatarUrl + ? `` + : '' + const avatar = `${avatarImg}` + header = `${avatar}${esc(opts.username || 'Developer')}` + } let yOffset = headerH + padding let embedded = '' diff --git a/generator/frontend/src/screens/WorkshopScreen.tsx b/generator/frontend/src/screens/WorkshopScreen.tsx index da18332..4d53204 100644 --- a/generator/frontend/src/screens/WorkshopScreen.tsx +++ b/generator/frontend/src/screens/WorkshopScreen.tsx @@ -25,15 +25,21 @@ const SVG_SANITIZE_CONFIG = { ], } +// Mini-preview swatches (bg + card + accent). Flat-color swatches all read +// the same dark/light — showing the accent color is what actually separates +// Midnight (blue) from Onyx (purple) from Nord (cyan), etc. 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 }, + { id: 'midnight', label: 'Midnight', bg: '#121820', card: '#1a2230', border: '#2a3444', accent: '#58a6ff', light: false }, + { id: 'onyx', label: 'Onyx', bg: '#09090b', card: '#18181b', border: '#27272a', accent: '#a78bfa', light: false }, + { id: 'nord', label: 'Nord', bg: '#1e2433', card: '#2a3142', border: '#3d4659', accent: '#88c0d0', light: false }, + { id: 'clean', label: 'Clean', bg: '#ffffff', card: '#f6f8fa', border: '#d8dee4', accent: '#0969da', light: true }, + { id: 'paper', label: 'Paper', bg: '#faf8f5', card: '#f5f0eb', border: '#e0d8cf', accent: '#b45309', light: true }, ] const ALL_WIDGETS = [ + // "name" is the avatar + username header. Pinned at the top — can be + // toggled off but never reordered. Keep this entry first. + { id: 'name', label: 'Name' }, { id: 'grade', label: 'Grade' }, { id: 'impact', label: 'Impact Timeline' }, { id: 'streaks', label: 'Streaks' }, @@ -75,8 +81,12 @@ const ICONS: { id: string; svg: ReactNode }[] = [ id: 'medal', svg: ( - - + + + + + + ), }, @@ -199,7 +209,7 @@ function ColorPicker({ value, onChange }: { value: string; onChange: (v: string) 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' + value === c ? 'ring-2 ring-offset-1 ring-gray-900' : 'hover:ring-1 hover:ring-gray-300' }`} style={{ backgroundColor: c }} /> @@ -243,9 +253,13 @@ export function WorkshopScreen({ // the stored order forgot. Keeps the UI functional if ALL_WIDGETS // gains or loses an entry between releases. const knownIds = useMemo(() => new Set(ALL_WIDGETS.map(w => w.id)), []) + // "name" is pinned at index 0 regardless of persisted order. We still keep + // it in orderedIds so the composite-render path can find it, but the drag + // UI below treats it as non-reorderable. const orderedIds = useMemo(() => { const seen = new Set() - const out: string[] = [] + const out: string[] = ['name'] + seen.add('name') for (const id of settings.widgetOrder) { if (knownIds.has(id) && !seen.has(id)) { seen.add(id); out.push(id) } } @@ -257,6 +271,8 @@ export function WorkshopScreen({ const moveWidget = (from: number, to: number) => { if (from === to || from < 0 || to < 0 || from >= orderedIds.length || to >= orderedIds.length) return + // Never move "name" and never drop another widget above it (index 0). + if (orderedIds[from] === 'name' || to === 0) return const next = orderedIds.slice() const [item] = next.splice(from, 1) next.splice(to, 0, item) @@ -367,15 +383,23 @@ export function WorkshopScreen({ key={t.id} onClick={() => updateSetting('theme', t.id)} title={t.label} - className={`w-9 h-9 rounded-lg transition-all ${ + aria-label={t.label} + className={`w-9 h-9 rounded-lg overflow-hidden 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' + ? 'ring-2 ring-gray-900 ring-offset-2' + : t.light + ? 'ring-1 ring-gray-200 hover:ring-gray-300' + : 'hover:ring-1 hover:ring-gray-400 hover:ring-offset-1' }`} - style={{ backgroundColor: t.color }} - /> + > + + + + + + + + ))}
@@ -393,24 +417,28 @@ export function WorkshopScreen({ const enabled = settings.widgets.includes(w.id) const hasAdvanced = ['grade', 'impact', 'streaks', 'collaborators', 'focus', 'languages', 'achievements'].includes(w.id) const isExpanded = expandedWidget === w.id && enabled - const isDragging = dragIndex === idx - const showDropLineAbove = dropIndex === idx && dragIndex !== null && dragIndex !== idx + // "name" is pinned — no drag affordance, no drop lines. + // The dropIndex comparisons below still use the real idx + // so downstream rows behave normally when name is skipped. + const isPinned = w.id === 'name' + const isDragging = !isPinned && dragIndex === idx + const showDropLineAbove = !isPinned && idx > 0 && dropIndex === idx && dragIndex !== null && dragIndex !== idx // Drop-line below the last row when dragging past the end. - const showDropLineBelow = idx === orderedIds.length - 1 && dropIndex === orderedIds.length && dragIndex !== null + const showDropLineBelow = !isPinned && idx === orderedIds.length - 1 && dropIndex === orderedIds.length && dragIndex !== null return (
- {showDropLineAbove &&
} + {showDropLineAbove &&
}
{ + draggable={!isPinned} + onDragStart={isPinned ? undefined : e => { setDragIndex(idx) e.dataTransfer.effectAllowed = 'move' // Firefox needs some payload to start a drag. e.dataTransfer.setData('text/plain', String(idx)) }} - onDragOver={e => { + onDragOver={isPinned ? undefined : e => { if (dragIndex === null) return e.preventDefault() e.dataTransfer.dropEffect = 'move' @@ -427,7 +455,7 @@ export function WorkshopScreen({ setDropIndex(target) } }} - onDrop={e => { + onDrop={isPinned ? undefined : e => { e.preventDefault() if (dragIndex === null || dropIndex === null) { setDragIndex(null); setDropIndex(null); return @@ -438,15 +466,28 @@ export function WorkshopScreen({ moveWidget(dragIndex, to) setDragIndex(null); setDropIndex(null) }} - onDragEnd={() => { setDragIndex(null); setDropIndex(null) }} + onDragEnd={isPinned ? undefined : () => { setDragIndex(null); setDropIndex(null) }} > - - ⋮⋮ - + {isPinned ? ( + + + + + + + ) : ( + + ⋮⋮ + + )} {hasAdvanced && enabled && ( @@ -468,7 +509,7 @@ export function WorkshopScreen({ )}
- {showDropLineBelow &&
} + {showDropLineBelow &&
} {isExpanded && (
diff --git a/generator/src/config.py b/generator/src/config.py index 6548122..fe9593b 100644 --- a/generator/src/config.py +++ b/generator/src/config.py @@ -55,10 +55,11 @@ DATA_SOURCE_TYPE = os.getenv("DATA_SOURCE", "direct") """Data source type: 'direct' for immediate API calls, 'queued' for batch processing.""" # Widget settings -WIDGET_ORDER = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"] -"""Default order of widgets. Customize by reordering this list.""" +WIDGET_ORDER = ["name", "grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"] +"""Default order of widgets. "name" is the avatar+username header and is +always pinned first in the UI — it can be toggled off but not reordered.""" -ENABLED_WIDGETS = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"] +ENABLED_WIDGETS = ["name", "grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"] """Which widgets to display. Remove any you don't want to show.""" # Language filtering diff --git a/generator/src/widgets/composite.py b/generator/src/widgets/composite.py index 2a6f7a5..c831790 100644 --- a/generator/src/widgets/composite.py +++ b/generator/src/widgets/composite.py @@ -40,20 +40,29 @@ def compose_widget( theme_name: str = "dark", username: str = "", avatar_b64: str = "", + show_name: bool = True, ) -> str: """ Takes rendered SVG strings for each widget type and composes them into a single unified profile widget by inlining widget SVGs directly. + + `show_name` controls whether the avatar + username header block is + drawn. It's the "name" pseudo-widget — pinned first in the UI, can be + toggled off but not reordered. When false, widgets start at the top + edge (minus the standard padding) so there's no orphan gap. """ t = THEMES[theme_name] total_w = 420 - header_h = 60 + header_h = 60 if show_name else 0 padding = 20 gap = 16 - # Extract inner content from each widget SVG + # Extract inner content from each widget SVG. "name" has no rendered + # widget — it maps to the header block and is consumed by show_name. parts = [] for key in enabled: + if key == "name": + continue if key in widgets and widgets[key]: inner, h = _extract_inner(widgets[key], key) parts.append((key, inner, h)) @@ -61,16 +70,16 @@ def compose_widget( content_h = sum(h for _, _, h in parts) + gap * max(len(parts) - 1, 0) total_h = header_h + content_h + padding * 2 + 10 - # Header - avatar_svg = "" - if avatar_b64: - avatar_svg = f''' + # Header (avatar + username). Only drawn when "name" is enabled. + header = "" + if show_name: + if avatar_b64: + avatar_svg = f''' ''' - else: - avatar_svg = f'' - - header = f''' + else: + avatar_svg = f'' + header = f''' {avatar_svg} {escape(username or "Developer")} diff --git a/generator/src/worker.py b/generator/src/worker.py index d956c6e..2f78daa 100644 --- a/generator/src/worker.py +++ b/generator/src/worker.py @@ -67,10 +67,18 @@ def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, s 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]] + enabled_set = set(enabled) + show_name = "name" in enabled_set + # Preserve "name" in the ordered list so the composite honors its + # user-ordered position (always 0 today, but future-proof). + ordered = [ + w for w in order + if w in enabled_set and (w == "name" or (w in widgets and widgets[w])) + ] composite = compose_widget( widgets=widgets, enabled=ordered, theme_name=theme, username=username, avatar_b64=payload.get("avatar_b64", ""), + show_name=show_name, ) out = {name: svg for name, svg in widgets.items() if svg} out["composite"] = composite @@ -113,6 +121,29 @@ def process_one() -> bool: return True +def render_composite_adhoc(username: str, override_settings: dict) -> str | None: + """Render the composite SVG for `username` using stored settings merged + with the per-request `override_settings`. Does NOT persist anything. + + Used by the public `GET /api/?...` endpoint so unauthenticated visitors + can preview/embed a widget configured purely via query string, without + touching the owner's stored settings. + + Returns the SVG string, or None if the user isn't enrolled / the fetcher + has no data for them (caller should fall through to the cached path). + """ + settings_row = db.get_settings(username) + if settings_row is None: + return None + result = fetcher_client.get_data(username) + payload = result.get("data") or {} + if not payload or payload.get("error") == "not_found": + return None + effective = {**settings_row["settings"], **(override_settings or {})} + widgets = _render_widgets(username, payload, effective) + return widgets.get("composite") + + def render_widgets_now(username: str) -> dict[str, str]: """Phase 2: synchronously render composite SVG and persist it. diff --git a/generator/tests/test_auth.py b/generator/tests/test_auth.py index e221e28..05b23e3 100644 --- a/generator/tests/test_auth.py +++ b/generator/tests/test_auth.py @@ -137,6 +137,16 @@ def test_login_rejects_external_next(api_client): assert s.get("oauth_next") == "/" +@pytest.mark.parametrize("bad_next", ["//evil.example", "//evil.example/x", "/\\evil.example"]) +def test_login_rejects_protocol_relative_next(api_client, bad_next): + # Browsers resolve //host and /\host against the current scheme, so these + # are open-redirect vectors even though they start with "/". + r = api_client.get(f"/api/auth/github/login?next={bad_next}") + 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"