import { createServer, request as httpRequest } from 'node:http'; import { request as httpsRequest } from 'node:https'; import { realpath, stat, readFile } from 'node:fs/promises'; import { extname, resolve, sep } from 'node:path'; import net from 'node:net'; import tls from 'node:tls'; const mime = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.wasm': 'application/wasm', '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.json': 'application/json', '.css': 'text/css; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.apk': 'application/vnd.android.package-archive', }; const noCache = { 'Cache-Control': 'no-store' }; const timeoutMs = 5000; function reply(res, status, body = '') { if (res.destroyed) return; if (!res.headersSent) res.writeHead(status, { ...noCache, 'Content-Type': 'text/plain; charset=utf-8' }); res.end(body); } function inside(base, path) { return path === base || path.startsWith(base + sep); } async function staticFile(base, pathname, req, res) { let file = resolve(base, `.${pathname}`); if (!inside(base, file)) return reply(res, 403); try { let real = await realpath(file); if (!inside(base, real)) return reply(res, 403); if ((await stat(real)).isDirectory()) { real = await realpath(resolve(real, 'index.html')); if (!inside(base, real)) return reply(res, 403); } file = real; } catch (error) { if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') return reply(res, 403); if (extname(pathname)) return reply(res, 404, 'Not found'); try { file = await realpath(resolve(base, 'index.html')); if (!inside(base, file)) return reply(res, 403); } catch { return reply(res, 404, 'Not found'); } } try { const body = await readFile(file); res.writeHead(200, { ...noCache, 'Content-Type': mime[extname(file)] ?? 'application/octet-stream' }); res.end(req.method === 'HEAD' ? undefined : body); } catch { reply(res, 404, 'Not found'); } } const PUBLIC_ASSET = /^\/(favicon\.(svg|png|ico)|apple-touch-icon\.png|manifest\.json|icons\/[A-Za-z0-9-]+\.png)$/; function upstreamRequest(target, options, callback) { return (target.protocol === 'https:' ? httpsRequest : httpRequest)( { protocol: target.protocol, hostname: target.hostname, port: target.port || undefined, ...options, timeout: timeoutMs }, callback, ); } function proxy(req, res, target) { const url = new URL(req.url, target); const headers = { ...req.headers, host: target.host }; delete headers.connection; const upstream = upstreamRequest(target, { method: req.method, path: `${url.pathname}${url.search}`, headers }, (replyFromUpstream) => { const forwarded = { ...replyFromUpstream.headers, ...noCache }; res.writeHead(replyFromUpstream.statusCode ?? 502, forwarded); replyFromUpstream.on('error', () => res.destroy()); replyFromUpstream.pipe(res); }); upstream.setTimeout(timeoutMs, () => upstream.destroy(new Error('upstream timeout'))); upstream.on('error', () => reply(res, 502, 'Upstream unavailable')); req.on('aborted', () => upstream.destroy()); res.on('close', () => { if (!res.writableEnded) upstream.destroy(); }); if (req.method === 'GET' || req.method === 'HEAD') { req.resume(); upstream.end(); } else req.pipe(upstream); } function authCheck(req, target, callback) { let completed = false; const finish = (result) => { if (completed) return; completed = true; req.removeListener('aborted', abort); req.socket.removeListener('close', abort); callback(result); }; const abort = () => check.destroy(); const check = upstreamRequest(target, { method: 'GET', path: '/', headers: { cookie: req.headers.cookie ?? '', accept: 'text/html', 'accept-encoding': 'identity', } }, (response) => { response.resume(); finish(response.statusCode === 200); }); check.setTimeout(timeoutMs, () => check.destroy(new Error('authentication check timeout'))); check.on('error', () => finish(null)); req.once('aborted', abort); req.socket.once('close', abort); check.end(); } function reject(socket, status, phrase = 'Forbidden') { if (!socket.destroyed) socket.end(`HTTP/1.1 ${status} ${phrase}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`); } export async function start({ root = resolve('build/web'), upstream = 'http://127.0.0.1:8095', host = '127.0.0.1', port = 8096 } = {}) { const base = await realpath(root); const target = new URL(upstream); if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) throw new Error('UPSTREAM must be credential-free HTTP(S)'); const sockets = new Set(); const upgrades = new Set(); let closing = false; let closePromise; const server = createServer((req, res) => { let url; try { url = new URL(req.url, 'http://preview'); if (!req.url.startsWith('/') || req.url.startsWith('//')) throw new Error('invalid path'); decodeURIComponent(url.pathname); } catch { return reply(res, 400, 'Bad request'); } const pathname = decodeURIComponent(url.pathname); if (pathname.startsWith('//')) return reply(res, 400, 'Bad request'); if (!['GET', 'HEAD', 'POST'].includes(req.method)) { res.setHeader('Allow', 'GET, HEAD, POST'); return reply(res, 405); } if (pathname === '/login' || pathname === '/logout' || pathname === '/chat-uploads' || pathname.startsWith('/artifacts/')) return proxy(req, res, target); if (req.method !== 'GET' && req.method !== 'HEAD') return reply(res, 405); // Icons and the web manifest are public: browsers and app installers // fetch them without the session cookie. if (PUBLIC_ASSET.test(pathname)) return staticFile(base, pathname, req, res); authCheck(req, target, (authenticated) => { if (res.destroyed) return; if (authenticated === null) return reply(res, 502, 'Authentication upstream unavailable'); if (!authenticated) { if (req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html') && !pathname.startsWith('/assets/')) { res.writeHead(302, { ...noCache, Location: `/login?next=${encodeURIComponent(`${url.pathname}${url.search}`)}` }); return res.end(); } return reply(res, 401, 'Authentication required'); } staticFile(base, pathname, req, res); }); }); server.on('connection', (socket) => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); }); server.on('upgrade', (req, socket, head) => { upgrades.add(socket); socket.on('close', () => upgrades.delete(socket)); let origin; try { if (req.url.split('?')[0] !== '/connect' || !req.headers.host || !req.headers.origin || !req.url.startsWith('/')) throw new Error(); origin = new URL(req.headers.origin); if (!['http:', 'https:'].includes(origin.protocol) || origin.host.toLowerCase() !== req.headers.host.toLowerCase()) throw new Error(); } catch { return reject(socket, 403); } authCheck(req, target, (authenticated) => { if (closing || socket.destroyed) return; if (authenticated === null) return reject(socket, 502, 'Bad Gateway'); if (!authenticated) return reject(socket, 401, 'Unauthorized'); const connect = target.protocol === 'https:' ? tls.connect : net.connect; const upstreamSocket = connect({ host: target.hostname, port: Number(target.port || (target.protocol === 'https:' ? 443 : 80)), ...(target.protocol === 'https:' ? { servername: target.hostname } : {}) }); upgrades.add(upstreamSocket); upstreamSocket.on('close', () => upgrades.delete(upstreamSocket)); upstreamSocket.setTimeout(timeoutMs, () => upstreamSocket.destroy(new Error('upgrade timeout'))); // Bound establishment only. A healthy, idle chat socket stays connected. upstreamSocket.once('data', () => upstreamSocket.setTimeout(0)); upstreamSocket.once(target.protocol === 'https:' ? 'secureConnect' : 'connect', () => { const headers = { ...req.headers, host: target.host, origin: target.origin }; const lines = Object.entries(headers).filter(([, value]) => value != null) .map(([key, value]) => `${key}: ${Array.isArray(value) ? value.join(', ') : value}`).join('\r\n'); upstreamSocket.write(`GET ${req.url} HTTP/1.1\r\n${lines}\r\n\r\n`); if (head.length) upstreamSocket.write(head); upstreamSocket.pipe(socket); socket.pipe(upstreamSocket); }); upstreamSocket.on('error', () => socket.destroy()); socket.on('error', () => upstreamSocket.destroy()); socket.on('close', () => upstreamSocket.destroy()); }); }); await new Promise((resolveListen, rejectListen) => { server.once('error', rejectListen); server.listen(port, host, resolveListen); }); return { server, port: server.address().port, close: () => closePromise ??= new Promise((resolveClose, rejectClose) => { closing = true; for (const socket of upgrades) socket.destroy(); server.close((error) => error ? rejectClose(error) : resolveClose()); for (const socket of sockets) socket.destroy(); }), }; } if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { const args = Object.fromEntries(process.argv.slice(2).reduce((result, value, index, all) => { if (value.startsWith('--')) result.push([value.slice(2), all[index + 1]]); return result; }, [])); start({ root: args.root ?? 'build/web', upstream: process.env.UPSTREAM ?? args.upstream ?? 'http://127.0.0.1:8095', host: args.host ?? '127.0.0.1', port: Number(args.port ?? 8096) }) .then((preview) => console.log(`preview http://${args.host ?? '127.0.0.1'}:${preview.port}`)) .catch((error) => { console.error(error); process.exitCode = 1; }); }