import test from 'node:test'; import assert from 'node:assert/strict'; import { createHmac } from 'node:crypto'; import { iceMiddleware } from '../dev/ice-server.ts'; import { fetchTurnOptions } from '../src/lib/webrtc.ts'; interface Credentials { expiresAt: number; iceServers: [{ urls: string }, { urls: string[]; username: string; credential: string }]; } interface ResponseResult { status: number; headers: Record; body?: Credentials; next?: boolean; } function request(handler: ReturnType, { method = 'GET', url = '/api/ice-servers', headers = { host: '127.0.0.1:5173' } }: { method?: string; url?: string; headers?: Record } = {}) { const result: ResponseResult = { 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'); assert.ok(first.body); assert.ok(second.body); 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, json: async () => null }) }), /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(); throw new Error('Expected abort'); } }), { name: 'AbortError' }); }); test('managed credentials reject malformed response shapes and non-string credentials', async () => { const expiresAt = Date.now() / 1000 + 3600; const turn = { urls: 'turn:localhost:3478', username: 'user', credential: 'password' }; for (const body of [ null, [], { expiresAt, iceServers: {} }, { expiresAt, iceServers: [null] }, { expiresAt, iceServers: [{ ...turn, urls: [null] }] }, { expiresAt, iceServers: [{ ...turn, urls: [] }] }, { expiresAt, iceServers: [{ ...turn, username: 123 }] }, { expiresAt, iceServers: [{ ...turn, credential: {} }] }, { expiresAt, iceServers: [{ ...turn, urls: 'turn:bad host' }] }, ]) { await assert.rejects(fetchTurnOptions({ allowTurn: true, managedTurn: true }, '/api/ice-servers', { fetchImpl: async () => ({ ok: true, json: async () => body }), }), /credentials|TURN opt-in/); } });