Files
tv/src/media/proxy.js
T
2026-10-27 05:49:38 -05:00

253 lines
9.7 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Path-based signed media proxy: /v1/p/<token>/<upstream path+query>, token = { o: origin, h: headers }.
// Relative URIs inside playlists resolve to the same token by themselves, so only absolute,
// root-relative, parent-relative or post-redirect URIs get rewritten.
const { pipeline } = require('stream');
const { sign, verify } = require('../sign');
const { send, error, CORS } = require('../http');
const { fetchUpstream, readBody, cleanHeaders, LRU } = require('./net');
const playlistCache = new LRU(300); // key -> { status, body, ct, cc }
const smallCache = new LRU(500); // key -> { status, headers, body }
const inflight = new Map();
const SMALL_MAX = 64 * 1024;
const stats = { active: 0, total: 0, playlistHits: 0, smallHits: 0, errors: 0 };
const M3U8_PATH = /\.m3u8?$/i;
const SNIFF_CT = /^(text\/|application\/octet-stream|binary\/octet-stream|application\/x-mpegurl|application\/vnd\.apple\.mpegurl|audio\/x?-?mpegurl|$)/i;
// Rewrite URIs that would not resolve to the right place relative to the proxied playlist URL.
function rewriteM3u8(text, { base, force, toProxy }) {
const fix = (uri) => {
const u = uri.trim();
if (!u || u.startsWith('data:') || u.startsWith('skd:')) return uri;
const needs = force || /^[a-z][a-z0-9+.-]*:/i.test(u) || u.startsWith('/') || u.startsWith('../');
if (!needs) return uri;
try {
const abs = new URL(u, base);
if (abs.protocol !== 'http:' && abs.protocol !== 'https:') return uri;
return toProxy(abs);
} catch {
return uri;
}
};
return text
.split(/\r?\n/)
.map((line) => {
const t = line.trim();
if (!t) return line;
if (t.startsWith('#')) return line.replace(/(URI\s*=\s*)(?:"([^"]*)"|'([^']*)')/gi, (m, p, d, s) => `${p}"${fix(d ?? s)}"`);
return fix(t);
})
.join('\n');
}
function playlistKind(text) {
if (/#EXT-X-STREAM-INF|#EXT-X-MEDIA:/i.test(text)) return 'master';
if (/#EXT-X-ENDLIST|#EXT-X-PLAYLIST-TYPE:\s*VOD/i.test(text)) return 'vod';
return 'live';
}
function copyHeaders(up, decoded) {
const out = { ...CORS };
for (const k of ['content-type', 'content-range', 'accept-ranges', 'last-modified', 'etag']) if (up[k]) out[k] = up[k];
if (!decoded) {
if (up['content-length']) out['content-length'] = up['content-length'];
if (up['content-encoding']) out['content-encoding'] = up['content-encoding'];
}
return out;
}
/**
* Proxy one request.
* opts: { origin, headers, rest (path+query after origin, no leading '/'), prefix (string to reach
* `<base>/v1/p/` from the playlist's directory), force (rewrite every URI) }
*/
async function proxy(req, res, opts) {
const headers = cleanHeaders(opts.headers);
let target;
try {
const o = new URL(opts.origin);
if (o.protocol !== 'http:' && o.protocol !== 'https:') throw new Error('bad origin');
target = new URL(`${o.origin}/${opts.rest}`);
} catch {
return error(req, res, 400, 'invalid upstream');
}
const range = req.headers.range;
const method = req.method === 'HEAD' ? 'HEAD' : 'GET';
const looksPlaylist = M3U8_PATH.test(target.pathname);
const toProxy = (abs) => `${opts.prefix}${sign({ o: abs.origin, h: headers })}${abs.pathname}${abs.search}`;
const plKey = `${req.url}`;
const smallKey = `${target}|${JSON.stringify(headers)}`;
stats.total++;
// cached playlist / small file
if (!range) {
const pl = playlistCache.get(plKey);
if (pl) {
stats.playlistHits++;
return send(req, res, pl.status, pl.body, pl.ct, { 'Cache-Control': pl.cc });
}
const sm = smallCache.get(smallKey);
if (sm) {
stats.smallHits++;
res.writeHead(sm.status, { ...sm.headers, 'Content-Length': sm.body.length });
return res.end(method === 'HEAD' ? undefined : sm.body);
}
}
// coalesce concurrent playlist fetches (many players poll the same live playlist)
if (looksPlaylist && !range && method === 'GET' && inflight.has(plKey)) {
try {
await inflight.get(plKey);
} catch {}
const pl = playlistCache.get(plKey);
if (pl) return send(req, res, pl.status, pl.body, pl.ct, { 'Cache-Control': pl.cc });
}
const ac = new AbortController();
const onClose = () => {
if (!res.writableFinished) ac.abort();
};
res.on('close', onClose);
const upHeaders = { ...headers, 'accept-encoding': looksPlaylist ? 'gzip, br' : 'identity' };
if (range) upHeaders.range = range;
if (req.headers['if-range']) upHeaders['if-range'] = req.headers['if-range'];
stats.active++;
let done;
if (looksPlaylist && !range && method === 'GET') inflight.set(plKey, new Promise((r) => (done = r)));
try {
let up;
try {
up = await fetchUpstream(target, { headers: upHeaders, method, signal: ac.signal });
} catch (e) {
if (ac.signal.aborted) return;
stats.errors++;
if (e.code === 'EBLOCKED' || e.code === 'EPROTO') return error(req, res, 403, e.message);
return error(req, res, 502, `upstream failed: ${e.message}`);
}
const ct = String(up.headers['content-type'] || '');
const redirected = up.url !== target.toString();
const len = Number(up.headers['content-length'] || NaN);
let playlist = /mpegurl/i.test(ct) || (looksPlaylist && up.statusCode < 400);
let first = null;
if (!playlist && method === 'GET' && !range && up.statusCode === 200 && SNIFF_CT.test(ct) && !(len > 4 * 1024 * 1024)) {
// peek at the first chunk to detect disguised playlists
first = await new Promise((resolve, reject) => {
const onData = (c) => {
cleanup();
up.body.pause();
resolve(c);
};
const onEnd = () => (cleanup(), resolve(Buffer.alloc(0)));
const onErr = (e) => (cleanup(), reject(e));
const cleanup = () => {
up.body.off('data', onData);
up.body.off('end', onEnd);
up.body.off('error', onErr);
};
up.body.on('data', onData).on('end', onEnd).on('error', onErr);
}).catch(() => null);
if (first === null) return error(req, res, 502, 'upstream read failed');
const head = first.subarray(0, 16).toString('utf8').replace(/^/, '').trimStart();
if (head.startsWith('#EXTM3U') || (first[0] === 0x1f && first[1] === 0x8b && looksPlaylist)) playlist = true;
}
if (playlist && method === 'GET') {
let buf;
try {
if (first) up.body.unshift(first);
buf = await readBody(up, 8 * 1024 * 1024);
} catch (e) {
if (ac.signal.aborted) return;
return error(req, res, 502, `playlist read failed: ${e.message}`);
}
const text = buf.toString('utf8').replace(/^/, '');
if (!text.trimStart().startsWith('#EXTM3U') || up.statusCode >= 400) {
return send(req, res, up.statusCode, buf, ct || 'text/plain; charset=utf-8');
}
const body = rewriteM3u8(text, { base: up.url, force: opts.force || redirected, toProxy });
const kind = playlistKind(text);
const cc = kind === 'live' ? 'no-store' : 'public, max-age=30';
const ctOut = 'application/vnd.apple.mpegurl; charset=utf-8';
playlistCache.set(plKey, { status: up.statusCode, body, ct: ctOut, cc }, kind === 'live' ? 3000 : 120000);
return send(req, res, up.statusCode, body, ctOut, { 'Cache-Control': cc });
}
const out = copyHeaders(up.headers, false);
out['cache-control'] = up.statusCode === 200 || up.statusCode === 206 ? 'public, max-age=3600' : 'no-store';
if (!out['accept-ranges'] && up.statusCode === 200) out['accept-ranges'] = 'none';
// tiny non-range files (AES keys, init segments): buffer + cache
if (!range && method === 'GET' && up.statusCode === 200 && len <= SMALL_MAX && !up.headers['content-encoding']) {
const chunks = first ? [first] : [];
for await (const c of up.body) chunks.push(c);
const body = Buffer.concat(chunks);
delete out['content-length'];
smallCache.set(smallKey, { status: 200, headers: out, body }, 10 * 60 * 1000);
res.writeHead(200, { ...out, 'Content-Length': body.length });
return res.end(body);
}
res.writeHead(up.statusCode, out);
if (method === 'HEAD') {
up.body.destroy();
return res.end();
}
if (first) {
if (!res.write(first)) await new Promise((r) => res.once('drain', r));
}
await new Promise((resolve) => {
pipeline(up.body, res, () => resolve());
});
} finally {
stats.active--;
res.off('close', onClose);
if (done) {
inflight.delete(plKey);
done();
}
}
}
// /v1/p/<token>/<rest>
async function handlePath(req, res) {
const m = req.url.match(/^\/v1\/p\/([^/?]+)\/([^]*)$/);
if (!m) return error(req, res, 400, 'bad proxy path');
const tok = verify(m[1]);
if (!tok || typeof tok.o !== 'string') return error(req, res, 403, 'invalid token');
const rest = m[2];
const depth = rest.split('?')[0].split('/').length;
return proxy(req, res, { origin: tok.o, headers: tok.h, rest, prefix: '../'.repeat(depth) });
}
// legacy /proxy/media?url=&h=<json>
async function handleLegacy(req, res, ctx) {
const target = (ctx.url.searchParams.get('url') || '').trim();
let u;
try {
u = new URL(target);
} catch {
return error(req, res, 400, 'missing or invalid ?url=');
}
if (u.protocol !== 'http:' && u.protocol !== 'https:') return error(req, res, 400, 'proxy only supports http/https');
let h = {};
try {
h = JSON.parse(ctx.url.searchParams.get('h') || '{}');
} catch {}
return proxy(req, res, {
origin: u.origin,
headers: h,
rest: `${u.pathname.slice(1)}${u.search}`,
prefix: '../v1/p/', // playlist URL dir is <base>/proxy/
force: true,
});
}
function proxyStats() {
return { ...stats, playlistCache: playlistCache.size, smallCache: smallCache.size };
}
module.exports = { proxy, handlePath, handleLegacy, rewriteM3u8, proxyStats };