Compare commits

...
6 Commits
Author SHA1 Message Date
dhkatz a6337f09b6 docs(payments): PayPal beside Patreon, our own checkout later (#28)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m36s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 4s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 4s
Updates the payments plan with PayPal and the decisions since #26.

**docs/payments.md**
- **PayPal (new section):** sold exactly as priced, $1.99 a month or $19.99 a year per room, as one subscription with a room count.
  - **Setup:** the product, plans and webhook are made through PayPal's API, and their IDs go in the config. The sandbox ones exist already.
  - **Checkout:** a redirect. The subscription carries the account (`custom_id` = the person's `sub`) and the VAT override.
  - **Webhook:** verified by PayPal's own `verify-webhook-signature`; the subscription is then fetched again from PayPal, plus a nightly sync. A status table says what each PayPal state grants.
- **Tax:**
  - **EU VAT:** non-Union OSS, with VAT included in the price. Each sale records two pieces of country evidence (the buyer's choice and their IP's country); if they disagree, no sale. The service makes the quarterly report itself.
  - **UK:** handled once registered with HMRC.
  - **US:** state thresholds, with sales reported per state.
  - **Where it sells first:** outside the EU and the UK until those registrations take effect.
- **No website of its own:** the app's pages use the API. The browser only passes through `/link/patreon`, `/checkout/paypal` and `/manage/<source>`, which return only to listed addresses.
- **Checkout elements (later):** our own checkout as iframes from `payments.t5de.dev`, so the processor doesn't show and Patreon can go.
- **Environments:** staging uses PayPal's sandbox and the locked staging hub. Patreon has no test mode, so both of its redirect URIs are listed.
- Goals, the processors table, lapses, phases (Patreon, then PayPal, then elements) and "before taking money" updated to match.

**docs/music.md:** the paid tier lists both ways to pay, plus the later checkout.

Updates the payments plan with PayPal and the decisions since #26.

**docs/payments.md**
- **PayPal (new section):** sold exactly as priced, $1.99 a month or $19.99 a year per room, as one subscription with a room count.
  - **Setup:** the product, plans and webhook are made through PayPal's API, and their IDs go in the config. The sandbox ones exist already.
  - **Checkout:** a redirect. The subscription carries the account (`custom_id` = the person's `sub`) and the VAT override.
  - **Webhook:** verified by PayPal's own `verify-webhook-signature`; the subscription is then fetched again from PayPal, plus a nightly sync. A status table says what each PayPal state grants.
- **Tax:**
  - **EU VAT:** non-Union OSS, with VAT included in the price. Each sale records two pieces of country evidence (the buyer's choice and their IP's country); if they disagree, no sale. The service makes the quarterly report itself.
  - **UK:** handled once registered with HMRC.
  - **US:** state thresholds, with sales reported per state.
  - **Where it sells first:** outside the EU and the UK until those registrations take effect.
- **No website of its own:** the app's pages use the API. The browser only passes through `/link/patreon`, `/checkout/paypal` and `/manage/<source>`, which return only to listed addresses.
- **Checkout elements (later):** our own checkout as iframes from `payments.t5de.dev`, so the processor doesn't show and Patreon can go.
- **Environments:** staging uses PayPal's sandbox and the locked staging hub. Patreon has no test mode, so both of its redirect URIs are listed.
- Goals, the processors table, lapses, phases (Patreon, then PayPal, then elements) and "before taking money" updated to match.

**docs/music.md:** the paid tier lists both ways to pay, plus the later checkout.

Co-authored-by: dhkatz <[email protected]>
2026-11-20 23:38:00 +00:00
dhkatz f3cc3f9f17 feat(accounts): locked registration, for staging (#27)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m35s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 5s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 14s
Locks staging down before payments' staging (PayPal's sandbox) exists.

**The problem:** staging's registration is closed, but signing in with Discord still makes an approved basic account at once (`auth.ts`). So any Discord account can sign in to Music's staging.

**The change:** a third registration setting, `locked`:
- Every new account waits for a moderator's approval, Discord sign-ins too.
- Only approved accounts sign in to T5DE's other sites. The gate is the OAuth provider's `postLogin.shouldRedirect`: an unapproved account is sent to the website (which shows "Waiting for Approval") and no code is issued. It runs on every authorize request and on `/oauth2/continue`.
- Finishing setup under `locked` keeps the person's approval, so an approved basic account doesn't lose Music access by becoming a member.
- **Console:** the setting has a "Locked" option. **Website:** the waiting screen for unapproved Discord accounts, and the sign-up page's note.

`open` and `closed` behave as before. Under `closed`, a member waiting for approval still signs in to Music (tested), so prod doesn't change.

**After merging:** infra sets staging's `REGISTRATION` to `locked`. That's only a default: if staging's registration was ever changed in the console, set it to Locked there. Accounts already on staging keep their approval.

**Checks:** `bun test` (77 pass, two new tests), `check-types`, `lint`.

Locks staging down before payments' staging (PayPal's sandbox) exists.

**The problem:** staging's registration is closed, but signing in with Discord still makes an approved basic account at once (`auth.ts`). So any Discord account can sign in to Music's staging.

**The change:** a third registration setting, `locked`:
- Every new account waits for a moderator's approval, Discord sign-ins too.
- Only approved accounts sign in to T5DE's other sites. The gate is the OAuth provider's `postLogin.shouldRedirect`: an unapproved account is sent to the website (which shows "Waiting for Approval") and no code is issued. It runs on every authorize request and on `/oauth2/continue`.
- Finishing setup under `locked` keeps the person's approval, so an approved basic account doesn't lose Music access by becoming a member.
- **Console:** the setting has a "Locked" option. **Website:** the waiting screen for unapproved Discord accounts, and the sign-up page's note.

`open` and `closed` behave as before. Under `closed`, a member waiting for approval still signs in to Music (tested), so prod doesn't change.

**After merging:** infra sets staging's `REGISTRATION` to `locked`. That's only a default: if staging's registration was ever changed in the console, set it to Locked there. Accounts already on staging keep their approval.

**Checks:** `bun test` (77 pass, two new tests), `check-types`, `lint`.

Co-authored-by: dhkatz <[email protected]>
2026-11-20 20:31:32 +00:00
dhkatz 02e8269d4d docs(payments): a payments service of its own, Patreon first (#26)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m36s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 5s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 4s
Rewrites the payments plan for a separate payments service, with Patreon as the first way to pay.

**docs/payments.md**
- **`t5de-payments` is its own service:** its own repo, Postgres database and secrets, at `payments.t5de.dev`, to contain the compliance risk. The hub and Music never hold a payment provider's key. Music reads entitlements (`GET /v1/entitlements/{sub}`), is told about changes over a signed back-channel call, and keeps the last answer it got.
- **Patreon first:** Patreon is the seller, so it handles sales tax and VAT.
  - **Linking:** members link Patreon with OAuth (`identity`).
  - **Tiers:** which tier gives how much is set in config in git.
  - **Webhook:** the service checks its webhook exists and is set up right on every start, and fixes it if not. Requests are verified with `X-Patreon-Signature` (HMAC-MD5).
  - **State:** after a webhook it re-fetches the member from Patreon, and a nightly sync of every member catches anything missed.
  - **Grace:** access runs until `next_charge_date` plus 7 days.
  - **Tokens:** Patreon rotates the creator token's refresh token, so the current pair is kept in the database.
- **Entitlements are counts** (`music.rooms` × N), because a Patreon member has only one tier. Moderators' grants (no money) come first, in phase 1.
- **Processors:**
  - **Polar:** used only if their support says yes in writing. Its acceptable use policy names YouTube downloaders (#30) and circumventing other services' terms (#18).
  - **Not used:** Stripe or PayPal directly (we'd be the seller), and IMVU credits.

**docs/music.md**
- **The paid tier sells hosting only.** YouTube limits are now the same in both tiers.
- **Tiers:** Room ($1.99, 1 room) and Rooms ($4.99, 3 rooms). The owner picks which rooms are paid. When the count drops, the most recently picked rooms go back to free first.
- The risks section and phase 3b point to t5de-payments.

Rewrites the payments plan for a separate payments service, with Patreon as the first way to pay.

**docs/payments.md**
- **`t5de-payments` is its own service:** its own repo, Postgres database and secrets, at `payments.t5de.dev`, to contain the compliance risk. The hub and Music never hold a payment provider's key. Music reads entitlements (`GET /v1/entitlements/{sub}`), is told about changes over a signed back-channel call, and keeps the last answer it got.
- **Patreon first:** Patreon is the seller, so it handles sales tax and VAT.
  - **Linking:** members link Patreon with OAuth (`identity`).
  - **Tiers:** which tier gives how much is set in config in git.
  - **Webhook:** the service checks its webhook exists and is set up right on every start, and fixes it if not. Requests are verified with `X-Patreon-Signature` (HMAC-MD5).
  - **State:** after a webhook it re-fetches the member from Patreon, and a nightly sync of every member catches anything missed.
  - **Grace:** access runs until `next_charge_date` plus 7 days.
  - **Tokens:** Patreon rotates the creator token's refresh token, so the current pair is kept in the database.
- **Entitlements are counts** (`music.rooms` × N), because a Patreon member has only one tier. Moderators' grants (no money) come first, in phase 1.
- **Processors:**
  - **Polar:** used only if their support says yes in writing. Its acceptable use policy names YouTube downloaders (#30) and circumventing other services' terms (#18).
  - **Not used:** Stripe or PayPal directly (we'd be the seller), and IMVU credits.

**docs/music.md**
- **The paid tier sells hosting only.** YouTube limits are now the same in both tiers.
- **Tiers:** Room ($1.99, 1 room) and Rooms ($4.99, 3 rooms). The owner picks which rooms are paid. When the count drops, the most recently picked rooms go back to free first.
- The risks section and phase 3b point to t5de-payments.

Co-authored-by: dhkatz <[email protected]>
2026-11-20 19:38:01 +00:00
dhkatz b496714151 fix(web): Next.js 16.4.6 (security advisories) (#25)
Release / release (push) Successful in 5s
CI / test (push) Successful in 1m43s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 1m2s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 6m23s
`next build` refuses to run on Next.js 16.4.3 now: two moderate advisories, [GHSA-mfr8-8qww-v76h](https://github.com/advisories/GHSA-mfr8-8qww-v76h) and [GHSA-vc7v-qv4w-wrv8](https://github.com/advisories/GHSA-vc7v-qv4w-wrv8) (cache leaks across root params with `'use cache'`, which the hub doesn't use), fixed in 16.4.5. This moves the website to 16.4.6, the latest 16.4 patch.

Checked locally: `next build` passes on 16.4.6 (it stopped with SecurityFatalError on 16.4.3).

`next build` refuses to run on Next.js 16.4.3 now: two moderate advisories, [GHSA-mfr8-8qww-v76h](https://github.com/advisories/GHSA-mfr8-8qww-v76h) and [GHSA-vc7v-qv4w-wrv8](https://github.com/advisories/GHSA-vc7v-qv4w-wrv8) (cache leaks across root params with `'use cache'`, which the hub doesn't use), fixed in 16.4.5. This moves the website to 16.4.6, the latest 16.4 patch.

Checked locally: `next build` passes on 16.4.6 (it stopped with SecurityFatalError on 16.4.3).

Co-authored-by: dhkatz <[email protected]>
2026-11-19 11:28:27 +00:00
dhkatz d0f7e4d8c3 ci: only main's newest commit moves latest-main (#24)
Release / release (push) Successful in 3s
CI / test (push) Successful in 7m26s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 5s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 5s
Two merges close together can build out of order: on 2026-11-19, #22's image job finished two minutes after #23's and moved `:latest-main` back to #22's build, so staging ran without the OpenID provider.

Now a main push tags `:main-<commit>` always, and `:latest-main` only if its commit is still main's newest (`git ls-remote origin refs/heads/main`). Whichever finishes last, `:latest-main` ends on the newest commit. Tags (`vX.Y.Z`) are unchanged.

t5de-catalog and t5de-site have the same line, and need the same fix.

Two merges close together can build out of order: on 2026-11-19, #22's image job finished two minutes after #23's and moved `:latest-main` back to #22's build, so staging ran without the OpenID provider.

Now a main push tags `:main-<commit>` always, and `:latest-main` only if its commit is still main's newest (`git ls-remote origin refs/heads/main`). Whichever finishes last, `:latest-main` ends on the newest commit. Tags (`vX.Y.Z`) are unchanged.

t5de-catalog and t5de-site have the same line, and need the same fix.

Co-authored-by: dhkatz <[email protected]>
2026-11-19 10:18:22 +00:00
dhkatz df42b7833a 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]>
2026-11-19 09:55:03 +00:00
29 changed files with 6920 additions and 170 deletions

No files matched your search

+5 -1
View File
@@ -55,7 +55,11 @@ jobs:
DOCKERFILE: ${{ matrix.dockerfile }}
run: |
case "$GITHUB_REF" in
refs/heads/main) version="main-${GITHUB_SHA::12}"; tags="latest-main $version" ;;
refs/heads/main)
version="main-${GITHUB_SHA::12}"; tags="$version"
# Merges close together can finish out of order: only main's newest commit moves latest-main (staging).
if [ "$(git ls-remote origin refs/heads/main | cut -f1)" = "$GITHUB_SHA" ]; then tags="latest-main $tags"
else echo "main has moved on since this commit: :$version only, latest-main stays"; fi ;;
refs/tags/v*)
version="${GITHUB_REF#refs/tags/v}"
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "Not a vX.Y.Z tag: no image"; exit 0; }
+6 -2
View File
@@ -9,13 +9,17 @@ payments in [docs/payments.md](docs/payments.md).
## What works
- **Accounts** (Better Auth): sign-up with email, username and password; sign-in by username. The first account is
an admin; roles user, moderator, admin. Registration open or closed (new accounts wait for a moderator's
approval): an admin's setting in the console, defaulting to the API's `REGISTRATION`.
an admin; roles user, moderator, admin. Registration open, closed (new accounts wait for a moderator's
approval) or locked (for staging: Discord sign-ins wait for approval too, and only approved accounts sign in to
T5DE's other sites): an admin's setting in the console, defaulting to the API's `REGISTRATION`.
- **Discord sign-in** (when `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set; Discord redirects to
`<API_URL>/api/auth/callback/discord`): the first time it makes a basic account (Discord's verified email,
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
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
API. The most recent proof wins (an account linked elsewhere moves, with a new pairwise ID). Link caps per person
(default 10).
+1
View File
@@ -12,6 +12,7 @@
"check-types": "tsc --noEmit"
},
"dependencies": {
"@better-auth/oauth-provider": "1.7.26",
"@t5de/db": "workspace:*",
"better-auth": "1.7.26",
"elysia": "1.4.30",
+120 -15
View File
@@ -2,6 +2,7 @@
// origin (Next.js rewrites /api to here), so session cookies are first-party; T5DE's proxy calls it with a bearer
// token.
import { Elysia, t } from "elysia";
import { createLocalJWKSet, jwtVerify, type JSONWebKeySet } from "jose";
import {
and,
asc,
@@ -20,7 +21,7 @@ import {
type ParentInfo,
type RoomModerator,
} from "@t5de/db";
import { passwordRules, usernameRules, validUsername, type Auth } from "./auth";
import { hubResource, passwordRules, usernameRules, validUsername, type Auth } from "./auth";
import { AgeError, AgeRefused, AgeService } from "./age";
import { imvuAgeProvider, imvuResult } from "./age/imvu";
import { ImvuClient, ImvuUnavailable, NoSuchImvuUser } from "./imvu";
@@ -168,6 +169,34 @@ export function createApp({
const hosted = new HostedRooms(db);
const decorations = new Decorations(db);
const apiBase = (apiURL ?? "http://localhost:4101").replace(/\/+$/, "");
/**
* An OAuth access token for the hub's API (a JWT the hub signed for its resource, docs/music.md): the person it's
* for and its scopes, or undefined if it isn't one. Keys from the JWT plugin's JWKS, kept ten minutes (and fetched
* again when a token names a key not seen yet).
*/
let jwks: { set: ReturnType<typeof createLocalJWKSet>; at: number } | undefined;
const keys = async (fresh = false) => {
if (!jwks || fresh || Date.now() - jwks.at > 10 * 60 * 1000)
jwks = { set: createLocalJWKSet((await auth.api.getJwks()) as JSONWebKeySet), at: Date.now() };
return jwks.set;
};
const accessToken = async (token: string) => {
const options = { issuer: `${apiBase}/api/auth`, audience: hubResource(apiBase), typ: "at+jwt", requiredClaims: ["sub", "azp"] };
let payload;
try {
({ payload } = await jwtVerify(token, await keys(), options));
} catch (e) {
if ((e as { code?: string }).code !== "ERR_JWKS_NO_MATCHING_KEY") return undefined;
try {
({ payload } = await jwtVerify(token, await keys(true), options));
} catch {
return undefined;
}
}
const scopes = typeof payload.scope === "string" ? payload.scope.split(" ") : [];
return { userId: String(payload.sub), clientId: String(payload.azp), scopes };
};
const realtime =
rt ??
new Realtime({
@@ -893,6 +922,21 @@ export function createApp({
.derive(async ({ request }) => {
// An API token: only routes open to scripts (`scripted`) take it; everywhere else it's signed out.
const bearer = request.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1];
// An OAuth access token from one of T5DE's sites (a JWT: three parts): only routes for them (`linking`) take it.
if (bearer && !bearer.startsWith(tokenPrefix) && bearer.split(".").length === 3) {
const tok = await accessToken(bearer);
const owner = tok ? (await db.select().from(user).where(eq(user.id, tok.userId)))[0] : undefined;
const ok = tok && owner && !owner.banned ? { person: owner, scopes: tok.scopes, clientId: tok.clientId } : undefined;
return {
person: undefined,
waiting: undefined,
basic: undefined,
sessionId: undefined,
tokenPerson: undefined,
oauth: ok,
badToken: !ok,
};
}
if (bearer?.startsWith(tokenPrefix)) {
const tok = await tokens.verify(bearer);
const owner = tok ? (await db.select().from(user).where(eq(user.id, tok.userId)))[0] : undefined;
@@ -903,6 +947,7 @@ export function createApp({
basic: undefined,
sessionId: undefined,
tokenPerson: tok && ok ? Object.assign(ok, { token: { id: tok.id, name: tok.name, grants: tok.grants } }) : undefined,
oauth: undefined,
badToken: !(tok && ok),
};
}
@@ -918,30 +963,31 @@ export function createApp({
basic: usable?.kind === "basic" ? usable : undefined,
sessionId: s?.session.id,
tokenPerson: undefined,
oauth: undefined,
badToken: false,
};
})
.macro({
/** Signed in: approved, still waiting, or a basic account. */
account: {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (tokenPerson || oauth || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
const me = person ?? waiting ?? basic;
if (!me) throw new Problem(401, "signed_out", "Sign in first.");
return { me };
},
},
signedIn: {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (tokenPerson || oauth || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person };
},
},
moderator: {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => {
if (tokenPerson || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (tokenPerson || oauth || badToken) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
if (!isModerator(person)) throw new Problem(403, "forbidden", "Only moderators can do this.");
@@ -950,14 +996,33 @@ export function createApp({
},
/** Signed in, or an API token (whose grants then limit every permission check). */
scripted: {
resolve: ({ person, waiting, basic, tokenPerson, badToken }) => {
resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (badToken) throw new Problem(401, "bad_token", "That token isn't valid: wrong, revoked or expired.");
if (oauth) throw new Problem(403, "token_not_allowed", "This token can't do this.");
if (tokenPerson) return { me: tokenPerson };
notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person };
},
},
/**
* Linking IMVU accounts: signed in on the website (a member), or one of T5DE's sites with the person's access
* token and the `imvu:link` scope (any account, basic ones too: docs/music.md, IMVU linking).
*/
linking: {
resolve: ({ person, waiting, basic, tokenPerson, oauth, badToken }) => {
if (badToken) throw new Problem(401, "bad_token", "That token isn't valid: wrong or expired.");
if (oauth) {
if (!oauth.scopes.includes("imvu:link"))
throw new Problem(403, "insufficient_scope", "This token can't link IMVU accounts (it needs the imvu:link scope).");
return { me: oauth.person };
}
if (tokenPerson) throw new Problem(403, "token_not_allowed", "API tokens can't do this. Sign in on the website.");
notMemberYet(waiting, basic);
if (!person) throw new Problem(401, "signed_out", "Sign in first.");
return { me: person };
},
},
})
// Who's signed in, and the home page.
@@ -976,6 +1041,19 @@ export function createApp({
},
{ account: true },
)
// A site that signs people in through the hub, by its client ID: its name, for the sign-in and consent pages.
.get(
"/oauth/clients/:clientId",
async ({ params }) => {
const [c] = await db
.select({ name: schema.oauthClient.name, skipConsent: schema.oauthClient.skipConsent, disabled: schema.oauthClient.disabled })
.from(schema.oauthClient)
.where(eq(schema.oauthClient.clientId, params.clientId));
if (!c || c.disabled) throw new Problem(404, "not_found", "No such site.");
return { client: { name: c.name ?? params.clientId, firstParty: c.skipConsent === true } };
},
{ params: t.Object({ clientId: t.String({ minLength: 1, maxLength: 128 }) }) },
)
// The hub's public settings: whether new accounts wait for approval, and whether Discord sign-in is on.
.get("/hub", async () => ({ registration: await settings.registration(), discord: discordOn }))
.get("/home", async ({ person }) => {
@@ -1083,7 +1161,9 @@ export function createApp({
const [taken] = await db.select({ id: user.id }).from(user).where(sql`lower(${user.username}) = lower(${name})`);
if (taken) throw new Problem(409, "username_taken", "That username is taken. Try another.");
const hash = await (await auth.$context).password.hash(body.password);
const approved = (await settings.registration()) === "open";
// Locked: a moderator has already approved this person (or they're still waiting), so finishing changes nothing.
const registration = await settings.registration();
const approved = registration === "open" || (registration === "locked" && me.approved === true);
let updated: Person | undefined;
try {
updated = await db.transaction(async (tx) => {
@@ -1139,6 +1219,31 @@ export function createApp({
},
{ scripted: true, params: imvuIdParam },
)
// A person's IMVU accounts and links in progress, for T5DE's sites (Music) with an imvu:link token, or the website.
.get(
"/account/imvu",
async ({ me }) => {
const links = await db.select().from(imvuLink).where(eq(imvuLink.userId, me.id)).orderBy(imvuLink.linkedAt);
const challenges = await db
.select()
.from(linkChallenge)
.where(and(eq(linkChallenge.userId, me.id), sql`${linkChallenge.createdAt} > now() - interval '1 day'`))
.orderBy(linkChallenge.createdAt);
return {
links: links.map((l) => ({ imvuId: l.imvuId, username: l.username, linkedAt: l.linkedAt.toISOString() })),
challenges: challenges.map((c) => ({
imvuId: c.imvuId,
username: c.username,
code: c.code,
createdAt: c.createdAt.toISOString(),
expiresAt: new Date(c.createdAt.getTime() + challengeLifetime).toISOString(),
})),
linkCap: me.linkCap,
canLink: links.length < me.linkCap,
};
},
{ linking: true },
)
.post(
"/account/links",
async ({ me, body, set }) => {
@@ -1166,7 +1271,7 @@ export function createApp({
},
};
},
{ signedIn: true, body: t.Object({ username: t.String({ minLength: 1, maxLength: 64 }) }) },
{ linking: true, body: t.Object({ username: t.String({ minLength: 1, maxLength: 64 }) }) },
)
.post(
"/account/links/:imvu/check",
@@ -1234,7 +1339,7 @@ export function createApp({
await realtime.linked(me.id, found.id);
return { link: await linkView(result.link), moved: result.moved };
},
{ signedIn: true, params: imvuIdParam },
{ linking: true, params: imvuIdParam },
)
.delete(
"/account/challenges/:imvu",
@@ -1242,7 +1347,7 @@ export function createApp({
await db.delete(linkChallenge).where(and(eq(linkChallenge.userId, me.id), eq(linkChallenge.imvuId, params.imvu)));
set.status = 204;
},
{ signedIn: true, params: imvuIdParam },
{ linking: true, params: imvuIdParam },
)
.patch(
"/account/links/:imvu",
@@ -1292,7 +1397,7 @@ export function createApp({
await audited(me, "link.remove", String(l.imvuId), { imvu: l.username });
set.status = 204;
},
{ signedIn: true, params: imvuIdParam },
{ linking: true, params: imvuIdParam },
)
.post(
"/account/signout-computers",
@@ -3494,7 +3599,7 @@ export function createApp({
query: t.Object({ q: t.Optional(t.String({ maxLength: 64 })), waiting: t.Optional(t.BooleanString()) }),
},
)
// Accounts waiting for approval (registration closed): approve, or decline (the account is deleted).
// Accounts waiting for approval (registration closed or locked): approve, or decline (the account is deleted).
.post(
"/console/people/:id/approve",
async ({ me, params }) => {
@@ -3529,7 +3634,7 @@ export function createApp({
},
{
moderator: true,
body: t.Object({ registration: t.Union([t.Literal("open"), t.Literal("closed")]) }),
body: t.Object({ registration: t.Union([t.Literal("open"), t.Literal("closed"), t.Literal("locked")]) }),
},
)
.get(
+138 -8
View File
@@ -1,11 +1,13 @@
// Accounts, sessions and proxy sign-in, by Better Auth: email and password with usernames, roles and bans (admin),
// Discord sign-in (basic accounts, docs/music.md), device sign-in for T5DE's proxy (RFC 8628), bearer tokens for the
// proxy's requests, and JWTs with published keys (for catalogs later), and two-factor sign-in (an authenticator app,
// with backup codes).
// proxy's requests, JWTs with published keys, two-factor sign-in (an authenticator app, with backup codes), and the
// hub as an OAuth 2.1 / OpenID Connect provider for T5DE's own sites (Music first).
import { timingSafeEqual } from "node:crypto";
import { oauthProvider } from "@better-auth/oauth-provider";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { admin, bearer, deviceAuthorization, jwt, twoFactor, username } from "better-auth/plugins";
import { count, eq, schema, type Database } from "@t5de/db";
import { and, asc, count, eq, schema, type Database } from "@t5de/db";
import { Settings } from "./settings";
export type AuthConfig = {
@@ -17,13 +19,60 @@ export type AuthConfig = {
secret: string;
/** Rate limits on sign-up, sign-in and the rest (on unless false: tests turn them off). */
rateLimit?: boolean;
/** Whether new accounts wait for approval (default: the hub's settings, with no environment defaults). */
/** Whether new accounts wait for approval, and whether unapproved ones may sign in to other sites (default: the
* hub's settings, with no environment defaults). */
settings?: Settings;
/** Discord sign-in (an application at discord.com/developers, redirecting to API_URL/api/auth/callback/discord);
* off without it. */
discord?: { clientId: string; clientSecret: string };
/** T5DE's own sites that sign people in through the hub (OpenID Connect): trusted, so there's no consent screen,
* and they may ask for the `imvu` scope. Made or updated at startup (seedClients). */
clients?: FirstPartyClient[];
/** Let clients use plain-HTTP redirect URIs on localhost (development only: a client running locally). */
localRedirects?: boolean;
};
/** A T5DE site that signs people in through the hub. */
export type FirstPartyClient = {
/** e.g. t5de-music */
clientId: string;
/** Shown to people, e.g. T5DE Music */
name: string;
/** At least 32 random characters; the hub keeps only its hash. */
secret: string;
/** Where the hub may send people back with a code, e.g. https://music.t5de.dev/api/auth/callback */
redirectUris: string[];
};
/**
* What OpenID Connect clients may ask for. `imvu`: the person's linked IMVU accounts, real IDs and names (first-party
* sites only: they act in IMVU rooms). `imvu:link`: link and unlink IMVU accounts on the person's behalf, through the
* hub's API.
*/
export const oauthScopes = ["openid", "profile", "email", "offline_access", "imvu", "imvu:link"] as const;
/** The hub's own API as an OAuth resource: access tokens for it (`resource` in the request) are JWTs it checks. */
export const hubResource = (apiURL: string) => `${apiURL.replace(/\/+$/, "")}/api/v1`;
/** How client secrets are kept (SHA-256, base64url); seedClients stores first-party secrets the same way. */
async function hashSecret(secret: string): Promise<string> {
return Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret))).toString("base64url");
}
async function verifySecret(secret: string, stored: string): Promise<boolean> {
const a = Buffer.from(await hashSecret(secret));
const b = Buffer.from(stored);
return a.length === b.length && timingSafeEqual(a, b);
}
/** A person's linked IMVU accounts, as the `imvu` claim gives them. */
async function imvuClaim(db: Database, userId: string) {
return db
.select({ id: schema.imvuLink.imvuId, username: schema.imvuLink.username })
.from(schema.imvuLink)
.where(eq(schema.imvuLink.userId, userId))
.orderBy(asc(schema.imvuLink.linkedAt));
}
/** The proxy's client ID in device sign-in. */
export const proxyClientID = "t5de-proxy";
@@ -52,6 +101,8 @@ export function createAuth(db: Database, config: AuthConfig) {
secret: config.secret,
trustedOrigins: [config.webURL],
database: drizzleAdapter(db, { provider: "pg", schema }),
// The JWT plugin's /token (a session as a JWT) is off: the OAuth provider issues tokens instead.
disabledPaths: ["/token"],
emailAndPassword: { enabled: true, minPasswordLength: passwordRules.min, maxPasswordLength: passwordRules.max },
socialProviders: config.discord
? { discord: { clientId: config.discord.clientId, clientSecret: config.discord.clientSecret } }
@@ -95,10 +146,10 @@ export function createAuth(db: Database, config: AuthConfig) {
create: {
before: async (u, ctx) => {
// Made by signing in with Discord (the OAuth callback): a basic account. It can use T5DE's other sites
// at once; the hub's features wait until it finishes setting up (and then for approval, if registration
// is closed).
// at once (unless registration is locked: then it waits for approval first); the hub's features wait
// until it finishes setting up (and then for approval, if registration is closed).
if (ctx?.path?.startsWith("/callback/"))
return { data: { ...u, role: "user", approved: true, kind: "basic" } };
return { data: { ...u, role: "user", approved: (await settings.registration()) !== "locked", kind: "basic" } };
// The first member runs the hub; with registration closed, the others wait for approval.
const [row] = await db.select({ n: count() }).from(schema.user).where(eq(schema.user.kind, "member"));
const first = (row?.n ?? 0) === 0;
@@ -125,9 +176,88 @@ export function createAuth(db: Database, config: AuthConfig) {
// Once it's on, signing in asks for a code from the app (or a backup code). The hub's own routes require it for
// sensitive permissions (permissions.ts `sensitive`).
twoFactor({ issuer: "T5DE", backupCodeOptions: { amount: 10, length: 10 } }),
jwt({ jwks: { keyPairConfig: { alg: "EdDSA", crv: "Ed25519" } } }),
jwt({ jwks: { keyPairConfig: { alg: "EdDSA", crv: "Ed25519" } }, disableSettingJwtHeader: true }),
// The issuer is API_URL/api/auth (discovery at /api/auth/.well-known/openid-configuration). People sign in on the
// website's /signin, which sends them back to the authorize endpoint; trusted clients skip /consent.
oauthProvider({
loginPage: `${config.webURL}/signin`,
consentPage: `${config.webURL}/consent`,
// With registration locked (staging), only approved accounts sign in to T5DE's other sites: anyone else is
// sent to the website, which says they're waiting for approval, and no code is issued. Checked again on
// every authorize request, including /oauth2/continue, so there's no way past it but approval.
postLogin: {
page: `${config.webURL}/`,
consentReferenceId: () => undefined,
shouldRedirect: async ({ user }) => user.approved !== true && (await settings.registration()) === "locked",
},
scopes: [...oauthScopes],
cachedTrustedClients: new Set((config.clients ?? []).map((c) => c.clientId)),
storeClientSecret: { hash: hashSecret, verify: verifySecret },
allowInsecureRedirectUri: (url) => config.localRedirects === true && ["localhost", "127.0.0.1"].includes(url.hostname),
resources: [{ identifier: hubResource(config.apiURL), name: "T5DE Hub API", allowedScopes: [...oauthScopes] }],
advertisedMetadata: {
scopes_supported: [...oauthScopes],
claims_supported: [
"sub", "iss", "aud", "exp", "iat", "sid", "scope", "azp",
"name", "preferred_username", "email", "email_verified", "picture", "imvu",
],
},
customUserInfoClaims: async ({ user, scopes }) => ({
...(scopes.includes("profile") && typeof user.username === "string"
? { preferred_username: typeof user.displayUsername === "string" ? user.displayUsername : user.username }
: {}),
...(scopes.includes("imvu") ? { imvu: await imvuClaim(db, user.id) } : {}),
}),
customIdTokenClaims: async ({ user, scopes }) => (scopes.includes("imvu") ? { imvu: await imvuClaim(db, user.id) } : {}),
}),
],
});
}
export type Auth = ReturnType<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 sign-in (basic accounts, docs/music.md); its redirect URL is
// 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
// 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
@@ -18,7 +22,7 @@ import { AgeService, type Provider } from "./age";
import { diditAgeProvider } from "./age/didit";
import { imvuAgeProvider } from "./age/imvu";
import { createApp } from "./app";
import { createAuth } from "./auth";
import { createAuth, seedClients, type FirstPartyClient } from "./auth";
import { Settings } from "./settings";
import { ImvuClient } from "./imvu";
@@ -39,7 +43,22 @@ const discord =
env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET
? { clientId: env.DISCORD_CLIENT_ID, clientSecret: env.DISCORD_CLIENT_SECRET }
: 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();
function required(name: string): string {
+8 -4
View File
@@ -4,9 +4,13 @@ import { eq, schema, type Database } from "@t5de/db";
const { hubSetting } = schema;
/** Open: new accounts can use the hub at once. Closed: they can sign in, and wait for a moderator's approval. */
export type Registration = "open" | "closed";
export const registrations: readonly Registration[] = ["open", "closed"];
/**
* Open: new accounts can use the hub at once. Closed: they can sign in, and wait for a moderator's approval (accounts
* from Discord sign-in can still use T5DE's other sites at once). Locked, for staging: every new account waits for
* approval, Discord ones too, and only approved accounts sign in to T5DE's other sites (auth.ts, postLogin).
*/
export type Registration = "open" | "closed" | "locked";
export const registrations: readonly Registration[] = ["open", "closed", "locked"];
export class Settings {
constructor(
@@ -17,7 +21,7 @@ export class Settings {
async registration(): Promise<Registration> {
const [row] = await this.db.select().from(hubSetting).where(eq(hubSetting.key, "registration"));
const value = row?.value ?? this.defaults.registration;
return value === "closed" ? "closed" : "open";
return value === "closed" || value === "locked" ? value : "open";
}
async setRegistration(value: Registration) {
+20 -1
View File
@@ -2,7 +2,7 @@
// verified email only, and never links by matching email; a basic account finishes setting up with a username and
// password; a member links Discord from their own session. Discord itself is stood in for below.
import { afterAll, beforeAll, expect, test } from "bun:test";
import { openDatabase, type Database } from "@t5de/db";
import { eq, openDatabase, schema, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { ImvuClient } from "../src/imvu";
@@ -203,3 +203,22 @@ test("a member links Discord from their own session; a Discord account already i
expect(refused.searchParams.get("error")).toBe("account_already_linked_to_different_user");
expect((await call(fay, "GET", "/api/v1/account")).json.discord.linked).toBe(false);
});
test("with registration locked, a Discord sign-in waits for approval too, and finishing setup keeps the approval", async () => {
await settings.setRegistration("locked");
try {
const gil: Cookie = { v: "" };
await viaDiscord(gil, { id: "1008", username: "gil", email: "[email protected]", verified: true });
const me = (await call(gil, "GET", "/api/v1/me")).json.person;
expect(me).toMatchObject({ kind: "basic", approved: false });
// Approved by a moderator, then finishing setup: still approved.
await db.update(schema.user).set({ approved: true }).where(eq(schema.user.id, me.id));
expect((await call(gil, "POST", "/api/v1/account/finish", { username: "gil", password: "a long password" })).json.person).toMatchObject({
kind: "member",
approved: true,
});
} finally {
await settings.setRegistration("open");
}
});
+223
View File
@@ -0,0 +1,223 @@
// 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;
let settings: Settings;
beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
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);
});
test("with registration locked, only approved accounts sign in to Music; closed doesn't stop anyone", async () => {
// Closed (prod): a member waiting for the hub's approval still signs in to Music.
await settings.setRegistration("closed");
const eli = await signUp("eli");
expect((await call(eli, "GET", "/api/v1/me")).json.person.approved).toBe(false);
await musicSignIn(eli);
await settings.setRegistration("locked");
try {
const fin = await signUp("fin");
const id = (await call(fin, "GET", "/api/v1/me")).json.person.id;
// Sent to the website (which says they're waiting), with no code for Music.
const a = await authorizeURL("openid profile imvu");
const r = await call(fin, "GET", a.path);
expect(r.status).toBe(302);
const to = new URL(r.location);
expect(to.origin + to.pathname).toBe(`${webURL}/`);
expect(to.searchParams.get("code")).toBeNull();
// Continuing from that page doesn't get past it either.
const cont = await call(fin, "POST", "/api/auth/oauth2/continue", { postLogin: true, oauth_query: to.search.slice(1) });
const again = new URL(cont.json.url);
expect(again.origin + again.pathname).toBe(`${webURL}/`);
expect(again.searchParams.get("code")).toBeNull();
// Nor does eli, approved for nothing: locked holds back everyone unapproved.
const b = await call(eli, "GET", (await authorizeURL("openid")).path);
expect(new URL(b.location).origin + new URL(b.location).pathname).toBe(`${webURL}/`);
// Once a moderator approves, it works.
await db.update(schema.user).set({ approved: true }).where(eq(schema.user.id, id));
await musicSignIn(fin);
} finally {
await settings.setRegistration("open");
}
});
+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>
);
}
+7 -2
View File
@@ -69,9 +69,14 @@ export async function decideAccount(_: ActionState, form: FormData): Promise<Act
export async function setRegistration(_: ActionState, form: FormData): Promise<ActionState> {
return attempt(async () => {
const registration = field(form, "registration") === "closed" ? "closed" : "open";
const value = field(form, "registration");
const registration = value === "closed" || value === "locked" ? value : "open";
unwrap(await api.console.settings.put({ registration }));
revalidatePath("/console");
return registration === "closed" ? "Registration closed: new accounts wait for approval." : "Registration open.";
return registration === "locked"
? "Registration locked: every new account waits for approval, and only approved ones sign in to other sites."
: registration === "closed"
? "Registration closed: new accounts wait for approval."
: "Registration open.";
});
}
+4 -1
View File
@@ -71,7 +71,9 @@ export default async function Console() {
<CardHeader>
<CardTitle>Registration</CardTitle>
<CardDescription>
{settings.registration === "closed"
{settings.registration === "locked"
? "Locked: every new account, Discord ones too, waits for a moderator's approval, and only approved accounts sign in to T5DE's other sites. For staging."
: settings.registration === "closed"
? "Closed: new accounts can sign in, but wait for a moderator's approval."
: "Open: new accounts can use the hub at once."}
</CardDescription>
@@ -82,6 +84,7 @@ export default async function Console() {
<NativeSelect name="registration" defaultValue={settings.registration} aria-label="Registration">
<NativeSelectOption value="open">Open</NativeSelectOption>
<NativeSelectOption value="closed">Closed</NativeSelectOption>
<NativeSelectOption value="locked">Locked</NativeSelectOption>
</NativeSelect>
<SubmitButton pendingLabel="Setting…">Set</SubmitButton>
</div>
+7 -1
View File
@@ -24,7 +24,13 @@ export default async function RootLayout({ children }: { children: React.ReactNo
<StagingBanner />
<Header />
<main className="mx-auto w-full max-w-5xl flex-1 px-4 py-10 sm:px-6 sm:py-14">
{me?.kind === "basic" ? (
{me?.kind === "basic" && !me.approved ? (
// Only while registration is locked (staging): Discord sign-ins wait for approval too.
<NarrowCard
title="Waiting for Approval"
description={`You're signed in with Discord as ${me.username}. A moderator will approve your account soon; until then you can't use the hub or T5DE's other sites.`}
/>
) : me?.kind === "basic" ? (
<NarrowCard
title="Finish Setting Up Your Account"
description={`You're signed in with Discord as ${me.username}. Choose a username and password to use the hub; T5DE's other sites already work with your Discord sign-in.`}
+15 -8
View File
@@ -6,28 +6,35 @@ import { NarrowCard } from "@/components/narrow-card";
import { Separator } from "@/components/ui/separator";
import { api, getMe, unwrap } from "@/lib/api";
import { discordError } from "@/lib/discord";
import { continueURL, requestedProvider, requestingClient } from "@/lib/oauth";
import { safeNext } from "@/lib/paths";
import { SignInForm } from "./signin-form";
export const metadata: Metadata = { title: "Sign in" };
export default async function SignIn({
searchParams,
}: {
searchParams: Promise<{ next?: string | string[]; error?: string | string[] }>;
}) {
export default async function SignIn({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
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);
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);
// 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 (
<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">
{error && <ErrorText>{error}</ErrorText>}
{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">
<Separator className="flex-1" />
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 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.refresh();
};
+1 -1
View File
@@ -10,7 +10,7 @@ export default async function SignUp() {
if (await getMe()) redirect("/account");
const { registration } = unwrap(await api.hub.get());
const description =
registration === "closed"
registration !== "open"
? "One T5DE account for all your IMVU accounts. New accounts need a moderator's approval."
: "One T5DE account for all your IMVU accounts.";
return (
+11 -2
View File
@@ -1,12 +1,13 @@
"use client";
// 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.
import { useState } from "react";
import { useEffect, useRef, useState } from "react";
import { ErrorText } from "@/components/forms";
import { Button } from "@/components/ui/button";
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 [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 (
<div className="space-y-2">
<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);
+2 -1
View File
@@ -10,13 +10,14 @@
},
"dependencies": {
"@base-ui/react": "^1.9.0",
"@better-auth/oauth-provider": "1.7.26",
"@elysiajs/eden": "1.4.9",
"@t5de/api": "workspace:*",
"better-auth": "1.7.26",
"class-variance-authority": "^0.7.1",
"cn": "^0.5.0",
"lucide-react": "^1.64.0",
"next": "16.4.3",
"next": "16.4.6",
"react": "19.3.1",
"react-dom": "19.3.1",
"server-only": "^0.0.1",
+15 -11
View File
@@ -11,6 +11,7 @@
"apps/api": {
"name": "@t5de/api",
"dependencies": {
"@better-auth/oauth-provider": "1.7.26",
"@t5de/db": "workspace:*",
"better-auth": "1.7.26",
"elysia": "1.4.30",
@@ -27,13 +28,14 @@
"name": "@t5de/web",
"dependencies": {
"@base-ui/react": "^1.9.0",
"@better-auth/oauth-provider": "1.7.26",
"@elysiajs/eden": "1.4.9",
"@t5de/api": "workspace:*",
"better-auth": "1.7.26",
"class-variance-authority": "^0.7.1",
"cn": "^0.5.0",
"lucide-react": "^1.64.0",
"next": "16.4.3",
"next": "16.4.6",
"react": "19.3.1",
"react-dom": "19.3.1",
"server-only": "^0.0.1",
@@ -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/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/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=="],
@@ -293,23 +297,23 @@
"@modelcontextprotocol/server": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@modelcontextprotocol/core": "2.4.0", "zod": "^4.2.0" } }, "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q=="],
"@next/env": ["@next/[email protected].3", "", {}, "sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ=="],
"@next/env": ["@next/[email protected].6", "", {}, "sha512-SunBjJ6t+oBtecS3dTjdVuMhUogP5wD/vrGL5EVuQYM1iS4O5ilL51HkiJ3sPjMzRHiCChvr4dbaSJbR7F3lxA=="],
"@next/swc-darwin-arm64": ["@next/[email protected].3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ=="],
"@next/swc-darwin-arm64": ["@next/[email protected].6", "", { "os": "darwin", "cpu": "arm64" }, "sha512-kJ4VVZkley17xKaJx72QN2IBqjrj7zenCQZaUF0l9ShS/1Mt2kW4+Z5KGG6vgr3L/J562xTOizVyM1iA/u5nlg=="],
"@next/swc-darwin-x64": ["@next/[email protected].3", "", { "os": "darwin", "cpu": "x64" }, "sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A=="],
"@next/swc-darwin-x64": ["@next/[email protected].6", "", { "os": "darwin", "cpu": "x64" }, "sha512-eIPGZIqC+8JKaeZmvnCANJQF4xWkkHqSnAAajtFxgwDMAOnCgxNvP52SeWZ41PyVwoe+Le/NQuZSaQ8j7YshSA=="],
"@next/swc-linux-arm64-gnu": ["@next/[email protected].3", "", { "os": "linux", "cpu": "arm64" }, "sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg=="],
"@next/swc-linux-arm64-gnu": ["@next/[email protected].6", "", { "os": "linux", "cpu": "arm64" }, "sha512-9nI6O8vvczH2D9ZNdMGqb/3NuT15T9ksOZnAmx9/gjF2cOi74+xxyf1Hk96uIMfm14c9y6wHeBq6SH8g6udvcA=="],
"@next/swc-linux-arm64-musl": ["@next/[email protected].3", "", { "os": "linux", "cpu": "arm64" }, "sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw=="],
"@next/swc-linux-arm64-musl": ["@next/[email protected].6", "", { "os": "linux", "cpu": "arm64" }, "sha512-7/qPhTxDp2ScluOJOhLuhWmlA17o1yZ0SIgpISBCpBxXgtnK4+KGywBpFkfLPiU1rnSM1faFGzYkH6i7JdTrqA=="],
"@next/swc-linux-x64-gnu": ["@next/[email protected].3", "", { "os": "linux", "cpu": "x64" }, "sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA=="],
"@next/swc-linux-x64-gnu": ["@next/[email protected].6", "", { "os": "linux", "cpu": "x64" }, "sha512-oOpbNa8XOW1qCGd9VvzC4fbkkRxEls7/WI6tz+YHC0xRA7KpV1U7DrAnCPjzVyOk/karzWEepCOcTIDmwK8FwQ=="],
"@next/swc-linux-x64-musl": ["@next/[email protected].3", "", { "os": "linux", "cpu": "x64" }, "sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw=="],
"@next/swc-linux-x64-musl": ["@next/[email protected].6", "", { "os": "linux", "cpu": "x64" }, "sha512-aM8CZ+OR2EwXaAYw7KGkW2GDmNDsLBIRe1MMRZCJPTdw/xhTD0IMUVO4sf3KqrzuRouGzwwLZn34+gFeVXiUQA=="],
"@next/swc-win32-arm64-msvc": ["@next/[email protected].3", "", { "os": "win32", "cpu": "arm64" }, "sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow=="],
"@next/swc-win32-arm64-msvc": ["@next/[email protected].6", "", { "os": "win32", "cpu": "arm64" }, "sha512-U0p7/tEtqvHX2crhd841CDwKtp5CFkKXVjOhmfccR3Pvp64sj8KBwRqsvltqLOwVBbj0NtkxwXSDpEHYGbxeXQ=="],
"@next/swc-win32-x64-msvc": ["@next/[email protected].3", "", { "os": "win32", "cpu": "x64" }, "sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg=="],
"@next/swc-win32-x64-msvc": ["@next/[email protected].6", "", { "os": "win32", "cpu": "x64" }, "sha512-3ZG15/5WIdlTQsIEvc9sPTTSL5XFrlLklIKmfF4fwsDnoAhu6NcBDXsk3mbGxNyo6aVLEGex+fHCv2MahY7a9g=="],
"@noble/ciphers": ["@noble/[email protected]", "", {}, "sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw=="],
@@ -723,7 +727,7 @@
"nanostores": ["[email protected]", "", {}, "sha512-FixtE239Gl6Gz0ZGCK0WzvNwObNCIwVT+L7zQcf1QgcA6AzBxblzqe9OT88qiucNkhsjSOqiogSaF5jVbJiqSA=="],
"next": ["[email protected].3", "", { "dependencies": { "@next/env": "16.4.3", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.5.23", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.4.3", "@next/swc-darwin-x64": "16.4.3", "@next/swc-linux-arm64-gnu": "16.4.3", "@next/swc-linux-arm64-musl": "16.4.3", "@next/swc-linux-x64-gnu": "16.4.3", "@next/swc-linux-x64-musl": "16.4.3", "@next/swc-win32-arm64-msvc": "16.4.3", "@next/swc-win32-x64-msvc": "16.4.3", "sharp": "^0.35.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA=="],
"next": ["[email protected].6", "", { "dependencies": { "@next/env": "16.4.6", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.5.23", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.4.6", "@next/swc-darwin-x64": "16.4.6", "@next/swc-linux-arm64-gnu": "16.4.6", "@next/swc-linux-arm64-musl": "16.4.6", "@next/swc-linux-x64-gnu": "16.4.6", "@next/swc-linux-x64-musl": "16.4.6", "@next/swc-win32-arm64-msvc": "16.4.6", "@next/swc-win32-x64-msvc": "16.4.6", "sharp": "^0.35.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-QZJiYhaZLJMo2KpkQGQIwvmd79WVsAWeYIU554a8d7zArS3si/IRy3lBNV/rtYhE70oLwdLYhPAXLPx8HwcwtA=="],
"node-releases": ["[email protected]", "", {}, "sha512-PfvofsGQ+MiOQIPkX9fU8ELUWmy5zL74CdQaph/ismKszfFkfwXaw0cGiwbwym2hT9k5+mdyl8O5WQ1MD8EHmA=="],
+5
View File
@@ -29,6 +29,11 @@ services:
DIDIT_API_KEY: ${DIDIT_API_KEY:-}
DIDIT_WORKFLOW_ID: ${DIDIT_WORKFLOW_ID:-}
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"]
depends_on:
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
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.
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 |
| `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
| | |
+33 -18
View File
@@ -10,8 +10,8 @@ accounts there without making a T5DE account first; one can be added later witho
## Goals
- **Cheap at scale**: listeners pull audio from a bandwidth-cheap host (Oracle Cloud's free tier to start), never
through home or the relay. A paid tier priced near cost, billed through a payments backend shared with the hub
(docs/payments.md).
through home or the relay. A paid tier priced near cost, through a Patreon membership and a payments service of
its own (docs/payments.md).
- **Three things to play** to start (**Decided**): existing internet radio stations (a searchable list from
radio-browser.info), the owner's own stream (bring your own), and a queue of songs found on YouTube. **More
sources later** without reworking anything (Sources, below). Jamendo and Audius are out for now: Jamendo's API is
@@ -84,6 +84,10 @@ The cost: Music's sign-in depends on the hub being up, and the hub gains a secon
Stored as a column on `user` (`kind: basic | member`); permissions treat basic accounts like unapproved ones on the
hub's own routes.
Staging is locked down (**Decided**): its registration is `locked`, so every new account, Discord ones too, waits for
a moderator's approval, and only approved accounts sign in to other sites (Music's and payments' staging). Prod
stays as above.
Email (**Decided**):
- Better Auth needs one, so a basic account takes Discord's, and only when Discord says it's verified. A Discord
@@ -255,14 +259,15 @@ both tiers, free with limits:
- **If YouTube breaks or has to go** (blocked, a takedown, a processor's demand), paid rooms keep everything they
paid for, and it's switched off without refunds.
- **What the pricing page sells** is music bot hosting, not "pay to play YouTube songs".
- **Free YouTube is the trial**: people use it, reach the limits, and upgrade.
- **What the pricing page sells** is music bot hosting, not "pay to play YouTube songs". YouTube's limits are the
same in both tiers (**Decided**), so nothing about YouTube is for sale.
- **The free tier is the trial**: people use it, want better audio or more listeners, and upgrade.
| | Free | Paid ($1.99 a month per room) |
| | Free | Paid ($1.99 a month per room with PayPal; Patreon: $1.99 for 1 room, $4.99 for 3) |
| --- | --- | --- |
| Rooms | 1 | One subscription per room |
| Rooms | 1 | As many as paid for, on top of the free one |
| Stations and own streams | Yes (direct where possible, so they cost nothing) | Yes |
| YouTube search and queue | Short queue, a few songs an hour | Unlimited queue, longer songs |
| YouTube search and queue | Fair-use limits: queue length, songs an hour, the longest song | The same |
| Audio | 64 kbps | 128 kbps |
| Listeners | A small cap (about 10) | Up to the room's capacity |
| Saved playlists, scheduled playback | No | Yes |
@@ -273,13 +278,23 @@ The free limits are what keep free YouTube affordable: it's always relayed (band
(CPU), unlike direct stations. The bot also leaves free rooms when they're empty. Exact limits are settings, tuned
once there's usage to look at.
Another way to pay, to check: **IMVU credits**, which every IMVU user already has. Buying a product we list in
IMVU's shop (a "Music Pass") is the payment, and the bot checks the buyer owns it. No processor at all, but it
depends on IMVU's rules for selling services and on how its credits cash out now; both to read before relying on it.
IMVU credits aren't a way to pay (**Decided**, docs/payments.md).
The paid entitlement is `music.room` with the room as its scope (docs/payments.md, Entitlements). Pricing: about
$1.99 a month per room (the most popular community bot starts at $4.99 for one room); on PayPal's micropayments
pricing that loses about 19¢ to fees. A yearly price at a discount on top.
**Paying** (**Decided**, docs/payments.md), from Music's Upgrade page; the payments service only redirects:
- **PayPal**: $1.99 a month or $19.99 a year per room, one subscription for any number of rooms. Outside the EU and
the UK at first (VAT, docs/payments.md).
- **Patreon**, linked to the person's account: a member has one tier, so tiers are room bundles, "Room" ($1.99 a
month, 1 room) and "Rooms" ($4.99, 3 rooms). After Patreon's 10% and processing, $1.99 is about $1.59. Yearly
memberships at a discount once Patreon turns them on for the page.
- Later, our own checkout embedded in the page, whichever processor is behind it (docs/payments.md, Checkout
elements).
The most popular community bot starts at $4.99 for one room.
The paid entitlement is `music.rooms`, a count (docs/payments.md, Concepts). The owner picks which of their rooms are
paid on the room's page, up to the count. If the count drops (a lapse, a smaller tier), the most recently picked
rooms go back to the free tier first, and the owner can swap which ones.
**One stream URL, many rooms.** The stream is plain HTTP, so anyone can paste a room's URL into other rooms (or any
player), and they'll all hear it. Only the bot's own room has commands, but every extra listener costs bandwidth,
@@ -324,9 +339,9 @@ published by CI like images. t5de-site moves from its copies to `@t5de/ui` when
charging for it makes it commercial. Relaying stations and owners' own streams is the safest part. Search providers
stay pluggable, so a licensed one can replace or join YouTube.
- **Payment processors**: Stripe and the merchants of record forbid selling services that infringe copyright, and
review what they're selling. A paid service built on YouTube's audio can get the merchant account closed, with
funds held. Music's merchant account is kept separate from T5DE's (docs/payments.md), so that can't take the hub's
payments with it.
Polar's rules name YouTube downloaders outright. A paid service built on YouTube's audio can get the account
closed, with funds held. Patreon is used, selling hosting only, and payments are a service of their own
(docs/payments.md), so a closed account can't take the hub or Music down with it.
- **YouTube from a datacenter**: yt-dlp from cloud IPs is often blocked ("confirm you're not a bot") and needs a
token provider, a JavaScript runtime and sometimes an account's cookies; it's also against YouTube's terms. Paying
users will expect it to work, so the operator setting that turns it off, and the status page, matter more.
@@ -347,7 +362,7 @@ published by CI like images. t5de-site moves from its copies to `@t5de/ui` when
DJs, bans, the stream URL. Infra: its stack and Postgres on t5de-apps, music.t5de.dev.
3. **Music, playing**: streamer with stations (relayed) and own streams, the bot with commands and permissions,
config sync. **Beta** (free tier).
3b. **Payments** (hub, docs/payments.md phases 1-2): entitlements, Music's processor, checkout; the paid tier.
3b. **Payments** (t5de-payments, docs/payments.md phases 1-2): entitlements and grants, Patreon; the paid tier.
4. **Search and queue**: content providers and the audio cache, the YouTube provider from HorizonRadio, MusicBrainz
metadata, `!play`, the queue page. (Phase 3's stations and own streams are already live providers.)
5. **Accounts, later**: merging basic into member accounts, `user.merged`, third-party OIDC clients (console,
@@ -355,5 +370,5 @@ published by CI like images. t5de-site moves from its copies to `@t5de/ui` when
## Open decisions
- The free tier's exact limits, and the yearly price (Paid tier, above).
- The free tier's exact limits, and YouTube's fair-use limits (Paid tier, above).
- Direct mode's details, once phase 0 has found the call that sets a room's radio and On Air.
+235 -91
View File
@@ -1,133 +1,277 @@
# Payments (plan)
Status: proposal for review (2026-11-18). Nothing here is **Decided** yet; open decisions are at the end.
Status: draft (2026-11-20; PayPal added the same day). Decisions marked **Decided** were agreed in discussion; the
rest are proposals. Open decisions are at the end.
Paid offerings for Music now (docs/music.md, Paid tier) and for the hub later, through one billing backend. More
than one payment processor from the start, because T5DE has adult content and the mainstream processors forbid it,
while Music has none.
Paid offerings for Music now (docs/music.md, Paid tier) and maybe for the hub later. Payments are their own service,
`t5de-payments`. The first ways to pay are a Patreon membership and a PayPal subscription; later, our own checkout
in which the processor doesn't show.
## Goals
- **One place** for prices, subscriptions and what people have paid for, keyed by the T5DE account (basic or member:
someone who only uses Music can pay).
- **Several processors**, chosen per merchant, behind one interface: switching one touches no app.
- **No card data** anywhere of ours: hosted checkout pages and portals only.
- **Apps ask one question**: does this account have entitlement X (for room Y)? They never talk to a processor.
- **Contain the risk** (**Decided**): processor accounts, their keys, payment records and webhooks live in one small
service with its own database and secrets, apart from the hub and Music. A processor closing an account, or a
payments bug, touches only this service; the hub and Music never hold a processor's key.
- **As little tax work as possible** (**Decided**): Patreon is the seller, so tax on its sales is its own. PayPal
makes us the seller: EU VAT through the non-Union One Stop Shop, worked out and recorded by this service (PayPal,
below); US sales tax only past a state's threshold.
- **No IMVU credits** (**Decided**).
- **No card data** anywhere of ours: the processor's own pages and buttons take the payment.
- **Apps ask one question**: how much of entitlement X does this account have? They never talk to a processor.
- **Eventually, the processor doesn't show** (**Decided**, later): people check out in our own checkout, embedded
from `payments.t5de.dev` in the app's page (Checkout elements, below), and which processor takes the payment is
ours to choose. Patreon is for now.
## Where it lives
## Where it lives (**Decided**)
In the hub's API, next to accounts (a module, `billing`), because the customer is the account. It moves with
accounts if they're ever split out (`accounts.t5de.dev`, docs/music.md). Apps reach it through the hub's API with the
person's access token, and the hub tells them about changes over the same signed back-channel as `user.merged`.
`t5de-payments`: its own repository, image, stack and Postgres database, at `payments.t5de.dev`. Deployed like the
other stacks, with its secrets in sops like theirs.
**Environments** (**Decided**): staging (`payments.staging.t5de.dev`) signs in through staging's hub and uses the
processors' test modes (PayPal's sandbox); prod (`payments.t5de.dev`) uses the live ones. Staging's hub registration
is locked, so only accounts a moderator approved can use it (docs/music.md, Kinds of account).
- **Who's who**: it's an OIDC client of the hub (docs/music.md, The OIDC provider), like Music, and knows people by
their `sub`. It never sees their IMVU accounts or rooms.
- **Apps read entitlements** with their own client credentials, `GET /v1/entitlements/{sub}`, and are told about
changes over a signed back-channel call (`entitlements.changed {sub}`, as `user.merged`), after which they read
again. Music keeps the last answer, so payments being down doesn't change any room.
- **No website of its own** (**Decided**): the pages people see (Upgrade, Billing under Account, "Make this room
paid") are the app's, built from this service's API (`GET /v1/accounts/{sub}`: entitlements, links and sources,
for the Billing page). What the browser goes through here only redirects:
- `/link/patreon`: signs in through the hub (at once: they're already signed in), sends them to Patreon to
approve, and back to the app.
- `/checkout/paypal?offer=…&rooms=…&country=…`: makes the subscription (rooms, VAT), sends them to PayPal to
approve, and back.
- `/manage/<source>`: to Patreon's or PayPal's own page for changing or cancelling.
Every redirect back goes only to a return address on the app's list (no open redirects).
```
music.t5de.dev ──checkout──► hub API (billing) ──hosted checkout──► processor (Stripe for Music)
▲ │ ▲ │
└── entitlement.changed ──┘ └──────────── webhooks ◄─────────────────┘
music.t5de.dev ── /link, /checkout ──► payments.t5de.dev ◄── webhooks, API ──► Patreon, PayPal
▲ │
└─── entitlements.changed, API ─────────┘
```
## Concepts
| | What |
| --- | --- |
| **Merchant** | Who sells, with its processor account: `music` and `t5de`. Products belong to one merchant and never mix, so a processor that bans adult content only ever sees Music's sales, and one merchant account being closed can't take the other's payments with it. |
| **Product, price** | What's sold and for how much (`music.room`, yearly). |
| **Customer** | An account at one merchant's processor: `(account, merchant) → processor customer ID`. |
| **Subscription** | Mirrored from the processor: status, period end, cancel at period end. |
| **Payment event** | Every webhook, kept as received. Unique by `(processor, event ID)`, so a replay changes nothing. |
| **Entitlement** | What apps check: `{account, key, scope, from, until, source}`, e.g. `music.room` scoped to a room. Made from subscriptions, from moderators' grants (gifts, testers; console, audited) and later from codes. |
| **Provider** | Where money comes from: `patreon`, `paypal`, maybe `polar` (Processors, below), `grant` for moderators' gifts and testers. |
| **Link** | A person's account at a provider: `(sub, provider) → provider's user ID`, unique both ways (Patreon; a PayPal subscription carries the `sub` itself). |
| **Source** | One thing that grants: a Patreon membership, a PayPal subscription, a grant. Mirrored from the provider: status, tier or quantity, paid until. |
| **Event** | Every webhook as received, with its verdict. Kept for the audit log; never trusted for state (below). |
| **Entitlement** | What apps read: `{sub, key, quantity, until, source}`, e.g. `music.rooms` × 3 until a date. An account's total is the sum of its live entitlements per key. |
Processing a webhook doesn't trust its order: it fetches the subscription's current state from the processor and
recomputes that account's entitlements from it. Late, repeated or reordered events then all end in the same place.
Entitlements are counts, not tied to a room: a Patreon member has one tier, so tiers are room bundles. Music decides
which of the owner's rooms are paid (docs/music.md, Paid tier).
## Processor adapters
Every change recomputes: a webhook, a nightly sync or a grant fetches the source's current state from the provider
and recomputes that account's entitlements from all its sources. Late, repeated, missed or reordered events then all
end in the same place.
```ts
interface Processor {
checkout(customer, price, scope, returnURL): Promise<{ url: string }>;
portal(customer, returnURL): Promise<{ url: string }>;
cancel(subscription, { atPeriodEnd: boolean }): Promise<void>;
refund(payment, amount?): Promise<void>;
// Verifies the signature and maps the processor's event to ours.
webhook(request): Promise<BillingEvent | null>;
subscription(id): Promise<SubscriptionState>;
}
## Patreon (**Decided**: first)
Patreon is the seller: it collects and remits VAT and US sales tax where required, runs payments, retries, refunds and
cancelling, and pays out. The page is T5DE Music's alone and marked not for adults; the hub's adult offerings never go
on it. Fees: 10% of income plus payment processing (patreon.com/pricing).
Set up by hand on patreon.com (the API reads tiers, it can't write them): the page, the tiers, payouts and tax
details, and an API client in the developer portal (redirect URIs `https://payments.t5de.dev/patreon/callback` and
`https://payments.staging.t5de.dev/patreon/callback`). Patreon has no test mode: staging uses the real page, with
memberships of our own.
**Configuration, in git**: the campaign's ID and each tier's ID with what it grants:
```yaml
patreon:
campaign: "<campaign ID>"
tiers:
"<Room tier ID>": { music.rooms: 1 }
"<Rooms tier ID>": { music.rooms: 3 }
```
Webhooks arrive at `POST /api/v1/billing/webhooks/<processor>` on the hub's API. Processors retry for days, so a hub
outage only delays them.
A tier that isn't listed grants nothing (a free membership, a tier for something else).
**Linking**: signed in, the person presses "Link Patreon" and approves our client on Patreon (scope `identity`). We
keep their Patreon user ID; `include=memberships` on `/identity` shows their membership to our campaign. A membership
whose Patreon account isn't linked yet grants nothing until it is, then counts at once. One Patreon account links to
one T5DE account; linking it elsewhere asks to unlink first.
**The creator token** (the developer portal's, scopes `campaigns`, `campaigns.members`, `w:campaigns.webhook`) reads
members and manages the webhook. It's seeded from sops; Patreon's refresh hands out a new refresh token each time, so
the current pair lives in the database, and an expiring or refused token is an alert.
**The webhook** is ours to keep right: on start the service lists its webhooks (`/api/oauth2/v2/webhooks` shows only
our client's), creates one if there's none, and patches its URI, triggers and `paused: false` if they've drifted.
The secret Patreon returns is kept in the database.
- Triggers: `members:create`, `members:update`, `members:delete`, `members:pledge:create`, `members:pledge:update`,
`members:pledge:delete`.
- Each request is checked against `X-Patreon-Signature` (the hex HMAC-MD5 of the body with the webhook's secret)
before anything else; then the member is fetched again (`/api/oauth2/v2/members/{id}`, with
`currently_entitled_tiers`) and that account recomputed.
- Patreon retries for a week and then pauses the webhook. The start-up check unpauses it, and a **nightly sync** of
every member (`/campaigns/{id}/members`) catches anything missed.
**From a member to an entitlement**:
| Patreon says | Entitlement |
| --- | --- |
| `patron_status: active_patron`, a listed tier in `currently_entitled_tiers` | The tier's grant, until `next_charge_date` plus 7 days' grace |
| `declined_patron` (a failed charge; Patreon retries) | Kept until the grace runs out |
| `former_patron`, deleted, or no listed tier | None |
Yearly memberships (`pledge_cadence: 12`) need nothing more: their `next_charge_date` is a year off. Patreon turns
them on for a page after some membership history; we've asked to be included.
Refunds, chargebacks and cancelling are Patreon's; the member's status follows them and our entitlement with it.
## PayPal (**Decided**: beside Patreon)
A PayPal business account (a sole proprietor, "T5DE Music" on receipts) with PayPal Subscriptions. We are the seller,
so the tax is ours (Tax, below). It sells exactly what the pricing says: **$1.99 a month or $19.99 a year per room**,
one subscription with a quantity (3 rooms is quantity 3), which Patreon's one-tier memberships can't.
**Product and plans** are made through PayPal's API and kept in the configuration (they're IDs, per environment):
```yaml
paypal:
product: PROD-… # "T5DE Music Room", a service, category software
plans:
music.rooms.monthly: P-… # $1.99 a month per room, quantity allowed
music.rooms.yearly: P-… # $19.99 a year per room
```
Prices change through the API (`update-pricing-schemes`) without new plans; how that reaches existing subscribers
(and the notice they're owed) is to check before the first change.
**Checkout** (`/checkout/paypal`): signed in, with the offer, the number of rooms and the buyer's country. The service
makes the subscription with `custom_id` = their `sub`, the quantity, and the VAT for their country (below) as a
plan override, then sends them to PayPal's approval page; PayPal sends them back to the app. Nothing is granted on
the way back: only PayPal's own word (the webhook, or fetching the subscription) does.
**The webhook** is made through the API too, on start (as Patreon's), for `BILLING.SUBSCRIPTION.ACTIVATED`,
`.UPDATED`, `.CANCELLED`, `.SUSPENDED`, `.EXPIRED`, `.PAYMENT.FAILED`, `PAYMENT.SALE.COMPLETED`, `.REFUNDED` and
`.REVERSED`. Each request is verified by PayPal (`/v1/notifications/verify-webhook-signature`, with our webhook's
ID) before anything else; then the subscription is fetched again and its account recomputed. A nightly sync fetches
every subscription the database knows.
**From a subscription to an entitlement**:
| PayPal says | Entitlement |
| --- | --- |
| `ACTIVE` | `music.rooms` × quantity, until `billing_info.next_billing_time` plus 7 days' grace |
| `SUSPENDED` (payments failed 3 times) | Kept until the grace runs out |
| `CANCELLED`, `EXPIRED` | Until the end of the period last paid for, then none |
| A refund or reversal of the last payment | None, at once |
**Where it sells**: everywhere but the EU and the UK at first; the EU once our One Stop Shop registration takes
effect; the UK once registered with HMRC (until then people there use Patreon). The checkout asks for the country and
refuses the ones not open yet.
**Fees**: about 3.49% + 49¢ (56¢ of $1.99) until PayPal enrolls the account in Dynamic Micropayments (4.99% + 9¢,
whichever is cheaper per payment), asked of PayPal support.
### Tax
- **EU VAT** (non-Union OSS, registered in one EU country, Ireland by default): VAT at the buyer's country's rate,
**included** in the price, so $1.99 is $1.99 everywhere. The rate table is in the configuration. Two pieces of
evidence of the country, recorded with each subscription: what the buyer chose and their IP address's country.
If they disagree, no sale; they're asked to check. One return a quarter, made from our own records (`vat-report
<quarter>`), even when there were no EU sales.
- **UK VAT**: the same, once registered with HMRC.
- **US sales tax**: none to start. A state's tax applies only past its threshold (usually $100k of sales, in a few
states also 200 transactions a year); the service reports sales per state, so we see one coming.
- Elsewhere: registration only past thresholds far above our sales (Norway, Switzerland, Australia and others).
## Checkout elements (later)
Our own checkout, so people don't see which processor takes the payment and Patreon can go: the payment parts of
the app's pages are iframes from `payments.t5de.dev/elements/…` (the offer, rooms, country and VAT, and the
processor's own buttons or card fields inside), so the app's page never handles prices, tax or payment details.
- The app frames them; only the apps on a list may (`frame-ancestors`). They tell the app's page when they're done or
need more room (`postMessage`, checked against the origin).
- Who's paying: the hub's sign-in can't be framed (it refuses, as it should), so the app hands the element a
short-lived token for the person (signed by the hub, for this service only). Cookies aren't in the way: the apps
and `payments.t5de.dev` are the same site.
- The redirects above stay, for anything that can't be embedded.
## Grants
Moderators give entitlements without money (testers, gifts, apologies): `{sub, key, quantity, until, reason, by}`,
from an admin command first and a page later, every one in the audit log. Phase 1 is built on these, so the paid
tier is tested before anyone pays.
## Processors
| Merchant | Candidates | Notes |
| | | Notes |
| --- | --- | --- |
| `music` | **Stripe** directly | 2.9% + 30¢ (US cards). We are the seller: sales tax and VAT are ours (Stripe Tax calculates; registering and filing are ours). EU VAT on digital services applies from the first sale to an EU consumer. |
| | **PayPal** (business account, micropayments pricing) | 4.99% + 9¢ once opted in (it applies to the whole account; standard is 3.49% + 49¢), so the cheapest for small charges, and familiar to buyers. We are the seller, as with Stripe. Same rules against infringing goods; known for sudden limits, funds held up to 180 days, and disputes that favour buyers of digital goods. Goods and services payments only, never friends and family. |
| | A **merchant of record** (Paddle, Polar, Stripe Managed Payments, which absorbed Lemon Squeezy) | About 5% + 50¢. They're the seller and handle tax everywhere. They review what they sell before onboarding, and a YouTube-based music service may not pass. |
| `t5de` | **Adult-friendly processors** (CCBill, Segpay, Verotel, Epoch) | Around 10-15% plus reserves, quoted per merchant. Their own content and age-verification rules (the hub's age checks help); read them before building anything adult that's paid. |
| | Crypto (self-hosted BTCPay Server) | No processor fees; an extra option, not the only one. |
| **Patreon** | Used | Above. No upfront review of what's offered; its guidelines still forbid infringing content, so the pages sell hosting (docs/music.md, Paid tier). |
| **Polar** (merchant of record) | To ask, not used | 5% + 50¢ (+1.5% for non-US cards) on new accounts. Its acceptable use policy (2026-10-01) forbids "third-party content downloaders, including … YouTube" (#30) and "services to circumvent the rules, paywalls or terms of other services" (#18). To ask its support, with an honest description; built only on a written yes. |
| Paddle, Stripe Managed Payments | Not used | Merchants of record with the same rules against downloaders and infringement. |
| **PayPal** | Used | Above. We're the seller: VAT through the One Stop Shop. Same rules against infringing goods; known for sudden limits and holds, and for siding with buyers in digital goods disputes. |
| Stripe directly | Not used | We'd be the seller, as with PayPal; a candidate for the checkout elements later. |
| Adult-friendly processors (CCBill, Segpay, Verotel, Epoch) | For the hub, later | Only if the hub ever sells adult content; a separate merchant account, never through Music's. Whether it's this service or another is decided then. |
## Pricing near cost
A provider is an adapter behind one interface, so they run side by side and more can join:
Card fees are mostly the fixed part, so small charges lose a lot:
```ts
interface Provider {
// Where to send a signed-in person to start paying, and to manage what they pay for.
join(sub, offer): Promise<{ url: string }>;
manage(sub): Promise<{ url: string }>;
// Verifies the signature; null when the request isn't the provider's.
webhook(request): Promise<{ source: string } | null>;
// A source's current state, fetched from the provider.
source(id): Promise<SourceState>;
// Every source, for the nightly sync.
sources(): AsyncIterable<SourceState>;
}
```
| Charge | PayPal micropayments (4.99% + 9¢) | Stripe (2.9% + 30¢) | Merchant of record (5% + 50¢) |
| --- | --- | --- | --- |
| $1 a month | 14¢ (14%) | 33¢ (33%) | 55¢ (55%) |
| $10 a year | 59¢ (6%) | 59¢ (6%) | $1.00 (10%) |
| $5 of credits | 34¢ (7%) | 45¢ (9%) | 75¢ (15%) |
## Lapses
So: a yearly price (about $10 a room), or credits bought in $5 steps that pay $1 a month per room. A real $1 a month
only works on PayPal's micropayments pricing.
- A failed renewal keeps the entitlement for 7 days past the charge date (Patreon and PayPal retry meanwhile), then
the extra rooms drop to the free tier. Nothing is deleted; paying again brings them back.
- A refund or chargeback ends that source's entitlement at once. Repeated chargebacks: no new PayPal checkouts for
that account.
- Every grant, change and revocation is in the audit log, with the event or person that caused it.
### Credits
## Selling as an individual
Credits change the fees, not who will process them: processors approve what credits are spent on, so a processor
that won't sell Music's paid tier won't sell credits for it either. If we sell them:
- **Per merchant**: Music's credits are spent only on Music. Credits usable in the hub too would put T5DE's sales
through Music's processor (or the reverse), which undoes the separation above.
- **Never transferable or cashable**: credits that move between people or turn back into money start to look like
money transmission.
- **No expiry, and refunds of unspent credits on request**: some US states treat expiring prepaid balances like gift
cards, and EU buyers have withdrawal rights. A ledger (bought, spent, refunded) per account, not a balance column.
### Selling as an individual
- No company is needed to start: Stripe and the merchants of record accept individuals (sole proprietors), with a
tax ID (SSN in the US) and a bank account. Income goes on a personal return (Schedule C in the US), with
- No company is needed: Patreon (and the merchants of record) accept individuals with a tax ID (SSN in the US) and a
bank account. Patreon reports the income (a 1099-K in the US); it goes on a personal return (Schedule C), with
self-employment tax on the profit.
- **With Stripe directly** we are the seller: the receipts show a business name (a trade name, which some states
require registering as a DBA), and EU sales legally need the seller's name and address shown.
- **With a merchant of record** the merchant of record is the seller: buyers see its name, and it handles tax
everywhere.
- A single-member LLC later: state filing fees vary widely (some states also charge a yearly minimum tax), plus a
free EIN and a registered agent to keep a home address off public records. It shields personal assets from the
business's debts and contracts, but not from claims about what its owner did personally, such as infringement.
- Patreon is the seller, so tax on its sales is Patreon's; PayPal's sales are ours (Tax, above), with "T5DE Music"
as the business name on receipts (some states want a trade name registered as a DBA). Income tax on both is ours.
- A single-member LLC later: state filing fees vary widely, plus a free EIN and a registered agent to keep a home
address off public records. It shields personal assets from the business's debts and contracts, but not from
claims about what its owner did personally, such as infringement.
- An hour with an accountant before the first sale; this section isn't tax or legal advice.
## Lapses, refunds and chargebacks
- A failed renewal gets a grace period (7 days), then the room drops to the free tier. Nothing is deleted.
- A refund or chargeback ends the entitlement at once. Repeated chargebacks: no new checkouts for that account.
- Every grant, refund and revocation is in the audit log.
## Phases
1. **Entitlements without money**: tables, moderators' grants in the console, the back-channel to Music, and
Music's paid features behind `music.room`. Lets the paid tier be tested and given away before anyone pays.
2. **Music's processor**: the adapter, checkout, webhooks, a Billing page under Account on the hub, links from Music.
3. **T5DE's processor**, when the hub has something to sell.
4. **Credits and codes**; a merchant of record if tax work grows.
1. **Entitlements without money**: the service with sign-in, grants, entitlements and the back-channel; Music's paid
features behind `music.rooms`. Lets the paid tier be tested and given away before anyone pays.
2. **Patreon**: linking, the webhook, the nightly sync; the page published.
3. **PayPal**: checkout (redirect), the webhook, the nightly sync, VAT and its report; outside the EU and the UK
first, the EU once the One Stop Shop registration takes effect.
4. **Checkout elements**: our own checkout, embedded; Patreon retired once it's no longer needed.
5. **Polar**, if it says yes; **the hub's offerings**, if it ever sells any (Processors, above).
## Before taking money
Terms of service with a refund policy, a privacy policy, and the accountant's hour (Selling as an individual, above).
- Terms of service: what's paid for (hosting, never a source), that sources such as YouTube can stop working or be
switched off without refunds, and refunds (Patreon's; ours for PayPal).
- A privacy policy covering what's kept (Patreon: user ID, membership status and tier; PayPal: subscription, payer
ID, country and its evidence; no payment details).
- The accountant's hour (Selling as an individual, above), before registering for the One Stop Shop.
## Open decisions
- Music: PayPal (cheapest for $1 charges, what the popular community bot uses), a merchant of record (it's the
seller and handles tax; a refusal at onboarding costs nothing), Stripe directly, or IMVU credits (docs/music.md,
Paid tier). Several can run side by side behind the adapter interface.
- Yearly price or credits for the paid tier.
- Whether the Billing page lives only on the hub, or Music also shows its own subscriptions.
- Polar's answer.
- Whether Dynamic Micropayments covers subscription renewals (asked of PayPal).
- Whether grants get a page, or stay an admin command.
- The tiers after launch: a 10-room tier for clubs, prices once there's usage to look at.
+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(),