feat(app): add guarded web preview server

This commit is contained in:
2026-10-21 13:25:09 +01:00
parent 718442d73d
commit e3a82b0b36
3 changed files with 130 additions and 0 deletions
+48
View File
@@ -0,0 +1,48 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createServer } from 'node:http';
import { start } from '../../tool/preview/server.mjs';
test('serves guarded assets, deep links, MIME and missing assets; forwards auth routes and artifacts', async t => {
const dir=await mkdtemp(join(tmpdir(),'preview-')); await mkdir(join(dir,'assets')); await writeFile(join(dir,'index.html'),'shell'); await writeFile(join(dir,'assets/a.wasm'),'wasm');
const upstream=createServer((req,res)=>{ if(req.url==='/') {res.writeHead(req.headers.cookie==='sid=yes'?200:302,{location:'/login'}).end();return} res.writeHead(200,{'x-forwarded':req.url}).end(req.url) });
await new Promise(ok=>upstream.listen(0,'127.0.0.1',ok));
const preview=await start({root:dir,upstream:`http://127.0.0.1:${upstream.address().port}`,port:0}); t.after(async()=>{await preview.close();upstream.close();await rm(dir,{recursive:true,force:true})});
const base=`http://127.0.0.1:${preview.port}`;
assert.equal((await fetch(base+'/assets/a.wasm')).status,401);
const headers={cookie:'sid=yes'};
const wasm=await fetch(base+'/assets/a.wasm',{headers}); assert.equal(wasm.headers.get('content-type'),'application/wasm'); assert.equal(wasm.headers.get('cache-control'),'no-store');
assert.equal(await (await fetch(base+'/runs/4',{headers})).text(),'shell');
assert.equal((await fetch(base+'/assets/missing.js',{headers})).status,404);
assert.equal((await fetch(base+'/..%2f..%2fetc/passwd',{headers})).status,403);
assert.equal((await fetch(base+'/artifacts/1/a',{headers})).status,200);
assert.equal((await fetch(base+'/login')).status,200);
});
test('rejects a directory index symlink that escapes the preview root', async t => {
const dir=await mkdtemp(join(tmpdir(),'preview-')), outside=await mkdtemp(join(tmpdir(),'preview-out-'));
await mkdir(join(dir,'linked')); await writeFile(join(outside,'secret.html'),'secret');
await symlink(join(outside,'secret.html'),join(dir,'linked','index.html'));
const upstream=createServer((req,res)=>res.end('ok'));
await new Promise(ok=>upstream.listen(0,'127.0.0.1',ok));
const preview=await start({root:dir,upstream:`http://127.0.0.1:${upstream.address().port}`,port:0});
t.after(async()=>{await preview.close();upstream.close();await rm(dir,{recursive:true,force:true});await rm(outside,{recursive:true,force:true})});
const response=await fetch(`http://127.0.0.1:${preview.port}/linked/`,{headers:{cookie:'sid=yes'}});
assert.equal(response.status,403);
});
test('rejects an SPA fallback index symlink that escapes the preview root', async t => {
const dir=await mkdtemp(join(tmpdir(),'preview-')), outside=await mkdtemp(join(tmpdir(),'preview-out-'));
await writeFile(join(outside,'secret.html'),'secret');
await symlink(join(outside,'secret.html'),join(dir,'index.html'));
const upstream=createServer((req,res)=>res.end('ok'));
await new Promise(ok=>upstream.listen(0,'127.0.0.1',ok));
const preview=await start({root:dir,upstream:`http://127.0.0.1:${upstream.address().port}`,port:0});
t.after(async()=>{await preview.close();upstream.close();await rm(dir,{recursive:true,force:true});await rm(outside,{recursive:true,force:true})});
const response=await fetch(`http://127.0.0.1:${preview.port}/missing-route`,{headers:{cookie:'sid=yes'}});
assert.equal(response.status,403);
assert.notEqual(await response.text(),'secret');
});
+14
View File
@@ -0,0 +1,14 @@
# Flutter web preview
Build and run from `app/`:
```sh
/Users/alan/development/flutter/bin/flutter build web
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.
+68
View File
@@ -0,0 +1,68 @@
import { createServer } from 'node:http';
import { realpath, stat } 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); };
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'); }
}
});
server.on('upgrade', (req,socket,head) => {
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); }
});
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())) };
}
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'));
}
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});
}