diff --git a/README.md b/README.md index 87237081..45fe0e3f 100644 --- a/README.md +++ b/README.md @@ -294,3 +294,7 @@ The KiwiSDR embedded player now uses the receiver's native `//SND` We ### KiwiSDR Cloudflare relay activation (v81) Site owner reports the independent Worker `https://radio-atlas-kiwi-bridge.ossam-hashim.workers.dev` has been enabled and `/healthz` returned HTTP 200. HTTP KiwiSDR devices that advertise `ext_api > 0` now *attempt* the in-app secure WSS bridge; HTTPS devices connect directly. Failed connections stay in Radio Atlas, show a receiver error and retain a clearly labeled optional original-device link. The owner reported no successful real WebSocket or decoded audio test yet. `healthz` alone does **not** demonstrate working stream relaying. See `proxy/KIWI_README.md` for staged browser/audio verification and origin requirements. + + +### KiwiSDR bridge deployed Worker sync (November 20, 2026) +Cloudflare Worker code in `proxy/kiwi-worker.js` tracks the Cloudflare AI Agent's deployed version `3e349979-4861-4f78-aa7d-8dc1fdc42b56`: handshake timeout limited to setup, missing/non-numeric `ext_api` denied, expired per-isolate rate counters pruned, and structured error codes distinguish forbidden origin, 429 rate limiting, and upstream errors. This does not constitute a verified end-to-end KiwiSDR audio session; real public receiver audio and mobile browser validation are still required. diff --git a/ROADMAP.md b/ROADMAP.md index 33e4d562..61a7fff5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -212,3 +212,9 @@ - Owner supplied confirmed Workers hostname `https://radio-atlas-kiwi-bridge.ossam-hashim.workers.dev` and reports HTTP 200 from `/healthz` (response body inferred from deployed code, not separately byte-checked). - Frontend configured to attempt WSS relay for HTTP-only publicly listed KiwiSDR receivers (when `ext_api > 0`). Receiver remains in-app on failure; normal station player unaffected. Cache bumped to v81. - **Acceptance limitation:** Cloudflare Agent could not test unauthorized WebSocket rejection or real SND playback. Before claiming end-to-end availability, test 403 origin rejection, 403 non-catalog receiver, a permitted WSS handshake, valid `SND` frames and actual audio from consenting receivers on Android and desktop. Avoid claiming all receivers work. + + +### KiwiSDR Cloudflare Worker source synchronization — 2026-11-20 +- Cloudflare Agent reported live Worker version `3e349979-4861-4f78-aa7d-8dc1fdc42b56` deployed at 10:36:08Z with four code corrections: handshake abort timer cleared after connection, fail-closed ext_api, counter sweep and structured error types (403/429/502/503). These are synchronized into `proxy/kiwi-worker.js` with updated unit tests. +- Independent Github Actions live Worker tests previously returned 200/403/403/426. The latest Cloudflare Agent reported zero events in its observability view, which contradicts known CI requests; investigate query window/sampling before drawing conclusions. +- Live WebSocket 101, real SND frames, actual audible receiver playback and comprehensive SSRF protections remain **unverified**. Do not mark end-to-end playback as complete. diff --git a/proxy/KIWI_README.md b/proxy/KIWI_README.md index 669b88fc..6035a1a8 100644 --- a/proxy/KIWI_README.md +++ b/proxy/KIWI_README.md @@ -1,6 +1,6 @@ # KiwiSDR WebSocket bridge — Radio Atlas -This is a **separate Cloudflare Worker** for KiwiSDR hardware which is HTTP/WS-only. GitHub Pages cannot host WebSockets, so this service is not part of the static deployment and is **not currently active**. +This is a **separate Cloudflare Worker** for KiwiSDR hardware which is HTTP/WS-only. GitHub Pages cannot host WebSockets, so this service is not part of the static deployment and is **deployed and configured in the frontend**. ## Design 1. Browser makes a secure WSS request to `/kiwi/ws?receiver=` with the Radio Atlas Origin. @@ -14,11 +14,11 @@ This is a **separate Cloudflare Worker** for KiwiSDR hardware which is HTTP/WS-o ## Deployment Deploy `proxy/kiwi-worker.js` to its own Cloudflare Worker (Workers & Pages). Do not overwrite the radio audio relay worker in `proxy/worker.js`. On a successful deployment, verify `https://.workers.dev/healthz` returns `ok`. -Before production activation: run origin-spoof and non-catalogue rejection tests; validate that a **consenting public KiwiSDR with ext_api enabled** delivers playable audio over WSS through the bridge; inspect Cloudflare costs/limits; use a managed security rate limit. Only then set the `KIWI_WS_RELAY` value in `js/modules/sdr.mjs` to the tested HTTPS origin, bump `sw.js`, and merge a separate frontend activation PR. Until then HTTP Kiwi devices retain their original link, while HTTPS Kiwi devices can play directly. +Production route: `https://radio-atlas-kiwi-bridge.ossam-hashim.workers.dev`. The website has already activated this endpoint (PR #146). Public GitHub Actions CI previously independently verified health, origin rejection, noncatalogue rejection, and missing upgrade; **real SND/audio sessions have not yet been verified**. A failed receiver must stay on-site with an explicit error, and the original receiver link remains optional. Cloudflare Agent reported Worker deployment version `3e349979-4861-4f78-aa7d-8dc1fdc42b56` on 2026-11-20 10:36 UTC. Cloudflare code was corrected to fail closed on absent `ext_api`, bound handshake timeouts, prune counters and distinguish 403/429. The repository must retain the same source code. Managed rate limits and real browser/audio QA remain outstanding. ## Contract - GET `/healthz` — plain `ok`. - WebSocket `/kiwi/ws?receiver=https%3A%2F%2Fexample.org%2F` — origin-validated, allowlisted, binary/text WebSocket passthrough. HTTP receiver URLs are allowed only through this secure browser-facing WSS relay. - Unknown/unapproved receiver: HTTP 403. Non-WebSocket request: 426. Directory failure: 503. -No claims of live functionality are made until the worker URL and end-to-end audio are verified. +Worker reachability/security tests do not establish functional playback. An actual permitted KiwiSDR audio session is the completion gate. diff --git a/proxy/kiwi-worker.js b/proxy/kiwi-worker.js index 28cccfb5..bac338e2 100644 --- a/proxy/kiwi-worker.js +++ b/proxy/kiwi-worker.js @@ -10,11 +10,22 @@ const DIRECTORY = SITE_ORIGIN + '/Radio/data/kiwisdr.json'; const ORIGINS = new Set([SITE_ORIGIN, 'http://localhost:8000', 'http://127.0.0.1:8000']); const WINDOW_MS = 60 * 1000; const RATE_LIMIT = 24; +const CONNECT_TIMEOUT_MS = 9000; +const SWEEP_MS = 5 * 60 * 1000; const counters = new Map(); +let lastSweep = 0; let directoryCache = null; let directoryDeadline = 0; -function error(status, reason) { +function log(level, code, detail) { + const record = { event: 'kiwi_bridge', code }; + if (detail) Object.assign(record, detail); + const line = JSON.stringify(record); + if (level === 'warn') console.warn(line); else console.log(line); +} + +function error(status, code, reason) { + log('warn', code, { status }); return new Response(reason, {status, headers:{'Content-Type':'text/plain; charset=utf-8','Cache-Control':'no-store'}}); } @@ -51,18 +62,27 @@ function normalizeReceiver(input) { return u.origin + '/'; } +function sweep(now) { + if (now - lastSweep < SWEEP_MS) return; + lastSweep = now; + for (const [ip, entry] of counters) { + if (now - entry.start >= WINDOW_MS) counters.delete(ip); + } +} + function permitRequest(request) { const origin = request.headers.get('Origin'); - if (!ORIGINS.has(origin)) return false; + if (!ORIGINS.has(origin)) return 'origin'; const ip = request.headers.get('CF-Connecting-IP') || 'unknown'; const now = Date.now(); + sweep(now); const prev = counters.get(ip); if (!prev || now - prev.start >= WINDOW_MS) { counters.set(ip, {start:now,count:1}); - return true; + return 'ok'; } prev.count++; - return prev.count <= RATE_LIMIT; + return prev.count <= RATE_LIMIT ? 'ok' : 'rate'; } async function permittedCatalog() { @@ -77,7 +97,10 @@ async function permittedCatalog() { if (!Array.isArray(doc.receivers)) throw new Error('Invalid SDR directory'); const allow = new Set(); for (const receiver of doc.receivers) { - if (Number(receiver.ext_api) <= 0 || receiver.online === false) continue; + if (!receiver || typeof receiver !== 'object') continue; + // Missing or non-numeric ext_api values are not valid authorization. + if (!(Number(receiver.ext_api) > 0)) continue; + if (receiver.online === false) continue; const users = Number(receiver.users); const slots = Number(receiver.max_users); if (Number.isFinite(users) && Number.isFinite(slots) && slots > 0 && users >= slots) continue; @@ -97,32 +120,46 @@ export default { async fetch(request) { const url = new URL(request.url); if (url.pathname === '/healthz') return new Response('ok', {headers:{'Content-Type':'text/plain'}}); - if (url.pathname !== '/kiwi/ws') return error(404, 'Not found'); - if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket') return error(426, 'WebSocket upgrade required'); - if (!permitRequest(request)) return error(403, 'Origin forbidden or request limit reached'); + if (url.pathname !== '/kiwi/ws') return error(404, 'not_found', 'Not found'); + if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket') return error(426, 'upgrade_required', 'WebSocket upgrade required'); + const permit = permitRequest(request); + if (permit === 'origin') return error(403, 'origin_forbidden', 'Origin forbidden'); + if (permit === 'rate') return error(429, 'rate_limited', 'Request limit reached'); const receiver = normalizeReceiver(url.searchParams.get('receiver') || ''); - if (!receiver) return error(400, 'Invalid receiver'); + if (!receiver) return error(400, 'invalid_receiver', 'Invalid receiver'); let allow; - try { allow = await permittedCatalog(); } catch { return error(503, 'Receiver directory unavailable'); } - if (!allow.has(receiver)) return error(403, 'Receiver is not approved for external API connections'); + try { allow = await permittedCatalog(); } catch { return error(503, 'directory_unavailable', 'Receiver directory unavailable'); } + if (!allow.has(receiver)) return error(403, 'receiver_not_allowed', 'Receiver is not approved for external API connections'); // The user cannot choose the upstream path or arbitrary WebSocket service. const target = new URL(receiver); target.pathname = '/' + Date.now() + '/SND'; target.search = ''; + // Bound only connection establishment, never an active audio session. + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), CONNECT_TIMEOUT_MS); let upstreamResponse; try { upstreamResponse = await fetch(target.toString(), { headers:{Upgrade:'websocket'}, redirect:'manual', - signal:AbortSignal.timeout(9000) + signal:controller.signal }); - } catch { return error(502, 'Receiver connection failed'); } - if (!upstreamResponse.webSocket) return error(502, 'Receiver refused WebSocket connection'); + } catch (err) { + log('warn', 'upstream_connect_failed', { receiver, aborted: controller.signal.aborted }); + return error(502, 'upstream_connect_failed', 'Receiver connection failed'); + } finally { + clearTimeout(timer); + } + if (!upstreamResponse.webSocket) { + log('warn', 'upstream_refused', { receiver, status: upstreamResponse.status }); + return error(502, 'upstream_refused', 'Receiver refused WebSocket connection'); + } const upstream = upstreamResponse.webSocket; const [client, server] = Object.values(new WebSocketPair()); server.accept(); upstream.accept(); + log('info', 'session_open', { receiver }); // Byte-for-byte proxy; native Kiwi protocol remains end-to-end. server.addEventListener('message', event => { diff --git a/tests/kiwi-worker.test.cjs b/tests/kiwi-worker.test.cjs index dfca1749..43278698 100644 --- a/tests/kiwi-worker.test.cjs +++ b/tests/kiwi-worker.test.cjs @@ -8,7 +8,10 @@ const code=fs.readFileSync('proxy/kiwi-worker.js','utf8') const sandbox={ URL, Set, Map, Number, Date, Response, AbortSignal, fetch:async()=>({ok:true,headers:{get:()=>null},text:async()=>JSON.stringify({receivers:[ {url:'http://public.receiver.org:8073/',ext_api:1,online:true,users:0,max_users:4}, - {url:'http://not-opted-in.org:8073/',ext_api:0,online:true,users:0,max_users:4} + {url:'http://not-opted-in.org:8073/',ext_api:0,online:true,users:0,max_users:4}, + {url:'http://missing-api.org:8073/',online:true,users:0,max_users:4}, + {url:'http://nan-api.org:8073/',ext_api:'not-a-number',online:true,users:0,max_users:4}, + null ]})}) }; vm.createContext(sandbox); vm.runInContext(code,sandbox); @@ -28,9 +31,18 @@ test('directory only permits operators who allow external API connections',async const allowed=await sandbox.permittedCatalog(); assert.ok(allowed.has('http://public.receiver.org:8073/')); assert.ok(!allowed.has('http://not-opted-in.org:8073/')); + assert.ok(!allowed.has('http://missing-api.org:8073/')); + assert.ok(!allowed.has('http://nan-api.org:8073/')); }); test('requires Radio Atlas origin and rejects foreign origins',()=>{ const req=(Origin)=>({headers:{get:(name)=>name==='Origin'?Origin:'198.51.100.4'}}); - assert.equal(sandbox.permitRequest(req('https://malicious.example')),false); - assert.equal(sandbox.permitRequest(req('https://samotech.github.io')),true); + assert.equal(sandbox.permitRequest(req('https://malicious.example')),'origin'); + assert.equal(sandbox.permitRequest(req('https://samotech.github.io')),'ok'); +}); + +test('rate limit distinguishes valid requests from throttled traffic',()=>{ + const request={headers:{get:name=>name==='Origin'?'https://samotech.github.io':'192.0.2.31'}}; + const statuses=Array.from({length:25},()=>sandbox.permitRequest(request)); + assert.deepEqual(statuses.slice(0,24),Array(24).fill('ok')); + assert.equal(statuses[24],'rate'); });