diff --git a/docs/features/discord.md b/docs/features/discord.md index 230631163..8153e69f5 100644 --- a/docs/features/discord.md +++ b/docs/features/discord.md @@ -1,22 +1,77 @@ # Discord link -Accepted Hacklytics hackers connect their Discord account from the Hackathon Hub. There is no bot in the server. Roles come from Discord's Linked Roles: the site publishes a few metadata values for the user, and the server's roles are tied to them. - -Who can link: a participant of that hackathon whose status is `approved` or `checked_in`, from the moment they are accepted. One Discord account links to one participant per hackathon. +Hacklytics hackers, judges and volunteers connect their Discord account from the portal. There is no bot in the server. Roles come from Discord's Linked Roles: the site publishes a few metadata values for the user, and the server's roles are tied to them. Discord is also a sign-in option on `/login`, on the same application. That is a separate thing: signing in with Discord grants no roles and links nothing. See [Signing in with Discord](#signing-in-with-discord). +## Who can link + +Three roles, held independently. One person can hold several, and the site publishes all of them in one update. The model is `DiscordRoles` in `packages/api/src/services/discord/roles.ts`; `discordContext` reads it from the database and `resolveConnectTarget` refuses anyone who holds none. + +| Role | Who | Joining is | +| --- | --- | --- | +| Hacker | A participant whose status is `approved` and who pressed "I'm coming" on the hackathon Overview (`attendance_confirmed_at` is set), or who is `checked_in`. Being accepted alone is not enough. | Optional | +| Judge | A `judge` row for that edition with `is_active` true, which is what approval sets. A pending, rejected or removed judge holds nothing. | Required | +| Volunteer | An active, unexpired `admin` row with role `volunteer` (added on the staff page). Volunteers are org-wide, not per edition, so the role applies to any edition that is `open`, `closed` or `in_progress`: registration has opened and the event is not over. Not a draft, an announcement, a finished or a cancelled edition. Full staff are not volunteers. | Required | + +Judges and volunteers need no registration. The edition is the one in the link (`?hackathon=ID`), or, from Discord's verification URL, the newest edition that is not cancelled or over in which the person holds a role. A confirmed hacker who is also a judge gets both. One Discord account links to one person: `discord_link.discord_user_id` is unique, and the same account may not sit on another person's registration for that hackathon. + +Where the link is stored: + +- `discord_link` holds one row per user: the Discord id and username, and the person's OAuth tokens, encrypted (see [Taking roles back](#taking-roles-back)). Every link writes it. +- A confirmed hacker's link is also copied onto their `hackathon_participant` row (`discord_*` columns), which carries the Ramadan choice and feeds the admin roster. Hackers who linked before judges and volunteers could keep that link as it is: the portal reads the participant row first, then `discord_link`. +- Unlink clears the roles on Discord first, then clears both stores. It does not need the person to be eligible, so someone who un-confirms, or is removed as a judge, can still unlink. + +## Taking roles back + +Discord changes a person's Linked Roles metadata only with that person's own token, so a role is not revoked unless the site kept the token. It does: at link time the callback stores the access token, refresh token and expiry in `discord_link`, encrypted with AES-256-GCM. The key comes from `AUTH_SECRET` through HKDF under its own label (`query/discord/token/v1`), so no new variable is needed, and each value is bound to its person, so a copy on another row does not open. Tokens are never logged and no tRPC procedure returns them. If `AUTH_SECRET` is rotated the stored tokens stop opening, and those links become as unrevocable as the legacy ones below. + +`syncDiscordRoles(db, userId)` (`packages/api/src/services/discord/sync.ts`) re-derives the person's roles for the edition the link flow would pick, refreshes the access token when it is near its end (storing the rotated pair), and publishes the metadata. A person who holds no role gets all five fields at 0. Nothing is sent when the metadata would not change (`discord_link.roles_sig` holds what was last published). It never throws into the change that called it: it logs and the change stands, as `autoAssignFoodGroups` does. A sync that does not land (Discord down, a refresh failing) leaves the link pending, so the daily job tries again. + +One person's syncs, links and unlinks take turns. Each runs inside a transaction that holds a per-person advisory lock (`withDiscordLock`, `pg_advisory_xact_lock` on `discord:`) for the whole of derive, refresh, publish and write-back, across the Discord calls (each has an 8 second timeout, and the lock wait gives up after 30). That is what stops two refreshes from racing on a single-use refresh token, two publishes from landing out of order, and a sync that read the old link from putting roles back on an account an unlink has just cleared. Work inside the lock uses its own transaction, never the pool. + +It runs after commit on: + +| Change | Where | +| --- | --- | +| A judge approved, switched off, added or removed | `judge.setActive`, `judge.create`, `judge.remove` | +| A volunteer granted, switched off, renewed with a new end date, or removed | `admin.create`, `admin.update`, `admin.remove` | +| A hacker's status changed in any direction, banned, or withdrawn | `updateParticipantStatus`, `batchUpdateParticipantStatus`, `banFromHackathons`, `withdrawRegistration`. Moving out of the accepted statuses takes the hacker roles back; moving in can give them, so a judge who is moved to approved after confirming gets the flower role at once. | +| Unlink | `unlinkDiscord`: the roles are zeroed with the stored token before the row is deleted. If Discord cannot be reached the unlink fails with an error and nothing is deleted. | +| Linking a different Discord account | `completeLink` zeroes the old account first, with the old account's token, then stores the new link. If the old account cannot be reached the link does not move. Linking X, unlinking, then linking Y, or linking Y straight over X, leaves the roles only on Y. | + +A batch can touch more people than one request should wait for (up to 2500 status changes, any number of bans). Those changes mark **every** linked person among them pending, in the same transaction as the change (`roles_sig` set to null by `markDiscordRolesPending`), then sync as many as fit in 100 people or 15 seconds. Nothing is left looking synced that is not. + +The daily job `POST /api/cron/application-reminders` also runs `syncExpiredDiscordRoles`. It takes two kinds of link: those pending, and volunteers whose published `volunteer` is still 1 (`roles_sig` ends in `v1`) although the admin row has expired or been switched off, which has no event of its own. Each run takes at most 15 people and stops after 20 seconds; whoever it does not reach is first in line the next day. They are taken by `sync_attempted_at`, never-tried first and then longest ago, so a link that keeps failing goes to the back instead of holding a slot. A link whose tokens are missing or will not open gets `roles_sig = 'unreachable'` after one try and leaves the job for good; linking again repairs it. The cron route also holds the reminder mail's own guarantee: a draft is stamped as taken before its mail is sent, so a Scheduler retry never mails one twice. + +If Discord answers `invalid_grant` to a refresh, the person withdrew the connection (or the token was replaced and lost). The link is dropped: the `discord_link` row and the copy on a registration are deleted. A refresh that fails for any other reason (a Discord outage) leaves the link alone; the next change or the next day's job tries again. + +Not covered: + +- **Links made before tokens were stored** have no token, so their roles cannot be changed from here. Today that is hackers' `accepted`, flower and Ramadan values, since judges and volunteers could not link before. To revoke one by hand, ask the person to remove the Hacklytics connection under Discord Settings > Connections, or to press "Update my roles" in the portal (which stores a token, after which everything above applies). Taking the server role away by hand is not enough on its own: Linked Roles lets them claim it again while their metadata still qualifies. +- **An edition ending** does not clear anything. A judge or volunteer role stays on until the person is removed, unlinks or their term expires. Hacker roles stay too. +- There is no way to un-confirm "I'm coming" from the portal; an organizer changing the status is what takes a hacker's roles back. +- A person whose roles apply in more than one live edition is synced for the newest, the same one a fresh link uses. + ## What the hacker sees -- Accepted and not linked: the dashboard's next step reads "Join the Hacklytics Discord". The same card is on the hackathon page. The button goes to `/api/discord/connect` and, after a successful link, sends them to the server invite. +- Accepted and not yet confirmed: the dashboard's next step reads "Confirm you're coming" and the hackathon Overview shows the card with "Confirm you're coming to get the Discord invite." No invite and no link until they do. Their flower still shows, because it is also their meal wave and is assigned on acceptance. +- Confirmed and not linked: the dashboard's next step reads "Join the Hacklytics Discord". The same card is on the hackathon page. The button goes to `/api/discord/connect` and, after a successful link, sends them to the server invite. - Participants who answered "Yes" to Ramadan fasting see an unticked checkbox: "Add the Ramadan meals role. Others in the server can see your roles." Nobody else sees it. - Linked: "Linked as @name", their flower, "Update my roles" (runs the same flow again and returns to the portal) and "Unlink". - Inside Discord the hacker opens the server menu, then Linked Roles, and connects Hacklytics to claim their roles. Roles are claimed by the user in Discord; the site cannot hand them out. - Unlink only clears what the site stored. The connection stays in Discord until the user removes it under Settings > Connections. +## What judges and volunteers see + +- Judges: a card at the top of the judge page (`/judge`). It reads "Join the Hacklytics Discord. It's required for judges: schedules and room changes are posted there." The approval email and the added-by-organizer email say the same and point to the portal step. +- Volunteers: the same card at the top of the check-in desk (`/scan`): "It's required for volunteers: shifts and desk changes are posted there." There is no volunteer email, because a volunteer is added on the staff page and nothing is sent; the card is the notice. +- Someone who is both reads "judges and volunteers". After linking they return to the page the card is on (hackers to the hackathon page, judges to `/judge`, volunteers to `/scan`), or go on to the server invite. +- Judges and volunteers have no flower and no Ramadan choice. + ## Flowers -Hackers see a flower ("Your bloom"). In code and the database it is a food group, because it also decides the meal wave. The eight groups live in one place, `FOOD_GROUPS` in `packages/api/src/services/discord/config.ts`. Each has a stable `key` (stored in the database), a `number` (sent to Discord as `food_group`) and a display name. Changing the list needs no migration. Keep numbers stable once server roles point at them. +Only hackers have a flower ("Your bloom"). In code and the database it is a food group, because it also decides the meal wave. The eight groups live in one place, `FOOD_GROUPS` in `packages/api/src/services/discord/config.ts`. Each has a stable `key` (stored in the database), a `number` (sent to Discord as `food_group`) and a display name. Changing the list needs no migration. Keep numbers stable once server roles point at them. | Number | Flower | | --- | --- | @@ -29,24 +84,28 @@ Hackers see a flower ("Your bloom"). In code and the database it is a food group | 7 | Orchid | | 8 | Rose | -Assignment is automatic. Whenever anyone is accepted or checked in (single or bulk status change, acceptance wave, mass acceptance email, event check-in), every accepted participant without a flower gets one right after, oldest registration first. Each takes the flower with the fewest members in that hackathon (ties random). The assignment runs in a transaction that locks the hackathon row, so concurrent assignments stay balanced. Existing flowers are never changed. If the assignment fails, the acceptance still stands and the flower is assigned the first time the participant's Discord card loads or they link. +Assignment is automatic and does not wait for the "I'm coming" answer. Whenever anyone is accepted or checked in (single or bulk status change, acceptance wave, mass acceptance email, event check-in), every accepted participant without a flower gets one right after, oldest registration first. Each takes the flower with the fewest members in that hackathon (ties random). The assignment runs in a transaction that locks the hackathon row, so concurrent assignments stay balanced. Existing flowers are never changed. If the assignment fails, the acceptance still stands and the flower is assigned the first time the participant's Discord card loads or they link. ## Setup 1. In the [Discord developer portal](https://discord.com/developers/applications) create an application. 2. OAuth2: add the redirect `https://datasciencegt.org/api/discord/callback` (the link) and `https://datasciencegt.org/api/auth/callback/discord` (sign-in). Copy the client ID and client secret. -3. General Information: set "Linked Roles Verification URL" to `https://datasciencegt.org/api/discord/connect`. It needs no hackathon parameter; the site picks the newest live edition the user is accepted to. +3. General Information: set "Linked Roles Verification URL" to `https://datasciencegt.org/api/discord/connect`. It needs no hackathon parameter; the site picks the newest live edition in which the user holds a role. 4. Register the metadata fields once, from a laptop: ``` DISCORD_CLIENT_ID=... DISCORD_BOT_TOKEN=... node tooling/scripts/src/discord-register-metadata.ts ``` - This registers `accepted`, `food_group` (labelled "Bloom") and `ramadan`. The bot token is the application's own credential for this one call. The application's bot user is never invited to the server, and the website never reads `DISCORD_BOT_TOKEN`. + This registers five fields, the most Discord allows: `accepted`, `food_group` (labelled "Bloom"), `ramadan`, `judge` and `volunteer`. The call replaces the whole set, so **re-run it once** after this change ships; the first three are unchanged. The bot token is the application's own credential for this one call. The application's bot user is never invited to the server, and the website never reads `DISCORD_BOT_TOKEN`. 5. In the server, create the roles, then Server Settings > Roles > (role) > Links > add requirement: - Flowers: `food_group` equals 1 for Cherry Blossom, up to 8 for Rose (see the table). Role names in the DS@GT server are "Bloom ยท ". - Ramadan meals: `ramadan` equals true. - - Optional Hacklytics role: `accepted` equals true. + - Optional Hacklytics role: `accepted` equals true. It now means a hacker who confirmed they are coming, not merely one who was accepted. + - "Hacklytics 2027 Judge": `judge` equals true. + - "Hacklytics 2027 Volunteer": `volunteer` equals true. + + Each requirement is on its own role; give a role only the one requirement it needs. Judges and volunteers are sent `food_group` and `ramadan` as 0, which no flower or Ramadan role matches. 6. Create the client secret in Secret Manager and let the App Hosting backend read it: ``` @@ -64,14 +123,25 @@ Assignment is automatic. Whenever anyone is accepted or checked in (single or bu | `DISCORD_INVITE_URL` | `apphosting.yaml` value | A permanent `https://` invite to the DS@GT server. | | `DISCORD_CLIENT_SECRET` | secret `discord-client-secret` | Needs the `grantaccess` step above. | | `DISCORD_BOT_TOKEN` | setup script only | Never set on the app. | +| `AUTH_SECRET` | existing | Also the source of the key that encrypts stored Discord tokens. No new variable. | Unless the three app variables are set the feature is hidden and `/api/discord/*` answers 404. ## Flow -`GET /api/discord/connect?hackathon=ID&ramadan=1|0&then=invite` checks the user is accepted, signs a 10 minute `state` (HMAC with `AUTH_SECRET`: user, hackathon, Ramadan choice, destination, nonce, expiry) and redirects to Discord with scopes `identify role_connections.write`. +`GET /api/discord/connect?hackathon=ID&ramadan=1|0&then=invite` checks the user holds a role for that edition (see [Who can link](#who-can-link)), signs a 10 minute `state` (HMAC with `AUTH_SECRET`: user, hackathon, Ramadan choice, destination, nonce, expiry) and redirects to Discord with scopes `identify role_connections.write`. + +`GET /api/discord/callback` verifies the state signature, expiry and signed-in user, exchanges the code, reads `/users/@me`, stores the Discord id, username and time, then `PUT`s `/users/@me/applications/{client id}/role-connection` as the user. The metadata is built by `roleMetadata` from the roles the person holds: + +| Key | Value | +| --- | --- | +| `accepted` | 1 only for a confirmed hacker, else 0 | +| `food_group` | The flower number for a confirmed hacker, else 0 | +| `ramadan` | 1 only when opted in and fasting is "Yes", for a confirmed hacker, else 0 | +| `judge` | 1 or 0 | +| `volunteer` | 1 or 0 | -`GET /api/discord/callback` verifies the state signature, expiry and signed-in user, exchanges the code, reads `/users/@me`, stores the Discord id, username and time, then `PUT`s `/users/@me/applications/{client id}/role-connection` as the user with `accepted`, `food_group` and `ramadan` (1 only when opted in and fasting is "Yes"). If that `PUT` fails the stored link is rolled back. The access token is never stored. Failures return to the hackathon page with `?discord=error&reason=` (`bad_code`, `rate_limited`, `discord_denied`, `discord_error`, `already_linked`, `not_accepted`, `bad_state`, `cancelled`); success returns `?discord=linked` or goes to the invite. +All five are always sent, so a role that no longer applies is overwritten. If that `PUT` fails the stored link is rolled back to what it was before (or removed, when the previous account's roles were just cleared). The tokens are stored encrypted, as described under [Taking roles back](#taking-roles-back). Failures return to the page the person's card is on (the hackathon page, `/judge` or `/scan`) with `?discord=error&reason=` (`bad_code`, `rate_limited`, `discord_denied`, `discord_error`, `already_linked`, `not_accepted`, `bad_state`, `cancelled`); success returns `?discord=linked` or goes to the invite. ## Signing in with Discord diff --git a/docs/features/hackathons.md b/docs/features/hackathons.md index fea25c872..0cfc64695 100644 --- a/docs/features/hackathons.md +++ b/docs/features/hackathons.md @@ -34,7 +34,7 @@ Steps, with the procedure that does each (under `trpc.hackathon.*` unless noted) The Ramadan fasting answer (`ramadanFasting`) is optional on the server: the form asks it only when the event's dates overlap Ramadan (`overlapsRamadan` in `sites/mainweb/lib/ramadan.ts`, Umm al-Qura calendar on the venue's days) and sends nothing otherwise, so the column is empty for those events. 3. **Edit or leave.** `updateMyRegistration` edits answers (consent fields are not re-sent) and only works while the edition is `open`, before the deadline, and while the participant is still `pending`. `withdrawRegistration` takes the registration back, but is refused once the person is on a team, checked in, or has a project, because that affects others, and once the edition is `completed` or `cancelled`. 4. **Decision.** An organizer accepts, rejects or waitlists (see Acceptance below). `checked_in` can only be reached from `approved`. -5. **Confirm.** `confirmAttendance` lets an accepted hacker say they are coming. It stamps `attendance_confirmed_at` once, so organizers can free the seats of people who never answer. +5. **Confirm.** `confirmAttendance` lets an accepted hacker say they are coming. It stamps `attendance_confirmed_at` once, so organizers can free the seats of people who never answer. It also opens the [Discord](./discord.md) step: an accepted hacker cannot link until they have answered. 6. **Check in.** The first event scan or desk admit moves `approved` to `checked_in` and stamps `checked_in_at`. See Hackathon events and check-in. 7. **Team.** `createTeam`, `joinTeam`, `leaveTeam`, `disbandTeam` and `setOpen` live in `packages/api/src/routers/team.ts` and need an accepted participant (`approved` or `checked_in`), so teams can form before check-in. The team window closes 34 hours after hacking starts. Leave and disband are refused within 12 hours of the submission deadline. 8. **Submit.** `submitProject` (same router) requires `checked_in`. Submissions open 12 hours after hacking starts, close at 36 and edits close at 34. Times count from `hacking_start_time`, else `start_date`. Solo entries are allowed. `withdrawProject`, `mySubmission` and `submissionWindow` are in the same file. How submissions become judging entries is covered in [Judging](../judging/README.md). @@ -60,7 +60,7 @@ It sends at most 200 a run, oldest first, with the Hacklytics look for editions ### Reminder setup -App Hosting has no scheduler, so a daily job posts to `POST /api/cron/application-reminders` with `Authorization: Bearer `. The job is Cloud Scheduler, set up separately; nothing in the repository triggers it yet. The route answers 404 when `CRON_SECRET` is unset (so it does nothing until then), 401 on a wrong token, 429 past 10 calls an hour from one address, and 200 with `{ claimed, sent, failed }`. The same secret has to be in App Hosting and in the scheduler job. Once: +App Hosting has no scheduler, so a daily job posts to `POST /api/cron/application-reminders` with `Authorization: Bearer `. The job is Cloud Scheduler, set up separately; nothing in the repository triggers it yet. The route answers 404 when `CRON_SECRET` is unset (so it does nothing until then), 401 on a wrong token, 429 past 10 calls an hour from one address, and 200 with `{ claimed, sent, failed }`. The same secret has to be in App Hosting and in the scheduler job. Once: The same daily run also finishes Discord role changes still pending and takes the volunteer role back from volunteers whose term has ended, capped at 15 people and 20 seconds a run (see [Discord](./discord.md#taking-roles-back)). 1. Generate a value: `node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"`. 2. `firebase apphosting:secrets:set CRON_SECRET` and paste it, then `firebase apphosting:secrets:grantaccess CRON_SECRET --backend query`. diff --git a/docs/operations/security.md b/docs/operations/security.md index 49a4474a5..e6dfd24d8 100644 --- a/docs/operations/security.md +++ b/docs/operations/security.md @@ -11,6 +11,7 @@ This page is the map of controls already in the product. It is not a pentest rep - Email code requests are capped in the database per client network, per email domain, per address and for the whole deployment. A request any cap refuses is answered as busy, never as sent (see [email](../features/email.md#sign-in-codes-are-separate)) - `allowDangerousEmailAccountLinking` is on so Google/Discord can attach to an existing verified email. That is why CSRF on the OAuth callback must stay on, and why Discord sign-in is refused unless Discord marks the email `verified` - Redirect callback only allows same-origin URLs +- Discord Linked Roles keep the person's OAuth tokens, encrypted with AES-256-GCM under a key derived from `AUTH_SECRET` (HKDF, its own label, bound to the person), so a role can be taken back when a judge, volunteer or hacker loses it. They are never logged or returned. See [Discord link](../features/discord.md#taking-roles-back) ## Authorization diff --git a/docs/packages/db.md b/docs/packages/db.md index 27a4cc439..c45d49c08 100644 --- a/docs/packages/db.md +++ b/docs/packages/db.md @@ -29,7 +29,7 @@ Files in `src/schemas/`, re-exported from `schemas/index.ts`. `drizzle.config.ts | `auth.ts` | `user`, `account`, `session`, `verificationToken` | | `members.ts` | `user_profile`, `member`, `membership_history` | | `admins.ts` | `admin` | -| `hackathons.ts` | `hackathon`, `hackathon_team`, `hackathon_participant`, `hackathon_project`, `hackathon_interest`, `hackathon_event`, `hackathon_event_attendee`, `hackathon_check_in_flag`, `hackathon_announcement`, `hackathon_announcement_recipient` | +| `hackathons.ts` | `hackathon`, `hackathon_team`, `hackathon_participant`, `hackathon_project`, `hackathon_interest`, `hackathon_event`, `hackathon_event_attendee`, `hackathon_check_in_flag`, `hackathon_announcement`, `hackathon_announcement_recipient`, `discord_link` | | `judge.ts` | `judge`, `judge_assignment` (live roster); `judging_project`, `judge_vote`, `hackathon_result` (retired, kept for past editions) | | `judging.ts` | `judging_*`: config, entries and members, challenges, buildings, rooms and room links, judges, guest sessions, presence, schedule and appointments, rubric, evaluations, deliberation, placements, repo checks | | `points.ts` | `hackathon_point_adjustment`, `hackathon_store_item`, `hackathon_store_purchase` | diff --git a/packages/api/src/.internal-tests/application-drafts.db.test.ts b/packages/api/src/.internal-tests/application-drafts.db.test.ts index a07cc5e5d..b704c8308 100644 --- a/packages/api/src/.internal-tests/application-drafts.db.test.ts +++ b/packages/api/src/.internal-tests/application-drafts.db.test.ts @@ -30,11 +30,20 @@ const mailed = vi.hoisted(() => ({ deadline?: Date | null; }[], refuse: new Set(), + /** While set, a mail waits here before it counts as sent. */ + hold: undefined as Promise | undefined, + inFlight: 0, })); vi.mock("@query/auth/email", () => ({ sendAcceptanceEmail: vi.fn(async () => {}), sendApplicationReminderEmail: vi.fn( async (message: (typeof mailed.calls)[number]) => { + mailed.inFlight++; + try { + await mailed.hold; + } finally { + mailed.inFlight--; + } if (mailed.refuse.has(message.email)) throw new Error("550 mailbox full"); mailed.calls.push(message); }, @@ -138,6 +147,7 @@ describe.skipIf(!URL)("application drafts against a real database", () => { beforeEach(() => { mailed.calls.length = 0; mailed.refuse.clear(); + mailed.hold = undefined; }); afterAll(async () => { @@ -499,6 +509,47 @@ describe.skipIf(!URL)("application drafts against a real database", () => { expect(a.claimed + b.claimed + c.claimed).toBe(mailed.calls.length); }, 60_000); + it("a Scheduler retry while the first run is still mailing sends nothing twice, because the claim comes first", async () => { + const h = await makeHackathon("rem-retry"); + const addresses: string[] = []; + const ids: string[] = []; + for (let i = 0; i < 5; i++) { + const id = await makeUser(`retry${i}`); + await plantDraft(id, h.id, NOW, 4); + addresses.push(email(`retry${i}`)); + ids.push(id); + } + + // The mailer is slow, so the first run is mid-send when the retry arrives. + let release!: () => void; + mailed.hold = new Promise((resolve) => { + release = resolve; + }); + const first = run(NOW); + await vi.waitFor(() => expect(mailed.inFlight).toBe(5)); + + // Nothing has left yet, and every draft is already stamped as taken. + expect(mailedTo(addresses)).toEqual([]); + for (const id of ids) { + expect((await draftRow(id, h.id))?.reminderSentAt).not.toBeNull(); + } + + const retry = await run(new Date(NOW.getTime() + 60_000)); + expect(retry).toEqual({ claimed: 0, sent: 0, failed: 0 }); + expect(mailedTo(addresses)).toEqual([]); + + release(); + expect(await first).toEqual({ claimed: 5, sent: 5, failed: 0 }); + expect([...mailedTo(addresses)].sort()).toEqual([...addresses].sort()); + // And a retry after it finished has nothing left either. + expect(await run(new Date(NOW.getTime() + 120_000))).toEqual({ + claimed: 0, + sent: 0, + failed: 0, + }); + expect(mailedTo(addresses)).toHaveLength(5); + }, 30_000); + it("re-checks a draft it had to wait for, so one taken or edited meanwhile is not mailed", async () => { const h = await makeHackathon("rem-lock"); const taken = await makeUser("lock-taken"); diff --git a/packages/api/src/.internal-tests/discord-link.db.test.ts b/packages/api/src/.internal-tests/discord-link.db.test.ts index b3fedf810..5eb66aa18 100644 --- a/packages/api/src/.internal-tests/discord-link.db.test.ts +++ b/packages/api/src/.internal-tests/discord-link.db.test.ts @@ -1,12 +1,22 @@ -import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; import type * as DbModule from "@query/db"; import type * as DrizzleOps from "drizzle-orm"; import type * as DiscordSvc from "../services/discord"; /** * Real-Postgres test for the Discord link: balanced food groups, the - * Linked Roles callback with a mocked fetch (Discord is never called), the - * default edition for the verification URL, unlink, and the admin bits. + * Linked Roles callback with a mocked fetch (Discord is never called), who may + * link (confirmed hackers, approved judges, volunteers), the default edition + * for the verification URL, unlink, and the admin bits. * Needs TEST_DATABASE_URL (disposable; never Neon or production). */ const URL = process.env.TEST_DATABASE_URL; @@ -15,7 +25,11 @@ type FetchCall = { url: string; init?: RequestInit }; // The mass-accept path mails each person through a dynamic import; nothing // here may reach a real mail provider. -vi.mock("@query/auth/email", () => ({ sendAcceptanceEmail: vi.fn(async () => {}) })); +vi.mock("@query/auth/email", () => ({ + sendAcceptanceEmail: vi.fn(async () => {}), + sendJudgeApprovedEmail: vi.fn(async () => {}), + sendJudgeAddedEmail: vi.fn(async () => {}), +})); describe.skipIf(!URL)("discord link against a real database", () => { const suffix = Math.random().toString(36).slice(2, 10); @@ -33,6 +47,8 @@ describe.skipIf(!URL)("discord link against a real database", () => { clientSecret: "secret-1", inviteUrl: "https://discord.gg/test", }; + // What AUTH_SECRET is for these tests: the tokens are sealed under it. + const SECRET = "t".repeat(40); const makeUser = async (tag: string) => { const id = `dl-${suffix}-${tag}`; @@ -67,6 +83,8 @@ describe.skipIf(!URL)("discord link against a real database", () => { hackathonId, userId, registrationStatus: "approved", + // Said "I'm coming": the Discord step waits for it. + attendanceConfirmedAt: new Date(), ramadanFasting: "Yes", ...extra, }) @@ -83,9 +101,16 @@ describe.skipIf(!URL)("discord link against a real database", () => { /** A Discord that answers each step, recording every call. */ const discordFetch = ( - over: { token?: number; me?: number; put?: number; meId?: string } = {}, + over: { + token?: number; + me?: number; + put?: number | number[]; + meId?: string; + } = {}, ) => { const calls: FetchCall[] = []; + const puts = [over.put ?? 200].flat(); + let putIndex = 0; const fn = vi.fn(async (url: string | URL | Request, init?: RequestInit) => { const u = String(url); calls.push({ url: u, init }); @@ -94,7 +119,11 @@ describe.skipIf(!URL)("discord link against a real database", () => { if (u.endsWith("/oauth2/token")) { const status = over.token ?? 200; return status === 200 - ? json(200, { access_token: "tok-user" }) + ? json(200, { + access_token: "tok-user", + refresh_token: "ref-user", + expires_in: 604800, + }) : json(status, { retry_after: 4.2 }); } if (u.endsWith("/users/@me")) { @@ -107,7 +136,7 @@ describe.skipIf(!URL)("discord link against a real database", () => { }) : json(status, {}); } - const status = over.put ?? 200; + const status = puts[Math.min(putIndex++, puts.length - 1)]!; return json(status, status === 200 ? {} : { retry_after: 2 }); }); return { fn: fn as unknown as typeof fetch, calls }; @@ -132,6 +161,7 @@ describe.skipIf(!URL)("discord link against a real database", () => { svc.completeLink({ db: S.db as any, config: CONFIG, + secret: SECRET, state: state(userId, hackathonId, r, t), code: "code-1", redirectUri: "https://datasciencegt.org/api/discord/callback", @@ -155,6 +185,20 @@ describe.skipIf(!URL)("discord link against a real database", () => { }); }, 120_000); + // Other files share this database and list every open edition, so the ones + // made here go as soon as each case is done, not at the end of the file. + let hackathonsBefore = 0; + beforeEach(() => { + hackathonsBefore = hackathonIds.length; + }); + afterEach(async () => { + const made = hackathonIds.splice(hackathonsBefore); + const db = S?.db; + if (made.length && db) { + await db.delete(S.hackathons).where(ops.inArray(S.hackathons.id, made)); + } + }); + afterAll(async () => { const db = S?.db; if (!db) return; @@ -220,7 +264,13 @@ describe.skipIf(!URL)("discord link against a real database", () => { expect(body).toEqual({ platform_name: "Hacklytics", platform_username: "Ada L", - metadata: { accepted: 1, food_group: number, ramadan: 1 }, + metadata: { + accepted: 1, + food_group: number, + ramadan: 1, + judge: 0, + volunteer: 0, + }, }); expect(stored).toMatchObject({ discordUserId: `d-happy-${suffix}`, @@ -270,6 +320,357 @@ describe.skipIf(!URL)("discord link against a real database", () => { }); }); + describe("who may link: hackers who confirmed, approved judges, volunteers", () => { + const makeJudge = async (hackathonId: string, userId: string, isActive = true) => { + const [judge] = await S.db! + .insert(S.judges) + .values({ userId, hackathonId, name: "Judge", email: `${userId}@example.test`, isActive }) + .returning(); + return judge!; + }; + const makeVolunteer = async (userId: string, extra: Record = {}) => { + await S.db!.insert(S.admins).values({ userId, role: "volunteer", ...extra }); + }; + const sent = (f: ReturnType) => + JSON.parse(f.calls[2]!.init!.body as string).metadata; + const linkRow = async (userId: string) => + ( + await S.db! + .select() + .from(S.discordLinks) + .where(ops.eq(S.discordLinks.userId, userId)) + )[0]; + + it("an accepted hacker who has not said they are coming cannot link or get an invite", async () => { + const h = await makeHackathon("rsvp"); + const u = await makeUser("rsvp"); + const p = await makeParticipant(h.id, u, { attendanceConfirmedAt: null }); + const f = discordFetch(); + expect(await link(u, h.id, f, null, "invite")).toEqual({ + ok: false, + reason: "not_accepted", + }); + expect(f.calls).toHaveLength(0); + expect(await svc.resolveConnectTarget(S.db as any, u, h.id)).toBeNull(); + expect(await svc.resolveConnectTarget(S.db as any, u, null)).toBeNull(); + + // The portal still shows them their flower (it is their meal wave) and + // asks for the answer. + const mine = await hackathonAs(u).myDiscord({ hackathonId: h.id }); + expect(mine).toMatchObject({ + eligible: false, + awaitingConfirmation: true, + roles: { hacker: false, judge: false, volunteer: false }, + linked: false, + }); + expect(mine.foodGroup?.key).toBe((await row(p.id)).foodGroup); + expect(await linkRow(u)).toBeUndefined(); + }); + + it("saying they are coming opens the step, and the metadata says accepted with their flower", async () => { + const h = await makeHackathon("rsvp-yes"); + const u = await makeUser("rsvp-yes"); + const p = await makeParticipant(h.id, u, { attendanceConfirmedAt: null }); + expect((await hackathonAs(u).myDiscord({ hackathonId: h.id })).eligible).toBe(false); + + await hackathonAs(u).confirmAttendance({ hackathonId: h.id }); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: true, + awaitingConfirmation: false, + roles: { hacker: true, judge: false, volunteer: false }, + }); + + const f = discordFetch({ meId: `d-rsvp-${suffix}` }); + expect(await link(u, h.id, f)).toMatchObject({ ok: true, home: "hackathon" }); + const number = svc.foodGroupByKey((await row(p.id)).foodGroup)!.number; + expect(sent(f)).toEqual({ + accepted: 1, + food_group: number, + ramadan: 0, + judge: 0, + volunteer: 0, + }); + }); + + it("a hacker who is already checked in is through the door without the answer", async () => { + const h = await makeHackathon("rsvp-door"); + const u = await makeUser("rsvp-door"); + await makeParticipant(h.id, u, { + registrationStatus: "checked_in", + attendanceConfirmedAt: null, + }); + expect(await link(u, h.id, discordFetch({ meId: `d-door-${suffix}` }))).toMatchObject({ + ok: true, + }); + }); + + it("an approved judge with no registration can link and gets judge, with the hacker values at 0", async () => { + const h = await makeHackathon("judge"); + const u = await makeUser("judge"); + await makeJudge(h.id, u); + const f = discordFetch({ meId: `d-judge-${suffix}` }); + expect(await link(u, h.id, f, null, "invite")).toMatchObject({ + ok: true, + then: "invite", + home: "judge", + username: "ada", + }); + expect(sent(f)).toEqual({ accepted: 0, food_group: 0, ramadan: 0, judge: 1, volunteer: 0 }); + + const stored = await linkRow(u); + expect(stored).toMatchObject({ discordUserId: `d-judge-${suffix}`, discordUsername: "ada" }); + expect(JSON.stringify(stored)).not.toContain("tok-user"); + const participants = await S.db! + .select() + .from(S.hackathonParticipants) + .where(ops.eq(S.hackathonParticipants.userId, u)); + expect(participants).toHaveLength(0); + + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: true, + roles: { hacker: false, judge: true, volunteer: false }, + linked: true, + username: "ada", + foodGroup: null, + fasting: false, + }); + // Updating roles again keeps the one row. + expect(await link(u, h.id, discordFetch({ meId: `d-judge-${suffix}` }))).toMatchObject({ ok: true }); + const again = await S.db! + .select() + .from(S.discordLinks) + .where(ops.eq(S.discordLinks.userId, u)); + expect(again).toHaveLength(1); + + await hackathonAs(u).unlinkDiscord({ hackathonId: h.id }); + expect(await linkRow(u)).toBeUndefined(); + expect((await hackathonAs(u).myDiscord({ hackathonId: h.id })).linked).toBe(false); + }); + + it("a judge who is not approved cannot link", async () => { + const h = await makeHackathon("judge-no"); + const u = await makeUser("judge-no"); + await makeJudge(h.id, u, false); + const f = discordFetch(); + expect(await link(u, h.id, f)).toEqual({ ok: false, reason: "not_accepted" }); + expect(f.calls).toHaveLength(0); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: false, + roles: { judge: false }, + }); + }); + + it("a volunteer links while an edition is open or live, with volunteer set", async () => { + const h = await makeHackathon("vol"); + const u = await makeUser("vol"); + await makeVolunteer(u); + const f = discordFetch({ meId: `d-vol-${suffix}` }); + expect(await link(u, h.id, f)).toMatchObject({ ok: true, home: "scan" }); + expect(sent(f)).toEqual({ accepted: 0, food_group: 0, ramadan: 0, judge: 0, volunteer: 1 }); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: true, + roles: { hacker: false, judge: false, volunteer: true }, + linked: true, + }); + }); + + it("a volunteer has no step on an edition that is not open or live", async () => { + const u = await makeUser("vol-status"); + await makeVolunteer(u); + for (const status of ["draft", "announced", "completed", "cancelled"]) { + const h = await makeHackathon(`vol-${status}`, { status }); + expect(await svc.resolveConnectTarget(S.db as any, u, h.id)).toBeNull(); + } + for (const status of ["open", "closed", "in_progress"]) { + const h = await makeHackathon(`vol-${status}`, { status }); + expect((await svc.resolveConnectTarget(S.db as any, u, h.id))?.roles.volunteer).toBe(true); + } + }); + + it("an inactive or expired volunteer, and full staff, are not volunteers", async () => { + const h = await makeHackathon("vol-no"); + const inactive = await makeUser("vol-inactive"); + await makeVolunteer(inactive, { isActive: false }); + const expired = await makeUser("vol-expired"); + await makeVolunteer(expired, { expiresAt: new Date(Date.now() - 60_000) }); + const staff = await makeUser("vol-staff"); + await S.db!.insert(S.admins).values({ userId: staff, role: "admin" }); + for (const u of [inactive, expired, staff]) { + expect(await svc.resolveConnectTarget(S.db as any, u, h.id)).toBeNull(); + } + }); + + it("the default edition for a volunteer is the newest one that is open or live", async () => { + const u = await makeUser("vol-default"); + await makeVolunteer(u); + await makeHackathon("vd-old", { + status: "completed", + startDate: new Date("2026-02-01T00:00:00Z"), + endDate: new Date("2026-02-03T00:00:00Z"), + }); + const live = await makeHackathon("vd-live", { + startDate: new Date("2033-02-01T00:00:00Z"), + endDate: new Date("2033-02-03T00:00:00Z"), + }); + await makeHackathon("vd-next", { + status: "announced", + startDate: new Date("2034-02-01T00:00:00Z"), + endDate: new Date("2034-02-03T00:00:00Z"), + }); + expect((await svc.resolveConnectTarget(S.db as any, u, null))?.hackathon.id).toBe(live.id); + const mine = await hackathonAs(u).myDiscord({}); + expect(mine.hackathon?.id).toBe(live.id); + expect(mine.roles.volunteer).toBe(true); + }); + + it("a judge who is also a confirmed hacker gets both, and both stores hold the link", async () => { + const h = await makeHackathon("both"); + const u = await makeUser("both"); + const p = await makeParticipant(h.id, u); + await makeJudge(h.id, u); + const f = discordFetch({ meId: `d-both-${suffix}` }); + expect(await link(u, h.id, f, 1)).toMatchObject({ ok: true, home: "hackathon" }); + const number = svc.foodGroupByKey((await row(p.id)).foodGroup)!.number; + expect(sent(f)).toEqual({ + accepted: 1, + food_group: number, + ramadan: 1, + judge: 1, + volunteer: 0, + }); + expect(await row(p.id)).toMatchObject({ discordUserId: `d-both-${suffix}`, ramadanRoleOptIn: true }); + expect(await linkRow(u)).toMatchObject({ discordUserId: `d-both-${suffix}` }); + }); + + it("a judge who is an accepted hacker not yet confirmed gets judge only, and the card asks for the answer", async () => { + const h = await makeHackathon("judge-unconfirmed"); + const u = await makeUser("judge-unconfirmed"); + const p = await makeParticipant(h.id, u, { attendanceConfirmedAt: null }); + await makeJudge(h.id, u); + const f = discordFetch({ meId: `d-ju-${suffix}` }); + expect(await link(u, h.id, f)).toMatchObject({ ok: true, home: "judge" }); + expect(sent(f)).toEqual({ accepted: 0, food_group: 0, ramadan: 0, judge: 1, volunteer: 0 }); + // The registration is left alone: no flower role, no mirrored link. + expect((await row(p.id)).discordUserId).toBeNull(); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: true, + awaitingConfirmation: true, + linked: true, + }); + }); + + it("a judge and a volunteer at once get both", async () => { + const h = await makeHackathon("jv"); + const u = await makeUser("jv"); + await makeJudge(h.id, u); + await makeVolunteer(u); + const f = discordFetch({ meId: `d-jv-${suffix}` }); + expect(await link(u, h.id, f)).toMatchObject({ ok: true }); + expect(sent(f)).toEqual({ accepted: 0, food_group: 0, ramadan: 0, judge: 1, volunteer: 1 }); + }); + + it("un-confirming or withdrawing leaves an existing link in place", async () => { + const h = await makeHackathon("keeplink"); + const u = await makeUser("keeplink"); + const p = await makeParticipant(h.id, u); + expect(await link(u, h.id, discordFetch({ meId: `d-keep2-${suffix}` }))).toMatchObject({ ok: true }); + + await S.db! + .update(S.hackathonParticipants) + .set({ attendanceConfirmedAt: null }) + .where(ops.eq(S.hackathonParticipants.id, p.id)); + const after = await hackathonAs(u).myDiscord({ hackathonId: h.id }); + expect(after).toMatchObject({ + eligible: false, + awaitingConfirmation: true, + linked: true, + username: "ada", + }); + expect(await row(p.id)).toMatchObject({ discordUserId: `d-keep2-${suffix}` }); + + await S.db! + .delete(S.hackathonParticipants) + .where(ops.eq(S.hackathonParticipants.id, p.id)); + expect(await linkRow(u)).toMatchObject({ discordUserId: `d-keep2-${suffix}` }); + }); + + it("a hacker linked before the confirmation step keeps the link", async () => { + const h = await makeHackathon("legacy"); + const u = await makeUser("legacy"); + await makeParticipant(h.id, u, { + attendanceConfirmedAt: null, + discordUserId: `d-legacy-${suffix}`, + discordUsername: "old", + discordLinkedAt: new Date(), + }); + expect(await hackathonAs(u).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: false, + awaitingConfirmation: true, + linked: true, + username: "old", + }); + }); + + it("refuses a Discord account another person already holds, whichever store holds it", async () => { + const h = await makeHackathon("held"); + const judgeA = await makeUser("held-a"); + const judgeB = await makeUser("held-b"); + await makeJudge(h.id, judgeA); + await makeJudge(h.id, judgeB); + const shared = `d-held-${suffix}`; + expect(await link(judgeA, h.id, discordFetch({ meId: shared }))).toMatchObject({ ok: true }); + const f = discordFetch({ meId: shared }); + expect(await link(judgeB, h.id, f)).toMatchObject({ ok: false, reason: "already_linked" }); + expect(f.calls).toHaveLength(2); + expect(await linkRow(judgeB)).toBeUndefined(); + + // A hacker linked before this table existed holds the account on the + // registration alone. + const hackerAccount = `d-held-hacker-${suffix}`; + const hacker = await makeUser("held-h"); + await makeParticipant(h.id, hacker, { + discordUserId: hackerAccount, + discordUsername: "old", + discordLinkedAt: new Date(), + }); + const judgeC = await makeUser("held-c"); + await makeJudge(h.id, judgeC); + expect(await link(judgeC, h.id, discordFetch({ meId: hackerAccount }))).toMatchObject({ + ok: false, + reason: "already_linked", + }); + expect(await linkRow(judgeC)).toBeUndefined(); + }); + + it("rolls back a first link, and restores the same account's previous link, when Discord refuses the roles", async () => { + const h = await makeHackathon("rollback"); + const u = await makeUser("rollback"); + await makeJudge(h.id, u); + expect(await link(u, h.id, discordFetch({ meId: `d-rb1-${suffix}`, put: 500 }))).toMatchObject({ + ok: false, + reason: "discord_error", + home: "judge", + }); + expect(await linkRow(u)).toBeUndefined(); + + expect(await link(u, h.id, discordFetch({ meId: `d-rb1-${suffix}` }))).toMatchObject({ ok: true }); + const first = await linkRow(u); + expect(await link(u, h.id, discordFetch({ meId: `d-rb1-${suffix}`, put: 403 }))).toMatchObject({ + ok: false, + reason: "discord_denied", + }); + // The same account again: what was stored before, tokens and all, is back. + expect(await linkRow(u)).toEqual(first); + }); + + it("the signed state stays bound to the user it was made for", () => { + const secret = "s".repeat(40); + const token = svc.signState({ u: "judge-1", h: "hack-1", r: null, t: "portal" }, secret); + expect(svc.verifyState(token, secret, { userId: "judge-1" })).toMatchObject({ u: "judge-1" }); + expect(svc.verifyState(token, secret, { userId: "judge-2" })).toBeNull(); + }); + }); + it("maps Discord errors and leaves nothing linked", async () => { const h = await makeHackathon("errors"); const u = await makeUser("errors"); @@ -331,7 +732,7 @@ describe.skipIf(!URL)("discord link against a real database", () => { await makeParticipant(current.id, u); await makeParticipant(pending.id, u, { registrationStatus: "pending" }); const target = await svc.resolveConnectTarget(S.db as any, u, null); - expect(target?.hackathon?.id).toBe(current.id); + expect(target?.hackathon.id).toBe(current.id); expect(await svc.resolveConnectTarget(S.db as any, u, pending.id)).toBeNull(); }); @@ -346,9 +747,12 @@ describe.skipIf(!URL)("discord link against a real database", () => { expect(before.foodGroup?.name).toBeTruthy(); expect(before.fasting).toBe(true); expect((await row(p.id)).foodGroup).toBe(before.foodGroup?.key); - expect( - await hackathonAs(stranger).myDiscord({ hackathonId: h.id }), - ).toEqual({ eligible: false }); + expect(await hackathonAs(stranger).myDiscord({ hackathonId: h.id })).toMatchObject({ + eligible: false, + awaitingConfirmation: false, + foodGroup: null, + linked: false, + }); await link(u, h.id, discordFetch({ meId: `d-my-${suffix}` }), 1); const linked = await hackathonAs(u).myDiscord({ hackathonId: h.id }); @@ -590,4 +994,847 @@ describe.skipIf(!URL)("discord link against a real database", () => { await expect(bug.adminGetAttendees({ hackathonId: h.id })).rejects.toThrow(); await expect(bug.exportAttendees({ hackathonId: h.id })).rejects.toThrow(); }); + + // Roles are published with the person's own token, so taking one back needs + // that token. These run the whole path against a fake Discord that tracks + // which account each token belongs to and records every metadata write. + describe("taking roles back", () => { + const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + type Put = { account: string; bearer: string; metadata: Record }; + const ZEROS = { accepted: 0, food_group: 0, ramadan: 0, judge: 0, volunteer: 0 }; + + /** A Discord that issues, rotates and revokes tokens, and logs each metadata write. */ + const makeWorld = () => { + const puts: Put[] = []; + const bearers = new Map(); + const refreshTokens = new Map(); + const issued: string[] = []; + let n = 0; + const world = { + puts, + issued, + refreshCalls: 0, + /** The refresh is applied at once and its answer arrives this late. */ + refreshDelayMs: 0, + putStatus: 200, + refreshFails: null as null | "invalid_grant" | 500, + beforePut: undefined as undefined | (() => Promise), + throws: false, + issue(account: string) { + const access = `at-${++n}`; + const refresh = `rt-${n}`; + bearers.set(access, account); + refreshTokens.set(refresh, account); + issued.push(access, refresh); + return { access_token: access, refresh_token: refresh, expires_in: 604800 }; + }, + fn: undefined as unknown as typeof fetch, + }; + world.fn = vi.fn(async (url: string | URL | Request, init?: RequestInit) => { + if (world.throws) throw new Error("network down"); + const u = String(url); + const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status }); + if (u.endsWith("/oauth2/token")) { + const form = new URLSearchParams(String(init?.body)); + if (form.get("grant_type") === "authorization_code") { + return json(200, world.issue(form.get("code")!.replace(/^code-/, ""))); + } + world.refreshCalls++; + if (world.refreshFails === "invalid_grant") { + return json(400, { error: "invalid_grant" }); + } + if (world.refreshFails === 500) return json(500, {}); + const account = refreshTokens.get(form.get("refresh_token")!); + if (!account) return json(400, { error: "invalid_grant" }); + refreshTokens.delete(form.get("refresh_token")!); + const issued = world.issue(account); + if (world.refreshDelayMs) await sleep(world.refreshDelayMs); + return json(200, issued); + } + const bearer = String((init?.headers as Record)?.Authorization ?? "") + .replace("Bearer ", ""); + const account = bearers.get(bearer); + if (!account) return json(401, {}); + if (u.endsWith("/users/@me")) { + return json(200, { id: account, username: account, global_name: account }); + } + await world.beforePut?.(); + if (world.putStatus !== 200) return json(world.putStatus, { retry_after: 1 }); + puts.push({ account, bearer, metadata: JSON.parse(String(init?.body)).metadata }); + return json(200, {}); + }) as unknown as typeof fetch; + return world; + }; + let world: ReturnType; + + // The sync a router runs reads the app's own settings, so those are set. + beforeAll(() => { + vi.stubEnv("DISCORD_CLIENT_ID", CONFIG.clientId); + vi.stubEnv("DISCORD_CLIENT_SECRET", CONFIG.clientSecret); + vi.stubEnv("DISCORD_INVITE_URL", CONFIG.inviteUrl); + vi.stubEnv("AUTH_SECRET", SECRET); + }); + afterAll(() => vi.unstubAllEnvs()); + beforeEach(() => { + world = makeWorld(); + vi.stubGlobal("fetch", world.fn); + }); + afterEach(() => vi.unstubAllGlobals()); + + const linkAs = (userId: string, hackathonId: string, account: string, r: 0 | 1 | null = null) => + svc.completeLink({ + db: S.db as any, + config: CONFIG, + secret: SECRET, + state: state(userId, hackathonId, r), + code: `code-${account}`, + redirectUri: "https://datasciencegt.org/api/discord/callback", + fetchImpl: world.fn, + }); + const linkOf = async (userId: string) => + (await S.db!.select().from(S.discordLinks).where(ops.eq(S.discordLinks.userId, userId)))[0]; + const putsFor = (account: string) => world.puts.filter((p) => p.account === account); + const lastFor = (account: string) => putsFor(account).at(-1)?.metadata; + const acct = (tag: string) => `d-${tag}-${suffix}`; + const staff = async (tag: string, role: "admin" | "super_admin" = "admin") => { + const id = await makeUser(tag); + await S.db!.insert(S.admins).values({ userId: id, role }); + return appRouterAs(id); + }; + const appRouterAs = (id: string) => appRouter.createCaller(ctx(id)); + // The daily job looks at every link in the database, so a case that counts + // what it did starts from none of this file's earlier ones. + const clearLinks = () => + S.db!.delete(S.discordLinks).where(ops.like(S.discordLinks.userId, `dl-${suffix}-%`)); + const expireToken = (userId: string) => + S.db! + .update(S.discordLinks) + .set({ tokenExpiresAt: new Date(Date.now() - 60_000) }) + .where(ops.eq(S.discordLinks.userId, userId)); + const newJudge = async (tag: string, hackathonId: string) => { + const u = await makeUser(tag); + const [judge] = await S.db! + .insert(S.judges) + .values({ userId: u, hackathonId, name: "Judge", email: `${u}@example.test`, isActive: true }) + .returning(); + return { u, judgeId: judge!.id }; + }; + + it("stores the tokens encrypted, under the person, and never hands them back", async () => { + const h = await makeHackathon("tok"); + const { u } = await newJudge("tok", h.id); + expect(await linkAs(u, h.id, acct("tok"))).toMatchObject({ ok: true }); + + const row = (await linkOf(u))!; + const [access, refresh] = world.issued; + expect(row.accessTokenEnc).toMatch(/^v1\./); + expect(row.refreshTokenEnc).toMatch(/^v1\./); + expect(row.tokenExpiresAt!.getTime()).toBeGreaterThan(Date.now() + 6 * 86_400_000); + expect(JSON.stringify(row)).not.toContain(access); + expect(JSON.stringify(row)).not.toContain(refresh); + const { openToken } = await import("../services/discord/token-crypto"); + expect(openToken(row.accessTokenEnc, SECRET, u)).toBe(access); + expect(openToken(row.refreshTokenEnc, SECRET, u)).toBe(refresh); + // Sealed for this person: on another row, or under another secret, it does not open. + expect(openToken(row.accessTokenEnc, SECRET, "someone-else")).toBeNull(); + expect(openToken(row.accessTokenEnc, "o".repeat(40), u)).toBeNull(); + + // Nothing the portal asks for carries them. + const mine = await hackathonAs(u).myDiscord({ hackathonId: h.id }); + const everything = JSON.stringify(mine); + for (const secret of [access, refresh, row.accessTokenEnc, row.refreshTokenEnc]) { + expect(everything).not.toContain(secret!); + } + expect(everything).not.toMatch(/token/i); + }); + + it("deactivating a judge takes the judge role back, and reactivating gives it again", async () => { + const h = await makeHackathon("deact"); + const { u, judgeId } = await newJudge("deact", h.id); + await linkAs(u, h.id, acct("deact")); + expect(lastFor(acct("deact"))).toMatchObject({ judge: 1 }); + + const admin = await staff("deact-admin"); + await admin.judge.setActive({ judgeId, isActive: false }); + expect(lastFor(acct("deact"))).toEqual(ZEROS); + + await admin.judge.setActive({ judgeId, isActive: true }); + expect(lastFor(acct("deact"))).toEqual({ ...ZEROS, judge: 1 }); + }); + + it("removing a judge takes the role back", async () => { + const h = await makeHackathon("rmjudge"); + const { u, judgeId } = await newJudge("rmjudge", h.id); + await linkAs(u, h.id, acct("rmjudge")); + await (await staff("rmjudge-admin", "super_admin")).judge.remove({ judgeId }); + expect(lastFor(acct("rmjudge"))).toEqual(ZEROS); + }); + + it("removing, switching off or ending a volunteer takes the role back", async () => { + const h = await makeHackathon("vol-rm"); + const admin = await staff("vol-rm-admin", "super_admin"); + const make = async (tag: string) => { + const u = await makeUser(tag); + const [row] = await S.db! + .insert(S.admins) + .values({ userId: u, role: "volunteer" }) + .returning(); + await linkAs(u, h.id, acct(tag)); + expect(lastFor(acct(tag))).toMatchObject({ volunteer: 1 }); + return row!.id; + }; + + await admin.admin.remove({ adminId: await make("vol-a") }); + expect(lastFor(acct("vol-a"))).toEqual(ZEROS); + + await admin.admin.update({ adminId: await make("vol-b"), isActive: false }); + expect(lastFor(acct("vol-b"))).toEqual(ZEROS); + + await admin.admin.update({ + adminId: await make("vol-c"), + expiresAt: new Date(Date.now() - 1000), + }); + expect(lastFor(acct("vol-c"))).toEqual(ZEROS); + }); + + it("the daily sweep zeroes a volunteer whose term ran out, once", async () => { + await clearLinks(); + const h = await makeHackathon("vol-sweep"); + const u = await makeUser("vol-sweep"); + const [row] = await S.db!.insert(S.admins).values({ userId: u, role: "volunteer" }).returning(); + await linkAs(u, h.id, acct("vol-sweep")); + const other = await makeUser("vol-sweep-live"); + await S.db!.insert(S.admins).values({ userId: other, role: "volunteer" }); + await linkAs(other, h.id, acct("vol-sweep-live")); + + // Nothing has expired yet. + expect(await svc.syncExpiredDiscordRoles(S.db as any)).toEqual({ checked: 0, synced: 0 }); + + await S.db! + .update(S.admins) + .set({ expiresAt: new Date(Date.now() - 1000) }) + .where(ops.eq(S.admins.id, row!.id)); + const before = world.puts.length; + expect(await svc.syncExpiredDiscordRoles(S.db as any)).toEqual({ checked: 1, synced: 1 }); + expect(world.puts.slice(before)).toHaveLength(1); + expect(lastFor(acct("vol-sweep"))).toEqual(ZEROS); + expect(lastFor(acct("vol-sweep-live"))).toMatchObject({ volunteer: 1 }); + + // Zeroed, so the next run has nothing to do. + expect(await svc.syncExpiredDiscordRoles(S.db as any)).toEqual({ checked: 0, synced: 0 }); + }); + + it("a hacker moved out of the accepted statuses, banned, or who withdraws loses the hacker roles", async () => { + const h = await makeHackathon("hacker-out"); + const admin = await staff("hacker-out-admin"); + const linked = async (tag: string, extra: Record = {}) => { + const u = await makeUser(tag); + const p = await makeParticipant(h.id, u, extra); + await linkAs(u, h.id, acct(tag)); + expect(lastFor(acct(tag))).toMatchObject({ accepted: 1 }); + return { u, p }; + }; + + const a = await linked("out-a"); + await admin.hackathon.updateParticipantStatus({ + hackathonId: h.id, + participantId: a.p.id, + status: "waitlisted", + }); + expect(lastFor(acct("out-a"))).toEqual(ZEROS); + + const b = await linked("out-b"); + await admin.hackathon.batchUpdateParticipantStatus({ + hackathonId: h.id, + participantIds: [b.p.id], + status: "rejected", + }); + expect(lastFor(acct("out-b"))).toEqual(ZEROS); + + const c = await linked("out-c"); + await hackathonAs(c.u).withdrawRegistration({ hackathonId: h.id }); + expect(lastFor(acct("out-c"))).toEqual(ZEROS); + + const d = await linked("out-d"); + const email = ( + await S.db!.select({ email: S.users.email }).from(S.users).where(ops.eq(S.users.id, d.u)) + )[0]!.email!; + await admin.hackathon.banFromHackathons({ email, reason: "Testing the ban" }); + expect(lastFor(acct("out-d"))).toEqual(ZEROS); + await S.db!.delete(S.hackathonBans).where(ops.eq(S.hackathonBans.email, email.toLowerCase())); + }); + + it("a hacker who is also a judge keeps judge when the hacker side goes", async () => { + const h = await makeHackathon("both-out"); + const { u } = await newJudge("both-out", h.id); + const p = await makeParticipant(h.id, u); + await linkAs(u, h.id, acct("both-out")); + expect(lastFor(acct("both-out"))).toMatchObject({ accepted: 1, judge: 1 }); + await (await staff("both-out-admin")).hackathon.updateParticipantStatus({ + hackathonId: h.id, + participantId: p.id, + status: "rejected", + }); + expect(lastFor(acct("both-out"))).toEqual({ ...ZEROS, judge: 1 }); + }); + + it("unlink clears the roles with the stored token, then deletes the link", async () => { + const h = await makeHackathon("unlink"); + const { u } = await newJudge("unlink", h.id); + await linkAs(u, h.id, acct("unlink")); + let linkedAtPut: boolean | undefined; + world.beforePut = async () => { + linkedAtPut = !!(await linkOf(u)); + }; + + await hackathonAs(u).unlinkDiscord({ hackathonId: h.id }); + expect(lastFor(acct("unlink"))).toEqual(ZEROS); + expect(linkedAtPut).toBe(true); + expect(await linkOf(u)).toBeUndefined(); + }); + + it("unlink keeps the link, and says so, when Discord cannot be reached to clear the roles", async () => { + const h = await makeHackathon("unlink-fail"); + const { u } = await newJudge("unlink-fail", h.id); + await linkAs(u, h.id, acct("unlink-fail")); + world.putStatus = 500; + await expect(hackathonAs(u).unlinkDiscord({ hackathonId: h.id })).rejects.toThrow( + /roles were not cleared/, + ); + expect(await linkOf(u)).toBeDefined(); + + world.putStatus = 200; + await hackathonAs(u).unlinkDiscord({ hackathonId: h.id }); + expect(await linkOf(u)).toBeUndefined(); + }); + + it("linking another Discord account first clears the roles on the old one", async () => { + const h = await makeHackathon("relink"); + const { u } = await newJudge("relink", h.id); + await linkAs(u, h.id, acct("relink-x")); + expect(await linkAs(u, h.id, acct("relink-y"))).toMatchObject({ ok: true }); + + expect(lastFor(acct("relink-x"))).toEqual(ZEROS); + expect(lastFor(acct("relink-y"))).toEqual({ ...ZEROS, judge: 1 }); + // X was cleared before Y was given anything. + const order = world.puts.map((p) => `${p.account}:${p.metadata.judge}`); + expect(order).toEqual([ + `${acct("relink-x")}:1`, + `${acct("relink-x")}:0`, + `${acct("relink-y")}:1`, + ]); + expect(await linkOf(u)).toMatchObject({ discordUserId: acct("relink-y") }); + }); + + it("does not move the link when the old account's roles cannot be cleared", async () => { + const h = await makeHackathon("relink-fail"); + const { u } = await newJudge("relink-fail", h.id); + await linkAs(u, h.id, acct("rf-x")); + world.putStatus = 500; + expect(await linkAs(u, h.id, acct("rf-y"))).toMatchObject({ + ok: false, + reason: "discord_error", + }); + expect(await linkOf(u)).toMatchObject({ discordUserId: acct("rf-x") }); + expect(putsFor(acct("rf-y"))).toHaveLength(0); + }); + + it("linking the same account again clears nothing", async () => { + const h = await makeHackathon("relink-same"); + const { u } = await newJudge("relink-same", h.id); + await linkAs(u, h.id, acct("rs")); + await linkAs(u, h.id, acct("rs")); + expect(putsFor(acct("rs")).map((p) => p.metadata.judge)).toEqual([1, 1]); + }); + + it("a link made before tokens were kept cannot be cleared, and still unlinks", async () => { + const h = await makeHackathon("legacy-link"); + const { u, judgeId } = await newJudge("legacy-link", h.id); + await S.db!.insert(S.discordLinks).values({ + userId: u, + discordUserId: acct("legacy"), + discordUsername: "old", + }); + await (await staff("legacy-admin")).judge.setActive({ judgeId, isActive: false }); + expect(world.puts).toHaveLength(0); + expect(await svc.syncDiscordRoles(S.db as any, u)).toBe("no_token"); + + await hackathonAs(u).unlinkDiscord({ hackathonId: h.id }); + expect(await linkOf(u)).toBeUndefined(); + expect(world.puts).toHaveLength(0); + }); + + it("refreshes an expired access token, stores the rotated pair, and publishes with the new one", async () => { + const h = await makeHackathon("refresh"); + const { u, judgeId } = await newJudge("refresh", h.id); + await linkAs(u, h.id, acct("refresh")); + const before = (await linkOf(u))!; + await expireToken(u); + + await (await staff("refresh-admin")).judge.setActive({ judgeId, isActive: false }); + expect(world.refreshCalls).toBe(1); + const after = (await linkOf(u))!; + expect(after.refreshTokenEnc).not.toBe(before.refreshTokenEnc); + expect(after.tokenExpiresAt!.getTime()).toBeGreaterThan(Date.now()); + const { openToken } = await import("../services/discord/token-crypto"); + const newAccess = openToken(after.accessTokenEnc, SECRET, u); + expect(newAccess).toBe(world.issued.at(-2)); + expect(world.puts.at(-1)).toMatchObject({ bearer: newAccess, metadata: ZEROS }); + }); + + it("drops the link when Discord says the connection was withdrawn", async () => { + const h = await makeHackathon("revoked"); + const { u } = await newJudge("revoked", h.id); + const p = await makeParticipant(h.id, u); + await linkAs(u, h.id, acct("revoked")); + expect((await row(p.id)).discordUserId).toBe(acct("revoked")); + await S.db! + .update(S.judges) + .set({ isActive: false }) + .where(ops.eq(S.judges.userId, u)); + await expireToken(u); + world.refreshFails = "invalid_grant"; + + expect(await svc.syncDiscordRoles(S.db as any, u)).toBe("revoked"); + expect(await linkOf(u)).toBeUndefined(); + expect((await row(p.id)).discordUserId).toBeNull(); + }); + + it("keeps the link when a refresh fails for another reason, and when the sync is a no-op", async () => { + const h = await makeHackathon("refresh-500"); + const { u, judgeId } = await newJudge("refresh-500", h.id); + await linkAs(u, h.id, acct("r500")); + await expireToken(u); + world.refreshFails = 500; + await S.db!.update(S.judges).set({ isActive: false }).where(ops.eq(S.judges.id, judgeId)); + expect(await svc.syncDiscordRoles(S.db as any, u)).toBe("failed"); + expect(await linkOf(u)).toBeDefined(); + + world.refreshFails = null; + expect(await svc.syncDiscordRoles(S.db as any, u)).toBe("synced"); + expect(await svc.syncDiscordRoles(S.db as any, u)).toBe("unchanged"); + expect(putsFor(acct("r500"))).toHaveLength(2); + }); + + + describe("a batch that revokes more roles than one request can sync", () => { + const HACKER = { ...ZEROS, accepted: 1, food_group: 4 }; + const sigOf = (m: Record) => + `a${m.accepted}f${m.food_group}r${m.ramadan}j${m.judge}v${m.volunteer}`; + + /** n hackers, each with a stored link and tokens, as if linked a while ago. */ + const linkedHackers = async (hackathonId: string, n: number, tag: string) => { + const { sealTokens } = await import("../services/discord/tokens"); + const people: { userId: string; participantId: string; account: string }[] = []; + const links: (typeof S.discordLinks.$inferInsert)[] = []; + for (let i = 0; i < n; i++) { + const userId = await makeUser(`${tag}${i}`); + const participantId = (await makeParticipant(hackathonId, userId)).id; + const account = acct(`${tag}${i}`); + const issued = world.issue(account); + links.push({ + userId, + discordUserId: account, + discordUsername: account, + ...sealTokens( + { + accessToken: issued.access_token, + refreshToken: issued.refresh_token, + expiresAt: new Date(Date.now() + 86_400_000), + }, + SECRET, + userId, + ), + rolesSig: sigOf(HACKER), + }); + people.push({ userId, participantId, account }); + } + await S.db!.insert(S.discordLinks).values(links); + return people; + }; + const sigs = async (people: { userId: string }[]) => + ( + await S.db! + .select({ sig: S.discordLinks.rolesSig }) + .from(S.discordLinks) + .where(ops.inArray(S.discordLinks.userId, people.map((p) => p.userId))) + ).map((r) => r.sig); + + it("marks every linked person pending in the same change, so nothing is left looking synced", async () => { + await clearLinks(); + const h = await makeHackathon("batch-down"); + const admin = await staff("batch-down-admin"); + const people = await linkedHackers(h.id, 150, "bd"); + expect(new Set(await sigs(people))).toEqual(new Set([sigOf(HACKER)])); + + // Discord is down, so no inline sync can land. + world.putStatus = 500; + await admin.hackathon.batchUpdateParticipantStatus({ + hackathonId: h.id, + participantIds: people.map((p) => p.participantId), + status: "rejected", + }); + expect(new Set(await sigs(people))).toEqual(new Set([null])); + expect(world.puts).toHaveLength(0); + + // Discord is back: the daily job clears them, a run at a time. + world.putStatus = 200; + expect(await svc.syncExpiredDiscordRoles(S.db as any, { limit: 100 })).toEqual({ + checked: 100, + synced: 100, + }); + expect(await svc.syncExpiredDiscordRoles(S.db as any, { limit: 100 })).toEqual({ + checked: 50, + synced: 50, + }); + expect(await svc.syncExpiredDiscordRoles(S.db as any, { limit: 100 })).toEqual({ + checked: 0, + synced: 0, + }); + expect(new Set(await sigs(people))).toEqual(new Set([sigOf(ZEROS)])); + for (const p of people) expect(lastFor(p.account)).toEqual(ZEROS); + }, 60_000); + + it("syncs what one request can and leaves the rest pending for the daily job", async () => { + await clearLinks(); + const h = await makeHackathon("batch-up"); + const admin = await staff("batch-up-admin"); + const people = await linkedHackers(h.id, 150, "bu"); + + await admin.hackathon.batchUpdateParticipantStatus({ + hackathonId: h.id, + participantIds: people.map((p) => p.participantId), + status: "rejected", + }); + // Whatever the request did not reach is pending, never still "accepted". + const after = await sigs(people); + expect(after.filter((sig) => sig === sigOf(HACKER))).toHaveLength(0); + expect(after.filter((sig) => sig === sigOf(ZEROS)).length).toBeGreaterThanOrEqual(50); + expect(after.filter((sig) => sig === null).length).toBe(150 - after.filter((sig) => sig === sigOf(ZEROS)).length); + + for (let run = 0; run < 3; run++) await svc.syncExpiredDiscordRoles(S.db as any, { limit: 100 }); + expect(new Set(await sigs(people))).toEqual(new Set([sigOf(ZEROS)])); + for (const p of people) expect(lastFor(p.account)).toEqual(ZEROS); + }, 60_000); + + it("marks a ban's people pending too", async () => { + await clearLinks(); + const h = await makeHackathon("batch-ban"); + const admin = await staff("batch-ban-admin"); + const [person] = await linkedHackers(h.id, 1, "bb"); + world.putStatus = 500; + const email = ( + await S.db!.select({ email: S.users.email }).from(S.users).where(ops.eq(S.users.id, person!.userId)) + )[0]!.email!; + await admin.hackathon.banFromHackathons({ email, reason: "Testing the ban" }); + expect(await sigs([person!])).toEqual([null]); + await S.db!.delete(S.hackathonBans).where(ops.eq(S.hackathonBans.email, email.toLowerCase())); + }); + }); + + describe("the daily job cannot be starved by links it cannot serve", () => { + const insertLink = async ( + tag: string, + over: { + secret?: string; + expired?: boolean; + sig: string | null; + attemptedAt?: Date | null; + }, + ) => { + const { sealTokens } = await import("../services/discord/tokens"); + const userId = await makeUser(tag); + const account = acct(tag); + const issued = world.issue(account); + await S.db!.insert(S.discordLinks).values({ + userId, + discordUserId: account, + discordUsername: account, + ...sealTokens( + { + accessToken: issued.access_token, + refreshToken: issued.refresh_token, + expiresAt: new Date(Date.now() + (over.expired ? -60_000 : 86_400_000)), + }, + over.secret ?? SECRET, + userId, + ), + rolesSig: over.sig, + syncAttemptedAt: over.attemptedAt ?? null, + }); + return { userId, account }; + }; + const sigOf = async (userId: string) => (await linkOf(userId))!.rolesSig; + const ROTATED = "z".repeat(40); + + it("a link whose tokens cannot be opened leaves the sweep for good", async () => { + await clearLinks(); + const stuck: { userId: string; account: string }[] = []; + for (let i = 0; i < 20; i++) { + stuck.push(await insertLink(`nt${i}`, { secret: ROTATED, sig: null })); + } + + expect(await svc.syncExpiredDiscordRoles(S.db as any, { limit: 15 })).toEqual({ + checked: 15, + synced: 0, + }); + expect(await svc.syncExpiredDiscordRoles(S.db as any, { limit: 15 })).toEqual({ + checked: 5, + synced: 0, + }); + // Every one was tried once and marked unreachable, so nothing is left to try. + expect(await svc.syncExpiredDiscordRoles(S.db as any, { limit: 15 })).toEqual({ + checked: 0, + synced: 0, + }); + for (const { userId } of stuck) expect(await sigOf(userId)).toBe("unreachable"); + expect(world.puts).toHaveLength(0); + }); + + it("takes at most 15 a run by default, and stops when its time is up", async () => { + await clearLinks(); + expect(svc.SWEEP_BATCH).toBe(15); + const pending: { userId: string; account: string }[] = []; + for (let i = 0; i < 20; i++) { + pending.push(await insertLink(`cap${i}`, { sig: null })); + } + expect(await svc.syncExpiredDiscordRoles(S.db as any)).toEqual({ checked: 15, synced: 15 }); + + // Five are left; Discord answers slowly, and the run has 150 ms. + world.beforePut = async () => { + await sleep(100); + }; + const run = await svc.syncExpiredDiscordRoles(S.db as any, { budgetMs: 150 }); + expect(run.checked).toBeGreaterThanOrEqual(1); + expect(run.checked).toBeLessThan(5); + const left = ( + await S.db! + .select({ sig: S.discordLinks.rolesSig }) + .from(S.discordLinks) + .where(ops.inArray(S.discordLinks.userId, pending.map((p) => p.userId))) + ).filter((r) => r.sig === null); + expect(left.length).toBe(5 - run.checked); + + // What it did not reach is still owed, and the next run finishes it. + world.beforePut = undefined; + expect(await svc.syncExpiredDiscordRoles(S.db as any)).toEqual({ + checked: left.length, + synced: left.length, + }); + }, 30_000); + + it("30 links that keep failing do not keep a real expired volunteer waiting", async () => { + await clearLinks(); + world.refreshFails = 500; + const stuck: { userId: string; account: string }[] = []; + for (let i = 0; i < 30; i++) { + stuck.push(await insertLink(`fl${i}`, { expired: true, sig: null })); + } + const volunteer = await insertLink("fl-vol", { + sig: "a0f0r0j0v1", + }); + await S.db!.insert(S.admins).values({ + userId: volunteer.userId, + role: "volunteer", + expiresAt: new Date(Date.now() - 60_000), + }); + + const sweep = () => svc.syncExpiredDiscordRoles(S.db as any, { limit: 15 }); + const attempts = async () => + new Map( + ( + await S.db! + .select({ id: S.discordLinks.userId, at: S.discordLinks.syncAttemptedAt }) + .from(S.discordLinks) + .where(ops.inArray(S.discordLinks.userId, stuck.map((s) => s.userId))) + ).map((r) => [r.id, r.at]), + ); + + // Each run takes the 15 tried longest ago (never-tried first), so the + // 31 are all reached in three runs, whatever order they sit in. + const seen = new Set(); + for (let run = 0; run < 3; run++) { + const before = await attempts(); + const result = await sweep(); + expect(result.checked).toBeLessThanOrEqual(15); + for (const [id, at] of await attempts()) { + if (at && at.getTime() !== before.get(id)?.getTime()) seen.add(id); + } + } + expect(seen.size).toBe(30); + // The volunteer was served, ahead of the links that only ever fail. + expect(await sigOf(volunteer.userId)).toBe("a0f0r0j0v0"); + expect(lastFor(volunteer.account)).toEqual(ZEROS); + // The failing ones are still owed a sync; nothing marked them done. + for (const { userId } of stuck) expect(await sigOf(userId)).toBeNull(); + }, 60_000); + }); + + describe("one person's changes take turns", () => { + // Roles are changed by a sync, a link and an unlink, each of which reads + // the link, calls Discord and writes back. Run at once they must not step + // on each other: a refresh token is single use, and two writes of "what + // Discord has" can land in the wrong order. + const opts = () => ({ config: CONFIG, secret: SECRET, fetchImpl: world.fn }); + const sig = (m: Record) => + `a${m.accepted}f${m.food_group}r${m.ramadan}j${m.judge}v${m.volunteer}`; + const setJudge = (judgeId: string, isActive: boolean) => + S.db!.update(S.judges).set({ isActive }).where(ops.eq(S.judges.id, judgeId)); + + it("two syncs at once refresh the token once, and neither drops the link", async () => { + const h = await makeHackathon("race-refresh"); + const { u, judgeId } = await newJudge("race-refresh", h.id); + await linkAs(u, h.id, acct("race-refresh")); + await expireToken(u); + await setJudge(judgeId, false); + world.refreshDelayMs = 120; + + const first = svc.syncDiscordRoles(S.db as any, u, opts()); + await sleep(20); + const second = svc.syncDiscordRoles(S.db as any, u, opts()); + const results = await Promise.all([first, second]); + + expect(results).toEqual(["synced", "unchanged"]); + expect(world.refreshCalls).toBe(1); + const row = (await linkOf(u))!; + expect(row.rolesSig).toBe(sig(ZEROS)); + expect(lastFor(acct("race-refresh"))).toEqual(ZEROS); + }); + + it("a sync that starts while another is publishing does not leave Discord behind the database", async () => { + const h = await makeHackathon("race-order"); + const { u, judgeId } = await newJudge("race-order", h.id); + await linkAs(u, h.id, acct("race-order")); + await setJudge(judgeId, false); + + // The first sync has read "no longer a judge" and is on its way to + // Discord. While it is there the judge is approved again, and a second + // sync starts. + let second!: Promise; + let held = false; + world.beforePut = async () => { + if (held) return; + held = true; + await setJudge(judgeId, true); + second = svc.syncDiscordRoles(S.db as any, u, opts()); + await sleep(120); + }; + await svc.syncDiscordRoles(S.db as any, u, opts()); + await second; + + // The approval is what Discord ends up with, and the database says so. + expect(lastFor(acct("race-order"))).toEqual({ ...ZEROS, judge: 1 }); + expect((await linkOf(u))!.rolesSig).toBe(sig({ ...ZEROS, judge: 1 })); + }); + + it("an unlink that starts during a sync still leaves the old account cleared", async () => { + const h = await makeHackathon("race-unlink"); + const { u, judgeId } = await newJudge("race-unlink", h.id); + await linkAs(u, h.id, acct("race-unlink")); + await setJudge(judgeId, false); + expect(await svc.syncDiscordRoles(S.db as any, u, opts())).toBe("synced"); + // Approved again: the next sync publishes judge, slowly. + await setJudge(judgeId, true); + + let unlinking!: Promise; + let held = false; + world.beforePut = async () => { + if (held) return; + held = true; + unlinking = hackathonAs(u).unlinkDiscord({ hackathonId: h.id }); + await sleep(120); + }; + expect(await svc.syncDiscordRoles(S.db as any, u, opts())).toBe("synced"); + await unlinking; + + expect(await linkOf(u)).toBeUndefined(); + expect(lastFor(acct("race-unlink"))).toEqual(ZEROS); + }); + + it("linking another account while a sync runs clears the old one last-write-wins in order", async () => { + const h = await makeHackathon("race-relink"); + const { u, judgeId } = await newJudge("race-relink", h.id); + await linkAs(u, h.id, acct("race-rx")); + await setJudge(judgeId, false); + expect(await svc.syncDiscordRoles(S.db as any, u, opts())).toBe("synced"); + await setJudge(judgeId, true); + + let linking!: Promise; + let held = false; + world.beforePut = async () => { + if (held) return; + held = true; + linking = linkAs(u, h.id, acct("race-ry")); + await sleep(120); + }; + await svc.syncDiscordRoles(S.db as any, u, opts()); + await linking; + + // X ends cleared and Y holds the role, whichever got there first. + expect(lastFor(acct("race-rx"))).toEqual(ZEROS); + expect(lastFor(acct("race-ry"))).toEqual({ ...ZEROS, judge: 1 }); + expect(await linkOf(u)).toMatchObject({ discordUserId: acct("race-ry") }); + }); + }); + + it("a status change that gives a role is synced too, single or in a batch", async () => { + await clearLinks(); + const h = await makeHackathon("status-up"); + const admin = await staff("status-up-admin"); + const make = async (tag: string) => { + const { u } = await newJudge(tag, h.id); + // Waitlisted, but already said they are coming. + const p = await makeParticipant(h.id, u, { registrationStatus: "waitlisted" }); + await linkAs(u, h.id, acct(tag)); + expect(lastFor(acct(tag))).toEqual({ ...ZEROS, judge: 1 }); + return p.id; + }; + + await admin.hackathon.updateParticipantStatus({ + hackathonId: h.id, + participantId: await make("up-single"), + status: "approved", + }); + expect(lastFor(acct("up-single"))).toMatchObject({ accepted: 1, judge: 1 }); + expect(lastFor(acct("up-single"))!.food_group).toBeGreaterThan(0); + + await admin.hackathon.batchUpdateParticipantStatus({ + hackathonId: h.id, + participantIds: [await make("up-batch")], + status: "approved", + }); + expect(lastFor(acct("up-batch"))).toMatchObject({ accepted: 1, judge: 1 }); + expect(lastFor(acct("up-batch"))!.food_group).toBeGreaterThan(0); + }); + + it("never throws into the change that triggered it", async () => { + const h = await makeHackathon("nothrow"); + const { u, judgeId } = await newJudge("nothrow", h.id); + await linkAs(u, h.id, acct("nothrow")); + const logs = [ + vi.spyOn(console, "error").mockImplementation(() => {}), + vi.spyOn(console, "warn").mockImplementation(() => {}), + ]; + world.throws = true; + await expect( + (await staff("nothrow-admin")).judge.setActive({ judgeId, isActive: false }), + ).resolves.toMatchObject({ success: true, isActive: false }); + const logged = logs.flatMap((log) => log.mock.calls.flat()).join(" "); + expect(logged).toContain("did not reach Discord"); + for (const secret of world.issued) expect(logged).not.toContain(secret); + for (const log of logs) log.mockRestore(); + // The judge is deactivated whether or not Discord heard about it. + expect((await S.db!.select().from(S.judges).where(ops.eq(S.judges.id, judgeId)))[0]!.isActive).toBe(false); + }); + + it("does nothing when Discord is not configured", async () => { + const h = await makeHackathon("off"); + const { u } = await newJudge("off", h.id); + await linkAs(u, h.id, acct("off")); + const before = world.puts.length; + expect(await svc.syncDiscordRoles(S.db as any, u, { config: null })).toBe("off"); + expect(world.puts).toHaveLength(before); + }); + }); }); diff --git a/packages/api/src/.internal-tests/hackathon-admin-edge.test.ts b/packages/api/src/.internal-tests/hackathon-admin-edge.test.ts index b1e360bea..f0481780d 100644 --- a/packages/api/src/.internal-tests/hackathon-admin-edge.test.ts +++ b/packages/api/src/.internal-tests/hackathon-admin-edge.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; +import type * as DiscordSync from "../services/discord/sync"; import { appRouter } from "../root"; import { errorFormatter } from "../trpc"; import { cache } from "../middleware/cache"; @@ -34,6 +35,16 @@ vi.mock("@query/auth/email", () => ({ sendAcceptanceEmail: (...args: any[]) => mockSendAcceptanceEmail(...args), })); +// These cases are about the admin flow, not Discord. The link bookkeeping the +// flow now does (marking links pending, syncing roles) is covered against a real +// database in discord-link.db.test.ts, so here it does nothing. +vi.mock("../services/discord/sync", async (importOriginal) => ({ + ...(await importOriginal()), + markDiscordRolesPending: vi.fn(async () => {}), + syncDiscordRoles: vi.fn(async () => "off" as const), + syncDiscordRolesFor: vi.fn(async () => {}), +})); + vi.mock("@query/db", () => { const table = (name: string) => ({ findFirst: (...args: any[]) => mockFindFirst(name, ...args), diff --git a/packages/api/src/.internal-tests/participant-edge.test.ts b/packages/api/src/.internal-tests/participant-edge.test.ts index 6d8f60142..c34031125 100644 --- a/packages/api/src/.internal-tests/participant-edge.test.ts +++ b/packages/api/src/.internal-tests/participant-edge.test.ts @@ -1,5 +1,6 @@ import { applicationAnswers } from "./_application-answers"; import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type * as DiscordSync from "../services/discord/sync"; import { appRouter } from "../root"; import { cache } from "../middleware/cache"; import { @@ -22,6 +23,16 @@ const mockUpdate = vi.fn(); const mockDelete = vi.fn(); const mockSelect = vi.fn((..._args: any[]) => [{ count: 0 }] as unknown[]); +// These cases are about the admin flow, not Discord. The link bookkeeping the +// flow now does (marking links pending, syncing roles) is covered against a real +// database in discord-link.db.test.ts, so here it does nothing. +vi.mock("../services/discord/sync", async (importOriginal) => ({ + ...(await importOriginal()), + markDiscordRolesPending: vi.fn(async () => {}), + syncDiscordRoles: vi.fn(async () => "off" as const), + syncDiscordRolesFor: vi.fn(async () => {}), +})); + vi.mock("@query/db", async () => { const { createTransactionMock } = await import("./_db-tx-mock"); diff --git a/packages/api/src/.internal-tests/qr-checkin.test.ts b/packages/api/src/.internal-tests/qr-checkin.test.ts index 09058e48b..b509d5cb8 100644 --- a/packages/api/src/.internal-tests/qr-checkin.test.ts +++ b/packages/api/src/.internal-tests/qr-checkin.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; +import type * as DiscordSync from "../services/discord/sync"; import { appRouter } from "../root"; import { cache } from "../middleware/cache"; import { @@ -31,6 +32,16 @@ const mockSelect = vi.fn(); // attendance joined to its event. Empty unless a test says otherwise. const mockEarlierAttendance = vi.fn<() => unknown[]>(() => []); +// These cases are about the admin flow, not Discord. The link bookkeeping the +// flow now does (marking links pending, syncing roles) is covered against a real +// database in discord-link.db.test.ts, so here it does nothing. +vi.mock("../services/discord/sync", async (importOriginal) => ({ + ...(await importOriginal()), + markDiscordRolesPending: vi.fn(async () => {}), + syncDiscordRoles: vi.fn(async () => "off" as const), + syncDiscordRolesFor: vi.fn(async () => {}), +})); + vi.mock("@query/db", async () => { const { createTransactionMock } = await import("./_db-tx-mock"); diff --git a/packages/api/src/.internal-tests/routers.test.ts b/packages/api/src/.internal-tests/routers.test.ts index 66925b9b8..b2a4d9988 100644 --- a/packages/api/src/.internal-tests/routers.test.ts +++ b/packages/api/src/.internal-tests/routers.test.ts @@ -1,6 +1,7 @@ import { applicationAnswers } from "./_application-answers"; import { describe, it, expect, vi, beforeEach } from "vitest"; +import type * as DiscordSync from "../services/discord/sync"; import { appRouter } from "../root"; import { TRPCError } from "@trpc/server"; import { z } from "zod"; @@ -34,6 +35,16 @@ vi.mock("@query/auth/email", () => ({ sendAcceptanceEmail: vi.fn(), })); +// These cases are about the admin flow, not Discord. The link bookkeeping the +// flow now does (marking links pending, syncing roles) is covered against a real +// database in discord-link.db.test.ts, so here it does nothing. +vi.mock("../services/discord/sync", async (importOriginal) => ({ + ...(await importOriginal()), + markDiscordRolesPending: vi.fn(async () => {}), + syncDiscordRoles: vi.fn(async () => "off" as const), + syncDiscordRolesFor: vi.fn(async () => {}), +})); + vi.mock("@query/db", () => { return { db: { diff --git a/packages/api/src/routers/admin.ts b/packages/api/src/routers/admin.ts index f92f5d993..d612571f5 100644 --- a/packages/api/src/routers/admin.ts +++ b/packages/api/src/routers/admin.ts @@ -24,6 +24,7 @@ import { import type { DrizzleDB } from "@query/db"; import { startOfEasternDay } from "../services/eastern-time"; import { readLiveHackathons } from "../services/metrics"; +import { syncDiscordRoles } from "../services/discord"; // Roles are a super admin's to give, with one exception: anyone on the admin // team may staff the check-in desk by granting and revoking the volunteer tier, @@ -424,6 +425,11 @@ export const adminRouter = createTRPCRouter({ ctx.cache.delete(`admins:list`); invalidatePortalContext(input.userId); + // A volunteer who is already linked to Discord gets the role at once. + if (newAdmin.role === "volunteer") { + await syncDiscordRoles(ctx.db as DrizzleDB, input.userId); + } + await recordAdminAction(ctx.db as DrizzleDB, { userId: ctx.userId, action: "admin.create", @@ -539,6 +545,12 @@ export const adminRouter = createTRPCRouter({ ctx.cache.delete(`admins:list`); invalidatePortalContext(targetAdmin.userId); + // Becoming, ceasing to be, switching off or renewing a volunteer moves the + // Discord volunteer role. + if (targetAdmin.role === "volunteer" || updatedAdmin.role === "volunteer") { + await syncDiscordRoles(ctx.db as DrizzleDB, targetAdmin.userId); + } + await recordAdminAction(ctx.db as DrizzleDB, { userId: ctx.userId, action: "admin.update", @@ -581,6 +593,10 @@ export const adminRouter = createTRPCRouter({ ctx.cache.delete(`admins:list`); invalidatePortalContext(targetAdmin.userId); + if (targetAdmin.role === "volunteer") { + await syncDiscordRoles(ctx.db as DrizzleDB, targetAdmin.userId); + } + await recordAdminAction(ctx.db as DrizzleDB, { userId: ctx.userId, action: "admin.remove", diff --git a/packages/api/src/routers/hackathon/admin/status.ts b/packages/api/src/routers/hackathon/admin/status.ts index eb33643e3..af9569749 100644 --- a/packages/api/src/routers/hackathon/admin/status.ts +++ b/packages/api/src/routers/hackathon/admin/status.ts @@ -19,7 +19,12 @@ import { } from "@query/db"; import { eq, and, inArray, ne, notExists, sql } from "drizzle-orm"; import type { DrizzleDB } from "@query/db"; -import { autoAssignFoodGroups } from "../../../services/discord"; +import { + autoAssignFoodGroups, + markDiscordRolesPending, + syncDiscordRoles, + syncDiscordRolesFor, +} from "../../../services/discord"; import { SEATED_STATUSES, assertSeats, @@ -103,6 +108,10 @@ export const statusProcedures = { "This applicant's status changed just now. Refresh and check again before letting them in.", }); } + // A linked Discord account is owed a sync, whatever this request reaches. + await markDiscordRolesPending(tx as unknown as DrizzleDB, [ + participant.userId, + ]); }); // After the commit, not inside it: the assignment takes the hackathon row @@ -110,6 +119,11 @@ export const statusProcedures = { if (input.status === "approved" || input.status === "checked_in") { await autoAssignFoodGroups(ctx.db as DrizzleDB, input.hackathonId); } + // Whichever way it moved, a linked Discord account follows: out of the + // accepted statuses it loses its hacker roles, and into them (with the + // flower just assigned) it may gain them. Nothing is sent when nothing + // changed. + await syncDiscordRoles(ctx.db as DrizzleDB, participant.userId); evictParticipantCaches(ctx.cache, input.hackathonId, [ participant.userId, @@ -507,7 +521,7 @@ export const statusProcedures = { participantIds, ); } - return tx + const changed = await tx .update(hackathonParticipants) .set({ registrationStatus: status, @@ -542,6 +556,13 @@ export const statusProcedures = { id: hackathonParticipants.id, userId: hackathonParticipants.userId, }); + // Every linked Discord account among them is owed a sync, however many + // this request manages to reach. + await markDiscordRolesPending( + tx as unknown as DrizzleDB, + changed.map((row) => row.userId), + ); + return changed; }); if ( @@ -550,6 +571,12 @@ export const statusProcedures = { ) { await autoAssignFoodGroups(ctx.db as DrizzleDB, hackathonId); } + // Any direction, as for one person above. Everyone linked among them is + // already marked pending; this reaches as many as the request has time for. + await syncDiscordRolesFor( + ctx.db as DrizzleDB, + rows.map((row) => row.userId), + ); evictParticipantCaches( ctx.cache, diff --git a/packages/api/src/routers/hackathon/bans.ts b/packages/api/src/routers/hackathon/bans.ts index 5be39b77e..e62e27d61 100644 --- a/packages/api/src/routers/hackathon/bans.ts +++ b/packages/api/src/routers/hackathon/bans.ts @@ -6,6 +6,10 @@ import { createTRPCRouter } from "../../trpc"; import { hackathonBanCacheKey, isAdmin } from "../../middleware/procedures"; import { recordAdminAction } from "../../middleware/audit"; import { evictParticipantCaches } from "./admin/seats"; +import { + markDiscordRolesPending, + syncDiscordRolesFor, +} from "../../services/discord"; const normalize = (email: string) => email.trim().toLowerCase(); @@ -114,6 +118,11 @@ export const hackathonBansRouter = createTRPCRouter({ userId: hackathonParticipants.userId, hackathonId: hackathonParticipants.hackathonId, }); + // Rejected, so a linked Discord account is owed a sync. + await markDiscordRolesPending( + tx as unknown as DrizzleDB, + rejected.map((row) => row.userId), + ); return { ban, rejectedUserIds: rejected }; }); @@ -121,6 +130,11 @@ export const hackathonBansRouter = createTRPCRouter({ for (const row of rejectedUserIds) { evictParticipantCaches(ctx.cache, row.hackathonId, [row.userId]); } + // Rejected, so any Discord roles they linked come back off. + await syncDiscordRolesFor( + db, + rejectedUserIds.map((row) => row.userId), + ); ctx.cache.delete(hackathonBanCacheKey(email)); diff --git a/packages/api/src/routers/hackathon/discord.ts b/packages/api/src/routers/hackathon/discord.ts index 83a7f6af1..d4d4ae6d9 100644 --- a/packages/api/src/routers/hackathon/discord.ts +++ b/packages/api/src/routers/hackathon/discord.ts @@ -1,73 +1,100 @@ -// The hacker's side of the Discord link: status (with the lazily assigned food -// group) and unlink. Linking itself is the OAuth route in sites/mainweb. +// The Discord link as the signed-in person sees it: which roles they hold, the +// link status (with the lazily assigned flower) and unlink. Linking itself is +// the OAuth route in sites/mainweb. import { z } from "zod"; -import { and, eq } from "drizzle-orm"; +import { TRPCError } from "@trpc/server"; import { createTRPCRouter, protectedProcedure } from "../../trpc"; -import { hackathonParticipants } from "@query/db"; import type { DrizzleDB } from "@query/db"; import { discordConfig, + discordContext, ensureFoodGroup, foodGroupByKey, - isDiscordEligible, + hasDiscordRole, + isAcceptedHacker, + isConfirmedHacker, + NO_ROLES, + storedLink, + unlinkDiscord, } from "../../services/discord"; export const hackathonDiscordRouter = createTRPCRouter({ + // With a hackathon id, that edition. Without one (the judge page and the + // check-in desk have none), the newest live edition in which the person + // holds a role. `eligible` means a role applies and they may link. A hacker + // who is accepted but has not said "I'm coming" is not eligible yet: + // `awaitingConfirmation` is what tells the portal to ask for it. Their + // flower is shown either way, because it is also their meal wave. myDiscord: protectedProcedure - .input(z.object({ hackathonId: z.string().uuid() })) + .input(z.object({ hackathonId: z.string().uuid().optional() })) .query(async ({ ctx, input }) => { const db = ctx.db as DrizzleDB; - const row = await db.query.hackathonParticipants.findFirst({ - where: { hackathonId: input.hackathonId, userId: ctx.userId as string }, - columns: { - id: true, - registrationStatus: true, - ramadanFasting: true, - ramadanRoleOptIn: true, - discordUsername: true, - discordLinkedAt: true, - foodGroup: true, - }, - }); - if (!row || !isDiscordEligible(row.registrationStatus)) { - return { eligible: false as const }; + const userId = ctx.userId as string; + const context = await discordContext( + db, + userId, + input.hackathonId ?? null, + ); + const enabled = !!discordConfig(); + if (!context) { + return { + hackathon: null, + enabled, + eligible: false, + roles: NO_ROLES, + awaitingConfirmation: false, + linked: false, + username: null, + foodGroup: null, + fasting: false, + ramadanOptIn: false, + }; } + + const { hackathon, participant, roles } = context; + const accepted = !!participant && isAcceptedHacker(participant.registrationStatus); // The group exists whether or not they ever link: it is their meal wave. const foodGroup = - foodGroupByKey(row.foodGroup) ?? - foodGroupByKey(await ensureFoodGroup(db, input.hackathonId, row.id)); + accepted && participant + ? (foodGroupByKey(participant.foodGroup) ?? + foodGroupByKey(await ensureFoodGroup(db, hackathon.id, participant.id))) + : null; + const link = await storedLink(db, userId, participant); return { - eligible: true as const, - enabled: !!discordConfig(), - linked: !!row.discordLinkedAt, - username: row.discordUsername, + hackathon, + enabled, + eligible: hasDiscordRole(roles), + roles, + awaitingConfirmation: !!participant && accepted && !isConfirmedHacker(participant), + linked: !!link, + username: link?.username ?? null, foodGroup, - fasting: row.ramadanFasting === "Yes", - ramadanOptIn: row.ramadanRoleOptIn ?? false, + fasting: roles.hacker && participant?.ramadanFasting === "Yes", + ramadanOptIn: (roles.hacker && participant?.ramadanRoleOptIn) || false, }; }), - // Clears what we stored. The Discord connection itself lives in the user's - // Discord settings; we hold no token and cannot remove it. + // Takes the roles back, then clears what we stored: the person's link and, + // for a hacker, the copy on their registration. The roles are cleared on + // Discord first, with the token kept for it, so unlinking is not a way to + // keep a role while linking another account. If Discord cannot be reached + // the link stays and the person can try again. unlinkDiscord: protectedProcedure .input(z.object({ hackathonId: z.string().uuid() })) .mutation(async ({ ctx, input }) => { - await (ctx.db as DrizzleDB) - .update(hackathonParticipants) - .set({ - discordUserId: null, - discordUsername: null, - discordLinkedAt: null, - ramadanRoleOptIn: null, - updatedAt: new Date(), - }) - .where( - and( - eq(hackathonParticipants.hackathonId, input.hackathonId), - eq(hackathonParticipants.userId, ctx.userId as string), - ), - ); + const result = await unlinkDiscord( + ctx.db as DrizzleDB, + ctx.userId as string, + input.hackathonId, + ); + if (result === "failed") { + throw new TRPCError({ + code: "INTERNAL_SERVER_ERROR", + message: + "Discord did not answer, so your roles were not cleared. Try again in a moment.", + }); + } return { ok: true }; }), }); diff --git a/packages/api/src/routers/hackathon/registration.ts b/packages/api/src/routers/hackathon/registration.ts index 9df6675fa..b8434405c 100644 --- a/packages/api/src/routers/hackathon/registration.ts +++ b/packages/api/src/routers/hackathon/registration.ts @@ -21,6 +21,10 @@ import type { DrizzleDB } from "@query/db"; import { evictParticipantCaches } from "./admin"; import { teamMemberCountsForUser } from "../../services/derived-counts"; import { saveDraftInput } from "../../services/application-drafts"; +import { + markDiscordRolesPending, + syncDiscordRoles, +} from "../../services/discord"; import { rateLimitShared } from "../../middleware/security"; // Postgres unique_violation on hackathon_participant_hackathon_user_idx โ€” a second @@ -526,20 +530,30 @@ export const hackathonRegistrationRouter = createTRPCRouter({ // The checks above are a read; a badge scan or a team join can land // before this. Repeating them here deletes nothing in that case. - const removed = await db - .delete(hackathonParticipants) - .where( - and( - eq(hackathonParticipants.id, participant.id), - notInArray(hackathonParticipants.registrationStatus, [ - "checked_in", - "rejected", - "waitlisted", - ]), - isNull(hackathonParticipants.teamId), - ), - ) - .returning({ id: hackathonParticipants.id }); + const removed = await db.transaction(async (tx) => { + const deleted = await tx + .delete(hackathonParticipants) + .where( + and( + eq(hackathonParticipants.id, participant.id), + notInArray(hackathonParticipants.registrationStatus, [ + "checked_in", + "rejected", + "waitlisted", + ]), + isNull(hackathonParticipants.teamId), + ), + ) + .returning({ id: hackathonParticipants.id }); + // A linked Discord account is owed a sync, even if this request's own + // attempt below does not reach Discord. + if (deleted.length > 0) { + await markDiscordRolesPending(tx as unknown as DrizzleDB, [ + ctx.userId as string, + ]); + } + return deleted; + }); if (removed.length === 0) { throw new TRPCError({ code: "CONFLICT", @@ -551,6 +565,7 @@ export const hackathonRegistrationRouter = createTRPCRouter({ evictParticipantCaches(ctx.cache, input.hackathonId, [ ctx.userId as string, ]); + await syncDiscordRoles(db, ctx.userId as string); return { success: true }; }), diff --git a/packages/api/src/routers/judge/admin.ts b/packages/api/src/routers/judge/admin.ts index 1abe389d8..e12a67af6 100644 --- a/packages/api/src/routers/judge/admin.ts +++ b/packages/api/src/routers/judge/admin.ts @@ -10,6 +10,7 @@ import { eq, and, sql, desc } from "drizzle-orm"; import { isAdmin, isSuperAdmin } from "../../middleware/procedures"; import { CacheKeys, invalidatePortalContext } from "../../middleware/cache"; import { portalOrigin } from "../../services/judging/claims"; +import { syncDiscordRoles } from "../../services/discord"; import type { DrizzleDB } from "@query/db"; // The organiser's side of the judge roster: who applied, who is approved, and @@ -116,6 +117,10 @@ export const judgeAdminRouter = createTRPCRouter({ ctx.cache.deletePattern(`${CacheKeys.judge(user.id)}*`); invalidatePortalContext(user.id); + // Someone already linked to Discord gets the judge role without linking + // again. + await syncDiscordRoles(ctx.db as DrizzleDB, user.id); + // There was no application, so nothing else tells them they are a judge. // Its own copy rather than the approval's. Best-effort: a mail failure // must not undo a judge already in the database. @@ -196,6 +201,10 @@ export const judgeAdminRouter = createTRPCRouter({ // approved judge waits out that TTL before the Judge tab appears. invalidatePortalContext(updated.userId); + // Approval and removal of approval both move the Discord role: the judge + // role is granted or taken back on their linked account. + await syncDiscordRoles(ctx.db as DrizzleDB, updated.userId); + // Tells the judge they were approved โ€” the register success screen // promises this. Only on the transition. Best-effort: a mail failure must // not undo an approval already in the database. @@ -277,6 +286,7 @@ export const judgeAdminRouter = createTRPCRouter({ if (removed) { ctx.cache.deletePattern(`${CacheKeys.judge(removed.userId)}*`); invalidatePortalContext(removed.userId); + await syncDiscordRoles(ctx.db as DrizzleDB, removed.userId); } return { success: true }; }), diff --git a/packages/api/src/services/discord/api.ts b/packages/api/src/services/discord/api.ts new file mode 100644 index 000000000..2fe807a19 --- /dev/null +++ b/packages/api/src/services/discord/api.ts @@ -0,0 +1,127 @@ +// The few Discord HTTP calls the link and the role sync share. + +import type { DiscordConfig } from "./config"; +import type { RoleMetadata } from "./roles"; + +export const API = "https://discord.com/api/v10"; + +/** Past this a sync gives up, so a slow Discord cannot hold an admin's click. */ +const TIMEOUT_MS = 8_000; + +export type LinkErrorReason = + | "not_accepted" + | "bad_code" + | "rate_limited" + | "discord_denied" + | "discord_error" + | "already_linked"; + +/** + * An error's message for a log. A Drizzle error's message carries the + * statement's parameters, which can hold stored values; keep to the part before + * them. + */ +export const safeMessage = (error: unknown) => + (error instanceof Error ? error.message : String(error)) + .split("params:")[0]! + .slice(0, 300); + +export function failureFor(status: number): LinkErrorReason { + if (status === 429) return "rate_limited"; + if (status === 401 || status === 403) return "discord_denied"; + return "discord_error"; +} + +/** + * A refused Discord call: logs the step, status and Discord's error body (never + * a token; the bodies of failed calls carry only an error code and message), + * and reads `retry_after` and `error` from the same body. + */ +export async function refusal( + step: "token" | "me" | "role-connection" | "refresh", + res: Response, +): Promise<{ status: number; retryAfter?: number; error?: string }> { + const text = await res.text().catch(() => ""); + // Deliberate operational logging: the only trace of why a call failed. + // oxlint-disable-next-line no-console + console.warn(`[Discord link] ${step} refused: ${res.status} ${text.slice(0, 300)}`); + let retryAfter: number | undefined; + let error: string | undefined; + try { + const body = JSON.parse(text) as { retry_after?: number; error?: unknown }; + if (res.status === 429 && typeof body.retry_after === "number") { + retryAfter = Math.ceil(body.retry_after); + } + if (typeof body.error === "string") error = body.error; + } catch { + // No JSON body: nothing more to read. + } + return { status: res.status, retryAfter, error }; +} + +/** What Discord hands back for a code or a refresh token. */ +export type DiscordTokens = { + accessToken: string; + refreshToken: string | null; + expiresAt: Date | null; +}; + +export function readTokens( + body: { access_token?: string; refresh_token?: string; expires_in?: number }, + now = Date.now(), +): DiscordTokens | null { + if (!body.access_token) return null; + return { + accessToken: body.access_token, + refreshToken: body.refresh_token ?? null, + expiresAt: + typeof body.expires_in === "number" + ? new Date(now + body.expires_in * 1000) + : null, + }; +} + +/** Publishes the person's Linked Roles metadata with their own token. */ +export function putRoleConnection( + doFetch: typeof fetch, + config: DiscordConfig, + accessToken: string, + platformUsername: string, + metadata: RoleMetadata, +) { + return doFetch( + `${API}/users/@me/applications/${config.clientId}/role-connection`, + { + method: "PUT", + headers: { + Authorization: `Bearer ${accessToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + platform_name: "Hacklytics", + platform_username: platformUsername, + metadata, + }), + signal: AbortSignal.timeout(TIMEOUT_MS), + }, + ); +} + +/** Trades a refresh token for a new access token (and a rotated refresh token). */ +export function refreshAccessToken( + doFetch: typeof fetch, + config: DiscordConfig, + refreshToken: string, +) { + return doFetch(`${API}/oauth2/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + client_id: config.clientId, + client_secret: config.clientSecret, + grant_type: "refresh_token", + refresh_token: refreshToken, + }), + signal: AbortSignal.timeout(TIMEOUT_MS), + }); +} diff --git a/packages/api/src/services/discord/config.ts b/packages/api/src/services/discord/config.ts index 8aa133091..759bd3884 100644 --- a/packages/api/src/services/discord/config.ts +++ b/packages/api/src/services/discord/config.ts @@ -28,10 +28,6 @@ export function foodGroupByKey( return FOOD_GROUPS.find((g) => g.key === key) ?? null; } -/** Statuses that may link: accepted, or already through the door. */ -export const isDiscordEligible = (status: string | null | undefined) => - status === "approved" || status === "checked_in"; - export type DiscordConfig = { clientId: string; clientSecret: string; @@ -49,3 +45,14 @@ export function discordConfig( if (!/^https:\/\//.test(inviteUrl)) return null; return { clientId, clientSecret, inviteUrl }; } + +/** + * The secret the stored Discord tokens are sealed under (through HKDF, see + * token-crypto.ts): the same AUTH_SECRET the rest of the app reads. Null when + * it is not set, and nothing then reads or writes a token. + */ +export function discordTokenSecret( + env: Record = process.env, +): string | null { + return env.AUTH_SECRET || env.NEXTAUTH_SECRET || null; +} diff --git a/packages/api/src/services/discord/discord.test.ts b/packages/api/src/services/discord/discord.test.ts index 7da70c531..d6be0a943 100644 --- a/packages/api/src/services/discord/discord.test.ts +++ b/packages/api/src/services/discord/discord.test.ts @@ -1,7 +1,19 @@ +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; import { describe, expect, it, vi } from "vitest"; import { discordConfig, FOOD_GROUPS, foodGroupByKey } from "./config"; import { autoAssignFoodGroups, pickFoodGroup } from "./food-group"; -import { ramadanFlag } from "./link"; +import { + hasDiscordRole, + isConfirmedHacker, + NO_ROLES, + ramadanFlag, + roleMetadata, + roleSignature, + rolesFor, + ZERO_METADATA, +} from "./roles"; +import { openToken, sealToken } from "./token-crypto"; import { signState, verifyState, STATE_TTL_MS } from "./state"; const SECRET = "x".repeat(40); @@ -100,3 +112,159 @@ describe("ramadanFlag and config", () => { }); }); }); + +describe("discord roles", () => { + const at = new Date("2027-02-01T00:00:00Z"); + const hacker = (registrationStatus: string, attendanceConfirmedAt: Date | null) => ({ + registrationStatus, + attendanceConfirmedAt, + }); + + it("makes a hacker eligible only once they said they are coming, or are checked in", () => { + expect(isConfirmedHacker(hacker("approved", null))).toBe(false); + expect(isConfirmedHacker(hacker("approved", at))).toBe(true); + expect(isConfirmedHacker(hacker("checked_in", null))).toBe(true); + for (const status of ["pending", "waitlisted", "rejected"]) { + expect(isConfirmedHacker(hacker(status, at))).toBe(false); + } + }); + + it("holds each role independently, and any combination", () => { + const base = { participant: null, judge: false, volunteer: false, hackathonStatus: "open" }; + expect(rolesFor(base)).toEqual(NO_ROLES); + expect(rolesFor({ ...base, judge: true })).toEqual({ ...NO_ROLES, judge: true }); + expect(rolesFor({ ...base, volunteer: true })).toEqual({ ...NO_ROLES, volunteer: true }); + expect( + rolesFor({ ...base, participant: hacker("approved", at), judge: true, volunteer: true }), + ).toEqual({ hacker: true, judge: true, volunteer: true }); + expect( + rolesFor({ ...base, participant: hacker("approved", null), judge: true }), + ).toEqual({ hacker: false, judge: true, volunteer: false }); + }); + + it("gives volunteers a role only while the edition is open or live", () => { + const volunteerIn = (hackathonStatus: string) => + rolesFor({ participant: null, judge: false, volunteer: true, hackathonStatus }).volunteer; + for (const status of ["open", "closed", "in_progress"]) expect(volunteerIn(status)).toBe(true); + for (const status of ["draft", "announced", "completed", "cancelled"]) { + expect(volunteerIn(status)).toBe(false); + } + }); + + it("reports whether anyone holds a role", () => { + expect(hasDiscordRole(NO_ROLES)).toBe(false); + expect(hasDiscordRole({ ...NO_ROLES, volunteer: true })).toBe(true); + }); + + it("always sends all five fields, with the hacker's three at zero for anyone else", () => { + const flower = { foodGroup: 4, ramadan: 1 as const }; + expect(roleMetadata({ hacker: true, judge: false, volunteer: false }, flower)).toEqual({ + accepted: 1, + food_group: 4, + ramadan: 1, + judge: 0, + volunteer: 0, + }); + expect(roleMetadata({ hacker: false, judge: true, volunteer: false }, null)).toEqual({ + ...ZERO_METADATA, + judge: 1, + }); + expect(roleMetadata({ hacker: false, judge: false, volunteer: true }, null)).toEqual({ + ...ZERO_METADATA, + volunteer: 1, + }); + // A flower is never sent to somebody who is not a confirmed hacker. + expect( + roleMetadata({ hacker: false, judge: true, volunteer: false }, { foodGroup: 4, ramadan: 1 }), + ).toEqual({ ...ZERO_METADATA, judge: 1 }); + expect(roleMetadata({ hacker: false, judge: false, volunteer: false }, null)).toEqual( + ZERO_METADATA, + ); + expect(roleMetadata({ hacker: true, judge: true, volunteer: true }, flower)).toEqual({ + accepted: 1, + food_group: 4, + ramadan: 1, + judge: 1, + volunteer: 1, + }); + }); +}); + +describe("registered Linked Roles metadata", () => { + it("is exactly what the link sends, and within Discord's limit of 5 fields", () => { + const script = readFileSync( + fileURLToPath( + new URL( + "../../../../../tooling/scripts/src/discord-register-metadata.ts", + import.meta.url, + ), + ), + "utf8", + ); + const registered = [...script.matchAll(/key: "(\w+)"/g)].map((m) => m[1]); + const sent = Object.keys( + roleMetadata( + { hacker: true, judge: true, volunteer: true }, + { foodGroup: 1, ramadan: 1 }, + ), + ); + expect([...registered].sort()).toEqual([...sent].sort()); + expect(registered.length).toBeLessThanOrEqual(5); + }); +}); + +describe("roleSignature", () => { + it("changes with every field, and ends in the volunteer flag", () => { + const seen = new Set([roleSignature(ZERO_METADATA)]); + for (const patch of [ + { accepted: 1 as const }, + { food_group: 3 }, + { ramadan: 1 as const }, + { judge: 1 as const }, + { volunteer: 1 as const }, + ]) { + seen.add(roleSignature({ ...ZERO_METADATA, ...patch })); + } + expect(seen.size).toBe(6); + expect(roleSignature({ ...ZERO_METADATA, volunteer: 1 })).toMatch(/v1$/); + expect(roleSignature({ ...ZERO_METADATA, judge: 1 })).not.toMatch(/v1$/); + }); +}); + +describe("stored Discord tokens", () => { + const key = "k".repeat(40); + + it("round-trips, and never shows the token in the sealed value", () => { + const sealed = sealToken("a-discord-access-token", key, "user-1"); + expect(sealed).toMatch(/^v1\.[\w-]+\.[\w-]+\.[\w-]+$/); + expect(sealed).not.toContain("a-discord-access-token"); + expect(openToken(sealed, key, "user-1")).toBe("a-discord-access-token"); + }); + + it("seals the same token differently each time", () => { + expect(sealToken("same", key, "user-1")).not.toBe(sealToken("same", key, "user-1")); + }); + + it("does not open for another person, another secret, or a malformed value", () => { + const sealed = sealToken("tok", key, "user-1"); + expect(openToken(sealed, key, "user-2")).toBeNull(); + expect(openToken(sealed, "j".repeat(40), "user-1")).toBeNull(); + for (const bad of [null, undefined, "", "garbage", "v2.a.b.c", `${sealed}.extra`, "v1.a.b"]) { + expect(openToken(bad, key, "user-1")).toBeNull(); + } + }); + + it("fails when any part of the ciphertext is changed, or the tag is cut short", () => { + const [version, iv, ciphertext, tag] = sealToken("tok-to-protect", key, "user-1").split("."); + const flip = (part: string) => { + const bytes = Buffer.from(part!, "base64url"); + bytes[0] = bytes[0]! ^ 1; + return bytes.toString("base64url"); + }; + expect(openToken([version, iv, flip(ciphertext!), tag].join("."), key, "user-1")).toBeNull(); + expect(openToken([version, flip(iv!), ciphertext, tag].join("."), key, "user-1")).toBeNull(); + expect(openToken([version, iv, ciphertext, flip(tag!)].join("."), key, "user-1")).toBeNull(); + const short = Buffer.from(tag!, "base64url").subarray(0, 8).toString("base64url"); + expect(openToken([version, iv, ciphertext, short].join("."), key, "user-1")).toBeNull(); + }); +}); diff --git a/packages/api/src/services/discord/index.ts b/packages/api/src/services/discord/index.ts index d6be4d8ae..c71824bf5 100644 --- a/packages/api/src/services/discord/index.ts +++ b/packages/api/src/services/discord/index.ts @@ -1,4 +1,6 @@ export * from "./config"; export * from "./state"; export * from "./food-group"; +export * from "./roles"; +export * from "./sync"; export * from "./link"; diff --git a/packages/api/src/services/discord/link.ts b/packages/api/src/services/discord/link.ts index d57744a14..5fd2d0493 100644 --- a/packages/api/src/services/discord/link.ts +++ b/packages/api/src/services/discord/link.ts @@ -1,141 +1,170 @@ -import { and, eq } from "drizzle-orm"; -import { hackathonParticipants } from "@query/db"; +import { and, eq, ne } from "drizzle-orm"; +import { discordLinks, hackathonParticipants } from "@query/db"; import type { DrizzleDB } from "@query/db"; -import { foodGroupByKey, isDiscordEligible } from "./config"; +import { + API, + failureFor, + putRoleConnection, + readTokens, + refusal, + safeMessage, +} from "./api"; +import type { LinkErrorReason } from "./api"; import type { DiscordConfig } from "./config"; -import { ensureFoodGroup } from "./food-group"; +import { + discordContext, + hackerPayload, + hasDiscordRole, + roleMetadata, + roleSignature, +} from "./roles"; +import type { DiscordParticipant, DiscordRoles } from "./roles"; import type { DiscordState } from "./state"; +import { withDiscordLock, zeroDiscordRoles } from "./sync"; +import { sealTokens } from "./tokens"; import { isUniqueViolation } from "../../middleware/db-errors"; -const API = "https://discord.com/api/v10"; - -type LinkErrorReason = - | "not_accepted" - | "bad_code" - | "rate_limited" - | "discord_denied" - | "discord_error" - | "already_linked"; - type HackathonRef = { id: string; name: string }; +/** + * Where the person goes back to: the hackathon page for a hacker, the judge + * page for a judge, the check-in desk for a volunteer. Each is where that + * role's Discord card lives. + */ +export type LinkHome = "hackathon" | "judge" | "scan"; + type LinkResult = | { ok: true; then: DiscordState["t"]; hackathon: HackathonRef; + home: LinkHome; username: string; } | { ok: false; reason: LinkErrorReason; hackathon?: HackathonRef; + home?: LinkHome; retryAfter?: number; }; /** - * The participant a connect request is for. With a hackathon id, that one; - * without (Discord's Linked Roles verification URL sends none), the newest - * edition that is not cancelled or over which the user is accepted to. - * Null when they are not accepted there. + * The edition a connect request is for, with what the person holds there. + * With a hackathon id, that one; without (Discord's Linked Roles verification + * URL sends none), the newest edition that is not cancelled or over in which + * they hold a role. Null when they hold none: not a confirmed hacker, an + * approved judge or a volunteer. */ export async function resolveConnectTarget( db: DrizzleDB, userId: string, hackathonId: string | null, ) { - if (hackathonId) { - const row = await db.query.hackathonParticipants.findFirst({ - where: { hackathonId, userId }, - with: { hackathon: { columns: { id: true, name: true } } }, - }); - return row && isDiscordEligible(row.registrationStatus) ? row : null; - } - const rows = await db.query.hackathonParticipants.findMany({ - where: { userId }, - with: { - hackathon: { - columns: { id: true, name: true, status: true, startDate: true }, - }, - }, - }); - const live = rows - .filter( - (r) => - isDiscordEligible(r.registrationStatus) && - r.hackathon && - r.hackathon.status !== "cancelled" && - r.hackathon.status !== "completed", - ) - .sort( - (a, b) => - new Date(b.hackathon!.startDate).getTime() - - new Date(a.hackathon!.startDate).getTime(), - ); - return live[0] ?? null; -} - -/** The Ramadan flag Discord receives: opted in AND fasting is "Yes". */ -export const ramadanFlag = (optIn: boolean, fasting: string | null | undefined) => - optIn && fasting === "Yes" ? 1 : 0; - -function failureFor(status: number): LinkErrorReason { - if (status === 429) return "rate_limited"; - if (status === 401 || status === 403) return "discord_denied"; - return "discord_error"; + const context = await discordContext(db, userId, hackathonId); + return context && hasDiscordRole(context.roles) ? context : null; } /** - * A refused Discord call: logs the step, status and Discord's error body (never - * a token; the bodies of failed calls carry only an error code and message), - * and reads `retry_after` from the same body for a 429. + * The Discord account stored for this person: the one on their participant + * row (where hackers linked before judges and volunteers could), else their + * own link row. */ -async function refusal( - step: "token" | "me" | "role-connection", - res: Response, -): Promise<{ status: number; retryAfter?: number }> { - const text = await res.text().catch(() => ""); - // Deliberate operational logging: the only trace of why a link failed. - // oxlint-disable-next-line no-console - console.warn(`[Discord link] ${step} refused: ${res.status} ${text.slice(0, 300)}`); - let retryAfter: number | undefined; - if (res.status === 429) { - try { - const n = (JSON.parse(text) as { retry_after?: number }).retry_after; - if (typeof n === "number") retryAfter = Math.ceil(n); - } catch { - // No JSON body: retry with no hint. - } +export async function storedLink( + db: DrizzleDB, + userId: string, + participant: Pick< + DiscordParticipant, + "discordUsername" | "discordLinkedAt" + > | null, +): Promise<{ username: string; linkedAt: Date } | null> { + if (participant?.discordLinkedAt && participant.discordUsername) { + return { + username: participant.discordUsername, + linkedAt: participant.discordLinkedAt, + }; } - return { status: res.status, retryAfter }; + const [row] = await db + .select({ + username: discordLinks.discordUsername, + linkedAt: discordLinks.linkedAt, + }) + .from(discordLinks) + .where(eq(discordLinks.userId, userId)) + .limit(1); + return row ?? null; +} + +/** Whether somebody else already holds this Discord account, in either store. */ +async function heldByAnother( + db: DrizzleDB, + discordUserId: string, + userId: string, + hackathonId: string, +): Promise { + const [link] = await db + .select({ id: discordLinks.id }) + .from(discordLinks) + .where( + and( + eq(discordLinks.discordUserId, discordUserId), + ne(discordLinks.userId, userId), + ), + ) + .limit(1); + if (link) return true; + const [participant] = await db + .select({ id: hackathonParticipants.id }) + .from(hackathonParticipants) + .where( + and( + eq(hackathonParticipants.hackathonId, hackathonId), + eq(hackathonParticipants.discordUserId, discordUserId), + ne(hackathonParticipants.userId, userId), + ), + ) + .limit(1); + return !!participant; } +const homeOf = (roles: DiscordRoles): LinkHome => + roles.hacker ? "hackathon" : roles.judge ? "judge" : "scan"; + +const failWith = + (hackathon: HackathonRef, home: LinkHome) => + (reason: LinkErrorReason, extra: { retryAfter?: number } = {}): LinkResult => ({ + ok: false, + reason, + hackathon, + home, + ...extra, + }); + /** * The callback, after the route has checked the state and session. Exchanges - * the code, reads the account, stores the link, then publishes the Linked - * Roles metadata with the user's own token. The token is never kept. + * the code, reads the account, stores the link and the person's tokens + * (encrypted, so a role can be taken back later), then publishes the Linked + * Roles metadata with their own token. When the person is changing to a + * different Discord account, the old account's roles are cleared first, so + * one person cannot leave a role on each account they link in turn. */ export async function completeLink(opts: { db: DrizzleDB; config: DiscordConfig; + /** AUTH_SECRET: the tokens are sealed under a key derived from it. */ + secret: string; state: DiscordState; code: string; redirectUri: string; fetchImpl?: typeof fetch; }): Promise { - const { db, config, state, code } = opts; + const { db, config, secret, state, code } = opts; const doFetch = opts.fetchImpl ?? fetch; - const participant = await resolveConnectTarget(db, state.u, state.h); - if (!participant) return { ok: false, reason: "not_accepted" }; - const hackathon: HackathonRef = { - id: participant.hackathon!.id, - name: participant.hackathon!.name, - }; - const fail = ( - reason: LinkErrorReason, - extra: { retryAfter?: number } = {}, - ): LinkResult => ({ ok: false, reason, hackathon, ...extra }); + // Refused here, before Discord is called at all, when they hold no role. + const early = await resolveConnectTarget(db, state.u, state.h); + if (!early) return { ok: false, reason: "not_accepted" }; + const failEarly = failWith(early.hackathon, homeOf(early.roles)); const tokenRes = await doFetch(`${API}/oauth2/token`, { method: "POST", @@ -150,97 +179,188 @@ export async function completeLink(opts: { }); if (!tokenRes.ok) { const { status, retryAfter } = await refusal("token", tokenRes); - if (status === 400) return fail("bad_code"); - return fail(failureFor(status), { retryAfter }); + if (status === 400) return failEarly("bad_code"); + return failEarly(failureFor(status), { retryAfter }); } - const accessToken = ((await tokenRes.json()) as { access_token?: string }) - .access_token; - if (!accessToken) return fail("bad_code"); + const tokens = readTokens(await tokenRes.json()); + if (!tokens) return failEarly("bad_code"); + const accessToken = tokens.accessToken; const meRes = await doFetch(`${API}/users/@me`, { headers: { Authorization: `Bearer ${accessToken}` }, }); if (!meRes.ok) { const { status, retryAfter } = await refusal("me", meRes); - return fail(failureFor(status), { retryAfter }); + return failEarly(failureFor(status), { retryAfter }); } const me = (await meRes.json()) as { id?: string; username?: string; global_name?: string | null; }; - if (!me.id || !me.username) return fail("discord_error"); + if (!me.id || !me.username) return failEarly("discord_error"); + const discordId = me.id; + const discordName = me.username; const displayName = me.global_name || me.username; - // The food group first, so the metadata always has one. - const groupKey = await ensureFoodGroup(db, hackathon.id, participant.id); - const optIn = - state.r === null - ? (participant.ramadanRoleOptIn ?? false) - : state.r === 1; - const ramadan = ramadanFlag(optIn, participant.ramadanFasting); - const before = { - discordUserId: participant.discordUserId, - discordUsername: participant.discordUsername, - discordLinkedAt: participant.discordLinkedAt, - ramadanRoleOptIn: participant.ramadanRoleOptIn, - }; - try { - await db - .update(hackathonParticipants) - .set({ - discordUserId: me.id, - discordUsername: me.username, - discordLinkedAt: new Date(), - ramadanRoleOptIn: ramadan === 1, - updatedAt: new Date(), - }) - .where( - and( - eq(hackathonParticipants.id, participant.id), - eq(hackathonParticipants.hackathonId, hackathon.id), - ), + // From here the person's Discord changes: their old account may be cleared, + // the link is stored and the roles are published. That is one turn, so a + // sync or an unlink for the same person cannot interleave. What they hold is + // read again inside it, since it may have changed while Discord was asked. + return withDiscordLock(db, state.u, async (tx): Promise => { + const target = await resolveConnectTarget(tx, state.u, state.h); + if (!target) return { ok: false, reason: "not_accepted" }; + const { hackathon, participant, roles } = target; + const home = homeOf(roles); + const fail = failWith(hackathon, home); + + if (await heldByAnother(tx, discordId, state.u, hackathon.id)) { + return fail("already_linked"); + } + + const [priorLink] = await tx + .select() + .from(discordLinks) + .where(eq(discordLinks.userId, state.u)) + .limit(1); + // A different account than the one linked before: its roles are cleared + // first, with the token kept for it. If Discord cannot be reached to do + // that, the link does not move. A link with no token, or one Discord says + // was withdrawn, has nothing to clear. + let clearedOldAccount = false; + if (priorLink && priorLink.discordUserId !== discordId) { + const cleared = await zeroDiscordRoles(tx, priorLink, { + config, + secret, + fetchImpl: doFetch, + }); + if (cleared === "failed") return fail("discord_error"); + clearedOldAccount = cleared === "cleared" || cleared === "revoked"; + } + + // Only a confirmed hacker has a flower and a Ramadan choice. + const hacker = await hackerPayload( + tx, + target, + state.r === null ? null : state.r === 1, + ); + const metadata = roleMetadata(roles, hacker); + const signature = roleSignature(metadata); + + const before = participant && { + discordUserId: participant.discordUserId, + discordUsername: participant.discordUsername, + discordLinkedAt: participant.discordLinkedAt, + ramadanRoleOptIn: participant.ramadanRoleOptIn, + }; + const linkedAt = new Date(); + const link = { + discordUserId: discordId, + discordUsername: discordName, + linkedAt, + ...sealTokens(tokens, secret, state.u), + // Set once Discord has taken the roles. + rolesSig: null, + }; + try { + await tx.transaction(async (inner) => { + await inner + .insert(discordLinks) + .values({ userId: state.u, ...link }) + .onConflictDoUpdate({ target: discordLinks.userId, set: link }); + // A confirmed hacker's link is mirrored on their participant row, which + // carries the Ramadan choice and the roster columns. + if (hacker && participant) { + await inner + .update(hackathonParticipants) + .set({ + discordUserId: discordId, + discordUsername: discordName, + discordLinkedAt: linkedAt, + ramadanRoleOptIn: hacker.ramadan === 1, + updatedAt: linkedAt, + }) + .where( + and( + eq(hackathonParticipants.id, participant.id), + eq(hackathonParticipants.hackathonId, hackathon.id), + ), + ); + } + }); + } catch (error) { + if (isUniqueViolation(error)) return fail("already_linked"); + throw error; + } + + let putRes: Response | null = null; + try { + putRes = await putRoleConnection( + doFetch, + config, + accessToken, + displayName, + metadata, ); - } catch (error) { - if (isUniqueViolation(error)) return fail("already_linked"); - throw error; - } + } catch (error) { + // oxlint-disable-next-line no-console + console.warn(`[Discord link] publish did not reach Discord: ${safeMessage(error)}`); + } + if (!putRes?.ok) { + // Roll the link back: a stored link whose roles never reached Discord + // would read as done. When the old account was just cleared there is + // nothing to go back to, so nothing is linked. + await tx.transaction(async (inner) => { + if (priorLink && !clearedOldAccount) { + await inner + .update(discordLinks) + .set({ + discordUserId: priorLink.discordUserId, + discordUsername: priorLink.discordUsername, + linkedAt: priorLink.linkedAt, + accessTokenEnc: priorLink.accessTokenEnc, + refreshTokenEnc: priorLink.refreshTokenEnc, + tokenExpiresAt: priorLink.tokenExpiresAt, + rolesSig: priorLink.rolesSig, + }) + .where(eq(discordLinks.userId, state.u)); + } else { + await inner + .delete(discordLinks) + .where(eq(discordLinks.userId, state.u)); + } + if (hacker && participant && before) { + await inner + .update(hackathonParticipants) + .set( + clearedOldAccount + ? { + discordUserId: null, + discordUsername: null, + discordLinkedAt: null, + ramadanRoleOptIn: null, + } + : before, + ) + .where(eq(hackathonParticipants.id, participant.id)); + } + }); + if (!putRes) return fail("discord_error"); + const { status, retryAfter } = await refusal("role-connection", putRes); + return fail(failureFor(status), { retryAfter }); + } - const group = foodGroupByKey(groupKey); - const putRes = await doFetch( - `${API}/users/@me/applications/${config.clientId}/role-connection`, - { - method: "PUT", - headers: { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - platform_name: "Hacklytics", - platform_username: displayName, - metadata: { - accepted: 1, - food_group: group?.number ?? 0, - ramadan, - }, - }), - }, - ); - if (!putRes.ok) { - // Roll the link back: a stored link whose roles never reached Discord - // would read as done. - await db - .update(hackathonParticipants) - .set(before) - .where(eq(hackathonParticipants.id, participant.id)); - const { status, retryAfter } = await refusal("role-connection", putRes); - return fail(failureFor(status), { retryAfter }); - } + await tx + .update(discordLinks) + .set({ rolesSig: signature }) + .where(eq(discordLinks.userId, state.u)); - return { - ok: true, - then: state.t, - hackathon, - username: me.username, - }; + return { + ok: true, + then: state.t, + hackathon, + home, + username: discordName, + }; + }); } diff --git a/packages/api/src/services/discord/roles.ts b/packages/api/src/services/discord/roles.ts new file mode 100644 index 000000000..2e01450b5 --- /dev/null +++ b/packages/api/src/services/discord/roles.ts @@ -0,0 +1,301 @@ +// Who may link Discord, and what Discord is told about them. One typed model +// for the three roles instead of booleans repeated across the router, the link +// flow and the portal. See docs/features/discord.md. + +import type { DrizzleDB } from "@query/db"; +import { isExpiredAdmin } from "../../types/portal-context"; +import { foodGroupByKey } from "./config"; +import { ensureFoodGroup } from "./food-group"; + +/** One person can hold several of these at once. */ +export type DiscordRoles = { + /** Accepted and said "I'm coming" (or already checked in). */ + hacker: boolean; + /** An approved judge of the edition. */ + judge: boolean; + /** Event staff of the volunteer tier, while an edition is open or live. */ + volunteer: boolean; +}; + +export const NO_ROLES: DiscordRoles = { + hacker: false, + judge: false, + volunteer: false, +}; + +export const hasDiscordRole = (roles: DiscordRoles) => + roles.hacker || roles.judge || roles.volunteer; + +/** Accepted: seated, whether or not they have said they are coming. */ +export const isAcceptedHacker = (status: string | null | undefined) => + status === "approved" || status === "checked_in"; + +/** + * A hacker earns the Discord step by answering "I'm coming" on the hackathon + * Overview. Being accepted alone is not enough. Checked in counts without the + * answer: they are in the building. + */ +export const isConfirmedHacker = (p: { + registrationStatus: string | null | undefined; + attendanceConfirmedAt: Date | null | undefined; +}) => + p.registrationStatus === "checked_in" || + (p.registrationStatus === "approved" && !!p.attendanceConfirmedAt); + +/** + * Volunteers are org-wide staff, not tied to one edition, so they qualify for + * any edition that is open or live: registration has opened and the event is + * not over. Not a draft, an announcement, a finished or a cancelled edition. + */ +export const VOLUNTEER_EDITION_STATUSES = [ + "open", + "closed", + "in_progress", +] as const; + +const isVolunteerEdition = (status: string) => + (VOLUNTEER_EDITION_STATUSES as readonly string[]).includes(status); + +/** The roles one person holds in one edition, from what the database says. */ +export function rolesFor(input: { + participant: { + registrationStatus: string | null | undefined; + attendanceConfirmedAt: Date | null | undefined; + } | null; + judge: boolean; + volunteer: boolean; + hackathonStatus: string; +}): DiscordRoles { + return { + hacker: !!input.participant && isConfirmedHacker(input.participant), + judge: input.judge, + volunteer: input.volunteer && isVolunteerEdition(input.hackathonStatus), + }; +} + +/** What the Linked Roles PUT carries: always all five registered fields. */ +export type RoleMetadata = { + accepted: 0 | 1; + food_group: number; + ramadan: 0 | 1; + judge: 0 | 1; + volunteer: 0 | 1; +}; + +/** Every field cleared: what Discord is told for someone who holds no role. */ +export const ZERO_METADATA: RoleMetadata = { + accepted: 0, + food_group: 0, + ramadan: 0, + judge: 0, + volunteer: 0, +}; + +/** + * What the Linked Roles PUT carries. `accepted` is 1 only for confirmed + * hackers; `food_group` and `ramadan` are a hacker's alone and 0 otherwise (no + * flower role matches 0). `judge` and `volunteer` are 1 or 0. All five are + * always sent, so a role that no longer applies is overwritten, not left behind. + */ +export function roleMetadata( + roles: DiscordRoles, + hacker: { foodGroup: number; ramadan: 0 | 1 } | null, +): RoleMetadata { + const asHacker = roles.hacker && hacker ? hacker : null; + return { + accepted: roles.hacker ? 1 : 0, + food_group: asHacker?.foodGroup ?? 0, + ramadan: asHacker?.ramadan ?? 0, + judge: roles.judge ? 1 : 0, + volunteer: roles.volunteer ? 1 : 0, + }; +} + +/** + * The metadata last published, as a short string, kept on the link. It tells a + * sync whether anything changed, and lets the daily job find volunteers whose + * published `volunteer` is still 1 (the string ends in `v1`). + */ +export const roleSignature = (m: RoleMetadata) => + `a${m.accepted}f${m.food_group}r${m.ramadan}j${m.judge}v${m.volunteer}`; + +/** The Ramadan flag Discord receives: opted in AND fasting is "Yes". */ +export const ramadanFlag = (optIn: boolean, fasting: string | null | undefined) => + optIn && fasting === "Yes" ? 1 : 0; + +export type DiscordParticipant = { + id: string; + registrationStatus: string; + attendanceConfirmedAt: Date | null; + foodGroup: string | null; + ramadanFasting: string | null; + ramadanRoleOptIn: boolean | null; + discordUserId: string | null; + discordUsername: string | null; + discordLinkedAt: Date | null; +}; + +export type DiscordContext = { + hackathon: { id: string; name: string }; + participant: DiscordParticipant | null; + roles: DiscordRoles; +}; + +const PARTICIPANT_COLUMNS = { + id: true, + registrationStatus: true, + attendanceConfirmedAt: true, + foodGroup: true, + ramadanFasting: true, + ramadanRoleOptIn: true, + discordUserId: true, + discordUsername: true, + discordLinkedAt: true, +} as const; + +const HACKATHON_COLUMNS = { + id: true, + name: true, + status: true, + startDate: true, +} as const; + +type Edition = { id: string; name: string; status: string; startDate: Date }; + +/** An active, unexpired admin row of the volunteer tier. */ +async function isVolunteer(db: DrizzleDB, userId: string): Promise { + const admin = await db.query.admins.findFirst({ + where: { userId, isActive: true, role: "volunteer" }, + columns: { expiresAt: true }, + }); + return !!admin && !isExpiredAdmin(admin); +} + +/** + * Everything the Discord step knows about one person for one edition. With a + * hackathon id, that edition, even when they hold no role there (the portal + * still shows a hacker who has not confirmed). Without one, which is what + * Discord's Linked Roles verification URL sends, the newest edition that is + * not cancelled or over in which they hold a role. Null when there is none. + */ +export async function discordContext( + db: DrizzleDB, + userId: string, + hackathonId: string | null, +): Promise { + if (hackathonId) { + const hackathon = await db.query.hackathons.findFirst({ + where: { id: hackathonId }, + columns: HACKATHON_COLUMNS, + }); + if (!hackathon) return null; + const [participant, judge, volunteer] = await Promise.all([ + db.query.hackathonParticipants.findFirst({ + where: { hackathonId, userId }, + columns: PARTICIPANT_COLUMNS, + }), + db.query.judges.findFirst({ + where: { hackathonId, userId, isActive: true }, + columns: { id: true }, + }), + isVolunteer(db, userId), + ]); + return { + hackathon: { id: hackathon.id, name: hackathon.name }, + participant: participant ?? null, + roles: rolesFor({ + participant: participant ?? null, + judge: !!judge, + volunteer, + hackathonStatus: hackathon.status, + }), + }; + } + + const volunteer = await isVolunteer(db, userId); + const [participants, judgeRows, openEditions] = await Promise.all([ + db.query.hackathonParticipants.findMany({ + where: { userId }, + columns: PARTICIPANT_COLUMNS, + with: { hackathon: { columns: HACKATHON_COLUMNS } }, + }), + db.query.judges.findMany({ + where: { userId, isActive: true }, + columns: { id: true }, + with: { hackathon: { columns: HACKATHON_COLUMNS } }, + }), + volunteer + ? db.query.hackathons.findMany({ + where: { status: { in: [...VOLUNTEER_EDITION_STATUSES] } }, + columns: HACKATHON_COLUMNS, + }) + : Promise.resolve([] as Edition[]), + ]); + + const editions = new Map< + string, + { edition: Edition; participant: DiscordParticipant | null; judge: boolean } + >(); + const entry = (edition: Edition) => { + let held = editions.get(edition.id); + if (!held) { + held = { edition, participant: null, judge: false }; + editions.set(edition.id, held); + } + return held; + }; + for (const { hackathon, ...participant } of participants) { + if (hackathon) entry(hackathon).participant = participant; + } + for (const { hackathon } of judgeRows) { + if (hackathon) entry(hackathon).judge = true; + } + for (const edition of openEditions) entry(edition); + + return ( + [...editions.values()] + .filter( + ({ edition }) => + edition.status !== "cancelled" && edition.status !== "completed", + ) + .map(({ edition, participant, judge }) => ({ + start: new Date(edition.startDate).getTime(), + context: { + hackathon: { id: edition.id, name: edition.name }, + participant, + roles: rolesFor({ + participant, + judge, + volunteer, + hackathonStatus: edition.status, + }), + } satisfies DiscordContext, + })) + .filter(({ context }) => hasDiscordRole(context.roles)) + .sort((a, b) => b.start - a.start)[0]?.context ?? null + ); +} + +/** + * A confirmed hacker's flower number and Ramadan flag, or null for anyone else. + * `ramadanOptIn` is the choice made in this flow; null keeps the stored one. + * The flower is assigned first if they have none, so the metadata always has one. + */ +export async function hackerPayload( + db: DrizzleDB, + context: DiscordContext, + ramadanOptIn: boolean | null, +): Promise<{ foodGroup: number; ramadan: 0 | 1 } | null> { + const { participant, roles, hackathon } = context; + if (!roles.hacker || !participant) return null; + const group = + foodGroupByKey(participant.foodGroup) ?? + foodGroupByKey(await ensureFoodGroup(db, hackathon.id, participant.id)); + return { + foodGroup: group?.number ?? 0, + ramadan: ramadanFlag( + ramadanOptIn ?? participant.ramadanRoleOptIn ?? false, + participant.ramadanFasting, + ), + }; +} diff --git a/packages/api/src/services/discord/sync.ts b/packages/api/src/services/discord/sync.ts new file mode 100644 index 000000000..18a814a77 --- /dev/null +++ b/packages/api/src/services/discord/sync.ts @@ -0,0 +1,395 @@ +// Keeping what Discord holds in step with what the site knows. Roles come from +// Linked Roles metadata, which only the person's own token can change, so the +// token kept at link time (tokens.ts) is what lets a removed judge, an ended +// volunteer term, a withdrawn hacker or an unlink actually take the role back. +// A link made before tokens were kept has none, and cannot be revoked here. + +import { and, eq, inArray, isNotNull, isNull, like, lte, or, sql } from "drizzle-orm"; +import { admins, discordLinks, hackathonParticipants } from "@query/db"; +import type { DrizzleDB } from "@query/db"; +import { putRoleConnection, refusal, safeMessage } from "./api"; +import { discordConfig, discordTokenSecret } from "./config"; +import { + discordContext, + hackerPayload, + hasDiscordRole, + roleMetadata, + roleSignature, + ZERO_METADATA, +} from "./roles"; +import type { RoleMetadata } from "./roles"; +import { accessTokenFor } from "./tokens"; +import type { LinkRow, SyncDeps } from "./tokens"; + +export type SyncOptions = { + /** Defaults to the app's Discord settings; null means the feature is off. */ + config?: SyncDeps["config"] | null; + /** Defaults to AUTH_SECRET. */ + secret?: string | null; + fetchImpl?: typeof fetch; +}; + +export type SyncResult = + | "synced" + | "unchanged" + | "off" + | "unlinked" + | "no_token" + | "revoked" + | "failed"; + +/** + * What one request syncs inline for a batch change: at most this many people, + * and no longer than the budget. Whoever is left is already marked pending, and + * the daily job picks them up. + */ +export const SYNC_BATCH = 100; +export const INLINE_BUDGET_MS = 15_000; +/** + * What one run of the daily job takes: at most this many people, and no longer + * than the budget (the route it runs in has other work and a caller that gives + * up). What it does not reach is still pending, and the next day's run is first + * to it. + */ +export const SWEEP_BATCH = 15; +export const SWEEP_BUDGET_MS = 20_000; + +/** + * What `roles_sig` holds for a link whose tokens are missing or will not open + * (made before tokens were kept, or sealed under a secret since changed). No + * sync can serve it, so it is not pending: it stays out of the daily job + * rather than being tried, and taking a slot, every day. Linking again repairs + * it. + */ +export const UNREACHABLE_SIG = "unreachable"; + +export type SweepOptions = SyncOptions & { + /** People per run. */ + limit?: number; + /** Wall-clock time per run. */ + budgetMs?: number; +}; + +function depsFrom(options: SyncOptions): SyncDeps | null { + const config = + options.config === undefined ? discordConfig() : options.config; + const secret = + options.secret === undefined ? discordTokenSecret() : options.secret; + if (!config || !secret) return null; + return { config, secret, doFetch: options.fetchImpl ?? fetch }; +} + +/** + * Runs `fn` holding this person's Discord lock, so a sync, a link and an unlink + * for one person take turns. Without it they interleave: a refresh token is + * single use, so two runs that both refresh leave one with `invalid_grant` and + * the link dropped; and two reads of "what Discord has" can be written back in + * the wrong order, or a sync that read the old link can publish roles onto an + * account an unlink has just cleared. + * + * It is a transaction-scoped advisory lock, held on the transaction `fn` is + * given for the whole of derive, refresh, publish and write-back, across the + * Discord calls (each has an 8 second timeout). Everything inside must use that + * `tx`, never the pool: another connection that asked for the same lock would + * wait on this one forever. Calls made through `tx` that open a transaction of + * their own become savepoints. + * + * Network failures are caught at the call, so an unreachable Discord does not + * roll the transaction back: a rotated token pair stored a moment earlier stays + * stored. + */ +export async function withDiscordLock( + db: DrizzleDB, + userId: string, + fn: (tx: DrizzleDB) => Promise, +): Promise { + return db.transaction(async (tx) => { + // A holder that hangs must not hold everyone behind it for ever. + await tx.execute(sql`select set_config('lock_timeout', '30s', true)`); + await tx.execute( + sql`select pg_advisory_xact_lock(hashtextextended(${`discord:${userId}`}, 0))`, + ); + return fn(tx as unknown as DrizzleDB); + }); +} + +/** + * Puts the metadata on Discord with the link's token. A refused access token + * is refreshed once and tried again. + */ +async function publish( + db: DrizzleDB, + link: LinkRow, + deps: SyncDeps, + metadata: RoleMetadata, +): Promise<"published" | "no_token" | "revoked" | "failed"> { + let row = link; + for (const force of [false, true]) { + const token = await accessTokenFor(db, row, deps, force); + if (!token.ok) return token.reason; + row = token.row; + let res: Response; + try { + res = await putRoleConnection( + deps.doFetch, + deps.config, + token.accessToken, + row.discordUsername, + metadata, + ); + } catch (error) { + // oxlint-disable-next-line no-console + console.warn(`[Discord sync] publish did not reach Discord: ${safeMessage(error)}`); + return "failed"; + } + if (res.ok) return "published"; + const { status } = await refusal("role-connection", res); + if (status !== 401 || force) return "failed"; + } + return "failed"; +} + +/** + * Clears every role the link published. Used before the link is unlinked or + * replaced by another Discord account. `no_token` and `revoked` mean there is + * nothing more this site can do for that account; `failed` means it could not + * be reached and the caller should not go on. + */ +export async function zeroDiscordRoles( + db: DrizzleDB, + link: LinkRow, + options: SyncOptions = {}, +): Promise<"cleared" | "off" | "no_token" | "revoked" | "failed"> { + const deps = depsFrom(options); + if (!deps) return "off"; + if (link.rolesSig === roleSignature(ZERO_METADATA)) return "cleared"; + const result = await publish(db, link, deps, ZERO_METADATA); + return result === "published" ? "cleared" : result; +} + +async function syncOne( + db: DrizzleDB, + userId: string, + deps: SyncDeps, +): Promise { + const [link] = await db + .select() + .from(discordLinks) + .where(eq(discordLinks.userId, userId)) + .limit(1); + if (!link) return "unlinked"; + + // The same edition the link flow would pick, so a sync and a fresh link + // publish the same thing. + const context = await discordContext(db, userId, null); + const metadata = + context && hasDiscordRole(context.roles) + ? roleMetadata(context.roles, await hackerPayload(db, context, null)) + : ZERO_METADATA; + const signature = roleSignature(metadata); + if (link.rolesSig === signature) return "unchanged"; + + const result = await publish(db, link, deps, metadata); + if (result === "revoked") return result; + // What the link now says Discord has. A sync that did not land leaves it + // pending (null), so the daily job tries again; nothing reads as done that + // is not. A link with no usable token is set aside instead: trying it again + // cannot help. + await db + .update(discordLinks) + .set({ + rolesSig: + result === "published" + ? signature + : result === "no_token" + ? UNREACHABLE_SIG + : null, + syncAttemptedAt: new Date(), + }) + .where( + and( + eq(discordLinks.userId, userId), + eq(discordLinks.discordUserId, link.discordUserId), + ), + ); + return result === "published" ? "synced" : result; +} + +/** + * Marks people's links as owing a sync. Called inside the transaction of the + * change that can revoke their roles, so the debt exists whenever the change + * does, however many people it touched and whether or not this request gets to + * Discord. People with no link are untouched. + */ +export async function markDiscordRolesPending( + db: DrizzleDB, + userIds: readonly string[], +): Promise { + if (userIds.length === 0) return; + await db + .update(discordLinks) + .set({ rolesSig: null }) + .where(inArray(discordLinks.userId, [...new Set(userIds)])); +} + +/** + * Re-derives what the person holds now and publishes it, or all zeros when + * they hold nothing. Call it after the change that could revoke or grant a + * role has committed. Never throws: the change has already happened, and the + * only record that Discord was not updated is the log, the same as + * autoAssignFoodGroups. + */ +export async function syncDiscordRoles( + db: DrizzleDB, + userId: string, + options: SyncOptions = {}, +): Promise { + const deps = depsFrom(options); + if (!deps) return "off"; + try { + return await withDiscordLock(db, userId, (tx) => syncOne(tx, userId, deps)); + } catch (error) { + // Deliberate operational logging: the only record that Discord kept a role + // it should have lost. + // oxlint-disable-next-line no-console + console.error(`[Discord sync] failed for user ${userId}: ${safeMessage(error)}`); + // The locked turn rolled back, so say a sync is still owed. + await markDiscordRolesPending(db, [userId]).catch(() => undefined); + return "failed"; + } +} + +/** + * The same for many people (a batch status change, a ban). Only people with a + * link are touched, a few at a time, at most SYNC_BATCH of them and for no + * longer than the budget. The change that called this has already marked every + * one of them pending, so whoever is not reached is left to the daily job. + */ +export async function syncDiscordRolesFor( + db: DrizzleDB, + userIds: readonly string[], + options: SyncOptions & { budgetMs?: number } = {}, +): Promise { + if (!depsFrom(options) || userIds.length === 0) return; + const stopAt = Date.now() + (options.budgetMs ?? INLINE_BUDGET_MS); + try { + const linked = await db + .select({ userId: discordLinks.userId }) + .from(discordLinks) + .where(inArray(discordLinks.userId, [...new Set(userIds)])) + .limit(SYNC_BATCH); + for (let i = 0; i < linked.length && Date.now() < stopAt; i += 5) { + await Promise.all( + linked + .slice(i, i + 5) + .map(({ userId }) => syncDiscordRoles(db, userId, options)), + ); + } + } catch (error) { + // oxlint-disable-next-line no-console + console.error(`[Discord sync] batch failed: ${safeMessage(error)}`); + } +} + +/** + * The daily sweep. Two kinds of link are owed a sync: those marked pending + * (a change that could revoke their roles that this site has not yet told + * Discord about, because the request ran out of time or Discord was down) and + * volunteers whose published `volunteer` is still 1 although their term has + * expired or been switched off, which has no event of its own. Capped, and + * the link tried longest ago goes first, so one that keeps failing cannot hold + * the rest. + */ +export async function syncExpiredDiscordRoles( + db: DrizzleDB, + options: SweepOptions = {}, +): Promise<{ checked: number; synced: number }> { + if (!depsFrom(options)) return { checked: 0, synced: 0 }; + try { + const rows = await db + .select({ userId: discordLinks.userId }) + .from(discordLinks) + .leftJoin(admins, eq(admins.userId, discordLinks.userId)) + .where( + or( + and( + isNull(discordLinks.rolesSig), + or( + isNotNull(discordLinks.refreshTokenEnc), + isNotNull(discordLinks.accessTokenEnc), + ), + ), + and( + eq(admins.role, "volunteer"), + or(lte(admins.expiresAt, new Date()), eq(admins.isActive, false)), + like(discordLinks.rolesSig, "%v1"), + ), + ), + ) + .orderBy(sql`${discordLinks.syncAttemptedAt} asc nulls first`) + .limit(options.limit ?? SWEEP_BATCH); + const stopAt = Date.now() + (options.budgetMs ?? SWEEP_BUDGET_MS); + let checked = 0; + let synced = 0; + for (const { userId } of rows) { + if (Date.now() >= stopAt) break; + checked++; + if ((await syncDiscordRoles(db, userId, options)) === "synced") synced++; + } + return { checked, synced }; + } catch (error) { + // oxlint-disable-next-line no-console + console.error(`[Discord sync] sweep failed: ${safeMessage(error)}`); + return { checked: 0, synced: 0 }; + } +} + +/** + * Unlinks: clears the roles on Discord with the stored token, then forgets the + * link (and the copy on this edition's registration). `failed` means Discord + * could not be reached to clear them, and nothing was deleted, so the person + * is not left holding roles the site can no longer take back. A link with no + * stored token is deleted regardless: there is nothing to clear it with. + */ +export async function unlinkDiscord( + db: DrizzleDB, + userId: string, + hackathonId: string, + options: SyncOptions = {}, +): Promise<"unlinked" | "failed"> { + try { + // Clearing the roles and forgetting the link are one turn: a sync that + // started before cannot publish onto the account after it is cleared. + return await withDiscordLock(db, userId, async (tx) => { + const [link] = await tx + .select() + .from(discordLinks) + .where(eq(discordLinks.userId, userId)) + .limit(1); + if (link && (await zeroDiscordRoles(tx, link, options)) === "failed") { + return "failed" as const; + } + await tx + .update(hackathonParticipants) + .set({ + discordUserId: null, + discordUsername: null, + discordLinkedAt: null, + ramadanRoleOptIn: null, + updatedAt: new Date(), + }) + .where( + and( + eq(hackathonParticipants.hackathonId, hackathonId), + eq(hackathonParticipants.userId, userId), + ), + ); + await tx.delete(discordLinks).where(eq(discordLinks.userId, userId)); + return "unlinked" as const; + }); + } catch (error) { + // oxlint-disable-next-line no-console + console.error(`[Discord sync] unlink failed for user ${userId}: ${safeMessage(error)}`); + return "failed"; + } +} diff --git a/packages/api/src/services/discord/token-crypto.ts b/packages/api/src/services/discord/token-crypto.ts new file mode 100644 index 000000000..a812c9d3c --- /dev/null +++ b/packages/api/src/services/discord/token-crypto.ts @@ -0,0 +1,69 @@ +import { + createCipheriv, + createDecipheriv, + hkdfSync, + randomBytes, +} from "node:crypto"; + +// Discord OAuth tokens at rest. AES-256-GCM, with a key derived from AUTH_SECRET +// through HKDF under its own label, so no new secret is needed and the key is +// never the one that signs sessions or the OAuth state. Each value carries its +// own random IV, and the person's id is authenticated data, so a ciphertext +// moved to another person's row fails to open. Rotating AUTH_SECRET makes +// stored tokens unreadable, which leaves those links as unrevocable as ones +// made before tokens were stored. + +const INFO = "query/discord/token/v1"; +const VERSION = "v1"; + +const keyFrom = (secret: string) => + Buffer.from(hkdfSync("sha256", secret, Buffer.alloc(0), INFO, 32)); + +const aadFor = (userId: string) => Buffer.from(`discord_link:${userId}`); + +/** `v1...`, base64url. */ +export function sealToken( + plain: string, + secret: string, + userId: string, +): string { + const iv = randomBytes(12); + const cipher = createCipheriv("aes-256-gcm", keyFrom(secret), iv, { + authTagLength: 16, + }); + cipher.setAAD(aadFor(userId)); + const ciphertext = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]); + return [VERSION, iv, ciphertext, cipher.getAuthTag()] + .map((part) => (typeof part === "string" ? part : part.toString("base64url"))) + .join("."); +} + +/** The plain token, or null when the value is malformed, tampered with, or sealed under another key or person. */ +export function openToken( + sealed: string | null | undefined, + secret: string, + userId: string, +): string | null { + if (!sealed) return null; + const [version, iv, ciphertext, tag, extra] = sealed.split("."); + if (version !== VERSION || !iv || !ciphertext || !tag || extra !== undefined) { + return null; + } + try { + // A fixed tag length, or a truncated tag would be accepted. + const decipher = createDecipheriv( + "aes-256-gcm", + keyFrom(secret), + Buffer.from(iv, "base64url"), + { authTagLength: 16 }, + ); + decipher.setAAD(aadFor(userId)); + decipher.setAuthTag(Buffer.from(tag, "base64url")); + return Buffer.concat([ + decipher.update(Buffer.from(ciphertext, "base64url")), + decipher.final(), + ]).toString("utf8"); + } catch { + return null; + } +} diff --git a/packages/api/src/services/discord/tokens.ts b/packages/api/src/services/discord/tokens.ts new file mode 100644 index 000000000..ff563499a --- /dev/null +++ b/packages/api/src/services/discord/tokens.ts @@ -0,0 +1,152 @@ +// The Discord tokens kept on a link, so a role can be taken back later. Only +// ever read here and in sync.ts; nothing returns them to a caller. + +import { and, eq } from "drizzle-orm"; +import { discordLinks, hackathonParticipants } from "@query/db"; +import type { DrizzleDB } from "@query/db"; +import { readTokens, refreshAccessToken, refusal, safeMessage } from "./api"; +import type { DiscordTokens } from "./api"; +import type { DiscordConfig } from "./config"; +import { openToken, sealToken } from "./token-crypto"; + +export type LinkRow = typeof discordLinks.$inferSelect; + +export type SyncDeps = { + config: DiscordConfig; + secret: string; + doFetch: typeof fetch; +}; + +/** A token is refreshed this long before it runs out. */ +const SKEW_MS = 60_000; + +/** The encrypted columns for a token set; all null when there is none. */ +export function sealTokens( + tokens: DiscordTokens | null, + secret: string, + userId: string, +) { + return { + accessTokenEnc: tokens ? sealToken(tokens.accessToken, secret, userId) : null, + refreshTokenEnc: tokens?.refreshToken + ? sealToken(tokens.refreshToken, secret, userId) + : null, + tokenExpiresAt: tokens?.expiresAt ?? null, + }; +} + +/** + * Forgets the link: the link row, and the copy on a registration. Used when + * Discord says the person withdrew the connection, so there is nothing left to + * keep up to date. + */ +export async function dropLink(db: DrizzleDB, row: LinkRow): Promise { + await db.transaction(async (tx) => { + await tx + .update(hackathonParticipants) + .set({ + discordUserId: null, + discordUsername: null, + discordLinkedAt: null, + ramadanRoleOptIn: null, + updatedAt: new Date(), + }) + .where( + and( + eq(hackathonParticipants.userId, row.userId), + eq(hackathonParticipants.discordUserId, row.discordUserId), + ), + ); + await tx + .delete(discordLinks) + .where( + and( + eq(discordLinks.userId, row.userId), + eq(discordLinks.discordUserId, row.discordUserId), + ), + ); + }); +} + +export type AccessToken = + | { ok: true; accessToken: string; row: LinkRow } + | { ok: false; reason: "no_token" | "revoked" | "failed" }; + +/** + * A working access token for the link, refreshing and storing the rotated + * pair when the stored one is near its end (or `force`d, because Discord + * refused it). `no_token` is a link with none stored, or none that opens: made + * before tokens were kept, or sealed under a secret since changed. `revoked` + * is Discord saying the person withdrew the connection; the link is dropped. + */ +export async function accessTokenFor( + db: DrizzleDB, + row: LinkRow, + deps: SyncDeps, + force = false, + retried = false, +): Promise { + const access = openToken(row.accessTokenEnc, deps.secret, row.userId); + if ( + !force && + access && + row.tokenExpiresAt && + row.tokenExpiresAt.getTime() - Date.now() > SKEW_MS + ) { + return { ok: true, accessToken: access, row }; + } + const refresh = openToken(row.refreshTokenEnc, deps.secret, row.userId); + if (!refresh) return { ok: false, reason: "no_token" }; + + // A network failure is a refresh that did not happen, not an error to throw: + // the caller may be inside a transaction that must still commit. + let res: Response; + try { + res = await refreshAccessToken(deps.doFetch, deps.config, refresh); + } catch (error) { + // oxlint-disable-next-line no-console + console.warn(`[Discord sync] refresh did not reach Discord: ${safeMessage(error)}`); + return { ok: false, reason: "failed" }; + } + if (!res.ok) { + const { status, error } = await refusal("refresh", res); + if (status === 400 && error === "invalid_grant") { + // A refresh token is single use: a run that got there first rotated it. + // Only a token nobody replaced is really dead. + const [latest] = await db + .select() + .from(discordLinks) + .where(eq(discordLinks.userId, row.userId)) + .limit(1); + if ( + !retried && + latest && + latest.discordUserId === row.discordUserId && + latest.refreshTokenEnc !== row.refreshTokenEnc + ) { + return accessTokenFor(db, latest, deps, force, true); + } + await dropLink(db, row); + return { ok: false, reason: "revoked" }; + } + return { ok: false, reason: "failed" }; + } + + const tokens = readTokens(await res.json().catch(() => ({}))); + if (!tokens) return { ok: false, reason: "failed" }; + const sealed = sealTokens( + { ...tokens, refreshToken: tokens.refreshToken ?? refresh }, + deps.secret, + row.userId, + ); + await db + .update(discordLinks) + .set(sealed) + .where( + and( + eq(discordLinks.userId, row.userId), + eq(discordLinks.discordUserId, row.discordUserId), + ), + ); + return { ok: true, accessToken: tokens.accessToken, row: { ...row, ...sealed } }; +} diff --git a/packages/auth/src/email.test.ts b/packages/auth/src/email.test.ts index 51191c7e6..e19fc51fa 100644 --- a/packages/auth/src/email.test.ts +++ b/packages/auth/src/email.test.ts @@ -12,7 +12,12 @@ vi.mock("nodemailer", () => ({ }, })); -const { sendAcceptanceEmail, sendApplicationReminderEmail } = await import("./email"); +const { + sendAcceptanceEmail, + sendApplicationReminderEmail, + sendJudgeAddedEmail, + sendJudgeApprovedEmail, +} = await import("./email"); describe("sendAcceptanceEmail", () => { beforeEach(() => { @@ -116,3 +121,41 @@ describe("sendApplicationReminderEmail", () => { expect(sent[0]?.html).not.toContain("hacklytics-wordmark.png"); }); }); + +describe("Discord in the acceptance and judge emails", () => { + beforeEach(() => { + sent.length = 0; + }); + + it("asks an accepted hacker to confirm before joining the Discord", async () => { + await sendAcceptanceEmail({ + email: "ada@example.com", + hackathonName: "Hacklytics: Digital Bloom", + host: "https://datasciencegt.org", + }); + expect(sent[0]?.text).toContain( + "Confirm you're coming in the Hackathon Hub, then join the Hacklytics Discord to get your flower role.", + ); + }); + + it("tells an approved or added judge the Discord is required, and points to the portal step", async () => { + await sendJudgeApprovedEmail({ + email: "judge@example.com", + hackathonName: "Hacklytics: Digital Bloom", + host: "https://datasciencegt.org", + }); + await sendJudgeAddedEmail({ + email: "judge@example.com", + hackathonName: "Hacklytics: Digital Bloom", + host: "https://datasciencegt.org", + }); + expect(sent).toHaveLength(2); + for (const message of sent) { + expect(message.text).toContain( + "Joining the Hacklytics Discord is required for judges. Schedules and room changes are posted there.", + ); + expect(message.text).toContain("Open the judge portal: https://datasciencegt.org/judge"); + expect(message.text).not.toContain("!"); + } + }); +}); diff --git a/packages/auth/src/email.ts b/packages/auth/src/email.ts index 10e72a9de..38a93749c 100644 --- a/packages/auth/src/email.ts +++ b/packages/auth/src/email.ts @@ -321,6 +321,7 @@ export async function sendJudgeApprovedEmail({ heading: "You're confirmed as a judge", paragraphs: [ `Your application to judge ${hackathonName} has been approved.`, + "Joining the Hacklytics Discord is required for judges. Schedules and room changes are posted there. Use the Join the Hacklytics Discord step in the judge portal.", "Club judges: sign in on your phone before you scan the code at your room or table, so your scores count under your account.", "On the day, scan the QR code at your judging room or table to take your seat, then score each project as it presents.", ], @@ -347,6 +348,7 @@ export async function sendJudgeAddedEmail({ heading: "You've been added as a judge", paragraphs: [ `An organizer added you as a judge for ${hackathonName}. There is nothing to apply for or wait on.`, + "Joining the Hacklytics Discord is required for judges. Schedules and room changes are posted there. Use the Join the Hacklytics Discord step in the judge portal.", "Sign in on your phone before you scan the code at your room or table, so your scores count under your account.", "On the day, scan the QR code at your judging room or table to take your seat, then score each project as it presents.", ], @@ -602,7 +604,7 @@ export async function sendAcceptanceEmail({ paragraphs: [ `Congratulations! You have been accepted to participate in ${hackathonName}.`, "Head over to the Hackathon Hub to view the event details, find a team, and get ready to build.", - "Join the Hacklytics Discord from the Hackathon Hub to get your flower role.", + "Confirm you're coming in the Hackathon Hub, then join the Hacklytics Discord to get your flower role.", ], ctaLabel: "Go to Hackathon Hub", ctaUrl: `${host}/hackathons`, diff --git a/packages/db/src/schemas/hackathons.ts b/packages/db/src/schemas/hackathons.ts index 55aa39212..8417c80bd 100644 --- a/packages/db/src/schemas/hackathons.ts +++ b/packages/db/src/schemas/hackathons.ts @@ -411,6 +411,47 @@ export const hackathonApplicationDrafts = pgTable( export type HackathonApplicationDraft = typeof hackathonApplicationDrafts.$inferSelect; +// The Discord account of someone who is not (or not only) a hacker. Judges and +// volunteers have no hackathon_participant row to hold the link, and the +// account is the person's, not an edition's, so it lives here, one row per +// user. A confirmed hacker's link is still mirrored on their participant row +// (it carries the Ramadan choice and the per-edition roster columns); the two +// are written together. The id and username are what Discord gave us. +// +// The token columns hold the OAuth tokens AES-256-GCM encrypted (see +// services/discord/token-crypto.ts), so a role can be taken back when a judge +// is removed, a volunteer's term ends or the person unlinks: with no token the +// site cannot change what Discord holds. They are null for a link made before +// they were stored, which cannot be revoked. `roles_sig` is the metadata last +// published ("a1f4r0j0v1"), so a sync that would change nothing sends nothing. +// Null means a sync is owed (a change that could revoke a role was made and +// Discord has not been told yet), and the daily job picks those up, oldest +// `sync_attempted_at` first. +export const discordLinks = pgTable( + "discord_link", + { + id: uuid("id").defaultRandom().primaryKey(), + userId: text("user_id") + .notNull() + .references(() => users.id, { onDelete: "cascade" }), + discordUserId: text("discord_user_id").notNull(), + discordUsername: text("discord_username").notNull(), + linkedAt: timestamp("linked_at", { withTimezone: true }).defaultNow().notNull(), + accessTokenEnc: text("access_token_enc"), + refreshTokenEnc: text("refresh_token_enc"), + tokenExpiresAt: timestamp("token_expires_at", { withTimezone: true }), + rolesSig: text("roles_sig"), + syncAttemptedAt: timestamp("sync_attempted_at", { withTimezone: true }), + }, + (table) => [ + // One Discord account per person; the first also makes the link upsert safe. + uniqueIndex("discord_link_user_idx").on(table.userId), + uniqueIndex("discord_link_discord_user_idx").on(table.discordUserId), + ], +); + +export type DiscordLink = typeof discordLinks.$inferSelect; + // Event scheduling for hackathons export const hackathonEvents = pgTable( "hackathon_event", diff --git a/sites/mainweb/app/(portal)/api/cron/application-reminders/route.test.ts b/sites/mainweb/app/(portal)/api/cron/application-reminders/route.test.ts index 27ff11b54..221d2b721 100644 --- a/sites/mainweb/app/(portal)/api/cron/application-reminders/route.test.ts +++ b/sites/mainweb/app/(portal)/api/cron/application-reminders/route.test.ts @@ -3,10 +3,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { POST } from "./route"; const run = vi.hoisted(() => vi.fn()); +const sweep = vi.hoisted(() => vi.fn()); vi.mock("@query/db", () => ({ db: { marker: "db" } })); vi.mock("@query/api/application-reminders", () => ({ sendApplicationReminders: run, })); +vi.mock("@query/api/discord", () => ({ syncExpiredDiscordRoles: sweep })); const SECRET = "s3cret-token-value"; @@ -27,6 +29,8 @@ describe("POST /api/cron/application-reminders", () => { beforeEach(() => { run.mockReset(); run.mockResolvedValue({ claimed: 3, sent: 2, failed: 1 }); + sweep.mockReset(); + sweep.mockResolvedValue({ checked: 2, synced: 1 }); }); afterEach(() => vi.unstubAllEnvs()); @@ -58,9 +62,32 @@ describe("POST /api/cron/application-reminders", () => { const res = await call({ authorization: `Bearer ${SECRET}` }); expect(res.status).toBe(200); expect(res.headers.get("cache-control")).toBe("no-store"); - expect(await res.json()).toEqual({ claimed: 3, sent: 2, failed: 1 }); + expect(await res.json()).toEqual({ + claimed: 3, + sent: 2, + failed: 1, + discord: { checked: 2, synced: 1 }, + }); expect(run).toHaveBeenCalledTimes(1); expect(run.mock.calls[0]?.[0]).toEqual({ marker: "db" }); + expect(sweep.mock.calls[0]?.[0]).toEqual({ marker: "db" }); + }); + + it("still sweeps the Discord roles when the reminders fail", async () => { + vi.stubEnv("CRON_SECRET", SECRET); + const log = vi.spyOn(console, "error").mockImplementation(() => undefined); + run.mockRejectedValue(new Error("mail down")); + const res = await call({ authorization: `Bearer ${SECRET}` }); + expect(res.status).toBe(500); + expect(sweep).toHaveBeenCalledTimes(1); + log.mockRestore(); + }); + + it("does not run either job without a good token", async () => { + vi.stubEnv("CRON_SECRET", SECRET); + await call({ authorization: "Bearer wrong" }); + expect(run).not.toHaveBeenCalled(); + expect(sweep).not.toHaveBeenCalled(); }); it("answers 500 without the error text when a run fails", async () => { diff --git a/sites/mainweb/app/(portal)/api/cron/application-reminders/route.ts b/sites/mainweb/app/(portal)/api/cron/application-reminders/route.ts index ce25bf26c..bda29bd76 100644 --- a/sites/mainweb/app/(portal)/api/cron/application-reminders/route.ts +++ b/sites/mainweb/app/(portal)/api/cron/application-reminders/route.ts @@ -3,6 +3,7 @@ import type { NextRequest } from "next/server"; import { NextResponse } from "next/server"; import { sendApplicationReminders } from "@query/api/application-reminders"; +import { syncExpiredDiscordRoles } from "@query/api/discord"; import { rateLimitShared, resolveClientIp, @@ -10,9 +11,11 @@ import { import { db } from "@query/db"; /** - * The daily nudge to finish an application. App Hosting has no scheduler, so - * Cloud Scheduler (set up separately, docs/features/hackathons.md) posts here - * with the shared secret. + * The daily nudge to finish an application, and the daily sweep that takes the + * Discord volunteer role back from volunteers whose term has run out, which + * has no event of its own. App Hosting has no scheduler, so Cloud Scheduler + * (set up separately, docs/features/hackathons.md) posts here with the shared + * secret. * * Node runtime and never cached: every call has to do the work. * @@ -72,15 +75,29 @@ export async function POST(req: NextRequest) { ); } + // Both jobs run whatever the other does. The sweep never throws, takes at + // most 15 people and gives up after 20 seconds, so it cannot hold up the + // reminders or push a run past Scheduler's deadline; what it does not reach + // is picked up the next day. + // + // A Scheduler retry, or a run that overlaps the last, cannot mail a reminder + // twice: sendApplicationReminders stamps each draft as taken in one UPDATE + // before anything is sent (so a crash loses a reminder, never doubles one), + // and a draft already stamped is not claimed again. The sweep is safe to + // overlap too: each person's Discord work takes a per-person lock. + let run; try { - const run = await sendApplicationReminders(db); - return NextResponse.json(run, { headers: noStore }); + run = await sendApplicationReminders(db); } catch (error) { // Logged here, not returned: the caller only needs to know it failed. console.error("[application-reminders] run failed:", error); + } + const discord = await syncExpiredDiscordRoles(db); + if (!run) { return NextResponse.json( { error: "Run failed" }, { status: 500, headers: noStore }, ); } + return NextResponse.json({ ...run, discord }, { headers: noStore }); } diff --git a/sites/mainweb/app/(portal)/api/discord/callback/route.ts b/sites/mainweb/app/(portal)/api/discord/callback/route.ts index 7f9b7e0e8..f0d9b18aa 100644 --- a/sites/mainweb/app/(portal)/api/discord/callback/route.ts +++ b/sites/mainweb/app/(portal)/api/discord/callback/route.ts @@ -18,8 +18,8 @@ export const dynamic = "force-dynamic"; /** * Discord sends the user back here with ?code=&state=. Checks the signed * state and the signed-in user, then links. On success it goes to the server - * invite (first join) or the portal; on any failure back to the hackathon page - * with ?discord=error&reason=. + * invite (first join) or the portal; on any failure back to the page the role's + * card lives on with ?discord=error&reason=. */ export async function GET(request: NextRequest) { const config = discordConfig(); @@ -53,6 +53,7 @@ export async function GET(request: NextRequest) { result = await completeLink({ db: db as DrizzleDB, config, + secret, state, code, redirectUri: redirectUri(), @@ -64,14 +65,14 @@ export async function GET(request: NextRequest) { if (!result.ok) { const extra: Record = {}; if (result.retryAfter) extra.retry = String(result.retryAfter); - return backToPortal(result.hackathon ?? null, { - discord: "error", - reason: result.reason, - ...extra, - }); + return backToPortal( + result.hackathon ?? null, + { discord: "error", reason: result.reason, ...extra }, + result.home, + ); } if (result.then === "invite") { return NextResponse.redirect(config.inviteUrl); } - return backToPortal(result.hackathon, { discord: "linked" }); + return backToPortal(result.hackathon, { discord: "linked" }, result.home); } diff --git a/sites/mainweb/app/(portal)/api/discord/connect/route.ts b/sites/mainweb/app/(portal)/api/discord/connect/route.ts index 44a08742f..06f7920a6 100644 --- a/sites/mainweb/app/(portal)/api/discord/connect/route.ts +++ b/sites/mainweb/app/(portal)/api/discord/connect/route.ts @@ -25,7 +25,8 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** * Starts the Discord link. Also the "Linked Roles Verification URL" in the * Discord developer portal, which sends no query: the edition then defaults to - * the live one the signed-in user is accepted to. + * the newest live one in which the signed-in user holds a role (a hacker who + * confirmed they are coming, an approved judge, or a volunteer). * * ?hackathon=ID optional * ?ramadan=1|0 optional; absent keeps the stored choice @@ -64,7 +65,7 @@ export async function GET(request: NextRequest) { userId, hackathonId, ); - if (!target?.hackathon) { + if (!target) { return backToPortal(null, { discord: "error", reason: "not_accepted" }); } diff --git a/sites/mainweb/app/(portal)/hackathons/[id]/HackathonDetailPage.tsx b/sites/mainweb/app/(portal)/hackathons/[id]/HackathonDetailPage.tsx index f508d1ada..d709a881a 100644 --- a/sites/mainweb/app/(portal)/hackathons/[id]/HackathonDetailPage.tsx +++ b/sites/mainweb/app/(portal)/hackathons/[id]/HackathonDetailPage.tsx @@ -279,7 +279,7 @@ export default function HackathonDetailPage() { // wrapper only re-points the colour and font tokens, so every other // hackathon is untouched. const bloom = isHacklyticsName(hackathon.name); - const foodGroup = discord.data?.eligible ? discord.data.foodGroup : null; + const foodGroup = discord.data?.foodGroup ?? null; const content = (
diff --git a/sites/mainweb/app/(portal)/judge/JudgePage.tsx b/sites/mainweb/app/(portal)/judge/JudgePage.tsx index e0788a266..8df043118 100644 --- a/sites/mainweb/app/(portal)/judge/JudgePage.tsx +++ b/sites/mainweb/app/(portal)/judge/JudgePage.tsx @@ -12,6 +12,7 @@ import { FormChipSelect } from "@query/ui/FormChipSelect"; import { useIsClient } from "@/lib/use-is-client"; import { usePortalContext } from "@/lib/use-portal-context"; import { LoadingScreen } from "@/components/portal/LoadingScreen"; +import { DiscordCard } from "@/components/hackathon/DiscordCard"; import { body, btnSecondary, @@ -165,6 +166,12 @@ export default function JudgePage() {

+ {/* The card shows itself only to an approved judge, for the newest live + edition; empty, the wrapper and its rule are hidden too. */} +
+ +
+ {judging.length > 0 && (

You are judging

diff --git a/sites/mainweb/app/(portal)/scan/ScanPage.tsx b/sites/mainweb/app/(portal)/scan/ScanPage.tsx index 62820b17a..d6805b228 100644 --- a/sites/mainweb/app/(portal)/scan/ScanPage.tsx +++ b/sites/mainweb/app/(portal)/scan/ScanPage.tsx @@ -14,6 +14,7 @@ import { pageTitle, } from "@query/ui/classes"; import { ScanAccess } from "@/components/portal/ScanAccess"; +import { DiscordCard } from "@/components/hackathon/DiscordCard"; // Only scanners use the desk, so the page ships without it. It starts loading // as soon as the role is known, alongside the hackathon list it waits on. @@ -62,6 +63,11 @@ export default function ScanPage() {

Check-in desk

+ {/* The card shows itself only to volunteers; empty, the wrapper hides. */} +
+ +
+ {showPicker && (