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]>
188 lines
9.1 KiB
TypeScript
188 lines
9.1 KiB
TypeScript
// The hub as an OpenID Connect provider (docs/music.md): T5DE Music signs people in with the authorization code flow
|
|
// (PKCE), gets their linked IMVU accounts from the `imvu` scope, and links IMVU accounts through the hub's API with an
|
|
// access token for it (`imvu:link`).
|
|
import { afterAll, beforeAll, expect, test } from "bun:test";
|
|
import { eq, openDatabase, schema, type Database } from "@t5de/db";
|
|
import { createApp } from "../src/app";
|
|
import { createAuth, hubResource, seedClients } from "../src/auth";
|
|
import { ImvuClient } from "../src/imvu";
|
|
import { Settings } from "../src/settings";
|
|
|
|
const webURL = "http://web.test";
|
|
const apiURL = "http://api.test";
|
|
const music = {
|
|
clientId: "t5de-music",
|
|
name: "T5DE Music",
|
|
secret: "music-secret-music-secret-music-secret-1234",
|
|
redirectUris: ["https://music.test/api/auth/callback"],
|
|
};
|
|
let db: Database;
|
|
let close: () => Promise<void>;
|
|
let base: string;
|
|
let stop: () => void;
|
|
|
|
beforeAll(async () => {
|
|
({ db, close } = await openDatabase("memory"));
|
|
const settings = new Settings(db, { registration: "open" });
|
|
const auth = createAuth(db, { apiURL, webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false, settings, clients: [music] });
|
|
await seedClients(db, apiURL, [music]);
|
|
const imvu = new ImvuClient("http://imvu.test", (async () => Response.json({ denormalized: {} })) as unknown as typeof fetch);
|
|
const hub = createApp({ db, auth, imvu, webURL, apiURL, settings });
|
|
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
|
|
const server = hub.app.server as unknown as { port: number; stop: () => void };
|
|
stop = () => server.stop();
|
|
base = `http://127.0.0.1:${server.port}`;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
stop();
|
|
await close();
|
|
});
|
|
|
|
type Cookie = { v: string };
|
|
|
|
async function call(cookie: Cookie, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
|
|
const form = body instanceof URLSearchParams;
|
|
const res = await fetch(base + path, {
|
|
method,
|
|
redirect: "manual",
|
|
headers: {
|
|
Origin: webURL,
|
|
...(body !== undefined ? { "Content-Type": form ? "application/x-www-form-urlencoded" : "application/json" } : {}),
|
|
...(cookie.v ? { Cookie: cookie.v } : {}),
|
|
...headers,
|
|
},
|
|
body: body === undefined ? undefined : form ? body.toString() : JSON.stringify(body),
|
|
});
|
|
const set = res.headers.getSetCookie();
|
|
if (set.length) cookie.v = set.map((c) => c.split(";")[0]).join("; ");
|
|
const text = await res.text();
|
|
let json: any;
|
|
try {
|
|
json = text ? JSON.parse(text) : undefined;
|
|
} catch {}
|
|
return { status: res.status, json, location: res.headers.get("location") ?? "" };
|
|
}
|
|
|
|
async function signUp(name: string) {
|
|
const cookie = { v: "" };
|
|
expect((await call(cookie, "POST", "/api/auth/sign-up/email", { email: `${name}@example.test`, password: "a long password", name, username: name })).status).toBe(200);
|
|
return cookie;
|
|
}
|
|
|
|
const b64url = (b: ArrayBuffer | Uint8Array) => Buffer.from(b as ArrayBuffer).toString("base64url");
|
|
|
|
/** Music's side: the authorize request, with PKCE and the hub's API as the token's resource. */
|
|
async function authorizeURL(scope: string, extra: Record<string, string> = {}) {
|
|
const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
const challenge = b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
|
|
const q = new URLSearchParams({
|
|
response_type: "code",
|
|
client_id: music.clientId,
|
|
redirect_uri: music.redirectUris[0]!,
|
|
scope,
|
|
state: "st-" + verifier.slice(0, 6),
|
|
code_challenge: challenge,
|
|
code_challenge_method: "S256",
|
|
resource: hubResource(apiURL),
|
|
...extra,
|
|
});
|
|
return { path: `/api/auth/oauth2/authorize?${q}`, verifier, state: q.get("state")! };
|
|
}
|
|
|
|
/** Music signs `cookie`'s person in: authorize (signed in already), then the code for tokens. */
|
|
async function musicSignIn(cookie: Cookie, scope = "openid profile email offline_access imvu imvu:link") {
|
|
const a = await authorizeURL(scope);
|
|
const r = await call(cookie, "GET", a.path);
|
|
expect(r.status).toBe(302);
|
|
const back = new URL(r.location);
|
|
expect(back.origin + back.pathname).toBe(music.redirectUris[0]!);
|
|
expect(back.searchParams.get("state")).toBe(a.state);
|
|
const code = back.searchParams.get("code")!;
|
|
const token = await call(
|
|
{ v: "" },
|
|
"POST",
|
|
"/api/auth/oauth2/token",
|
|
new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: music.redirectUris[0]!, code_verifier: a.verifier, resource: hubResource(apiURL) }),
|
|
{ Authorization: "Basic " + Buffer.from(`${music.clientId}:${music.secret}`).toString("base64") },
|
|
);
|
|
expect(token.status).toBe(200);
|
|
return token.json as { access_token: string; id_token: string; refresh_token?: string; scope: string };
|
|
}
|
|
|
|
const bearer = (t: string) => ({ Authorization: `Bearer ${t}` });
|
|
|
|
test("discovery: the issuer is the API's /api/auth", async () => {
|
|
const d = (await call({ v: "" }, "GET", "/api/auth/.well-known/openid-configuration")).json;
|
|
expect(d.issuer).toBe(`${apiURL}/api/auth`);
|
|
expect(d.scopes_supported).toEqual(expect.arrayContaining(["openid", "imvu", "imvu:link"]));
|
|
expect(d.jwks_uri).toBe(`${apiURL}/api/auth/jwks`);
|
|
});
|
|
|
|
test("the sign-in page can name the site asking", async () => {
|
|
expect((await call({ v: "" }, "GET", `/api/v1/oauth/clients/${music.clientId}`)).json).toEqual({ client: { name: "T5DE Music", firstParty: true } });
|
|
expect((await call({ v: "" }, "GET", "/api/v1/oauth/clients/nobody")).status).toBe(404);
|
|
});
|
|
|
|
test("signed out, authorize sends people to the website's sign-in page with the request", async () => {
|
|
const a = await authorizeURL("openid profile imvu", { t5de_provider: "discord" });
|
|
const r = await call({ v: "" }, "GET", a.path);
|
|
expect(r.status).toBe(302);
|
|
const to = new URL(r.location);
|
|
expect(to.origin + to.pathname).toBe(`${webURL}/signin`);
|
|
expect(to.searchParams.get("client_id")).toBe(music.clientId);
|
|
expect(to.searchParams.get("sig")).toBeTruthy();
|
|
// The hint for the sign-in page comes along.
|
|
expect(to.searchParams.get("t5de_provider")).toBe("discord");
|
|
});
|
|
|
|
test("Music signs a member in without a consent screen, and gets their IMVU accounts", async () => {
|
|
const ada = await signUp("ada");
|
|
const me = (await call(ada, "GET", "/api/v1/me")).json.person;
|
|
await db.insert(schema.imvuLink).values({ imvuId: 4242, userId: me.id, pairwiseId: "pw-4242", username: "AdaInIMVU" });
|
|
|
|
const t = await musicSignIn(ada);
|
|
expect(t.scope.split(" ")).toEqual(expect.arrayContaining(["openid", "imvu", "imvu:link"]));
|
|
expect(t.refresh_token).toBeTruthy();
|
|
// The ID token carries the IMVU accounts.
|
|
const idClaims = JSON.parse(Buffer.from(t.id_token.split(".")[1]!, "base64url").toString());
|
|
expect(idClaims).toMatchObject({ iss: `${apiURL}/api/auth`, aud: music.clientId, sub: me.id, imvu: [{ id: 4242, username: "AdaInIMVU" }] });
|
|
|
|
const info = (await call({ v: "" }, "GET", "/api/auth/oauth2/userinfo", undefined, bearer(t.access_token))).json;
|
|
expect(info).toMatchObject({ sub: me.id, preferred_username: "ada", email: "[email protected]", imvu: [{ id: 4242, username: "AdaInIMVU" }] });
|
|
|
|
// The access token works on the routes for T5DE's sites, and only those.
|
|
const imvu = await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer(t.access_token));
|
|
expect(imvu.status).toBe(200);
|
|
expect(imvu.json.links).toEqual([expect.objectContaining({ imvuId: 4242, username: "AdaInIMVU" })]);
|
|
expect((await call({ v: "" }, "GET", "/api/v1/account", undefined, bearer(t.access_token))).json.error).toBe("token_not_allowed");
|
|
expect((await call({ v: "" }, "GET", "/api/v1/me", undefined, bearer(t.access_token))).json.error).toBe("token_not_allowed");
|
|
// A token that isn't the hub's.
|
|
expect((await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer("aaa.bbb.ccc"))).status).toBe(401);
|
|
});
|
|
|
|
test("without imvu and imvu:link, Music gets no IMVU accounts and can't link", async () => {
|
|
const bo = await signUp("bo_");
|
|
const t = await musicSignIn(bo, "openid profile");
|
|
const info = (await call({ v: "" }, "GET", "/api/auth/oauth2/userinfo", undefined, bearer(t.access_token))).json;
|
|
expect(info.imvu).toBeUndefined();
|
|
expect((await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer(t.access_token))).json.error).toBe("insufficient_scope");
|
|
});
|
|
|
|
test("a basic account links IMVU accounts through Music; the website still says finish setting up", async () => {
|
|
// A basic account, as Discord sign-in makes them (discord.test.ts covers that part).
|
|
const cy = await signUp("cyd");
|
|
const id = (await call(cy, "GET", "/api/v1/me")).json.person.id;
|
|
await db.update(schema.user).set({ kind: "basic", username: null, displayUsername: null }).where(eq(schema.user.id, id));
|
|
const t = await musicSignIn(cy);
|
|
const imvu = await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer(t.access_token));
|
|
expect(imvu).toMatchObject({ status: 200, json: { links: [], canLink: true } });
|
|
expect((await call(cy, "GET", "/api/v1/account/imvu")).json.error).toBe("finish_setup");
|
|
});
|
|
|
|
test("a website session still links as before", async () => {
|
|
const dee = await signUp("dee");
|
|
expect((await call(dee, "GET", "/api/v1/account/imvu")).status).toBe(200);
|
|
});
|
|
|