diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..aa65688 --- /dev/null +++ b/.env.example @@ -0,0 +1,6 @@ +# Run bun run dev:setup to create .env.development with a random secret. +TURN_SECRET=replace-with-a-random-secret +TURN_HOST=127.0.0.1 +TURN_PORT=3478 +VITE_ICE_ENDPOINT=/api/ice-servers +VITE_STUN_URL=stun:127.0.0.1:3478 diff --git a/.gitignore b/.gitignore index f06235c..af45a21 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ node_modules dist +.env +.env.* +!.env.example diff --git a/README.md b/README.md index 85a2a1c..5d9567e 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,11 @@ relay-only routing or hide your IP from the peer. A remote peer can independentl proxy their own traffic; the opt-in controls this app's configuration and the relay candidates it accepts, not arbitrary software run by the other person. +When a credential endpoint is configured (including the local development setup +below), **Use the configured relay with temporary credentials** replaces manual +credential entry. The app fetches fresh credentials for each new connection, +only after TURN opt-in. Uncheck it to use a different relay manually. + TURN credentials stay in the current component's memory; the app does not persist them or include them in codes. The relay receives its authentication exchange and can observe addresses, timing and traffic volume, and may charge for bandwidth. @@ -117,6 +122,82 @@ not a substitute for trusting the host or a portable WebRTC egress filter. ## Development +### Local STUN/TURN environment (Linux) + +Keep Vite on the host for hot reload; only coturn runs in Docker. Both bind to +loopback, so use two browser tabs on this machine. No DNS, certificates, firewall +changes or production services are needed. Nothing is enabled at boot, and the +container has no automatic restart policy. + +```sh +# Start Docker only when needed (if it isn't already running). +sudo systemctl start docker.service +# If you just joined the docker group, log in again or run: newgrp docker +bun install --frozen-lockfile +bun run dev:setup # creates ignored .env.development, without overwriting it +bun run turn:up +bun run dev # open the printed localhost URL in two tabs +``` + +Pick a file in the sender tab, choose Receive in the other, and check **Allow a +TURN relay** in both tabs. Leave **Use the configured relay with temporary +credentials** checked. Exchange codes and compare fingerprints as usual. Reset, +failure or completion clears consent, so check it again for each connection. +STUN defaults to the local server; TURN remains opt-in, with direct routes preferred. + +```sh +bun run test # protocol and temporary-credential unit tests +bun run test:turn # real Chromium file transfer, forced TURN/UDP +bun run test:turn --tcp # same test, TURN/TCP only +bun run build +bun run test:browser # direct-path browser regressions +docker compose --env-file .env.development logs --tail=50 coturn +``` + +The TURN checks start and stop their own Vite server and isolated browser profiles; +coturn must already be running. They obtain real temporary credentials, force +relay-only routing, assert selected relay candidates on both ends, verify exact +received bytes and receipts, and exercise cancellation and reconnection. TCP here +means browser-to-TURN transport; relay-to-peer traffic is UDP. These same-machine +checks do not test Internet NATs or a remote server's firewall. + +Stop Vite with Ctrl-C, then: + +```sh +bun run turn:down +# Optional: stop Docker too, after finishing any other containers. +sudo systemctl stop docker.service docker.socket containerd.service +``` + +`.env.development` contains the private shared `TURN_SECRET`, server-side +`TURN_HOST`/`TURN_PORT`, and public `VITE_ICE_ENDPOINT`/`VITE_STUN_URL` settings. +See [.env.example](.env.example). The secret never enters the client bundle. +Compose passes it directly to coturn; no config-file environment substitution is +assumed. If changing the port, update both `TURN_PORT` and `VITE_STUN_URL`, then +rerun `turn:up` and restart Vite. The image is pinned to a concrete release; +loopback listeners and UDP relay ports 49160–49200 are defined in [compose.yaml](compose.yaml). +Loopback peer access is explicitly allowed for these local tests. + +The credential endpoint is **development-only**, implemented as Vite middleware. +It isn't included in `dist/` or `vite preview`. Production builds ignore +`.env.development` and retain the existing static/manual configuration. To reuse +the client integration later, set `VITE_ICE_ENDPOINT` and `VITE_STUN_URL` when +building and implement the same JSON endpoint behind your production access +policy. [dev/ice-server.js](dev/ice-server.js) contains the HMAC issuance logic. +There are no accounts or room sessions in this app to authorize production +credential issuance automatically. Don't expose this development endpoint or +reuse the loopback-permitting Compose configuration as a public relay. + +Credentials expire after one hour; each new code exchange fetches fresh ones. +Automatic renewal during long transfers is not implemented because this app +uses manual signaling. Keep development transfers below that duration; expired +or failed sessions need fresh codes. + +Configuration references: [coturn Docker usage](https://github.com/coturn/coturn/blob/master/docker/coturn/README.md) +and [coturn configuration](https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf). + +### Existing checks and static build + ```sh bun install --frozen-lockfile bun run dev diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..8fe95c5 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,33 @@ +# Linux development only. No boot startup or automatic container restart. +services: + coturn: + image: coturn/coturn:4.18.0-r0-alpine + network_mode: host + restart: "no" + command: + - -n + - --listening-ip=127.0.0.1 + - --relay-ip=127.0.0.1 + - --listening-port=${TURN_PORT:-3478} + - --realm=hellcon.local + - --use-auth-secret + - --static-auth-secret=${TURN_SECRET:?Run bun run dev:setup first} + - --fingerprint + - --min-port=49160 + - --max-port=49200 + - --no-tls + # DTLS is opt-in in coturn 4.18; leave it disabled. + - --no-tcp-relay + - --no-multicast-peers + # Needed for two browsers relaying to each other on this machine. + - --allow-loopback-peers + - --no-cli + - --no-software-attribute + - --log-file=stdout + tmpfs: + - /var/lib/coturn + logging: + driver: json-file + options: + max-size: "5m" + max-file: "2" diff --git a/dev/ice-server.js b/dev/ice-server.js new file mode 100644 index 0000000..0a8cb16 --- /dev/null +++ b/dev/ice-server.js @@ -0,0 +1,28 @@ +import { createHmac, randomUUID } from 'node:crypto'; + +// Shared by Vite and the browser integration checks. Never imported by the client. +export function iceMiddleware(env) { + const secret = env.TURN_SECRET; + if (!secret) throw new Error('TURN_SECRET is required. Run bun run dev:setup first.'); + const host = env.TURN_HOST || '127.0.0.1'; + const port = env.TURN_PORT || '3478'; + return (req, res, next) => { + if (req.url?.split('?')[0] !== '/api/ice-servers') return next(); + res.setHeader('Cache-Control', 'no-store'); + if (req.method !== 'GET') { + res.writeHead(405, { Allow: 'GET' }); res.end(); return; + } + if (req.headers['sec-fetch-site'] === 'cross-site' || + (req.headers.origin && req.headers.origin !== `http://${req.headers.host}`)) { + res.writeHead(403); res.end(); return; + } + const expiresAt = Math.floor(Date.now() / 1000) + 3600; + const username = `${expiresAt}:${randomUUID()}`; + const credential = createHmac('sha1', secret).update(username).digest('base64'); + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ expiresAt, iceServers: [ + { urls: `stun:${host}:${port}` }, + { urls: [`turn:${host}:${port}?transport=udp`, `turn:${host}:${port}?transport=tcp`], username, credential }, + ] })); + }; +} diff --git a/package.json b/package.json index 90eecfc..219311a 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,10 @@ "type": "module", "scripts": { "dev": "vite", + "dev:setup": "node scripts/dev-setup.mjs", + "turn:up": "docker compose --env-file .env.development up -d", + "turn:down": "docker compose --env-file .env.development down", + "test:turn": "node scripts/browser-check.mjs --turn", "build": "vite build", "preview": "vite preview", "test": "node --test", diff --git a/scripts/browser-check.mjs b/scripts/browser-check.mjs index 86c233a..0be5f76 100644 --- a/scripts/browser-check.mjs +++ b/scripts/browser-check.mjs @@ -8,8 +8,12 @@ import { dirname, extname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const provider = process.argv.includes('--default-network') ? 'google' : 'none'; +const turn = process.argv.includes('--turn'); +const transport = process.argv.includes('--tcp') ? 'tcp' : 'udp'; +const vite = turn ? await (await import('vite')).createServer({ server: { middlewareMode: true }, appType: 'spa' }) : null; const profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-')); const server = createServer(async (req, res) => { + if (vite) return vite.middlewares(req, res); try { const pathname = new URL(req.url, 'http://localhost').pathname; const base = pathname.startsWith('/src/lib/') ? root : join(root, 'dist'); @@ -61,6 +65,19 @@ async function page() { const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true }); await call('Runtime.enable', {}, sessionId); await call('Page.enable', {}, sessionId); + if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: ` + window.__peers = []; + const NativePC = window.RTCPeerConnection; + window.RTCPeerConnection = class extends NativePC { + constructor(config) { super({ ...config, iceTransportPolicy: 'relay' }); window.__peers.push(this); } + setConfiguration(config) { + const iceServers = config.iceServers.filter(s => s.username).map(s => ({ ...s, + urls: (Array.isArray(s.urls) ? s.urls : [s.urls]).filter(url => url.endsWith('transport=${transport}')) + })); + super.setConfiguration({ ...config, iceServers, iceTransportPolicy: 'relay' }); + } + }; + ` }, sessionId); await call('Page.navigate', { url: origin }, sessionId); for (let n = 0; n < 100; n++) { try { if (await evaluate(sessionId, `location.origin === ${JSON.stringify(origin)} && document.readyState === 'complete'`)) break; } @@ -72,16 +89,19 @@ async function page() { } const click = (session, label) => evaluate(session, `(() => { const b = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === ${JSON.stringify(label)}); if (!b || b.disabled) throw new Error('Unavailable button: ' + ${JSON.stringify(label)}); b.click(); })()`); const input = (session, selector, value) => evaluate(session, `(() => { const el = document.querySelector(${JSON.stringify(selector)}); el.value = ${JSON.stringify(value)}; el.dispatchEvent(new Event(el.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true })); })()`); +const enableTurn = session => evaluate(session, `(() => { const checkbox = document.querySelector('.checkbox input'); if (!checkbox.checked) checkbox.click(); })()`); async function connect(sender, receiver, size) { await evaluate(sender, `(() => { const input = document.querySelector('#file-input'); const files = new DataTransfer(); files.items.add(new File([new Uint8Array(${size}).fill(123)], 'browser-test.bin')); input.files = files.files; input.dispatchEvent(new Event('change', { bubbles: true })); })()`); await input(sender, '#stun-provider', provider); await input(receiver, '#stun-provider', provider); + if (turn) { await enableTurn(sender); await enableTurn(receiver); } await click(sender, 'Create code'); await wait(sender, "!!document.querySelector('#output-code')"); const offer = await evaluate(sender, "document.querySelector('#output-code').value"); await input(receiver, '#offer-input', 'invalid-code!'); await click(receiver, 'Accept & create answer'); await wait(receiver, "!!document.querySelector('[role=alert]')"); assert.equal(await evaluate(receiver, "document.querySelector('#offer-input').disabled"), false); + if (turn) await enableTurn(receiver); await input(receiver, '#offer-input', offer); await click(receiver, 'Accept & create answer'); await wait(receiver, "!!document.querySelector('#output-code')"); const answer = await evaluate(receiver, "document.querySelector('#output-code').value"); @@ -100,6 +120,21 @@ async function connect(sender, receiver, size) { assert.equal(await evaluate(receiver, "!!document.querySelector('.incoming')"), false); await click(receiver, 'Both fingerprints match — confirm'); await wait(receiver, "!!document.querySelector('.incoming')"); + if (turn) { + for (const session of [sender, receiver]) { + const types = await evaluate(session, `(async () => { + for (let attempt = 0; attempt < 50; attempt++) { + const stats = await window.__peers.at(-1).getStats(); + const transport = [...stats.values()].find(s => s.type === 'transport' && s.selectedCandidatePairId); + const pair = transport && stats.get(transport.selectedCandidatePairId); + if (pair) return [stats.get(pair.localCandidateId)?.candidateType, stats.get(pair.remoteCandidateId)?.candidateType]; + await new Promise(resolve => setTimeout(resolve, 100)); + } + throw new Error('No selected ICE candidate pair in WebRTC statistics'); + })()`); + assert.deepEqual(types, ['relay', 'relay'], 'Both ends must actually use relay candidates'); + } + } } try { const sender = await page(), receiver = await page(); @@ -129,10 +164,12 @@ try { await click(receiver, 'Receive in memory (up to 64 MiB)'); await wait(sender, "document.querySelector('[role=status]').textContent.includes('confirmed the complete file')"); console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.'); + if (turn) console.log(`PASS: forced TURN over ${transport.toUpperCase()}, relay candidates at both ends, exact file bytes and receipt.`); assert.deepEqual(browserErrors, []); } finally { browser.kill(); await new Promise(resolve => { if (browser.exitCode !== null) resolve(); else browser.once('exit', resolve); }); await new Promise(resolve => server.close(resolve)); + await vite?.close(); await rm(profile, { recursive: true, force: true, maxRetries: 3 }); } diff --git a/scripts/dev-setup.mjs b/scripts/dev-setup.mjs new file mode 100644 index 0000000..45484ef --- /dev/null +++ b/scripts/dev-setup.mjs @@ -0,0 +1,12 @@ +import { randomBytes } from 'node:crypto'; +import { writeFile } from 'node:fs/promises'; + +try { + await writeFile(new URL('../.env.development', import.meta.url), + `# Local development only; shared by Compose and Vite.\nTURN_SECRET=${randomBytes(32).toString('hex')}\nTURN_HOST=127.0.0.1\nTURN_PORT=3478\nVITE_ICE_ENDPOINT=/api/ice-servers\nVITE_STUN_URL=stun:127.0.0.1:3478\n`, + { flag: 'wx', mode: 0o600 }); + console.log('Created .env.development with a private development TURN secret.'); +} catch (error) { + if (error.code !== 'EEXIST') throw error; + console.log('.env.development already exists; left unchanged. See .env.example for required settings.'); +} diff --git a/src/components/NetworkSettings.vue b/src/components/NetworkSettings.vue index 5790a5b..3fc06c9 100644 --- a/src/components/NetworkSettings.vue +++ b/src/components/NetworkSettings.vue @@ -2,6 +2,7 @@ import { STUN_PROVIDERS } from '../lib/webrtc.js'; const settings = defineModel({ required: true }); defineProps({ disabled: Boolean }); +const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || ''; diff --git a/src/components/TransferPanel.vue b/src/components/TransferPanel.vue index 204a669..0e75afa 100644 --- a/src/components/TransferPanel.vue +++ b/src/components/TransferPanel.vue @@ -1,7 +1,7 @@