feat(accounts): locked registration, for staging
A third registration setting, locked: every new account waits for a moderator's approval, Discord sign-ins too, and only approved accounts sign in to T5DE's other sites. Today staging's closed registration still lets any Discord account in as a basic account, straight into Music's staging (and soon payments' staging, with PayPal's sandbox). The gate is the OAuth provider's postLogin check: an unapproved account is sent to the website's waiting page and no code is issued, on every authorize request and /oauth2/continue. Open and closed behave as before, so prod's Music sign-ins don't change.
This commit is contained in:
1 parent
02e8269d4d
commit
23cae691a9
11 files changed
+111
-22
No files matched your search
@@ -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_URL>/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
|
||||
|
||||
+5
-3
@@ -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(
|
||||
|
||||
+13
-4
@@ -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 },
|
||||
|
||||
@@ -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<Registration> {
|
||||
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) {
|
||||
|
||||
@@ -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: "[email protected]", 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");
|
||||
}
|
||||
});
|
||||
@@ -20,10 +20,11 @@ let db: Database;
|
||||
let close: () => Promise<void>;
|
||||
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");
|
||||
}
|
||||
});
|
||||
@@ -69,9 +69,14 @@ export async function decideAccount(_: ActionState, form: FormData): Promise<Act
|
||||
|
||||
export async function setRegistration(_: ActionState, form: FormData): Promise<ActionState> {
|
||||
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.";
|
||||
});
|
||||
}
|
||||
@@ -71,9 +71,11 @@ export default async function Console() {
|
||||
<CardHeader>
|
||||
<CardTitle>Registration</CardTitle>
|
||||
<CardDescription>
|
||||
{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."}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@@ -82,6 +84,7 @@ export default async function Console() {
|
||||
<NativeSelect name="registration" defaultValue={settings.registration} aria-label="Registration">
|
||||
<NativeSelectOption value="open">Open</NativeSelectOption>
|
||||
<NativeSelectOption value="closed">Closed</NativeSelectOption>
|
||||
<NativeSelectOption value="locked">Locked</NativeSelectOption>
|
||||
</NativeSelect>
|
||||
<SubmitButton pendingLabel="Setting…">Set</SubmitButton>
|
||||
</div>
|
||||
|
||||
@@ -24,7 +24,13 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
<StagingBanner />
|
||||
<Header />
|
||||
<main className="mx-auto w-full max-w-5xl flex-1 px-4 py-10 sm:px-6 sm:py-14">
|
||||
{me?.kind === "basic" ? (
|
||||
{me?.kind === "basic" && !me.approved ? (
|
||||
// Only while registration is locked (staging): Discord sign-ins wait for approval too.
|
||||
<NarrowCard
|
||||
title="Waiting for Approval"
|
||||
description={`You're signed in with Discord as ${me.username}. A moderator will approve your account soon; until then you can't use the hub or T5DE's other sites.`}
|
||||
/>
|
||||
) : me?.kind === "basic" ? (
|
||||
<NarrowCard
|
||||
title="Finish Setting Up Your Account"
|
||||
description={`You're signed in with Discord as ${me.username}. Choose a username and password to use the hub; T5DE's other sites already work with your Discord sign-in.`}
|
||||
|
||||
@@ -10,7 +10,7 @@ export default async function SignUp() {
|
||||
if (await getMe()) redirect("/account");
|
||||
const { registration } = unwrap(await api.hub.get());
|
||||
const description =
|
||||
registration === "closed"
|
||||
registration !== "open"
|
||||
? "One T5DE account for all your IMVU accounts. New accounts need a moderator's approval."
|
||||
: "One T5DE account for all your IMVU accounts.";
|
||||
return (
|
||||
|
||||
@@ -84,6 +84,10 @@ The cost: Music's sign-in depends on the hub being up, and the hub gains a secon
|
||||
Stored as a column on `user` (`kind: basic | member`); permissions treat basic accounts like unapproved ones on the
|
||||
hub's own routes.
|
||||
|
||||
Staging is locked down (**Decided**): its registration is `locked`, so every new account, Discord ones too, waits for
|
||||
a moderator's approval, and only approved accounts sign in to other sites (Music's and payments' staging). Prod
|
||||
stays as above.
|
||||
|
||||
Email (**Decided**):
|
||||
|
||||
- Better Auth needs one, so a basic account takes Discord's, and only when Discord says it's verified. A Discord
|
||||
|
||||
Reference in new issue
Block a user