/** * Spotify on the person's own object, for its podcasts (owner, 4 Nov 2026: * Cotton Music is the music a person owns as files, with no Spotify library * import): one Spotify sign-in from the phone, the grant kept sealed by the * object, the followed shows and saved episodes pulled on the object's own * alarm into the Podcasts tool. The official Web API only, read-only scopes; * the audio is never touched. Podcasts is retired (TABLE DROP 1, 27 Nov 2026) * and its pull is gone: connect, status and disconnect stay, as the phone * still calls them, while Spotify is parked. * * GET /v1/spotify/connect (owner) { authorizeUrl, state }: Spotify's * consent page, with PKCE (S256) and a one-shot state; the redirect is * the callback on the open host (cottondb.com live, the dev Worker's * own host on dev), which is the one URI registered on the app * GET /v1/spotify/callback Spotify sends the browser back here with * `code` and `state`; the open host finds the object by the state's * database id (src/open.ts), the object trades the code with the * verifier, seals the refresh token into a `secret` row, names the * account by `/v1/me` and answers a plain page * GET /v1/spotify/status (owner) { available, account: null | { * userId, displayName, connectedAt, phase, syncing, syncedAt, * lastPassAt, lastError, lastErrorMessage, retryAt, episodesWaiting, * shows } } * POST /v1/spotify/disconnect (owner) {}: forgets the grant (Spotify has * no revocation endpoint: the person removes Cotton at * spotify.com/account/apps, which the answer says); the shows * subscribed stay the person's * * STATE is `.`, its hash and the PKCE verifier kept in * this object's meta alone, ten minutes, spent once. * * THE GRANT is a `secret` row of kind api_key, service `spotify`, named * `spotify.`: `sealed` is the refresh token under SERVICE_TOKEN_KEY (t1, src/vault.ts) with the * row's id bound in. Spotify may hand a new refresh token on a refresh; the * pull seals it in the same row. No answer, page or log line carries it. * * THE CLIENT is the owner's own Spotify developer app: SPOTIFY_CLIENT_ID (a * var) and SPOTIFY_CLIENT_SECRET (a secret). A development Worker may name * SPOTIFY_ACCOUNTS_URL and SPOTIFY_API_URL to talk to a fake Spotify * instead; production refuses them. */ import type { Engine, Outcome } from "./engine.ts"; import { isProduction, type Env } from "./env.ts"; import { esc, page, s256 } from "./oauth.ts"; import { randomToken, refuse, sha256Hex } from "./http.ts"; import { equalSql } from "./mcp/tools/records/where.ts"; import type { Store } from "./store.ts"; import * as vault from "./vault.ts"; /** Saved shows and episodes (user-library-read) and the episodes' resume points (user-read-playback-position): nothing of the person's music. */ export const SCOPES = ["user-library-read", "user-read-playback-position"] as const; export const ACCOUNTS_URL = "https://accounts.spotify.com"; export const API_URL = "https://api.spotify.com/v1"; export const CALLBACK_PATH = "/v1/spotify/callback"; /** Where the person takes Cotton's access away: Spotify has no revocation endpoint. */ export const APPS_PAGE = "https://www.spotify.com/account/apps/"; /** The routes this module answers on a personal object (the callback apart: it carries no bearer). */ export const SPOTIFY_PATH = /^\/v1\/spotify\/(connect|status|disconnect)$/; export const STATE_TTL_MS = 10 * 60 * 1000; const ACCOUNT = "spotify_account"; const PENDING = "spotify_pending"; const SECRET = "secret"; const SERVICE = "spotify"; export type Phase = "waiting" | "syncing" | "synced" | "reconnect"; export interface PassError { code: string; message: string; at: string; } /** The steps of one whole pull, in order; each keeps its own cursor. */ export const STEPS: readonly Step[] = ["shows", "episodes"]; export type Step = "shows" | "episodes"; export interface Cursors { /** Followed shows, whole each cycle; `seen` the ones this cycle met, so an unfollowed show leaves. */ shows: { offset: number; seen: string[] }; /** Saved episodes, whole each cycle (resume points move): kept in `spotify_episode_marks`, then written onto the Podcasts tool's episodes. */ episodes: { offset: number }; } export interface Show { spotify_id: string; name: string; /** The RSS feed found for it by name on the iTunes directory; null when none matched (a Spotify exclusive has none). */ feed_url: string | null; /** Whether the directory was asked: a show not yet asked is asked on a later pass. */ looked_up: boolean; /** The Podcasts tool's `podcast` row the feed is subscribed as; null until it is. */ podcast?: string | null; /** When subscribing was last tried, and why it failed; tried again a cycle later. */ subscribe_tried_at?: string | null; subscribe_error?: string | null; } /** The one connected Spotify account, as this object keeps it in its meta (never synced). */ export interface Account { user_id: string; display_name: string | null; secret: string; connected_at: string; phase: Phase; /** The step a cycle is at; null between cycles. */ step: Step | null; cursors: Cursors; cycle_started_at: string | null; synced_at: string | null; last_pass_at: string | null; last_error: PassError | null; /** Spotify asked us to wait (429 Retry-After): no call before this instant. */ retry_at: string | null; /** Followed shows and the feed each resolved to. */ shows: Show[]; } export function freshCursors(): Cursors { return { shows: { offset: 0, seen: [] }, episodes: { offset: 0 }, }; } /** What the object lends this module. */ export interface SpotifyHost { env: Env; store: Store; /** The object's own SQLite: the pull's private tables. */ sql: SqlStorage; databaseId: string; /** Writes in one transaction and one version, logged as Spotify's. */ write(fn: (engine: Engine, version: number, outcome: Outcome) => T): T; /** The same, with what it makes or changes in a sealed table sealed at arrival (src/arrival_seam.ts): `fn` runs twice. */ writeSealed(fn: (engine: Engine, version: number, outcome: Outcome) => T): Promise; /** Sets the object's alarm for now: a new grant is pulled at once. */ wake(): Promise; /** What the pull fetches with: the Worker's fetch, or a test's. */ fetcher: (input: string, init?: RequestInit) => Promise; } // ── the account in the meta ────────────────────────────────────────────── export function readAccount(store: Store): Account | null { const raw = store.meta(ACCOUNT); if (!raw) return null; try { return JSON.parse(raw) as Account; } catch { return null; } } /** The Spotify account, stopped by a pass for want of an unopened grant the SERVICE_TOKEN_KEY rekey has just moved, pulls again (as src/google.ts `reviveRekeyed`). */ export function reviveRekeyed(store: Store, secrets: Set): number { const a = readAccount(store); if (!a || a.phase !== "reconnect" || !secrets.has(a.secret) || !a.last_error?.message.startsWith("the grant is not in the vault any more")) return 0; store.setMeta(ACCOUNT, JSON.stringify({ ...a, phase: a.synced_at ? "synced" : "waiting", last_error: null, retry_at: null })); return 1; } /** The account replaced, read fresh: a pass never writes over a disconnect that landed meanwhile. */ export function saveAccount(store: Store, account: Account): void { const held = readAccount(store); if (!held || held.user_id !== account.user_id) return; store.setMeta(ACCOUNT, JSON.stringify(account)); } // ── the client ─────────────────────────────────────────────────────────── /** The client this Worker is, or a refusal naming what it lacks. */ export function client(env: Env): { id: string; secret: string } { if (!env.SPOTIFY_CLIENT_ID || !env.SPOTIFY_CLIENT_SECRET) refuse(503, "spotify_unavailable", "this Worker has no Spotify client yet (SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET)"); return { id: env.SPOTIFY_CLIENT_ID, secret: env.SPOTIFY_CLIENT_SECRET }; } /** Spotify's two hosts: the real ones, or a development Worker's fake. */ export function hosts(env: Env): { accounts: string; api: string } { const accounts = env.SPOTIFY_ACCOUNTS_URL?.replace(/\/+$/, ""); const api = env.SPOTIFY_API_URL?.replace(/\/+$/, ""); if ((accounts || api) && isProduction(env)) refuse(503, "spotify_misconfigured", "SPOTIFY_ACCOUNTS_URL and SPOTIFY_API_URL are for a development Worker's fake Spotify, never production"); return { accounts: accounts || ACCOUNTS_URL, api: api || API_URL }; } /** The one redirect: the callback on the open host, registered on the Spotify app as is. */ export function redirectUri(env: Env): string { if (!env.OPEN_HOST) refuse(503, "spotify_unavailable", "this Worker has no open host to bring Spotify's answer back to (OPEN_HOST)"); return `${env.SPOTIFY_REDIRECT_SCHEME === "http" && !isProduction(env) ? "http" : "https"}://${env.OPEN_HOST}${CALLBACK_PATH}`; } /** The Basic header the token endpoint takes from a confidential client. */ export function basic(c: { id: string; secret: string }): string { return `Basic ${btoa(`${c.id}:${c.secret}`)}`; } // ── connect ────────────────────────────────────────────────────────────── interface Pending { hash: string; expires: number; verifier: string; } function readPending(store: Store): Pending[] { try { const parsed = JSON.parse(store.meta(PENDING) ?? "[]") as unknown; return Array.isArray(parsed) ? (parsed as Pending[]) : []; } catch { return []; } } /** `GET /v1/spotify/connect`: Spotify's consent page for this object, its one-shot state and its PKCE challenge. */ export async function connect(host: SpotifyHost): Promise<{ authorizeUrl: string; state: string }> { const { id } = client(host.env); const { accounts } = hosts(host.env); const redirect = redirectUri(host.env); const state = `${host.databaseId}.${randomToken(24)}`; const verifier = randomToken(48); const now = Date.now(); const pending = readPending(host.store).filter((p) => p.expires > now); pending.push({ hash: await sha256Hex(state), expires: now + STATE_TTL_MS, verifier }); host.store.setMeta(PENDING, JSON.stringify(pending)); const url = new URL(`${accounts}/authorize`); url.search = new URLSearchParams({ client_id: id, response_type: "code", redirect_uri: redirect, scope: SCOPES.join(" "), state, code_challenge_method: "S256", code_challenge: await s256(verifier), show_dialog: "true", }).toString(); return { authorizeUrl: url.toString(), state }; } /** A state this object gave and has not spent: its verifier once, and never again (null). */ /** Whether `state` is one this object gave, unspent and in time: looked at, not spent (the confirming page). */ export async function awaiting(store: Store, state: string): Promise { const hash = await sha256Hex(state); return readPending(store).some((p) => p.hash === hash && p.expires > Date.now()); } async function spend(store: Store, state: string): Promise { const hash = await sha256Hex(state); const now = Date.now(); const pending = readPending(store); const held = pending.find((p) => p.hash === hash && p.expires > now); const left = pending.filter((p) => p.hash !== hash && p.expires > now); store.setMeta(PENDING, left.length ? JSON.stringify(left) : null); return held?.verifier ?? null; } function said(title: string, line: string, status = 200): Response { return page(title, `

