This repository was archived by the owner on Aug 19, 2026. It is now read-only.
Repository navigation
feat: public preview — anonymous access to cohorts, curriculum and leaderboards - #97
Merged
Merged
Conversation
Public-preview routes need to render for an unauthenticated viewer, where @getuser() yields undefined. Passing that through the role filters as-is was unsafe: isAtLeastRole fell back to rank 0 for an unknown role, and STUDENT *is* rank 0, so an anonymous viewer would have been granted full student-level visibility of every minRole-tagged link. Introduce ViewerRole (UserRole | null) with an explicit anonymous rank of -1, and drop both `?? 0` fallbacks so the rank lookup is exhaustive by construction — a new UserRole member is now a compile error here rather than a silent leak. No behaviour change for authenticated roles. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Mark GET /cohorts and GET /cohorts/:id @public() so the public-preview catalog and week-by-week curriculum pages render for logged-out visitors, and thread ViewerRole from the controller through listCohorts/getCohort into GetCohortResponseDto.fromEntity. @getuser() yields undefined on a @public() route, so both handlers type the param as User | undefined and pass `user?.role ?? null` rather than dereferencing it. Neither route may ever gain a @roles() decorator: RolesGuard does not check IS_PUBLIC_KEY and would deref user.role on undefined. Bonus questions and minRole-tagged links needed no new code here — they already route through canViewBonusQuestions/filterLinksByRole, which now understand anonymous. Classroom ids and invite links do need explicit handling: they are join tokens rather than content, so anyone holding one can enrol. fromEntity now returns null for classroomId, weeks[].classroomInviteLink and weeks[].classroomAssignmentUrl when the viewer is anonymous. Authenticated responses are unchanged. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…-only The public curriculum pages need to render inline question images, so GET /cohorts/attachments/:id/:filename becomes @public(). On its own that would be a leak. getAttachment resolves <cohort type>/<filename> straight off disk and never checks which question an attachment belongs to, so @public() alone would serve bonus-question images — staff-only content — to anyone holding a cohort id, which the now-public catalog hands out. Today that is every attachment in the repo: all four files under assets/cohort-configs/attachments/ are referenced by bonusQuestions. Gate it instead: a non-staff viewer may fetch a filename only if some non-bonus question in that cohort references it. TA/Admin keep unrestricted access via the existing canViewBonusQuestions helper, so this matches how the same content is already gated in GetCohortResponseDto.fromEntity. Missing-permission returns 404 rather than 403 so the response does not confirm a staff-only file exists. The findOne now loads weeks instead of selecting only type. The existing basename() path-traversal guard is untouched and still runs first. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
GET /cohorts/available returned type, season, dates and registration deadline but no id, so the public landing page had no key to deep-link a program card to its cohort page. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The public preview shows per-cohort leaderboards, but LeaderboardEntryDto is far too wide to expose: it carries the member's real name, Discord global name, user id, attendance counts and a full per-component score breakdown. Rather than loosen that shape, add a separate endpoint alongside it. GET /scores/cohort/:cohortId/leaderboard/public returns Discord handle, rank and total score only. PublicLeaderboardEntryDto is a hand-written projection — not an Omit<> and not a spread — with a field-by-field constructor, so a field added to LeaderboardEntryDto later cannot surface here by default; leaking a new one has to be an act of commission. Ranks are the position in the existing sorted result, so public and authenticated leaderboards agree on ordering and the client never needs raw component scores to derive it. Ordering stays primary-by-exercise-score per docs/leaderboard-algorithm.md, which means a lower totalScore can outrank a higher one in the public view; re-sorting on totalScore would make the two leaderboards disagree. The authenticated endpoint and its DTO are untouched. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
GET /scores/cohort/:cohortId/leaderboard carried no @roles, and RolesGuard returns true when no @roles metadata is present — so any authenticated STUDENT could read every cohort's full leaderboard, including members' real names. Note displayName is a getter over `name || discordGlobalName || discordUserName`, so it is the real name too whenever one is set. Redact rather than restrict: students keep every score and attendance figure the leaderboard UI renders today (attendance counts and score, exercise, group discussion, totals), with identity reduced to the Discord handle. userId is kept so the client can still highlight the signed-in member's own row. TA/Admin responses are unchanged. StudentLeaderboardEntryDto is a hand-written projection like its public sibling, and here that is load-bearing rather than defensive: these rows are built from a LeaderboardEntryDto that holds the real name, so a spread or Object.assign would copy it straight through. Ordering is untouched across all three tiers, so clients that derive rank from array position keep working. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
AuthGuard returned true for @public() routes before ever populating request.user, so @getuser() was undefined for every caller regardless of their token. That was harmless while public routes ignored the user, but GET /cohorts and GET /cohorts/:id now serve a role-gated projection — which meant a signed-in student, TA or admin browsing the curriculum got the anonymous view: no bonus questions, no classroom links, no minRole-tagged links. The attachment gate had the same problem, 404-ing staff on their own bonus-question images. Resolve the session on public routes too when a token is present, and treat a missing or invalid one as anonymous rather than an error. Public routes stay open to everyone; they just know who is asking. Gated routes are untouched: still 401 without a usable token. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
theanmolsharma
marked this pull request as ready for review
August 16, 2026 11:53
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Backend half of the public-preview work. Makes a curated slice of the portal readable without
logging in — cohort catalog, week-by-week curriculum, and per-cohort leaderboards — without
leaking PII or staff-only content.
Companion to the
portal-frontendpublic-preview work. Land in step with the frontend, notahead of it (see Breaking changes).
The core problem
The app has only ever had three authenticated roles, and this introduces a fourth, less
privileged tier: anonymous. The existing fallback made that dangerous —
STUDENTis rank0, so passingnullfor an anonymous viewer would have resolved tofull student-level visibility of every
minRole-tagged link. The first commit replaces thefallback with an explicit
ViewerRole = UserRole | null, an anonymous rank of-1, and anexhaustive lookup — a new
UserRolemember is now a compile error rather than a silent leak.Commits
d350cc1d577cde@Public()onGET /cohorts+/cohorts/:id; classroom join tokens nulled for anonymousaa8c2b0ba4bdacidadded toGET /cohorts/availableso the landing page can deep-link997e63dGET /scores/cohort/:id/leaderboard/public15ddb4e736991eTwo things worth reviewer attention
The attachment route needed a gate, not just
@Public().getAttachmentresolves<cohort type>/<filename>straight off disk and never checks which question owns the file —and today every attachment in the repo is referenced by a
bonusQuestion, i.e. staff-only.A plain
@Public()would have made all of them anonymously fetchable. Non-staff can now onlyfetch filenames referenced by a non-bonus question; missing permission returns 404 rather than
403 so the response doesn't confirm a staff-only file exists.
736991efixes a bug introduced byd577cde.AuthGuardreturnedtruefor@Public()routes before populating
request.user, so@GetUser()wasundefinedfor every callerregardless of token. Harmless while public routes ignored the user — but once
/cohortsserveda role-gated projection it meant signed-in students and staff got the anonymous view: no bonus
questions, no classroom links. Public routes now resolve the session when a token is present and
treat a missing or invalid one as anonymous rather than an error. Gated routes are untouched.
Breaking changes
Student leaderboard identity.
GET /scores/cohort/:cohortId/leaderboardstill requires auth,but its shape now depends on role. Staff responses are unchanged (all 17 fields). Student rows
drop
name,displayNameanddiscordGlobalName, keepinguserIdanddiscordUsername.Note
displayNamewas a getter overname || discordGlobalName || discordUserName, so it wasthe real name whenever one was set — dropping
namealone would have left the leak open.Every score and attendance figure students see today is preserved (attendance, total, exercise,
group discussion), so only the identity column changes. The frontend must switch that column from
displayNametodiscordUsernameor it will render blanks. Students will see Discord handleswhere they previously saw real names — intended, but a visible product change.
Ordering is identical across all three tiers, so anything deriving rank from array position keeps
working.
Deferred
Public cohort metrics (
GET /cohorts/metrics) is not in this PR — it depends on #90, stillopen. Once that merges it is a one-line
@Roles(TA, ADMIN)→@Public()swap ongetAllCohortsMetrics. Until then/cohort-metricsmust stay behind login: it currently computesthose numbers in the browser by fanning out over the leaderboard, which would ship every student's
real name to anonymous browsers.
Known risk, unchanged
Throttling is 5 requests/sec per IP, globally —
app.module.tsfalls through to its defaultsbecause no
throttler.*config key exists anywhere. That was survivable when every caller was alogged-in individual; anonymous visitors behind NAT, corporate proxies and mobile carriers share
an IP, so one visitor's burst can 429 another. Left as-is by decision; the frontend is expected to
avoid fan-out on public pages. Worth watching after launch.
🤖 Generated with Claude Code