Podcasts: en español solamente, y se acuerdan de dónde ibas
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 **Podcasts**: programas por categoría —Salud y fitness,
Deporte, Comedia, Noticias, Historia, Crímenes reales, Ciencia, Tecnología,
Sociedad y cultura, Negocios, Ficción, Educación, Música, Ocio— que suenan mientras
entrenás y siguen donde los dejaste. Sin dependencias nuevas y sin clave de API: el
directorio de Apple es público.

**En español se comprueba, no se supone.** La tienda dice dónde se *vende* un
podcast, no en qué idioma está —en el ranking español de comedia hay uno en catalán
y en el argentino uno en inglés—, así que se lee el `<language>` del feed de cada
programa (los primeros 64 KB, con una petición `Range`: el idioma está en las
primeras líneas) y se descarta lo que no sea español. Un feed sin etiqueta se queda:
feeds genuinamente españoles la omiten, y tirarlos por una omisión sería sacar
podcasts buenos de la lista. La respuesta cuenta cuántos quedaron afuera y por qué
(`skipped`), así que una lista corta nunca es un misterio, y abrir un programa en
otro idioma se contesta con `spanish:false` en vez de con una lista vacía.

Es la otra mitad de la radio y es lo contrario en todo lo que le importa al
reproductor: un podcast es un **archivo** —tiene principio, final y un minuto en el
que ibas—. Por eso hay un módulo de reglas puras (`lib/podcast-view.js`: dónde
retomar, qué cuenta como escuchado, cuál sigue, cuántas posiciones se guardan) y
por eso `lib/radio-player.js` pasa a ser `lib/player.js`: **un solo elemento de
audio** para las dos cosas, que es lo que impide que una emisora y un episodio suenen
a la vez. La barra crece línea de progreso, −15 s, +30 s, siguiente episodio y reloj;
la posición se guarda por perfil (con tope de 200, lo más nuevo primero) en pausa, al
parar, al terminar y cuando la app se va al fondo, porque con la pantalla bloqueada
iOS suspende los temporizadores y un guardado sólo desde el tick perdería lo
escuchado con el teléfono guardado. Media Session muestra episodio, programa y
progreso en la pantalla bloqueada.

Nada se descarga y nada pasa por el servidor: el episodio llega como la URL del
`enclosure` y el audio va de quien lo publica al teléfono. Acá no hay lista blanca
posible —un feed vive en cualquier host—, así que la puerta es **https, host real y
nunca una dirección privada**, comprobada en la URL y en dónde terminó el pedido, con
el cuerpo leído a tope y la conexión cortada al llegar: este contenedor vive adentro
de una casa.

Verificado con datos reales: 20 programas en español por categoría (idiomas es, es-ES,
es-mx), un feed de 40 episodios parseado, un feed en inglés contestado como
`spanish:false` y la dirección de metadatos rechazada con 400 sin hacer el pedido.

Fuera de los podcasts: la página de la API ocultaba `health` y `music` enteras —el
generador sólo dibuja las secciones de su tabla de etiquetas—, así que ahora están,
con radio y podcasts incluidas.
This commit is contained in:
dsantillan committed 2026-09-23 21:11:20 -04:00
1 parent a3e13df279
commit 22654c61fc
31 files changed
+3687 -360

No files matched your search