${esc(line)}

`, status); } const NOT = "Spotify was not connected"; /** * `GET /v1/spotify/callback?code&state` (or `?error&state`): the state is * spent first, whatever follows; then the code is traded with its verifier, * the scopes checked, the account named, the grant sealed and the pull woken. */ export async function callback(host: SpotifyHost, url: URL): Promise { const state = url.searchParams.get("state") ?? ""; const verifier = state.startsWith(`${host.databaseId}.`) ? await spend(host.store, state) : null; if (!verifier) return said(NOT, "This link has expired or was already used. Start again from Cotton.", 400); if (url.searchParams.get("error")) return said(NOT, "Spotify did not give Cotton access. You can close this page."); const code = url.searchParams.get("code"); if (!code) return said(NOT, "Spotify sent no code back. Start again from Cotton.", 400); const c = client(host.env); const { accounts, api } = hosts(host.env); const traded = await host.fetcher(`${accounts}/api/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", authorization: basic(c) }, body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri(host.env), code_verifier: verifier }).toString(), }); const grant = (await traded.json().catch(() => ({}))) as { access_token?: string; refresh_token?: string; scope?: string }; if (!traded.ok || !grant.access_token) return said(NOT, "Spotify refused the sign-in. Start again from Cotton.", 502); const granted = new Set((grant.scope ?? "").split(" ")); const missing = SCOPES.filter((s) => !granted.has(s)); if (missing.length) return said(NOT, `Spotify gave less access than Cotton reads with (${missing.join(", ")}). Start again from Cotton.`, 400); if (!grant.refresh_token) return said(NOT, "Spotify gave no lasting access. Start again from Cotton.", 502); const me = await host.fetcher(`${api}/me`, { headers: { authorization: `Bearer ${grant.access_token}` } }); const profile = (await me.json().catch(() => ({}))) as { id?: string; display_name?: string | null }; if (!me.ok || !profile.id) return said(NOT, "Spotify did not say whose account this is. Start again from Cotton.", 502); const held = readAccount(host.store); if (held && held.user_id !== profile.id) { return said(NOT, `Cotton already reads the Spotify account ${held.display_name ?? held.user_id}. Disconnect it in Cotton first.`, 409); } await keepGrant(host, profile.id, profile.display_name ?? null, grant.refresh_token); await host.wake(); return said("Spotify is connected", `Cotton now reads the Spotify podcasts of ${profile.display_name ?? profile.id}. You can close this page and go back to Cotton.`); } /** Seals a refresh token into the account's secret row: the one there, or a new one named for the account. */ export async function sealGrant(host: SpotifyHost, userId: string, refreshToken: string): Promise<{ id: string; patch: Record; held: boolean }> { const name = `spotify.${userId}`; // Its row is the one the account names (a sealed name is never read here, OPEN-TABLES.md §3), or the one by that name. const was = readAccount(host.store); const pointed = was && was.user_id === userId ? was.secret : null; const held = (pointed ? host.store.get(SECRET, pointed) : null) ?? host.store.select(SECRET, [equalSql("service", SERVICE), equalSql("name", name)], "created_at, id", 1)[0] ?? null; const id = held?.id ?? crypto.randomUUID(); const sealed = await vault.sealServiceToken(host.env, id, JSON.stringify({ kind: "api_key", key: refreshToken })); return { id, held: Boolean(held), patch: { sealed, hint: [...refreshToken].slice(-4).join(""), kind: "api_key", site: "open.spotify.com", trashed_at: null } }; } async function keepGrant(host: SpotifyHost, userId: string, displayName: string | null, refreshToken: string): Promise { const { id, patch, held } = await sealGrant(host, userId, refreshToken); await host.writeSealed((engine, version, outcome) => { const row = held ? host.store.get(SECRET, id) : null; if (row) engine.update(row, patch, version, outcome); else engine.create(SECRET, { ...patch, name: `spotify.${userId}`, service: SERVICE }, version, outcome, 0, { id }); const was = readAccount(host.store); const account: Account = was && was.user_id === userId ? { ...was, display_name: displayName, secret: id, phase: was.synced_at ? "synced" : "waiting", last_error: null, retry_at: null } : { user_id: userId, display_name: displayName, secret: id, connected_at: new Date().toISOString(), phase: "waiting", step: null, cursors: freshCursors(), cycle_started_at: null, synced_at: null, last_pass_at: null, last_error: null, retry_at: null, shows: [], }; host.store.setMeta(ACCOUNT, JSON.stringify(account)); }); } /** The refresh token the account's secret row seals, or null when it does not open. */ export async function refreshTokenOf(host: SpotifyHost, account: Account): Promise { const row = host.store.get(SECRET, account.secret); const sealed = typeof row?.data.sealed === "string" ? row.data.sealed : null; if (!sealed) return null; const opened = await vault.openServiceToken(host.env, account.secret, sealed); if (!opened) return null; try { const payload = JSON.parse(opened) as { key?: unknown }; return typeof payload.key === "string" ? payload.key : null; } catch { return null; } } // ── status and disconnect ──────────────────────────────────────────────── /** `GET /v1/spotify/status`: whether this Worker can connect at all, and how the one account stands. */ export function status(host: SpotifyHost): Record { const a = readAccount(host.store); return { available: Boolean(host.env.SPOTIFY_CLIENT_ID && host.env.SPOTIFY_CLIENT_SECRET && host.env.OPEN_HOST), account: a ? { userId: a.user_id, displayName: a.display_name, connectedAt: a.connected_at, phase: a.phase, syncing: a.phase === "syncing", step: a.step, syncedAt: a.synced_at, lastPassAt: a.last_pass_at, lastError: a.last_error?.code ?? null, lastErrorMessage: a.last_error?.message ?? null, retryAt: a.retry_at, // Saved episodes whose resume point has found no episode of a subscribed show (yet). episodesWaiting: host.sql.exec<{ n: number }>("SELECT count(*) AS n FROM sqlite_master WHERE type = 'table' AND name = 'spotify_episode_marks'").one().n ? host.sql.exec<{ n: number }>("SELECT count(*) AS n FROM spotify_episode_marks WHERE applied_position IS NULL").one().n : 0, shows: { followed: a.shows.length, resolved: a.shows.filter((s) => s.feed_url).map((s) => ({ name: s.name, feedUrl: s.feed_url, podcast: s.podcast ?? null, subscribeError: s.subscribe_error ?? null })), unresolved: a.shows.filter((s) => s.looked_up && !s.feed_url).map((s) => s.name), }, } : null, }; } /** `POST /v1/spotify/disconnect`: the grant's secret binned, the account forgotten; the shows subscribed stay. */ export function disconnect(host: SpotifyHost): Record { const account = readAccount(host.store); if (!account) refuse(404, "not_connected", "no Spotify account is connected"); host.write((engine, version, outcome) => { const row = host.store.get(SECRET, account.secret); if (row) engine.delete(row, version, outcome); host.store.setMeta(ACCOUNT, null); }); return { ok: true, account: account.user_id, revokeAt: APPS_PAGE }; }