Files
HellCon/dev/ice-server.ts
T

36 lines
1.6 KiB
TypeScript

import type { IncomingMessage } from 'node:http';
import { createHmac, randomUUID } from 'node:crypto';
interface IceResponse {
setHeader(name: string, value: string): unknown;
writeHead(status: number, headers?: Record<string, string>): unknown;
end(body?: string): unknown;
}
// Shared by Vite and the browser integration checks. Never imported by the client.
export function iceMiddleware(env: NodeJS.ProcessEnv) {
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: Pick<IncomingMessage, 'url' | 'method' | 'headers'>, res: IceResponse, next: () => void) => {
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 },
] }));
};
}