Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions proxy/KIWI_README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# 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**.

## Design
1. Browser makes a secure WSS request to `/kiwi/ws?receiver=<encoded original URL>` with the Radio Atlas Origin.
2. Worker reads the published receiver catalogue `/Radio/data/kiwisdr.json`, caches its allowed origin list for two minutes, verifies the receiver advertises `ext_api > 0`, isn't explicitly offline and has a free receiver slot when known.
3. Worker rejects forbidden/private/loopback/test literal hostnames, credentials, arbitrary URL paths and non-catalogued receivers. Only the server chooses the `/<timestamp>/SND` WebSocket path.
4. Worker upgrades to the receiver's native WebSocket and relays Kiwi frames both directions without storing audio.
5. The radio page decodes native SND audio and exposes volume, mode and tuning in its own interface. The original receiver page remains an optional external link.

**Restrictions:** no iframe proxying, no bypass of receiver login/password or owner API restrictions, and no proxying OpenWebRX/WebSDR proprietary APIs. The worker does not record sessions. Rate limiting is *per-isolate* and is not sufficient for a high-traffic public production service; use Cloudflare WAF or Durable Objects for robust global quotas. HTTP receiver connections from the Worker to hardware are not encrypted on that leg; prefer HTTPS receivers where possible. DNS-rebinding checks are bounded by the hosting platform's networking controls — consider dedicated curated host allowlists for high-assurance deployments.

## 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://<your-worker>.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.

## 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.
144 changes: 144 additions & 0 deletions proxy/kiwi-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/**
* Radio Atlas KiwiSDR WebSocket bridge (Cloudflare Worker).
*
* Public catalogue allowlist only, no general-purpose open proxy.
* Deploy separately. GitHub Pages cannot accept WebSockets.
* Limited to receivers that advertise ext_api > 0 and a free slot.
*/
const SITE_ORIGIN = 'https://samotech.github.io';
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 counters = new Map();
let directoryCache = null;
let directoryDeadline = 0;

function error(status, reason) {
return new Response(reason, {status, headers:{'Content-Type':'text/plain; charset=utf-8','Cache-Control':'no-store'}});
}

function publicHost(hostname) {
const h = hostname.toLowerCase().replace(/\.$/, '');
if (!h || h === 'localhost' || h.endsWith('.localhost') ||
h.endsWith('.local') || h.endsWith('.internal') ||
h.endsWith('.test') || h.endsWith('.invalid') || h.includes('%') ||
h.includes('[') || h.includes(']')) return false;
if (/^[0-9.]+$/.test(h)) {
const p = h.split('.').map(Number);
if (p.length !== 4 || p.some(v => !Number.isInteger(v) || v < 0 || v > 255)) return false;
const [a,b,c] = p;
if (a === 0 || a === 10 || a === 127 || a >= 224 ||
a === 100 && b >= 64 && b <= 127 ||
a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 ||
a === 192 && b === 168 || a === 192 && b === 0 && c === 0 ||
a === 192 && b === 0 && c === 2 ||
a === 198 && b === 18 || a === 198 && b === 19 ||
a === 198 && b === 51 && c === 100 ||
a === 203 && b === 0 && c === 113) return false;
return true;
}
return h.includes('.') && /^[a-z0-9.-]+$/.test(h);
}

function normalizeReceiver(input) {
let u;
try { u = new URL(input); } catch { return ''; }
if (!['http:', 'https:'].includes(u.protocol) ||
u.username || u.password || !publicHost(u.hostname)) return '';
const port = u.port ? Number(u.port) : (u.protocol === 'https:' ? 443 : 80);
if (!Number.isInteger(port) || port < 1 || port > 65535) return '';
return u.origin + '/';
}

function permitRequest(request) {
const origin = request.headers.get('Origin');
if (!ORIGINS.has(origin)) return false;
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
const now = Date.now();
const prev = counters.get(ip);
if (!prev || now - prev.start >= WINDOW_MS) {
counters.set(ip, {start:now,count:1});
return true;
}
prev.count++;
return prev.count <= RATE_LIMIT;
}

