feat(accounts): the hub as an OpenID Connect provider for T5DE Music (#23)
Second half of docs/music.md's phase 1: the hub as an OAuth 2.1 / OpenID Connect provider, with T5DE Music as its first client. Builds on #22 (merged). **Provider** (`@better-auth/oauth-provider` 1.7.26): issuer `API_URL/api/auth` (prod: `https://hub.t5de.dev/api/auth`), discovery at `/api/auth/.well-known/openid-configuration`, keys from the existing JWT plugin (Ed25519). The JWT plugin's `/token` route is off (nothing used it). Seven tables (migration `0022_oauth_provider`). - **Music** (`t5de-music`) is made at startup from `MUSIC_CLIENT_SECRET` and `MUSIC_REDIRECT_URIS`: trusted (no consent screen), confidential, PKCE required, HTTPS redirect URIs only (plain HTTP on localhost in development). Its secret is stored as a SHA-256 hash the hub supplies (`storeClientSecret`), so seeding and the plugin agree. Dynamic client registration stays off. - **Scopes**: `openid profile email offline_access`, `imvu` (the person's linked IMVU accounts, real IDs and names, in the ID token and userinfo: first-party sites only, as the plan says) and `imvu:link`. - **The hub's API as a resource**: Music asks for `resource=API_URL/api/v1` and gets a JWT access token (`at+jwt`, that audience). The API checks it against its own keys. Routes for sites (`linking`): `GET /api/v1/account/imvu` and the existing link routes (start, check, cancel, unlink), for any account including basic ones. Every other route answers such a token 403 `token_not_allowed`, and a token without `imvu:link` 403 `insufficient_scope`. **Website**: `/signin` opened by authorize ("Sign in with your T5DE account to continue to T5DE Music") sends people back to authorize once signed in, by password or Discord. `t5de_provider=discord` in Music's request starts Discord at once, so "Sign in with Discord" on Music goes straight to Discord. `/consent` for sites added later. `GET /api/v1/oauth/clients/:id` names the site. Second half of docs/music.md's phase 1: the hub as an OAuth 2.1 / OpenID Connect provider, with T5DE Music as its first client. Builds on #22 (merged). **Provider** (`@better-auth/oauth-provider` 1.7.26): issuer `API_URL/api/auth` (prod: `https://hub.t5de.dev/api/auth`), discovery at `/api/auth/.well-known/openid-configuration`, keys from the existing JWT plugin (Ed25519). The JWT plugin's `/token` route is off (nothing used it). Seven tables (migration `0022_oauth_provider`). - **Music** (`t5de-music`) is made at startup from `MUSIC_CLIENT_SECRET` and `MUSIC_REDIRECT_URIS`: trusted (no consent screen), confidential, PKCE required, HTTPS redirect URIs only (plain HTTP on localhost in development). Its secret is stored as a SHA-256 hash the hub supplies (`storeClientSecret`), so seeding and the plugin agree. Dynamic client registration stays off. - **Scopes**: `openid profile email offline_access`, `imvu` (the person's linked IMVU accounts, real IDs and names, in the ID token and userinfo: first-party sites only, as the plan says) and `imvu:link`. - **The hub's API as a resource**: Music asks for `resource=API_URL/api/v1` and gets a JWT access token (`at+jwt`, that audience). The API checks it against its own keys. Routes for sites (`linking`): `GET /api/v1/account/imvu` and the existing link routes (start, check, cancel, unlink), for any account including basic ones. Every other route answers such a token 403 `token_not_allowed`, and a token without `imvu:link` 403 `insufficient_scope`. **Website**: `/signin` opened by authorize ("Sign in with your T5DE account to continue to T5DE Music") sends people back to authorize once signed in, by password or Discord. `t5de_provider=discord` in Music's request starts Discord at once, so "Sign in with Discord" on Music goes straight to Discord. `/consent` for sites added later. `GET /api/v1/oauth/clients/:id` names the site. Tests: `apps/api/test/oidc.test.ts` runs Music's whole flow against the API (discovery, sign-in redirect with the hint, code + PKCE, token, ID token and userinfo claims, the access token on link routes and refused elsewhere, scopes, a basic account linking through Music). Full suite 75/75; `check-types` and `build` pass. Not checked in a browser yet. **Not in this PR** (later phases): merging a basic account into a member (`user.merged`), pairwise subjects and the console for third-party clients, `@imvu/verify` in place of the hub's link code. Deploying: `MUSIC_CLIENT_SECRET` (32+ random characters, shared with Music's stack) and `MUSIC_REDIRECT_URIS=https://music.t5de.dev/api/auth/callback` in the hub stacks (dhkatz/infra), with Music's own stack. Tests: `apps/api/test/oidc.test.ts` runs Music's whole flow against the API (discovery, sign-in redirect with the hint, code + PKCE, token, ID token and userinfo claims, the access token on link routes and refused elsewhere, scopes, a basic account linking through Music). Full suite 75/75; `check-types` and `build` pass. Not checked in a browser yet. **Not in this PR** (later phases): merging a basic account into a member (`user.merged`), pairwise subjects and the console for third-party clients, `@imvu/verify` in place of the hub's link code. Deploying: `MUSIC_CLIENT_SECRET` (32+ random characters, shared with Music's stack) and `MUSIC_REDIRECT_URIS=https://music.t5de.dev/api/auth/callback` in the hub stacks (dhkatz/infra), with Music's own stack. Co-authored-by: dhkatz <[email protected]>
This commit was merged in pull request #23.
This commit is contained in:
1 parent
f05874f800
commit
df42b7833a
20 files changed
+6531
-29
No files matched your search
+125
-4
@@ -1,11 +1,13 @@
|
||||
// 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, and JWTs with published keys (for catalogs later), and two-factor sign-in (an authenticator app,
|
||||
// with backup codes).
|
||||
// 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 { count, eq, schema, type Database } from "@t5de/db";
|
||||
import { and, asc, count, eq, schema, type Database } from "@t5de/db";
|
||||
import { Settings } from "./settings";
|
||||
|
||||
export type AuthConfig = {
|
||||
@@ -22,8 +24,54 @@ export type AuthConfig = {
|
||||
/** 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<string> {
|
||||
return Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret))).toString("base64url");
|
||||
}
|
||||
async function verifySecret(secret: string, stored: string): Promise<boolean> {
|
||||
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";
|
||||
|
||||
@@ -52,6 +100,8 @@ export function createAuth(db: Database, config: AuthConfig) {
|
||||
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 } }
|
||||
@@ -125,9 +175,80 @@ export function createAuth(db: Database, config: AuthConfig) {
|
||||
// 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" } } }),
|
||||
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`,
|
||||
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<typeof createAuth>;
|
||||
|
||||
/**
|
||||
* 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 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user