// Discord sign-in (docs/music.md, Accounts): it makes a basic account (Discord only, none of the hub's features), from a // 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 { createApp } from "../src/app"; import { createAuth } from "../src/auth"; import { ImvuClient } from "../src/imvu"; import { Settings } from "../src/settings"; const webURL = "http://web.test"; let db: Database; let close: () => Promise; let base: string; let stop: () => void; let settings: Settings; /** The Discord account the next sign-in comes back as. */ let discordProfile: Record = {}; const realFetch = globalThis.fetch; beforeAll(async () => { // Discord's token and profile endpoints, as Better Auth's Discord provider calls them. globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; if (url.startsWith("https://discord.com/api/oauth2/token")) return Response.json({ access_token: "discord-at", token_type: "Bearer", expires_in: 3600, refresh_token: "discord-rt", scope: "identify email" }); if (/^https:\/\/discord\.com\/api\/users\/(@|%40)me/.test(url)) return Response.json(discordProfile); return realFetch(input, init); }) as typeof fetch; ({ db, close } = await openDatabase("memory")); settings = new Settings(db, { registration: "open" }); const auth = createAuth(db, { apiURL: "http://api.test", webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false, settings, discord: { clientId: "discord-client", clientSecret: "discord-secret" }, }); const imvu = new ImvuClient("http://imvu.test", (async () => Response.json({ denormalized: {} })) as unknown as typeof fetch); const hub = createApp({ db, auth, imvu, webURL, 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 () => { globalThis.fetch = realFetch; stop(); await close(); }); type Cookie = { v: string }; /** Keeps the cookies a response sets (Better Auth's state, then the session). */ function keep(cookie: Cookie, res: Response) { const jar = new Map(cookie.v ? cookie.v.split("; ").map((c) => c.split("=", 2) as [string, string]) : []); for (const c of res.headers.getSetCookie()) { const [pair] = c.split(";"); const [k, v] = pair!.split("=", 2) as [string, string]; if (/max-age=0/i.test(c) || v === "") jar.delete(k); else jar.set(k, v); } cookie.v = [...jar].map(([k, v]) => `${k}=${v}`).join("; "); } async function call(cookie: Cookie, method: string, path: string, body?: unknown) { const res = await realFetch(base + path, { method, redirect: "manual", headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...(cookie.v ? { Cookie: cookie.v } : {}) }, body: body !== undefined ? JSON.stringify(body) : undefined, }); keep(cookie, res); const text = await res.text(); let json: any; try { json = text ? JSON.parse(text) : undefined; } catch { json = undefined; } return { status: res.status, json, location: res.headers.get("location") ?? "" }; } /** Goes through Discord's sign-in (or linking, from a signed-in session) and returns where the browser ends up. */ async function viaDiscord(cookie: Cookie, profile: Record, link = false) { discordProfile = { discriminator: "0", avatar: null, global_name: profile.username, ...profile }; const start = link ? await call(cookie, "POST", "/api/auth/link-social", { provider: "discord", callbackURL: `${webURL}/account`, errorCallbackURL: `${webURL}/account` }) : await call(cookie, "POST", "/api/auth/sign-in/social", { provider: "discord", callbackURL: `${webURL}/`, errorCallbackURL: `${webURL}/signin` }); expect(start.status).toBe(200); const state = new URL(start.json.url).searchParams.get("state"); expect(state).toBeTruthy(); const back = await call(cookie, "GET", `/api/auth/callback/discord?code=discord-code&state=${encodeURIComponent(state!)}`); expect(back.status).toBe(302); return new URL(back.location, webURL); } async function signUp(name: string, email = `${name}@example.test`) { const cookie = { v: "" }; expect((await call(cookie, "POST", "/api/auth/sign-up/email", { email, password: "a long password", name, username: name })).status).toBe(200); return cookie; } test("a basic account from Discord can't use the hub until it finishes setting up; the first member still runs the hub", async () => { expect((await call({ v: "" }, "GET", "/api/v1/hub")).json).toEqual({ registration: "open", discord: true }); const disco: Cookie = { v: "" }; const landed = await viaDiscord(disco, { id: "1001", username: "disco", email: "disco@example.test", verified: true }); expect(landed.pathname).toBe("/"); expect(landed.searchParams.get("error")).toBeNull(); const me = (await call(disco, "GET", "/api/v1/me")).json.person; expect(me).toMatchObject({ kind: "basic", role: "user", username: "disco", email: "disco@example.test" }); expect(await call(disco, "GET", "/api/v1/account")).toMatchObject({ status: 403, json: { error: "finish_setup" } }); expect((await call(disco, "POST", "/api/v1/account/links", { username: "someone" })).json.error).toBe("finish_setup"); // Basic accounts don't count: the first member is still the admin. const ada = await signUp("ada"); expect((await call(ada, "GET", "/api/v1/me")).json.person).toMatchObject({ kind: "member", role: "admin" }); // Signing in with the same Discord account again is the same person. const again: Cookie = { v: "" }; await viaDiscord(again, { id: "1001", username: "disco", email: "disco@example.test", verified: true }); expect((await call(again, "GET", "/api/v1/me")).json.person.id).toBe(me.id); }); test("Discord sign-in needs a verified email, and never links to an account by its email", async () => { const unverified = await viaDiscord({ v: "" }, { id: "1002", username: "nover", email: "nover@example.test", verified: false }); expect(unverified.pathname).toBe("/signin"); expect(unverified.searchParams.get("error")).toBe("email_not_verified"); const noEmail = await viaDiscord({ v: "" }, { id: "1003", username: "phone", email: null, verified: false }); expect(noEmail.searchParams.get("error")).toBe("email_not_found"); // bea is a member; someone puts her address on their Discord account. await signUp("bea"); const thief: Cookie = { v: "" }; const taken = await viaDiscord(thief, { id: "1004", username: "thief", email: "bea@example.test", verified: true }); expect(taken.pathname).toBe("/signin"); expect(taken.searchParams.get("error")).toBe("account_not_linked"); expect((await call(thief, "GET", "/api/v1/me")).status).toBe(401); }); test("finishing setup: a username and password make a member, still signing in with Discord too", async () => { const cass: Cookie = { v: "" }; await viaDiscord(cass, { id: "1005", username: "cass", email: "cass@example.test", verified: true }); const id = (await call(cass, "GET", "/api/v1/me")).json.person.id; const finish = (username: string, password = "a long password") => call(cass, "POST", "/api/v1/account/finish", { username, password }); expect((await finish("no spaces")).json.error).toBe("invalid_username"); expect((await finish("imvu_123")).json.error).toBe("invalid_username"); expect((await finish("Ada")).json.error).toBe("username_taken"); expect((await finish("cass_", "short")).json.error).toBe("invalid_password"); const done = await finish("Cass_"); expect(done.status).toBe(200); expect(done.json.person).toMatchObject({ id, kind: "member", username: "Cass_", approved: true }); expect((await call(cass, "GET", "/api/v1/account")).json).toMatchObject({ discord: { available: true, linked: true } }); expect((await finish("again")).json.error).toBe("already_member"); // The password works, and so does Discord. const byPassword: Cookie = { v: "" }; expect((await call(byPassword, "POST", "/api/auth/sign-in/username", { username: "cass_", password: "a long password" })).status).toBe(200); expect((await call(byPassword, "GET", "/api/v1/me")).json.person.id).toBe(id); const byDiscord: Cookie = { v: "" }; await viaDiscord(byDiscord, { id: "1005", username: "cass", email: "cass@example.test", verified: true }); expect((await call(byDiscord, "GET", "/api/v1/me")).json.person).toMatchObject({ id, kind: "member" }); }); test("with registration closed, a finished account waits for approval", async () => { await settings.setRegistration("closed"); try { const dee: Cookie = { v: "" }; await viaDiscord(dee, { id: "1006", username: "dee", email: "dee@example.test", verified: true }); expect((await call(dee, "POST", "/api/v1/account/finish", { username: "dee", password: "a long password" })).json.person).toMatchObject({ kind: "member", approved: false, }); expect((await call(dee, "GET", "/api/v1/account")).json.error).toBe("awaiting_approval"); } finally { await settings.setRegistration("open"); } }); test("a member links Discord from their own session; a Discord account already in use can't be linked again", async () => { const eve = await signUp("eve"); expect((await call(eve, "GET", "/api/v1/account")).json.discord).toEqual({ available: true, linked: false }); // Another address than eve's own: allowed, it's her session that links it. const linked = await viaDiscord(eve, { id: "1007", username: "eve_discord", email: "eve.other@example.test", verified: true }, true); expect(linked.pathname).toBe("/account"); expect(linked.searchParams.get("error")).toBeNull(); expect((await call(eve, "GET", "/api/v1/account")).json.discord).toEqual({ available: true, linked: true }); // And unlinks it again (she keeps her password). expect((await call(eve, "DELETE", "/api/v1/account/discord")).status).toBe(204); expect((await call(eve, "GET", "/api/v1/account")).json.discord.linked).toBe(false); expect((await call(eve, "DELETE", "/api/v1/account/discord")).status).toBe(404); // disco's Discord account (a basic account) can't be added to fay's: merging comes later. const fay = await signUp("fay"); const refused = await viaDiscord(fay, { id: "1001", username: "disco", email: "disco@example.test", verified: true }, true); 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); });