The hub as an OpenID Connect provider for T5DE Music
Pull request / title (pull_request) Successful in 1s
CI / test (pull_request) Successful in 1m30s
CI / image (apps/api/Dockerfile, t5de-hub-api) (pull_request) Skipped
CI / image (apps/web/Dockerfile, t5de-hub-web) (pull_request) Skipped

This commit is contained in:
dhkatz committed 2026-11-19 01:22:33 -08:00
1 parent f0a9661f8e
commit 096ee32fa5
20 files changed
+6531 -29

No files matched your search

+3
View File
@@ -16,6 +16,9 @@ payments in [docs/payments.md](docs/payments.md).
no username or password) for T5DE's other sites, such as Music (docs/music.md); it finishes setting up no username or password) for T5DE's other sites, such as Music (docs/music.md); it finishes setting up
with a username and password to use the hub. Members link Discord from their account page. Accounts are with a username and password to use the hub. Members link Discord from their account page. Accounts are
never linked by matching email. never linked by matching email.
- **Signing in on T5DE's other sites**: the hub is an OpenID Connect provider (issuer `<API_URL>/api/auth`) for
T5DE Music (`MUSIC_CLIENT_SECRET`, `MUSIC_REDIRECT_URIS`), with an `imvu` scope for the person's linked IMVU
accounts and `imvu:link` for linking them from Music (docs/api.md).
- **Linking IMVU accounts**: the person puts a code in the account's tagline; the hub reads it from IMVU's public - **Linking IMVU accounts**: the person puts a code in the account's tagline; the hub reads it from IMVU's public
API. The most recent proof wins (an account linked elsewhere moves, with a new pairwise ID). Link caps per person API. The most recent proof wins (an account linked elsewhere moves, with a new pairwise ID). Link caps per person
(default 10). (default 10).
+1
View File
@@ -12,6 +12,7 @@
"check-types": "tsc --noEmit" "check-types": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@better-auth/oauth-provider": "1.7.26",
"@t5de/db": "workspace:*", "@t5de/db": "workspace:*",
"better-auth": "1.7.26", "better-auth": "1.7.26",
"elysia": "1.4.30", "elysia": "1.4.30",
+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 // origin (Next.js rewrites /api to here), so session cookies are first-party; T5DE's proxy calls it with a bearer
// token. // token.
import { Elysia, t } from "elysia"; import { Elysia, t } from "elysia";
import { createLocalJWKSet, jwtVerify, type JSONWebKeySet } from "jose";
import { import {
and, and,
asc, asc,
@@ -20,7 +21,7 @@ import {
type ParentInfo, type ParentInfo,
type RoomModerator, type RoomModerator,
} from "@t5de/db"; } 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 { AgeError, AgeRefused, AgeService } from "./age";
import { imvuAgeProvider, imvuResult } from "./age/imvu"; import { imvuAgeProvider, imvuResult } from "./age/imvu";
import { ImvuClient, ImvuUnavailable, NoSuchImvuUser } from "./imvu"; import { ImvuClient, ImvuUnavailable, NoSuchImvuUser } from "./imvu";
@@ -168,6 +169,34 @@ export function createApp({
const hosted = new HostedRooms(db); const hosted = new HostedRooms(db);
const decorations = new Decorations(db); const decorations = new Decorations(db);
const apiBase = (apiURL ?? "http://localhost:4101").replace(/\/+$/, ""); 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 = const realtime =
rt ?? rt ??
new Realtime({ new Realtime({
@@ -893,6 +922,21 @@ export function createApp({
.derive(async ({ request }) => { .derive(async ({ request }) => {
// An API token: only routes open to scripts (`scripted`) take it; everywhere else it's signed out. // 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]; 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)) { if (bearer?.startsWith(tokenPrefix)) {
const tok = await tokens.verify(bearer); const tok = await tokens.verify(bearer);
const owner = tok ? (await db.select().from(user).where(eq(user.id, tok.userId)))[0] : undefined; 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, basic: undefined,
sessionId: undefined, sessionId: undefined,
tokenPerson: tok && ok ? Object.assign(ok, { token: { id: tok.id, name: tok.name, grants: tok.grants } }) : undefined, tokenPerson: tok && ok ? Object.assign(ok, { token: { id: tok.id, name: tok.name, grants: tok.grants } }) : undefined,
oauth: undefined,
badToken: !(tok && ok), badToken: !(tok && ok),
}; };
} }
@@ -918,30 +963,31 @@ export function createApp({
basic: usable?.kind === "basic" ? usable : undefined, basic: usable?.kind === "basic" ? usable : undefined,
sessionId: s?.session.id, sessionId: s?.session.id,
tokenPerson: undefined, tokenPerson: undefined,
oauth: undefined,
badToken: false, badToken: false,
}; };
}) })
.macro({ .macro({
/** Signed in: approved, still waiting, or a basic account. */ /** Signed in: approved, still waiting, or a basic account. */
account: { account: {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => { resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website."); 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; const me = person ?? waiting ?? basic;
if (!me) throw new Problem(401, "signed_out", "Sign in first."); if (!me) throw new Problem(401, "signed_out", "Sign in first.");
return { me }; return { me };
}, },
}, },
signedIn: { signedIn: {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => { resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website."); 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); notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first."); if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person }; return { me: person };
}, },
}, },
moderator: { moderator: {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => { resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website."); 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); notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first."); if (!person) throw new Problem(401, "signed_out", "Sign in first.");
if (!isModerator(person)) throw new Problem(403, "forbidden", "Only moderators can do this."); 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). */ /** Signed in, or an API token (whose grants then limit every permission check). */
scripted: { 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 (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 }; if (tokenPerson) return { me: tokenPerson };
notMemberYet(waiting, basic); notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first."); if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person }; 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. // Who's signed in, and the home page.
@@ -976,6 +1041,19 @@ export function createApp({
}, },
{ account: true }, { 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. // 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("/hub", async () => ({ registration: await settings.registration(), discord: discordOn }))
.get("/home", async ({ person }) => { .get("/home", async ({ person }) => {
@@ -1139,6 +1217,31 @@ export function createApp({
}, },
{ scripted: true, params: imvuIdParam }, { 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( .post(
"/account/links", "/account/links",
async ({ me, body, set }) => { 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( .post(
"/account/links/:imvu/check", "/account/links/:imvu/check",
@@ -1234,7 +1337,7 @@ export function createApp({
await realtime.linked(me.id, found.id); await realtime.linked(me.id, found.id);
return { link: await linkView(result.link), moved: result.moved }; return { link: await linkView(result.link), moved: result.moved };
}, },
{ signedIn: true, params: imvuIdParam }, { linking: true, params: imvuIdParam },
) )
.delete( .delete(
"/account/challenges/:imvu", "/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))); await db.delete(linkChallenge).where(and(eq(linkChallenge.userId, me.id), eq(linkChallenge.imvuId, params.imvu)));
set.status = 204; set.status = 204;
}, },
{ signedIn: true, params: imvuIdParam }, { linking: true, params: imvuIdParam },
) )
.patch( .patch(
"/account/links/:imvu", "/account/links/:imvu",
@@ -1292,7 +1395,7 @@ export function createApp({
await audited(me, "link.remove", String(l.imvuId), { imvu: l.username }); await audited(me, "link.remove", String(l.imvuId), { imvu: l.username });
set.status = 204; set.status = 204;
}, },
{ signedIn: true, params: imvuIdParam }, { linking: true, params: imvuIdParam },
) )
.post( .post(
"/account/signout-computers", "/account/signout-computers",
+125 -4
View File
@@ -1,11 +1,13 @@
// Accounts, sessions and proxy sign-in, by Better Auth: email and password with usernames, roles and bans (admin), // 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 // 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, // proxy's requests, JWTs with published keys, two-factor sign-in (an authenticator app, with backup codes), and the
// with backup codes). // 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 { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { admin, bearer, deviceAuthorization, jwt, twoFactor, username } from "better-auth/plugins"; 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"; import { Settings } from "./settings";
export type AuthConfig = { 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); /** Discord sign-in (an application at discord.com/developers, redirecting to API_URL/api/auth/callback/discord);
* off without it. */ * off without it. */
discord?: { clientId: string; clientSecret: string }; 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. */ /** The proxy's client ID in device sign-in. */
export const proxyClientID = "t5de-proxy"; export const proxyClientID = "t5de-proxy";
@@ -52,6 +100,8 @@ export function createAuth(db: Database, config: AuthConfig) {
secret: config.secret, secret: config.secret,
trustedOrigins: [config.webURL], trustedOrigins: [config.webURL],
database: drizzleAdapter(db, { provider: "pg", schema }), 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 }, emailAndPassword: { enabled: true, minPasswordLength: passwordRules.min, maxPasswordLength: passwordRules.max },
socialProviders: config.discord socialProviders: config.discord
? { discord: { clientId: config.discord.clientId, clientSecret: config.discord.clientSecret } } ? { 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 // 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`). // sensitive permissions (permissions.ts `sensitive`).
twoFactor({ issuer: "T5DE", backupCodeOptions: { amount: 10, length: 10 } }), 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>; 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 });
}
}
+21 -2
View File
@@ -8,6 +8,10 @@
// DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET // DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET
// Discord sign-in (basic accounts, docs/music.md); its redirect URL is // Discord sign-in (basic accounts, docs/music.md); its redirect URL is
// API_URL/api/auth/callback/discord. Off unless both are set. // API_URL/api/auth/callback/discord. Off unless both are set.
// MUSIC_CLIENT_SECRET, MUSIC_REDIRECT_URIS
// T5DE Music (docs/music.md) as an OpenID Connect client of the hub, client ID t5de-music: its
// secret (at least 32 characters) and redirect URIs, comma-separated (e.g.
// https://music.t5de.dev/api/auth/callback). The issuer is API_URL/api/auth.
// AGE_PROVIDERS ways to verify age, comma-separated (default imvu): imvu, didit // AGE_PROVIDERS ways to verify age, comma-separated (default imvu): imvu, didit
// DIDIT_API_KEY, DIDIT_WORKFLOW_ID, DIDIT_WEBHOOK_SECRET // DIDIT_API_KEY, DIDIT_WORKFLOW_ID, DIDIT_WEBHOOK_SECRET
// Didit's ID document check (docs/design.md, "Age"); its webhook is API_URL/api/v1/age/webhook/didit // Didit's ID document check (docs/design.md, "Age"); its webhook is API_URL/api/v1/age/webhook/didit
@@ -18,7 +22,7 @@ import { AgeService, type Provider } from "./age";
import { diditAgeProvider } from "./age/didit"; import { diditAgeProvider } from "./age/didit";
import { imvuAgeProvider } from "./age/imvu"; import { imvuAgeProvider } from "./age/imvu";
import { createApp } from "./app"; import { createApp } from "./app";
import { createAuth } from "./auth"; import { createAuth, seedClients, type FirstPartyClient } from "./auth";
import { Settings } from "./settings"; import { Settings } from "./settings";
import { ImvuClient } from "./imvu"; import { ImvuClient } from "./imvu";
@@ -39,7 +43,22 @@ const discord =
env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET
? { clientId: env.DISCORD_CLIENT_ID, clientSecret: env.DISCORD_CLIENT_SECRET } ? { clientId: env.DISCORD_CLIENT_ID, clientSecret: env.DISCORD_CLIENT_SECRET }
: undefined; : undefined;
const auth = createAuth(db, { apiURL, webURL, secret, settings, discord }); const clients: FirstPartyClient[] = [];
if (env.MUSIC_CLIENT_SECRET)
clients.push({
clientId: "t5de-music",
name: "T5DE Music",
secret: env.MUSIC_CLIENT_SECRET,
redirectUris: (env.MUSIC_REDIRECT_URIS ?? "").split(",").map((u) => u.trim()).filter(Boolean),
});
// In development, Music runs on http://localhost too.
const auth = createAuth(db, { apiURL, webURL, secret, settings, discord, clients, localRedirects: dev });
try {
await seedClients(db, apiURL, clients);
} catch (e) {
console.error("OAuth clients:", (e as Error).message);
process.exit(1);
}
const imvu = new ImvuClient(); const imvu = new ImvuClient();
function required(name: string): string { function required(name: string): string {
+187
View File
@@ -0,0 +1,187 @@
// The hub as an OpenID Connect provider (docs/music.md): T5DE Music signs people in with the authorization code flow
// (PKCE), gets their linked IMVU accounts from the `imvu` scope, and links IMVU accounts through the hub's API with an
// access token for it (`imvu:link`).
import { afterAll, beforeAll, expect, test } from "bun:test";
import { eq, openDatabase, schema, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth, hubResource, seedClients } from "../src/auth";
import { ImvuClient } from "../src/imvu";
import { Settings } from "../src/settings";
const webURL = "http://web.test";
const apiURL = "http://api.test";
const music = {
clientId: "t5de-music",
name: "T5DE Music",
secret: "music-secret-music-secret-music-secret-1234",
redirectUris: ["https://music.test/api/auth/callback"],
};
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
const settings = new Settings(db, { registration: "open" });
const auth = createAuth(db, { apiURL, webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false, settings, clients: [music] });
await seedClients(db, apiURL, [music]);
const imvu = new ImvuClient("http://imvu.test", (async () => Response.json({ denormalized: {} })) as unknown as typeof fetch);
const hub = createApp({ db, auth, imvu, webURL, apiURL, settings });
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
stop();
await close();
});
type Cookie = { v: string };
async function call(cookie: Cookie, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
const form = body instanceof URLSearchParams;
const res = await fetch(base + path, {
method,
redirect: "manual",
headers: {
Origin: webURL,
...(body !== undefined ? { "Content-Type": form ? "application/x-www-form-urlencoded" : "application/json" } : {}),
...(cookie.v ? { Cookie: cookie.v } : {}),
...headers,
},
body: body === undefined ? undefined : form ? body.toString() : JSON.stringify(body),
});
const set = res.headers.getSetCookie();
if (set.length) cookie.v = set.map((c) => c.split(";")[0]).join("; ");
const text = await res.text();
let json: any;
try {
json = text ? JSON.parse(text) : undefined;
} catch {}
return { status: res.status, json, location: res.headers.get("location") ?? "" };
}
async function signUp(name: string) {
const cookie = { v: "" };
expect((await call(cookie, "POST", "/api/auth/sign-up/email", { email: `${name}@example.test`, password: "a long password", name, username: name })).status).toBe(200);
return cookie;
}
const b64url = (b: ArrayBuffer | Uint8Array) => Buffer.from(b as ArrayBuffer).toString("base64url");
/** Music's side: the authorize request, with PKCE and the hub's API as the token's resource. */
async function authorizeURL(scope: string, extra: Record<string, string> = {}) {
const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
const challenge = b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
const q = new URLSearchParams({
response_type: "code",
client_id: music.clientId,
redirect_uri: music.redirectUris[0]!,
scope,
state: "st-" + verifier.slice(0, 6),
code_challenge: challenge,
code_challenge_method: "S256",
resource: hubResource(apiURL),
...extra,
});
return { path: `/api/auth/oauth2/authorize?${q}`, verifier, state: q.get("state")! };
}
/** Music signs `cookie`'s person in: authorize (signed in already), then the code for tokens. */
async function musicSignIn(cookie: Cookie, scope = "openid profile email offline_access imvu imvu:link") {
const a = await authorizeURL(scope);
const r = await call(cookie, "GET", a.path);
expect(r.status).toBe(302);
const back = new URL(r.location);
expect(back.origin + back.pathname).toBe(music.redirectUris[0]!);
expect(back.searchParams.get("state")).toBe(a.state);
const code = back.searchParams.get("code")!;
const token = await call(
{ v: "" },
"POST",
"/api/auth/oauth2/token",
new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: music.redirectUris[0]!, code_verifier: a.verifier, resource: hubResource(apiURL) }),
{ Authorization: "Basic " + Buffer.from(`${music.clientId}:${music.secret}`).toString("base64") },
);
expect(token.status).toBe(200);
return token.json as { access_token: string; id_token: string; refresh_token?: string; scope: string };
}
const bearer = (t: string) => ({ Authorization: `Bearer ${t}` });
test("discovery: the issuer is the API's /api/auth", async () => {
const d = (await call({ v: "" }, "GET", "/api/auth/.well-known/openid-configuration")).json;
expect(d.issuer).toBe(`${apiURL}/api/auth`);
expect(d.scopes_supported).toEqual(expect.arrayContaining(["openid", "imvu", "imvu:link"]));
expect(d.jwks_uri).toBe(`${apiURL}/api/auth/jwks`);
});
test("the sign-in page can name the site asking", async () => {
expect((await call({ v: "" }, "GET", `/api/v1/oauth/clients/${music.clientId}`)).json).toEqual({ client: { name: "T5DE Music", firstParty: true } });
expect((await call({ v: "" }, "GET", "/api/v1/oauth/clients/nobody")).status).toBe(404);
});
test("signed out, authorize sends people to the website's sign-in page with the request", async () => {
const a = await authorizeURL("openid profile imvu", { t5de_provider: "discord" });
const r = await call({ v: "" }, "GET", a.path);
expect(r.status).toBe(302);
const to = new URL(r.location);
expect(to.origin + to.pathname).toBe(`${webURL}/signin`);
expect(to.searchParams.get("client_id")).toBe(music.clientId);
expect(to.searchParams.get("sig")).toBeTruthy();
// The hint for the sign-in page comes along.
expect(to.searchParams.get("t5de_provider")).toBe("discord");
});
test("Music signs a member in without a consent screen, and gets their IMVU accounts", async () => {
const ada = await signUp("ada");
const me = (await call(ada, "GET", "/api/v1/me")).json.person;
await db.insert(schema.imvuLink).values({ imvuId: 4242, userId: me.id, pairwiseId: "pw-4242", username: "AdaInIMVU" });
const t = await musicSignIn(ada);
expect(t.scope.split(" ")).toEqual(expect.arrayContaining(["openid", "imvu", "imvu:link"]));
expect(t.refresh_token).toBeTruthy();
// The ID token carries the IMVU accounts.
const idClaims = JSON.parse(Buffer.from(t.id_token.split(".")[1]!, "base64url").toString());
expect(idClaims).toMatchObject({ iss: `${apiURL}/api/auth`, aud: music.clientId, sub: me.id, imvu: [{ id: 4242, username: "AdaInIMVU" }] });
const info = (await call({ v: "" }, "GET", "/api/auth/oauth2/userinfo", undefined, bearer(t.access_token))).json;
expect(info).toMatchObject({ sub: me.id, preferred_username: "ada", email: "[email protected]", imvu: [{ id: 4242, username: "AdaInIMVU" }] });
// The access token works on the routes for T5DE's sites, and only those.
const imvu = await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer(t.access_token));
expect(imvu.status).toBe(200);
expect(imvu.json.links).toEqual([expect.objectContaining({ imvuId: 4242, username: "AdaInIMVU" })]);
expect((await call({ v: "" }, "GET", "/api/v1/account", undefined, bearer(t.access_token))).json.error).toBe("token_not_allowed");
expect((await call({ v: "" }, "GET", "/api/v1/me", undefined, bearer(t.access_token))).json.error).toBe("token_not_allowed");
// A token that isn't the hub's.
expect((await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer("aaa.bbb.ccc"))).status).toBe(401);
});
test("without imvu and imvu:link, Music gets no IMVU accounts and can't link", async () => {
const bo = await signUp("bo_");
const t = await musicSignIn(bo, "openid profile");
const info = (await call({ v: "" }, "GET", "/api/auth/oauth2/userinfo", undefined, bearer(t.access_token))).json;
expect(info.imvu).toBeUndefined();
expect((await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer(t.access_token))).json.error).toBe("insufficient_scope");
});
test("a basic account links IMVU accounts through Music; the website still says finish setting up", async () => {
// A basic account, as Discord sign-in makes them (discord.test.ts covers that part).
const cy = await signUp("cyd");
const id = (await call(cy, "GET", "/api/v1/me")).json.person.id;
await db.update(schema.user).set({ kind: "basic", username: null, displayUsername: null }).where(eq(schema.user.id, id));
const t = await musicSignIn(cy);
const imvu = await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer(t.access_token));
expect(imvu).toMatchObject({ status: 200, json: { links: [], canLink: true } });
expect((await call(cy, "GET", "/api/v1/account/imvu")).json.error).toBe("finish_setup");
});
test("a website session still links as before", async () => {
const dee = await signUp("dee");
expect((await call(dee, "GET", "/api/v1/account/imvu")).status).toBe(200);
});
+45
View File
@@ -0,0 +1,45 @@
"use client";
// Allow or deny a site's request. The provider's client plugin sends the page's signed request (oauth_query) along,
// and answers with where to go next: back to the site, with a code or with access_denied.
import { oauthProviderClient } from "@better-auth/oauth-provider/client";
import { createAuthClient } from "better-auth/react";
import { useState } from "react";
import { ErrorText } from "@/components/forms";
import { Button } from "@/components/ui/button";
const consentClient = createAuthClient({
baseURL: typeof window === "undefined" ? undefined : window.location.origin,
plugins: [oauthProviderClient()],
});
export function ConsentForm() {
const [pending, setPending] = useState<"allow" | "deny" | null>(null);
const [error, setError] = useState("");
async function answer(accept: boolean) {
setPending(accept ? "allow" : "deny");
setError("");
const { data, error } = await consentClient.oauth2.consent({ accept });
const url = data && typeof data === "object" && "url" in data ? (data as { url?: string }).url : undefined;
if (error || !url) {
setError(error?.message ?? "That didn't work. Start again from the site.");
setPending(null);
return;
}
window.location.assign(url);
}
return (
<div className="space-y-3">
<div className="flex gap-2">
<Button type="button" disabled={pending !== null} onClick={() => void answer(true)}>
{pending === "allow" ? "Allowing…" : "Allow"}
</Button>
<Button type="button" variant="outline" disabled={pending !== null} onClick={() => void answer(false)}>
{pending === "deny" ? "Denying…" : "Deny"}
</Button>
</div>
{error && <ErrorText>{error}</ErrorText>}
</div>
);
}
+42
View File
@@ -0,0 +1,42 @@
// Another site asks to sign the person in with their T5DE account. T5DE's own sites (Music) are trusted and never get
// here; this is for sites added later (docs/music.md, The OIDC provider).
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { NarrowCard } from "@/components/narrow-card";
import { api, getMe } from "@/lib/api";
import { ConsentForm } from "./consent-form";
export const metadata: Metadata = { title: "Allow Access" };
/** What each scope lets a site see or do, in words. */
const scopeText: Record<string, string> = {
openid: "Know it's you",
profile: "Your name and username",
email: "Your email address",
offline_access: "Stay signed in when you're away",
imvu: "Your linked IMVU accounts",
"imvu:link": "Link and unlink IMVU accounts for you",
};
export default async function Consent({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
const params = await searchParams;
const me = await getMe();
if (!me) redirect("/signin");
const clientId = typeof params.client_id === "string" ? params.client_id : "";
const site = clientId ? (await api.oauth.clients({ clientId }).get()).data : undefined;
const name = site && "client" in site ? site.client.name : undefined;
if (!name) return <NarrowCard title="Allow Access" description="This request isn't valid any more. Start again from the site." />;
const scopes = (typeof params.scope === "string" ? params.scope : "").split(" ").filter((s) => s in scopeText);
return (
<NarrowCard title="Allow Access" description={`${name} wants to use your T5DE account, ${me.username}.`}>
<div className="space-y-4">
<ul className="list-disc space-y-1 pl-5 text-sm">
{scopes.map((s) => (
<li key={s}>{scopeText[s]}</li>
))}
</ul>
<ConsentForm />
</div>
</NarrowCard>
);
}
+15 -8
View File
@@ -6,28 +6,35 @@ import { NarrowCard } from "@/components/narrow-card";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { api, getMe, unwrap } from "@/lib/api"; import { api, getMe, unwrap } from "@/lib/api";
import { discordError } from "@/lib/discord"; import { discordError } from "@/lib/discord";
import { continueURL, requestedProvider, requestingClient } from "@/lib/oauth";
import { safeNext } from "@/lib/paths"; import { safeNext } from "@/lib/paths";
import { SignInForm } from "./signin-form"; import { SignInForm } from "./signin-form";
export const metadata: Metadata = { title: "Sign in" }; export const metadata: Metadata = { title: "Sign in" };
export default async function SignIn({ export default async function SignIn({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
searchParams,
}: {
searchParams: Promise<{ next?: string | string[]; error?: string | string[] }>;
}) {
const params = await searchParams; const params = await searchParams;
const next = safeNext(params.next); // Opened for another T5DE site (Music): back to it once signed in.
const forSite = continueURL(params);
const next = forSite ?? safeNext(params.next);
if (await getMe()) redirect(next); if (await getMe()) redirect(next);
const { discord } = unwrap(await api.hub.get()); const { discord } = unwrap(await api.hub.get());
const clientId = requestingClient(params);
const site = forSite && clientId ? (await api.oauth.clients({ clientId }).get()).data : undefined;
const siteName = site && "client" in site ? site.client.name : undefined;
const error = discordError(params.error); const error = discordError(params.error);
// The site asked for Discord (its "Sign in with Discord" button): go straight there, unless that just failed.
const autoDiscord = discord && forSite !== undefined && requestedProvider(params) === "discord" && !error;
return ( return (
<NarrowCard title="Sign in" description="to your T5DE account."> <NarrowCard
title="Sign in"
description={siteName ? `with your T5DE account to continue to ${siteName}.` : "to your T5DE account."}
>
<div className="space-y-6"> <div className="space-y-6">
{error && <ErrorText>{error}</ErrorText>} {error && <ErrorText>{error}</ErrorText>}
{discord && ( {discord && (
<> <>
<DiscordButton mode="sign-in" next={next} /> <DiscordButton mode="sign-in" next={next} auto={autoDiscord} />
<div className="flex items-center gap-3 text-xs text-muted-foreground"> <div className="flex items-center gap-3 text-xs text-muted-foreground">
<Separator className="flex-1" /> <Separator className="flex-1" />
or with your username or with your username
+2
View File
@@ -18,6 +18,8 @@ export function SignInForm({ next }: { next: string }) {
const [step, setStep] = useState<"password" | "code" | "backup">("password"); const [step, setStep] = useState<"password" | "code" | "backup">("password");
const done = () => { const done = () => {
// Back to the hub's authorize endpoint (signing in for another T5DE site): a full page load, it's the API's.
if (next.startsWith("/api/")) return window.location.assign(next);
router.push(next); router.push(next);
router.refresh(); router.refresh();
}; };
+11 -2
View File
@@ -1,12 +1,13 @@
"use client"; "use client";
// Discord sign-in (a basic account the first time, docs/music.md) and, from the account page, linking Discord to a // Discord sign-in (a basic account the first time, docs/music.md) and, from the account page, linking Discord to a
// member's account. Discord sends people back to the API, which sends them on to these addresses on this site. // member's account. Discord sends people back to the API, which sends them on to these addresses on this site.
import { useState } from "react"; import { useEffect, useRef, useState } from "react";
import { ErrorText } from "@/components/forms"; import { ErrorText } from "@/components/forms";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { authClient } from "@/lib/auth-client"; import { authClient } from "@/lib/auth-client";
export function DiscordButton({ mode, next = "/" }: { mode: "sign-in" | "link"; next?: string }) { /** auto: start at once (a T5DE site asked for Discord sign-in). */
export function DiscordButton({ mode, next = "/", auto = false }: { mode: "sign-in" | "link"; next?: string; auto?: boolean }) {
const [pending, setPending] = useState(false); const [pending, setPending] = useState(false);
const [error, setError] = useState(""); const [error, setError] = useState("");
@@ -29,6 +30,14 @@ export function DiscordButton({ mode, next = "/" }: { mode: "sign-in" | "link";
} }
} }
const started = useRef(false);
useEffect(() => {
if (!auto || started.current) return;
started.current = true;
void go();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [auto]);
return ( return (
<div className="space-y-2"> <div className="space-y-2">
<Button type="button" variant={mode === "link" ? "outline" : "default"} className={mode === "link" ? undefined : "w-full"} disabled={pending} onClick={() => void go()}> <Button type="button" variant={mode === "link" ? "outline" : "default"} className={mode === "link" ? undefined : "w-full"} disabled={pending} onClick={() => void go()}>
+25
View File
@@ -0,0 +1,25 @@
// Signing in for another T5DE site (OpenID Connect, docs/music.md). The hub's authorize endpoint sends people who
// aren't signed in to /signin with the site's request and a signature; once they're signed in, this sends them back
// to the authorize endpoint with the same request, which then returns them to the site.
type Params = Record<string, string | string[] | undefined>;
/** The provider's own parameters on the sign-in page, not part of the site's request. */
const internal = new Set(["sig", "exp", "ba_iat", "ba_param", "next", "error"]);
/** Where to go once signed in, if the sign-in page was opened for a site's request (else undefined). */
export function continueURL(params: Params): string | undefined {
if (typeof params.sig !== "string" || typeof params.client_id !== "string") return undefined;
const q = new URLSearchParams();
for (const [k, v] of Object.entries(params)) {
if (internal.has(k) || v === undefined) continue;
for (const one of Array.isArray(v) ? v : [v]) q.append(k, one);
}
return `/api/auth/oauth2/authorize?${q}`;
}
/** The site's client ID, if the page was opened for one. */
export const requestingClient = (params: Params) => (typeof params.client_id === "string" ? params.client_id : undefined);
/** Whether the site asked to go straight to a sign-in provider (Music's "Sign in with Discord"). */
export const requestedProvider = (params: Params) => (typeof params.t5de_provider === "string" ? params.t5de_provider : undefined);
+1
View File
@@ -10,6 +10,7 @@
}, },
"dependencies": { "dependencies": {
"@base-ui/react": "^1.9.0", "@base-ui/react": "^1.9.0",
"@better-auth/oauth-provider": "1.7.26",
"@elysiajs/eden": "1.4.9", "@elysiajs/eden": "1.4.9",
"@t5de/api": "workspace:*", "@t5de/api": "workspace:*",
"better-auth": "1.7.26", "better-auth": "1.7.26",
+4
View File
@@ -11,6 +11,7 @@
"apps/api": { "apps/api": {
"name": "@t5de/api", "name": "@t5de/api",
"dependencies": { "dependencies": {
"@better-auth/oauth-provider": "1.7.26",
"@t5de/db": "workspace:*", "@t5de/db": "workspace:*",
"better-auth": "1.7.26", "better-auth": "1.7.26",
"elysia": "1.4.30", "elysia": "1.4.30",
@@ -27,6 +28,7 @@
"name": "@t5de/web", "name": "@t5de/web",
"dependencies": { "dependencies": {
"@base-ui/react": "^1.9.0", "@base-ui/react": "^1.9.0",
"@better-auth/oauth-provider": "1.7.26",
"@elysiajs/eden": "1.4.9", "@elysiajs/eden": "1.4.9",
"@t5de/api": "workspace:*", "@t5de/api": "workspace:*",
"better-auth": "1.7.26", "better-auth": "1.7.26",
@@ -139,6 +141,8 @@
"@better-auth/mongo-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-mGVJ0UIL1hjrp5aCuv4hFinZhpB7vvpu1c/fSa40Ktk4GugXcXguVwHI4hiDqGCttslTz0LOa5gqT+BfzgdJWw=="], "@better-auth/mongo-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-mGVJ0UIL1hjrp5aCuv4hFinZhpB7vvpu1c/fSa40Ktk4GugXcXguVwHI4hiDqGCttslTz0LOa5gqT+BfzgdJWw=="],
"@better-auth/oauth-provider": ["@better-auth/[email protected]", "", { "dependencies": { "jose": "^6.2.3", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3", "better-auth": "^1.7.26", "better-call": "~1.4.5" } }, "sha512-wzeIJ2Yogsd8HN5QLm3avpEubJmwo/hg00qZf6c7Ivu/doJlg0PENJOxgK2oRdjbl787i9GOKp1pAzTCQpMGDg=="],
"@better-auth/prisma-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-rXc6dI6HBhD4uXh1gMJU0ScQjojt3wIS4+DziIm/j8ujoTBEG96hFVN0vFVIq/D7SnimXIsPu5rqJ7GYSDbDtw=="], "@better-auth/prisma-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-rXc6dI6HBhD4uXh1gMJU0ScQjojt3wIS4+DziIm/j8ujoTBEG96hFVN0vFVIq/D7SnimXIsPu5rqJ7GYSDbDtw=="],
"@better-auth/telemetry": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3" } }, "sha512-XSxQWg+guJ4X9KrcsdJCUPcXk/GaKxPNSXrhuDRhoWhk3ommioRB2Y6/to6ROy1fGP8JtXqRN4ZPiyKZnfy4Sw=="], "@better-auth/telemetry": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3" } }, "sha512-XSxQWg+guJ4X9KrcsdJCUPcXk/GaKxPNSXrhuDRhoWhk3ommioRB2Y6/to6ROy1fGP8JtXqRN4ZPiyKZnfy4Sw=="],
+5
View File
@@ -29,6 +29,11 @@ services:
DIDIT_API_KEY: ${DIDIT_API_KEY:-} DIDIT_API_KEY: ${DIDIT_API_KEY:-}
DIDIT_WORKFLOW_ID: ${DIDIT_WORKFLOW_ID:-} DIDIT_WORKFLOW_ID: ${DIDIT_WORKFLOW_ID:-}
DIDIT_WEBHOOK_SECRET: ${DIDIT_WEBHOOK_SECRET:-} DIDIT_WEBHOOK_SECRET: ${DIDIT_WEBHOOK_SECRET:-}
# Discord sign-in (basic accounts), and T5DE Music as an OpenID Connect client (apps/api/src/index.ts).
DISCORD_CLIENT_ID: ${DISCORD_CLIENT_ID:-}
DISCORD_CLIENT_SECRET: ${DISCORD_CLIENT_SECRET:-}
MUSIC_CLIENT_SECRET: ${MUSIC_CLIENT_SECRET:-}
MUSIC_REDIRECT_URIS: ${MUSIC_REDIRECT_URIS:-}
ports: ["4101:4101"] ports: ["4101:4101"]
depends_on: depends_on:
postgres: { condition: service_healthy } postgres: { condition: service_healthy }
+26 -1
View File
@@ -3,7 +3,7 @@
`apps/api` (Elysia on Bun). The route definitions in `apps/api/src/app.ts` are the reference: their schemas validate `apps/api` (Elysia on Bun). The route definitions in `apps/api/src/app.ts` are the reference: their schemas validate
requests and type the website's client (Eden). This is the overview. requests and type the website's client (Eden). This is the overview.
- `/api/auth/*`: Better Auth (accounts, sessions, device sign-in, JWT keys). - `/api/auth/*`: Better Auth (accounts, sessions, device sign-in, JWT keys, and the OpenID Connect provider).
- `/api/v1/*`: the hub's own routes. - `/api/v1/*`: the hub's own routes.
The website reaches the API through its own origin (Next.js rewrites `/api` to it), so sessions are first-party The website reaches the API through its own origin (Next.js rewrites `/api` to it), so sessions are first-party
@@ -30,6 +30,31 @@ is. Codes: `invalid`, `signed_out`, `forbidden`, `not_found`, `no_such_imvu_acco
| `GET /api/v1/hub` | (anyone) `{registration, discord}`: registration `open` or `closed`, and whether Discord sign-in is on | | `GET /api/v1/hub` | (anyone) `{registration, discord}`: registration `open` or `closed`, and whether Discord sign-in is on |
| `POST /api/v1/account/finish` | (a basic account) `{username, password}` → `{person}`: it becomes a member (`invalid_username`, `invalid_password`, `username_taken`, `already_member`); with registration closed it then waits for approval. Discord stays linked. | | `POST /api/v1/account/finish` | (a basic account) `{username, password}` → `{person}`: it becomes a member (`invalid_username`, `invalid_password`, `username_taken`, `already_member`); with registration closed it then waits for approval. Discord stays linked. |
## Signing in on T5DE's other sites (OpenID Connect)
The hub is an OAuth 2.1 / OpenID Connect provider (Better Auth's `@better-auth/oauth-provider`) for T5DE's own sites,
Music first (docs/music.md, The OIDC provider). The issuer is `API_URL/api/auth`; discovery at
`/api/auth/.well-known/openid-configuration`, keys at `/api/auth/jwks` (Ed25519, the same keys as the JWT plugin).
- **Clients**: first-party sites are made at startup from the environment (`MUSIC_CLIENT_SECRET`,
`MUSIC_REDIRECT_URIS`: client ID `t5de-music`), trusted (no consent screen), confidential (`client_secret_basic`),
PKCE required, HTTPS redirect URIs (plain HTTP on localhost in development). Dynamic registration is off.
- **Flow**: authorization code. `/api/auth/oauth2/authorize` sends people who aren't signed in to the website's
`/signin` with the request and a signature; once signed in (password or Discord) the page sends them back to
authorize, which returns them to the site with a code. `t5de_provider=discord` in the request starts Discord
sign-in at once (a site's "Sign in with Discord"). Other sites' requests show `/consent`.
- **Tokens**: `/api/auth/oauth2/token`, `/userinfo`, `/introspect`, `/revoke`. Ask for `resource=API_URL/api/v1` to
get an access token for the hub's API (a JWT, `typ: at+jwt`, audience that resource), needed for the routes below.
- **Scopes**: `openid`, `profile` (`name`, `preferred_username` for members), `email`, `offline_access` (a refresh
token), `imvu` (first-party only: `imvu: [{id, username}]`, the person's linked IMVU accounts, in the ID token and
userinfo), `imvu:link` (the hub's link routes with the person's access token).
| | |
| --- | --- |
| `GET /api/v1/oauth/clients/:clientId` | (anyone) `{client: {name, firstParty}}`: for the sign-in and consent pages |
| `GET /api/v1/account/imvu` | (`imvu:link` token, or the website) `{links, challenges, linkCap, canLink}` |
| `POST /api/v1/account/links`, `POST .../:imvu/check`, `DELETE /api/v1/account/challenges/:imvu`, `DELETE /api/v1/account/links/:imvu` | also take an `imvu:link` token, for any account (basic ones too); see the website routes below. Other routes answer such tokens 403 `token_not_allowed`, and a token without the scope gets 403 `insufficient_scope`. |
## Proxies ## Proxies
| | | | | |
+150
View File
@@ -0,0 +1,150 @@
CREATE TABLE "oauth_access_token" (
"id" text PRIMARY KEY NOT NULL,
"token" text NOT NULL,
"client_id" text NOT NULL,
"session_id" text,
"user_id" text,
"reference_id" text,
"authorization_code_id" text,
"resources" text[],
"requested_user_info_claims" text[],
"refresh_id" text,
"expires_at" timestamp with time zone NOT NULL,
"created_at" timestamp with time zone NOT NULL,
"revoked" timestamp with time zone,
"confirmation" jsonb,
"scopes" text[] NOT NULL,
CONSTRAINT "oauth_access_token_token_unique" UNIQUE("token")
);
--> statement-breakpoint
CREATE TABLE "oauth_client" (
"id" text PRIMARY KEY NOT NULL,
"client_id" text NOT NULL,
"client_secret" text,
"client_discovery_id" text,
"disabled" boolean DEFAULT false,
"skip_consent" boolean,
"enable_end_session" boolean,
"subject_type" text,
"scopes" text[],
"client_credentials_scopes" text[] DEFAULT '{}'::text[],
"user_id" text,
"created_at" timestamp with time zone,
"updated_at" timestamp with time zone,
"name" text,
"uri" text,
"icon" text,
"contacts" text[],
"tos" text,
"policy" text,
"software_id" text,
"software_version" text,
"software_statement" text,
"redirect_uris" text[] NOT NULL,
"post_logout_redirect_uris" text[],
"backchannel_logout_uri" text,
"backchannel_logout_session_required" boolean,
"token_endpoint_auth_method" text,
"application_type" text,
"jwks" text,
"jwks_uri" text,
"grant_types" text[],
"response_types" text[],
"require_pkce" boolean,
"dpop_bound_access_tokens" boolean DEFAULT false,
"reference_id" text,
"metadata" jsonb,
CONSTRAINT "oauth_client_client_id_unique" UNIQUE("client_id")
);
--> statement-breakpoint
CREATE TABLE "oauth_client_assertion" (
"id" text PRIMARY KEY NOT NULL,
"expires_at" timestamp with time zone NOT NULL
);
--> statement-breakpoint
CREATE TABLE "oauth_client_resource" (
"id" text PRIMARY KEY NOT NULL,
"client_id" text NOT NULL,
"resource_id" text NOT NULL,
"metadata" jsonb,
"created_at" timestamp with time zone
);
--> statement-breakpoint
CREATE TABLE "oauth_consent" (
"id" text PRIMARY KEY NOT NULL,
"client_id" text NOT NULL,
"user_id" text,
"reference_id" text,
"resources" text[],
"requested_user_info_claims" text[],
"scopes" text[] NOT NULL,
"created_at" timestamp with time zone NOT NULL,
"updated_at" timestamp with time zone NOT NULL
);
--> statement-breakpoint
CREATE TABLE "oauth_refresh_token" (
"id" text PRIMARY KEY NOT NULL,
"token" text NOT NULL,
"client_id" text NOT NULL,
"session_id" text,
"user_id" text NOT NULL,
"reference_id" text,
"authorization_code_id" text,
"resources" text[],
"requested_user_info_claims" text[],
"expires_at" timestamp with time zone NOT NULL,
"created_at" timestamp with time zone NOT NULL,
"revoked" timestamp with time zone,
"rotated_at" timestamp with time zone,
"rotation_replay_response" text,
"rotation_replay_expires_at" timestamp with time zone,
"auth_time" timestamp with time zone,
"confirmation" jsonb,
"scopes" text[] NOT NULL,
CONSTRAINT "oauth_refresh_token_token_unique" UNIQUE("token")
);
--> statement-breakpoint
CREATE TABLE "oauth_resource" (
"id" text PRIMARY KEY NOT NULL,
"identifier" text NOT NULL,
"name" text NOT NULL,
"access_token_ttl" integer,
"refresh_token_ttl" integer,
"signing_algorithm" text,
"signing_key_id" text,
"allowed_scopes" text[],
"custom_claims" jsonb,
"dpop_bound_access_tokens_required" boolean DEFAULT false,
"disabled" boolean DEFAULT false,
"created_at" timestamp with time zone,
"updated_at" timestamp with time zone,
"policy_version" integer DEFAULT 1,
"metadata" jsonb,
CONSTRAINT "oauth_resource_identifier_unique" UNIQUE("identifier")
);
--> statement-breakpoint
ALTER TABLE "oauth_access_token" ADD CONSTRAINT "oauth_access_token_client_id_oauth_client_client_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."oauth_client"("client_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "oauth_access_token" ADD CONSTRAINT "oauth_access_token_session_id_session_id_fk" FOREIGN KEY ("session_id") REFERENCES "public"."session"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "oauth_access_token" ADD CONSTRAINT "oauth_access_token_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "oauth_access_token" ADD CONSTRAINT "oauth_access_token_refresh_id_oauth_refresh_token_id_fk" FOREIGN KEY ("refresh_id") REFERENCES "public"."oauth_refresh_token"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "oauth_client" ADD CONSTRAINT "oauth_client_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "oauth_client_resource" ADD CONSTRAINT "oauth_client_resource_client_id_oauth_client_client_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."oauth_client"("client_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "oauth_client_resource" ADD CONSTRAINT "oauth_client_resource_resource_id_oauth_resource_identifier_fk" FOREIGN KEY ("resource_id") REFERENCES "public"."oauth_resource"("identifier") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "oauth_consent" ADD CONSTRAINT "oauth_consent_client_id_oauth_client_client_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."oauth_client"("client_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "oauth_consent" ADD CONSTRAINT "oauth_consent_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "oauth_refresh_token" ADD CONSTRAINT "oauth_refresh_token_client_id_oauth_client_client_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."oauth_client"("client_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "oauth_refresh_token" ADD CONSTRAINT "oauth_refresh_token_session_id_session_id_fk" FOREIGN KEY ("session_id") REFERENCES "public"."session"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "oauth_refresh_token" ADD CONSTRAINT "oauth_refresh_token_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "oauth_access_token_client" ON "oauth_access_token" USING btree ("client_id");--> statement-breakpoint
CREATE INDEX "oauth_access_token_session" ON "oauth_access_token" USING btree ("session_id");--> statement-breakpoint
CREATE INDEX "oauth_access_token_user" ON "oauth_access_token" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "oauth_access_token_code" ON "oauth_access_token" USING btree ("authorization_code_id");--> statement-breakpoint
CREATE INDEX "oauth_access_token_refresh" ON "oauth_access_token" USING btree ("refresh_id");--> statement-breakpoint
CREATE INDEX "oauth_client_resource_client" ON "oauth_client_resource" USING btree ("client_id");--> statement-breakpoint
CREATE INDEX "oauth_client_resource_resource" ON "oauth_client_resource" USING btree ("resource_id");--> statement-breakpoint
CREATE INDEX "oauth_consent_client" ON "oauth_consent" USING btree ("client_id");--> statement-breakpoint
CREATE INDEX "oauth_consent_user" ON "oauth_consent" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "oauth_refresh_token_client" ON "oauth_refresh_token" USING btree ("client_id");--> statement-breakpoint
CREATE INDEX "oauth_refresh_token_session" ON "oauth_refresh_token" USING btree ("session_id");--> statement-breakpoint
CREATE INDEX "oauth_refresh_token_user" ON "oauth_refresh_token" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "oauth_refresh_token_code" ON "oauth_refresh_token" USING btree ("authorization_code_id");
File diff suppressed because it is too large. Load diff
+7
View File
@@ -155,6 +155,13 @@
"when": 1795079107938, "when": 1795079107938,
"tag": "0021_account_kind", "tag": "0021_account_kind",
"breakpoints": true "breakpoints": true
},
{
"idx": 22,
"version": "7",
"when": 1795079888659,
"tag": "0022_oauth_provider",
"breakpoints": true
} }
] ]
} }
+165
View File
@@ -139,6 +139,171 @@ export const twoFactor = pgTable(
(t) => [index("two_factor_user").on(t.userId), index("two_factor_secret").on(t.secret)], (t) => [index("two_factor_user").on(t.userId), index("two_factor_secret").on(t.secret)],
); );
// --- The hub as an OAuth 2.1 / OpenID Connect provider (Better Auth's oauth-provider plugin, docs/music.md) ----------
// T5DE's own sites (Music) sign people in through the hub. Columns as the plugin defines them (getAuthTables).
// A site that signs people in through the hub. First-party ones are made at startup (auth.ts, firstPartyClients).
export const oauthClient = pgTable("oauth_client", {
id: text("id").primaryKey(),
clientId: text("client_id").notNull().unique(),
clientSecret: text("client_secret"),
clientDiscoveryId: text("client_discovery_id"),
disabled: boolean("disabled").default(false),
skipConsent: boolean("skip_consent"),
enableEndSession: boolean("enable_end_session"),
subjectType: text("subject_type"),
scopes: text("scopes").array(),
clientCredentialsScopes: text("client_credentials_scopes").array().default(sql`'{}'::text[]`),
userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
createdAt: timestamp("created_at", { withTimezone: true }),
updatedAt: timestamp("updated_at", { withTimezone: true }),
name: text("name"),
uri: text("uri"),
icon: text("icon"),
contacts: text("contacts").array(),
tos: text("tos"),
policy: text("policy"),
softwareId: text("software_id"),
softwareVersion: text("software_version"),
softwareStatement: text("software_statement"),
redirectUris: text("redirect_uris").array().notNull(),
postLogoutRedirectUris: text("post_logout_redirect_uris").array(),
backchannelLogoutUri: text("backchannel_logout_uri"),
backchannelLogoutSessionRequired: boolean("backchannel_logout_session_required"),
tokenEndpointAuthMethod: text("token_endpoint_auth_method"),
applicationType: text("application_type"),
jwks: text("jwks"),
jwksUri: text("jwks_uri"),
grantTypes: text("grant_types").array(),
responseTypes: text("response_types").array(),
requirePKCE: boolean("require_pkce"),
dpopBoundAccessTokens: boolean("dpop_bound_access_tokens").default(false),
referenceId: text("reference_id"),
metadata: jsonb("metadata"),
});
export const oauthResource = pgTable("oauth_resource", {
id: text("id").primaryKey(),
identifier: text("identifier").notNull().unique(),
name: text("name").notNull(),
accessTokenTtl: integer("access_token_ttl"),
refreshTokenTtl: integer("refresh_token_ttl"),
signingAlgorithm: text("signing_algorithm"),
signingKeyId: text("signing_key_id"),
allowedScopes: text("allowed_scopes").array(),
customClaims: jsonb("custom_claims"),
dpopBoundAccessTokensRequired: boolean("dpop_bound_access_tokens_required").default(false),
disabled: boolean("disabled").default(false),
createdAt: timestamp("created_at", { withTimezone: true }),
updatedAt: timestamp("updated_at", { withTimezone: true }),
policyVersion: integer("policy_version").default(1),
metadata: jsonb("metadata"),
});
export const oauthClientResource = pgTable(
"oauth_client_resource",
{
id: text("id").primaryKey(),
clientId: text("client_id")
.notNull()
.references(() => oauthClient.clientId, { onDelete: "cascade" }),
resourceId: text("resource_id")
.notNull()
.references(() => oauthResource.identifier, { onDelete: "cascade" }),
metadata: jsonb("metadata"),
createdAt: timestamp("created_at", { withTimezone: true }),
},
(t) => [index("oauth_client_resource_client").on(t.clientId), index("oauth_client_resource_resource").on(t.resourceId)],
);
export const oauthRefreshToken = pgTable(
"oauth_refresh_token",
{
id: text("id").primaryKey(),
token: text("token").notNull().unique(),
clientId: text("client_id")
.notNull()
.references(() => oauthClient.clientId, { onDelete: "cascade" }),
sessionId: text("session_id").references(() => session.id, { onDelete: "set null" }),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
referenceId: text("reference_id"),
authorizationCodeId: text("authorization_code_id"),
resources: text("resources").array(),
requestedUserInfoClaims: text("requested_user_info_claims").array(),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
revoked: timestamp("revoked", { withTimezone: true }),
rotatedAt: timestamp("rotated_at", { withTimezone: true }),
rotationReplayResponse: text("rotation_replay_response"),
rotationReplayExpiresAt: timestamp("rotation_replay_expires_at", { withTimezone: true }),
authTime: timestamp("auth_time", { withTimezone: true }),
confirmation: jsonb("confirmation"),
scopes: text("scopes").array().notNull(),
},
(t) => [
index("oauth_refresh_token_client").on(t.clientId),
index("oauth_refresh_token_session").on(t.sessionId),
index("oauth_refresh_token_user").on(t.userId),
index("oauth_refresh_token_code").on(t.authorizationCodeId),
],
);
export const oauthAccessToken = pgTable(
"oauth_access_token",
{
id: text("id").primaryKey(),
token: text("token").notNull().unique(),
clientId: text("client_id")
.notNull()
.references(() => oauthClient.clientId, { onDelete: "cascade" }),
sessionId: text("session_id").references(() => session.id, { onDelete: "set null" }),
userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
referenceId: text("reference_id"),
authorizationCodeId: text("authorization_code_id"),
resources: text("resources").array(),
requestedUserInfoClaims: text("requested_user_info_claims").array(),
refreshId: text("refresh_id").references(() => oauthRefreshToken.id, { onDelete: "cascade" }),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
revoked: timestamp("revoked", { withTimezone: true }),
confirmation: jsonb("confirmation"),
scopes: text("scopes").array().notNull(),
},
(t) => [
index("oauth_access_token_client").on(t.clientId),
index("oauth_access_token_session").on(t.sessionId),
index("oauth_access_token_user").on(t.userId),
index("oauth_access_token_code").on(t.authorizationCodeId),
index("oauth_access_token_refresh").on(t.refreshId),
],
);
export const oauthConsent = pgTable(
"oauth_consent",
{
id: text("id").primaryKey(),
clientId: text("client_id")
.notNull()
.references(() => oauthClient.clientId, { onDelete: "cascade" }),
userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
referenceId: text("reference_id"),
resources: text("resources").array(),
requestedUserInfoClaims: text("requested_user_info_claims").array(),
scopes: text("scopes").array().notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull(),
},
(t) => [index("oauth_consent_client").on(t.clientId), index("oauth_consent_user").on(t.userId)],
);
// Single-use client assertions (private_key_jwt), remembered until they expire.
export const oauthClientAssertion = pgTable("oauth_client_assertion", {
id: text("id").primaryKey(),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
});
// A T5DE proxy signing in: it shows userCode, the person approves it on the website. // A T5DE proxy signing in: it shows userCode, the person approves it on the website.
export const deviceCode = pgTable("device_code", { export const deviceCode = pgTable("device_code", {
id: text("id").primaryKey(), id: text("id").primaryKey(),