Files
faunosteo/scripts/browser/serve.mjs
T
bchanot 4439fd2420 test(tests): R4.1e browser harness and TS baselines (Chromium, Firefox, WebKit)
Playwright harness under scripts/browser: 127.0.0.1 server with the DEPLOY
CSP, export and import baselines of the TypeScript engine under a 4 GiB RSS
watchdog (not a guaranteed memory limit), O9 browser columns in
inflate.browsers.json (26 rows agree with Node in all three engines).
Results of 2026-10-18 committed; the O9 Node test no longer expects browser
columns in inflate.json.
2026-10-18 15:05:28 +02:00

160 lines
5.3 KiB
JavaScript

// Static server of the production build for the browser harness (R4.1e):
// apps/app/dist with the SPA fallback of docker/nginx.conf, `.wasm` as
// application/wasm, the production CSP of DEPLOY.md on every response, and
// the env.js docker/entrypoint.sh writes when no APP_* variable is set (the
// local tool, no Supabase). Binds 127.0.0.1 only.
//
// node scripts/browser/serve.mjs [--port 4173] [--csp with|without]
//
// --csp with (default): script-src carries 'wasm-unsafe-eval' (DEPLOY.md
// note for R2+ images); without: the header exactly without the keyword,
// for the CSP proofs of later slices.
import { readFileSync } from 'node:fs'
import { readFile, stat } from 'node:fs/promises'
import { createServer } from 'node:http'
import { extname, join, resolve, sep } from 'node:path'
import { pathToFileURL } from 'node:url'
import { parseArgs } from 'node:util'
import { DIST_DIR, REPO_ROOT } from './lib/paths.mjs'
const HOST = '127.0.0.1'
const WASM_KEYWORD = "'wasm-unsafe-eval'"
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.wasm': 'application/wasm',
'.woff2': 'font/woff2',
'.txt': 'text/plain; charset=utf-8',
}
// Byte for byte what docker/entrypoint.sh writes with no APP_* variable set.
export const LOCAL_TOOL_ENV_JS = `window.__APP_CONFIG__ = {
siteName: "Faunosteo",
brandName: "Faunosteo",
footerName: "Faunosteo",
tagline: "Outils pour ostéopathes animaliers",
supabaseUrl: "",
supabaseAnonKey: "",
authProviders: ""
};
`
/** The nginx header line of DEPLOY.md, the one app-image.sh reads too. */
export function productionCsp() {
const deploy = readFileSync(join(REPO_ROOT, 'DEPLOY.md'), 'utf8')
const line = /^add_header Content-Security-Policy "(.*)" always;$/m
const match = line.exec(deploy)
if (!match) throw new Error('DEPLOY.md: no Content-Security-Policy line')
return match[1]
}
export function cspVariant(policy, variant) {
const without = policy.replace(` ${WASM_KEYWORD}`, '')
if (variant === 'without') return without
if (!without.includes("script-src 'self'")) {
throw new Error("DEPLOY.md CSP: no script-src 'self'")
}
return without.replace(
"script-src 'self'",
`script-src 'self' ${WASM_KEYWORD}`,
)
}
/** The request path, or null when it cannot be decoded safely. */
function requestPath(url) {
try {
const path = decodeURIComponent(new URL(url, 'http://local').pathname)
return path.includes('\0') ? null : path
} catch {
return null
}
}
/** A regular file under `root` for `path`, never outside it. */
async function fileUnder(root, path) {
const full = resolve(root, `.${path}`)
if (!full.startsWith(root + sep)) return null
try {
return (await stat(full)).isFile() ? full : null
} catch {
return null
}
}
function send(res, { status, body = '', type, csp, noStore = false, head }) {
const headers = { 'Content-Security-Policy': csp }
if (type) headers['Content-Type'] = type
if (noStore) headers['Cache-Control'] = 'no-store, no-cache, must-revalidate'
headers['Content-Length'] = Buffer.byteLength(body)
res.writeHead(status, headers)
res.end(head ? undefined : body)
}
/** nginx.conf: env.js generated, /assets/ files or 404, else the SPA. */
async function route(root, path) {
if (path === '/env.js') {
return { body: LOCAL_TOOL_ENV_JS, type: MIME['.js'], noStore: true }
}
const file = await fileUnder(root, path)
if (file) {
const type = MIME[extname(file)] ?? 'application/octet-stream'
return { body: await readFile(file), type }
}
if (path.startsWith('/assets/')) return { status: 404 }
return { body: await readFile(join(root, 'index.html')), type: MIME['.html'] }
}
async function respond(req, res, { root, csp }) {
const head = req.method === 'HEAD'
if (req.method !== 'GET' && !head) return send(res, { status: 405, csp })
const path = requestPath(req.url)
if (path === null) return send(res, { status: 400, csp })
try {
const answer = await route(root, path)
send(res, { status: 200, ...answer, csp, head })
} catch {
send(res, { status: 500, csp })
}
}
/** Starts the server; `port` 0 picks a free one. */
export function startServer({ root = DIST_DIR, port = 0, csp = 'with' } = {}) {
const policy = cspVariant(productionCsp(), csp)
const server = createServer((req, res) =>
respond(req, res, { root, csp: policy }),
)
return new Promise((done, fail) => {
server.once('error', fail)
server.listen(port, HOST, () => {
const url = `http://${HOST}:${server.address().port}`
done({ url, csp: policy, close: () => server.close() })
})
})
}
async function main() {
const { values } = parseArgs({
options: {
port: { type: 'string', default: '4173' },
csp: { type: 'string', default: 'with' },
},
})
if (!['with', 'without'].includes(values.csp)) {
throw new Error('--csp is "with" or "without"')
}
const server = await startServer({
port: Number(values.port),
csp: values.csp,
})
console.log(`serving apps/app/dist on ${server.url}`)
console.log(`Content-Security-Policy: ${server.csp}`)
}
if (import.meta.url === pathToFileURL(process.argv[1]).href) await main()