fix(app): harden guarded preview proxy

This commit is contained in:
2026-10-21 13:32:54 +01:00
parent e3a82b0b36
commit 5cd269fca4
4 changed files with 366 additions and 96 deletions
+14 -4
View File
@@ -8,7 +8,17 @@ UPSTREAM=http://127.0.0.1:8095 node tool/preview/server.mjs --port 8080
```
The preview binds to loopback by default and authenticates static requests by
checking the upstream authenticated web proxy with the browser cookie. Login,
logout and artifacts are forwarded to that proxy; `/connect` is forwarded only
for same-origin websocket upgrades. Set `UPSTREAM` to the authenticated proxy,
never the raw control server. Tests use isolated local fixtures and port 0.
checking the upstream authenticated web proxy with the browser cookie. Unauthenticated
HTML navigation goes to the proxy's `/login?next=...`; unauthenticated assets and
WebSocket upgrades are refused. Login, logout and artifacts are streamed to the
proxy without decoding compressed response bodies. `/connect` accepts only a
same-origin browser Origin, checks the cookie, then maps Origin and Host to the
configured upstream origin before upgrading. HTTP and HTTPS upstreams are
supported using Node's normal TLS certificate verification. Set `UPSTREAM` to
the authenticated proxy, never the raw control server. The root path and files
must exist locally, and only GET, HEAD, and POST are supported. Tests use
isolated loopback fixtures and port 0.
The persistent preview API is `start({ root, upstream, host, port })` from
`tool/preview/server.mjs`; it resolves to `{ server, port, close }`. Call
`close()` to stop accepting requests and close tracked upgraded sockets.
+185 -56
View File
@@ -1,68 +1,197 @@
import { createServer } from 'node:http';
import { realpath, stat } from 'node:fs/promises';
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' };
const noCache = { 'Cache-Control':'no-store' };
const response = (res, status, body='') => { if (!res.headersSent) res.writeHead(status, { ...noCache, 'Content-Type':'text/plain; charset=utf-8' }); res.end(body); };
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',
};
const noCache = { 'Cache-Control': 'no-store' };
const timeoutMs = 5000;
export async function start({ root=resolve('build/web'), upstream='http://127.0.0.1:8095', host='127.0.0.1', port=8080 }={}) {
const base = await realpath(root), target = new URL(upstream);
if (!['http:','https:'].includes(target.protocol)) throw new Error('UPSTREAM must be HTTP(S)');
const server = createServer(async (req,res) => {
let pathname;
try { pathname = decodeURIComponent(new URL(req.url, 'http://preview').pathname); } catch { return response(res,400); }
if (!['GET','HEAD','POST'].includes(req.method)) { res.setHeader('Allow','GET, HEAD, POST'); return response(res,405); }
if (pathname === '/login' || pathname === '/logout' || pathname.startsWith('/artifacts/')) return proxy(req,res,target);
try {
const check = await fetch(new URL('/', target), { headers: { cookie:req.headers.cookie ?? '', accept:'text/html' }, redirect:'manual' });
if (!check.ok || check.status >= 300) return response(res, check.status === 401 || check.status === 302 ? 401 : 502, 'Authentication required');
} catch { return response(res,502,'Authentication upstream unavailable'); }
if (req.method !== 'GET' && req.method !== 'HEAD') return response(res,405);
let file = resolve(base, `.${pathname}`);
if (file !== base && !file.startsWith(base + sep)) return response(res,403);
try {
let real = await realpath(file);
if (real !== base && !real.startsWith(base + sep)) return response(res,403);
if ((await stat(real)).isDirectory()) {
real = await realpath(resolve(real,'index.html'));
if (real !== base && !real.startsWith(base + sep)) return response(res,403);
}
file = real;
const body = await (await import('node:fs/promises')).readFile(file);
res.writeHead(200,{...noCache,'Content-Type':mime[extname(file)] ?? 'application/octet-stream'}); res.end(req.method==='HEAD' ? undefined : body);
} catch (e) {
if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') return response(res,403);
if (extname(pathname)) return response(res,404,'Not found');
try {
const fallback=await realpath(resolve(base,'index.html'));
if (fallback !== base && !fallback.startsWith(base + sep)) return response(res,403);
const body=await (await import('node:fs/promises')).readFile(fallback);
res.writeHead(200,{...noCache,'Content-Type':mime['.html']}); res.end(body);
} catch { response(res,404,'Not found'); }
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);
}
});
server.on('upgrade', (req,socket,head) => {
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 {
const hostHeader=req.headers.host, origin=new URL(req.headers.origin);
if (req.url.split('?')[0] !== '/connect' || !hostHeader || origin.host.toLowerCase() !== hostHeader.toLowerCase() || !['http:','https:'].includes(origin.protocol)) return reject(socket,403);
const connect=target.protocol==='https:' ? tls.connect : net.connect;
const u=connect(Number(target.port || (target.protocol==='https:'?443:80)),target.hostname,()=>{
const headers={...req.headers,host:target.host}; delete headers.origin;
u.write(`GET ${req.url} HTTP/1.1\r\n${Object.entries(headers).map(([k,v])=>`${k}: ${v}`).join('\r\n')}\r\n\r\n`); if(head.length)u.write(head); u.pipe(socket); socket.pipe(u);
}); u.on('error',()=>socket.destroy()); socket.on('error',()=>u.destroy());
} catch { reject(socket,403); }
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'); }
}
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);
});
await new Promise((ok,fail)=>{server.once('error',fail);server.listen(port,host,ok)});
return { server, port:server.address().port, close:()=>new Promise((ok,fail)=>server.close(e=>e?fail(e):ok())) };
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 reject(socket,status){socket.end(`HTTP/1.1 ${status} Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)}
function proxy(req,res,target){
const url=new URL(req.url,target); fetch(url,{method:req.method,headers:{cookie:req.headers.cookie??'',...(req.headers['content-type']?{'content-type':req.headers['content-type']}:{})},body:['GET','HEAD'].includes(req.method)?undefined:req,duplex:'half',redirect:'manual'}).then(async r=>{res.writeHead(r.status,{...Object.fromEntries(r.headers),...noCache});res.end(Buffer.from(await r.arrayBuffer()))}).catch(()=>response(res,502,'Upstream unavailable'));
function authCheck(req, target, callback) {
let completed = false;
const finish = (result) => {
if (completed) return;
completed = true;
callback(result);
};
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.on('aborted', () => check.destroy());
req.socket.once('close', () => { if (!completed) check.destroy(); });
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 = 8080 } = {}) {
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.startsWith('/artifacts/')) return proxy(req, res, target);
if (req.method !== 'GET' && req.method !== 'HEAD') return reply(res, 405);
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')));
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((a,v,i,x)=>{if(v.startsWith('--'))a.push([v.slice(2),x[i+1]]);return a},[]));
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??8080)}).then(s=>console.log(`preview http://${args.host??'127.0.0.1'}:${s.port}`)).catch(e=>{console.error(e);process.exitCode=1});
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 ?? 8080) })
.then((preview) => console.log(`preview http://${args.host ?? '127.0.0.1'}:${preview.port}`))
.catch((error) => { console.error(error); process.exitCode = 1; });
}