feat(accounts): Discord sign-in and basic accounts (#22)
Release / release (push) Successful in 5s
CI / test (push) Successful in 7m39s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 32s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 22s

First half of docs/music.md's phase 1 (Accounts): Discord sign-in and basic accounts. The OIDC provider (Music as a trusted client, the `imvu` scope) is the next PR.

**Discord sign-in** (on 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** (`user.kind = "basic"`): Discord's name and email, no username or password. Basic accounts are for T5DE's other sites (Music); on the hub, every route but `/me` and `/account/finish` answers 403 `finish_setup`, and the website shows "Finish Setting Up Your Account" in place of every page.
- Only a **verified** Discord email (`user.validateUserInfo`): `email_not_verified`, or `email_not_found` for Discord accounts without one.
- **Never linked by matching email** (`accountLinking.disableImplicitLinking`): a Discord account whose email belongs to another T5DE account ends with `account_not_linked`, and the sign-in page says to sign in and link Discord from Account.
- Basic accounts don't count toward "the first account is an admin".

**Finishing setup**: `POST /api/v1/account/finish {username, password}` adds a password sign-in and a username in one transaction and makes the account a member (waiting for approval if registration is closed). Discord stays linked.

**Members** link Discord from the Account page (`/api/auth/link-social`; `account_already_linked_to_different_user` if it belongs to another account; merging basic accounts into members is phase 5) and unlink it (`DELETE /api/v1/account/discord`, audited). The console tags basic accounts "Discord only".

First half of docs/music.md's phase 1 (Accounts): Discord sign-in and basic accounts. The OIDC provider (Music as a trusted client, the `imvu` scope) is the next PR.

**Discord sign-in** (on 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** (`user.kind = "basic"`): Discord's name and email, no username or password. Basic accounts are for T5DE's other sites (Music); on the hub, every route but `/me` and `/account/finish` answers 403 `finish_setup`, and the website shows "Finish Setting Up Your Account" in place of every page.
- Only a **verified** Discord email (`user.validateUserInfo`): `email_not_verified`, or `email_not_found` for Discord accounts without one.
- **Never linked by matching email** (`accountLinking.disableImplicitLinking`): a Discord account whose email belongs to another T5DE account ends with `account_not_linked`, and the sign-in page says to sign in and link Discord from Account.
- Basic accounts don't count toward "the first account is an admin".

**Finishing setup**: `POST /api/v1/account/finish {username, password}` adds a password sign-in and a username in one transaction and makes the account a member (waiting for approval if registration is closed). Discord stays linked.

**Members** link Discord from the Account page (`/api/auth/link-social`; `account_already_linked_to_different_user` if it belongs to another account; merging basic accounts into members is phase 5) and unlink it (`DELETE /api/v1/account/discord`, audited). The console tags basic accounts "Discord only".

Also: Better Auth 1.7.14 → 1.7.26 (the OAuth provider package in the next PR needs it); migration `0021_account_kind` (one column, default `member`).

Tests: `apps/api/test/discord.test.ts` runs Better Auth's real social sign-in and callback against a stand-in for Discord's token and profile endpoints (basic account, verified email only, no linking by email, finishing setup, closed registration, linking and unlinking). Full suite 68/68, `check-types` and `build` pass locally. The new pages (sign-in's Discord button, Finish Setting Up, the Discord card) aren't checked in a browser yet: that needs the Discord application, then staging.

Before deploying: a Discord application with both redirect URLs (prod and staging), and its ID and secret in the hub stacks' secrets (dhkatz/infra).
Also: Better Auth 1.7.14 → 1.7.26 (the OAuth provider package in the next PR needs it); migration `0021_account_kind` (one column, default `member`).

Tests: `apps/api/test/discord.test.ts` runs Better Auth's real social sign-in and callback against a stand-in for Discord's token and profile endpoints (basic account, verified email only, no linking by email, finishing setup, closed registration, linking and unlinking). Full suite 68/68, `check-types` and `build` pass locally. The new pages (sign-in's Discord button, Finish Setting Up, the Discord card) aren't checked in a browser yet: that needs the Discord application, then staging.

Before deploying: a Discord application with both redirect URLs (prod and staging), and its ID and secret in the hub stacks' secrets (dhkatz/infra).

Co-authored-by: dhkatz <[email protected]>
This commit was merged in pull request #22.
This commit is contained in:
dhkatz authored and dhkatz committed 2026-11-19 09:50:40 +00:00
1 parent a66a3a4b6a
commit f05874f800
24 files changed
+5214 -173

No files matched your search

+1 -1
View File
@@ -13,7 +13,7 @@
},
"dependencies": {
"@t5de/db": "workspace:*",
"better-auth": "1.7.14",
"better-auth": "1.7.26",
"elysia": "1.4.30",
"jose": "6.2.14",
"sanitize-html": "2.18.1"
+101 -17
View File
@@ -20,7 +20,7 @@ import {
type ParentInfo,
type RoomModerator,
} from "@t5de/db";
import type { Auth } from "./auth";
import { passwordRules, usernameRules, validUsername, type Auth } from "./auth";
import { AgeError, AgeRefused, AgeService } from "./age";
import { imvuAgeProvider, imvuResult } from "./age/imvu";
import { ImvuClient, ImvuUnavailable, NoSuchImvuUser } from "./imvu";
@@ -62,7 +62,7 @@ import {
type Scope,
} from "./permissions";
const { user, session, imvuLink, linkChallenge, audit, hostedRoom, catalog, product, hosting } = schema;
const { user, session, account, imvuLink, linkChallenge, audit, hostedRoom, catalog, product, hosting } = schema;
export type Deps = {
db: Database;
@@ -106,6 +106,12 @@ type Link = typeof imvuLink.$inferSelect;
const roles = ["user", "moderator", "admin"] as const;
const isModerator = (p: Person) => p.role === "moderator" || p.role === "admin";
/** A signed-in person who can't use the hub's features yet: waiting for approval, or a basic account. */
function notMemberYet(waiting: Person | undefined, basic: Person | undefined) {
if (basic) throw new Problem(403, "finish_setup", "Finish setting up your T5DE account first: choose a username and password.");
if (waiting) throw new Problem(403, "awaiting_approval", "Your account is waiting for a moderator's approval.");
}
// Link codes: "t5de-" and eight letters and digits without look-alikes.
function linkCode(): string {
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
@@ -151,6 +157,8 @@ export function createApp({
}: Deps) {
const age = ageService ?? new AgeService(db, [imvuAgeProvider(imvu)]);
const settings = hubSettings ?? new Settings(db);
/** Whether Discord sign-in is configured (DISCORD_CLIENT_ID and DISCORD_CLIENT_SECRET). */
const discordOn = Boolean((auth.options.socialProviders as Record<string, unknown> | undefined)?.discord);
const signer = new Signer(db, apiURL ?? "http://localhost:4101");
const products = new Products(db, signer, imvu);
const perms = new Permissions(db);
@@ -225,6 +233,7 @@ export function createApp({
banned: p.banned === true,
banReason: p.banReason ?? "",
approved: p.approved,
kind: (p.kind === "basic" ? "basic" : "member") as "basic" | "member",
twoFactor: p.twoFactorEnabled,
});
@@ -887,10 +896,11 @@ export function createApp({
if (bearer?.startsWith(tokenPrefix)) {
const tok = await tokens.verify(bearer);
const owner = tok ? (await db.select().from(user).where(eq(user.id, tok.userId)))[0] : undefined;
const ok = owner && !owner.banned && owner.approved ? owner : undefined;
const ok = owner && !owner.banned && owner.approved && owner.kind === "member" ? owner : undefined;
return {
person: undefined,
waiting: undefined,
basic: undefined,
sessionId: undefined,
tokenPerson: tok && ok ? Object.assign(ok, { token: { id: tok.id, name: tok.name, grants: tok.grants } }) : undefined,
badToken: !(tok && ok),
@@ -898,38 +908,41 @@ export function createApp({
}
const s = await auth.api.getSession({ headers: request.headers });
const person = s?.user ? ((await db.select().from(user).where(eq(user.id, s.user.id)))[0] ?? undefined) : undefined;
// A person waiting for approval counts as signed out everywhere but their own account (/me).
// A person waiting for approval, and a basic account (Discord only, until it finishes setting up), count as
// signed out everywhere but their own account.
const usable = person && !person.banned ? person : undefined;
const member = usable?.kind === "member" ? usable : undefined;
return {
person: usable?.approved ? usable : undefined,
waiting: usable && !usable.approved ? usable : undefined,
person: member?.approved ? member : undefined,
waiting: member && !member.approved ? member : undefined,
basic: usable?.kind === "basic" ? usable : undefined,
sessionId: s?.session.id,
tokenPerson: undefined,
badToken: false,
};
})
.macro({
/** Signed in, approved or still waiting. */
/** Signed in: approved, still waiting, or a basic account. */
account: {
resolve: ({ person, waiting, tokenPerson, badToken }) => {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
const me = person ?? waiting;
const me = person ?? waiting ?? basic;
if (!me) throw new Problem(401, "signed_out", "Sign in first.");
return { me };
},
},
signedIn: {
resolve: ({ person, waiting, tokenPerson, badToken }) => {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
if (waiting) throw new Problem(403, "awaiting_approval", "Your account is waiting for a moderator's approval.");
notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person };
},
},
moderator: {
resolve: ({ person, waiting, tokenPerson, badToken }) => {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
if (waiting) throw new Problem(403, "awaiting_approval", "Your account is waiting for a moderator's approval.");
notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
if (!isModerator(person)) throw new Problem(403, "forbidden", "Only moderators can do this.");
return { me: person };
@@ -937,10 +950,10 @@ export function createApp({
},
/** Signed in, or an API token (whose grants then limit every permission check). */
scripted: {
resolve: ({ person, waiting, tokenPerson, badToken }) => {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => {
if (badToken) throw new Problem(401, "bad_token", "That token isn't valid: wrong, revoked or expired.");
if (tokenPerson) return { me: tokenPerson };
if (waiting) throw new Problem(403, "awaiting_approval", "Your account is waiting for a moderator's approval.");
notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person };
},
@@ -963,8 +976,8 @@ export function createApp({
},
{ account: true },
)
// The hub's public settings: whether new accounts wait for approval.
.get("/hub", async () => ({ registration: await settings.registration() }))
// The hub's public settings: whether new accounts wait for approval, and whether Discord sign-in is on.
.get("/hub", async () => ({ registration: await settings.registration(), discord: discordOn }))
.get("/home", async ({ person }) => {
const online = (await visibleOnline(person)).length;
if (!person) return { onlineCount: online };
@@ -1026,8 +1039,14 @@ export function createApp({
.select({ n: count() })
.from(session)
.where(and(eq(session.userId, me.id), ilike(session.userAgent, "t5de-proxy%"), sql`${session.expiresAt} > now()`));
const [discord] = await db
.select({ id: account.accountId })
.from(account)
.where(and(eq(account.userId, me.id), eq(account.providerId, "discord")));
return {
person: personView(me),
// Discord sign-in: whether the hub offers it, and whether this account has it.
discord: { available: discordOn, linked: discord !== undefined },
links: await linkViews(me.id, links),
challenges: challenges.map((c) => ({
imvuId: c.imvuId,
@@ -1046,6 +1065,71 @@ export function createApp({
},
{ signedIn: true },
)
// A basic account (made by signing in with Discord) becomes a member: a username and password, then approval if
// registration is closed. Discord stays linked.
.post(
"/account/finish",
async ({ me, body }) => {
if (me.kind !== "basic") throw new Problem(409, "already_member", "Your account is already set up.");
const name = body.username.trim();
if (!validUsername(name))
throw new Problem(
400,
"invalid_username",
`A username is ${usernameRules.min} to ${usernameRules.max} letters, digits and underscores.`,
);
if (body.password.length < passwordRules.min || body.password.length > passwordRules.max)
throw new Problem(400, "invalid_password", `A password is at least ${passwordRules.min} characters.`);
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";
let updated: Person | undefined;
try {
updated = await db.transaction(async (tx) => {
// A password sign-in, as Better Auth's own sign-up makes it.
await tx.insert(account).values({
id: randomID(),
accountId: me.id,
providerId: "credential",
userId: me.id,
password: hash,
});
const [u] = await tx
.update(user)
.set({ username: name.toLowerCase(), displayUsername: name, kind: "member", approved })
.where(and(eq(user.id, me.id), eq(user.kind, "basic")))
.returning();
if (!u) throw new Problem(409, "already_member", "Your account is already set up.");
return u;
});
} catch (e) {
if ((e as { code?: string; cause?: { code?: string } }).code === "23505" || (e as { cause?: { code?: string } }).cause?.code === "23505")
throw new Problem(409, "username_taken", "That username is taken. Try another.");
throw e;
}
await audited(me, "account.finish", me.id, { username: name }, { person: me.id });
return { person: personView(updated!) };
},
{
account: true,
body: t.Object({ username: t.String({ minLength: 1, maxLength: 64 }), password: t.String({ minLength: 1, maxLength: 1024 }) }),
},
)
// Unlinks Discord from a member's account (they keep their password; basic accounts can't: it's their only way in).
.delete(
"/account/discord",
async ({ me, set }) => {
const removed = await db
.delete(account)
.where(and(eq(account.userId, me.id), eq(account.providerId, "discord")))
.returning({ id: account.accountId });
if (removed.length === 0) throw new Problem(404, "not_found", "Discord isn't linked.");
await audited(me, "account.discord_unlink", me.id, {}, { person: me.id });
set.status = 204;
},
{ signedIn: true },
)
.post(
"/account/claims/:imvu",
async ({ me, params }) => {
+64 -12
View File
@@ -1,10 +1,11 @@
// Accounts, sessions and proxy sign-in, by Better Auth: email and password with usernames, roles and bans (admin),
// device sign-in for T5DE's proxy (RFC 8628), bearer tokens for the proxy's requests, and JWTs with published keys
// (for catalogs later), and two-factor sign-in (an authenticator app, with backup codes).
// Discord sign-in (basic accounts, docs/music.md), device sign-in for T5DE's proxy (RFC 8628), bearer tokens for the
// proxy's requests, and JWTs with published keys (for catalogs later), and two-factor sign-in (an authenticator app,
// with backup codes).
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { admin, bearer, deviceAuthorization, jwt, twoFactor, username } from "better-auth/plugins";
import { count, schema, type Database } from "@t5de/db";
import { count, eq, schema, type Database } from "@t5de/db";
import { Settings } from "./settings";
export type AuthConfig = {
@@ -18,11 +19,31 @@ export type AuthConfig = {
rateLimit?: boolean;
/** Whether new accounts wait for approval (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. */
discord?: { clientId: string; clientSecret: string };
};
/** The proxy's client ID in device sign-in. */
export const proxyClientID = "t5de-proxy";
/** Usernames: letters, digits and underscores; imvu_<ID> is reserved for unclaimed creators (docs/imports.md). */
export const usernameRules = { min: 3, max: 32 };
export const validUsername = (name: string) =>
name.length >= usernameRules.min &&
name.length <= usernameRules.max &&
/^[A-Za-z0-9_]+$/.test(name) &&
!/^imvu_/i.test(name);
/** Passwords' lengths (Better Auth's emailAndPassword). */
export const passwordRules = { min: 10, max: 256 };
/** Errors Discord sign-in can end with, as Better Auth names them (the website shows a sentence for each). */
export const discordErrors = {
/** The Discord account's email isn't verified, or it has none (phone-only accounts). */
emailNotVerified: "email_not_verified",
} as const;
export function createAuth(db: Database, config: AuthConfig) {
const settings = config.settings ?? new Settings(db);
return betterAuth({
@@ -31,11 +52,38 @@ export function createAuth(db: Database, config: AuthConfig) {
secret: config.secret,
trustedOrigins: [config.webURL],
database: drizzleAdapter(db, { provider: "pg", schema }),
emailAndPassword: { enabled: true, minPasswordLength: 10, maxPasswordLength: 256 },
emailAndPassword: { enabled: true, minPasswordLength: passwordRules.min, maxPasswordLength: passwordRules.max },
socialProviders: config.discord
? { discord: { clientId: config.discord.clientId, clientSecret: config.discord.clientSecret } }
: {},
account: {
accountLinking: {
enabled: true,
// Never link or merge by matching email: Discord is linked to an account only from that account's own
// session (Account page). Otherwise anyone who puts a member's address on a Discord account could sign in
// as them. A Discord sign-in whose email belongs to an account it isn't linked to ends with
// `account_not_linked`.
disableImplicitLinking: true,
// A member's Discord account may use another address than the member does.
allowDifferentEmails: true,
// A basic account's only way in is Discord: it can't be unlinked.
allowUnlinkingAll: false,
},
},
user: {
additionalFields: {
linkCap: { type: "number", defaultValue: 10, input: false },
approved: { type: "boolean", defaultValue: true, input: false },
kind: { type: "string", defaultValue: "member", input: false },
},
// A new account from Discord takes Discord's email, and only a verified one.
validateUserInfo: ({ user, source }) => {
if (source.action !== "create-user" || source.method !== "oauth") return;
if (!user.email || user.emailVerified !== true)
return {
error: discordErrors.emailNotVerified,
errorDescription: "Verify your email in Discord, then sign in again.",
};
},
},
// Proxies stay signed in for months; a session is extended when it's used.
@@ -45,22 +93,26 @@ export function createAuth(db: Database, config: AuthConfig) {
databaseHooks: {
user: {
create: {
// The first account runs the hub; with registration closed, the others wait for approval.
before: async (u) => {
const [row] = await db.select({ n: count() }).from(schema.user);
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).
if (ctx?.path?.startsWith("/callback/"))
return { data: { ...u, role: "user", approved: true, 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;
const approved = first || (await settings.registration()) === "open";
return { data: { ...u, role: first ? "admin" : "user", approved } };
return { data: { ...u, role: first ? "admin" : "user", approved, kind: "member" } };
},
},
},
},
plugins: [
username({
minUsernameLength: 3,
maxUsernameLength: 32,
// imvu_<ID> is reserved for unclaimed creators (docs/imports.md).
usernameValidator: (name) => /^[A-Za-z0-9_]+$/.test(name) && !/^imvu_/i.test(name),
minUsernameLength: usernameRules.min,
maxUsernameLength: usernameRules.max,
usernameValidator: validUsername,
}),
admin({ defaultRole: "user", adminRoles: ["admin"] }),
deviceAuthorization({
+8 -1
View File
@@ -5,6 +5,9 @@
// WEB_URL the website's address (default http://localhost:4100)
// PORT default 4101
// REGISTRATION open or closed (new accounts wait for a moderator's approval), until an admin sets it in the console
// DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET
// Discord sign-in (basic accounts, docs/music.md); its redirect URL is
// API_URL/api/auth/callback/discord. Off unless both are set.
// AGE_PROVIDERS ways to verify age, comma-separated (default imvu): imvu, didit
// DIDIT_API_KEY, DIDIT_WORKFLOW_ID, DIDIT_WEBHOOK_SECRET
// Didit's ID document check (docs/design.md, "Age"); its webhook is API_URL/api/v1/age/webhook/didit
@@ -32,7 +35,11 @@ const webURL = env.WEB_URL ?? "http://localhost:4100";
const { db } = await openDatabase(env.DATABASE_URL ?? "./data/db");
const settings = new Settings(db, { registration: env.REGISTRATION });
const auth = createAuth(db, { apiURL, webURL, secret, settings });
const discord =
env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET
? { clientId: env.DISCORD_CLIENT_ID, clientSecret: env.DISCORD_CLIENT_SECRET }
: undefined;
const auth = createAuth(db, { apiURL, webURL, secret, settings, discord });
const imvu = new ImvuClient();
function required(name: string): string {
+205
View File
@@ -0,0 +1,205 @@
// Discord sign-in (docs/music.md, Accounts): it makes a basic account (Discord only, none of the hub's features), from a
// 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 { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { ImvuClient } from "../src/imvu";
import { Settings } from "../src/settings";
const webURL = "http://web.test";
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
let settings: Settings;
/** The Discord account the next sign-in comes back as. */
let discordProfile: Record<string, unknown> = {};
const realFetch = globalThis.fetch;
beforeAll(async () => {
// Discord's token and profile endpoints, as Better Auth's Discord provider calls them.
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
if (url.startsWith("https://discord.com/api/oauth2/token"))
return Response.json({ access_token: "discord-at", token_type: "Bearer", expires_in: 3600, refresh_token: "discord-rt", scope: "identify email" });
if (/^https:\/\/discord\.com\/api\/users\/(@|%40)me/.test(url)) return Response.json(discordProfile);
return realFetch(input, init);
}) as typeof fetch;
({ db, close } = await openDatabase("memory"));
settings = new Settings(db, { registration: "open" });
const auth = createAuth(db, {
apiURL: "http://api.test",
webURL,
secret: "test-secret-test-secret-test-secret-1234",
rateLimit: false,
settings,
discord: { clientId: "discord-client", clientSecret: "discord-secret" },
});
const imvu = new ImvuClient("http://imvu.test", (async () => Response.json({ denormalized: {} })) as unknown as typeof fetch);
const hub = createApp({ db, auth, imvu, webURL, settings });
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
globalThis.fetch = realFetch;
stop();
await close();
});
type Cookie = { v: string };
/** Keeps the cookies a response sets (Better Auth's state, then the session). */
function keep(cookie: Cookie, res: Response) {
const jar = new Map(cookie.v ? cookie.v.split("; ").map((c) => c.split("=", 2) as [string, string]) : []);
for (const c of res.headers.getSetCookie()) {
const [pair] = c.split(";");
const [k, v] = pair!.split("=", 2) as [string, string];
if (/max-age=0/i.test(c) || v === "") jar.delete(k);
else jar.set(k, v);
}
cookie.v = [...jar].map(([k, v]) => `${k}=${v}`).join("; ");
}
async function call(cookie: Cookie, method: string, path: string, body?: unknown) {
const res = await realFetch(base + path, {
method,
redirect: "manual",
headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...(cookie.v ? { Cookie: cookie.v } : {}) },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
keep(cookie, res);
const text = await res.text();
let json: any;
try {
json = text ? JSON.parse(text) : undefined;
} catch {
json = undefined;
}
return { status: res.status, json, location: res.headers.get("location") ?? "" };
}
/** Goes through Discord's sign-in (or linking, from a signed-in session) and returns where the browser ends up. */
async function viaDiscord(cookie: Cookie, profile: Record<string, unknown>, link = false) {
discordProfile = { discriminator: "0", avatar: null, global_name: profile.username, ...profile };
const start = link
? await call(cookie, "POST", "/api/auth/link-social", { provider: "discord", callbackURL: `${webURL}/account`, errorCallbackURL: `${webURL}/account` })
: await call(cookie, "POST", "/api/auth/sign-in/social", { provider: "discord", callbackURL: `${webURL}/`, errorCallbackURL: `${webURL}/signin` });
expect(start.status).toBe(200);
const state = new URL(start.json.url).searchParams.get("state");
expect(state).toBeTruthy();
const back = await call(cookie, "GET", `/api/auth/callback/discord?code=discord-code&state=${encodeURIComponent(state!)}`);
expect(back.status).toBe(302);
return new URL(back.location, webURL);
}
async function signUp(name: string, email = `${name}@example.test`) {
const cookie = { v: "" };
expect((await call(cookie, "POST", "/api/auth/sign-up/email", { email, password: "a long password", name, username: name })).status).toBe(200);
return cookie;
}
test("a basic account from Discord can't use the hub until it finishes setting up; the first member still runs the hub", async () => {
expect((await call({ v: "" }, "GET", "/api/v1/hub")).json).toEqual({ registration: "open", discord: true });
const disco: Cookie = { v: "" };
const landed = await viaDiscord(disco, { id: "1001", username: "disco", email: "[email protected]", verified: true });
expect(landed.pathname).toBe("/");
expect(landed.searchParams.get("error")).toBeNull();
const me = (await call(disco, "GET", "/api/v1/me")).json.person;
expect(me).toMatchObject({ kind: "basic", role: "user", username: "disco", email: "[email protected]" });
expect(await call(disco, "GET", "/api/v1/account")).toMatchObject({ status: 403, json: { error: "finish_setup" } });
expect((await call(disco, "POST", "/api/v1/account/links", { username: "someone" })).json.error).toBe("finish_setup");
// Basic accounts don't count: the first member is still the admin.
const ada = await signUp("ada");
expect((await call(ada, "GET", "/api/v1/me")).json.person).toMatchObject({ kind: "member", role: "admin" });
// Signing in with the same Discord account again is the same person.
const again: Cookie = { v: "" };
await viaDiscord(again, { id: "1001", username: "disco", email: "[email protected]", verified: true });
expect((await call(again, "GET", "/api/v1/me")).json.person.id).toBe(me.id);
});
test("Discord sign-in needs a verified email, and never links to an account by its email", async () => {
const unverified = await viaDiscord({ v: "" }, { id: "1002", username: "nover", email: "[email protected]", verified: false });
expect(unverified.pathname).toBe("/signin");
expect(unverified.searchParams.get("error")).toBe("email_not_verified");
const noEmail = await viaDiscord({ v: "" }, { id: "1003", username: "phone", email: null, verified: false });
expect(noEmail.searchParams.get("error")).toBe("email_not_found");
// bea is a member; someone puts her address on their Discord account.
await signUp("bea");
const thief: Cookie = { v: "" };
const taken = await viaDiscord(thief, { id: "1004", username: "thief", email: "[email protected]", verified: true });
expect(taken.pathname).toBe("/signin");
expect(taken.searchParams.get("error")).toBe("account_not_linked");
expect((await call(thief, "GET", "/api/v1/me")).status).toBe(401);
});
test("finishing setup: a username and password make a member, still signing in with Discord too", async () => {
const cass: Cookie = { v: "" };
await viaDiscord(cass, { id: "1005", username: "cass", email: "[email protected]", verified: true });
const id = (await call(cass, "GET", "/api/v1/me")).json.person.id;
const finish = (username: string, password = "a long password") => call(cass, "POST", "/api/v1/account/finish", { username, password });
expect((await finish("no spaces")).json.error).toBe("invalid_username");
expect((await finish("imvu_123")).json.error).toBe("invalid_username");
expect((await finish("Ada")).json.error).toBe("username_taken");
expect((await finish("cass_", "short")).json.error).toBe("invalid_password");
const done = await finish("Cass_");
expect(done.status).toBe(200);
expect(done.json.person).toMatchObject({ id, kind: "member", username: "Cass_", approved: true });
expect((await call(cass, "GET", "/api/v1/account")).json).toMatchObject({ discord: { available: true, linked: true } });
expect((await finish("again")).json.error).toBe("already_member");
// The password works, and so does Discord.
const byPassword: Cookie = { v: "" };
expect((await call(byPassword, "POST", "/api/auth/sign-in/username", { username: "cass_", password: "a long password" })).status).toBe(200);
expect((await call(byPassword, "GET", "/api/v1/me")).json.person.id).toBe(id);
const byDiscord: Cookie = { v: "" };
await viaDiscord(byDiscord, { id: "1005", username: "cass", email: "[email protected]", verified: true });
expect((await call(byDiscord, "GET", "/api/v1/me")).json.person).toMatchObject({ id, kind: "member" });
});
test("with registration closed, a finished account waits for approval", async () => {
await settings.setRegistration("closed");
try {
const dee: Cookie = { v: "" };
await viaDiscord(dee, { id: "1006", username: "dee", email: "[email protected]", verified: true });
expect((await call(dee, "POST", "/api/v1/account/finish", { username: "dee", password: "a long password" })).json.person).toMatchObject({
kind: "member",
approved: false,
});
expect((await call(dee, "GET", "/api/v1/account")).json.error).toBe("awaiting_approval");
} finally {
await settings.setRegistration("open");
}
});
test("a member links Discord from their own session; a Discord account already in use can't be linked again", async () => {
const eve = await signUp("eve");
expect((await call(eve, "GET", "/api/v1/account")).json.discord).toEqual({ available: true, linked: false });
// Another address than eve's own: allowed, it's her session that links it.
const linked = await viaDiscord(eve, { id: "1007", username: "eve_discord", email: "[email protected]", verified: true }, true);
expect(linked.pathname).toBe("/account");
expect(linked.searchParams.get("error")).toBeNull();
expect((await call(eve, "GET", "/api/v1/account")).json.discord).toEqual({ available: true, linked: true });
// And unlinks it again (she keeps her password).
expect((await call(eve, "DELETE", "/api/v1/account/discord")).status).toBe(204);
expect((await call(eve, "GET", "/api/v1/account")).json.discord.linked).toBe(false);
expect((await call(eve, "DELETE", "/api/v1/account/discord")).status).toBe(404);
// disco's Discord account (a basic account) can't be added to fay's: merging comes later.
const fay = await signUp("fay");
const refused = await viaDiscord(fay, { id: "1001", username: "disco", email: "[email protected]", verified: true }, true);
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);
});
+2 -2
View File
@@ -51,7 +51,7 @@ async function signUp(name: string) {
}
test("closed: new accounts wait for approval; the first one runs the hub", async () => {
expect((await call({ v: "" }, "GET", "/api/v1/hub")).json).toEqual({ registration: "closed" });
expect((await call({ v: "" }, "GET", "/api/v1/hub")).json).toEqual({ registration: "closed", discord: false });
const admin = await signUp("ada");
expect((await call(admin, "GET", "/api/v1/me")).json.person).toMatchObject({ role: "admin", approved: true });
expect((await call(admin, "GET", "/api/v1/account")).status).toBe(200);
@@ -100,7 +100,7 @@ test("only admins open or close registration", async () => {
expect((await call(mod, "PUT", "/api/v1/console/settings", { registration: "open" })).status).toBe(403);
expect((await call(admin, "PUT", "/api/v1/console/settings", { registration: "open" })).json).toEqual({ registration: "open" });
expect((await call({ v: "" }, "GET", "/api/v1/hub")).json).toEqual({ registration: "open" });
expect((await call({ v: "" }, "GET", "/api/v1/hub")).json).toEqual({ registration: "open", discord: false });
// Open: new accounts can use the hub at once.
const eve = await signUp("eve");
expect((await call(eve, "GET", "/api/v1/account")).status).toBe(200);
+21
View File
@@ -52,6 +52,27 @@ export async function saveSettings(
});
}
/** Unlinks Discord (members keep their username and password). */
export async function unlinkDiscord(_: ActionState, _form: FormData): Promise<ActionState> {
return attempt(async () => {
unwrap(await api.account.discord.delete());
done();
});
}
/** A basic account (Discord only) becomes a member: a username and password. */
export async function finishSetup(_: ActionState, form: FormData): Promise<ActionState> {
// Passwords aren't trimmed.
const password = typeof form.get("password") === "string" ? (form.get("password") as string) : "";
if (password !== form.get("password2")) return { error: "The passwords don't match." };
const state = await attempt(async () => {
unwrap(await api.account.finish.post({ username: field(form, "username"), password }));
});
if (state?.error) return state;
revalidatePath("/", "layout");
redirect("/account?welcome=1");
}
export async function signOutComputers(_: ActionState, _form: FormData): Promise<ActionState> {
return attempt(async () => {
unwrap(await api.account["signout-computers"].post());
+36
View File
@@ -0,0 +1,36 @@
// Discord on a member's account: link it to sign in with Discord too (and on T5DE's other sites), or unlink it.
import { DiscordButton } from "@/components/discord-button";
import { ActionForm, ErrorText, SubmitButton } from "@/components/forms";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { unlinkDiscord } from "./actions";
export function DiscordCard({ linked, error }: { linked: boolean; error?: string }) {
return (
<Card>
<CardHeader>
<CardTitle>Discord</CardTitle>
<CardDescription>
{linked
? "Linked: you can sign in with Discord, here and on T5DE's other sites."
: "Link Discord to sign in with it, here and on T5DE's other sites."}
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{error && <ErrorText>{error}</ErrorText>}
{linked ? (
<ActionForm action={unlinkDiscord}>
<SubmitButton
variant="outline"
pendingLabel="Unlinking…"
confirm="Unlink Discord? You'll sign in with your username and password only."
>
Unlink Discord
</SubmitButton>
</ActionForm>
) : (
<DiscordButton mode="link" />
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,31 @@
"use client";
// A basic account (made by signing in with Discord) chooses a username and password, and becomes a member.
import { ActionForm, SubmitButton } from "@/components/forms";
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { finishSetup } from "./actions";
export function FinishSetupForm() {
return (
<ActionForm action={finishSetup}>
<FieldGroup>
<Field>
<FieldLabel htmlFor="username">Username</FieldLabel>
<Input id="username" name="username" autoComplete="username" required minLength={3} maxLength={32} pattern="[A-Za-z0-9_]+" autoFocus />
<FieldDescription>Letters, digits and underscores. Other T5DE members see it.</FieldDescription>
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input id="password" name="password" type="password" autoComplete="new-password" required minLength={10} maxLength={256} />
</Field>
<Field>
<FieldLabel htmlFor="password2">Password again</FieldLabel>
<Input id="password2" name="password2" type="password" autoComplete="new-password" required minLength={10} maxLength={256} />
</Field>
<Field>
<SubmitButton pendingLabel="Setting up…">Finish setting up</SubmitButton>
</Field>
</FieldGroup>
</ActionForm>
);
}
+5 -1
View File
@@ -7,16 +7,18 @@ import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { api, getMe, isModerator, unwrap } from "@/lib/api";
import { discordError } from "@/lib/discord";
import { claimCreator, linkAccount, signOutComputers } from "./actions";
import { AgeCard } from "./age-card";
import { ChallengeCard } from "./challenge-card";
import { DiscordCard } from "./discord-card";
import { LinkCard } from "./link-card";
import { TokensCard } from "./tokens-card";
import { TwoFactorCard } from "./two-factor-card";
export const metadata: Metadata = { title: "Account" };
export default async function Account({ searchParams }: { searchParams: Promise<{ welcome?: string; age?: string }> }) {
export default async function Account({ searchParams }: { searchParams: Promise<{ welcome?: string; age?: string; error?: string }> }) {
const me = await getMe();
if (!me) redirect("/signin?next=/account");
const [account, age, tokens] = await Promise.all([
@@ -120,6 +122,8 @@ export default async function Account({ searchParams }: { searchParams: Promise<
<AgeCard age={age} back={params.age === "back"} />
{account.discord.available && <DiscordCard linked={account.discord.linked} error={discordError(params.error)} />}
<Card>
<CardHeader>
<CardTitle>T5DE on your computers</CardTitle>
@@ -36,6 +36,7 @@ export default async function PersonPage({ params }: { params: Promise<{ id: str
</span>
{person.banned && <Tag tone="danger">banned: {person.banReason}</Tag>}
{!person.approved && <Tag tone="strong">waiting for approval</Tag>}
{person.kind === "basic" && <Tag>Discord only: hasn't finished setting up</Tag>}
{person.twoFactor && <Tag>two-factor on</Tag>}
</span>
</PageHeader>
+7 -1
View File
@@ -76,7 +76,13 @@ export default async function People({
<DateTime iso={p.createdAt} dateOnly />
</TableCell>
<TableCell className="text-right">
{p.banned ? <Tag tone="danger">banned</Tag> : !p.approved && <Tag tone="strong">waiting</Tag>}
{p.banned ? (
<Tag tone="danger">banned</Tag>
) : p.kind === "basic" ? (
<Tag>Discord only</Tag>
) : (
!p.approved && <Tag tone="strong">waiting</Tag>
)}
</TableCell>
</TableRow>
))}
+9 -1
View File
@@ -4,6 +4,7 @@ import { Header } from "@/components/header";
import { NarrowCard } from "@/components/narrow-card";
import { StagingBanner } from "@/components/staging-banner";
import { getMe } from "@/lib/api";
import { FinishSetupForm } from "./account/finish-setup-form";
import { cn } from "@/lib/utils";
import "./globals.css";
@@ -23,7 +24,14 @@ 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 && !me.approved ? (
{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.`}
>
<FinishSetupForm />
</NarrowCard>
) : me && !me.approved ? (
<NarrowCard
title="Waiting for Approval"
description={`Thanks for signing up, ${me.username}. A moderator will approve your account soon; until then you can't use the hub.`}
+28 -4
View File
@@ -1,18 +1,42 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { DiscordButton } from "@/components/discord-button";
import { ErrorText } from "@/components/forms";
import { NarrowCard } from "@/components/narrow-card";
import { getMe } from "@/lib/api";
import { Separator } from "@/components/ui/separator";
import { api, getMe, unwrap } from "@/lib/api";
import { discordError } from "@/lib/discord";
import { safeNext } from "@/lib/paths";
import { SignInForm } from "./signin-form";
export const metadata: Metadata = { title: "Sign in" };
export default async function SignIn({ searchParams }: { searchParams: Promise<{ next?: string | string[] }> }) {
const next = safeNext((await searchParams).next);
export default async function SignIn({
searchParams,
}: {
searchParams: Promise<{ next?: string | string[]; error?: string | string[] }>;
}) {
const params = await searchParams;
const next = safeNext(params.next);
if (await getMe()) redirect(next);
const { discord } = unwrap(await api.hub.get());
const error = discordError(params.error);
return (
<NarrowCard title="Sign in" description="to your T5DE account.">
<SignInForm next={next} />
<div className="space-y-6">
{error && <ErrorText>{error}</ErrorText>}
{discord && (
<>
<DiscordButton mode="sign-in" next={next} />
<div className="flex items-center gap-3 text-xs text-muted-foreground">
<Separator className="flex-1" />
or with your username
<Separator className="flex-1" />
</div>
</>
)}
<SignInForm next={next} />
</div>
</NarrowCard>
);
}
+40
View File
@@ -0,0 +1,40 @@
"use client";
// Discord sign-in (a basic account the first time, docs/music.md) and, from the account page, linking Discord to a
// member's account. Discord sends people back to the API, which sends them on to these addresses on this site.
import { useState } from "react";
import { ErrorText } from "@/components/forms";
import { Button } from "@/components/ui/button";
import { authClient } from "@/lib/auth-client";
export function DiscordButton({ mode, next = "/" }: { mode: "sign-in" | "link"; next?: string }) {
const [pending, setPending] = useState(false);
const [error, setError] = useState("");
async function go() {
setPending(true);
setError("");
const origin = window.location.origin;
const back =
mode === "link"
? { callbackURL: `${origin}/account`, errorCallbackURL: `${origin}/account` }
: { callbackURL: origin + next, errorCallbackURL: `${origin}/signin?next=${encodeURIComponent(next)}` };
const { error } =
mode === "link"
? await authClient.linkSocial({ provider: "discord", ...back })
: await authClient.signIn.social({ provider: "discord", ...back });
// On success the browser is already on its way to Discord.
if (error) {
setError(error.message ?? "That didn't work. Try again.");
setPending(false);
}
}
return (
<div className="space-y-2">
<Button type="button" variant={mode === "link" ? "outline" : "default"} className={mode === "link" ? undefined : "w-full"} disabled={pending} onClick={() => void go()}>
{pending ? "Going to Discord…" : mode === "link" ? "Link Discord" : "Sign in with Discord"}
</Button>
{error && <ErrorText>{error}</ErrorText>}
</div>
);
}
+15
View File
@@ -0,0 +1,15 @@
// What went wrong with Discord sign-in or linking, as a sentence. Better Auth sends people back with ?error=<code>.
const messages: Record<string, string> = {
email_not_verified: "Your Discord account's email isn't verified. Verify it in Discord, then try again.",
email_not_found: "Your Discord account has no email. Add one in Discord and verify it, then try again.",
account_not_linked:
"This email belongs to a T5DE account. Sign in to it with your username and password, then link Discord from your account page.",
account_already_linked_to_different_user: "That Discord account already signs in to another T5DE account.",
access_denied: "Discord sign-in was cancelled.",
};
/** The sentence for an error Discord sign-in came back with (undefined if there's none). */
export function discordError(code: string | string[] | undefined): string | undefined {
if (typeof code !== "string" || !code) return undefined;
return messages[code] ?? "Signing in with Discord didn't work. Try again.";
}
+1 -1
View File
@@ -12,7 +12,7 @@
"@base-ui/react": "^1.9.0",
"@elysiajs/eden": "1.4.9",
"@t5de/api": "workspace:*",
"better-auth": "1.7.14",
"better-auth": "1.7.26",
"class-variance-authority": "^0.7.1",
"cn": "^0.5.0",
"lucide-react": "^1.64.0",