From 544122de5cff01f6396e9345bbfadc1da49eedb3 Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Mon, 30 Nov 2026 10:47:13 -0800 Subject: [PATCH] Keep the Spotify example login callback on loopback Serve the one-shot callback page from memory and finish denied, repeated, and missing-token requests explicitly. Document the matching redirect URI and cover the listener with offline tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- typescript/examples/music/README.md | 2 +- typescript/examples/music/src/authz.ts | 59 ++++++++++++++-------- typescript/tests/examples.test.mjs | 69 +++++++++++++++++++++++++- 3 files changed, 106 insertions(+), 24 deletions(-) diff --git a/typescript/examples/music/README.md b/typescript/examples/music/README.md index abe01eda..50df2823 100644 --- a/typescript/examples/music/README.md +++ b/typescript/examples/music/README.md @@ -13,7 +13,7 @@ This example also requires additional setup to use the Spotify API: 1. Go to https://developer.spotify.com/dashboard. 2. Log into Spotify with your user account if you are not already logged in. 3. Click the button in the upper right labeled "Create App". -4. Fill in the form, making sure the Redirect URI is http://localhost:PORT/callback, where PORT is a four-digit port number you choose for the authorization redirect. +4. Register `http://127.0.0.1:PORT/callback` as the Redirect URI, replacing `PORT` with a four-digit port of your choice. The example listens only on this IPv4 loopback address. If your app previously used `localhost`, add the new URI to its settings. 5. Click the settings button and copy down the Client ID and Client Secret (the client secret requires you to click 'View client secret'). 6. In your `.env` file, set `SPOTIFY_APP_CLI` to your Client ID and `SPOTIFY_APP_CLISEC` to your Client Secret. Also set `SPOTIFY_APP_PORT` to the PORT on your local machine that you chose in step 4. diff --git a/typescript/examples/music/src/authz.ts b/typescript/examples/music/src/authz.ts index c86bd142..13af8afa 100644 --- a/typescript/examples/music/src/authz.ts +++ b/typescript/examples/music/src/authz.ts @@ -2,6 +2,7 @@ import open from "open"; import chalk from "chalk"; import express from "express"; import dotenv from "dotenv"; +import { readFileSync } from "fs"; import path from "path"; dotenv.config({ path: path.join(__dirname, "../../../.env") }); @@ -30,19 +31,20 @@ const scope = [ const baseClientId = process.env.SPOTIFY_APP_CLI; const defaultPort = process.env.SPOTIFY_APP_PORT; +const loopbackHost = "127.0.0.1"; export class Authzor { url: string; app: express.Express; handler: AuthzHandler; server: AuthzServer; - private redirectCount = 0; + private callbackHtml?: string; constructor( public port = defaultPort, public showDialog = false, public clientId = baseClientId ) { - const redirectUri = "http://localhost:" + port + "/callback"; + const redirectUri = `http://${loopbackHost}:${port}/callback`; this.url = "https://accounts.spotify.com/authorize" + @@ -59,36 +61,42 @@ export class Authzor { this.app = express(); this.app.get("/callback", (req, res) => { - if (req.query.error) { - console.log( - chalk.red("Something went wrong. Error: "), - req.query.error - ); - } else { - // update this when implementing re-auth on token expire - if (this.redirectCount === 0) { - res.sendFile(__dirname + "/callback.html"); - this.redirectCount++; - } + res.set("Cache-Control", "no-store"); + const html = this.callbackHtml; + if (html === undefined) { + res.status(410).send("This Spotify login callback has already been used."); + return; + } + this.callbackHtml = undefined; + if (req.query.error !== undefined) { + res.status(400).send("Spotify authorization failed. You can close this window."); + this.finish(undefined); + return; } + res.type("html").send(html); }); this.app.get("/token", (req, res) => { - res.sendStatus(200); - const token = req.query.access_token as string; - if (token) { - if (this.handler) { - this.handler(token); - } + const token = req.query.access_token; + if (typeof token !== "string" || !token) { + res.status(400).send("Missing Spotify access token."); + this.finish(undefined); + return; } - this.close(); + res.sendStatus(200); + this.finish(token); }); } authorize(connect: boolean, handler: AuthzHandlerFn) { - if (baseClientId && connect) { + if (this.clientId && connect) { + const port = Number(this.port); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error("Set SPOTIFY_APP_PORT to a TCP port between 1 and 65535."); + } + this.callbackHtml = readFileSync(path.join(__dirname, "callback.html"), "utf8"); this.handler = handler; - this.server = this.app.listen(this.port, () => { + this.server = this.app.listen(port, loopbackHost, () => { if (this.showDialog) { console.log( chalk.blue( @@ -103,6 +111,13 @@ export class Authzor { } } + private finish(token: string | undefined) { + const handler = this.handler; + this.handler = undefined; + this.close(); + handler?.(token); + } + close() { if (this.server) { this.server.close(); diff --git a/typescript/tests/examples.test.mjs b/typescript/tests/examples.test.mjs index 987efbdc..8543bec4 100644 --- a/typescript/tests/examples.test.mjs +++ b/typescript/tests/examples.test.mjs @@ -1,7 +1,9 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { readFileSync } from "node:fs"; +import { once } from "node:events"; +import { copyFileSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { describe, test } from "node:test"; import { fileURLToPath } from "node:url"; @@ -59,6 +61,71 @@ function compileExample(file) { }).outputText; } +async function startMusicLogin(t) { + const file = join(examplesDir, "music", "src", "authz.ts"); + const dir = mkdtempSync(join(tmpdir(), "typechat-music-login-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const page = join(dir, "callback.html"); + copyFileSync(join(dirname(file), "callback.html"), page); + const html = readFileSync(page, "utf8"); + + const open = t.mock.fn(); + const require = createRequire(file); + const exports = {}; + compileFunction(compileExample(file), ["require", "exports", "__dirname"], { filename: file })( + name => name === "open" ? open : name === "dotenv" ? { config() {} } : require(name), exports, dir + ); + const auth = new exports.Authzor("4321", false, "test-client"); + const listen = auth.app.listen.bind(auth.app); + // Let the OS choose a free port, but exercise the example's actual bind address. + t.mock.method(auth.app, "listen", (port, ...args) => { + assert.equal(port, 4321); + return listen(0, ...args); + }); + const tokens = []; + auth.authorize(true, token => tokens.push(token)); + const server = auth.server; + t.after(() => { if (server.listening) server.close(); }); + await once(server, "listening"); + const { address, port } = server.address(); + assert.equal(address, "127.0.0.1"); + const url = new URL(open.mock.calls[0].arguments[0]); + assert.equal(url.searchParams.get("redirect_uri"), `http://${address}:4321/callback`); + rmSync(page); // Serving the callback must no longer depend on the file. + const get = path => fetch(`http://${address}:${port}${path}`, { signal: AbortSignal.timeout(5000) }); + return { get, html, server, tokens }; +} + +test("music login serves the preloaded callback once and completes with the token", async t => { + const { get, html, server, tokens } = await startMusicLogin(t); + const callback = await get("/callback"); + assert.equal(callback.status, 200); + assert.match(callback.headers.get("content-type"), /^text\/html/); + assert.equal(await callback.text(), html); + assert.equal((await get("/callback")).status, 410); + assert.deepEqual(tokens, []); + assert.equal((await get("/token?access_token=test-token")).status, 200); + assert.deepEqual(tokens, ["test-token"]); + assert.equal(server.listening, false); +}); + +test("music login finishes a denied callback without a token", async t => { + const { get, server, tokens } = await startMusicLogin(t); + const response = await get("/callback?error=access_denied"); + assert.equal(response.status, 400); + assert.match(await response.text(), /authorization failed/); + assert.deepEqual(tokens, [undefined]); + assert.equal(server.listening, false); +}); + +test("music login reports a missing token and closes the listener", async t => { + const { get, server, tokens } = await startMusicLogin(t); + assert.equal((await get("/callback")).status, 200); + assert.equal((await get("/token")).status, 400); + assert.deepEqual(tokens, [undefined]); + assert.equal(server.listening, false); +}); + for (const example of examples) { const source = compileExample(join(examplesDir, example, "src", "main.ts"));