async function permittedCatalog() {
if (directoryCache && Date.now() < directoryDeadline) return directoryCache;
const res = await fetch(DIRECTORY, {headers:{Accept:'application/json'}, cf:{cacheTtl:120}});
if (!res.ok) throw new Error('SDR directory unavailable');
const length = Number(res.headers.get('Content-Length'));
if (length && length > 4500000) throw new Error('SDR directory too large');
const text = await res.text();
if (text.length > 4500000) throw new Error('SDR directory too large');
const doc = JSON.parse(text);
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;
const users = Number(receiver.users);
const slots = Number(receiver.max_users);
if (Number.isFinite(users) && Number.isFinite(slots) && slots > 0 && users >= slots) continue;
const url = normalizeReceiver(receiver.url);
if (url) allow.add(url);
}
directoryCache = allow;
directoryDeadline = Date.now() + 120000;
return allow;
}

function closePeer(ws, code, reason) {
try { ws.close(code, reason); } catch {}
}

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');
const receiver = normalizeReceiver(url.searchParams.get('receiver') || '');
if (!receiver) return error(400, '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');

// The user cannot choose the upstream path or arbitrary WebSocket service.
const target = new URL(receiver);
target.pathname = '/' + Date.now() + '/SND';
target.search = '';
let upstreamResponse;
try {
upstreamResponse = await fetch(target.toString(), {
headers:{Upgrade:'websocket'},
redirect:'manual',
signal:AbortSignal.timeout(9000)
});
} catch { return error(502, 'Receiver connection failed'); }
if (!upstreamResponse.webSocket) return error(502, 'Receiver refused WebSocket connection');
const upstream = upstreamResponse.webSocket;
const [client, server] = Object.values(new WebSocketPair());
server.accept();
upstream.accept();

// Byte-for-byte proxy; native Kiwi protocol remains end-to-end.
server.addEventListener('message', event => {
if (upstream.readyState === 1) {
try { upstream.send(event.data); } catch { closePeer(server,1011,'Upstream error'); }
}
});
upstream.addEventListener('message', event => {
if (server.readyState === 1) {
try { server.send(event.data); } catch { closePeer(upstream,1001,'Client gone'); }
}
});
server.addEventListener('close', () => closePeer(upstream,1000,'Client closed'));
upstream.addEventListener('close', () => closePeer(server,1000,'Receiver closed'));
server.addEventListener('error', () => closePeer(upstream,1011,'Client error'));
upstream.addEventListener('error', () => closePeer(server,1011,'Receiver error'));
return new Response(null, {status:101,webSocket:client});
}
};
36 changes: 36 additions & 0 deletions tests/kiwi-worker.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';
const test=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const vm=require('node:vm');
const code=fs.readFileSync('proxy/kiwi-worker.js','utf8')
.replace('export default {','var exported = {');
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}
]})}) };
vm.createContext(sandbox);
vm.runInContext(code,sandbox);
test('rejects private, local and metadata IPs',()=>{
for(const host of ['localhost','127.0.0.1','10.0.0.2','169.254.169.254','192.168.0.1','172.16.1.3','100.64.0.1','test.local','[::1]']) {
assert.equal(sandbox.publicHost(host),false,host);
}
assert.equal(sandbox.publicHost('public.receiver.org'),true);
});
test('normalizes receivers to approved origins only',()=>{
assert.equal(sandbox.normalizeReceiver('http://public.receiver.org:8073/path'), 'http://public.receiver.org:8073/');
assert.equal(sandbox.normalizeReceiver('http://127.0.0.1:8073/'),'');
assert.equal(sandbox.normalizeReceiver('http://user:pass@public.receiver.org/'),'');
assert.equal(sandbox.normalizeReceiver('javascript:alert(1)'),'');
});
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/'));
});
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);
});
Loading