Files
kuentagym/api/test/server-radio.test.js
T
dsantillan 48cf976635
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Radio: estaciones en vivo mientras entrenás
Música tiene una sección **Radio**: estaciones en vivo por género (Workout/Rave,
Techno/House, R&B/Soul, Latina, Hip-Hop, Reggae, Chill, Jazz, Rock, Electrónica),
sin publicidad primero —SomaFM y Radio Paradise— y detrás el directorio público de
radio-browser. Nada de esto suma dependencias: la lista la arma api/radio.js.

Tres decisiones que no se ven en la pantalla y son las que hacen que funcione:

- **El audio no pasa por el servidor.** La api entrega la lista y después no ve un
  byte: el teléfono habla con la estación. Sin ancho de banda, sin disco, sin copias.
- **La URL del stream viene resuelta en la lista**, porque iOS sólo deja arrancar
  audio dentro del gesto del toque: cualquier cosa asíncrona entre el dedo y el
  play() es un botón que no hace nada, sin error en ninguna parte.
- **El `<audio>` vive fuera de React** (lib/radio-player.js): un elemento dentro de
  un componente se desmonta con él, y eso es la música cortándose al cambiar de
  pantalla — justo lo que no puede pasar en medio de una serie.

Barra arriba de la barra de pestañas con pausa (deja la estación donde estaba) y
parar; Media Session pone estación, pista y controles en la pantalla bloqueada, y
las canciones siguen con el teléfono en el bolsillo. Qué suena lo dicen SomaFM y
Radio Paradise y nadie más: en el resto la barra muestra la estación en vez de
inventar una pista.

api/test/server-radio.test.js guarda las dos puertas (sesión obligatoria, `src`+`id`
reconstruidos en vez de confiar en el objeto del cliente); RadioBar.test.jsx y el
caso de la fila en Music.test.jsx guardan lo demás.

También: radio.js en el COPY del Dockerfile —importar un archivo que no está copiado
es un contenedor que arranca en ERR_MODULE_NOT_FOUND—, /api/radio y /api/radio/now
(con /api/music/lookup, que faltaba) en la especificación, y docs/RADIO.md.
2026-09-23 20:38:19 -04:00

83 lines
3.8 KiB
JavaScript

/* The two radio routes, against the real server: who may call them, and what `/now` agrees to look
up. What a genre actually returns is api/test/radio.test.js, which owns the directory logic and
stubs the network — this file is the guards, because a guard is exactly the thing that quietly
stops guarding.
The second one matters more than it looks. `/api/radio/now` takes a source and an id *from the
request* and uses them to build a URL this process then fetches; if the source stopped being
checked, the api container (which sits on the owner's own network) would become a request proxy
for anyone holding a session. */
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-radio-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: 'u_r', 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;
}
test('the station list needs a session', async t => {
const h = await startServer(t);
// Not an open station directory: the list is what this instance's owner pays attention to, and
// the audio itself never passes through here.
const r = await fetch(`${h.api}/api/radio`);
assert.equal(r.status, 401);
});
test('what is playing needs a session too', async t => {
const h = await startServer(t);
const r = await fetch(`${h.api}/api/radio/now?src=soma&id=beatblender`);
assert.equal(r.status, 401);
});
test('a station that is not one of the two known sources is refused, unfetched', async t => {
const h = await startServer(t);
for (const q of [
'src=http://127.0.0.1:3000&id=health', // a source that is not one of ours
'src=soma', // no id at all
'src=soma&id=' + encodeURIComponent('../../x'),// an id that would walk out of the path
'src=soma&id=' + encodeURIComponent('a b c'),
'id=beatblender' // no source
]) {
const r = await fetch(`${h.api}/api/radio/now?${q}`, { headers: cookie('u_r') });
assert.equal(r.status, 400, `${q} should be refused`);
assert.match((await r.json()).error, /no such station/);
}
});