Skip to content
This repository was archived by the owner on Aug 19, 2026. It is now read-only.

feat: public preview — anonymous access to cohorts, curriculum and leaderboards - #97

Merged
theanmolsharma merged 7 commits into
mainfrom
auckland
Aug 17, 2026
Merged

theanmolsharma merged 7 commits into
mainfrom
auckland

Conversation

@theanmolsharma

Copy link
Copy Markdown
Collaborator

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-frontend public-preview work. Land in step with the frontend, not
ahead 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 —

return (ROLE_RANK[role] ?? 0) >= (ROLE_RANK[minRole] ?? 0);

STUDENT is rank 0, so passing null for an anonymous viewer would have resolved to
full student-level visibility of every minRole-tagged link. The first commit replaces the
fallback with an explicit ViewerRole = UserRole | null, an anonymous rank of -1, and an
exhaustive lookup — a new UserRole member is now a compile error rather than a silent leak.

Commits

Commit Change
d350cc1 anonymous tier in the role filters
d577cde @Public() on GET /cohorts + /cohorts/:id; classroom join tokens nulled for anonymous
aa8c2b0 public attachment route, bonus-question images kept staff-only
ba4bdac id added to GET /cohorts/available so the landing page can deep-link
997e63d new GET /scores/cohort/:id/leaderboard/public
15ddb4e real names removed from the student leaderboard
736991e public routes now identify the caller when a token is present

Two things worth reviewer attention

The attachment route needed a gate, not just @Public(). getAttachment resolves
<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 only
fetch 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.

736991e fixes a bug introduced by d577cde. AuthGuard returned true for @Public()
routes before populating request.user, so @GetUser() was undefined for every caller
regardless of token. Harmless while public routes ignored the user — but once /cohorts served
a 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/leaderboard still requires auth,
but its shape now depends on role. Staff responses are unchanged (all 17 fields). Student rows
drop name, displayName and discordGlobalName, keeping userId and discordUsername.

Note displayName was a getter over name || discordGlobalName || discordUserName, so it was
the real name whenever one was set — dropping name alone 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
displayName to discordUsername or it will render blanks. Students will see Discord handles
where 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, still
open. Once that merges it is a one-line @Roles(TA, ADMIN) → @Public() swap on
getAllCohortsMetrics. Until then /cohort-metrics must stay behind login: it currently computes
those 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.ts falls through to its defaults
because no throttler.* config key exists anywhere. That was survivable when every caller was a
logged-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

theanmolsharma and others added 7 commits August 16, 2026 12:01
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
theanmolsharma marked this pull request as ready for review August 16, 2026 11:53

@Vayras Vayras left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@theanmolsharma
theanmolsharma merged commit 7ba5886 into main Aug 17, 2026
4 checks passed
@theanmolsharma
theanmolsharma deleted the auckland branch August 17, 2026 03:23
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants