import http from 'node:http'; import net from 'node:net'; import { randomBytes, timingSafeEqual } from 'node:crypto'; import { resolvePublic, webUrl } from './policy.mjs'; // A destination is resolved once and the socket connects to that exact address. // Never pass the original hostname to a second resolver after the policy check. export async function createGateway({ resolver, allowedTestHosts = new Set() } = {}) { const username = 'runestone'; const password = randomBytes(32).toString('hex'); const expected = Buffer.from(`Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`); const sockets = new Set(); let stopped = false; let resolving = 0; const authenticate = (req, socket) => { const actual = Buffer.from(req.headers['proxy-authorization'] || ''); if (actual.length === expected.length && timingSafeEqual(actual, expected)) return true; socket.end('HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm="RuneStone"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'); return false; }; const destination = async (host, port) => { if (stopped) throw new Error('Network gate is stopped.'); if (![80, 443].includes(port) && !allowedTestHosts.has(host)) throw new Error('Destination port is blocked.'); if (resolving >= 64) throw new Error('The DNS request limit was reached.'); resolving++; let timer; try { return await Promise.race([ resolvePublic(host, resolver, allowedTestHosts), new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error('DNS lookup timed out.')), 10_000); }), ]); } finally { clearTimeout(timer); resolving--; } }; const track = (socket) => { sockets.add(socket); socket.on('error', () => {}); socket.once('close', () => sockets.delete(socket)); socket.setTimeout(60_000, () => socket.destroy()); }; const server = http.createServer({ maxHeaderSize: 16_384, requestTimeout: 30_000, headersTimeout: 15_000 }, async (req, res) => { if (!authenticate(req, req.socket)) return; try { const url = new URL(webUrl(req.url, { blank: false })); if (url.protocol !== 'http:') throw new Error('HTTPS requires CONNECT.'); const port = Number(url.port || 80); const target = await destination(url.hostname, port); if (stopped || req.destroyed) return res.destroy(); const headers = { ...req.headers, host: url.host, connection: 'close' }; for (const name of ['proxy-authorization', 'proxy-connection', 'upgrade', ...(req.headers.connection || '').toLowerCase().split(',').map(x => x.trim())]) delete headers[name]; const upstream = http.request({ hostname: target.address, family: target.family, port, path: url.pathname + url.search, method: req.method, headers, agent: false }, (response) => { res.writeHead(response.statusCode, response.headers); response.pipe(res); }); upstream.on('socket', track); upstream.on('error', () => { if (!res.headersSent) res.writeHead(502); res.end(); }); res.once('close', () => upstream.destroy()); req.pipe(upstream); } catch { res.writeHead(403); res.end('Destination blocked.'); } }); server.on('connect', async (req, client, head) => { if (!authenticate(req, client)) return; try { if (!/^(?:\[[\da-fA-F:]+\]|[^:/\s@?#]+):\d+$/.test(req.url)) throw new Error('Invalid tunnel destination.'); const url = new URL(`https://${req.url}`); const port = Number(url.port || 443); const target = await destination(url.hostname, port); if (stopped || client.destroyed) return client.destroy(); const upstream = net.connect({ host: target.address, family: target.family, port }); track(upstream); upstream.once('connect', () => { client.write('HTTP/1.1 200 Connection Established\r\n\r\n'); if (head.length) upstream.write(head); client.pipe(upstream); upstream.pipe(client); }); upstream.once('error', () => client.destroy()); client.once('close', () => upstream.destroy()); } catch { client.end('HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'); } }); server.on('upgrade', (_req, socket) => socket.destroy()); server.on('connection', (socket) => { if (stopped || sockets.size >= 256) return socket.destroy(); track(socket); }); await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); }); return { port: server.address().port, username, password, close() { stopped = true; for (const socket of sockets) socket.destroy(); return new Promise(resolve => server.close(resolve)); }, }; }