Música: a playlist screen per profile, with Apple's limits stated plainly
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
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
The idea was "each person types their Apple Music username and their public playlists appear". Apple does not allow that, and it is worth writing down rather than discovering later: there is no API for another person's public playlists — their own developer forums answer that request with "you can't" (threads 692941 and 123894) — and a profile page is rendered by JavaScript with nothing behind it to call. MusicKit offers the catalog and the *signed-in* user's own library, and the second needs an Apple Developer Program membership for a developer token plus a Music-User-Token per person: a private key and a third-party secret in an app that holds none, to fetch something other than what was asked for. What a self-hosted app can do is the share link, which every playlist has: Music → Share → Copy Link. So the Música screen (next to Salud in Home's header, plus a section in Settings) keeps a list of them per profile, in the profile document like the routines — so they sync to the other devices and travel in a backup — and tapping one opens it in Apple Music on the iPhone. The username is a link to the person's public profile. The list is nicer than a column of URLs because the API reads each link's public page for a title, artwork and track count. That is scraping, so it is built to lose: a page that says nothing leaves the card showing the name its owner typed, and nothing on the screen depends on it. `POST /api/music/lookup` is host-allowlisted to Apple's music hosts — https only, checked again on the URL a redirect lands on — because the api container sits on the same network as everything else the owner runs, and a route that fetches whatever it is handed is a request-forgery lever. That boundary has its own tests, including the LAN addresses it must refuse. The parsing lives in api/music.js rather than in both halves: two copies of a parser kept in step by hand is a bomb, and this is the same shape as vitals.js. It is in the Dockerfile's COPY for the same reason vitals.js had to be.
This commit is contained in:
1 parent
45183c725f
commit
caed0cbaa0
18 files changed
+743
-16
No files matched your search
+4
-4
@@ -53,10 +53,10 @@ RUN npm ci --omit=dev --omit=optional && npm cache clean --force
|
||||
|
||||
# Every local module server.js imports, listed rather than `COPY . .` so a stray file in api/
|
||||
# (a test, a script, a stray JSON) cannot reach the published image. vitals.js joined the list
|
||||
# with the Apple Health ingest — 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 ./
|
||||
# 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 ./
|
||||
COPY coach ./coach
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/* music.js — what a public Apple Music page says about itself.
|
||||
*
|
||||
* This is the API half of the Música screen. The client keeps the links (frontend/src/lib/music.js
|
||||
* owns reading and validating those); this fetches one and reads its title, artwork and track count
|
||||
* so the list looks like a list of playlists instead of a column of URLs.
|
||||
*
|
||||
* It lives beside server.js, exported and tested on its own, for the reason vitals.js does: it is
|
||||
* the only part of the route with logic in it, and it is much easier to test against real markup
|
||||
* than to watch a phone do it. server.js owns the socket, this owns the parsing.
|
||||
*
|
||||
* ── Two things that are not negotiable here ──────────────────────────────────────────────────
|
||||
*
|
||||
* HOST-ALLOWLISTED. The URL comes from a signed-in user and the request is made from the api
|
||||
* container, which sits on the same network as everything else the owner runs — so a route that
|
||||
* fetches whatever it is handed is a request-forgery lever. Only Apple's own music hosts are
|
||||
* reachable, which is a set nobody can point at the LAN. `hostAllowed` is used both before the
|
||||
* request and again on the final URL, because a redirect must not be a way around it.
|
||||
*
|
||||
* BEST EFFORT. Apple's markup is theirs to change; a page that yields nothing costs the reader the
|
||||
* artwork and the track count, never the playlist (the card falls back to the name its owner
|
||||
* typed). Apple publishes a schema.org MusicPlaylist block for previews to read, which is the part
|
||||
* this leans on; the Open Graph tags are the fallback.
|
||||
*/
|
||||
export const MUSIC_HOSTS = new Set(['music.apple.com', 'itunes.apple.com', 'geo.music.apple.com']);
|
||||
export const MUSIC_TIMEOUT_MS = 8000;
|
||||
export const MUSIC_MAX_HTML = 1024 * 1024; // a playlist page is a few hundred KB; more is not one
|
||||
|
||||
/** Is this URL one we are willing to fetch? https, and one of Apple's music hosts. */
|
||||
export function hostAllowed(url) {
|
||||
try {
|
||||
const u = new URL(String(url));
|
||||
return u.protocol === 'https:' && MUSIC_HOSTS.has(u.hostname.toLowerCase());
|
||||
} catch { return false }
|
||||
}
|
||||
|
||||
/** Read at most `max` bytes of a response, as text. */
|
||||
export async function readCapped(res, max = MUSIC_MAX_HTML) {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of res.body || []) {
|
||||
size += chunk.length;
|
||||
if (size > max) break;
|
||||
chunks.push(chunk);
|
||||
}
|
||||
return Buffer.concat(chunks).toString('utf8');
|
||||
}
|
||||
|
||||
const decode = s => String(s || '')
|
||||
.replace(/"/g, '"').replace(/�?39;/g, "'").replace(/'/g, "'")
|
||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/ /g, ' ');
|
||||
|
||||
/** @returns {{title:string|null, artwork:string|null, tracks:number|null, curator:string|null}} */
|
||||
export function parseMusicPage(html) {
|
||||
const text = String(html || '');
|
||||
const out = { title: null, artwork: null, tracks: null, curator: null };
|
||||
const meta = prop => {
|
||||
const m = new RegExp(`<meta[^>]+(?:property|name)=["']${prop}["'][^>]+content=["']([^"']*)["']`, 'i').exec(text)
|
||||
|| new RegExp(`<meta[^>]+content=["']([^"']*)["'][^>]+(?:property|name)=["']${prop}["']`, 'i').exec(text);
|
||||
return m ? decode(m[1]) : null;
|
||||
};
|
||||
for (const m of text.matchAll(/<script[^>]+application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)) {
|
||||
let data;
|
||||
try { data = JSON.parse(m[1].trim()); } catch { continue }
|
||||
for (const node of Array.isArray(data) ? data : [data]) {
|
||||
if (!node || node['@type'] !== 'MusicPlaylist') continue;
|
||||
if (node.name) out.title = decode(node.name);
|
||||
if (typeof node.numTracks === 'number') out.tracks = node.numTracks;
|
||||
const img = node.image;
|
||||
if (typeof img === 'string') out.artwork = img;
|
||||
else if (img && typeof img === 'object' && img.url) out.artwork = img.url;
|
||||
const by = node.byArtist || node.author || node.creator;
|
||||
if (by && typeof by === 'object' && by.name) out.curator = decode(by.name);
|
||||
}
|
||||
}
|
||||
if (!out.title) out.title = meta('og:title') || meta('twitter:title');
|
||||
if (!out.artwork) out.artwork = meta('og:image') || meta('twitter:image');
|
||||
// Apple serves the preview image at whatever size it likes; asking their own CDN template for a
|
||||
// bigger one is a string substitution, and harmless when the path does not match.
|
||||
if (out.artwork) out.artwork = out.artwork.replace(/\/\d+x\d+(bb)?\.(jpg|png|webp)$/i, '/600x600bb.jpg');
|
||||
return out;
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { startWarmup } from './coach/warmup.js';
|
||||
import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
|
||||
import { verifyError } from './verify-error.js';
|
||||
import { parsePayload, mergeVitals, vitalsSeries, emptyVitals, RETENTION_DAYS } from './vitals.js';
|
||||
import { hostAllowed, readCapped, parseMusicPage } from './music.js';
|
||||
|
||||
const PORT = +(process.env.PORT || 3000);
|
||||
const DATA = process.env.DATA_DIR || '/data';
|
||||
@@ -1100,6 +1101,43 @@ const routes = {
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
|
||||
/* ---------- Apple Music: reading a link's public page ----------
|
||||
*
|
||||
* The client keeps the links; this only fills in what a link can say about itself — its title,
|
||||
* its artwork, how many tracks — so the list looks like a list of playlists instead of a column
|
||||
* of URLs. Apple publishes a schema.org MusicPlaylist block for previews; it is read here and
|
||||
* anything unexpected degrades to the name the person typed (see lib/music.js).
|
||||
*
|
||||
* HOST-ALLOWLISTED, and that is a security boundary rather than tidiness: the URL comes from a
|
||||
* signed-in user, the request is made from this container, and this container sits on the same
|
||||
* network as everything else the owner runs — a route that fetches whatever it is handed is a
|
||||
* request-forgery lever (the same reasoning as PUSH_AGENT below, which is why it exists). Only
|
||||
* Apple's own music hosts are reachable, which is a set no attacker can point at the LAN. */
|
||||
'POST /api/music/lookup': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const body = await readBody(req);
|
||||
const target = text(body.url).trim();
|
||||
if (!hostAllowed(target)) return json(res, 400, { error: 'not an Apple Music link' });
|
||||
let r;
|
||||
try {
|
||||
r = await fetch(target, {
|
||||
redirect: 'follow',
|
||||
signal: AbortSignal.timeout(MUSIC_TIMEOUT_MS),
|
||||
headers: { 'User-Agent': 'KuentaGYM (self-hosted)' }
|
||||
});
|
||||
} catch {
|
||||
return json(res, 200, { ok: true, meta: null, error: 'unreachable' });
|
||||
}
|
||||
// Where we ended up is checked too, not only where we were pointed: a redirect is otherwise a
|
||||
// way around the allowlist.
|
||||
if (!r.ok || !hostAllowed(r.url)) {
|
||||
return json(res, 200, { ok: true, meta: null, error: r.ok ? 'off-host' : 'http-' + r.status });
|
||||
}
|
||||
const html = await readCapped(r, MUSIC_MAX_HTML);
|
||||
json(res, 200, { ok: true, meta: parseMusicPage(html) });
|
||||
},
|
||||
|
||||
'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }),
|
||||
|
||||
'POST /api/push/subscribe': async (req, res) => {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/* What a public Apple Music page says about itself, and which links this API is willing to fetch.
|
||||
*
|
||||
* The parser is best-effort by design — Apple's markup is theirs to change — so these tests are
|
||||
* about the two things that must not wobble: the schema block is read when it is there, the Open
|
||||
* Graph tags take over when it is not, and a page that is not a playlist at all returns nothing
|
||||
* rather than throwing. The allowlist gets the same treatment, because that one is a boundary
|
||||
* rather than a convenience. */
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseMusicPage, hostAllowed } from '../music.js';
|
||||
|
||||
const PAGE = `<!DOCTYPE html><html><head>
|
||||
<meta property="og:title" content="Leg Day — Playlist by Ana">
|
||||
<meta property="og:image" content="https://is1-ssl.mzstatic.com/image/thumb/Feature/abc/3000x3000bb.jpg">
|
||||
<script type="application/ld+json">
|
||||
{"@context":"https://schema.org","@type":"MusicPlaylist","name":"Leg Day '24","numTracks":42,
|
||||
"image":"https://is1-ssl.mzstatic.com/image/thumb/Feature/abc/1000x1000bb.jpg",
|
||||
"byArtist":{"@type":"MusicGroup","name":"Ana"}}
|
||||
</script></head><body>Leg Day</body></html>`;
|
||||
|
||||
test('reads the schema block first, and asks Apple\'s CDN for one useful size', () => {
|
||||
const m = parseMusicPage(PAGE);
|
||||
assert.equal(m.title, "Leg Day '24");
|
||||
assert.equal(m.tracks, 42);
|
||||
assert.equal(m.curator, 'Ana');
|
||||
assert.equal(m.artwork, 'https://is1-ssl.mzstatic.com/image/thumb/Feature/abc/600x600bb.jpg');
|
||||
});
|
||||
|
||||
test('falls back to Open Graph, and never invents what it cannot read', () => {
|
||||
const noSchema = PAGE.replace(/<script[\s\S]*?<\/script>/, '');
|
||||
const m = parseMusicPage(noSchema);
|
||||
assert.equal(m.title, 'Leg Day — Playlist by Ana');
|
||||
assert.ok(m.artwork.endsWith('600x600bb.jpg'));
|
||||
assert.equal(m.tracks, null);
|
||||
assert.equal(m.curator, null);
|
||||
|
||||
// A schema block that is there but unparseable is the same as one that is not: half a JSON object
|
||||
// must not take the title down with it.
|
||||
const broken = parseMusicPage(PAGE.replace('"numTracks":42,', '"numTracks":,'));
|
||||
assert.equal(broken.title, 'Leg Day — Playlist by Ana');
|
||||
assert.equal(broken.tracks, null);
|
||||
});
|
||||
|
||||
test('says nothing rather than throwing when the page is not a playlist', () => {
|
||||
const empty = { title: null, artwork: null, tracks: null, curator: null };
|
||||
assert.deepEqual(parseMusicPage('<html><body>Sign in to Apple Music</body></html>'), empty);
|
||||
assert.deepEqual(parseMusicPage(''), empty);
|
||||
assert.deepEqual(parseMusicPage(null), empty);
|
||||
// The `content` before `property` order is real markup too, and is matched.
|
||||
assert.equal(parseMusicPage('<meta content="X" property="og:title">').title, 'X');
|
||||
});
|
||||
|
||||
test('only Apple\'s own music hosts, over https — this is a boundary, not a preference', () => {
|
||||
assert.equal(hostAllowed('https://music.apple.com/us/playlist/x/pl.1'), true);
|
||||
assert.equal(hostAllowed('https://itunes.apple.com/us/album/x/1'), true);
|
||||
assert.equal(hostAllowed('https://geo.music.apple.com/us/playlist/x/pl.1'), true);
|
||||
// The interesting ones: the api container sits on the owner's network, so anything that could
|
||||
// name a machine on it is refused — a lookalike domain, a LAN address, localhost, plain http, and
|
||||
// a scheme that is not http at all.
|
||||
assert.equal(hostAllowed('https://music.apple.com.evil.test/us/playlist/x/pl.1'), false);
|
||||
assert.equal(hostAllowed('http://music.apple.com/us/playlist/x/pl.1'), false);
|
||||
assert.equal(hostAllowed('http://127.0.0.1:3000/api/health'), false);
|
||||
assert.equal(hostAllowed('http://192.168.1.1/'), false);
|
||||
assert.equal(hostAllowed('http://169.254.169.254/latest/meta-data/'), false);
|
||||
assert.equal(hostAllowed('file:///etc/passwd'), false);
|
||||
assert.equal(hostAllowed('gopher://music.apple.com/'), false);
|
||||
assert.equal(hostAllowed('not a url'), false);
|
||||
assert.equal(hostAllowed(''), false);
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
/* POST /api/music/lookup, against the real server: who may call it, and what it will agree to
|
||||
fetch. The fetch itself is Apple's, so the happy path is covered by api/test/music.test.js —
|
||||
these are the two guards, and a guard is exactly the kind of thing that quietly stops guarding. */
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import net from 'node:net';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const SECRET = crypto.randomBytes(32).toString('hex');
|
||||
|
||||
function mintSession(uid, sv = 0) {
|
||||
const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
|
||||
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
|
||||
}
|
||||
const cookie = uid => ({ Cookie: `gymsid=${mintSession(uid)}` });
|
||||
|
||||
const freePort = () => new Promise(r => {
|
||||
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
|
||||
});
|
||||
|
||||
async function startServer(t) {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-music-'));
|
||||
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
|
||||
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: 'u_m', name: 'One', created: '2026-01-01T00:00:00.000Z' }], creds: [], subs: [], invites: [] }));
|
||||
const port = await freePort();
|
||||
const child = spawn(process.execPath, ['server.js'], {
|
||||
cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
|
||||
});
|
||||
const h = { api: `http://127.0.0.1:${port}`, log: '' };
|
||||
child.stdout.on('data', d => h.log += d);
|
||||
child.stderr.on('data', d => h.log += d);
|
||||
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
|
||||
let up = false;
|
||||
for (let i = 0; i < 100 && !up; i++) {
|
||||
try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
|
||||
if (!up) await new Promise(r => setTimeout(r, 100));
|
||||
}
|
||||
assert.ok(up, `server never came up:\n${h.log}`);
|
||||
return h;
|
||||
}
|
||||
|
||||
const lookup = (h, url, headers = cookie('u_m')) => fetch(`${h.api}/api/music/lookup`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin', ...headers },
|
||||
body: JSON.stringify({ url })
|
||||
});
|
||||
|
||||
test('the lookup needs a session', async t => {
|
||||
const h = await startServer(t);
|
||||
const r = await fetch(`${h.api}/api/music/lookup`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: 'https://music.apple.com/us/playlist/x/pl.1' })
|
||||
});
|
||||
assert.equal(r.status, 401);
|
||||
});
|
||||
|
||||
test('it refuses anything that is not an Apple Music link, before any request is made', async t => {
|
||||
const h = await startServer(t);
|
||||
// The api container sits on the owner's network. Every one of these would be a request forged
|
||||
// from the container if the host were not checked, so each is a 400 and none of them is fetched.
|
||||
for (const url of [
|
||||
'http://127.0.0.1:3000/api/health',
|
||||
'http://169.254.169.254/latest/meta-data/',
|
||||
'http://192.168.1.1/',
|
||||
'https://music.apple.com.evil.test/us/playlist/x/pl.1',
|
||||
'http://music.apple.com/us/playlist/x/pl.1', // plain http, even on the right host
|
||||
'https://open.spotify.com/playlist/37i9dQZF1DXcBWIGoYBM5M',
|
||||
'not a url', '', null
|
||||
]) {
|
||||
const r = await lookup(h, url);
|
||||
assert.equal(r.status, 400, `${url} should be refused`);
|
||||
assert.match((await r.json()).error, /Apple Music/);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user