From 520cba35ab178c851d5b3cc3f1af9b9af769b3f7 Mon Sep 17 00:00:00 2001 From: ArnoldDeRuiter <187004+ArnoldDeRuiter@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:58:01 +0100 Subject: [PATCH 1/8] Let vidapi fall back to hls.js on webOS --- webos/README.md | 7 ++++--- webos/js/lib/providers.js | 2 +- webos/test/browser/player.test.js | 6 +++--- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/webos/README.md b/webos/README.md index 54191714..9f99af8f 100644 --- a/webos/README.md +++ b/webos/README.md @@ -100,9 +100,10 @@ Results are from one live run in desktop Chrome, with one title per source: | sportstv | Live | Many | **Did not play**, cause not checked. The chooser appears. It also has a plain-HTTP host and one HEVC channel. | A TV takes a different path for HLS: it tries the platform's native player first, which needs no CORS, and -uses hls.js only as a fallback where the source allows it. vidapi has no fallback. Its segments are named -`.html` and sent as `text/html`, so it depends entirely on the native player accepting that. vidapi and -sportstv are the first things to try on a real TV. +uses hls.js only as a fallback where the source allows it. vidapi's segments are named `.html` and sent as +`text/html`. On an LG webOS 10.3 TV the native player rejects them at once (`MEDIA_ELEMENT_ERROR: Format +error`), while hls.js plays the same stream at 1080p; its segment host now sends `Access-Control-Allow-Origin: *`. +So vidapi falls back to hls.js. sportstv is still untried on a TV. ### Why the other 33 are left out diff --git a/webos/js/lib/providers.js b/webos/js/lib/providers.js index 7f768c57..98bfb21a 100644 --- a/webos/js/lib/providers.js +++ b/webos/js/lib/providers.js @@ -9,7 +9,7 @@ { id: 'idub', kind: 'vod', search: true, viewAll: true, related: true, hosts: /^v\.mover\.uz$/, ignoreHeaders: [], hlsjs: false }, { id: 'vidapi', kind: 'vod', search: false, viewAll: false, related: false, - hosts: null, ignoreHeaders: ['referer', 'origin', 'user-agent'], hlsjs: false }, + hosts: null, ignoreHeaders: ['referer', 'origin', 'user-agent'], hlsjs: true }, { id: 'anilibria', kind: 'vod', search: true, viewAll: true, related: true, hosts: /^cache\.libria\.fun$/, ignoreHeaders: ['user-agent'], hlsjs: true }, { id: 'animevost', kind: 'vod', search: true, viewAll: true, related: true, diff --git a/webos/test/browser/player.test.js b/webos/test/browser/player.test.js index d459c3ea..b90eaf53 100644 --- a/webos/test/browser/player.test.js +++ b/webos/test/browser/player.test.js @@ -645,8 +645,8 @@ test('webOS user agent: native HLS first through , then hls.js where the test('webOS user agent: a provider without hls.js moves on, and hls.js is never loaded', async () => { const body = { videoSources: [ - { quality: 'x', videoUrl: 'https://rotating.site/x/master', type: 'hls', headers: { Referer: 'r' } }, - { quality: 'y', videoUrl: 'https://cdn.test/y.mp4', type: 'mp4' } + { quality: 'x', videoUrl: 'https://v.mover.uz/x/master', type: 'hls' }, + { quality: 'y', videoUrl: 'https://v.mover.uz/y.mp4', type: 'mp4' } ] }; const { page, log, context } = await openApp({ userAgent: 'Mozilla/5.0 (Web0S; Linux/SmartTV) Chrome/53.0 WebAppManager', @@ -654,7 +654,7 @@ test('webOS user agent: a provider without hls.js moves on, and hls.js is never media: (u) => (u.includes('y.mp4') ? 'clip' : null) }); await waitFocus(page, /Title 5000/); - await page.evaluate(() => window.Sozo.Player.play({ provider: 'vidapi', contentUrl: 'x', title: 'A', isSerial: true, episode: { mediaRef: 'r', episode: 1, season: 1 }, episodes: [], startPosition: 0 })); + await page.evaluate(() => window.Sozo.Player.play({ provider: 'idub', contentUrl: 'x', title: 'A', isSerial: true, episode: { mediaRef: 'r', episode: 1, season: 1 }, episodes: [], startPosition: 0 })); await waitPlaying(page); assert.equal(await page.evaluate(() => !!window.Hls), false); noErrors(log); From e0bb3fc738a07a7b2e6eb1afca3c990fc25c1365 Mon Sep 17 00:00:00 2001 From: ArnoldDeRuiter <187004+ArnoldDeRuiter@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:12:16 +0100 Subject: [PATCH 2/8] Play vidapi natively on webOS through a loopback relay that fixes segment content types --- webos/README.md | 23 ++++- webos/index.html | 1 + webos/js/app.js | 2 + webos/js/lib/providers.js | 2 +- webos/js/lib/relabel.js | 47 +++++++++++ webos/js/player.js | 8 +- webos/service/package.json | 5 ++ webos/service/proxy.js | 135 ++++++++++++++++++++++++++++++ webos/service/service.js | 29 +++++++ webos/service/services.json | 13 +++ webos/test/browser/player.test.js | 36 ++++++++ webos/test/package.test.js | 11 +++ webos/test/relay.test.js | 122 +++++++++++++++++++++++++++ webos/tools/package.js | 30 +++++-- webos/tools/stage.js | 15 +++- 15 files changed, 467 insertions(+), 12 deletions(-) create mode 100644 webos/js/lib/relabel.js create mode 100644 webos/service/package.json create mode 100644 webos/service/proxy.js create mode 100644 webos/service/service.js create mode 100644 webos/service/services.json create mode 100644 webos/test/relay.test.js diff --git a/webos/README.md b/webos/README.md index 9f99af8f..552c191c 100644 --- a/webos/README.md +++ b/webos/README.md @@ -26,9 +26,11 @@ npm ci --ignore-scripts npm run package ``` -This copies only the shipped files to `dist/app`, runs `ares-package --check`, and writes -`dist/ipk/com.soplay.sozo.webos_1.0.0_all.ipk` (about 241 KB). It then opens the ipk and fails unless it -holds exactly the shipped files, byte for byte. +This copies only the shipped files to `dist/app` and the relay service (`service/`) to `dist/service`, +runs `ares-package --check`, and writes `dist/ipk/com.soplay.sozo.webos_1.0.0_all.ipk` (about 246 KB). It +then opens the ipk and fails unless it holds exactly the shipped app and service files, byte for byte. +`ares-package` prints a generic Node.js version notice for any package with a service; that one notice is +allowed, because `service/` is held to ES5 by the tests. `--no-minify` is deliberate. By default `ares-package` runs terser over every `.js`, including `hls.min.js`, so the ES5 checks would no longer describe what ships. @@ -103,7 +105,20 @@ A TV takes a different path for HLS: it tries the platform's native player first uses hls.js only as a fallback where the source allows it. vidapi's segments are named `.html` and sent as `text/html`. On an LG webOS 10.3 TV the native player rejects them at once (`MEDIA_ELEMENT_ERROR: Format error`), while hls.js plays the same stream at 1080p; its segment host now sends `Access-Control-Allow-Origin: *`. -So vidapi falls back to hls.js. sportstv is still untried on a TV. +So on webOS vidapi goes through the relay below, with hls.js as the fallback. sportstv is still untried on a TV. + +### Native HLS relay (webOS only) + +The ipk carries a small JS service, `com.soplay.sozo.webos.service` (`service/`). At startup the app +subscribes to it through `PalmServiceBridge`; the service listens on `127.0.0.1` on a free port and answers +with that port and a random per-run token. For a provider marked `relabel: true` (vidapi), the native +player is given `http://127.0.0.1://p?u=`. The service fetches the same bytes, +names them by content (`#EXTM3U` as a playlist, `0x47` as MPEG-TS, and so on) instead of trusting +`text/html`, and rewrites every playlist URI to come back through itself. Nothing is decoded or changed. + +On an LG webOS 10.3 TV a vidapi film started in 1.7 s at 1920x800 this way, and hls.js was never loaded; +plain hls.js starts on the lowest level. If the service is missing or down, the URL is left as it is, +the native player fails, and the ladder falls back to hls.js. Off webOS nothing calls the service. ### Why the other 33 are left out diff --git a/webos/index.html b/webos/index.html index d3fba43c..79be9b61 100644 --- a/webos/index.html +++ b/webos/index.html @@ -21,6 +21,7 @@ + diff --git a/webos/js/app.js b/webos/js/app.js index 45651343..283a68e7 100644 --- a/webos/js/app.js +++ b/webos/js/app.js @@ -261,6 +261,8 @@ root.addEventListener('resize', fit, false); applyLanguage(); app.api = Sozo.Api.create({ onStatus: function (ok) { setOffline(!ok); } }); + app.relabel = Sozo.Relabel.create({ isWebOS: Sozo.Platform.isWebOS(root.navigator && root.navigator.userAgent) }); + app.relabel.start(); app.topbar = Sozo.Topbar.create(app); Nav.init(doc.getElementById('app')); Nav.onBack(function () { app.back(); }); diff --git a/webos/js/lib/providers.js b/webos/js/lib/providers.js index 98bfb21a..c625b20c 100644 --- a/webos/js/lib/providers.js +++ b/webos/js/lib/providers.js @@ -9,7 +9,7 @@ { id: 'idub', kind: 'vod', search: true, viewAll: true, related: true, hosts: /^v\.mover\.uz$/, ignoreHeaders: [], hlsjs: false }, { id: 'vidapi', kind: 'vod', search: false, viewAll: false, related: false, - hosts: null, ignoreHeaders: ['referer', 'origin', 'user-agent'], hlsjs: true }, + hosts: null, ignoreHeaders: ['referer', 'origin', 'user-agent'], hlsjs: true, relabel: true }, { id: 'anilibria', kind: 'vod', search: true, viewAll: true, related: true, hosts: /^cache\.libria\.fun$/, ignoreHeaders: ['user-agent'], hlsjs: true }, { id: 'animevost', kind: 'vod', search: true, viewAll: true, related: true, diff --git a/webos/js/lib/relabel.js b/webos/js/lib/relabel.js new file mode 100644 index 00000000..f298f008 --- /dev/null +++ b/webos/js/lib/relabel.js @@ -0,0 +1,47 @@ +(function (root) { + 'use strict'; + var Sozo = root.Sozo || (root.Sozo = {}); + + var SERVICE = 'luna://com.soplay.sozo.webos.service/relay'; + + // webOS only: the bundled service relays HLS over loopback with corrected content types, + // so the native player can play sources whose hosts label segments as text/html. + function create(options) { + var o = options || {}; + var Bridge = o.Bridge || root.PalmServiceBridge; + var base = null; + var bridge = null; + var started = false; + + function start() { + if (started || !o.isWebOS || typeof Bridge !== 'function') return; + started = true; + try { + bridge = new Bridge(); + bridge.onservicecallback = function (text) { + var m = null; + try { m = JSON.parse(text); } catch (e) { m = null; } + if (m && m.returnValue && m.port && /^[0-9a-f]+$/.test(m.token || '')) { + base = 'http://127.0.0.1:' + m.port + '/' + m.token + '/p?u='; + } else { + base = null; + } + }; + bridge.call(SERVICE, JSON.stringify({ subscribe: true })); + } catch (e) { + bridge = null; + base = null; + } + } + + return { + start: start, + ready: function () { return base !== null; }, + wrap: function (u) { return base === null ? u : base + encodeURIComponent(u); } + }; + } + + var api = { create: create, SERVICE: SERVICE }; + Sozo.Relabel = api; + if (typeof module !== 'undefined' && module.exports) module.exports = api; +}(typeof window !== 'undefined' ? window : global)); diff --git a/webos/js/player.js b/webos/js/player.js index 5ae758e8..9361ba2f 100644 --- a/webos/js/player.js +++ b/webos/js/player.js @@ -756,7 +756,7 @@ // A failing reports here, not on the video element. child.onerror = function () { if (id === token) fail({}); }; child.type = 'application/x-mpegURL'; - child.src = source.url; + child.src = relabelled(source.url); video.appendChild(child); video.load(); doPlay(); @@ -767,6 +767,12 @@ } } + // Native HLS through the loopback relay where the provider's hosts mislabel segments. + function relabelled(u) { + var r = app && app.relabel; + return provider.relabel === true && r && r.ready() ? r.wrap(u) : u; + } + function fail(info) { if (!open || !ladder || failedToken === token) return; failedToken = token; diff --git a/webos/service/package.json b/webos/service/package.json new file mode 100644 index 00000000..cfc82a8e --- /dev/null +++ b/webos/service/package.json @@ -0,0 +1,5 @@ +{ + "name": "com.soplay.sozo.webos.service", + "version": "1.0.0", + "main": "service.js" +} diff --git a/webos/service/proxy.js b/webos/service/proxy.js new file mode 100644 index 00000000..9002302f --- /dev/null +++ b/webos/service/proxy.js @@ -0,0 +1,135 @@ +'use strict'; +// Loopback HLS relay for the webOS native player: same bytes, corrected content types. +var http = require('http'); +var https = require('https'); +var url = require('url'); +var crypto = require('crypto'); + +var PLAYLIST = 'application/vnd.apple.mpegurl'; +var MAX_PLAYLIST = 4 * 1024 * 1024; +var MAX_REDIRECTS = 5; +var TIMEOUT = 20000; +var UA = 'Mozilla/5.0 (Web0S; Linux/SmartTV) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36'; + +function isUpstream(u) { + return /^https?:\/\/[^\/\s]+/i.test(u || ''); +} + +// Media type from the first bytes, so a segment sent as text/html still reaches the player as video. +function sniff(head, upstreamType) { + var b = head || []; + var text = ''; + for (var i = 0; i < Math.min(b.length, 16); i++) text += String.fromCharCode(b[i]); + if (/^\s*#EXTM3U/.test(text)) return PLAYLIST; + if (b[0] === 0x47) return 'video/mp2t'; + if (text.slice(4, 8) === 'ftyp' || text.slice(4, 8) === 'styp' || text.slice(4, 8) === 'moof') return 'video/mp4'; + if (text.slice(0, 3) === 'ID3' || (b[0] === 0xff && (b[1] & 0xf6) === 0xf0)) return 'audio/aac'; + var t = String(upstreamType || '').split(';')[0].trim().toLowerCase(); + if (!t || t === 'text/html' || t === 'text/plain' || t === 'application/octet-stream') return 'application/octet-stream'; + return t; +} + +// Every URI in a playlist is made absolute and sent back through the relay. +function rewritePlaylist(text, base, wrap) { + return String(text).split(/\r?\n/).map(function (line) { + var s = line.trim(); + if (!s) return line; + if (s.charAt(0) !== '#') return wrap(url.resolve(base, s)); + return line.replace(/URI="([^"]*)"/g, function (m, uri) { + return 'URI="' + wrap(url.resolve(base, uri)) + '"'; + }); + }).join('\n'); +} + +function wrapper(port, token) { + return function (u) { + return 'http://127.0.0.1:' + port + '/' + token + '/p?u=' + encodeURIComponent(u); + }; +} + +function fetchUpstream(target, range, hops, cb) { + var lib = /^https:/i.test(target) ? https : http; + var opts = url.parse(target); + opts.headers = { 'User-Agent': UA, 'Accept': '*/*' }; + if (range) opts.headers.Range = range; + var done = false; + var req = lib.get(opts, function (res) { + var loc = res.headers.location; + if (res.statusCode >= 300 && res.statusCode < 400 && loc) { + res.resume(); + if (hops >= MAX_REDIRECTS) { done = true; cb(new Error('too many redirects')); return; } + done = true; + fetchUpstream(url.resolve(target, loc), range, hops + 1, cb); + return; + } + done = true; + cb(null, res, target); + }); + req.setTimeout(TIMEOUT, function () { req.abort(); }); + req.on('error', function (e) { if (!done) { done = true; cb(e); } }); + return req; +} + +function handle(req, res, token, wrap) { + var parsed = url.parse(req.url, true); + if (parsed.pathname !== '/' + token + '/p') { res.writeHead(404); res.end(); return; } + var target = String(parsed.query.u || ''); + if (!isUpstream(target)) { res.writeHead(400); res.end(); return; } + var upstream = fetchUpstream(target, req.headers.range, 0, function (err, up, finalUrl) { + if (err) { if (!res.headersSent) res.writeHead(502); res.end(); return; } + if (up.statusCode >= 400) { up.resume(); res.writeHead(up.statusCode); res.end(); return; } + var first = true; + var dead = false; + var playlist = false; + var chunks = []; + var size = 0; + up.on('data', function (chunk) { + if (dead) return; + if (first) { + first = false; + var type = sniff(chunk, up.headers['content-type']); + playlist = type === PLAYLIST; + if (!playlist) { + var h = { 'Content-Type': type, 'Access-Control-Allow-Origin': '*' }; + ['content-length', 'content-range', 'accept-ranges'].forEach(function (k) { if (up.headers[k]) h[k] = up.headers[k]; }); + res.writeHead(up.statusCode, h); + } + } + if (playlist) { + size += chunk.length; + if (size > MAX_PLAYLIST) { dead = true; up.destroy(); res.writeHead(502); res.end(); return; } + chunks.push(chunk); + } else { + res.write(chunk); + } + }); + up.on('end', function () { + if (dead) return; + if (first) { res.writeHead(up.statusCode, { 'Content-Length': '0' }); res.end(); return; } + if (!playlist) { res.end(); return; } + var body = rewritePlaylist(Buffer.concat(chunks).toString('utf8'), finalUrl, wrap); + res.writeHead(200, { 'Content-Type': PLAYLIST, 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-cache' }); + res.end(body); + }); + up.on('error', function () { if (dead) return; dead = true; if (!res.headersSent) res.writeHead(502); res.end(); }); + }); + req.on('close', function () { if (upstream) upstream.abort(); }); +} + +// Listens on loopback only, on a free port; every path carries a per-run token. +function start(cb) { + var token = crypto.randomBytes(12).toString('hex'); + var wrap = null; + var server = http.createServer(function (req, res) { + if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405); res.end(); return; } + handle(req, res, token, wrap); + }); + server.on('error', function (e) { cb(e); }); + server.listen(0, '127.0.0.1', function () { + var port = server.address().port; + wrap = wrapper(port, token); + cb(null, { port: port, token: token, server: server }); + }); +} + +module.exports = { sniff: sniff, rewritePlaylist: rewritePlaylist, wrapper: wrapper, isUpstream: isUpstream, start: start, PLAYLIST: PLAYLIST }; diff --git a/webos/service/service.js b/webos/service/service.js new file mode 100644 index 00000000..a403b59b --- /dev/null +++ b/webos/service/service.js @@ -0,0 +1,29 @@ +'use strict'; +// webOS service: starts the loopback relay and tells the app where it is. +var Service = require('webos-service'); +var proxy = require('./proxy.js'); + +var ID = 'com.soplay.sozo.webos.service'; +var service = new Service(ID); +var relay = null; +var waiting = []; + +function withRelay(cb) { + if (relay) { cb(null, relay); return; } + waiting.push(cb); + if (waiting.length > 1) return; + proxy.start(function (err, r) { + if (!err) relay = r; + var list = waiting; + waiting = []; + list.forEach(function (f) { f(err, r); }); + }); +} + +// The app holds this subscription while it runs, which keeps the service alive. +service.register('relay', function (message) { + withRelay(function (err, r) { + if (err) { message.respond({ returnValue: false, errorText: String(err.message || err) }); return; } + message.respond({ returnValue: true, port: r.port, token: r.token, subscribed: !!message.isSubscription }); + }); +}, function () {}); diff --git a/webos/service/services.json b/webos/service/services.json new file mode 100644 index 00000000..cd72e38b --- /dev/null +++ b/webos/service/services.json @@ -0,0 +1,13 @@ +{ + "id": "com.soplay.sozo.webos.service", + "description": "Loopback HLS relay so the native player gets correct content types", + "services": [ + { + "name": "com.soplay.sozo.webos.service", + "description": "Loopback HLS relay so the native player gets correct content types", + "commands": [ + { "name": "relay", "description": "Start the relay and report its port and token", "public": true } + ] + } + ] +} diff --git a/webos/test/browser/player.test.js b/webos/test/browser/player.test.js index b90eaf53..99bdbbda 100644 --- a/webos/test/browser/player.test.js +++ b/webos/test/browser/player.test.js @@ -661,6 +661,42 @@ test('webOS user agent: a provider without hls.js moves on, and hls.js is never await context.close(); }); +test('webOS: a relabel provider plays natively through the loopback relay, and others stay direct', async () => { + const init = () => { + window.__sources = []; + window.PalmServiceBridge = function () { + const self = this; + self.call = function (uri) { + window.__bridgeUri = uri; + setTimeout(() => self.onservicecallback(JSON.stringify({ returnValue: true, port: 4321, token: 'ab12' })), 0); + }; + }; + new MutationObserver((list) => list.forEach((m) => m.addedNodes.forEach((n) => { + if (n.tagName === 'SOURCE') window.__sources.push(n.src); + }))).observe(document, { childList: true, subtree: true }); + }; + const hls = 'https://seg.example/x/master'; + const libria = 'https://cache.libria.fun/y/master.m3u8'; + const { page, context } = await openApp({ + userAgent: 'Mozilla/5.0 (Web0S; Linux/SmartTV) Chrome/120.0 WebAppManager', + init, + routes: { media: (q) => ({ body: { videoSources: [{ quality: 'x', videoUrl: q.get('provider') === 'anilibria' ? libria : hls, type: 'hls' }] } }) }, + media: () => null + }); + await waitFocus(page, /Title 5000/); + await page.waitForFunction(() => window.Sozo.App.relabel.ready()); + assert.equal(await page.evaluate(() => window.__bridgeUri), 'luna://com.soplay.sozo.webos.service/relay'); + await page.evaluate(() => window.Sozo.Player.play({ provider: 'vidapi', contentUrl: 'x', title: 'A', isSerial: true, episode: { mediaRef: 'r', episode: 1, season: 1 }, episodes: [], startPosition: 0 })); + await page.waitForFunction(() => window.__sources.length > 0); + assert.equal(await page.evaluate(() => window.__sources[0]), 'http://127.0.0.1:4321/ab12/p?u=' + encodeURIComponent(hls)); + await back(page); + await page.evaluate(() => { window.__sources = []; }); + await page.evaluate(() => window.Sozo.Player.play({ provider: 'anilibria', contentUrl: 'y', title: 'B', isSerial: true, episode: { mediaRef: 'r', episode: 1, season: 1 }, episodes: [], startPosition: 0 })); + await page.waitForFunction(() => window.__sources.length > 0); + assert.equal(await page.evaluate(() => window.__sources[0]), libria, 'only providers that ask for it go through the relay'); + await context.close(); +}); + test('18+: an adult envelope title never reaches the video, and an adult request is refused', async () => { const routes = filmRoutes({ title: 'Bad XXX film', videoSources: [SRC('a')] }); const { page, log, context } = await openApp({ routes, media: () => 'clip' }); diff --git a/webos/test/package.test.js b/webos/test/package.test.js index 748045d1..1cb9da24 100644 --- a/webos/test/package.test.js +++ b/webos/test/package.test.js @@ -36,6 +36,17 @@ test('verify rejects dev files, stray files, missing files and changed bytes', ( for (const [files, want] of cases) assert.match(verify(files, ID, { 'a.js': hash }).join('\n'), want); }); +test('verify checks a packaged service byte for byte, and only the services it was told about', () => { + const SVC = 'usr/palm/services/' + ID + '.service/'; + const svc = { [ID + '.service']: { 'service.js': hash } }; + const base = { [PREFIX + 'a.js']: body }; + assert.deepStrictEqual(verify({ ...base, [SVC + 'service.js']: body }, ID, { 'a.js': hash }, svc), []); + assert.match(verify(base, ID, { 'a.js': hash }, svc).join('\n'), /missing: com\.example\.app\.service\/service\.js/); + assert.match(verify({ ...base, [SVC + 'service.js']: Buffer.from('x') }, ID, { 'a.js': hash }, svc).join('\n'), /content changed: .*service\.js/); + assert.match(verify({ ...base, [SVC + 'service.js']: body, [SVC + 'extra.js']: body }, ID, { 'a.js': hash }, svc).join('\n'), /not a shipped service file: .*extra\.js/); + assert.match(verify({ ...base, [SVC + 'service.js']: body }, ID, { 'a.js': hash }).join('\n'), /unexpected path: usr\/palm\/services/); +}); + test('readTar and readAr read names and bytes back', () => { const tar = Buffer.concat([tarEntry('./usr/a.js', body), tarEntry('./usr/b.txt', Buffer.alloc(513, 97)), Buffer.alloc(1024)]); const files = readTar(tar); diff --git a/webos/test/relay.test.js b/webos/test/relay.test.js new file mode 100644 index 00000000..f0b09016 --- /dev/null +++ b/webos/test/relay.test.js @@ -0,0 +1,122 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('fs'); +const http = require('http'); +const path = require('path'); +const acorn = require('acorn'); +const { ROOT } = require('./helper.js'); +const proxy = require('../service/proxy.js'); +const Relabel = require('../js/lib/relabel.js'); + +const TS = Buffer.concat([Buffer.from([0x47, 0x40, 0x00, 0x10]), Buffer.alloc(184, 0xff)]); + +test('sniff names media by its bytes, not by a text/html label', () => { + assert.equal(proxy.sniff(Buffer.from('#EXTM3U\n'), 'text/html'), proxy.PLAYLIST); + assert.equal(proxy.sniff(TS, 'text/html; charset=UTF-8'), 'video/mp2t'); + assert.equal(proxy.sniff(Buffer.from('\0\0\0\x18ftypisom'), 'text/html'), 'video/mp4'); + assert.equal(proxy.sniff(Buffer.from('ID3\x04'), 'text/html'), 'audio/aac'); + assert.equal(proxy.sniff(Buffer.from(''), 'text/html'), 'application/octet-stream'); + assert.equal(proxy.sniff(Buffer.from('WEBVTT'), 'text/vtt'), 'text/vtt'); +}); + +test('rewritePlaylist sends every URI, relative or absolute, back through the relay', () => { + const wrap = (u) => 'R(' + u + ')'; + const text = '#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI="key.bin"\n#EXT-X-MAP:URI="/init.mp4"\n#EXTINF:6,\nseg0.html\n\nhttps://cdn.test/seg1.html\n#EXT-X-ENDLIST'; + const out = proxy.rewritePlaylist(text, 'https://a.test/x/pl/index.m3u8', wrap).split('\n'); + assert.equal(out[1], '#EXT-X-KEY:METHOD=AES-128,URI="R(https://a.test/x/pl/key.bin)"'); + assert.equal(out[2], '#EXT-X-MAP:URI="R(https://a.test/init.mp4)"'); + assert.equal(out[4], 'R(https://a.test/x/pl/seg0.html)'); + assert.equal(out[5], ''); + assert.equal(out[6], 'R(https://cdn.test/seg1.html)'); + assert.equal(out[7], '#EXT-X-ENDLIST'); +}); + +test('isUpstream takes only http(s) URLs with a host', () => { + assert.equal(proxy.isUpstream('https://a.test/x'), true); + assert.equal(proxy.isUpstream('http://a.test'), true); + assert.equal(proxy.isUpstream('file:///etc/passwd'), false); + assert.equal(proxy.isUpstream('https:///x'), false); + assert.equal(proxy.isUpstream(''), false); +}); + +function listen(server) { + return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server.address().port))); +} + +test('relay: a host that labels everything text/html comes out as a playlist and video, on loopback only', async () => { + const upstream = http.createServer((req, res) => { + if (req.url === '/moved') { res.writeHead(302, { Location: '/pl/master' }); res.end(); return; } + if (req.url === '/pl/master') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nv/index\n'); return; } + if (req.url === '/pl/v/index') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('#EXTM3U\n#EXTINF:6,\nseg0.html\n#EXT-X-ENDLIST\n'); return; } + if (req.url === '/pl/v/seg0.html') { + if (req.headers.range === 'bytes=0-187') { res.writeHead(206, { 'Content-Type': 'text/html', 'Content-Range': 'bytes 0-187/188', 'Content-Length': '188' }); res.end(TS); return; } + res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': String(TS.length) }); res.end(TS); return; + } + res.writeHead(404); res.end(); + }); + const upPort = await listen(upstream); + const relay = await new Promise((resolve, reject) => proxy.start((err, r) => (err ? reject(err) : resolve(r)))); + try { + assert.equal(relay.server.address().address, '127.0.0.1'); + const wrap = proxy.wrapper(relay.port, relay.token); + const master = await fetch(wrap('http://127.0.0.1:' + upPort + '/moved')); + assert.equal(master.headers.get('content-type'), proxy.PLAYLIST); + const variantUrl = (await master.text()).split('\n').find((l) => l.startsWith('http')); + assert.equal(variantUrl, wrap('http://127.0.0.1:' + upPort + '/pl/v/index'), 'resolved against the redirect target'); + const segUrl = (await (await fetch(variantUrl)).text()).split('\n').find((l) => l.startsWith('http')); + const seg = await fetch(segUrl); + assert.equal(seg.headers.get('content-type'), 'video/mp2t'); + assert.deepEqual(Buffer.from(await seg.arrayBuffer()), TS); + const part = await fetch(segUrl, { headers: { Range: 'bytes=0-187' } }); + assert.equal(part.status, 206); + assert.equal(part.headers.get('content-range'), 'bytes 0-187/188'); + assert.equal((await fetch('http://127.0.0.1:' + relay.port + '/wrongtoken/p?u=' + encodeURIComponent('http://127.0.0.1:' + upPort + '/pl/master'))).status, 404); + assert.equal((await fetch(wrap('file:///etc/passwd'))).status, 400); + assert.equal((await fetch(wrap('http://127.0.0.1:' + upPort + '/nope'))).status, 404); + } finally { + relay.server.close(); + upstream.close(); + } +}); + +test('Relabel: off the TV it never calls the bridge and leaves URLs alone', () => { + let made = 0; + function Bridge() { made++; } + const r = Relabel.create({ isWebOS: false, Bridge }); + r.start(); + assert.equal(made, 0); + assert.equal(r.ready(), false); + assert.equal(r.wrap('https://a.test/x'), 'https://a.test/x'); +}); + +test('Relabel: on webOS it subscribes once and wraps URLs after the service answers', () => { + const calls = []; + let inst = null; + function Bridge() { inst = this; this.call = (uri, params) => calls.push([uri, JSON.parse(params)]); } + const r = Relabel.create({ isWebOS: true, Bridge }); + r.start(); + r.start(); + assert.deepEqual(calls, [[Relabel.SERVICE, { subscribe: true }]]); + assert.equal(r.ready(), false); + inst.onservicecallback(JSON.stringify({ returnValue: true, port: 4321, token: 'ab12' })); + assert.equal(r.wrap('https://a.test/x?y=1'), 'http://127.0.0.1:4321/ab12/p?u=https%3A%2F%2Fa.test%2Fx%3Fy%3D1'); + inst.onservicecallback(JSON.stringify({ returnValue: false, errorText: 'gone' })); + assert.equal(r.ready(), false, 'a failure falls back to the plain URL'); + inst.onservicecallback('not json'); + assert.equal(r.wrap('https://a.test/x'), 'https://a.test/x'); + inst.onservicecallback(JSON.stringify({ returnValue: true, port: 1, token: '../x' })); + assert.equal(r.ready(), false, 'a token is hex only'); +}); + +test('the relay service is ES5 for the oldest webOS Node, and its id matches the app', () => { + for (const f of fs.readdirSync(path.join(ROOT, 'service')).filter((n) => n.endsWith('.js'))) { + assert.doesNotThrow(() => acorn.parse(fs.readFileSync(path.join(ROOT, 'service', f), 'utf8'), { ecmaVersion: 5, sourceType: 'script' }), f); + } + const app = JSON.parse(fs.readFileSync(path.join(ROOT, 'appinfo.json'), 'utf8')).id; + const svc = JSON.parse(fs.readFileSync(path.join(ROOT, 'service', 'services.json'), 'utf8')); + assert.equal(svc.id, app + '.service'); + assert.equal(svc.services[0].name, svc.id); + assert.equal(JSON.parse(fs.readFileSync(path.join(ROOT, 'service', 'package.json'), 'utf8')).name, svc.id); + assert.equal(Relabel.SERVICE, 'luna://' + svc.id + '/relay'); +}); diff --git a/webos/tools/package.js b/webos/tools/package.js index a07f18f9..8faa18d4 100644 --- a/webos/tools/package.js +++ b/webos/tools/package.js @@ -6,11 +6,12 @@ const path = require('path'); const zlib = require('zlib'); const { spawnSync } = require('child_process'); const { ROOT } = require('../test/helper.js'); -const { DIST: APP, stage } = require('./stage.js'); +const { DIST: APP, SERVICE_DIST: SVC, stage, stageService } = require('./stage.js'); const OUT = path.join(ROOT, 'dist', 'ipk'); const ARES = path.join(ROOT, 'node_modules', '@webos-tools', 'cli', 'bin', 'ares-package.js'); const INSTALL_ROOT = 'usr/palm/applications/'; +const SERVICE_ROOT = 'usr/palm/services/'; const FORBIDDEN = /(^|\/)(test|tests|tools|node_modules|dist|package\.json|package-lock\.json|\.[^/]+)(\/|$)/; function ares(args) { @@ -67,12 +68,23 @@ function dataFiles(ipkPath) { } // Returns problems. A package may hold the shipped files, byte for byte, and packageinfo.json. -function verify(files, appId, expected) { +// services: {serviceId: {file: sha256}} for services packaged next to the app. +function verify(files, appId, expected, services) { const prefix = INSTALL_ROOT + appId + '/'; + const svc = services || {}; + const svcSeen = {}; const seen = new Set(); const problems = []; for (const name of Object.keys(files)) { if (name === 'usr/palm/packages/' + appId + '/packageinfo.json') continue; + const sid = Object.keys(svc).find((id) => name.startsWith(SERVICE_ROOT + id + '/')); + if (sid) { + const srel = name.slice((SERVICE_ROOT + sid + '/').length); + (svcSeen[sid] = svcSeen[sid] || new Set()).add(srel); + if (!Object.prototype.hasOwnProperty.call(svc[sid], srel)) problems.push('not a shipped service file: ' + sid + '/' + srel); + else if (svc[sid][srel] !== crypto.createHash('sha256').update(files[name]).digest('hex')) problems.push('content changed: ' + sid + '/' + srel); + continue; + } if (!name.startsWith(prefix)) { problems.push('unexpected path: ' + name); continue; } const rel = name.slice(prefix.length); seen.add(rel); @@ -81,6 +93,9 @@ function verify(files, appId, expected) { else if (expected[rel] !== crypto.createHash('sha256').update(files[name]).digest('hex')) problems.push('content changed: ' + rel); } for (const rel of Object.keys(expected)) if (!seen.has(rel)) problems.push('missing: ' + rel); + for (const sid of Object.keys(svc)) { + for (const rel of Object.keys(svc[sid])) if (!(svcSeen[sid] && svcSeen[sid].has(rel))) problems.push('missing: ' + sid + '/' + rel); + } return problems; } @@ -88,20 +103,25 @@ function main() { fs.rmSync(path.join(ROOT, 'dist'), { recursive: true, force: true }); const expected = {}; for (const f of stage()) expected[f] = crypto.createHash('sha256').update(fs.readFileSync(path.join(APP, f))).digest('hex'); + const svcFiles = {}; + for (const f of stageService()) svcFiles[f] = crypto.createHash('sha256').update(fs.readFileSync(path.join(SVC, f))).digest('hex'); + const svcId = JSON.parse(fs.readFileSync(path.join(SVC, 'services.json'), 'utf8')).id; fs.mkdirSync(OUT, { recursive: true }); ares(['--check', APP]); // Without --no-minify, terser rewrites every .js, the vendored hls.js included, and the // ES5 checks would no longer describe what ships. - const log = ares(['--no-minify', '-o', OUT, APP]); - if (/\[Warning\]/.test(log)) throw new Error('ares-package warned, see above'); + const log = ares(['--no-minify', '-o', OUT, APP, SVC]); + // Any service triggers ares-package's generic Node.js version notice; service/ is held to ES5 instead. + const warnings = log.split('\n').filter((l) => /\[Warning\]/.test(l) && !/Node\.js version available on the target device/.test(l)); + if (warnings.length) throw new Error('ares-package warned, see above'); const ipks = fs.readdirSync(OUT).filter((f) => f.endsWith('.ipk')); if (ipks.length !== 1) throw new Error('expected one ipk, found ' + ipks.length); const ipk = path.join(OUT, ipks[0]); const appId = JSON.parse(fs.readFileSync(path.join(APP, 'appinfo.json'), 'utf8')).id; const files = dataFiles(ipk); - const problems = verify(files, appId, expected); + const problems = verify(files, appId, expected, { [svcId]: svcFiles }); if (problems.length) throw new Error('bad package:\n ' + problems.join('\n ')); console.log(Object.keys(files).sort().join('\n')); diff --git a/webos/tools/stage.js b/webos/tools/stage.js index b48dc0cd..e80c659e 100644 --- a/webos/tools/stage.js +++ b/webos/tools/stage.js @@ -5,6 +5,8 @@ const path = require('path'); const { ROOT, shippedFiles } = require('../test/helper.js'); const DIST = path.join(ROOT, 'dist', 'app'); +const SERVICE_SRC = path.join(ROOT, 'service'); +const SERVICE_DIST = path.join(ROOT, 'dist', 'service'); function stage() { fs.rmSync(DIST, { recursive: true, force: true }); @@ -17,9 +19,20 @@ function stage() { return files; } +// The loopback relay service ships next to the app; every file in service/ goes in. +function stageService() { + fs.rmSync(SERVICE_DIST, { recursive: true, force: true }); + const files = fs.readdirSync(SERVICE_SRC).filter((f) => fs.statSync(path.join(SERVICE_SRC, f)).isFile()).sort(); + fs.mkdirSync(SERVICE_DIST, { recursive: true }); + for (const f of files) fs.copyFileSync(path.join(SERVICE_SRC, f), path.join(SERVICE_DIST, f)); + return files; +} + if (require.main === module) { stage(); + stageService(); console.log(DIST); + console.log(SERVICE_DIST); } -module.exports = { DIST, stage }; +module.exports = { DIST, SERVICE_DIST, stage, stageService }; From 0b0eb1aac2bcb623c972e9d142681ec77a701cea Mon Sep 17 00:00:00 2001 From: ArnoldDeRuiter <187004+ArnoldDeRuiter@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:05:20 +0100 Subject: [PATCH 3/8] Restrict the relay to Sozo and public hosts, pipe segments, abort redirected requests --- webos/service/proxy.js | 165 +++++++++++++++++++++++++++++---------- webos/service/service.js | 7 +- webos/test/relay.test.js | 89 ++++++++++++++++++++- 3 files changed, 216 insertions(+), 45 deletions(-) diff --git a/webos/service/proxy.js b/webos/service/proxy.js index 9002302f..01dc749d 100644 --- a/webos/service/proxy.js +++ b/webos/service/proxy.js @@ -4,6 +4,8 @@ var http = require('http'); var https = require('https'); var url = require('url'); var crypto = require('crypto'); +var dns = require('dns'); +var net = require('net'); var PLAYLIST = 'application/vnd.apple.mpegurl'; var MAX_PLAYLIST = 4 * 1024 * 1024; @@ -47,9 +49,58 @@ function wrapper(port, token) { }; } -function fetchUpstream(target, range, hops, cb) { +// Public internet only: loopback, private, link-local, CGNAT, multicast and reserved ranges are refused. +function isPublicAddress(ip) { + var v = String(ip || '').toLowerCase(); + var mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v); + if (mapped) v = mapped[1]; + if (net.isIPv4(v)) { + var o = v.split('.').map(Number); + if (o[0] === 0 || o[0] === 10 || o[0] === 127 || o[0] >= 224) return false; + if (o[0] === 100 && o[1] >= 64 && o[1] <= 127) return false; + if (o[0] === 169 && o[1] === 254) return false; + if (o[0] === 172 && o[1] >= 16 && o[1] <= 31) return false; + if (o[0] === 192 && (o[1] === 168 || (o[1] === 0 && (o[2] === 0 || o[2] === 2)))) return false; + if (o[0] === 198 && (o[1] === 18 || o[1] === 19 || (o[1] === 51 && o[2] === 100))) return false; + if (o[0] === 203 && o[1] === 0 && o[2] === 113) return false; + return true; + } + if (net.isIPv6(v)) { + if (v === '::' || v === '::1') return false; + if (/^f[cd]/.test(v) || /^fe[89ab]/.test(v) || /^ff/.test(v)) return false; + if (/^2001:0?db8:/.test(v) || /^64:ff9b:/.test(v) || /^::/.test(v)) return false; + return true; + } + return false; +} + +// dns.lookup that fails for any non-public answer; checked at connect time, so DNS rebinding cannot slip past. +function publicLookup(isPublic) { + return function (hostname, options, cb) { + if (typeof options === 'function') { cb = options; options = {}; } + var o = typeof options === 'number' ? { family: options } : (options || {}); + dns.lookup(hostname, { family: o.family || 0, hints: o.hints || 0, all: true }, function (err, list, fam) { + if (err) { cb(err); return; } + if (typeof list === 'string') list = [{ address: list, family: fam }]; + for (var i = 0; i < list.length; i++) { + if (!isPublic(list[i].address)) { cb(new Error('refused address ' + list[i].address)); return; } + } + if (!list.length) { cb(new Error('no address')); return; } + if (o.all) cb(null, list); + else cb(null, list[0].address, list[0].family); + }); + }; +} + +// Follows redirects; hold.req is always the live request, so the caller can abort whichever hop is open. +function fetchUpstream(target, range, hops, policy, hold, cb) { var lib = /^https:/i.test(target) ? https : http; var opts = url.parse(target); + if (policy.publicOnly) { + var literal = String(opts.hostname || '').replace(/^\[|\]$/g, ''); + if (net.isIP(literal) && !policy.isPublic(literal)) { cb(new Error('refused address ' + literal)); return; } + opts.lookup = publicLookup(policy.isPublic); + } opts.headers = { 'User-Agent': UA, 'Accept': '*/*' }; if (range) opts.headers.Range = range; var done = false; @@ -57,72 +108,100 @@ function fetchUpstream(target, range, hops, cb) { var loc = res.headers.location; if (res.statusCode >= 300 && res.statusCode < 400 && loc) { res.resume(); - if (hops >= MAX_REDIRECTS) { done = true; cb(new Error('too many redirects')); return; } + req.abort(); done = true; - fetchUpstream(url.resolve(target, loc), range, hops + 1, cb); + var next = url.resolve(target, loc); + if (hops >= MAX_REDIRECTS || !isUpstream(next)) { cb(new Error('bad redirect')); return; } + if (hold.aborted) return; + fetchUpstream(next, range, hops + 1, policy, hold, cb); return; } done = true; cb(null, res, target); }); + hold.req = req; req.setTimeout(TIMEOUT, function () { req.abort(); }); req.on('error', function (e) { if (!done) { done = true; cb(e); } }); - return req; } -function handle(req, res, token, wrap) { +function sendPlaylist(up, res, finalUrl, wrap, first) { + var chunks = [first]; + var size = first.length; + var dead = false; + up.on('data', function (chunk) { + if (dead) return; + size += chunk.length; + if (size > MAX_PLAYLIST) { dead = true; up.destroy(); res.writeHead(502); res.end(); return; } + chunks.push(chunk); + }); + up.on('end', function () { + if (dead) return; + var body = rewritePlaylist(Buffer.concat(chunks).toString('utf8'), finalUrl, wrap); + res.writeHead(200, { 'Content-Type': PLAYLIST, 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-cache' }); + res.end(body); + }); + up.resume(); +} + +// Media is piped, so a slow player throttles the upstream instead of filling memory. +function sendMedia(up, res, type, first) { + var h = { 'Content-Type': type, 'Access-Control-Allow-Origin': '*' }; + ['content-length', 'content-range', 'accept-ranges'].forEach(function (k) { if (up.headers[k]) h[k] = up.headers[k]; }); + res.writeHead(up.statusCode, h); + if (res.write(first) === false) { + res.once('drain', function () { up.pipe(res); }); + } else { + up.pipe(res); + } +} + +function handle(req, res, token, wrap, policy) { var parsed = url.parse(req.url, true); if (parsed.pathname !== '/' + token + '/p') { res.writeHead(404); res.end(); return; } var target = String(parsed.query.u || ''); if (!isUpstream(target)) { res.writeHead(400); res.end(); return; } - var upstream = fetchUpstream(target, req.headers.range, 0, function (err, up, finalUrl) { - if (err) { if (!res.headersSent) res.writeHead(502); res.end(); return; } + var hold = { req: null, aborted: false }; + res.on('close', function () { + hold.aborted = true; + if (hold.req) hold.req.abort(); + }); + fetchUpstream(target, req.headers.range, 0, policy, hold, function (err, up, finalUrl) { + if (err) { + if (!res.headersSent) res.writeHead(/^refused/.test(err.message) ? 403 : 502); + res.end(); + return; + } if (up.statusCode >= 400) { up.resume(); res.writeHead(up.statusCode); res.end(); return; } - var first = true; - var dead = false; - var playlist = false; - var chunks = []; - var size = 0; - up.on('data', function (chunk) { - if (dead) return; - if (first) { - first = false; - var type = sniff(chunk, up.headers['content-type']); - playlist = type === PLAYLIST; - if (!playlist) { - var h = { 'Content-Type': type, 'Access-Control-Allow-Origin': '*' }; - ['content-length', 'content-range', 'accept-ranges'].forEach(function (k) { if (up.headers[k]) h[k] = up.headers[k]; }); - res.writeHead(up.statusCode, h); - } - } - if (playlist) { - size += chunk.length; - if (size > MAX_PLAYLIST) { dead = true; up.destroy(); res.writeHead(502); res.end(); return; } - chunks.push(chunk); - } else { - res.write(chunk); - } + up.on('error', function () { if (!res.headersSent) res.writeHead(502); res.end(); }); + var got = false; + up.once('data', function (first) { + got = true; + up.pause(); + var type = sniff(first, up.headers['content-type']); + if (type === PLAYLIST) sendPlaylist(up, res, finalUrl, wrap, first); + else sendMedia(up, res, type, first); }); - up.on('end', function () { - if (dead) return; - if (first) { res.writeHead(up.statusCode, { 'Content-Length': '0' }); res.end(); return; } - if (!playlist) { res.end(); return; } - var body = rewritePlaylist(Buffer.concat(chunks).toString('utf8'), finalUrl, wrap); - res.writeHead(200, { 'Content-Type': PLAYLIST, 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-cache' }); - res.end(body); + up.once('end', function () { + if (!got) { res.writeHead(up.statusCode, { 'Content-Length': '0' }); res.end(); } }); - up.on('error', function () { if (dead) return; dead = true; if (!res.headersSent) res.writeHead(502); res.end(); }); }); - req.on('close', function () { if (upstream) upstream.abort(); }); +} + +// webos-service puts the calling app's id (WAM's pid already split off) or service name in message.sender. +function callerAllowed(sender, appId) { + return typeof sender === 'string' && sender === appId; } // Listens on loopback only, on a free port; every path carries a per-run token. -function start(cb) { +// options.allowPrivate and options.isPublic are for tests against a local upstream; the service sets neither. +function start(cb, options) { + var o = options || {}; + var policy = { publicOnly: !o.allowPrivate, isPublic: o.isPublic || isPublicAddress }; var token = crypto.randomBytes(12).toString('hex'); var wrap = null; var server = http.createServer(function (req, res) { if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405); res.end(); return; } - handle(req, res, token, wrap); + handle(req, res, token, wrap, policy); }); server.on('error', function (e) { cb(e); }); server.listen(0, '127.0.0.1', function () { @@ -132,4 +211,4 @@ function start(cb) { }); } -module.exports = { sniff: sniff, rewritePlaylist: rewritePlaylist, wrapper: wrapper, isUpstream: isUpstream, start: start, PLAYLIST: PLAYLIST }; +module.exports = { sniff: sniff, rewritePlaylist: rewritePlaylist, wrapper: wrapper, isUpstream: isUpstream, isPublicAddress: isPublicAddress, callerAllowed: callerAllowed, start: start, PLAYLIST: PLAYLIST }; diff --git a/webos/service/service.js b/webos/service/service.js index a403b59b..004562ed 100644 --- a/webos/service/service.js +++ b/webos/service/service.js @@ -4,6 +4,7 @@ var Service = require('webos-service'); var proxy = require('./proxy.js'); var ID = 'com.soplay.sozo.webos.service'; +var APP = 'com.soplay.sozo.webos'; var service = new Service(ID); var relay = null; var waiting = []; @@ -20,8 +21,12 @@ function withRelay(cb) { }); } -// The app holds this subscription while it runs, which keeps the service alive. +// The app holds this subscription while it runs, which keeps the service alive. Only Sozo itself gets the token. service.register('relay', function (message) { + if (!proxy.callerAllowed(message.sender, APP)) { + message.respond({ returnValue: false, errorText: 'caller not allowed' }); + return; + } withRelay(function (err, r) { if (err) { message.respond({ returnValue: false, errorText: String(err.message || err) }); return; } message.respond({ returnValue: true, port: r.port, token: r.token, subscribed: !!message.isSubscription }); diff --git a/webos/test/relay.test.js b/webos/test/relay.test.js index f0b09016..36c6c06e 100644 --- a/webos/test/relay.test.js +++ b/webos/test/relay.test.js @@ -40,6 +40,10 @@ test('isUpstream takes only http(s) URLs with a host', () => { assert.equal(proxy.isUpstream(''), false); }); +function startRelay(options) { + return new Promise((resolve, reject) => proxy.start((err, r) => (err ? reject(err) : resolve(r)), options)); +} + function listen(server) { return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server.address().port))); } @@ -56,7 +60,7 @@ test('relay: a host that labels everything text/html comes out as a playlist and res.writeHead(404); res.end(); }); const upPort = await listen(upstream); - const relay = await new Promise((resolve, reject) => proxy.start((err, r) => (err ? reject(err) : resolve(r)))); + const relay = await startRelay({ allowPrivate: true }); try { assert.equal(relay.server.address().address, '127.0.0.1'); const wrap = proxy.wrapper(relay.port, relay.token); @@ -120,3 +124,86 @@ test('the relay service is ES5 for the oldest webOS Node, and its id matches the assert.equal(JSON.parse(fs.readFileSync(path.join(ROOT, 'service', 'package.json'), 'utf8')).name, svc.id); assert.equal(Relabel.SERVICE, 'luna://' + svc.id + '/relay'); }); + +test('isPublicAddress refuses loopback, private, link-local, CGNAT, reserved and multicast, v4 and v6', () => { + for (const ip of ['127.0.0.1', '10.1.2.3', '172.16.0.1', '172.31.255.255', '192.168.1.120', '169.254.1.1', '100.64.0.1', '0.0.0.0', + '224.0.0.1', '255.255.255.255', '203.0.113.250', '::1', '::', 'fe80::1', 'fd00::1', 'ff02::1', '2001:db8:1000::fa', '::ffff:192.168.1.1', 'not-an-ip']) { + assert.equal(proxy.isPublicAddress(ip), false, ip); + } + for (const ip of ['188.114.96.0', '104.17.88.107', '172.32.0.1', '2a06:98c1:3120::', '::ffff:8.8.8.8']) { + assert.equal(proxy.isPublicAddress(ip), true, ip); + } +}); + +test('relay: by default a LAN or loopback upstream is refused, by literal address and by name', async () => { + let hits = 0; + const lan = http.createServer((req, res) => { hits++; res.end('#EXTM3U\n'); }); + const port = await listen(lan); + const relay = await startRelay(); + try { + const wrap = proxy.wrapper(relay.port, relay.token); + for (const host of ['127.0.0.1', 'localhost', '[::1]', '192.168.1.1', '10.0.0.1']) { + assert.equal((await fetch(wrap('http://' + host + ':' + port + '/x'))).status, 403, host); + } + assert.equal(hits, 0, 'nothing reached the LAN server'); + } finally { + relay.server.close(); + lan.close(); + } +}); + +test('relay: a redirect to a refused address is refused at that hop', async () => { + let hits = 0; + const inner = http.createServer((req, res) => { hits++; res.end('secret'); }); + const innerPort = await new Promise((r) => inner.listen(0, '127.0.0.2', () => r(inner.address().port))); + const hop = http.createServer((req, res) => { res.writeHead(302, { Location: 'http://127.0.0.2:' + innerPort + '/secret' }); res.end(); }); + const hopPort = await listen(hop); + // Only 127.0.0.1 counts as public here, so the first hop passes and the redirect target does not. + const relay = await startRelay({ isPublic: (ip) => ip === '127.0.0.1' }); + try { + assert.equal((await fetch(proxy.wrapper(relay.port, relay.token)('http://127.0.0.1:' + hopPort + '/'))).status, 403); + assert.equal(hits, 0); + } finally { + relay.server.close(); + hop.close(); + inner.close(); + } +}); + +test('relay: leaving mid-redirect aborts the next hop, and a large segment is piped intact', async () => { + let secondClosed = null; + const big = Buffer.alloc(6 * 1024 * 1024, 0x47); + const up = http.createServer((req, res) => { + if (req.url === '/hop') { res.writeHead(302, { Location: '/hang' }); res.end(); return; } + if (req.url === '/hang') { secondClosed = new Promise((r) => req.on('close', r)); return; } + if (req.url === '/big.ts') { res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': String(big.length) }); res.end(big); return; } + res.writeHead(404); res.end(); + }); + const upPort = await listen(up); + const relay = await startRelay({ allowPrivate: true }); + try { + const wrap = proxy.wrapper(relay.port, relay.token); + const ctrl = new AbortController(); + const pending = fetch(wrap('http://127.0.0.1:' + upPort + '/hop'), { signal: ctrl.signal }).catch(() => null); + while (!secondClosed) await new Promise((r) => setTimeout(r, 10)); + ctrl.abort(); + await pending; + await secondClosed; + const seg = await fetch(wrap('http://127.0.0.1:' + upPort + '/big.ts')); + assert.equal(seg.headers.get('content-type'), 'video/mp2t'); + const body = Buffer.from(await seg.arrayBuffer()); + assert.equal(body.length, big.length); + assert.ok(body.equals(big)); + } finally { + relay.server.close(); + up.close(); + } +}); + +test('callerAllowed only lets the app itself have the token', () => { + assert.equal(proxy.callerAllowed('com.soplay.sozo.webos', 'com.soplay.sozo.webos'), true); + assert.equal(proxy.callerAllowed('com.other.app', 'com.soplay.sozo.webos'), false); + assert.equal(proxy.callerAllowed('com.soplay.sozo.webos.evil', 'com.soplay.sozo.webos'), false); + assert.equal(proxy.callerAllowed(undefined, 'com.soplay.sozo.webos'), false); + assert.equal(proxy.callerAllowed('', 'com.soplay.sozo.webos'), false); +}); From 3aea758950df2422ad45b0fcba579e4cf3c6198e Mon Sep 17 00:00:00 2001 From: ArnoldDeRuiter <187004+ArnoldDeRuiter@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:17:21 +0100 Subject: [PATCH 4/8] Make the relay service private --- webos/service/services.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webos/service/services.json b/webos/service/services.json index cd72e38b..2bbc7f9f 100644 --- a/webos/service/services.json +++ b/webos/service/services.json @@ -6,7 +6,7 @@ "name": "com.soplay.sozo.webos.service", "description": "Loopback HLS relay so the native player gets correct content types", "commands": [ - { "name": "relay", "description": "Start the relay and report its port and token", "public": true } + { "name": "relay", "description": "Start the relay and report its port and token", "public": false } ] } ] From ffc565b14e660a5b5e94fedbb324ecaa9063ecce Mon Sep 17 00:00:00 2001 From: ArnoldDeRuiter <187004+ArnoldDeRuiter@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:29:09 +0100 Subject: [PATCH 5/8] Answer 502 when a relay request cannot be made, such as a redirect to a non-http scheme --- webos/service/proxy.js | 12 ++++++++++-- webos/test/relay.test.js | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/webos/service/proxy.js b/webos/service/proxy.js index 01dc749d..a03f1f90 100644 --- a/webos/service/proxy.js +++ b/webos/service/proxy.js @@ -104,7 +104,15 @@ function fetchUpstream(target, range, hops, policy, hold, cb) { opts.headers = { 'User-Agent': UA, 'Accept': '*/*' }; if (range) opts.headers.Range = range; var done = false; - var req = lib.get(opts, function (res) { + var req; + // http.get throws on some URLs (an odd scheme or host); that must become a 502, not an uncaught exception. + try { + req = lib.get(opts, onResponse); + } catch (e) { + cb(e); + return; + } + function onResponse(res) { var loc = res.headers.location; if (res.statusCode >= 300 && res.statusCode < 400 && loc) { res.resume(); @@ -118,7 +126,7 @@ function fetchUpstream(target, range, hops, policy, hold, cb) { } done = true; cb(null, res, target); - }); + } hold.req = req; req.setTimeout(TIMEOUT, function () { req.abort(); }); req.on('error', function (e) { if (!done) { done = true; cb(e); } }); diff --git a/webos/test/relay.test.js b/webos/test/relay.test.js index 36c6c06e..342b3639 100644 --- a/webos/test/relay.test.js +++ b/webos/test/relay.test.js @@ -207,3 +207,24 @@ test('callerAllowed only lets the app itself have the token', () => { assert.equal(proxy.callerAllowed(undefined, 'com.soplay.sozo.webos'), false); assert.equal(proxy.callerAllowed('', 'com.soplay.sozo.webos'), false); }); + +test('relay: a redirect to a non-http scheme or a hostless URL answers 502 and the service keeps running', async () => { + const up = http.createServer((req, res) => { + const to = { '/ftp': 'ftp://example.com/x.ts', '/js': 'javascript:alert(1)', '/file': 'file:///etc/passwd', '/nohost': 'http:///x' }[req.url]; + if (to) { res.writeHead(302, { Location: to }); res.end(); return; } + res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('#EXTM3U\n'); + }); + const upPort = await listen(up); + const relay = await startRelay({ allowPrivate: true }); + try { + const wrap = proxy.wrapper(relay.port, relay.token); + for (const p of ['/ftp', '/js', '/file', '/nohost']) { + assert.equal((await fetch(wrap('http://127.0.0.1:' + upPort + p))).status, 502, p); + } + const ok = await fetch(wrap('http://127.0.0.1:' + upPort + '/ok')); + assert.equal(ok.headers.get('content-type'), proxy.PLAYLIST, 'still serving after the bad redirects'); + } finally { + relay.server.close(); + up.close(); + } +}); From 932274365d0165fe227aa55bd1a28c2739ed92c3 Mon Sep 17 00:00:00 2001 From: ArnoldDeRuiter <187004+ArnoldDeRuiter@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:34:37 +0100 Subject: [PATCH 6/8] Percent-encode non-ASCII relay paths and normalise IPv6 before the public-address check --- webos/service/proxy.js | 72 +++++++++++++++++++++++++++++----------- webos/test/relay.test.js | 32 ++++++++++++++++-- 2 files changed, 82 insertions(+), 22 deletions(-) diff --git a/webos/service/proxy.js b/webos/service/proxy.js index a03f1f90..6d81d158 100644 --- a/webos/service/proxy.js +++ b/webos/service/proxy.js @@ -49,29 +49,59 @@ function wrapper(port, token) { }; } +// Eight 16-bit groups from any IPv6 spelling (zero runs, leading zeros, a dotted IPv4 tail, a zone id), or null. +function ipv6Groups(ip) { + var v = String(ip).split('%')[0]; + var tail = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(v); + if (tail) { + var q = tail.slice(1).map(Number); + v = v.slice(0, tail.index) + ((q[0] << 8) | q[1]).toString(16) + ':' + ((q[2] << 8) | q[3]).toString(16); + } + var halves = v.split('::'); + if (halves.length > 2) return null; + var head = halves[0] ? halves[0].split(':') : []; + var rest = halves.length === 2 && halves[1] ? halves[1].split(':') : []; + var fill = halves.length === 2 ? 8 - head.length - rest.length : 0; + if (fill < 0 || (halves.length === 1 && head.length !== 8)) return null; + var parts = head.concat(new Array(fill + 1).join('0').split(''), rest); + if (parts.length !== 8) return null; + var out = []; + for (var i = 0; i < 8; i++) { + if (!/^[0-9a-f]{1,4}$/i.test(parts[i])) return null; + out.push(parseInt(parts[i], 16)); + } + return out; +} + +function isPublicV4(o) { + if (o[0] === 0 || o[0] === 10 || o[0] === 127 || o[0] >= 224) return false; + if (o[0] === 100 && o[1] >= 64 && o[1] <= 127) return false; + if (o[0] === 169 && o[1] === 254) return false; + if (o[0] === 172 && o[1] >= 16 && o[1] <= 31) return false; + if (o[0] === 192 && (o[1] === 168 || (o[1] === 0 && (o[2] === 0 || o[2] === 2)))) return false; + if (o[0] === 198 && (o[1] === 18 || o[1] === 19 || (o[1] === 51 && o[2] === 100))) return false; + if (o[0] === 203 && o[1] === 0 && o[2] === 113) return false; + return true; +} + +function v4From(hi, lo) { + return [hi >> 8, hi & 255, lo >> 8, lo & 255]; +} + // Public internet only: loopback, private, link-local, CGNAT, multicast and reserved ranges are refused. +// IPv6 is normalised first, so expanded or IPv4-embedding spellings cannot slip past. function isPublicAddress(ip) { var v = String(ip || '').toLowerCase(); - var mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v); - if (mapped) v = mapped[1]; - if (net.isIPv4(v)) { - var o = v.split('.').map(Number); - if (o[0] === 0 || o[0] === 10 || o[0] === 127 || o[0] >= 224) return false; - if (o[0] === 100 && o[1] >= 64 && o[1] <= 127) return false; - if (o[0] === 169 && o[1] === 254) return false; - if (o[0] === 172 && o[1] >= 16 && o[1] <= 31) return false; - if (o[0] === 192 && (o[1] === 168 || (o[1] === 0 && (o[2] === 0 || o[2] === 2)))) return false; - if (o[0] === 198 && (o[1] === 18 || o[1] === 19 || (o[1] === 51 && o[2] === 100))) return false; - if (o[0] === 203 && o[1] === 0 && o[2] === 113) return false; - return true; - } - if (net.isIPv6(v)) { - if (v === '::' || v === '::1') return false; - if (/^f[cd]/.test(v) || /^fe[89ab]/.test(v) || /^ff/.test(v)) return false; - if (/^2001:0?db8:/.test(v) || /^64:ff9b:/.test(v) || /^::/.test(v)) return false; - return true; - } - return false; + if (net.isIPv4(v)) return isPublicV4(v.split('.').map(Number)); + if (!net.isIPv6(v.split('%')[0])) return false; + var h = ipv6Groups(v); + if (!h) return false; + if (!h[0] && !h[1] && !h[2] && !h[3] && !h[4]) return h[5] === 0xffff ? isPublicV4(v4From(h[6], h[7])) : false; + if ((h[0] & 0xfe00) === 0xfc00 || (h[0] & 0xffc0) === 0xfe80 || (h[0] & 0xff00) === 0xff00) return false; + if (h[0] === 0x2001 && (h[1] === 0x0db8 || h[1] === 0)) return false; + if (h[0] === 0x64 && h[1] === 0xff9b) return false; + if (h[0] === 0x2002) return isPublicV4(v4From(h[1], h[2])); + return true; } // dns.lookup that fails for any non-public answer; checked at connect time, so DNS rebinding cannot slip past. @@ -101,6 +131,8 @@ function fetchUpstream(target, range, hops, policy, hold, cb) { if (net.isIP(literal) && !policy.isPublic(literal)) { cb(new Error('refused address ' + literal)); return; } opts.lookup = publicLookup(policy.isPublic); } + // http.get refuses unescaped non-ASCII, so a path like /файл.ts is percent-encoded; existing escapes stay. + opts.path = String(opts.path || '/').replace(/[\ud800-\udbff][\udc00-\udfff]|[^\x21-\x7e]/g, function (c) { return encodeURIComponent(c); }); opts.headers = { 'User-Agent': UA, 'Accept': '*/*' }; if (range) opts.headers.Range = range; var done = false; diff --git a/webos/test/relay.test.js b/webos/test/relay.test.js index 342b3639..0f91b9e7 100644 --- a/webos/test/relay.test.js +++ b/webos/test/relay.test.js @@ -127,10 +127,12 @@ test('the relay service is ES5 for the oldest webOS Node, and its id matches the test('isPublicAddress refuses loopback, private, link-local, CGNAT, reserved and multicast, v4 and v6', () => { for (const ip of ['127.0.0.1', '10.1.2.3', '172.16.0.1', '172.31.255.255', '192.168.1.120', '169.254.1.1', '100.64.0.1', '0.0.0.0', - '224.0.0.1', '255.255.255.255', '203.0.113.250', '::1', '::', 'fe80::1', 'fd00::1', 'ff02::1', '2001:db8:1000::fa', '::ffff:192.168.1.1', 'not-an-ip']) { + '224.0.0.1', '255.255.255.255', '203.0.113.250', '::1', '::', 'fe80::1', 'fd00::1', 'ff02::1', '2001:db8:1000::fa', '::ffff:192.168.1.1', 'not-an-ip', + '0:0:0:0:0:0:0:1', '0:0:0:0:0:ffff:7f00:1', '0000:0000:0000:0000:0000:0000:0000:0000', '0:0:0:0:0:ffff:c0a8:178', '::ffff:127.0.0.1', + 'FE80::1%eth0', '2002:c0a8:0101::1', '2001:0:4136:e378::1', '64:ff9b::a00:1']) { assert.equal(proxy.isPublicAddress(ip), false, ip); } - for (const ip of ['188.114.96.0', '104.17.88.107', '172.32.0.1', '2a06:98c1:3120::', '::ffff:8.8.8.8']) { + for (const ip of ['188.114.96.0', '104.17.88.107', '172.32.0.1', '2a06:98c1:3120::', '::ffff:8.8.8.8', '2606:4700:4700:0:0:0:0:1111', '0:0:0:0:0:ffff:808:808', '2002:0808:0808::1']) { assert.equal(proxy.isPublicAddress(ip), true, ip); } }); @@ -228,3 +230,29 @@ test('relay: a redirect to a non-http scheme or a hostless URL answers 502 and t up.close(); } }); + +test('relay: non-Latin playlist and segment paths are percent-encoded and play through', async () => { + const seen = []; + const up = http.createServer((req, res) => { + const path = decodeURIComponent(req.url); + seen.push(req.url); + if (path === '/видео/плейлист.m3u8') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('#EXTM3U\n#EXTINF:6,\nсегмент 0.ts\n'); return; } + if (path === '/видео/сегмент 0.ts') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(TS); return; } + res.writeHead(404); res.end(); + }); + const upPort = await listen(up); + const relay = await startRelay({ allowPrivate: true }); + try { + const wrap = proxy.wrapper(relay.port, relay.token); + const pl = await fetch(wrap('http://127.0.0.1:' + upPort + '/видео/плейлист.m3u8')); + assert.equal(pl.status, 200); + const segUrl = (await pl.text()).split('\n').find((l) => l.startsWith('http')); + const seg = await fetch(segUrl); + assert.equal(seg.headers.get('content-type'), 'video/mp2t'); + assert.deepEqual(Buffer.from(await seg.arrayBuffer()), TS); + assert.ok(seen.every((u) => /^[\x21-\x7e]+$/.test(u)), 'upstream only ever saw escaped paths'); + } finally { + relay.server.close(); + up.close(); + } +}); From 663ba9c8007cc5d55951a0440e28a21c43b544a0 Mon Sep 17 00:00:00 2001 From: ArnoldDeRuiter <187004+ArnoldDeRuiter@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:01:40 +0100 Subject: [PATCH 7/8] Answer 502 for unparsable relay targets and redirects, drop unparsable playlist lines --- webos/service/proxy.js | 26 ++++++++++++++++++-------- webos/test/relay.test.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/webos/service/proxy.js b/webos/service/proxy.js index 6d81d158..bf66d45d 100644 --- a/webos/service/proxy.js +++ b/webos/service/proxy.js @@ -31,16 +31,25 @@ function sniff(head, upstreamType) { return t; } -// Every URI in a playlist is made absolute and sent back through the relay. +// url.resolve throws on some URLs (e.g. http://[bad/x); null lets the caller drop or refuse it. +function resolve(base, ref) { + try { return url.resolve(base, ref); } catch (e) { return null; } +} + +// Every URI in a playlist is made absolute and sent back through the relay; a line with an unparsable URI is dropped. function rewritePlaylist(text, base, wrap) { return String(text).split(/\r?\n/).map(function (line) { var s = line.trim(); if (!s) return line; - if (s.charAt(0) !== '#') return wrap(url.resolve(base, s)); - return line.replace(/URI="([^"]*)"/g, function (m, uri) { - return 'URI="' + wrap(url.resolve(base, uri)) + '"'; + if (s.charAt(0) !== '#') { var u = resolve(base, s); return u === null ? null : wrap(u); } + var bad = false; + var out = line.replace(/URI="([^"]*)"/g, function (m, uri) { + var r = resolve(base, uri); + if (r === null) { bad = true; return m; } + return 'URI="' + wrap(r) + '"'; }); - }).join('\n'); + return bad ? null : out; + }).filter(function (line) { return line !== null; }).join('\n'); } function wrapper(port, token) { @@ -125,7 +134,8 @@ function publicLookup(isPublic) { // Follows redirects; hold.req is always the live request, so the caller can abort whichever hop is open. function fetchUpstream(target, range, hops, policy, hold, cb) { var lib = /^https:/i.test(target) ? https : http; - var opts = url.parse(target); + var opts; + try { opts = url.parse(target); } catch (e) { cb(e); return; } if (policy.publicOnly) { var literal = String(opts.hostname || '').replace(/^\[|\]$/g, ''); if (net.isIP(literal) && !policy.isPublic(literal)) { cb(new Error('refused address ' + literal)); return; } @@ -150,8 +160,8 @@ function fetchUpstream(target, range, hops, policy, hold, cb) { res.resume(); req.abort(); done = true; - var next = url.resolve(target, loc); - if (hops >= MAX_REDIRECTS || !isUpstream(next)) { cb(new Error('bad redirect')); return; } + var next = resolve(target, loc); + if (next === null || hops >= MAX_REDIRECTS || !isUpstream(next)) { cb(new Error('bad redirect')); return; } if (hold.aborted) return; fetchUpstream(next, range, hops + 1, policy, hold, cb); return; diff --git a/webos/test/relay.test.js b/webos/test/relay.test.js index 0f91b9e7..4ee5e38b 100644 --- a/webos/test/relay.test.js +++ b/webos/test/relay.test.js @@ -256,3 +256,35 @@ test('relay: non-Latin playlist and segment paths are percent-encoded and play t up.close(); } }); + +test('rewritePlaylist drops a line whose URI cannot be parsed and keeps the rest', () => { + const wrap = (u) => 'R(' + u + ')'; + const text = '#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI="http://[bad/key"\n#EXTINF:6,\nhttp://[bad/x.ts\n#EXTINF:6,\nseg1.ts'; + const out = proxy.rewritePlaylist(text, 'https://a.test/pl/index.m3u8', wrap).split('\n'); + assert.deepEqual(out, ['#EXTM3U', '#EXTINF:6,', '#EXTINF:6,', 'R(https://a.test/pl/seg1.ts)']); +}); + +test('relay: an unparsable target, redirect or playlist line answers 502 or is dropped, and the service keeps running', async () => { + const up = http.createServer((req, res) => { + if (req.url === '/redir') { res.writeHead(302, { Location: 'http://[bad/x' }); res.end(); return; } + if (req.url === '/pl') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('#EXTM3U\n#EXTINF:6,\nhttp://[bad/x.ts\n#EXTINF:6,\nok.ts\n'); return; } + res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('#EXTM3U\n'); + }); + const upPort = await listen(up); + const relay = await startRelay({ allowPrivate: true }); + try { + const wrap = proxy.wrapper(relay.port, relay.token); + assert.equal((await fetch(wrap('http://[bad/x'))).status, 502, 'target'); + assert.equal((await fetch(wrap('http://127.0.0.1:' + upPort + '/redir'))).status, 502, 'redirect'); + const pl = await fetch(wrap('http://127.0.0.1:' + upPort + '/pl')); + assert.equal(pl.status, 200); + const lines = (await pl.text()).split('\n').filter((l) => l.startsWith('http')); + assert.equal(lines.length, 1); + assert.ok(lines[0].includes(encodeURIComponent('http://127.0.0.1:' + upPort + '/ok.ts'))); + const ok = await fetch(wrap('http://127.0.0.1:' + upPort + '/ok')); + assert.equal(ok.headers.get('content-type'), proxy.PLAYLIST, 'still serving'); + } finally { + relay.server.close(); + up.close(); + } +}); From 02ca3f6091432bf8abd743804a6dd86e59782c84 Mon Sep 17 00:00:00 2001 From: ArnoldDeRuiter <187004+ArnoldDeRuiter@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:01:40 +0100 Subject: [PATCH 8/8] Record sportstv playing natively on webOS 10.3 in the README --- webos/README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/webos/README.md b/webos/README.md index 552c191c..44d45add 100644 --- a/webos/README.md +++ b/webos/README.md @@ -105,7 +105,9 @@ A TV takes a different path for HLS: it tries the platform's native player first uses hls.js only as a fallback where the source allows it. vidapi's segments are named `.html` and sent as `text/html`. On an LG webOS 10.3 TV the native player rejects them at once (`MEDIA_ELEMENT_ERROR: Format error`), while hls.js plays the same stream at 1080p; its segment host now sends `Access-Control-Allow-Origin: *`. -So on webOS vidapi goes through the relay below, with hls.js as the fallback. sportstv is still untried on a TV. +So on webOS vidapi goes through the relay below, with hls.js as the fallback. sportstv plays natively on the +same TV at 1080p without the relay or hls.js (Setanta Sports 1 Eurasia via `stream.mcquack.net` and Futbol via +`185.121.1.163:8083`, both plain HTTP). ### Native HLS relay (webOS only) @@ -176,6 +178,6 @@ on Chromium 53. Nothing here has run on Chromium 53. - Install on the oldest TV available and check Home, Search, Detail and the exit dialog. - Play one mp4 source and one HLS source, then seek, change source and resume. -- Try vidapi and sportstv with native HLS. +- Try vidapi and sportstv with native HLS on webOS older than 10.3. - Use the Magic Remote pointer, the arrows, OK and Back, including held keys. - Check that the screensaver stays off during playback and how `ended` behaves.