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

+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 }) => {