Cotton code
198 lines · 11.4 KB · TypeScriptRaw
/** * Spotify connect end to end against `wrangler dev` and a FAKE Spotify (no * real login exists for a walk): a little HTTP server on this Mac answers * as accounts.spotify.com (authorize, token) and api.spotify.com (saved * shows and episodes, in the Web API's shapes), from a synthetic library. * The Worker is pointed at it by the development vars SPOTIFY_ACCOUNTS_URL * and SPOTIFY_API_URL. * *   cd apps/business && pnpm -s exec tsx scripts/__tests__/e2e-spotify.ts [--log <dir>] * * The walk: the owner asks /v1/spotify/connect; the "browser" opens the * consent page, which the fake answers with its redirect to the callback; * the callback on the open host trades the code (the fake checks the PKCE * verifier against the challenge, the client's Basic header and the * redirect); the object's pull reads the followed shows and the saved * episodes, and asks for nothing of the person's music (Cotton Music is * their own files). `--log <dir>` keeps the walk's lines and the status * answers there. wrangler dev and the fake are stopped however it ends. */import type { ChildProcess } from "node:child_process";import { createHash, randomBytes } from "node:crypto";import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { createServer, type Server } from "node:http";import { tmpdir } from "node:os";import { join } from "node:path";import { check, startDevWorker, stop } from "./dev-worker.ts";import { personalSlug } from "../dev-server";const tmp = mkdtempSync(join(tmpdir(), "e2e-spotify-"));const logAt = process.argv.includes("--log") ? process.argv[process.argv.indexOf("--log") + 1]! : null;const lines: string[] = [];const say = (line: string): void => {  lines.push(line);  console.log(line);};let wrangler: ChildProcess | null = null;let fake: Server | null = null;const cleanup = (): void => {  stop(wrangler);  wrangler = null;  fake?.close();  rmSync(tmp, { recursive: true, force: true });};process.on("exit", cleanup);process.on("SIGINT", () => process.exit(130));// ── the fake Spotify ─────────────────────────────────────────────────────const CLIENT = { id: "walk-fake-client", secret: "walk-fake-secret" };const SCOPES = "user-library-read user-read-playback-position";const USER = { id: "walk.listener", display_name: "Walk Listener" };let origin = "";const library = {  shows: [{ id: "wshw1", uri: "spotify:show:wshw1", name: "Walk Synthetic Exclusive Show" }],  episodes: [{ id: "wep1", uri: "spotify:episode:wep1", name: "Walk Episode 1", resume_point: { fully_played: false, resume_position_ms: 61_000 }, show: { id: "wshw1", name: "Walk Synthetic Exclusive Show" } }],};const asked: string[] = [];const codes = new Map<string, { challenge: string; redirect: string }>();let access = "";let refresh = "";function page(url: URL, all: unknown[], size = 2): Record<string, unknown> {  const offset = Number(url.searchParams.get("offset") ?? 0);  const items = all.slice(offset, offset + size);  const more = offset + size < all.length;  return { items, total: all.length, offset, limit: size, next: more ? `${origin}${url.pathname}?offset=${offset + size}&limit=${size}` : null };}function answer(url: URL, method: string, headers: Record<string, string | string[] | undefined>, form: URLSearchParams): { status: number; body: unknown; type?: string; location?: string } {  if (url.pathname === "/authorize") {    check(url.searchParams.get("client_id") === CLIENT.id && url.searchParams.get("code_challenge_method") === "S256" && url.searchParams.get("scope") === SCOPES, "the consent page names the client, PKCE S256 and the read scopes");    const code = `code-${randomBytes(8).toString("hex")}`;    codes.set(code, { challenge: url.searchParams.get("code_challenge")!, redirect: url.searchParams.get("redirect_uri")! });    const back = new URL(url.searchParams.get("redirect_uri")!);    back.search = new URLSearchParams({ code, state: url.searchParams.get("state")! }).toString();    return { status: 302, body: "", location: back.toString() };  }  if (url.pathname === "/api/token" && method === "POST") {    if (headers.authorization !== `Basic ${Buffer.from(`${CLIENT.id}:${CLIENT.secret}`).toString("base64")}`) return { status: 401, body: { error: "invalid_client" } };    if (form.get("grant_type") === "authorization_code") {      const held = codes.get(form.get("code") ?? "");      codes.delete(form.get("code") ?? "");      const verified = held && createHash("sha256").update(form.get("code_verifier") ?? "").digest("base64url") === held.challenge && held.redirect === form.get("redirect_uri");      if (!verified) return { status: 400, body: { error: "invalid_grant" } };      access = `walk-access-${randomBytes(6).toString("hex")}`;      refresh = `walk-refresh-${randomBytes(6).toString("hex")}`;      return { status: 200, body: { access_token: access, refresh_token: refresh, scope: SCOPES, expires_in: 3600, token_type: "Bearer" } };    }    if (form.get("grant_type") === "refresh_token" && form.get("refresh_token") === refresh) {      access = `walk-access-${randomBytes(6).toString("hex")}`;      return { status: 200, body: { access_token: access, scope: SCOPES, expires_in: 3600, token_type: "Bearer" } };    }    return { status: 400, body: { error: "invalid_grant" } };  }  if (!url.pathname.startsWith("/v1/")) return { status: 404, body: { error: "not found" } };  asked.push(url.pathname);  if (headers.authorization !== `Bearer ${access}`) return { status: 401, body: { error: { status: 401, message: "Invalid access token" } } };  const p = url.pathname.slice(3);  if (p === "/me") return { status: 200, body: USER };  if (p === "/me/shows") return { status: 200, body: page(url, library.shows.map((show) => ({ added_at: "2026-01-01T00:00:00Z", show }))) };  if (p === "/me/episodes") return { status: 200, body: page(url, library.episodes.map((episode) => ({ added_at: "2026-01-01T00:00:00Z", episode }))) };  return { status: 404, body: { error: { status: 404, message: "Service not found" } } };}async function startFake(): Promise<string> {  fake = createServer((req, res) => {    const chunks: Buffer[] = [];    req.on("data", (c: Buffer) => chunks.push(c));    req.on("end", () => {      const url = new URL(req.url ?? "/", origin);      const a = answer(url, req.method ?? "GET", req.headers, new URLSearchParams(Buffer.concat(chunks).toString("utf8")));      if (a.location) res.writeHead(a.status, { location: a.location });      else res.writeHead(a.status, { "content-type": a.type ?? "application/json" });      res.end(Buffer.isBuffer(a.body) ? a.body : a.location ? "" : JSON.stringify(a.body));    });  });  await new Promise<void>((done) => fake!.listen(0, "127.0.0.1", done));  const { port } = fake.address() as { port: number };  origin = `http://127.0.0.1:${port}`;  return origin;}// ── the walk ─────────────────────────────────────────────────────────────type Status = { available: boolean; account: null | { displayName: string; phase: string; step: string | null; lastError: string | null; episodesWaiting: number; shows: { followed: number; resolved: unknown[]; unresolved: string[] } } };async function main(): Promise<void> {  const fakeAt = await startFake();  say(`fake Spotify at ${fakeAt}`);  const database = "33333333-3333-4333-8333-333333333333";  const dev = await startDevWorker(tmp, database, (child) => (wrangler = child), {    // The top level of wrangler.jsonc is the live Worker's: the fake is the development Worker's alone.    ENV_LABEL: "dev",    SPOTIFY_CLIENT_ID: CLIENT.id,    SPOTIFY_CLIENT_SECRET: CLIENT.secret,    SPOTIFY_ACCOUNTS_URL: fakeAt,    SPOTIFY_API_URL: `${fakeAt}/v1`,    SPOTIFY_REDIRECT_SCHEME: "http",  });  const minted = await dev.api<{ token: string }>("POST", "/v1/act", { act: "mint_token", args: { name: "e2e spotify", scopes: ["owner"], allow: "all" } }, dev.credential);  const owner = minted.token;  const before = await dev.api<Status>("GET", "/v1/spotify/status", undefined, owner);  check(before.available && before.account === null, "the Worker can connect Spotify and holds no account");  const connect = await dev.api<{ authorizeUrl: string; state: string }>("GET", "/v1/spotify/connect", undefined, owner);  say(`consent page: ${connect.authorizeUrl.replace(/state=[^&]+/, "state=…").replace(/code_challenge=[^&]+/, "code_challenge=…")}`);  check(connect.authorizeUrl.startsWith(`${fakeAt}/authorize?`), "the consent page is the fake's authorize");  // The browser: the consent page answers its redirect to the callback.  const consent = await fetch(connect.authorizeUrl, { redirect: "manual" });  const back = new URL(consent.headers.get("location")!);  check(back.pathname === "/v1/spotify/callback" && back.searchParams.get("state") === connect.state, "Spotify sends the browser back to the open host's callback with the state");  // wrangler dev's open host is 127.0.0.1 on its own port: the browser lands there.  const landed = await fetch(`${dev.base}${back.pathname}${back.search}`);  const done = await landed.text();  check(landed.status === 200 && done.includes("Spotify is connected") && done.includes(USER.display_name), "the callback trades the code with its verifier and says Spotify is connected");  check(!done.includes(refresh), "the page never carries the refresh token");  let status: Status | null = null;  for (let i = 0; i < 120; i++) {    status = await dev.api<Status>("GET", "/v1/spotify/status", undefined, owner);    if (status.account?.phase === "synced" && status.account.step === null) break;    await new Promise((r) => setTimeout(r, 1000));  }  say(`status after the first cycle: ${JSON.stringify(status)}`);  check(status?.account?.phase === "synced", "the pull ran its whole cycle on the object's alarm");  check(status!.account!.episodesWaiting === 1, "the saved episode's resume point waits for the Podcasts tool");  say(`shows: ${JSON.stringify(status!.account!.shows)}`);  check(status!.account!.shows.followed === 1, "the followed show is read");  const music = [...new Set(asked)].filter((p) => p !== "/v1/me" && p !== "/v1/me/shows" && p !== "/v1/me/episodes");  check(music.length === 0, `nothing of the person's music is asked for (${music.join(", ") || "none"})`);  check((await fetch(`${dev.base}/b/${personalSlug()}/v1/spotify/history`, { method: "POST", headers: { authorization: `Bearer ${owner}`, "content-type": "application/json" }, body: "{}" })).status === 404, "the history import is gone");  const off = await dev.api<{ ok: boolean; revokeAt: string }>("POST", "/v1/spotify/disconnect", {}, owner);  check(off.ok, `disconnect forgets the grant (the person takes access away at ${off.revokeAt})`);  const gone = await dev.api<Status>("GET", "/v1/spotify/status", undefined, owner);  check(gone.account === null, "and the status says no account");  say(`Spotify API paths asked: ${[...new Set(asked)].join(", ")}`);  say("e2e spotify: every check held");}main()  .catch((error: unknown) => {    say(`FAILED: ${error instanceof Error ? error.message : String(error)}`);    process.exitCode = 1;  })  .finally(() => {    if (logAt) {      mkdirSync(logAt, { recursive: true });      writeFileSync(join(logAt, "e2e-spotify.log"), `${lines.join("\n")}\n`);    }    cleanup();    process.exit(process.exitCode ?? 0);  });