Radio: estaciones en vivo mientras entrenás
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

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.
This commit is contained in:
dsantillan committed 2026-09-23 20:38:19 -04:00
1 parent e1d28f971d
commit 48cf976635
22 files changed
+1662 -15

No files matched your search

+2 -2
View File
@@ -55,8 +55,8 @@ RUN npm ci --omit=dev --omit=optional && npm cache clean --force
# (a test, a script, a stray JSON) cannot reach the published image. vitals.js joined the list
# with the Apple Health ingest and music.js with the Música one — an import of a file that is not
# copied here is a container that boots straight into ERR_MODULE_NOT_FOUND, which is exactly what
# the first health build would have done.
COPY server.js push-messages.js verify-error.js vitals.js music.js jev.js insights.js ./
# the first health build would have done. radio.js is the station directory behind the player.
COPY server.js push-messages.js verify-error.js vitals.js music.js radio.js jev.js insights.js ./
COPY coach ./coach
ENV NODE_ENV=production
ENV PORT=3000
+193
View File
@@ -88,6 +88,11 @@ tags:
description: >-
Apple Health metrics ingested from an iPhone (Health Auto Export automations) —
per profile, write-only for the phone's ingest key
- name: music
description: >-
Música — reading a public Apple Music page for a saved playlist's card, and the live radio
station directory. Audio is never proxied by this server: the list carries resolved stream
URLs and the phone talks to the station directly.
- name: admin
description: Admin dashboard — requires an admin session (`ADMIN_UIDS` or `admin:true`)
@@ -909,6 +914,158 @@ paths:
description: The gateway refused or failed; the message carries what it said.
'401': { $ref: '#/components/responses/Unauthorized' }
/api/radio:
get:
tags: [music]
operationId: radioGet
summary: Live radio stations for a genre, with their stream URLs resolved
description: |
What the **Radio** section of the Música screen draws. Every station arrives with the URL to
hand an `<audio>` element already resolved — the one non-obvious decision here, and it is
about iOS: audio may only start *inside* the tap that asked for it, so anything asynchronous
between the finger and the `play()` is a press that quietly does nothing.
The audio never passes through this server. The list is the whole feature on this side: the
phone then talks to the station directly, so this instance spends no bandwidth and keeps no
copy of anything. Sources are SomaFM (commercial-free) and Radio Paradise for the curated
picks, and the public radio-browser directory for the rest, filtered to HTTPS and to codecs a
browser plays without a library (HLS streams are skipped — that would mean shipping a player
library).
A session is required. Not to protect the stations — they are public — but because this
container sits on the owner's own network and fetches on behalf of whoever asks.
An unknown or missing `genre` is not an error: it falls back to the first genre.
parameters:
- name: genre
in: query
schema:
type: string
enum: [workout, techno, rnb, latin, hiphop, reggae, chill, jazz, rock, electronic]
description: Genre key. Missing or unrecognised falls back to `workout`.
responses:
'200':
description: The genres for the chips, and the stations for the one that was asked for.
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
genres:
type: array
description: Every chip the screen offers, so the client never hard-codes them.
items:
type: object
properties:
key: { type: string }
label: { type: string }
genre: { type: string, description: The genre actually answered with. }
label: { type: string, description: That genre's human label. }
stations:
type: array
description: Curated, ad-free picks first, then the directory. At most 40.
items: { $ref: '#/components/schemas/RadioStation' }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/radio/now:
get:
tags: [music]
operationId: radioNow
summary: What a station says it is playing
description: |
The line under the station's name in the player bar, and the metadata the lock screen shows.
Only **SomaFM** and **Radio Paradise** publish this; for anything else the answer is
`now: null` and the bar shows the station itself rather than inventing a track.
The station is rebuilt from `src` + `id` rather than accepted as an object, and the id is
checked against a plain-id pattern, because the id is used to build a URL this process
fetches: without that, a session would be enough to make the api a request proxy for anything
on the owner's network. The two known sources are the only ones accepted.
The client polls this every 45 seconds while something plays — the screen's own timer, so
when iOS suspends it on a locked screen the caption freezes and the music does not.
parameters:
- name: src
in: query
required: true
schema: { type: string, enum: [soma, paradise] }
description: Which service the station belongs to.
- name: id
in: query
required: true
schema: { type: string, pattern: '^[A-Za-z0-9_-]{1,40}$' }
description: The station's id at that service (a SomaFM channel like `beatblender`, or a Radio Paradise mix like `main`).
responses:
'200':
description: The current track, or `null` when the station does not publish one.
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
now:
type: object
nullable: true
properties:
artist: { type: string, nullable: true }
title: { type: string }
cover: { type: string, nullable: true, description: HTTPS album art, when the station sends one. }
'400':
description: No such station — an unknown `src`, or an `id` that is not a plain id.
'401': { $ref: '#/components/responses/Unauthorized' }
/api/music/lookup:
post:
tags: [music]
operationId: musicLookup
summary: Read what a public Apple Music page says about itself
description: |
Apple has no API for somebody else's public playlists, so a playlist saved in KuentaGYM is a
*link* — and this is how the card gets its title, artwork, track count and curator without
the client fetching Apple itself (which CORS would refuse anyway).
The URL must be an Apple Music link on an allowlisted host (`hostAllowed`), and so must the
URL the request ends up at: a redirect is otherwise a way around the allowlist. This
container sits on the owner's own network, which is the whole reason for the check.
An unreachable page or a page that left the allowlist is **not** an error status — the answer
is `200` with `meta: null` and an `error` naming which of the two happened, because the app's
job then is to save the link anyway with the name the person typed.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [url]
properties:
url: { type: string, description: A public `https://music.apple.com/...` link. }
responses:
'200':
description: 'What the page said, or `meta: null` with a reason.'
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
meta:
type: object
nullable: true
properties:
title: { type: string, nullable: true }
artwork: { type: string, nullable: true }
tracks: { type: integer, nullable: true }
curator: { type: string, nullable: true }
error:
type: string
description: Present only when `meta` is null — `unreachable`, `off-host` or `http-<status>`.
'400':
description: Not an Apple Music link, or a plain-`http`/off-host URL. Refused before any request is made.
'401': { $ref: '#/components/responses/Unauthorized' }
/api/vitals/ingest:
post:
tags: [health]
@@ -1627,6 +1784,42 @@ components:
properties:
ok: { type: boolean, const: true }
RadioStation:
type: object
description: >-
One row in the Radio section: everything the screen needs to draw the station *and* to start
playing it, because the `play()` has to happen inside the tap that chose it.
required: [src, id, name, url]
properties:
src:
type: string
enum: [soma, paradise, rb]
description: >-
Where it came from — `soma` (SomaFM, commercial-free), `paradise` (Radio Paradise, four
hand-mixed channels) or `rb` (the public radio-browser directory). `src` + `id` is what
`GET /api/radio/now` is asked about, and only the first two answer.
id: { type: string, description: The station's id at that source. }
name: { type: string }
genre: { type: string, nullable: true, description: Free-form tags or the channel's own genre. }
detail:
type: string
nullable: true
description: The second line — country, codec, bitrate for the directory, or "no advertising" for the curated ones.
image: { type: string, nullable: true, description: HTTPS logo, when the source publishes one. }
url:
type: string
description: >-
The stream, already resolved to an HTTPS URL a browser plays natively. For SomaFM this
comes from the channel's own `.pls` rather than a guessed bitrate URL.
example:
src: soma
id: beatblender
name: Beat Blender
genre: Electronic
detail: A late night blend
image: null
url: https://ice2.somafm.com/beatblender-128-mp3
SessionUser:
type: object
description: The caller's identity, as returned by /api/me and the sign-in routes.
+325
View File
@@ -0,0 +1,325 @@
/* radio.js — the radio stations the app can play.
*
* Radio, not files, and that is the whole point: a public stream is made to be listened to — it is
* the radio in a car, not a download — so nothing here copies anything, and the audio never passes
* through this server. The browser gets a stream URL and plays it straight from the station, which
* is why a music library costs this instance no disk and no bandwidth.
*
* Three sources, each picked for a reason:
*
* SomaFM listener-supported since 2000, no advertising at all, and a channel list
* published as JSON for exactly this kind of use. Their `.pls` gives the direct
* stream, so nothing is guessed from a channel id.
* Radio Paradise listener-supported, no advertising, four mixes, and a public now-playing API
* that even carries the cover of the album.
* radio-browser an open-source directory (AGPL) of ~50,000 stations, no key, no account. It is
* where the genres SomaFM does not carry come from — salsa, reggaetón, latin
* broadcasters — with the honest caveat that those stations are commercial and may
* air advertising. The directory has none; the stations are their own business.
*
* Everything here is a pure function of what is fetched, with `fetch` injected, so the filters —
* HTTPS only, MP3/AAC only, no HLS, no dead entries — are testable without a network.
*/
/* The hosts *this process* is allowed to call, and only these.
*
* A different list from the music lookup's, because it guards a different thing: that one screens
* URLs a signed-in person typed, this one screens the calls this module makes — which are our own
* constants plus the community directory. The stream hosts (ice*.somafm.com, the directory's
* stations, the Paradise mixes) are never fetched here: they are handed to the browser, which
* reaches them directly. That is the point of radio — the audio does not pass through this server. */
export const RADIO_HOSTS = Object.freeze([
'somafm.com', // the channel list, and what is playing
'api.somafm.com', // the .pls that resolves to a stream
'api.radioparadise.com', // what is playing, with the cover
'all.api.radio-browser.info', // the directory (a load-balanced name, so it is the one to use)
'de1.api.radio-browser.info', // the same, pinned, in case the round-robin name is unreachable
'nl1.api.radio-browser.info'
]);
/** HTTPS and on the list. Exported because the rule is worth testing on its own. */
export function allowedHost(url, hosts = RADIO_HOSTS) {
try {
const u = new URL(String(url));
return u.protocol === 'https:' && hosts.includes(u.hostname.toLowerCase());
} catch { return false }
}
const UA = 'KuentaGYM (self-hosted)';
const TIMEOUT_MS = 12000;
const CACHE_MS = 10 * 60 * 1000;
const MAX_STATIONS = 40;
/* The genres, as the chips the screen draws.
*
* Each one names the SomaFM channels that fit it (curated by hand, because a machine cannot know
* that "Seven Inch Soul" is the R&B one) and the radio-browser tags that fill in the rest. A genre
* with neither is a chip that shows nothing, so there are none. */
export const GENRES = Object.freeze([
{ key: 'workout', label: 'Workout / Rave', soma: ['beatblender', 'thetrip', 'cliqhop', 'dubstep', 'defcon'], tags: ['rave', 'dance', 'techno'], paradise: ['main'] },
{ key: 'techno', label: 'Techno / House', soma: ['beatblender', 'thetrip', 'lush'], tags: ['techno', 'house', 'deep house'], paradise: [] },
{ key: 'rnb', label: 'R&B / Soul', soma: ['7soul', 'fluid'], tags: ['r&b', 'soul', 'funk'], paradise: ['mellow'] },
{ key: 'latin', label: 'Latina / Salsa', soma: ['bossa', 'reggae'], tags: ['salsa', 'latin', 'reggaeton', 'bachata'], paradise: ['global'] },
{ key: 'hiphop', label: 'Hip-Hop', soma: ['fluid', 'cliqhop'], tags: ['hip hop', 'rap'], paradise: [] },
{ key: 'reggae', label: 'Reggae', soma: ['reggae', 'suburbsofgoa'], tags: ['reggae', 'dancehall'], paradise: ['global'] },
{ key: 'chill', label: 'Chill / Focus', soma: ['groovesalad', 'dronezone', 'synphaera', 'deepspaceone'], tags: ['chillout', 'ambient', 'lounge'], paradise: ['mellow'] },
{ key: 'jazz', label: 'Jazz / Lounge', soma: ['sonicuniverse', 'illstreet', 'secretagent'], tags: ['jazz', 'lounge', 'swing'], paradise: ['mellow'] },
{ key: 'rock', label: 'Rock / Indie', soma: ['indiepop', 'poptron', 'metal', 'seventies', 'u80s'], tags: ['rock', 'indie', 'alternative'], paradise: ['main', 'rock'] },
{ key: 'electronic', label: 'Electrónica', soma: ['digitalis', 'spacestation', 'vaporwaves', 'u80s'], tags: ['electronic', 'synthwave', 'electro'], paradise: ['main'] }
]);
export const genreOf = key => GENRES.find(g => g.key === key) || null;
/** The four Radio Paradise mixes. Fixed URLs: the mixes are the station, and they do not move. */
export const PARADISE = Object.freeze([
{ id: 'main', name: 'Radio Paradise', detail: 'eclectic rock, no advertising', url: 'https://stream.radioparadise.com/mp3-192' },
{ id: 'mellow', name: 'Radio Paradise · Mellow', detail: 'calm mix', url: 'https://stream.radioparadise.com/mellow-192' },
{ id: 'rock', name: 'Radio Paradise · Rock', detail: 'harder mix', url: 'https://stream.radioparadise.com/rock-192' },
{ id: 'global', name: 'Radio Paradise · Global', detail: 'world mix', url: 'https://stream.radioparadise.com/global-192' }
]);
/* ---------- a small polite cache ----------
*
* radio-browser is a community service run on donations and SomaFM is listener-supported: neither
* should see a request per tap. Everything fetched here is cached for ten minutes, which is also
* what makes switching genres on the screen feel instant the second time. */
const cache = new Map();
function cached(key, ttl, produce) {
const hit = cache.get(key);
if (hit && Date.now() - hit.at < ttl) return hit.value;
return produce().then(value => {
if (value != null) cache.set(key, { at: Date.now(), value });
return value;
});
}
export const clearRadioCache = () => cache.clear();
/** One GET, allowlisted, with a timeout, returning text or null. Never throws at the caller. */
export async function get(url, { fetchImpl = fetch, timeoutMs = TIMEOUT_MS, headers = {} } = {}) {
// The gate: every outgoing call in this module goes through here, so the allowlist is one rule in
// one place rather than a check each caller has to remember.
if (!allowedHost(url)) return null;
try {
const r = await fetchImpl(url, {
headers: { 'User-Agent': UA, ...headers },
signal: AbortSignal.timeout(timeoutMs)
});
if (!r.ok) return null;
return await r.text();
} catch { return null; }
}
/* ---------- SomaFM ---------- */
/**
* The stream inside a `.pls`. SomaFM publishes one playlist per channel and format, with several
* mirrors of the same stream; the first entry is the canonical one. Reading it is what makes this
* work for every channel without guessing a bitrate into a URL.
*/
export function parsePls(text) {
if (typeof text !== 'string') return null;
const line = text.split(/\r?\n/).find(l => /^\s*file1\s*=/i.test(l));
if (!line) return null;
const url = line.slice(line.indexOf('=') + 1).trim();
return /^https:\/\//i.test(url) ? url : null;
}
/** The playlist URL for a channel: the best quality it publishes, preferring MP3 (it plays everywhere). */
export function pickPlaylist(channel) {
const lists = Array.isArray(channel?.playlists) ? channel.playlists : [];
const best = lists.filter(p => p && /^https:\/\//i.test(p.url || ''));
const order = best.find(p => p.format === 'mp3' && p.quality === 'highest')
|| best.find(p => p.format === 'mp3')
|| best.find(p => p.format === 'aac' && p.quality === 'highest')
|| best.find(p => p.format === 'aac')
|| best[0];
return order ? order.url : null;
}
/** One SomaFM channel, as a station the screen can list. */
export function somaStation(channel) {
const id = String(channel?.id || '').trim();
const name = String(channel?.title || '').trim();
const pls = pickPlaylist(channel);
if (!id || !name || !pls) return null;
return {
src: 'soma',
id,
name,
genre: String(channel.genre || '').trim(),
detail: String(channel.description || '').replace(/\s+/g, ' ').trim().slice(0, 160),
image: /^https:\/\//i.test(channel.xlimage || channel.largeimage || '') ? (channel.xlimage || channel.largeimage) : null,
listeners: Number(channel.listeners) || null,
// The `.pls` is resolved into a real stream URL when somebody presses play, not here: forty
// channels would be forty requests to list a screen.
pls
};
}
/** The channel list, cached. */
export async function somaChannels({ fetchImpl = fetch } = {}) {
return cached('soma:channels', CACHE_MS, async () => {
const text = await get('https://somafm.com/channels.json', { fetchImpl });
if (!text) return [];
try {
const data = JSON.parse(text);
return (data.channels || []).map(somaStation).filter(Boolean);
} catch { return []; }
});
}
/* ---------- radio-browser ---------- */
/* The codecs a browser plays natively, without a library: HLS (`.m3u8`) needs one on Chrome and
Android, and this project does not add a dependency for a station. */
const PLAYABLE = /^(mp3|aac|aac\+|aacp|ogg|opus)$/i;
/**
* Station rows from the directory, filtered to what can actually be played and heard.
*
* HTTPS is not a preference: the app is served over HTTPS and a browser refuses to play an HTTP
* stream from an HTTPS page, so an `http://` row is a station that silently does nothing. The same
* argument, one step earlier, for a dead or broken entry.
*/
export function rbStations(rows) {
if (!Array.isArray(rows)) return [];
const out = [];
const seen = new Set();
for (const r of rows) {
const url = String(r?.url_resolved || r?.url || '').trim();
if (!/^https:\/\//i.test(url)) continue;
if (/\.m3u8(\?|$)/i.test(url)) continue; // HLS: not without a library
const codec = String(r?.codec || '').trim();
if (codec && !PLAYABLE.test(codec)) continue;
const name = String(r?.name || '').replace(/\s+/g, ' ').trim();
if (!name || seen.has(url)) continue;
seen.add(url);
out.push({
src: 'rb',
id: String(r.stationuuid || url).slice(0, 60),
name: name.slice(0, 80),
genre: String(r.tags || '').split(',').slice(0, 3).join(', ').slice(0, 60),
detail: [r.country, codec, r.bitrate ? r.bitrate + ' kbps' : null].filter(Boolean).join(' · '),
image: /^https:\/\//i.test(r.favicon || '') ? r.favicon : null,
url
});
}
return out;
}
/** The directory's best stations for one tag, cached per tag. */
export async function rbByTag(tag, { fetchImpl = fetch } = {}) {
const key = 'rb:' + tag;
return cached(key, CACHE_MS, async () => {
const q = new URLSearchParams({
limit: '20', hidebroken: 'true', order: 'clickcount', reverse: 'true'
});
const text = await get(`https://all.api.radio-browser.info/json/stations/bytagexact/${encodeURIComponent(tag)}?${q}`, { fetchImpl });
if (!text) return [];
try { return rbStations(JSON.parse(text)); } catch { return []; }
});
}
/* ---------- the list the screen shows ---------- */
/**
* Every station for a genre: the curated SomaFM channels first (no advertising, and the ones worth
* pressing), then Radio Paradise on the genres it fits, then the directory for everything else.
*/
export async function stationsFor(genreKey, { fetchImpl = fetch } = {}) {
const genre = genreOf(genreKey) || GENRES[0];
const [channels, ...tagged] = await Promise.all([
somaChannels({ fetchImpl }),
...genre.tags.map(tag => rbByTag(tag, { fetchImpl }))
]);
const bySoma = new Map(channels.map(c => [c.id, c]));
/* The curated channels get their stream resolved *here*, in the list, for one reason: on iOS
`play()` has to be called inside the tap's own task, and waiting for a round trip first is what
makes a press do nothing. Five channels per genre, cached for ten minutes, is a cheap price for
a play button that always plays. A channel whose stream cannot be resolved is left out rather
than listed as a row that does nothing. */
const picks = (await Promise.all(
genre.soma.map(id => bySoma.get(id)).filter(Boolean).map(async c => ({ ...c, url: await streamFor(c, { fetchImpl }) }))
)).filter(c => c.url);
// The mixes of Radio Paradise that fit this genre, named per genre rather than offered everywhere:
// "Rock" under Chill is a suggestion nobody asked for.
const wanted = new Set(genre.paradise || []);
const paradise = PARADISE.filter(p => wanted.has(p.id))
.map(p => ({ src: 'paradise', id: p.id, name: p.name, genre: p.detail, detail: 'no advertising', image: null, url: p.url }));
const seen = new Set(picks.map(p => p.id));
const rest = [];
for (const list of tagged) {
for (const s of list) {
if (seen.has(s.id)) continue;
seen.add(s.id);
rest.push(s);
}
}
return { genre, stations: [...picks, ...paradise, ...rest].slice(0, MAX_STATIONS) };
}
/** The genres the screen offers, with their labels. */
export const genreList = () => GENRES.map(g => ({ key: g.key, label: g.label }));
/* ---------- resolving a station into a stream ---------- */
/**
* The URL to hand an `<audio>` element.
*
* SomaFM's `.pls` is fetched (and cached) at this point, because that is when it is needed and not
* when the list is drawn. Everything else already carries its stream.
*/
export async function streamFor(station, { fetchImpl = fetch } = {}) {
if (!station) return null;
if (station.src === 'soma') {
if (!station.pls || !allowedHost(station.pls)) return null;
return cached('pls:' + station.pls, CACHE_MS, async () => parsePls(await get(station.pls, { fetchImpl })));
}
const url = String(station.url || '');
return /^https:\/\//i.test(url) ? url : null;
}
/* ---------- what is playing ---------- */
/**
* The current track, where the station publishes one.
*
* Only SomaFM and Radio Paradise do, and the difference is the whole reason they are first in each
* genre: a station that says what it is playing is a station you can trust with your ears. Anything
* else — the directory's thousands — gets no line, rather than an invented one.
*/
export function nowFrom(src, data) {
if (src === 'soma') {
const song = (data && Array.isArray(data.songs) && data.songs[0]) || null;
if (!song || !song.title) return null;
return {
artist: String(song.artist || '').trim().slice(0, 80) || null,
title: String(song.title).trim().slice(0, 120),
cover: /^https:\/\//i.test(song.albumArt || '') ? song.albumArt : null
};
}
if (src === 'paradise') {
if (!data || !data.title) return null;
return {
artist: String(data.artist || '').trim().slice(0, 80) || null,
title: String(data.title).trim().slice(0, 120),
cover: /^https:\/\//i.test(data.cover || '') ? data.cover : null
};
}
return null;
}
/** Fetches what is playing, for the two sources that publish it. */
export async function nowPlaying(station, { fetchImpl = fetch } = {}) {
if (!station) return null;
if (station.src === 'soma') {
const text = await get(`https://somafm.com/songs/${encodeURIComponent(station.id)}.json`, { fetchImpl });
if (!text) return null;
try { return nowFrom('soma', JSON.parse(text)); } catch { return null; }
}
if (station.src === 'paradise') {
const chan = PARADISE.findIndex(p => p.id === station.id);
const text = await get('https://api.radioparadise.com/api/now_playing?chan=' + (chan < 0 ? 0 : chan), { fetchImpl });
if (!text) return null;
try { return nowFrom('paradise', JSON.parse(text)); } catch { return null; }
}
return null;
}
+40
View File
@@ -21,6 +21,7 @@ import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
import { verifyError } from './verify-error.js';
import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, RETENTION_DAYS } from './vitals.js';
import { hostAllowed, readCapped, parseMusicPage } from './music.js';
import { genreList, stationsFor, nowPlaying } from './radio.js';
import { jevConfig, jevEndpoint, stateHash, insightFreshness, budgetFor } from './jev.js';
import {
readInsight, clearInsight, runInsight, stateFor, summarizeState, endpointHost
@@ -133,6 +134,21 @@ function writeVitals(uid, doc) { atomicWrite(vitalsFile(uid), JSON.stringify(doc
/** What a sync is answered with: how much is in the profile now, not just what just arrived. */
const wantRaw = req => new URL(req.url, 'http://x').searchParams.get('raw') === '1';
/* One station, rebuilt from the query string rather than trusted as an object.
*
* The client only ever sends back what it was given, but "only ever" is not a security property:
* what comes back is a source and an id, and the id is used to build a URL this process fetches.
* So the shape is checked here — a known source, a plain id — and the URL for a SomaFM channel is
* rebuilt from the allowlisted host rather than taken from the request. */
function stationFromQuery(q) {
const src = String(q.get('src') || '');
const id = String(q.get('id') || '');
if (!/^[a-z0-9_-]{1,40}$/i.test(id)) return null;
if (src === 'soma') return { src, id };
if (src === 'paradise') return { src, id };
return null;
}
const storedCounts = doc => ({
metrics: doc ? Object.keys(doc.metrics || {}).length : 0,
days: doc ? Object.values(doc.metrics || {}).reduce((n, m) => n + Object.keys(m.days || {}).length, 0) : 0,
@@ -1261,6 +1277,30 @@ const routes = {
json(res, 200, { ok: true, meta: parseMusicPage(html) });
},
/* ---------- radio ----------
*
* Two routes, both session-gated, and neither proxies audio: the list — every station with the
* stream URL already resolved, so a tap can call `play()` inside the gesture iOS demands — and
* what is playing on the stations that publish it. The audio itself goes from the phone straight to the
* station — this server's part is the list, and a session requirement is what stops it becoming
* an open gateway someone else's page can borrow. */
'GET /api/radio': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const key = new URL(req.url, 'http://x').searchParams.get('genre') || '';
const { genre, stations } = await stationsFor(key);
json(res, 200, { ok: true, genres: genreList(), genre: genre.key, label: genre.label, stations });
},
'GET /api/radio/now': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const q = new URL(req.url, 'http://x').searchParams;
const station = stationFromQuery(q);
if (!station) return json(res, 400, { error: 'no such station' });
json(res, 200, { ok: true, now: await nowPlaying(station) });
},
'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }),
'POST /api/push/subscribe': async (req, res) => {
+222
View File
@@ -0,0 +1,222 @@
/* The radio sources, tested without a network: everything here is a filter or a parse, and the
filters are the point. A station that cannot be played is worse than no station — a row that does
nothing when tapped, on a screen whose whole job is to make sound.
The three rules that are load-bearing: HTTPS (an http stream is blocked by the browser on an
https page, silently), no HLS (Chrome and Android need a library, and this project does not add
one for a station), and nothing fetched from a host that is not on our own list. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
GENRES, genreList, genreOf, PARADISE, parsePls, pickPlaylist, somaStation, rbStations,
nowFrom, allowedHost, get, streamFor, stationsFor, nowPlaying, RADIO_HOSTS, clearRadioCache
} from '../radio.js';
const pls = 'https://api.somafm.com/beatblender.pls';
const channel = (over = {}) => ({
id: 'beatblender', title: 'Beat Blender', genre: 'electronic',
description: 'A late night blend of deep-house and downtempo chill.',
playlists: [
{ url: pls, format: 'mp3', quality: 'highest' },
{ url: 'https://api.somafm.com/beatblender130.pls', format: 'aac', quality: 'highest' }
],
...over
});
test('the genres the screen offers are the ones a person asked for', () => {
const keys = genreList().map(g => g.key);
for (const want of ['workout', 'techno', 'rnb', 'latin', 'hiphop', 'reggae', 'chill', 'jazz', 'rock', 'electronic']) {
assert.ok(keys.includes(want), want + ' is offered');
}
// Every genre names at least one SomaFM channel or one tag: a chip that shows nothing is a chip
// that should not be there.
for (const g of GENRES) assert.ok(g.soma.length + g.tags.length > 0, g.key + ' has a source');
assert.equal(genreOf('nope'), null);
assert.equal(genreOf('rnb').label, 'R&B / Soul');
});
test('a .pls gives the stream, and anything else gives nothing', () => {
const text = [
'[playlist]', 'numberofentries=2',
'File1=https://ice2.somafm.com/beatblender-128-mp3',
'Title1=SomaFM: Beat Blender', 'Length1=-1',
'File2=https://ice6.somafm.com/beatblender-128-mp3',
'Version=2'
].join('\n');
assert.equal(parsePls(text), 'https://ice2.somafm.com/beatblender-128-mp3', 'the first mirror');
// An http stream would be blocked by the browser on an https page, so it is not a stream here.
assert.equal(parsePls('[playlist]\nFile1=http://ice2.somafm.com/x'), null);
assert.equal(parsePls('<html>nope</html>'), null);
assert.equal(parsePls(null), null);
assert.equal(parsePls(''), null);
});
test('the playlist chosen is the best one that plays everywhere', () => {
assert.equal(pickPlaylist(channel()), pls, 'mp3 highest wins over aac highest');
assert.equal(pickPlaylist(channel({ playlists: [
{ url: 'https://api.somafm.com/x256.pls', format: 'mp3', quality: 'highest' },
{ url: 'https://api.somafm.com/x.pls', format: 'mp3', quality: 'high' }
] })), 'https://api.somafm.com/x256.pls');
assert.equal(pickPlaylist(channel({ playlists: [{ url: 'https://api.somafm.com/x130.pls', format: 'aac', quality: 'highest' }] })),
'https://api.somafm.com/x130.pls', 'aac is the fallback, not nothing');
assert.equal(pickPlaylist(channel({ playlists: [{ url: 'http://api.somafm.com/x.pls', format: 'mp3' }] })), null);
assert.equal(pickPlaylist(channel({ playlists: [] })), null);
});
test('a SomaFM channel becomes a station, and a broken one does not', () => {
const s = somaStation(channel());
assert.equal(s.src, 'soma');
assert.equal(s.id, 'beatblender');
assert.equal(s.pls, pls);
assert.equal(s.detail, 'A late night blend of deep-house and downtempo chill.');
assert.equal(somaStation(channel({ id: '' })), null);
assert.equal(somaStation(channel({ title: ' ' })), null);
assert.equal(somaStation(channel({ playlists: [] })), null);
assert.equal(somaStation(null), null);
});
test('the directory is filtered down to what can be played', () => {
const rows = [
{ stationuuid: 'a', name: 'Techno One', url_resolved: 'https://x.example/stream', codec: 'MP3', bitrate: 192, country: 'Germany', tags: 'techno,dance' },
{ stationuuid: 'b', name: 'Plain HTTP', url_resolved: 'http://x.example/stream', codec: 'MP3' },
{ stationuuid: 'c', name: 'HLS only', url_resolved: 'https://x.example/live.m3u8', codec: 'AAC' },
{ stationuuid: 'd', name: 'Unknown codec', url_resolved: 'https://x.example/wm', codec: 'WMAL' },
{ stationuuid: 'e', name: 'Wild', url_resolved: 'https://x.example/wm2' },
{ stationuuid: 'f', name: 'Techno One', url_resolved: 'https://x.example/stream', codec: 'MP3' },
{ stationuuid: 'g', name: ' ', url_resolved: 'https://x.example/blank', codec: 'MP3' },
{ stationuuid: 'h', name: 'AAC+ Latin', url_resolved: 'https://y.example/aac', codec: 'AAC+', bitrate: 64, country: 'Colombia' }
];
const out = rbStations(rows);
// "Wild" has no codec at all, and that is kept on purpose: a blank codec means the directory did
// not say, which is common, rather than that the station is unplayable. The ones it *does* name
// and that no browser plays (WMAL), and the HLS ones, are the ones dropped.
assert.deepEqual(out.map(s => s.name), ['Techno One', 'Wild', 'AAC+ Latin'], 'only what is known to be unplayable is dropped');
assert.equal(out[0].detail, 'Germany · MP3 · 192 kbps');
assert.equal(out[0].genre, 'techno, dance');
assert.equal(out[2].detail, 'Colombia · AAC+ · 64 kbps');
assert.equal(rbStations('nope').length, 0);
assert.equal(rbStations([{ name: 'no url' }]).length, 0);
});
test('what is playing is read from the two stations that publish it, and invented for nobody', () => {
assert.deepEqual(nowFrom('soma', { songs: [{ title: 'Cuban Nights', artist: 'Miguel Migs', albumArt: 'https://cdn.example/a.jpg' }] }),
{ artist: 'Miguel Migs', title: 'Cuban Nights', cover: 'https://cdn.example/a.jpg' });
assert.deepEqual(nowFrom('paradise', { artist: 'Yes', title: 'I have seen all good people', cover: 'https://img.example/c.jpg' }),
{ artist: 'Yes', title: 'I have seen all good people', cover: 'https://img.example/c.jpg' });
// No song playing, no cover, or a source that publishes nothing: null, never a placeholder.
assert.equal(nowFrom('soma', { songs: [] }), null);
assert.equal(nowFrom('soma', null), null);
assert.equal(nowFrom('rb', { title: 'x' }), null);
assert.equal(nowFrom('paradise', {}), null);
const noArt = nowFrom('soma', { songs: [{ title: 'x' }] });
assert.equal(noArt.artist, null);
assert.equal(noArt.cover, null);
});
test('only our own hosts may be fetched, over https', () => {
assert.equal(allowedHost('https://somafm.com/channels.json'), true);
assert.equal(allowedHost('https://api.somafm.com/beatblender.pls'), true);
assert.equal(allowedHost('https://all.api.radio-browser.info/json/stations'), true);
assert.equal(allowedHost('https://api.radioparadise.com/api/now_playing?chan=0'), true);
// The stream hosts are reached by the browser, never by this process — so they are not here.
assert.equal(allowedHost('https://ice2.somafm.com/beatblender-128-mp3'), false);
assert.equal(allowedHost('http://somafm.com/channels.json'), false, 'https only');
assert.equal(allowedHost('https://evil.example/somafm.com'), false);
assert.equal(allowedHost('https://somafm.com.evil.example/x'), false);
assert.equal(allowedHost('not a url'), false);
assert.equal(allowedHost('https://somafm.com/', ['example.com']), false, 'the list is the argument');
assert.ok(RADIO_HOSTS.every(h => h === h.toLowerCase()));
});
/* The gate itself, and the one test that can see it: `get` is the only place this module makes an
outgoing call, so an off-list URL must die there — not at a caller that might forget. */
test('get refuses an off-list url without calling fetch at all', async () => {
let calls = 0;
const fetchImpl = async () => { calls++; return { ok: true, text: async () => 'x' }; };
for (const url of ['https://evil.example/x', 'http://somafm.com/channels.json', 'https://somafm.com.evil.example/x', 'not a url']) {
assert.equal(await get(url, { fetchImpl }), null, url);
}
assert.equal(calls, 0, 'nothing left this process');
// ...and an on-list one does go out, so the test above is not passing because get never works.
assert.equal(await get('https://somafm.com/channels.json', { fetchImpl }), 'x');
assert.equal(calls, 1);
});
test('resolving a stream never fetches anything outside the allowlist', async () => {
clearRadioCache();
const calls = [];
const fetchImpl = async (url) => {
calls.push(String(url));
if (String(url).includes('evil')) throw new Error('should not be called');
return { ok: true, text: async () => '[playlist]\nFile1=https://ice2.somafm.com/beatblender-128-mp3\n' };
};
const url = await streamFor({ src: 'soma', id: 'beatblender', pls }, { fetchImpl });
assert.equal(url, 'https://ice2.somafm.com/beatblender-128-mp3');
assert.deepEqual(calls, [pls]);
// Cached: a second press does not ask SomaFM again.
assert.equal(await streamFor({ src: 'soma', id: 'beatblender', pls }, { fetchImpl }), url);
assert.equal(calls.length, 1);
// A directory station carries its own stream: nothing is fetched, and an http one is refused.
assert.equal(await streamFor({ src: 'rb', id: 'x', url: 'https://y.example/aac' }, { fetchImpl }), 'https://y.example/aac');
assert.equal(await streamFor({ src: 'rb', id: 'x', url: 'http://y.example/aac' }, { fetchImpl }), null);
assert.equal(await streamFor(null, { fetchImpl }), null);
// A SomaFM station whose playlist points off the list is refused rather than followed.
assert.equal(await streamFor({ src: 'soma', id: 'x', pls: 'https://evil.example/x.pls' }, { fetchImpl }), null);
assert.equal(calls.length, 1);
});
test('a genre list puts the curated channels first and the directory last', async () => {
clearRadioCache();
const fetchImpl = async (url) => {
const u = String(url);
if (u.includes('channels.json')) {
return { ok: true, text: async () => JSON.stringify({ channels: [
channel(), channel({ id: 'bossa', title: 'Bossa Beyond' }), channel({ id: 'reggae', title: 'Heavyweight Reggae' })
] }) };
}
if (u.includes('api.somafm.com')) {
// The channel's own playlist, which is what turns a channel into something playable.
return { ok: true, text: async () => '[playlist]\nFile1=https://ice2.somafm.com/x-128-mp3\n' };
}
if (u.includes('radio-browser')) {
return { ok: true, text: async () => JSON.stringify([
{ stationuuid: 'z1', name: 'Salsa Dura', url_resolved: 'https://z.example/salsa', codec: 'MP3', country: 'Colombia', tags: 'salsa' },
{ stationuuid: 'z2', name: 'Dead', url_resolved: 'http://z.example/dead', codec: 'MP3' }
]) };
}
return { ok: false, text: async () => '' };
};
// The curated channels come back with their stream already resolved (`fetchImpl` answers the
// `.pls` above), and a channel whose stream cannot be resolved is not listed at all.
const { genre, stations } = await stationsFor('latin', { fetchImpl });
assert.equal(genre.key, 'latin');
const names = stations.map(s => s.name);
// The no-advertising stations first — that is what the order is for.
assert.deepEqual(names.slice(0, 3), ['Bossa Beyond', 'Heavyweight Reggae', 'Radio Paradise · Global']);
assert.ok(names.includes('Salsa Dura'), 'and the directory fills in the genres SomaFM does not carry');
assert.ok(stations.every(s => /^https:\/\//.test(s.url || '')), 'every row can be played when it is tapped');
assert.equal(names.includes('Dead'), false);
// An unknown genre falls back to the first one rather than showing a blank screen.
const fallback = await stationsFor('nope', { fetchImpl });
assert.equal(fallback.genre.key, 'workout');
});
test('what is playing is asked for at the right address, per source', async () => {
const calls = [];
const fetchImpl = async (url) => {
calls.push(String(url));
if (String(url).includes('somafm')) return { ok: true, text: async () => JSON.stringify({ songs: [{ title: 'T', artist: 'A' }] }) };
return { ok: true, text: async () => JSON.stringify({ title: 'Paradise Song', artist: 'PR' }) };
};
const soma = await nowPlaying({ src: 'soma', id: 'beatblender' }, { fetchImpl });
assert.equal(soma.title, 'T');
assert.match(calls[0], /somafm\.com\/songs\/beatblender\.json/);
const para = await nowPlaying({ src: 'paradise', id: 'rock' }, { fetchImpl });
assert.equal(para.artist, 'PR');
assert.match(calls[1], /chan=2/, 'the third mix is chan=2');
// A directory station publishes nothing, so nothing is asked and nothing is shown.
assert.equal(await nowPlaying({ src: 'rb', id: 'x', url: 'https://y.example/aac' }, { fetchImpl }), null);
assert.equal(calls.length, 2);
assert.equal(PARADISE.length, 4);
});
+82
View File
@@ -0,0 +1,82 @@
/* 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/);
}
});