+3 -2
View File
@@ -55,8 +55,9 @@ 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. 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 ./
# the first health build would have done. radio.js is the station directory behind the player, and
# podcasts.js the Spanish-language one behind the episodes.
COPY server.js push-messages.js verify-error.js vitals.js music.js radio.js podcasts.js jev.js insights.js ./
COPY coach ./coach
ENV NODE_ENV=production
ENV PORT=3000
+185 -4
View File
@@ -90,9 +90,10 @@ tags:
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.
Música — reading a public Apple Music page for a saved playlist's card, the live radio station
directory, and the Spanish-language podcast directory. Audio is never proxied by this server:
a station arrives as a resolved stream URL, an episode as the publisher's own file URL, and
the phone talks to the station or the publisher directly.
- name: admin
description: Admin dashboard — requires an admin session (`ADMIN_UIDS` or `admin:true`)
@@ -161,7 +162,7 @@ paths:
server", never as "supports everything".
items:
type: string
enum: [vitals, vitals.hours, vitals.receipt, music.lookup, radio, insights]
enum: [vitals, vitals.hours, vitals.receipt, music.lookup, radio, podcasts, insights]
coach:
type: object
description: Present only when the AI Coach is configured on this instance.
@@ -1040,6 +1041,136 @@ paths:
description: No such station — an unknown `src`, or an `id` that is not a plain id.
'401': { $ref: '#/components/responses/Unauthorized' }
/api/podcasts:
get:
tags: [music]
operationId: podcastsGet
summary: Spanish-language podcast shows for a category
description: |
What the **Podcasts** section of the Música screen draws. Apple's public podcast directory
(no API key, no account) supplies the storefront charts per category and the feed URL behind
each show; the episodes themselves come from the publisher's own RSS, fetched by
`GET /api/podcasts/show`.
**Spanish only, and checked rather than assumed.** A storefront says a podcast is sold in
Spain or Mexico, which is not the same as being in Spanish — the Spanish comedy chart carries
a Catalan show, the Argentine one an English show. So each show's feed is read (its first
64 KB, with a `Range` request) and its `<language>` decides: `es`, `es-ES`, `es-419` and
`spa` are kept, `ca` and `en` are dropped, and a feed that declares no language at all is
kept too — genuinely Spanish feeds omit the tag, and dropping them over an omission would
quietly remove good podcasts. `skipped` reports how many went each way, so a short list is
never a mystery.
The audio never passes through this server: an episode is a file URL in the publisher's
enclosure, handed to the phone. What this route costs is server-side requests to Apple and to
each publisher's feed, so the answer is cached for thirty minutes.
A session is required. Not to protect the shows — they are public — but because this
container sits on the owner's own network and fetches on behalf of whoever asks.
parameters:
- name: category
in: query
schema:
type: string
enum: [fitness, sports, comedy, news, history, truecrime, science, tech, society, business, fiction, education, music, leisure]
description: Category key. Missing or unrecognised falls back to `fitness`.
responses:
'200':
description: The categories for the chips, and the Spanish shows in the one asked for.
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
categories:
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, description: Spanish label, like the rest of the show list. }
category: { type: string, description: The category actually answered with. }
label: { type: string }
shows:
type: array
description: At most 20, Spanish-language only.
items: { $ref: '#/components/schemas/PodcastShow' }
skipped:
type: object
description: Why a candidate did not make the list — each reason counted.
properties:
duplicate: { type: integer, description: Listed by both storefronts. }
language: { type: integer, description: Declared a language that is not Spanish. }
unreadable: { type: integer, description: The feed did not answer. }
failed: { type: integer, description: An unexpected error while checking (should be 0). }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/podcasts/show:
get:
tags: [music]
operationId: podcastsShow
summary: One show's episodes, read out of the publisher's feed
description: |
The episode list behind a show, newest first, from the publisher's own RSS — the same feed
every podcast app in the world reads. Each episode carries the `https://` URL of its audio
file (`enclosure`), which is what the phone plays; nothing is downloaded by this server and
no audio is proxied.
Two things are refused or reported rather than faked:
- **A URL this process will not fetch** is a `400`. Podcast feeds live on every host in the
world, so there is no allowlist to hide behind: the rule is https, no credentials, a real
hostname, and never a private address (no loopback, no `10.`/`192.168.`/`172.16-31.`, no
link-local, no IPv6 literals, no `.local`). A redirect is checked the same way, because a
redirect is otherwise the way around it.
- **A feed that is not Spanish** is answered with `200` and `spanish: false` (with
`episodes: []`), not with a hidden empty list: the show exists, it is simply not in
Spanish, and saying which of the two it is is the whole point of the field.
Episodes without a public audio enclosure are left out: a trailer, a subscriber-only episode
or a video is a row that plays silence or nothing. Feeds are up to a few megabytes, so the
body is read with a cap and the connection is dropped at it; a feed cut off mid-item simply
loses that last, unparseable item.
parameters:
- name: feed
in: query
required: true
schema: { type: string }
description: The show's feed URL, exactly as `GET /api/podcasts` returned it.
- name: title
in: query
schema: { type: string, maxLength: 120 }
description: The directory's name for the show, used only when the feed declares none.
- name: image
in: query
schema: { type: string, maxLength: 300 }
description: The directory's artwork, used only when the feed declares none.
responses:
'200':
description: 'The show and its episodes — or `show: null` when the feed did not answer.'
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
feed: { type: string }
spanish: { type: boolean }
show:
allOf: [{ $ref: '#/components/schemas/PodcastShow' }]
nullable: true
description: Null when the feed could not be read at all.
episodes:
type: array
description: At most 40, newest first. Empty when the show is not in Spanish.
items: { $ref: '#/components/schemas/PodcastEpisode' }
error: { type: string, nullable: true, description: '`unreadable` when `show` is null.' }
'400':
description: The feed URL is not one this server will fetch (not https, not a public host).
'401': { $ref: '#/components/responses/Unauthorized' }
/api/music/lookup:
post:
tags: [music]
@@ -1808,6 +1939,56 @@ components:
properties:
ok: { type: boolean, const: true }
PodcastShow:
type: object
description: >-
One show in the Podcasts section. `feed` is the only field the episodes can be fetched with,
and it is what the show is saved by in a profile.
required: [feed, name]
properties:
feed: { type: string, description: The publisher's RSS URL, https and public. }
id: { type: string, description: The directory's own id for the show. }
name: { type: string }
author: { type: string }
image: { type: string, nullable: true, description: HTTPS artwork. }
genre: { type: string, nullable: true }
country: { type: string, description: 'The storefront it was found in: `es` or `mx`.' }
lang:
type: string
nullable: true
description: >-
What the feed itself declares — `es`, `es-ES`, `es-mx`… — or null when it declares
nothing, which is a "kept, unconfirmed" and not a "not Spanish".
example:
feed: https://feeds.example.com/nadie-sabe-nada.rss
name: Nadie Sabe Nada
author: Cadena SER
genre: Comedy
country: es
lang: es-ES
PodcastEpisode:
type: object
description: >-
One episode: a file with a length, which is the difference that matters against a radio
station — there is a position to remember and a place to resume from.
required: [id, title, url]
properties:
id: { type: string, description: The feed's guid, or the audio URL when it has none. }
title: { type: string }
url: { type: string, description: The `https://` audio file to play. Never proxied. }
date: { type: string, nullable: true, description: ISO 8601, from `pubDate`. }
duration: { type: integer, nullable: true, description: Seconds, when the feed declares one. }
image: { type: string, nullable: true, description: Episode artwork, else the show's. }
episode: { type: integer, nullable: true, description: '`itunes:episode`, when the feed numbers them.' }
bytes: { type: integer, nullable: true, description: The enclosure's declared size. }
example:
id: 312f2e94-ac78-5c37-8e0e-1f6c9d2a4b71
title: Nadie Sabe Nada | 14x03 | En el corazón del ajo
url: https://audio.example.com/nsn-14x03.mp3
date: '2025-09-19T10:00:00.000Z'
duration: 3135
RadioStation:
type: object
description: >-
+513
View File
@@ -0,0 +1,513 @@
/* podcasts.js — Spanish-language podcasts, browsed by category, played as files.
*
* Radio and podcasts are the two halves of "something to listen to while training", and they are
* opposites in every way that matters to this code:
*
* - Radio is a **stream**: endless, no position, and every station is a channel somebody else is
* programming. Nothing about it is stored.
* - A podcast is a **file**: it has a beginning and an end, it is worth resuming where you left
* it, and skipping back fifteen seconds is the most-used button in every podcast app ever made.
*
* So this module answers a different question — *which file* — and the player has to do more with
* the answer than it does for a station.
*
* ## Where the list comes from, and why there is no API key
*
* Apple's podcast directory, through two public endpoints that need no key and no account: the
* storefront **top charts** (`/<country>/rss/toppodcasts/limit=N/genre=<id>/json`) and
* `lookup?id=…` for what the charts omit — above all the **feed URL**, which is the only field that
* really matters, because the episodes come from the publisher's own RSS and from nowhere else.
*
* One consequence is deliberate: **no audio passes through here.** An episode is an `https://` URL
* in the publisher's enclosure, handed to the phone; the bytes go from the publisher to the phone.
* What this server contributes is the list, the same bargain the radio makes.
*
* ## "Spanish only" is checked, not assumed
*
* A storefront says a podcast is *sold* in Spain or Mexico, which is not the same as being in
* Spanish, and the difference shows: the Spanish comedy chart carries a Catalan show and the
* Argentine one carries an English one. The authoritative answer is in the feed, in `<language>`,
* so every show is checked:
*
* - `feedLanguage()` reads the **first 64 KB** with a `Range` request. `<language>` is channel
* metadata that sits in the first ~1.5 KB of every feed looked at, always before the first
* `<item>`, so a 64 KB slice answers the question and a 5 MB feed does not have to be downloaded
* to ask it.
* - `es` / `es-ES` / `es-419` / `spa` keeps the show; `ca`, `en`, `pt` and the rest are dropped.
* - **A feed with no tag at all keeps its place.** Genuinely Spanish feeds do omit it (La Ruina is
* one), and dropping them over an omission would quietly remove good podcasts; the storefront is
* the fallback signal, and it is not a guess.
*
* ## What may be fetched
*
* Radio has a host allowlist because it only ever talks to three services. Podcasts cannot: feeds
* live on every host in the world. So the rule is the other one, and it is the rule that matters for
* an api container sitting on somebody's home network:
*
* - **https only**, no credentials in the URL, a real hostname, and **never a private address** —
* no loopback, no `10.`/`192.168.`/`172.16-31.`, no link-local, no IPv6 literals, no `.local` or
* `.internal`. A feed URL is attacker-influenced data, and an api that fetches whatever it is
* handed is how a home network gets mapped from the outside.
* - The check is applied to the URL **and again to where the request ended up**, because a
* redirect is otherwise the way around it — the lesson music.js learned with Apple's CDN.
* - Bodies are read with a cap and the connection is dropped when it is reached: podcast feeds are
* routinely several megabytes, and one of them is not allowed to be an out-of-memory bug.
*/
const UA = 'KuentaGYM (self-hosted)';
const TIMEOUT_MS = 12000;
const CACHE_MS = 30 * 60 * 1000;
/** `<language>` lives in the first couple of KB; 64 KB is generous and still one round trip. */
const LANG_HEAD_BYTES = 64 * 1024;
/** A cap, not a target: the largest feeds seen are ~5 MB, and a truncated one still parses. */
const MAX_FEED_BYTES = 6 * 1024 * 1024;
const MAX_URL = 600;
const CHART_LIMIT = 25;
/* How many candidates to language-check per category, and how many at a time.
*
* The check is one request per show (see below), so this pair is the whole cost of a category: a
* cold list of twenty Spanish shows needs roughly twenty-six checks, and with a pool of ten that is
* three rounds of latency rather than twenty-six of them. Ten at once to twenty different
* publishers is also about as far as politeness goes: they are other people's servers, and they are
* paying for the bandwidth of being listed. */
const CHECK_LIMIT = 26;
const POOL = 10;
export const MAX_SHOWS = 20;
export const MAX_EPISODES = 40;
/** Spain and Mexico: between them, most of what is published in Spanish. */
export const STORES = Object.freeze(['es', 'mx']);
/* The categories, as the chips the screen draws.
*
* Apple's own genre ids with Spanish labels, which is the whole trick: an id is stable and the chart
* is per id, so a category is one number rather than a search term whose results drift week to week.
* Ordered so the two a gym screen actually wants come first. */
export const CATEGORIES = Object.freeze([
{ key: 'fitness', label: 'Salud y fitness', genre: 1512 },
{ key: 'sports', label: 'Deporte', genre: 1545 },
{ key: 'comedy', label: 'Comedia', genre: 1303 },
{ key: 'news', label: 'Noticias', genre: 1489 },
{ key: 'history', label: 'Historia', genre: 1487 },
{ key: 'truecrime', label: 'Crímenes reales', genre: 1488 },
{ key: 'science', label: 'Ciencia', genre: 1533 },
{ key: 'tech', label: 'Tecnología', genre: 1318 },
{ key: 'society', label: 'Sociedad y cultura', genre: 1324 },
{ key: 'business', label: 'Negocios', genre: 1321 },
{ key: 'fiction', label: 'Ficción', genre: 1483 },
{ key: 'education', label: 'Educación', genre: 1304 },
{ key: 'music', label: 'Música', genre: 1310 },
{ key: 'leisure', label: 'Ocio', genre: 1502 }
]);
/** The categories the screen offers, with their labels. */
export const categoryList = () => CATEGORIES.map(c => ({ key: c.key, label: c.label }));
/** One category by key, or null. An unknown key falls back to the first one at the route. */
export const categoryOf = key => CATEGORIES.find(c => c.key === String(key || '')) || null;
/* ---------- fetching, with the one rule ---------- */
const IPV4_PRIVATE = [
/^0\./, /^10\./, /^127\./, /^169\.254\./, /^192\.168\./,
/^172\.(1[6-9]|2\d|3[01])\./, /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./
];
/** A hostname this process may talk to: public, named, and not a device in the same house. */
export function publicHost(hostname) {
const h = String(hostname || '').toLowerCase().replace(/\.$/, '');
if (!h || h === 'localhost' || h.endsWith('.localhost')) return false;
if (h.endsWith('.local') || h.endsWith('.internal') || h.endsWith('.home.arpa')) return false;
// IPv6 literals (`::1`, `fe80::`, `fc00::/7`) arrive bracketed from URL.hostname; none of them is
// worth the address parsing a list of hostnames would need.
if (h.includes(':')) return false;
if (IPV4_PRIVATE.some(re => re.test(h))) return false;
if (/^\d+\.\d+\.\d+\.\d+$/.test(h)) return true; // a public IPv4 literal, allowed
return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(h); // a real, dotted hostname
}
/**
* The URL of a feed this module will fetch: https, no credentials, a public host, and short enough
* to be a URL rather than a payload. Exported because the rule is worth testing on its own.
*/
export function safeFeedUrl(url) {
if (typeof url !== 'string' || !url.length || url.length > MAX_URL) return null;
let u;
try { u = new URL(url); } catch { return null }
if (u.protocol !== 'https:') return null;
if (u.username || u.password) return null;
if (!publicHost(u.hostname)) return null;
u.hash = '';
return u.toString();
}
/* One function fetches, so the rule above is one rule in one place rather than a check each caller
has to remember — the shape radio.js settled on after a mutation showed a stray fetch slipping
past the allowlist. */
export async function get(url, { fetchImpl = fetch, timeoutMs = TIMEOUT_MS, headers = {}, max = MAX_FEED_BYTES } = {}) {
const safe = safeFeedUrl(url);
if (!safe) return null;
try {
const r = await fetchImpl(safe, { headers: { 'User-Agent': UA, ...headers }, signal: AbortSignal.timeout(timeoutMs) });
if (!r.ok && r.status !== 206) return null;
// Where we ended up, not only where we were pointed: a redirect is otherwise the way around the
// rule above.
if (r.url && !safeFeedUrl(r.url)) return null;
return await readCapped(r, max);
} catch { return null }
}
/**
* A body, up to `max` bytes, with the connection dropped as soon as the cap is reached.
*
* `res.text()` on a five-megabyte feed is how a feed reader becomes an out-of-memory bug, and a
* server that ignores the `Range` header we send for the language check would otherwise hand us a
* whole archive to read the first kilobyte of.
*/
export async function readCapped(res, max) {
const reader = res.body?.getReader?.();
if (!reader) return String(await res.text().catch(() => '')).slice(0, max);
const decoder = new TextDecoder();
let text = '';
let bytes = 0;
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
bytes += value.byteLength;
text += decoder.decode(value, { stream: true });
if (bytes >= max) { await reader.cancel().catch(() => {}); break }
}
} catch { /* a feed that dies mid-body still has a usable beginning */ }
// The cap is applied to the text as well as to the loop: a body streamed in one big chunk would
// otherwise be fully decoded before the check below ever ran.
return text.slice(0, max);
}
/* The cache, with a ceiling.
*
* Every entry here is small on purpose — a language tag, a parsed episode list — but "small" times
* an unbounded number of feed URLs is still a leak on a box with 1 GB of RAM, so the oldest entries
* go when there are too many. Nothing depends on an entry still being there: a miss is a refetch. */
const CACHE_MAX = 400;
let cache = new Map();
function cached(key, ms, fn) {
const hit = cache.get(key);
if (hit && Date.now() - hit.at < ms) return hit.value;
const value = Promise.resolve().then(fn).catch(() => null);
cache.set(key, { at: Date.now(), value });
if (cache.size > CACHE_MAX) {
for (const k of [...cache.keys()].slice(0, cache.size - CACHE_MAX)) cache.delete(k);
}
return value;
}
/** Only for tests: forget everything fetched. */
export function clearPodcastCache() { cache = new Map() }
/* ---------- the directory ---------- */
const apple = path => 'https://itunes.apple.com' + path;
/** The rows of a storefront chart: the ids, which is all a chart is good for. */
export function chartEntries(json) {
const entries = json && json.feed && json.feed.entry;
if (!Array.isArray(entries)) return [];
return entries
.map(e => ({ id: String(e?.id?.attributes?.['im:id'] || '') }))
.filter(e => e.id);
}
/**
* One show out of a `lookup` result.
*
* `feedUrl` is the field that matters; the rest is decoration the chart already carried, and the
* lookup is here only because the chart does not carry the feed.
*/
export function showFrom(row, country) {
const feed = safeFeedUrl(row?.feedUrl);
if (!feed) return null;
const name = String(row?.collectionName || '').trim();
if (!name) return null;
const art = [row?.artworkUrl600, row?.artworkUrl100].find(u => /^https:\/\//i.test(u || '')) || null;
return {
id: String(row?.collectionId || feed),
feed,
name: name.slice(0, 120),
author: String(row?.artistName || '').trim().slice(0, 80),
image: art,
genre: String(row?.primaryGenreName || '').trim().slice(0, 40),
country: String(country || row?.country || '').toLowerCase()
};
}
/** The storefront chart ids for a genre, cached for half an hour. */
export async function chartIds(country, genre, { fetchImpl = fetch } = {}) {
return cached(`chart:${country}:${genre}`, CACHE_MS, async () => {
const text = await get(apple(`/${country}/rss/toppodcasts/limit=${CHART_LIMIT}/genre=${genre}/json`), { fetchImpl });
if (!text) return [];
try { return chartEntries(JSON.parse(text)).map(e => e.id) } catch { return [] }
});
}
/** The details for a set of ids, in one request: `lookup` takes a comma-separated list. */
export async function lookupShows(ids, country, { fetchImpl = fetch } = {}) {
if (!ids.length) return [];
return cached(`lookup:${country}:${ids.join(',')}`, CACHE_MS, async () => {
const text = await get(apple(`/lookup?id=${ids.join(',')}&country=${country}`), { fetchImpl });
if (!text) return [];
try {
const json = JSON.parse(text);
return (json.results || []).map(r => showFrom(r, country)).filter(Boolean);
} catch { return [] }
});
}
/* ---------- the language check ---------- */
/** `es`, `es-ES`, `es-419` and `spa` are Spanish; `ca`, `en`, `et` are not; nothing is a "maybe". */
export function isSpanish(lang) {
const l = String(lang || '').trim().toLowerCase();
if (!l) return true;
return /^(es|spa)(\b|[_-])/.test(l);
}
/** `<language>` out of a feed, CDATA and all. */
export function languageOf(text) {
const m = /<language>\s*(?:<!\[CDATA\[)?\s*([^\]<\s]+)/i.exec(String(text || ''));
return m ? m[1].trim().toLowerCase().slice(0, 12) : null;
}
/**
* What a feed says its language is, from the first bytes of it.
*
* Two different answers, and the difference matters: `{ lang: null, ok: true }` is a feed that
* answered and declares nothing (keep it), while `null` is a feed that could not be read at all
* (drop it — a row whose every tap fails is worse than no row). A feed whose language is declared
* and is not Spanish is dropped on the spot.
*/
export async function feedLanguage(feed, { fetchImpl = fetch } = {}) {
const url = safeFeedUrl(feed);
if (!url) return null;
return cached('lang:' + url, CACHE_MS, async () => {
const head = await get(url, {
fetchImpl,
max: LANG_HEAD_BYTES,
headers: { Range: `bytes=0-${LANG_HEAD_BYTES - 1}` }
});
if (head == null || head === '') return null;
return { lang: languageOf(head), ok: true };
});
}
/** Run `fn` over `items` with a small pool, keeping the order and never throwing out of the pool. */
export async function mapLimit(items, limit, fn) {
const out = new Array(items.length).fill(null);
let next = 0;
const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
for (;;) {
const i = next++;
if (i >= items.length) return;
try { out[i] = await fn(items[i], i) } catch { out[i] = null }
}
});
await Promise.all(workers);
return out;
}
/**
* The shows of one category: the storefront charts, their feeds, and only the Spanish ones.
*
* The per-show cost is one 64 KB ranged request, so this is not free — the whole answer is cached
* for half an hour, which is what makes a category chip a tap rather than a wait.
*/
export async function showsFor(genreKey, { fetchImpl = fetch } = {}) {
const category = categoryOf(genreKey) || CATEGORIES[0];
const perStore = await Promise.all(STORES.map(async country => {
const ids = await chartIds(country, category.genre, { fetchImpl });
return lookupShows(ids, country, { fetchImpl });
}));
// Interleaved rather than one storefront after the other: the two countries publish different
// podcasts, and a list that shows twenty Spanish ones before the first Mexican one is not a list
// of what is out there.
const lists = perStore.filter(Array.isArray);
const rows = [];
for (let i = 0; lists.some(l => l[i]); i++) {
for (const list of lists) if (list[i]) rows.push(list[i]);
}
const seen = new Set();
/* *Why* a show was left out is reported, not just dropped.
*
* It used to be `return null` for every reason, which made three different things — "not in
* Spanish", "the feed did not answer", "the pool swallowed an unexpected error" — the same
* observable outcome. A refactor that accidentally let the third one happen then looked exactly
* like the rule working. A count per reason makes each of them a fact a test can assert on. */
const skipped = { duplicate: 0, language: 0, unreadable: 0, failed: 0 };
const results = await mapLimit(rows.slice(0, CHECK_LIMIT), POOL, async show => {
if (seen.has(show.feed)) return { skip: 'duplicate' };
seen.add(show.feed);
const lang = await feedLanguage(show.feed, { fetchImpl });
if (!lang) return { skip: 'unreadable' };
if (!isSpanish(lang.lang)) return { skip: 'language' };
return { show: { ...show, lang: lang.lang || null } };
});
const shows = [];
for (const r of results) {
// A null is an error the pool caught: counted as a failure rather than passing for a show that
// was filtered on purpose.
if (!r) { skipped.failed++; continue }
if (r.skip) { skipped[r.skip]++; continue }
shows.push(r.show);
if (shows.length >= MAX_SHOWS) break;
}
return { category, shows, skipped };
}
/* ---------- the feed ---------- */
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
const safeCodePoint = n => (Number.isFinite(n) && n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : '');
/** Named and numeric entities — not a parser, a decoder for what titles actually contain. */
export function decodeEntities(text) {
return String(text == null ? '' : text)
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => safeCodePoint(parseInt(hex, 16)))
.replace(/&#(\d+);/g, (_, dec) => safeCodePoint(parseInt(dec, 10)))
.replace(/&([a-z]+);/gi, (m, name) => (name.toLowerCase() in ENTITIES ? ENTITIES[name.toLowerCase()] : m));
}
/** The text of a tag, CDATA unwrapped, entities decoded, whitespace collapsed. */
export function tagText(item, tag) {
const m = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, 'i').exec(String(item || ''));
if (!m) return '';
return decodeEntities(m[1].replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1')).replace(/\s+/g, ' ').trim();
}
/** One attribute of the first matching tag, whatever order the feed wrote its attributes in. */
export function tagAttr(item, tag, attr) {
const m = new RegExp(`<${tag}(\\s[^>]*)>`, 'i').exec(String(item || ''));
if (!m) return '';
const a = new RegExp(`${attr}\\s*=\\s*["']([^"']*)["']`, 'i').exec(m[1]);
return a ? decodeEntities(a[1]).trim() : '';
}
/**
* A duration in seconds, from the three shapes feeds actually use.
*
* `itunes:duration` is free text: `00:52:15` on one feed, the bare `4847` on the next, `1:02:03` on
* a third — all three seen in one afternoon of Spanish comedy charts. A bare number is seconds;
* anything with colons is h:mm:ss or m:ss.
*/
export function parseDuration(value) {
const v = String(value == null ? '' : value).trim();
if (!v) return null;
if (/^\d+$/.test(v)) return Number(v);
const parts = v.split(':').map(p => Number(p.trim()));
if (parts.length < 2 || parts.length > 3) return null;
if (parts.some(n => !Number.isFinite(n) || n < 0)) return null;
return parts.length === 3
? parts[0] * 3600 + parts[1] * 60 + parts[2]
: parts[0] * 60 + parts[1];
}
const AUDIO_EXT = /\.(mp3|m4a|m4b|aac|ogg|oga|opus|mp4)(\?|#|$)/i;
/**
* One `<item>` into an episode, or null when there is nothing to play.
*
* The enclosure *is* the podcast: an item without a public audio file is a trailer, a
* subscriber-only episode or a video — three kinds of row that would play silence or nothing. The
* `type` attribute is trusted when it is there and the file extension when it is not, and a video
* enclosure is refused either way, because this player has no picture.
*/
export function episodeFrom(item, { image = null } = {}) {
const url = tagAttr(item, 'enclosure', 'url');
if (!/^https:\/\//i.test(url)) return null;
const type = tagAttr(item, 'enclosure', 'type').toLowerCase();
if (type ? !/^audio\//.test(type) : !AUDIO_EXT.test(url)) return null;
const title = tagText(item, 'title');
if (!title) return null;
const date = Date.parse(tagText(item, 'pubDate'));
const num = Number(tagText(item, 'itunes:episode'));
const art = tagAttr(item, 'itunes:image', 'href');
const bytes = Number(tagAttr(item, 'enclosure', 'length'));
return {
id: (tagText(item, 'guid') || url).slice(0, 200),
title: title.slice(0, 200),
url,
date: Number.isFinite(date) ? new Date(date).toISOString() : null,
duration: parseDuration(tagText(item, 'itunes:duration')),
image: /^https:\/\//i.test(art) ? art : image,
episode: Number.isFinite(num) && num > 0 ? num : null,
bytes: Number.isFinite(bytes) && bytes > 0 ? bytes : null
};
}
/**
* A feed into a show and its episodes.
*
* Deliberately tolerant, because feeds are the wild west and a rejected feed is a podcast nobody can
* play: a body truncated by the cap above simply loses its last, unterminated item, and a channel
* that declares no title falls back to whatever the directory called it.
*/
export function parseFeed(text, { fallbackTitle = '', fallbackImage = null } = {}) {
const src = String(text || '');
const first = src.search(/<item[\s>]/i);
const head = first < 0 ? src : src.slice(0, first);
const items = src.match(/<item[\s>][\s\S]*?(?:<\/item>|$)/gi) || [];
const image = tagAttr(head, 'itunes:image', 'href') || tagAttr(head, 'image', 'url') || fallbackImage;
const episodes = [];
const seen = new Set();
for (const item of items) {
// The last item of a truncated feed has no closing tag; half an episode is not an episode.
if (!/<\/item>/i.test(item)) continue;
const ep = episodeFrom(item, { image });
if (!ep || seen.has(ep.id)) continue;
seen.add(ep.id);
episodes.push(ep);
}
/* Newest first, by date when the feed gave one: a feed ordered by hand, or by an editorial
calendar, is not the one you want at the top of a list sorted by nothing. */
episodes.sort((a, b) => (Date.parse(b.date || '') || 0) - (Date.parse(a.date || '') || 0));
return {
show: {
title: tagText(head, 'title') || fallbackTitle,
author: tagText(head, 'itunes:author'),
image: image || null,
language: languageOf(src),
episodes: episodes.length
},
episodes: episodes.slice(0, MAX_EPISODES)
};
}
/**
* One show with its episodes, straight from the publisher's feed.
*
* The feed URL is data from a directory rather than something a browser typed, and it is put through
* `safeFeedUrl` again here — the api container is on somebody's network, so the rule is re-applied
* at every use and not only where the URL first appeared.
*
* The parsed language is returned rather than enforced, so the route can say *why* a feed was
* refused instead of answering "not found" to a Spanish user holding an English feed.
*/
export async function episodesFor(feed, { fetchImpl = fetch, title = '', image = null } = {}) {
const url = safeFeedUrl(feed);
if (!url) return null;
/* The *parsed* feed is cached, never its text: a feed is up to six megabytes and forty episodes
are a few kilobytes, so caching the body would be the whole memory budget for nothing. */
const parsed = await cached('feed:' + url, CACHE_MS, async () => {
const text = await get(url, { fetchImpl });
if (!text) return null;
const p = parseFeed(text);
return p.episodes.length ? p : null;
});
if (!parsed) return null;
return {
feed: url,
show: {
...parsed.show,
// The directory's name and artwork are only a fallback for a channel that declares neither.
title: parsed.show.title || title || 'Podcast',
image: parsed.show.image || (/^https:\/\//i.test(image || '') ? image : null)
},
episodes: parsed.episodes
};
}
+45
View File
@@ -22,6 +22,7 @@ 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 { categoryList, showsFor, episodesFor, safeFeedUrl, isSpanish } from './podcasts.js';
import { jevConfig, jevEndpoint, stateHash, insightFreshness, budgetFor } from './jev.js';
import {
readInsight, clearInsight, runInsight, stateFor, summarizeState, endpointHost
@@ -36,6 +37,7 @@ export const API_FEATURES = Object.freeze([
'vitals.receipt', // per-metric `shape`, and per-day `own` / `hours_sum`
'music.lookup', // POST /api/music/lookup
'radio', // GET /api/radio, GET /api/radio/now
'podcasts', // GET /api/podcasts, GET /api/podcasts/show
'insights' // GET/POST /api/insights (the second opinion)
]);
@@ -1302,6 +1304,49 @@ const routes = {
json(res, 200, { ok: true, now: await nowPlaying(station) });
},
/* ---------- podcasts ----------
*
* Two routes, both session-gated, and neither proxies audio: the list of Spanish shows for a
* category, and one show's episodes read out of the publisher's own feed. The episode URLs go to
* the phone from here; the audio then goes from the publisher to the phone.
*
* Unlike the radio — three known hosts, one allowlist — a feed can live anywhere, so the gate is
* `safeFeedUrl`: https, a real hostname, and never a private address (see api/podcasts.js). That
* matters more here than anywhere else in this file, because this process is running inside
* somebody's house and the URL arrives from a browser. */
'GET /api/podcasts': 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('category') || '';
const { category, shows, skipped } = await showsFor(key);
json(res, 200, { ok: true, categories: categoryList(), category: category.key, label: category.label, shows, skipped });
},
'GET /api/podcasts/show': 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 feed = safeFeedUrl(q.get('feed') || '');
if (!feed) return json(res, 400, { error: 'not a feed this server will fetch' });
const got = await episodesFor(feed, {
title: text(q.get('title')).slice(0, 120),
image: text(q.get('image')).slice(0, 300)
});
// A feed that does not answer is not an error status: the screen says so, the same way a music
// lookup that cannot reach Apple says so, and nothing about it is a 500.
if (!got) return json(res, 200, { ok: true, show: null, episodes: [], error: 'unreadable' });
/* A feed that declares another language is answered with the fact rather than hidden: the show
exists, it is simply not in Spanish, and saying that is better than an empty list that looks
like a feed with no episodes. */
const spanish = isSpanish(got.show.language);
json(res, 200, {
ok: true,
...got,
spanish,
episodes: spanish ? got.episodes : []
});
},
'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }),
'POST /api/push/subscribe': async (req, res) => {
+331
View File
@@ -0,0 +1,331 @@
/* Podcasts, tested without a network: everything here is a filter, a parse or a rule about what may
be fetched — and those are the three things that decide whether this feature is usable, safe and
actually in Spanish.
The load-bearing rule is the Spanish one. A storefront says a podcast is *sold* in Spain or
Mexico, and that is not the same as being in Spanish: the Spanish comedy chart carries a Catalan
show and the Argentine chart carries Joe Rogan. The feed's own `<language>` is the answer, and the
two edges of it are both tested — `ca` and `en` get dropped, and a feed that declares nothing
stays, because Spanish feeds do omit the tag and dropping good podcasts over an omission is worse
than keeping a rare miss.
The other rule is what this process will fetch. A feed URL is attacker-influenced data and the api
container sits on somebody's home network, so loopback, private ranges and `.local` names are
refused *before* a request is made. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
CATEGORIES, STORES, MAX_EPISODES, MAX_SHOWS, categoryList, categoryOf, isSpanish, languageOf,
publicHost, safeFeedUrl, parseDuration, decodeEntities, episodeFrom, parseFeed, tagText, tagAttr,
get, readCapped, feedLanguage, showsFor, episodesFor, chartEntries, showFrom, mapLimit,
clearPodcastCache
} from '../podcasts.js';
/* A stand-in for `fetch`: a body, a status, and the url it ended at. */
const res = (text, { status = 200, url = undefined } = {}) => ({
ok: status >= 200 && status < 300, status, url, body: null,
text: async () => text
});
/* ---------- categories ---------- */
test('every category has a label and an Apple genre id, and the keys are unique', () => {
const keys = categoryList().map(c => c.key);
assert.equal(new Set(keys).size, keys.length, 'no key twice');
for (const c of CATEGORIES) {
assert.ok(c.label.trim(), c.key + ' has a label');
assert.ok(Number.isInteger(c.genre) && c.genre > 0, c.key + ' has a genre id');
}
// The two a gym screen wants first, and Spanish labels — this list is read in Spanish.
assert.equal(keys[0], 'fitness');
assert.equal(keys[1], 'sports');
assert.equal(categoryOf('fitness').label, 'Salud y fitness');
assert.equal(categoryOf('nope'), null);
assert.ok(STORES.includes('es') && STORES.includes('mx'));
});
/* ---------- what may be fetched ---------- */
test('only a public https host is ever fetched', () => {
assert.ok(safeFeedUrl('https://feeds.example.com/show.rss'));
assert.ok(safeFeedUrl('https://example.com/a/b/c'), 'a feed with no extension is still a feed');
// Anything else is refused, and refused *before* the request — see the spy test below.
for (const bad of [
'http://feeds.example.com/show.rss', // plain http: the browser would refuse the audio too
'https://user:pw@feeds.example.com/x.rss', // credentials in the URL
'https://localhost/x.rss',
'https://127.0.0.1/x.rss',
'https://10.0.0.5/x.rss',
'https://192.168.1.10/x.rss',
'https://172.20.3.4/x.rss',
'https://169.254.169.254/latest/meta-data/', // the cloud metadata address
'https://100.64.0.1/x.rss', // carrier-grade NAT
'https://nas.local/x.rss',
'https://router.internal/x.rss',
'https://[::1]/x.rss',
'https://[fd00::1]/x.rss',
'file:///etc/passwd',
'not a url',
'',
null,
'https://' + 'a'.repeat(600) + '.com/x.rss' // longer than any real feed URL
]) assert.equal(safeFeedUrl(bad), null, `${bad} is refused`);
// The host rule on its own, for the cases a feed URL cannot express.
assert.equal(publicHost('example.com'), true);
assert.equal(publicHost('example.com.'), true, 'a trailing dot is the same host');
assert.equal(publicHost('8.8.8.8'), true, 'a public address literal is allowed');
assert.equal(publicHost('evil.com.localhost'), false);
});
test('an off-list url is refused without calling fetch at all', async () => {
let called = 0;
const fetchImpl = async () => { called++; return res('x') };
for (const bad of ['http://example.com/x.rss', 'https://127.0.0.1/x.rss', 'https://a.local/x.rss']) {
assert.equal(await get(bad, { fetchImpl }), null);
}
assert.equal(called, 0, 'the gate is inside get, so no caller can forget it');
});
test('a redirect off the allowed shape is refused too', async () => {
// Where the request ended up is checked, not only where it was pointed: a redirect to the router
// is otherwise the whole way around the rule.
const fetchImpl = async () => res('<rss/>', { url: 'https://192.168.1.1/x.rss' });
assert.equal(await get('https://feeds.example.com/x.rss', { fetchImpl }), null);
});
test('the body is read up to a cap and then dropped', async () => {
clearPodcastCache();
const huge = 'x'.repeat(5000);
assert.equal((await readCapped(res(huge), 100)).length, 100);
// A server that ignores Range hands us a real stream: it must be cut, not buffered whole.
const streamed = await readCapped(new Response('y'.repeat(200000)), 1000);
assert.equal(streamed.length, 1000);
});
/* ---------- Spanish only ---------- */
test('a Spanish language tag is what keeps a show, and the edges are both tested', () => {
for (const yes of ['es', 'es-ES', 'es-es', 'ES', 'es-419', 'es-MX', 'spa']) {
assert.equal(isSpanish(yes), true, yes + ' is Spanish');
}
for (const no of ['ca', 'ca-ES', 'en', 'en-US', 'pt', 'pt-BR', 'gl', 'eu', 'est', 'de']) {
assert.equal(isSpanish(no), false, no + ' is not Spanish');
}
// No tag at all is a "maybe": kept, because genuinely Spanish feeds omit it and the storefront is
// the fallback signal. See the header of api/podcasts.js.
assert.equal(isSpanish(null), true);
assert.equal(isSpanish(''), true);
});
test('the language tag is read out of a feed, CDATA and all', () => {
assert.equal(languageOf('<channel><language>es-ES</language><item/></channel>'), 'es-es');
assert.equal(languageOf('<language><![CDATA[es]]></language>'), 'es');
assert.equal(languageOf('<language>\n es-419\n</language>'), 'es-419');
assert.equal(languageOf('<channel><title>x</title></channel>'), null);
assert.equal(languageOf(null), null);
});
test('a feed that declares another language never reaches the list', async () => {
clearPodcastCache();
// The four cases, in one category: Spanish, no tag, Catalan, English — plus a feed that is down.
const langs = {
'https://a.example.com/feed': '<language>es-ES</language>',
'https://b.example.com/feed': '<title>sin etiqueta</title>',
'https://c.example.com/feed': '<language>ca</language>',
'https://d.example.com/feed': '<language>en-US</language>'
};
const fetchImpl = async url => {
if (url.includes('/rss/toppodcasts/')) {
const country = url.includes('/mx/') ? 'mx' : 'es';
return res(JSON.stringify({ feed: { entry: [{ id: { attributes: { 'im:id': country + '1' } } }] } }), { url });
}
if (url.includes('/lookup')) {
const country = url.split('country=')[1];
const rows = [1, 2, 3, 4, 5].map(n => ({
collectionId: `${country}${n}`,
collectionName: `${country} show ${n}`,
artistName: 'Alguien',
artworkUrl600: 'https://img.example.com/x.jpg',
primaryGenreName: 'Comedy',
feedUrl: ['https://a.example.com/feed', 'https://b.example.com/feed', 'https://c.example.com/feed', 'https://d.example.com/feed', 'https://down.example.com/feed'][n - 1]
}));
return res(JSON.stringify({ results: rows }), { url });
}
if (langs[url]) return res(langs[url], { status: url.startsWith('https://b.') ? 200 : 206, url });
return res('', { status: 500, url });
};
const { category, shows, skipped } = await showsFor('comedy', { fetchImpl });
assert.equal(category.key, 'comedy');
// Each reason is a number, so "dropped for language" cannot pass for "the fetch blew up".
assert.equal(skipped.language, 2, 'Catalan and English');
assert.equal(skipped.unreadable, 1, 'the feed that is down');
assert.equal(skipped.failed, 0, 'nothing threw');
assert.equal(skipped.duplicate, 5, 'the second storefront listed the same five feeds');
const names = shows.map(s => s.name);
assert.ok(names.includes('es show 1'), 'Spanish kept');
assert.ok(names.includes('es show 2'), 'no tag kept');
assert.ok(!names.includes('es show 3'), 'Catalan dropped');
assert.ok(!names.includes('es show 4'), 'English dropped');
assert.ok(!names.includes('es show 5'), 'a feed that is down is not a row that cannot play');
assert.equal(shows[0].lang, 'es-es');
assert.equal(shows[1].lang, null);
// One row per feed even though both storefronts listed the same five shows.
assert.equal(new Set(shows.map(s => s.feed)).size, shows.length);
assert.ok(shows.length <= MAX_SHOWS);
});
test('a feed that cannot be read is not Spanish-by-default', async () => {
clearPodcastCache();
const fetchImpl = async url => {
if (url.includes('/rss/')) return res(JSON.stringify({ feed: { entry: [{ id: { attributes: { 'im:id': '1' } } }] } }), { url });
if (url.includes('/lookup')) return res(JSON.stringify({ results: [{ collectionId: '1', collectionName: 'S', feedUrl: 'https://a.example.com/feed' }] }), { url });
return res('', { status: 503, url });
};
assert.equal(await feedLanguage('https://a.example.com/feed', { fetchImpl }), null);
const { shows, skipped } = await showsFor('comedy', { fetchImpl });
assert.deepEqual(shows, []);
assert.equal(skipped.unreadable, 1, 'unreadable, by that rule and not by an accident');
assert.equal(skipped.failed, 0, 'and not by an exception the pool swallowed');
});
test('the language check reads the head of the feed, not the whole archive', async () => {
clearPodcastCache();
let asked = null;
const fetchImpl = async (url, opts) => { asked = opts.headers.Range; return res('<language>es</language>', { status: 206, url }) };
assert.deepEqual(await feedLanguage('https://a.example.com/feed', { fetchImpl }), { lang: 'es', ok: true });
assert.equal(asked, 'bytes=0-65535');
});
/* ---------- the directory rows ---------- */
test('a show is kept only when it has a feed this process will fetch', () => {
const base = { collectionId: 12, collectionName: 'Un podcast', feedUrl: 'https://a.example.com/feed' };
assert.equal(showFrom(base, 'es').feed, 'https://a.example.com/feed');
assert.equal(showFrom(base, 'es').country, 'es');
assert.equal(showFrom({ ...base, feedUrl: 'http://a.example.com/feed' }, 'es'), null, 'http feed');
assert.equal(showFrom({ ...base, feedUrl: 'https://10.0.0.1/feed' }, 'es'), null, 'private host');
assert.equal(showFrom({ ...base, feedUrl: null }, 'es'), null, 'no feed at all');
assert.equal(showFrom({ ...base, collectionName: ' ' }, 'es'), null, 'no name');
// An http artwork is dropped rather than shown broken.
assert.equal(showFrom({ ...base, artworkUrl600: 'http://img/x.jpg' }, 'es').image, null);
assert.equal(chartEntries({ feed: { entry: [{ id: { attributes: { 'im:id': '7' } } }, { id: {} }] } }).length, 1);
assert.deepEqual(chartEntries({}), []);
});
/* ---------- the feed ---------- */
const feed = ({ items, extra = '' }) => `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
<channel>
<title>Nadie Sabe Nada</title>
<language>es-ES</language>
<itunes:author>Cadena SER</itunes:author>
<itunes:image href="https://img.example.com/nsn.jpg"/>
${extra}
${items}
</channel></rss>`;
const item = ({ title = 'Un episodio', date = 'Tue, 02 Sep 2025 10:00:00 GMT', dur = '00:52:15', enc = '<enclosure url="https://audio.example.com/1.mp3" type="audio/mpeg" length="12345678"/>', guid = 'ep-1', extra = '' }) =>
`<item><title>${title}</title><description><![CDATA[<p>bla</p>]]></description>
<pubDate>${date}</pubDate><itunes:duration>${dur}</itunes:duration><guid>${guid}</guid>${enc}${extra}</item>`;
test('a duration is read in all three shapes feeds use', () => {
assert.equal(parseDuration('00:52:15'), 3135);
assert.equal(parseDuration('4847'), 4847);
assert.equal(parseDuration('1:02:03'), 3723);
assert.equal(parseDuration('12:30'), 750);
assert.equal(parseDuration(''), null);
assert.equal(parseDuration(null), null);
assert.equal(parseDuration('una hora'), null);
assert.equal(parseDuration('1:2:3:4'), null);
});
test('titles come out with CDATA unwrapped and entities decoded', () => {
assert.equal(decodeEntities('Rock &amp; Roll &#8212; 4 &lt; 5'), 'Rock & Roll — 4 < 5');
assert.equal(tagText('<title><![CDATA[324. La Ruina & Co]]></title>', 'title'), '324. La Ruina & Co');
assert.equal(tagAttr('<enclosure type="audio/mpeg" url="https://x/1.mp3"/>', 'enclosure', 'url'), 'https://x/1.mp3');
assert.equal(tagAttr('<enclosure type="audio/mpeg"/>', 'enclosure', 'url'), '');
});
test('an item with nothing to play is not an episode', () => {
const opts = { image: 'https://img.example.com/show.jpg' };
// A video enclosure: this player has no picture.
assert.equal(episodeFrom(item({ enc: '<enclosure url="https://v.example.com/1.mp4" type="video/mp4"/>' }), opts), null);
// A subscriber-only episode has no enclosure at all.
assert.equal(episodeFrom(item({ enc: '' }), opts), null, 'no enclosure');
// No type, but an audio file: kept, because plenty of feeds omit the type.
const noType = episodeFrom(item({ enc: '<enclosure url="https://audio.example.com/1.mp3"/>' }), opts);
assert.equal(noType.url, 'https://audio.example.com/1.mp3');
// No type and not an audio file: refused.
assert.equal(episodeFrom(item({ enc: '<enclosure url="https://docs.example.com/notes.pdf"/>' }), opts), null);
// http audio would be blocked by the browser on an https page.
assert.equal(episodeFrom(item({ enc: '<enclosure url="http://audio.example.com/1.mp3" type="audio/mpeg"/>' }), opts), null);
assert.equal(episodeFrom(item({ title: '' }), opts), null, 'no title');
const ep = episodeFrom(item({ extra: '<itunes:episode>14</itunes:episode>' }), opts);
assert.equal(ep.episode, 14);
assert.equal(ep.duration, 3135);
assert.equal(ep.image, 'https://img.example.com/show.jpg', 'falls back to the channel image');
assert.equal(ep.bytes, 12345678);
});
test('a feed becomes a show with its episodes, newest first', () => {
const text = feed({
items: [
item({ title: 'Viejo', date: 'Mon, 01 Sep 2025 10:00:00 GMT', guid: 'a' }),
item({ title: 'Nuevo', date: 'Wed, 03 Sep 2025 10:00:00 GMT', guid: 'b' }),
item({ title: 'Sin fecha', date: '', guid: 'c' })
]
});
const { show, episodes } = parseFeed(text);
assert.equal(show.title, 'Nadie Sabe Nada');
assert.equal(show.author, 'Cadena SER');
assert.equal(show.language, 'es-es');
assert.equal(show.image, 'https://img.example.com/nsn.jpg');
assert.deepEqual(episodes.map(e => e.title), ['Nuevo', 'Viejo', 'Sin fecha']);
assert.equal(episodes.length, show.episodes);
});
test('a feed truncated by the cap loses its last item and nothing else', () => {
// The body was cut mid-item: the parser must not invent a half episode, and must not throw.
const text = feed({ items: item({ title: 'Uno', guid: 'a' }) }) + '<item><title>Dos a medias</title><enclosure url="https://a.example.com/2.mp3" type="audio/mpeg"';
const { episodes } = parseFeed(text);
assert.deepEqual(episodes.map(e => e.title), ['Uno']);
});
test('a show with no title of its own takes the directory name', () => {
const { show, episodes } = parseFeed('<rss><channel><language>es</language>' + item({}) + '</channel></rss>', { fallbackTitle: 'Desde Apple' });
assert.equal(show.title, 'Desde Apple');
assert.equal(episodes.length, 1);
});
test('the list of episodes is capped, and duplicates are one episode', () => {
const many = Array.from({ length: MAX_EPISODES + 5 }, (_, i) => item({ title: 'E' + i, guid: 'g' + i }));
assert.equal(parseFeed(feed({ items: many })).episodes.length, MAX_EPISODES);
const twice = item({ title: 'Repetido', guid: 'same' }) + item({ title: 'Repetido (otra vez)', guid: 'same' });
assert.deepEqual(parseFeed(feed({ items: twice })).episodes.map(e => e.title), ['Repetido']);
});
/* ---------- the whole way through ---------- */
test('episodesFor refuses an unsafe feed and parses a real one', async () => {
clearPodcastCache();
assert.equal(await episodesFor('http://a.example.com/feed'), null);
assert.equal(await episodesFor('https://10.0.0.1/feed'), null);
const fetchImpl = async url => res(feed({ items: item({}) }), { url });
const got = await episodesFor('https://a.example.com/feed', { fetchImpl, title: 'De Apple' });
assert.equal(got.feed, 'https://a.example.com/feed');
assert.equal(got.show.title, 'Nadie Sabe Nada');
assert.equal(got.episodes[0].url, 'https://audio.example.com/1.mp3');
// An unreadable feed is null, not an exception. A different URL, because the parsed feed above is
// cached for half an hour on purpose — that cache is what keeps a big feed from being downloaded
// again every time somebody opens the show.
assert.equal(await episodesFor('https://b.example.com/feed', { fetchImpl: async () => res('', { status: 500 }), title: 'x' }), null);
});
test('the pool keeps the order and never throws out of itself', async () => {
const out = await mapLimit([1, 2, 3, 4, 5], 2, async n => {
if (n === 3) throw new Error('boom');
return n * 2;
});
assert.deepEqual(out, [2, 4, null, 8, 10]);
});
+91
View File
@@ -0,0 +1,91 @@
/* The two podcast routes, against the real server: who may call them, and which feed URLs this
process will agree to fetch.
The feed rule is the one that matters, and it matters more here than in any other route: a podcast
feed can live on any host in the world, so there is no allowlist to fall back on — only the rule
in `safeFeedUrl`. This container runs inside somebody's house, and the URL arrives from a browser,
so `http://192.168.1.1/…` is not a bad feed, it is a request this process must never make. */
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-podcasts-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: 'u_p', 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 podcast list needs a session', async t => {
const h = await startServer(t);
const r = await fetch(`${h.api}/api/podcasts`);
assert.equal(r.status, 401);
});
test('so does a show', async t => {
const h = await startServer(t);
const r = await fetch(`${h.api}/api/podcasts/show?feed=${encodeURIComponent('https://feeds.example.com/x.rss')}`);
assert.equal(r.status, 401);
});
test('a feed URL that is not public https is refused before any request is made', async t => {
const h = await startServer(t);
for (const feed of [
'http://169.254.169.254/latest/meta-data/', // the cloud metadata address
'http://127.0.0.1:3000/api/health',
'https://127.0.0.1/x.rss',
'https://192.168.1.1/x.rss',
'https://10.0.0.5/x.rss',
'https://router.local/x.rss',
'https://[::1]/x.rss',
'http://feeds.example.com/x.rss', // plain http, even on a real host
'https://user:pw@feeds.example.com/x.rss',
'file:///etc/passwd',
'not a url',
''
]) {
const r = await fetch(`${h.api}/api/podcasts/show?feed=${encodeURIComponent(feed)}`, { headers: cookie('u_p') });
assert.equal(r.status, 400, `${feed} is refused`);
assert.match((await r.json()).error, /feed this server will fetch/);
}
});
test('the instance says it supports podcasts', async t => {
const h = await startServer(t);
const cfg = await (await fetch(`${h.api}/api/config`)).json();
assert.ok(cfg.features.includes('podcasts'), 'features: ' + cfg.features.join(','));
});