Cotton code
183 lines · 9.7 KB · TypeScriptRaw
/** * A fake Spotify for the Spotify tests: the accounts host's token endpoint, * the Web API's saved shows and episodes, the iTunes directory and the * shows' feeds, answered from a little library in the shapes the Web API * reference gives them. Every call is kept. Nothing here is anyone's real * library: the names and ids are made up. No call leaves the test. */import { SELF } from "cloudflare:test";import { expect, vi } from "vitest";import { s256 } from "../src/oauth.ts";import { SCOPES } from "../src/spotify.ts";import { DATABASE_ID } from "./personal.ts";/** A Spotify show and a saved episode, as the Web API answers them. */export interface SShow {  id: string;  uri: string;  name: string;}export interface SEpisode {  id: string;  uri: string;  name: string;  resume_point?: { fully_played?: boolean; resume_position_ms?: number };  show?: SShow;}export interface Call {  url: URL;  method: string;  authorization: string | null;  form: Record<string, string>;}export const reply = (status: number, body: unknown, headers: Record<string, string> = {}): Response =>  new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } });export const CLIENT_ID = "test-spotify-client";export const CLIENT_SECRET = "test-spotify-secret";export const REFRESH = "AQBtest-spotify-refresh-wxyz";export const ROTATED = "AQBtest-spotify-rotated-qrst";export const USER = { id: "synthetic.listener", display_name: "Synthetic Listener" };// ── the library, in the Web API's shapes ────────────────────────────────const image = (key: string, width: number): { url: string; height: number; width: number } => ({ url: `https://i.scdn.co/image/${key}-${width}`, height: width, width });export function show(n: number, name = `Synthetic Show ${n}`): SShow & Record<string, unknown> {  return { id: `shw${n}`, uri: `spotify:show:shw${n}`, name, description: "", media_type: "audio", total_episodes: 10, type: "show", images: [image(`shw${n}`, 640)] };}export function episode(n: number, showN: number, resumeMs: number, fully = false): SEpisode & Record<string, unknown> {  return {    id: `ep${n}`,    uri: `spotify:episode:ep${n}`,    name: `Synthetic Episode ${n}`,    duration_ms: 1_800_000,    release_date: "2026-01-01",    type: "episode",    resume_point: { fully_played: fully, resume_position_ms: resumeMs },    show: show(showN),  };}/** * The person's Spotify as a little store; `pageSize` stands in for Spotify's 50. */export class FakeSpotify {  pageSize = 2;  shows: SShow[] = [];  episodes: SEpisode[] = [];  /** Feeds the iTunes directory knows, by show name. */  feeds = new Map<string, string>();  /** Answers queued for the next API calls, ahead of the library (a 401, a 429). */  readonly next: Response[] = [];  /** Hands out a new refresh token on the next refresh. */  rotate = false;  /** The token endpoint refuses refreshing with invalid_grant. */  revoked = false;  readonly asked: URL[] = [];  access = "BQtest-access-1";  private paged<T>(url: URL, all: T[], base: string): Record<string, unknown> {    const offset = Number(url.searchParams.get("offset") ?? 0);    const limit = Math.min(Number(url.searchParams.get("limit") ?? 20), this.pageSize);    const items = all.slice(offset, offset + limit);    const more = offset + limit < all.length;    return { href: url.toString(), items, limit, offset, total: all.length, previous: null, next: more ? `${base}?offset=${offset + limit}&limit=${limit}` : null };  }  readonly route = async (call: Call): Promise<Response | null> => {    const u = call.url;    if (u.href === "https://accounts.spotify.com/api/token") {      expect(call.authorization).toBe(`Basic ${btoa(`${CLIENT_ID}:${CLIENT_SECRET}`)}`);      if (call.form.grant_type === "refresh_token") {        if (this.revoked) return reply(400, { error: "invalid_grant", error_description: "Refresh token revoked" });        this.access = `BQtest-access-${Date.now()}`;        return reply(200, { access_token: this.access, token_type: "Bearer", expires_in: 3600, scope: SCOPES.join(" "), ...(this.rotate ? { refresh_token: ROTATED } : {}) });      }      return null;    }    if (u.host === "itunes.apple.com") {      const term = u.searchParams.get("term") ?? "";      const feed = this.feeds.get(term);      // The directory answers near names too; only the exact name is the show.      const results = [{ collectionName: `${term} Extra`, feedUrl: "https://feeds.example.test/not-this" }, ...(feed ? [{ collectionName: term, feedUrl: feed, artistName: "Synthetic Publisher" }] : [])];      return reply(200, { resultCount: results.length, results });    }    if (u.host === "feeds.example.test") {      const name = [...this.feeds].find(([, feed]) => feed === u.href)?.[0];      if (!name) return new Response("no such feed", { status: 404 });      const items = [1, 2, 3]        .map((n) => `<item><title>Synthetic Episode ${n}</title><guid>syn-${n}</guid><pubDate>Mon, 0${n} Nov 2026 06:00:00 -0000</pubDate><enclosure url="https://audio.example.test/${n}.mp3" length="1000" type="audio/mpeg"/><itunes:duration>30:00</itunes:duration></item>`)        .join("");      const rss = `<?xml version="1.0"?><rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"><channel><title>${name}</title><itunes:author>Synthetic Publisher</itunes:author><description>A made-up show.</description>${items}</channel></rss>`;      return new Response(rss, { headers: { "content-type": "application/rss+xml" } });    }    if (u.host !== "api.spotify.com") return null;    this.asked.push(u);    const queued = this.next.shift();    if (queued) return queued;    expect(call.authorization).toBe(`Bearer ${this.access}`);    const p = u.pathname.replace(/^\/v1/, "");    const base = `https://api.spotify.com/v1${p}`;    if (p === "/me") return reply(200, { ...USER, type: "user", uri: `spotify:user:${USER.id}`, href: `https://api.spotify.com/v1/users/${USER.id}`, external_urls: {}, images: [] });    if (p === "/me/shows") return reply(200, this.paged(u, this.shows.map((s) => ({ added_at: "2026-01-01T00:00:00Z", show: s })), base));    if (p === "/me/episodes") return reply(200, this.paged(u, this.episodes.map((e) => ({ added_at: "2026-01-01T00:00:00Z", episode: e })), base));    return reply(404, { error: { status: 404, message: "Service not found" } });  };}/** Spotify, answering each call with the first route that answers it; a call no route answers fails the test. */export function spotify(...routes: ((call: Call) => Response | null | Promise<Response | null>)[]): Call[] {  const calls: Call[] = [];  vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {    const request = new Request(input as RequestInfo, init);    const type = request.headers.get("content-type") ?? "";    const call: Call = {      url: new URL(request.url),      method: request.method,      authorization: request.headers.get("authorization"),      form: type.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries([...(await request.formData())].map(([k, v]) => [k, String(v)])) : {},    };    calls.push(call);    for (const route of routes) {      const answer = await route(call);      if (answer) return answer;    }    throw new Error(`Spotify was called where the test expects no call: ${call.method} ${call.url.toString()}`);  });  return calls;}/** The token endpoint trading a code for the whole grant, its verifier checked against the challenge the connect gave. */export function trades(challenge: () => string, scope = SCOPES.join(" ")) {  return async (call: Call): Promise<Response | null> => {    if (call.url.href !== "https://accounts.spotify.com/api/token" || call.form.grant_type !== "authorization_code") return null;    expect(await s256(call.form.code_verifier ?? "")).toBe(challenge());    return reply(200, { access_token: "BQtest-access-1", token_type: "Bearer", scope, expires_in: 3600, refresh_token: REFRESH });  };}/** A callback page as the person's browser goes through it: a "Connect …?" page is tapped through (src/connect_confirm.ts). */export async function page(url: string): Promise<{ status: number; text: string }> {  const res = await SELF.fetch(url, { redirect: "manual" });  const text = await res.text();  if (!text.includes('<form method="post"')) return { status: res.status, text };  const form = new URLSearchParams([...text.matchAll(/<input type="hidden" name="(\w+)" value="([^"]*)">/g)].map((m) => [m[1]!, m[2]!.replace(/&amp;/g, "&")]));  const tapped = await SELF.fetch(url.split("?")[0]!, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: form.toString() });  return { status: tapped.status, text: await tapped.text() };}/** Connect as the owner, all the way: the consent page, then Spotify's answer brought back through `/b/<slug>`. */export async function connectSpotify(slug: string, owner: string, fake: FakeSpotify, scope?: string): Promise<{ status: number; text: string; state: string; calls: Call[] }> {  let challenge = "";  const calls = spotify(trades(() => challenge, scope), fake.route);  const res = await SELF.fetch(`https://example.test/b/${slug}/v1/spotify/connect`, { headers: { authorization: `Bearer ${owner}` } });  expect(res.status).toBe(200);  const { authorizeUrl, state } = (await res.json()) as { authorizeUrl: string; state: string };  expect(state.startsWith(`${DATABASE_ID}.`)).toBe(true);  challenge = new URL(authorizeUrl).searchParams.get("code_challenge")!;  return { ...(await page(`https://example.test/b/${slug}/v1/spotify/callback?code=test-code&state=${encodeURIComponent(state)}`)), state, calls };}