Files
faunosteo/scripts/browser/serve.mjs
T
bchanot c84186b032 test(tests): R4.2e browser measurements of the Rust import (module worker page, same perimeter as the TS baseline)
r4-import.mjs runs the 226 baseline files and the hostile classes through a disposable
module worker calling SheetHandle.import_pdf in Chromium 156, Firefox 157 and WebKit 27.2
under the RSS watchdog (not a guaranteed limit); compare-imports.mjs prints TS vs Rust;
serve.mjs gains opt-in mounts (/r4/, /pkg/). Results 2026-10-18-r4-import.json: 666/678
agreements, the 12 others are the 4 declared files; W4 met (max 68 MiB linear); the
1 GiB ceiling traps in every engine.
2026-10-18 16:58:42 +02:00

195 lines
6.5 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] [--r4]
//
// --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.
//
// --r4 also mounts the R4 import page and the core module builds (R4.2e,
// r4-import.mjs): /r4/ (scripts/browser/r4-import-page), /pkg/ and
// /pkg-proofs/ (packages/core-wasm). A mounted path is a file or a 404,
// never the SPA fallback. Without it nothing changes.
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, HARNESS_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',
}
export const R4_MOUNTS = {
'/r4/': join(HARNESS_DIR, 'r4-import-page'),
'/pkg/': join(REPO_ROOT, 'packages/core-wasm/pkg'),
'/pkg-proofs/': join(REPO_ROOT, 'packages/core-wasm/pkg-proofs'),
}
// 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)
}
async function fileAnswer(file) {
const type = MIME[extname(file)] ?? 'application/octet-stream'
return { body: await readFile(file), type }
}
/** A mounted directory: its file (index.html for a directory) or a 404. */
async function mountedAnswer(mounts, path) {
const prefix = Object.keys(mounts).find((p) => path.startsWith(p))
if (!prefix) return null
const rest = path.slice(prefix.length - 1)
const file = await fileUnder(
mounts[prefix],
rest.endsWith('/') ? `${rest}index.html` : rest,
)
return file ? fileAnswer(file) : { status: 404 }
}
/** nginx.conf: env.js generated, /assets/ files or 404, else the SPA. */
async function route(root, path, mounts) {
const mounted = await mountedAnswer(mounts, path)
if (mounted) return mounted
if (path === '/env.js') {
return { body: LOCAL_TOOL_ENV_JS, type: MIME['.js'], noStore: true }
}
const file = await fileUnder(root, path)
if (file) return fileAnswer(file)
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, mounts }) {
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, mounts)
send(res, { status: 200, ...answer, csp, head })
} catch {
send(res, { status: 500, csp })
}
}
/** Starts the server; `port` 0 picks a free one; `mounts` see --r4. */
export function startServer({
root = DIST_DIR,
port = 0,
csp = 'with',
mounts = {},
} = {}) {
const policy = cspVariant(productionCsp(), csp)
const server = createServer((req, res) =>
respond(req, res, { root, csp: policy, mounts }),
)
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' },
r4: { type: 'boolean', default: false },
},
})
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,
mounts: values.r4 ? R4_MOUNTS : {},
})
console.log(`serving apps/app/dist on ${server.url}`)
if (values.r4) console.log(`R4 import page on ${server.url}/r4/`)
console.log(`Content-Security-Policy: ${server.csp}`)
}
if (import.meta.url === pathToFileURL(process.argv[1]).href) await main()