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

This commit is contained in:
dhkatz authored and David Katz committed 2026-11-19 01:51:05 -08:00
1 parent f05874f800
commit 9112e3cc30
20 files changed
+6531 -29

No files matched your search

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