diff --git a/README.md b/README.md index 149804c..9a6b85b 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,9 @@ payments in [docs/payments.md](docs/payments.md). ## What works - **Accounts** (Better Auth): sign-up with email, username and password; sign-in by username. The first account is - an admin; roles user, moderator, admin. Registration open or closed (new accounts wait for a moderator's - approval): an admin's setting in the console, defaulting to the API's `REGISTRATION`. + an admin; roles user, moderator, admin. Registration open, closed (new accounts wait for a moderator's + approval) or locked (for staging: Discord sign-ins wait for approval too, and only approved accounts sign in to + T5DE's other sites): an admin's setting in the console, defaulting to the API's `REGISTRATION`. - **Discord sign-in** (when `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set; Discord redirects to `/api/auth/callback/discord`): the first time it makes a basic account (Discord's verified email, no username or password) for T5DE's other sites, such as Music (docs/music.md); it finishes setting up diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index ee4ab62..d37d209 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -1161,7 +1161,9 @@ export function createApp({ const [taken] = await db.select({ id: user.id }).from(user).where(sql`lower(${user.username}) = lower(${name})`); if (taken) throw new Problem(409, "username_taken", "That username is taken. Try another."); const hash = await (await auth.$context).password.hash(body.password); - const approved = (await settings.registration()) === "open"; + // Locked: a moderator has already approved this person (or they're still waiting), so finishing changes nothing. + const registration = await settings.registration(); + const approved = registration === "open" || (registration === "locked" && me.approved === true); let updated: Person | undefined; try { updated = await db.transaction(async (tx) => { @@ -3597,7 +3599,7 @@ export function createApp({ query: t.Object({ q: t.Optional(t.String({ maxLength: 64 })), waiting: t.Optional(t.BooleanString()) }), }, ) - // Accounts waiting for approval (registration closed): approve, or decline (the account is deleted). + // Accounts waiting for approval (registration closed or locked): approve, or decline (the account is deleted). .post( "/console/people/:id/approve", async ({ me, params }) => { @@ -3632,7 +3634,7 @@ export function createApp({ }, { moderator: true, - body: t.Object({ registration: t.Union([t.Literal("open"), t.Literal("closed")]) }), + body: t.Object({ registration: t.Union([t.Literal("open"), t.Literal("closed"), t.Literal("locked")]) }), }, ) .get( diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts index ec96f8d..4c10d59 100644 --- a/apps/api/src/auth.ts +++ b/apps/api/src/auth.ts @@ -19,7 +19,8 @@ export type AuthConfig = { secret: string; /** Rate limits on sign-up, sign-in and the rest (on unless false: tests turn them off). */ rateLimit?: boolean; - /** Whether new accounts wait for approval (default: the hub's settings, with no environment defaults). */ + /** Whether new accounts wait for approval, and whether unapproved ones may sign in to other sites (default: the + * hub's settings, with no environment defaults). */ settings?: Settings; /** Discord sign-in (an application at discord.com/developers, redirecting to API_URL/api/auth/callback/discord); * off without it. */ @@ -145,10 +146,10 @@ export function createAuth(db: Database, config: AuthConfig) { create: { before: async (u, ctx) => { // Made by signing in with Discord (the OAuth callback): a basic account. It can use T5DE's other sites - // at once; the hub's features wait until it finishes setting up (and then for approval, if registration - // is closed). + // at once (unless registration is locked: then it waits for approval first); the hub's features wait + // until it finishes setting up (and then for approval, if registration is closed). if (ctx?.path?.startsWith("/callback/")) - return { data: { ...u, role: "user", approved: true, kind: "basic" } }; + return { data: { ...u, role: "user", approved: (await settings.registration()) !== "locked", kind: "basic" } }; // The first member runs the hub; with registration closed, the others wait for approval. const [row] = await db.select({ n: count() }).from(schema.user).where(eq(schema.user.kind, "member")); const first = (row?.n ?? 0) === 0; @@ -181,6 +182,14 @@ export function createAuth(db: Database, config: AuthConfig) { oauthProvider({ loginPage: `${config.webURL}/signin`, consentPage: `${config.webURL}/consent`, + // With registration locked (staging), only approved accounts sign in to T5DE's other sites: anyone else is + // sent to the website, which says they're waiting for approval, and no code is issued. Checked again on + // every authorize request, including /oauth2/continue, so there's no way past it but approval. + postLogin: { + page: `${config.webURL}/`, + consentReferenceId: () => undefined, + shouldRedirect: async ({ user }) => user.approved !== true && (await settings.registration()) === "locked", + }, scopes: [...oauthScopes], cachedTrustedClients: new Set((config.clients ?? []).map((c) => c.clientId)), storeClientSecret: { hash: hashSecret, verify: verifySecret }, diff --git a/apps/api/src/settings.ts b/apps/api/src/settings.ts index 243f8a6..5edfaf6 100644 --- a/apps/api/src/settings.ts +++ b/apps/api/src/settings.ts @@ -4,9 +4,13 @@ import { eq, schema, type Database } from "@t5de/db"; const { hubSetting } = schema; -/** Open: new accounts can use the hub at once. Closed: they can sign in, and wait for a moderator's approval. */ -export type Registration = "open" | "closed"; -export const registrations: readonly Registration[] = ["open", "closed"]; +/** + * Open: new accounts can use the hub at once. Closed: they can sign in, and wait for a moderator's approval (accounts + * from Discord sign-in can still use T5DE's other sites at once). Locked, for staging: every new account waits for + * approval, Discord ones too, and only approved accounts sign in to T5DE's other sites (auth.ts, postLogin). + */ +export type Registration = "open" | "closed" | "locked"; +export const registrations: readonly Registration[] = ["open", "closed", "locked"]; export class Settings { constructor( @@ -17,7 +21,7 @@ export class Settings { async registration(): Promise { const [row] = await this.db.select().from(hubSetting).where(eq(hubSetting.key, "registration")); const value = row?.value ?? this.defaults.registration; - return value === "closed" ? "closed" : "open"; + return value === "closed" || value === "locked" ? value : "open"; } async setRegistration(value: Registration) { diff --git a/apps/api/test/discord.test.ts b/apps/api/test/discord.test.ts index a0ad4bf..fa5ac0d 100644 --- a/apps/api/test/discord.test.ts +++ b/apps/api/test/discord.test.ts @@ -2,7 +2,7 @@ // verified email only, and never links by matching email; a basic account finishes setting up with a username and // password; a member links Discord from their own session. Discord itself is stood in for below. import { afterAll, beforeAll, expect, test } from "bun:test"; -import { openDatabase, type Database } from "@t5de/db"; +import { eq, openDatabase, schema, type Database } from "@t5de/db"; import { createApp } from "../src/app"; import { createAuth } from "../src/auth"; import { ImvuClient } from "../src/imvu"; @@ -203,3 +203,22 @@ test("a member links Discord from their own session; a Discord account already i expect(refused.searchParams.get("error")).toBe("account_already_linked_to_different_user"); expect((await call(fay, "GET", "/api/v1/account")).json.discord.linked).toBe(false); }); + +test("with registration locked, a Discord sign-in waits for approval too, and finishing setup keeps the approval", async () => { + await settings.setRegistration("locked"); + try { + const gil: Cookie = { v: "" }; + await viaDiscord(gil, { id: "1008", username: "gil", email: "gil@example.test", verified: true }); + const me = (await call(gil, "GET", "/api/v1/me")).json.person; + expect(me).toMatchObject({ kind: "basic", approved: false }); + + // Approved by a moderator, then finishing setup: still approved. + await db.update(schema.user).set({ approved: true }).where(eq(schema.user.id, me.id)); + expect((await call(gil, "POST", "/api/v1/account/finish", { username: "gil", password: "a long password" })).json.person).toMatchObject({ + kind: "member", + approved: true, + }); + } finally { + await settings.setRegistration("open"); + } +}); diff --git a/apps/api/test/oidc.test.ts b/apps/api/test/oidc.test.ts index 8456ec8..5561e27 100644 --- a/apps/api/test/oidc.test.ts +++ b/apps/api/test/oidc.test.ts @@ -20,10 +20,11 @@ let db: Database; let close: () => Promise; let base: string; let stop: () => void; +let settings: Settings; beforeAll(async () => { ({ db, close } = await openDatabase("memory")); - const settings = new Settings(db, { registration: "open" }); + settings = new Settings(db, { registration: "open" }); const auth = createAuth(db, { apiURL, webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false, settings, clients: [music] }); await seedClients(db, apiURL, [music]); const imvu = new ImvuClient("http://imvu.test", (async () => Response.json({ denormalized: {} })) as unknown as typeof fetch); @@ -185,3 +186,38 @@ test("a website session still links as before", async () => { expect((await call(dee, "GET", "/api/v1/account/imvu")).status).toBe(200); }); + +test("with registration locked, only approved accounts sign in to Music; closed doesn't stop anyone", async () => { + // Closed (prod): a member waiting for the hub's approval still signs in to Music. + await settings.setRegistration("closed"); + const eli = await signUp("eli"); + expect((await call(eli, "GET", "/api/v1/me")).json.person.approved).toBe(false); + await musicSignIn(eli); + + await settings.setRegistration("locked"); + try { + const fin = await signUp("fin"); + const id = (await call(fin, "GET", "/api/v1/me")).json.person.id; + // Sent to the website (which says they're waiting), with no code for Music. + const a = await authorizeURL("openid profile imvu"); + const r = await call(fin, "GET", a.path); + expect(r.status).toBe(302); + const to = new URL(r.location); + expect(to.origin + to.pathname).toBe(`${webURL}/`); + expect(to.searchParams.get("code")).toBeNull(); + // Continuing from that page doesn't get past it either. + const cont = await call(fin, "POST", "/api/auth/oauth2/continue", { postLogin: true, oauth_query: to.search.slice(1) }); + const again = new URL(cont.json.url); + expect(again.origin + again.pathname).toBe(`${webURL}/`); + expect(again.searchParams.get("code")).toBeNull(); + // Nor does eli, approved for nothing: locked holds back everyone unapproved. + const b = await call(eli, "GET", (await authorizeURL("openid")).path); + expect(new URL(b.location).origin + new URL(b.location).pathname).toBe(`${webURL}/`); + + // Once a moderator approves, it works. + await db.update(schema.user).set({ approved: true }).where(eq(schema.user.id, id)); + await musicSignIn(fin); + } finally { + await settings.setRegistration("open"); + } +}); diff --git a/apps/web/app/console/actions.ts b/apps/web/app/console/actions.ts index 7a4c5cc..da7e991 100644 --- a/apps/web/app/console/actions.ts +++ b/apps/web/app/console/actions.ts @@ -69,9 +69,14 @@ export async function decideAccount(_: ActionState, form: FormData): Promise { return attempt(async () => { - const registration = field(form, "registration") === "closed" ? "closed" : "open"; + const value = field(form, "registration"); + const registration = value === "closed" || value === "locked" ? value : "open"; unwrap(await api.console.settings.put({ registration })); revalidatePath("/console"); - return registration === "closed" ? "Registration closed: new accounts wait for approval." : "Registration open."; + return registration === "locked" + ? "Registration locked: every new account waits for approval, and only approved ones sign in to other sites." + : registration === "closed" + ? "Registration closed: new accounts wait for approval." + : "Registration open."; }); } diff --git a/apps/web/app/console/page.tsx b/apps/web/app/console/page.tsx index 59588b1..7d12590 100644 --- a/apps/web/app/console/page.tsx +++ b/apps/web/app/console/page.tsx @@ -71,9 +71,11 @@ export default async function Console() { Registration - {settings.registration === "closed" - ? "Closed: new accounts can sign in, but wait for a moderator's approval." - : "Open: new accounts can use the hub at once."} + {settings.registration === "locked" + ? "Locked: every new account, Discord ones too, waits for a moderator's approval, and only approved accounts sign in to T5DE's other sites. For staging." + : settings.registration === "closed" + ? "Closed: new accounts can sign in, but wait for a moderator's approval." + : "Open: new accounts can use the hub at once."} @@ -82,6 +84,7 @@ export default async function Console() { Open Closed + Locked Set diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index f55f0a4..84f5f17 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -24,7 +24,13 @@ export default async function RootLayout({ children }: { children: React.ReactNo
- {me?.kind === "basic" ? ( + {me?.kind === "basic" && !me.approved ? ( + // Only while registration is locked (staging): Discord sign-ins wait for approval too. + + ) : me?.kind === "basic" ? (