// Accounts, sessions and proxy sign-in, by Better Auth: email and password with usernames, roles and bans (admin), // Discord sign-in (basic accounts, docs/music.md), device sign-in for T5DE's proxy (RFC 8628), bearer tokens for the // proxy's requests, JWTs with published keys, two-factor sign-in (an authenticator app, with backup codes), and the // hub as an OAuth 2.1 / OpenID Connect provider for T5DE's own sites (Music first). import { timingSafeEqual } from "node:crypto"; import { oauthProvider } from "@better-auth/oauth-provider"; import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { admin, bearer, deviceAuthorization, jwt, twoFactor, username } from "better-auth/plugins"; import { and, asc, count, eq, schema, type Database } from "@t5de/db"; import { Settings } from "./settings"; export type AuthConfig = { /** The API's own address, e.g. https://hub-api.t5de.dev. */ apiURL: string; /** The website's address, e.g. https://hub.t5de.dev: trusted origin, and where /device is. */ webURL: string; /** At least 32 random characters; signs sessions. */ 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, 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. */ discord?: { clientId: string; clientSecret: string }; /** T5DE's own sites that sign people in through the hub (OpenID Connect): trusted, so there's no consent screen, * and they may ask for the `imvu` scope. Made or updated at startup (seedClients). */ clients?: FirstPartyClient[]; /** Let clients use plain-HTTP redirect URIs on localhost (development only: a client running locally). */ localRedirects?: boolean; }; /** A T5DE site that signs people in through the hub. */ export type FirstPartyClient = { /** e.g. t5de-music */ clientId: string; /** Shown to people, e.g. T5DE Music */ name: string; /** At least 32 random characters; the hub keeps only its hash. */ secret: string; /** Where the hub may send people back with a code, e.g. https://music.t5de.dev/api/auth/callback */ redirectUris: string[]; }; /** * What OpenID Connect clients may ask for. `imvu`: the person's linked IMVU accounts, real IDs and names (first-party * sites only: they act in IMVU rooms). `imvu:link`: link and unlink IMVU accounts on the person's behalf, through the * hub's API. */ export const oauthScopes = ["openid", "profile", "email", "offline_access", "imvu", "imvu:link"] as const; /** The hub's own API as an OAuth resource: access tokens for it (`resource` in the request) are JWTs it checks. */ export const hubResource = (apiURL: string) => `${apiURL.replace(/\/+$/, "")}/api/v1`; /** How client secrets are kept (SHA-256, base64url); seedClients stores first-party secrets the same way. */ async function hashSecret(secret: string): Promise { return Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret))).toString("base64url"); } async function verifySecret(secret: string, stored: string): Promise { const a = Buffer.from(await hashSecret(secret)); const b = Buffer.from(stored); return a.length === b.length && timingSafeEqual(a, b); } /** A person's linked IMVU accounts, as the `imvu` claim gives them. */ async function imvuClaim(db: Database, userId: string) { return db .select({ id: schema.imvuLink.imvuId, username: schema.imvuLink.username }) .from(schema.imvuLink) .where(eq(schema.imvuLink.userId, userId)) .orderBy(asc(schema.imvuLink.linkedAt)); } /** The proxy's client ID in device sign-in. */ export const proxyClientID = "t5de-proxy"; /** Usernames: letters, digits and underscores; imvu_ 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({ baseURL: config.apiURL, basePath: "/api/auth", secret: config.secret, trustedOrigins: [config.webURL], database: drizzleAdapter(db, { provider: "pg", schema }), // The JWT plugin's /token (a session as a JWT) is off: the OAuth provider issues tokens instead. disabledPaths: ["/token"], 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. session: { expiresIn: 60 * 60 * 24 * 60, updateAge: 60 * 60 * 24 }, rateLimit: { enabled: config.rateLimit !== false, window: 60, max: 100 }, advanced: { ipAddress: { ipAddressHeaders: ["cf-connecting-ip", "x-forwarded-for"] } }, databaseHooks: { user: { 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 (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: (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; const approved = first || (await settings.registration()) === "open"; return { data: { ...u, role: first ? "admin" : "user", approved, kind: "member" } }; }, }, }, }, plugins: [ username({ minUsernameLength: usernameRules.min, maxUsernameLength: usernameRules.max, usernameValidator: validUsername, }), admin({ defaultRole: "user", adminRoles: ["admin"] }), deviceAuthorization({ verificationUri: `${config.webURL}/device`, expiresIn: "10m", interval: "3s", validateClient: (clientId) => clientId === proxyClientID, }), bearer(), // Once it's on, signing in asks for a code from the app (or a backup code). The hub's own routes require it for // sensitive permissions (permissions.ts `sensitive`). twoFactor({ issuer: "T5DE", backupCodeOptions: { amount: 10, length: 10 } }), jwt({ jwks: { keyPairConfig: { alg: "EdDSA", crv: "Ed25519" } }, disableSettingJwtHeader: true }), // The issuer is API_URL/api/auth (discovery at /api/auth/.well-known/openid-configuration). People sign in on the // website's /signin, which sends them back to the authorize endpoint; trusted clients skip /consent. 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 }, allowInsecureRedirectUri: (url) => config.localRedirects === true && ["localhost", "127.0.0.1"].includes(url.hostname), resources: [{ identifier: hubResource(config.apiURL), name: "T5DE Hub API", allowedScopes: [...oauthScopes] }], advertisedMetadata: { scopes_supported: [...oauthScopes], claims_supported: [ "sub", "iss", "aud", "exp", "iat", "sid", "scope", "azp", "name", "preferred_username", "email", "email_verified", "picture", "imvu", ], }, customUserInfoClaims: async ({ user, scopes }) => ({ ...(scopes.includes("profile") && typeof user.username === "string" ? { preferred_username: typeof user.displayUsername === "string" ? user.displayUsername : user.username } : {}), ...(scopes.includes("imvu") ? { imvu: await imvuClaim(db, user.id) } : {}), }), customIdTokenClaims: async ({ user, scopes }) => (scopes.includes("imvu") ? { imvu: await imvuClaim(db, user.id) } : {}), }), ], }); } export type Auth = ReturnType; /** * Makes or updates T5DE's own sites as OAuth clients: their secret's hash, redirect URIs and scopes, trusted (no * consent screen), and allowed to ask for tokens for the hub's API. Run at startup, before serving. */ export async function seedClients(db: Database, apiURL: string, clients: FirstPartyClient[]) { const now = new Date(); const resource = hubResource(apiURL); for (const c of clients) { if (c.secret.length < 32) throw new Error(`${c.clientId}: the client secret needs at least 32 characters`); if (c.redirectUris.length === 0) throw new Error(`${c.clientId}: no redirect URIs`); const values = { clientSecret: await hashSecret(c.secret), name: c.name, redirectUris: c.redirectUris, scopes: [...oauthScopes], skipConsent: true, disabled: false, subjectType: "public", tokenEndpointAuthMethod: "client_secret_basic", grantTypes: ["authorization_code", "refresh_token"], responseTypes: ["code"], applicationType: "web", requirePKCE: true, updatedAt: now, }; await db .insert(schema.oauthClient) .values({ id: crypto.randomUUID(), clientId: c.clientId, createdAt: now, ...values }) .onConflictDoUpdate({ target: schema.oauthClient.clientId, set: values }); } // Each may ask for tokens for the hub's API (the plugin checks this link). The resource row is the plugin's // (`resources` above, made when it starts); made here too in case this runs first. await db .insert(schema.oauthResource) .values({ id: crypto.randomUUID(), identifier: resource, name: "T5DE Hub API", allowedScopes: [...oauthScopes], createdAt: now, updatedAt: now }) .onConflictDoNothing({ target: schema.oauthResource.identifier }); for (const c of clients) { const [linked] = await db .select({ id: schema.oauthClientResource.id }) .from(schema.oauthClientResource) .where(and(eq(schema.oauthClientResource.clientId, c.clientId), eq(schema.oauthClientResource.resourceId, resource))); if (!linked) await db.insert(schema.oauthClientResource).values({ id: crypto.randomUUID(), clientId: c.clientId, resourceId: resource, createdAt: now }); } }