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

+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,
"tag": "0021_account_kind",
"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)],
);
// --- 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.
export const deviceCode = pgTable("device_code", {
id: text("id").primaryKey(),