Cotton code
194 lines · 10.3 KB · TypeScriptRaw
/** * Spotify on the person's object, for its podcasts (src/spotify.ts, * src/spotify_pull.ts): the consent page with PKCE and a one-shot state, the * grant sealed, the status, the disconnect; the pull of followed shows into * the Podcasts tool and saved episodes' resume points onto their episodes, * reruns that change nothing, a 401 answered by a fresh token, a 429's * Retry-After honoured, a grant Spotify no longer honours; and nothing of * the person's music asked for or written. Spotify is a fake (test/spotify.ts). */import { env, runInDurableObject } from "cloudflare:test";import { afterEach, describe, expect, it } from "vitest";import { Refused } from "../src/http.ts";import { s256 } from "../src/oauth.ts";import { client, hosts, SCOPES } from "../src/spotify.ts";import { Store, type StoredRow } from "../src/store.ts";import { connectSpotify, episode, FakeSpotify, page, REFRESH, show, spotify, USER } from "./spotify.ts";import { DATABASE_ID, http, personalObject } from "./personal.ts";// A connect wakes the object's pull, which may ask Spotify after a test is done: it finds an empty library, never the network.afterEach(() => {  spotify(new FakeSpotify().route);});const bearer = (token: string): Record<string, string> => ({ authorization: `Bearer ${token}` });const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));interface Status {  available: boolean;  account: null | {    userId: string;    displayName: string | null;    phase: string;    step: string | null;    lastError: string | null;    retryAt: string | null;    episodesWaiting: number;    shows: { followed: number; resolved: { name: string; feedUrl: string }[]; unresolved: string[] };  };}async function status(slug: string, owner: string): Promise<Status> {  const res = await http<Status>(slug, "GET", "/v1/spotify/status", undefined, bearer(owner));  expect(res.status, JSON.stringify(res.body)).toBe(200);  return res.body;}/** Every live row of a table, keyed by id. */async function rows(slug: string, table: string): Promise<StoredRow[]> {  return runInDurableObject(stub(slug), (_i, state) => [...new Store(state.storage.sql, () => new Date()).scan(table)]);}/** A library of followed shows (one with a feed, one a Spotify exclusive) and saved episodes. */function library(): FakeSpotify {  const f = new FakeSpotify();  f.shows = [show(1, "Synthetic Morning Show"), show(2, "A Spotify Exclusive")];  f.feeds.set("Synthetic Morning Show", "https://feeds.example.test/morning.xml");  f.episodes = [episode(1, 1, 125_400), episode(2, 1, 0, true)];  return f;}describe("connecting Spotify", () => {  it("answers the owner Spotify's consent page: the read scopes, PKCE S256, a state naming the database, the open host's callback", async () => {    const { owner } = await personalObject("sconnect");    const res = await http<{ authorizeUrl: string; state: string }>("sconnect", "GET", "/v1/spotify/connect", undefined, bearer(owner));    expect(res.status, JSON.stringify(res.body)).toBe(200);    const url = new URL(res.body.authorizeUrl);    expect(url.origin + url.pathname).toBe("https://accounts.spotify.com/authorize");    const q = Object.fromEntries(url.searchParams);    expect(q).toEqual({      client_id: "test-spotify-client",      response_type: "code",      redirect_uri: "https://cottondb.com/v1/spotify/callback",      scope: "user-library-read user-read-playback-position",      state: res.body.state,      code_challenge_method: "S256",      code_challenge: expect.stringMatching(/^[A-Za-z0-9_-]{43}$/),      show_dialog: "true",    });    expect(res.body.state).toMatch(new RegExp(`^${DATABASE_ID}\\.[A-Za-z0-9_-]{20,}$`));  });  it("is the owner's alone, and refuses by name on a Worker with no Spotify client or a fake Spotify in production", async () => {    await personalObject("sstranger");    expect((await http("sstranger", "GET", "/v1/spotify/connect")).status).toBe(403);    expect((await http("sstranger", "GET", "/v1/spotify/status")).status).toBe(403);    const refusal = (fn: () => unknown): string => {      try {        fn();      } catch (e) {        return (e as Refused).code;      }      return "none";    };    expect(refusal(() => client({ ...env, SPOTIFY_CLIENT_SECRET: undefined }))).toBe("spotify_unavailable");    expect(refusal(() => hosts({ ...env, ENV_LABEL: "production", SPOTIFY_API_URL: "http://127.0.0.1:9999/v1" }))).toBe("spotify_misconfigured");    expect(hosts({ ...env, SPOTIFY_API_URL: "http://127.0.0.1:9999/v1/" }).api).toBe("http://127.0.0.1:9999/v1");  });  it("trades the code with the verifier the challenge was made from, names the account by /me, seals the refresh token and says so plainly", async () => {    const { owner } = await personalObject("strade");    const fake = new FakeSpotify();    const done = await connectSpotify("strade", owner, fake);    expect(done.status, done.text).toBe(200);    expect(done.text).toContain("Spotify is connected");    expect(done.text).toContain(USER.display_name);    expect(done.text).not.toContain(REFRESH);    const trade = done.calls.find((c) => c.form.grant_type === "authorization_code")!;    expect(trade.form).toEqual({ grant_type: "authorization_code", code: "test-code", redirect_uri: "https://cottondb.com/v1/spotify/callback", code_verifier: expect.any(String) });    expect(trade.form.code_verifier!.length).toBeGreaterThanOrEqual(43);    expect(await s256(trade.form.code_verifier!)).toMatch(/^[A-Za-z0-9_-]{43}$/);    await runInDurableObject(stub("strade"), (_i, state) => {      const store = new Store(state.storage.sql, () => new Date());      const row = store.list("secret", { column: "service", equals: "spotify" })[0]!;      expect(row.data).toMatchObject({ name: `spotify.${USER.id}`, kind: "api_key", hint: REFRESH.slice(-4) });      expect(String(row.data.sealed)).toMatch(/^t1:/);      expect(JSON.stringify(row.data)).not.toContain(REFRESH);      expect(store.meta("spotify_pending")).toBeNull();    });    const s = await status("strade", owner);    expect(s.available).toBe(true);    expect(s.account).toMatchObject({ userId: USER.id, displayName: USER.display_name, lastError: null });  });  it("spends a state once, refuses one it never gave, keeps nothing when declined or given less than it reads with", async () => {    const { owner } = await personalObject("sonce");    const first = await connectSpotify("sonce", owner, new FakeSpotify());    expect(first.status).toBe(200);    const calls = spotify(new FakeSpotify().route);    const again = await page(`https://example.test/b/sonce/v1/spotify/callback?code=test-code&state=${encodeURIComponent(first.state)}`);    expect(again.status).toBe(400);    expect(again.text).toContain("expired or was already used");    const forged = await page(`https://example.test/b/sonce/v1/spotify/callback?code=test-code&state=${DATABASE_ID}.forged-state-value`);    expect(forged.status).toBe(400);    // The pull the first connect woke may refresh meanwhile; no code was traded again.    expect(calls.filter((c) => c.form.grant_type === "authorization_code")).toEqual([]);    const { owner: o2 } = await personalObject("sdecline");    spotify();    const connect = await http<{ state: string }>("sdecline", "GET", "/v1/spotify/connect", undefined, bearer(o2));    const declined = await page(`https://example.test/b/sdecline/v1/spotify/callback?error=access_denied&state=${encodeURIComponent(connect.body.state)}`);    expect(declined.text).toContain("Spotify did not give Cotton access");    const less = await connectSpotify("sdecline", o2, new FakeSpotify(), "user-library-read");    expect(less.status).toBe(400);    expect(less.text).toContain("user-read-playback-position");    expect((await status("sdecline", o2)).account).toBeNull();  });  it("brings Spotify's answer back to the open host, which finds the object by the state alone", async () => {    const { owner } = await personalObject("sopen");    const admin = await fetchAdmin("sopen");    expect(admin).toBe(200);    const fake = new FakeSpotify();    let challenge = "";    const { trades } = await import("./spotify.ts");    spotify(trades(() => challenge), fake.route);    const res = await http<{ authorizeUrl: string; state: string }>("sopen", "GET", "/v1/spotify/connect", undefined, bearer(owner));    challenge = new URL(res.body.authorizeUrl).searchParams.get("code_challenge")!;    const done = await page(`https://cottondb.com/v1/spotify/callback?code=test-code&state=${encodeURIComponent(res.body.state)}`);    expect(done.status, done.text).toBe(200);    expect(done.text).toContain("Spotify is connected");  });  // Podcasts left with TABLE DROP 1 (owner, 27 Nov 2026): no show is subscribed by the pull, so none is left to keep.  it("disconnects: the grant's secret binned, the account forgotten", async () => {    const { owner } = await personalObject("sdisc");    const fake = library();    await connectSpotify("sdisc", owner, fake);    spotify(fake.route);    const res = await http<{ ok: boolean; account: string; revokeAt: string }>("sdisc", "POST", "/v1/spotify/disconnect", {}, bearer(owner));    expect(res.body).toEqual({ ok: true, account: USER.id, revokeAt: "https://www.spotify.com/account/apps/" });    expect((await status("sdisc", owner)).account).toBeNull();    expect(await rows("sdisc", "secret").then((r) => r.filter((s) => s.data.service === "spotify"))).toEqual([]);    expect((await http("sdisc", "POST", "/v1/spotify/disconnect", {}, bearer(owner))).status).toBe(404);  });});/** Enters the object in the directory, so the open host finds it by its database id. */async function fetchAdmin(slug: string): Promise<number> {  const { SELF } = await import("cloudflare:test");  const { ADMIN, OWNER_PHONE } = await import("./personal.ts");  const res = await SELF.fetch("https://cottondb.com/v1/admin/directory", { method: "POST", headers: { "content-type": "application/json", ...ADMIN }, body: JSON.stringify({ database_id: DATABASE_ID, slug, phone: OWNER_PHONE }) });  return res.status;}describe("the history import", () => {  it("is gone: Spotify's streaming history is not Cotton Music's", async () => {    const { owner } = await personalObject("shistory");    const res = await http("shistory", "POST", "/v1/spotify/history", { listens: [] }, bearer(owner));    expect(res.status).toBe(404);    expect(SCOPES).toEqual(["user-library-read", "user-read-playback-position"]);  });});