/* 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 `` 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, searchShows, appleSearch, normQuery
} 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('', { 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('es-ES '), 'es-es');
assert.equal(languageOf(''), 'es');
assert.equal(languageOf('\n es-419\n'), 'es-419');
assert.equal(languageOf('x'), 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': 'es-ES',
'https://b.example.com/feed': 'sin etiqueta',
'https://c.example.com/feed': 'ca',
'https://d.example.com/feed': 'en-US'
};
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('es', { 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 = '' }) => `
Nadie Sabe Nada
es-ES
Cadena SER
${extra}
${items}
`;
const item = ({ title = 'Un episodio', date = 'Tue, 02 Sep 2025 10:00:00 GMT', dur = '00:52:15', enc = '', guid = 'ep-1', extra = '' }) =>
`- ${title}bla
]]>
${date}${dur}${guid}${enc}${extra}`;
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 & Roll — 4 < 5'), 'Rock & Roll — 4 < 5');
assert.equal(tagText('', 'title'), '324. La Ruina & Co');
assert.equal(tagAttr('', 'enclosure', 'url'), 'https://x/1.mp3');
assert.equal(tagAttr('', '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: '' }), 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: '' }), opts);
assert.equal(noType.url, 'https://audio.example.com/1.mp3');
// No type and not an audio file: refused.
assert.equal(episodeFrom(item({ enc: '' }), opts), null);
// http audio would be blocked by the browser on an https page.
assert.equal(episodeFrom(item({ enc: '' }), opts), null);
assert.equal(episodeFrom(item({ title: '' }), opts), null, 'no title');
const ep = episodeFrom(item({ extra: '14' }), 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' }) }) + '- Dos a medias e.title), ['Uno']);
});
test('a show with no title of its own takes the directory name', () => {
const { show, episodes } = parseFeed('es' + item({}) + '', { 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]);
});
/* ---------- search ---------- */
test('a query has to be a query here too', () => {
assert.equal(normQuery(' Crimen real '), 'Crimen real', 'the term goes to Apple as typed');
assert.equal(normQuery('a'), '');
assert.equal(normQuery(null), '');
assert.equal(normQuery('x'.repeat(200)).length, 80);
});
test('a search is Apple\'s, one request per storefront, Spanish and no key', async () => {
clearPodcastCache();
const asked = [];
const fetchImpl = async url => {
asked.push(url);
if (url.includes('/search?')) {
const country = new URL(url).searchParams.get('country');
return res(JSON.stringify({ results: [{
collectionId: country + '1',
collectionName: 'Crimen ' + country,
artistName: 'Alguien',
artworkUrl600: 'https://img.example.com/x.jpg',
primaryGenreName: 'True Crime',
feedUrl: 'https://feeds.example.com/' + country
}] }), { url });
}
// Both feeds declare Spanish, except the Mexican one, which declares English.
if (url === 'https://feeds.example.com/es') return res('es-ES', { status: 206, url });
if (url === 'https://feeds.example.com/mx') return res('en', { status: 206, url });
return res('', { status: 500, url });
};
const { query, shows, skipped } = await searchShows('crimen', { fetchImpl });
assert.equal(query, 'crimen');
assert.deepEqual(shows.map(s => s.name), ['Crimen es'], 'only the Spanish one');
assert.equal(shows[0].lang, 'es-es');
assert.equal(skipped.language, 1, 'and the other one is counted, not silently missing');
assert.equal(skipped.failed, 0);
// One request per storefront, not one per show: `media=podcast`, the storefront, and `lang=es`.
const searches = asked.filter(u => u.includes('/search?'));
assert.equal(searches.length, 2);
const q = new URL(searches[0]).searchParams;
assert.equal(q.get('media'), 'podcast');
assert.equal(q.get('term'), 'crimen');
assert.equal(q.get('lang'), 'es');
assert.deepEqual(searches.map(u => new URL(u).searchParams.get('country')).sort(), ['es', 'mx']);
});
test('a search result goes through the same feed rule as a chart entry', async () => {
clearPodcastCache();
const fetchImpl = async url => {
if (url.includes('/search?')) {
return res(JSON.stringify({ results: [
{ collectionId: '1', collectionName: 'Bueno', feedUrl: 'https://feeds.example.com/a' },
{ collectionId: '2', collectionName: 'Inservible', feedUrl: 'http://feeds.example.com/b' },
{ collectionId: '3', collectionName: 'Privado', feedUrl: 'https://10.0.0.9/c' }
] }), { url });
}
return res('es', { status: 206, url });
};
const { shows } = await searchShows('algo', { fetchImpl });
assert.deepEqual(shows.map(s => s.name), ['Bueno'], 'an http feed and a private host are not shows');
});
test('one letter is not a search, and nobody is asked', async () => {
clearPodcastCache();
let called = 0;
const fetchImpl = async () => { called++; return res('{}') };
const { shows, query } = await searchShows('c', { fetchImpl });
assert.deepEqual(shows, []);
assert.equal(query, '');
assert.equal(called, 0);
// And the storefronts are cached: the same query twice is one request each.
const impl = async url => url.includes('/search?')
? res(JSON.stringify({ results: [{ collectionId: '1', collectionName: 'X', feedUrl: 'https://feeds.example.com/x' }] }), { url })
: res('es', { status: 206, url });
let n = 0;
const counting = async (url, ...rest) => { if (url.includes('/search?')) n++; return impl(url, ...rest) };
await searchShows('comedia', { fetchImpl: counting });
await searchShows('comedia', { fetchImpl: counting });
assert.equal(n, 2, 'one per storefront, then cached');
});