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

+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({