import { createServer } from "node:http"; import { appendFileSync, readFileSync, writeFileSync, existsSync } from "node:fs"; const [clientId, clientSecret] = process.argv.slice(2); if (!clientId || !clientSecret) { console.error("usage: node scripts/spotify-auth.mjs "); process.exit(1); } const REDIRECT = "http://127.0.0.1:8888/callback"; const SCOPE = "user-read-currently-playing user-read-recently-played user-top-read"; const authUrl = "https://accounts.spotify.com/authorize?" + new URLSearchParams({ client_id: clientId, response_type: "code", redirect_uri: REDIRECT, scope: SCOPE, }); console.log("\n1. open this in your browser and approve:\n\n" + authUrl + "\n"); console.log("2. waiting for the redirect on " + REDIRECT + " ...\n"); const server = createServer(async (req, res) => { const url = new URL(req.url, "http://127.0.0.1:8888"); if (url.pathname !== "/callback") { res.writeHead(404).end(); return; } const code = url.searchParams.get("code"); const err = url.searchParams.get("error"); if (err || !code) { res.writeHead(400).end("no code (" + (err || "missing") + ")"); server.close(); process.exit(1); } const tokenRes = await fetch("https://accounts.spotify.com/api/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: "Basic " + Buffer.from(`${clientId}:${clientSecret}`).toString("base64"), }, body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: REDIRECT, }), }); const data = await tokenRes.json(); if (!data.refresh_token) { res.writeHead(500).end("token exchange failed: " + JSON.stringify(data)); console.error("\ntoken exchange failed:\n", data); server.close(); process.exit(1); } const block = `\nSPOTIFY_CLIENT_ID=${clientId}\n` + `SPOTIFY_CLIENT_SECRET=${clientSecret}\n` + `SPOTIFY_REFRESH_TOKEN=${data.refresh_token}\n`; if (existsSync(".dev.vars")) { const cur = readFileSync(".dev.vars", "utf8").replace(/^SPOTIFY_[A-Z_]+=.*$/gm, "").replace(/\n{3,}/g, "\n\n"); writeFileSync(".dev.vars", cur.trimEnd() + "\n" + block); } else { appendFileSync(".dev.vars", block); } res.writeHead(200, { "Content-Type": "text/plain" }).end("done — you can close this tab."); console.log("wrote SPOTIFY_CLIENT_ID / SPOTIFY_CLIENT_SECRET / SPOTIFY_REFRESH_TOKEN to .dev.vars\n"); console.log("for prod, run:"); console.log(" npx wrangler secret put SPOTIFY_CLIENT_ID"); console.log(" npx wrangler secret put SPOTIFY_CLIENT_SECRET"); console.log(" npx wrangler secret put SPOTIFY_REFRESH_TOKEN\n"); server.close(); process.exit(0); }); server.listen(8888, "127.0.0.1");