feat(accounts): the hub as an OpenID Connect provider for T5DE Music (#23)
Release / release (push) Successful in 3s
CI / test (push) Successful in 1m40s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 4s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 3s

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:
dhkatz authored and dhkatz committed 2026-11-19 09:55:03 +00:00
1 parent f05874f800
commit df42b7833a
20 files changed
+6531 -29

No files matched your search

+115 -12
View File
@@ -2,6 +2,7 @@
// origin (Next.js rewrites /api to here), so session cookies are first-party; T5DE's proxy calls it with a bearer
// token.
import { Elysia, t } from "elysia";
import { createLocalJWKSet, jwtVerify, type JSONWebKeySet } from "jose";
import {
and,
asc,
@@ -20,7 +21,7 @@ import {
type ParentInfo,
type RoomModerator,
} from "@t5de/db";
import { passwordRules, usernameRules, validUsername, type Auth } from "./auth";
import { hubResource, 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";
@@ -168,6 +169,34 @@ export function createApp({
const hosted = new HostedRooms(db);
const decorations = new Decorations(db);
const apiBase = (apiURL ?? "http://localhost:4101").replace(/\/+$/, "");
/**
* An OAuth access token for the hub's API (a JWT the hub signed for its resource, docs/music.md): the person it's
* for and its scopes, or undefined if it isn't one. Keys from the JWT plugin's JWKS, kept ten minutes (and fetched
* again when a token names a key not seen yet).
*/
let jwks: { set: ReturnType<typeof createLocalJWKSet>; at: number } | undefined;
const keys = async (fresh = false) => {
if (!jwks || fresh || Date.now() - jwks.at > 10 * 60 * 1000)
jwks = { set: createLocalJWKSet((await auth.api.getJwks()) as JSONWebKeySet), at: Date.now() };
return jwks.set;
};
const accessToken = async (token: string) => {
const options = { issuer: `${apiBase}/api/auth`, audience: hubResource(apiBase), typ: "at+jwt", requiredClaims: ["sub", "azp"] };
let payload;
try {
({ payload } = await jwtVerify(token, await keys(), options));
} catch (e) {
if ((e as { code?: string }).code !== "ERR_JWKS_NO_MATCHING_KEY") return undefined;
try {
({ payload } = await jwtVerify(token, await keys(true), options));
} catch {
return undefined;
}
}
const scopes = typeof payload.scope === "string" ? payload.scope.split(" ") : [];
return { userId: String(payload.sub), clientId: String(payload.azp), scopes };
};
const realtime =
rt ??
new Realtime({
@@ -893,6 +922,21 @@ export function createApp({
.derive(async ({ request }) => {
// An API token: only routes open to scripts (`scripted`) take it; everywhere else it's signed out.
const bearer = request.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1];
// An OAuth access token from one of T5DE's sites (a JWT: three parts): only routes for them (`linking`) take it.
if (bearer && !bearer.startsWith(tokenPrefix) && bearer.split(".").length === 3) {
const tok = await accessToken(bearer);
const owner = tok ? (await db.select().from(user).where(eq(user.id, tok.userId)))[0] : undefined;
const ok = tok && owner && !owner.banned ? { person: owner, scopes: tok.scopes, clientId: tok.clientId } : undefined;
return {
person: undefined,
waiting: undefined,
basic: undefined,
sessionId: undefined,
tokenPerson: undefined,
oauth: ok,
badToken: !ok,
};
}
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;
@@ -903,6 +947,7 @@ export function createApp({
basic: undefined,
sessionId: undefined,
tokenPerson: tok && ok ? Object.assign(ok, { token: { id: tok.id, name: tok.name, grants: tok.grants } }) : undefined,
oauth: undefined,
badToken: !(tok && ok),
};
}
@@ -918,30 +963,31 @@ export function createApp({
basic: usable?.kind === "basic" ? usable : undefined,
sessionId: s?.session.id,
tokenPerson: undefined,
oauth: undefined,
badToken: false,
};
})
.macro({
/** Signed in: approved, still waiting, or a basic account. */
account: {
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.");
resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (tokenPerson || oauth || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
const me = person ?? waiting ?? basic;
if (!me) throw new Problem(401, "signed_out", "Sign in first.");
return { me };
},
},
signedIn: {
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.");
resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (tokenPerson || oauth || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person };
},
},
moderator: {
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.");
resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (tokenPerson || oauth || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
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.");
@@ -950,14 +996,33 @@ export function createApp({
},
/** Signed in, or an API token (whose grants then limit every permission check). */
scripted: {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => {
resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (badToken) throw new Problem(401, "bad_token", "That token isn't valid: wrong, revoked or expired.");
if (oauth) throw new Problem(403, "token_not_allowed", "This token can't do this.");
if (tokenPerson) return { me: tokenPerson };
notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person };
},
},
/**
* Linking IMVU accounts: signed in on the website (a member), or one of T5DE's sites with the person's access
* token and the `imvu:link` scope (any account, basic ones too: docs/music.md, IMVU linking).
*/
linking: {
resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (badToken) throw new Problem(401, "bad_token", "That token isn't valid: wrong or expired.");
if (oauth) {
if (!oauth.scopes.includes("imvu:link"))
throw new Problem(403, "insufficient_scope", "This token can't link IMVU accounts (it needs the imvu:link scope).");
return { me: oauth.person };
}
if (tokenPerson) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person };
},
},
})
// Who's signed in, and the home page.
@@ -976,6 +1041,19 @@ export function createApp({
},
{ account: true },
)
// A site that signs people in through the hub, by its client ID: its name, for the sign-in and consent pages.
.get(
"/oauth/clients/:clientId",
async ({ params }) => {
const [c] = await db
.select({ name: schema.oauthClient.name, skipConsent: schema.oauthClient.skipConsent, disabled: schema.oauthClient.disabled })
.from(schema.oauthClient)
.where(eq(schema.oauthClient.clientId, params.clientId));
if (!c || c.disabled) throw new Problem(404, "not_found", "No such site.");
return { client: { name: c.name ?? params.clientId, firstParty: c.skipConsent === true } };
},
{ params: t.Object({ clientId: t.String({ minLength: 1, maxLength: 128 }) }) },
)
// 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 }) => {
@@ -1139,6 +1217,31 @@ export function createApp({
},
{ scripted: true, params: imvuIdParam },
)
// A person's IMVU accounts and links in progress, for T5DE's sites (Music) with an imvu:link token, or the website.
.get(
"/account/imvu",
async ({ me }) => {
const links = await db.select().from(imvuLink).where(eq(imvuLink.userId, me.id)).orderBy(imvuLink.linkedAt);
const challenges = await db
.select()
.from(linkChallenge)
.where(and(eq(linkChallenge.userId, me.id), sql`${linkChallenge.createdAt} > now() - interval '1 day'`))
.orderBy(linkChallenge.createdAt);
return {
links: links.map((l) => ({ imvuId: l.imvuId, username: l.username, linkedAt: l.linkedAt.toISOString() })),
challenges: challenges.map((c) => ({
imvuId: c.imvuId,
username: c.username,
code: c.code,
createdAt: c.createdAt.toISOString(),
expiresAt: new Date(c.createdAt.getTime() + challengeLifetime).toISOString(),
})),
linkCap: me.linkCap,
canLink: links.length < me.linkCap,
};
},
{ linking: true },
)
.post(
"/account/links",
async ({ me, body, set }) => {
@@ -1166,7 +1269,7 @@ export function createApp({
},
};
},
{ signedIn: true, body: t.Object({ username: t.String({ minLength: 1, maxLength: 64 }) }) },
{ linking: true, body: t.Object({ username: t.String({ minLength: 1, maxLength: 64 }) }) },
)
.post(
"/account/links/:imvu/check",
@@ -1234,7 +1337,7 @@ export function createApp({
await realtime.linked(me.id, found.id);
return { link: await linkView(result.link), moved: result.moved };
},
{ signedIn: true, params: imvuIdParam },
{ linking: true, params: imvuIdParam },
)
.delete(
"/account/challenges/:imvu",
@@ -1242,7 +1345,7 @@ export function createApp({
await db.delete(linkChallenge).where(and(eq(linkChallenge.userId, me.id), eq(linkChallenge.imvuId, params.imvu)));
set.status = 204;
},
{ signedIn: true, params: imvuIdParam },
{ linking: true, params: imvuIdParam },
)
.patch(
"/account/links/:imvu",
@@ -1292,7 +1395,7 @@ export function createApp({
await audited(me, "link.remove", String(l.imvuId), { imvu: l.username });
set.status = 204;
},
{ signedIn: true, params: imvuIdParam },
{ linking: true, params: imvuIdParam },
)
.post(
"/account/signout-computers",