Add Coturn TURN server
This commit is contained in:
1 parent
752d0cf3af
commit
c3ca3e1752
13 files changed
+309
-11
No files matched your search
@@ -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
|
||||||
@@ -1,2 +1,5 @@
|
|||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
@@ -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
|
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.
|
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
|
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
|
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.
|
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
|
## 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
|
```sh
|
||||||
bun install --frozen-lockfile
|
bun install --frozen-lockfile
|
||||||
bun run dev
|
bun run dev
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -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 },
|
||||||
|
] }));
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -6,6 +6,10 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"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",
|
"build": "vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"test": "node --test",
|
"test": "node --test",
|
||||||
|
|||||||
@@ -8,8 +8,12 @@ import { dirname, extname, join, resolve } from 'node:path';
|
|||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
const provider = process.argv.includes('--default-network') ? 'google' : 'none';
|
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 profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-'));
|
||||||
const server = createServer(async (req, res) => {
|
const server = createServer(async (req, res) => {
|
||||||
|
if (vite) return vite.middlewares(req, res);
|
||||||
try {
|
try {
|
||||||
const pathname = new URL(req.url, 'http://localhost').pathname;
|
const pathname = new URL(req.url, 'http://localhost').pathname;
|
||||||
const base = pathname.startsWith('/src/lib/') ? root : join(root, 'dist');
|
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 });
|
const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true });
|
||||||
await call('Runtime.enable', {}, sessionId);
|
await call('Runtime.enable', {}, sessionId);
|
||||||
await call('Page.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);
|
await call('Page.navigate', { url: origin }, sessionId);
|
||||||
for (let n = 0; n < 100; n++) {
|
for (let n = 0; n < 100; n++) {
|
||||||
try { if (await evaluate(sessionId, `location.origin === ${JSON.stringify(origin)} && document.readyState === 'complete'`)) break; }
|
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 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 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) {
|
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 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(sender, '#stun-provider', provider);
|
||||||
await input(receiver, '#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')");
|
await click(sender, 'Create code'); await wait(sender, "!!document.querySelector('#output-code')");
|
||||||
const offer = await evaluate(sender, "document.querySelector('#output-code').value");
|
const offer = await evaluate(sender, "document.querySelector('#output-code').value");
|
||||||
await input(receiver, '#offer-input', 'invalid-code!');
|
await input(receiver, '#offer-input', 'invalid-code!');
|
||||||
await click(receiver, 'Accept & create answer');
|
await click(receiver, 'Accept & create answer');
|
||||||
await wait(receiver, "!!document.querySelector('[role=alert]')");
|
await wait(receiver, "!!document.querySelector('[role=alert]')");
|
||||||
assert.equal(await evaluate(receiver, "document.querySelector('#offer-input').disabled"), false);
|
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 input(receiver, '#offer-input', offer); await click(receiver, 'Accept & create answer');
|
||||||
await wait(receiver, "!!document.querySelector('#output-code')");
|
await wait(receiver, "!!document.querySelector('#output-code')");
|
||||||
const answer = await evaluate(receiver, "document.querySelector('#output-code').value");
|
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);
|
assert.equal(await evaluate(receiver, "!!document.querySelector('.incoming')"), false);
|
||||||
await click(receiver, 'Both fingerprints match — confirm');
|
await click(receiver, 'Both fingerprints match — confirm');
|
||||||
await wait(receiver, "!!document.querySelector('.incoming')");
|
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 {
|
try {
|
||||||
const sender = await page(), receiver = await page();
|
const sender = await page(), receiver = await page();
|
||||||
@@ -129,10 +164,12 @@ try {
|
|||||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
||||||
await wait(sender, "document.querySelector('[role=status]').textContent.includes('confirmed the complete file')");
|
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.');
|
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, []);
|
assert.deepEqual(browserErrors, []);
|
||||||
} finally {
|
} finally {
|
||||||
browser.kill();
|
browser.kill();
|
||||||
await new Promise(resolve => { if (browser.exitCode !== null) resolve(); else browser.once('exit', resolve); });
|
await new Promise(resolve => { if (browser.exitCode !== null) resolve(); else browser.once('exit', resolve); });
|
||||||
await new Promise(resolve => server.close(resolve));
|
await new Promise(resolve => server.close(resolve));
|
||||||
|
await vite?.close();
|
||||||
await rm(profile, { recursive: true, force: true, maxRetries: 3 });
|
await rm(profile, { recursive: true, force: true, maxRetries: 3 });
|
||||||
}
|
}
|
||||||
@@ -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.');
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
import { STUN_PROVIDERS } from '../lib/webrtc.js';
|
import { STUN_PROVIDERS } from '../lib/webrtc.js';
|
||||||
const settings = defineModel({ required: true });
|
const settings = defineModel({ required: true });
|
||||||
defineProps({ disabled: Boolean });
|
defineProps({ disabled: Boolean });
|
||||||
|
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -17,9 +18,12 @@ defineProps({ disabled: Boolean });
|
|||||||
<label class="checkbox"><input type="checkbox" v-model="settings.allowTurn" /> Allow a TURN relay for this connection (opt-in)</label>
|
<label class="checkbox"><input type="checkbox" v-model="settings.allowTurn" /> Allow a TURN relay for this connection (opt-in)</label>
|
||||||
<template v-if="settings.allowTurn">
|
<template v-if="settings.allowTurn">
|
||||||
<p class="status">Both people must opt in. Your browser may contact this relay and route encrypted file traffic through it. The operator sees addresses, timing and traffic volume, and may charge for bandwidth. Use credentials you are authorized to use; they remain in this tab.</p>
|
<p class="status">Both people must opt in. Your browser may contact this relay and route encrypted file traffic through it. The operator sees addresses, timing and traffic volume, and may charge for bandwidth. Use credentials you are authorized to use; they remain in this tab.</p>
|
||||||
<input v-model="settings.turnUrl" class="stun-input" aria-label="TURN address" placeholder="turns:relay.example:5349?transport=tcp" autocomplete="off" />
|
<label v-if="iceEndpoint" class="checkbox"><input type="checkbox" v-model="settings.managedTurn" /> Use the configured relay with temporary credentials</label>
|
||||||
<input v-model="settings.username" class="stun-input" aria-label="TURN username" placeholder="TURN username" autocomplete="off" />
|
<template v-if="!iceEndpoint || !settings.managedTurn">
|
||||||
<input v-model="settings.credential" class="stun-input" type="password" aria-label="TURN password" placeholder="TURN password" autocomplete="off" />
|
<input v-model="settings.turnUrl" class="stun-input" aria-label="TURN address" placeholder="turns:relay.example:5349?transport=tcp" autocomplete="off" />
|
||||||
|
<input v-model="settings.username" class="stun-input" aria-label="TURN username" placeholder="TURN username" autocomplete="off" />
|
||||||
|
<input v-model="settings.credential" class="stun-input" type="password" aria-label="TURN password" placeholder="TURN password" autocomplete="off" />
|
||||||
|
</template>
|
||||||
</template>
|
</template>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
</template>
|
</template>
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { computed, onBeforeUnmount, ref } from 'vue';
|
import { computed, onBeforeUnmount, ref } from 'vue';
|
||||||
import NetworkSettings from './NetworkSettings.vue';
|
import NetworkSettings from './NetworkSettings.vue';
|
||||||
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.js';
|
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.js';
|
||||||
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.js';
|
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.js';
|
||||||
|
|
||||||
const props = defineProps({ sending: Boolean });
|
const props = defineProps({ sending: Boolean });
|
||||||
@@ -18,7 +18,9 @@ const incoming = ref(null);
|
|||||||
const downloadUrl = ref('');
|
const downloadUrl = ref('');
|
||||||
const choosing = ref(false);
|
const choosing = ref(false);
|
||||||
const dragover = ref(false);
|
const dragover = ref(false);
|
||||||
const settings = ref({ stunChoice: 'google', customStun: '', allowTurn: false, turnUrl: '', username: '', credential: '' });
|
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
|
||||||
|
const defaultStun = import.meta.env.VITE_STUN_URL || '';
|
||||||
|
const settings = ref({ stunChoice: defaultStun ? 'custom' : 'google', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
|
||||||
const canSaveToDisk = typeof window.showSaveFilePicker === 'function';
|
const canSaveToDisk = typeof window.showSaveFilePicker === 'function';
|
||||||
let active = null;
|
let active = null;
|
||||||
let copyTimer;
|
let copyTimer;
|
||||||
@@ -109,7 +111,8 @@ function start() {
|
|||||||
stunUrl: chosen.stunChoice === 'custom' ? chosen.customStun.trim() || null : STUN_PROVIDERS.find(p => p.id === chosen.stunChoice)?.url ?? null,
|
stunUrl: chosen.stunChoice === 'custom' ? chosen.customStun.trim() || null : STUN_PROVIDERS.find(p => p.id === chosen.stunChoice)?.url ?? null,
|
||||||
turnUrl: chosen.turnUrl.trim(),
|
turnUrl: chosen.turnUrl.trim(),
|
||||||
};
|
};
|
||||||
const pc = createPeerConnection(options);
|
// Fetch managed credentials before gathering, while retaining normal cancellation.
|
||||||
|
const pc = createPeerConnection(iceEndpoint && options.managedTurn ? { ...options, allowTurn: false } : options);
|
||||||
const session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
|
const session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
|
||||||
active = session;
|
active = session;
|
||||||
session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000);
|
session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000);
|
||||||
@@ -133,6 +136,9 @@ async function createCode() {
|
|||||||
validateMetadata({ name: file.value.name, size: file.value.size, mime: file.value.type || '' });
|
validateMetadata({ name: file.value.name, size: file.value.size, mime: file.value.type || '' });
|
||||||
}
|
}
|
||||||
session = start();
|
session = start();
|
||||||
|
const configured = await fetchTurnOptions(session.options, iceEndpoint, { signal: session.controller.signal });
|
||||||
|
if (active !== session) return;
|
||||||
|
session.pc.setConfiguration(iceConfiguration(configured));
|
||||||
const options = { ...session.options, signal: session.controller.signal };
|
const options = { ...session.options, signal: session.controller.signal };
|
||||||
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v2'));
|
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v2'));
|
||||||
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options);
|
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options);
|
||||||
|
|||||||
+17
-1
@@ -16,7 +16,8 @@ export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl =
|
|||||||
}
|
}
|
||||||
// Credentials and URLs are ignored unless this user explicitly opts in.
|
// Credentials and URLs are ignored unless this user explicitly opts in.
|
||||||
if (allowTurn) {
|
if (allowTurn) {
|
||||||
if (!/^turns?:[^\s/?#@]+(?:\?transport=(?:udp|tcp))?$/i.test(turnUrl) || !username || !credential) {
|
const urls = Array.isArray(turnUrl) ? turnUrl : [turnUrl];
|
||||||
|
if (!urls.length || !urls.every(url => typeof url === 'string' && /^turns?:[^\s/?#@]+(?:\?transport=(?:udp|tcp))?$/i.test(url)) || !username || !credential) {
|
||||||
throw new Error('TURN opt-in requires a turn: or turns: address, username and password.');
|
throw new Error('TURN opt-in requires a turn: or turns: address, username and password.');
|
||||||
}
|
}
|
||||||
iceServers.push({ urls: turnUrl, username, credential });
|
iceServers.push({ urls: turnUrl, username, credential });
|
||||||
@@ -24,6 +25,21 @@ export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl =
|
|||||||
return { iceServers };
|
return { iceServers };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function fetchTurnOptions(options, endpoint, { signal, fetchImpl = fetch } = {}) {
|
||||||
|
if (!options.allowTurn || !options.managedTurn || !endpoint) return options;
|
||||||
|
const response = await fetchImpl(endpoint, { credentials: 'same-origin', cache: 'no-store', signal });
|
||||||
|
if (!response.ok) throw new Error('Could not obtain TURN credentials. Check the local dev server.');
|
||||||
|
const { expiresAt, iceServers } = await response.json();
|
||||||
|
const turn = iceServers?.find(server => {
|
||||||
|
const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
|
||||||
|
return urls.length && urls.every(url => /^turns?:/i.test(url));
|
||||||
|
});
|
||||||
|
if (!turn || !Number.isFinite(expiresAt) || expiresAt <= Date.now() / 1000 + 30) throw new Error('Missing or expired TURN credentials.');
|
||||||
|
const result = { ...options, turnUrl: turn.urls, username: turn.username, credential: turn.credential };
|
||||||
|
iceConfiguration(result); // Validate before passing server-supplied data to WebRTC.
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
export function createPeerConnection(options) {
|
export function createPeerConnection(options) {
|
||||||
return new RTCPeerConnection(iceConfiguration(options));
|
return new RTCPeerConnection(iceConfiguration(options));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createHmac } from 'node:crypto';
|
||||||
|
import { iceMiddleware } from '../dev/ice-server.js';
|
||||||
|
import { fetchTurnOptions } from '../src/lib/webrtc.js';
|
||||||
|
|
||||||
|
function request(handler, { method = 'GET', url = '/api/ice-servers', headers = { host: '127.0.0.1:5173' } } = {}) {
|
||||||
|
const result = { status: 200, headers: {} };
|
||||||
|
handler({ method, url, headers }, {
|
||||||
|
setHeader(key, value) { result.headers[key] = value; },
|
||||||
|
writeHead(status, headers) { result.status = status; Object.assign(result.headers, headers); },
|
||||||
|
end(body) { result.body = body ? JSON.parse(body) : undefined; },
|
||||||
|
}, () => { result.next = true; });
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('temporary credentials match coturn HMAC, expire in an hour and never expose the secret', () => {
|
||||||
|
const secret = 'test-only-secret';
|
||||||
|
const handler = iceMiddleware({ TURN_SECRET: secret });
|
||||||
|
const first = request(handler), second = request(handler);
|
||||||
|
assert.equal(first.headers['Cache-Control'], 'no-store');
|
||||||
|
const { expiresAt, iceServers } = first.body;
|
||||||
|
const turn = iceServers[1];
|
||||||
|
assert.ok(Math.abs(expiresAt - Date.now() / 1000 - 3600) < 2);
|
||||||
|
assert.ok(turn.username.startsWith(`${expiresAt}:`));
|
||||||
|
assert.notEqual(turn.username, second.body.iceServers[1].username);
|
||||||
|
assert.equal(turn.credential, createHmac('sha1', secret).update(turn.username).digest('base64'));
|
||||||
|
assert.deepEqual(turn.urls, ['turn:127.0.0.1:3478?transport=udp', 'turn:127.0.0.1:3478?transport=tcp']);
|
||||||
|
assert.ok(!JSON.stringify(first.body).includes(secret));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('development endpoint rejects cross-site issuance and unsupported methods', () => {
|
||||||
|
assert.throws(() => iceMiddleware({}), /TURN_SECRET/);
|
||||||
|
const handler = iceMiddleware({ TURN_SECRET: 'test' });
|
||||||
|
assert.equal(request(handler, { method: 'POST' }).status, 405);
|
||||||
|
assert.equal(request(handler, { headers: { 'sec-fetch-site': 'cross-site' } }).status, 403);
|
||||||
|
assert.equal(request(handler, { headers: { host: 'localhost', origin: 'http://elsewhere' } }).status, 403);
|
||||||
|
assert.equal(request(handler, { url: '/other' }).next, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('managed credentials require opt-in, refresh each connection, and fail closed', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const handler = iceMiddleware({ TURN_SECRET: 'test' });
|
||||||
|
const fetchImpl = async () => { calls++; return { ok: true, json: async () => request(handler).body }; };
|
||||||
|
await fetchTurnOptions({ managedTurn: true }, '/api/ice-servers', { fetchImpl });
|
||||||
|
await fetchTurnOptions({ allowTurn: true, managedTurn: false }, '/api/ice-servers', { fetchImpl });
|
||||||
|
assert.equal(calls, 0);
|
||||||
|
const options = { allowTurn: true, managedTurn: true, stunUrl: null };
|
||||||
|
const first = await fetchTurnOptions(options, '/api/ice-servers', { fetchImpl });
|
||||||
|
const second = await fetchTurnOptions(options, '/api/ice-servers', { fetchImpl });
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
assert.notEqual(first.username, second.username);
|
||||||
|
assert.equal(first.stunUrl, null, 'User STUN choice must be preserved');
|
||||||
|
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { fetchImpl: async () => ({ ok: false }) }), /Could not obtain/);
|
||||||
|
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { fetchImpl: async () => ({ ok: true, json: async () => ({ expiresAt: 1, iceServers: [] }) }) }), /expired/);
|
||||||
|
const controller = new AbortController(); controller.abort();
|
||||||
|
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { signal: controller.signal, fetchImpl: async (_url, { signal }) => { signal.throwIfAborted(); } }), { name: 'AbortError' });
|
||||||
|
});
|
||||||
+14
-4
@@ -1,8 +1,18 @@
|
|||||||
import { defineConfig } from 'vite';
|
import { defineConfig, loadEnv } from 'vite';
|
||||||
import vue from '@vitejs/plugin-vue';
|
import vue from '@vitejs/plugin-vue';
|
||||||
|
import { iceMiddleware } from './dev/ice-server.js';
|
||||||
|
|
||||||
// base './' so the built app can be served from any static path (or opened from a subdirectory)
|
// base './' so the built app can be served from any static path (or opened from a subdirectory)
|
||||||
export default defineConfig({
|
export default defineConfig(({ mode }) => {
|
||||||
base: './',
|
const env = { ...loadEnv(mode, process.cwd(), ''), ...process.env };
|
||||||
plugins: [vue()],
|
return {
|
||||||
|
base: './',
|
||||||
|
server: { host: '127.0.0.1' },
|
||||||
|
plugins: [vue(), {
|
||||||
|
name: 'local-turn-credentials',
|
||||||
|
configureServer(server) {
|
||||||
|
if (env.VITE_ICE_ENDPOINT === '/api/ice-servers') server.middlewares.use(iceMiddleware(env));
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
};
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user