/* POST /api/music/lookup, against the real server: who may call it, and what it will agree to fetch. The fetch itself is Apple's, so the happy path is covered by api/test/music.test.js — these are the two guards, and a guard is exactly the kind of thing that quietly stops guarding. */ import { test } from 'node:test'; import assert from 'node:assert/strict'; import crypto from 'node:crypto'; import net from 'node:net'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { spawn } from 'node:child_process'; import { fileURLToPath } from 'node:url'; const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..'); const SECRET = crypto.randomBytes(32).toString('hex'); function mintSession(uid, sv = 0) { const payload = `${uid}:${Date.now() + 86400000}:${sv}`; return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url'); } const cookie = uid => ({ Cookie: `gymsid=${mintSession(uid)}` }); const freePort = () => new Promise(r => { const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); }); }); async function startServer(t) { const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-music-')); fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 }); fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: 'u_m', name: 'One', created: '2026-01-01T00:00:00.000Z' }], creds: [], subs: [], invites: [] })); const port = await freePort(); const child = spawn(process.execPath, ['server.js'], { cwd: API, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' } }); const h = { api: `http://127.0.0.1:${port}`, log: '' }; child.stdout.on('data', d => h.log += d); child.stderr.on('data', d => h.log += d); t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); }); let up = false; for (let i = 0; i < 100 && !up; i++) { try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ } if (!up) await new Promise(r => setTimeout(r, 100)); } assert.ok(up, `server never came up:\n${h.log}`); return h; } const lookup = (h, url, headers = cookie('u_m')) => fetch(`${h.api}/api/music/lookup`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin', ...headers }, body: JSON.stringify({ url }) }); test('the lookup needs a session', async t => { const h = await startServer(t); const r = await fetch(`${h.api}/api/music/lookup`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url: 'https://music.apple.com/us/playlist/x/pl.1' }) }); assert.equal(r.status, 401); }); test('it refuses anything that is not an Apple Music link, before any request is made', async t => { const h = await startServer(t); // The api container sits on the owner's network. Every one of these would be a request forged // from the container if the host were not checked, so each is a 400 and none of them is fetched. for (const url of [ 'http://127.0.0.1:3000/api/health', 'http://169.254.169.254/latest/meta-data/', 'http://192.168.1.1/', 'https://music.apple.com.evil.test/us/playlist/x/pl.1', 'http://music.apple.com/us/playlist/x/pl.1', // plain http, even on the right host 'https://open.spotify.com/playlist/37i9dQZF1DXcBWIGoYBM5M', 'not a url', '', null ]) { const r = await lookup(h, url); assert.equal(r.status, 400, `${url} should be refused`); assert.match((await r.json()).error, /Apple Music/); } });