Files
faunosteo/scripts/browser/serve.mjs
T

270 lines
9.4 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 by default, or the one address
// `--host` resolves to (the DEV origin); never a wildcard address.
//
// 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.
//
// startServer({ reportViolations: true }) (r4-app-csp.mjs) appends
// `report-uri /__csp-report` to the policy and keeps the reports POSTed
// there; not a CLI option.
import { readFileSync } from 'node:fs'
import { readFile, stat } from 'node:fs/promises'
import { lookup } from 'node:dns/promises'
import { createServer } from 'node:http'
import { BlockList } from 'node:net'
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'
/** The wildcard addresses, in every spelling the resolver and the kernel accept. */
const WILDCARDS = new BlockList()
WILDCARDS.addAddress('0.0.0.0', 'ipv4')
WILDCARDS.addAddress('::', 'ipv6')
const isWildcard = ({ address, family }) =>
WILDCARDS.check(address.replace(/%.*$/, ''), family === 6 ? 'ipv6' : 'ipv4')
/**
* The one address `host` names, resolved before any socket exists: an empty
* host, a wildcard in any spelling (`0`, `0::`, `::ffff:0.0.0.0`…) or a name
* resolving to one is refused, so the server can never bind every interface.
*/
async function bindAddress(host) {
if (!host.trim()) throw new Error('--host must name one address')
const results = await lookup(host, { all: true, verbatim: true })
if (results.length === 0 || results.some(isWildcard)) {
throw new Error(`--host "${host}" resolves to a wildcard address`)
}
return results[0]
}
const WASM_KEYWORD = "'wasm-unsafe-eval'"
const REPORT_PATH = '/__csp-report'
const MAX_REPORT_BYTES = 64 * 1024
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'] }
}
/** A violation report the browser POSTs (`report-uri`), kept as sent. */
async function collectReport(req, res, { csp, reports }) {
const chunks = []
let size = 0
for await (const chunk of req) {
size += chunk.length
if (size > MAX_REPORT_BYTES) break
chunks.push(chunk)
}
try {
reports.push(JSON.parse(Buffer.concat(chunks).toString('utf8')))
} catch {
reports.push({ unparsed: true, bytes: size })
}
send(res, { status: 204, csp })
}
async function respond(req, res, { root, csp, mounts, reports }) {
if (reports && req.method === 'POST' && req.url === REPORT_PATH) {
return collectReport(req, res, { csp, reports })
}
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;
* `reportViolations` appends `report-uri` to the policy (its directives
* unchanged) and keeps every report the browser POSTs in `reports`.
*/
export function startServer({
root = DIST_DIR,
port = 0,
csp = 'with',
mounts = {},
reportViolations = false,
host = HOST,
} = {}) {
const enforced = cspVariant(productionCsp(), csp)
const policy = reportViolations
? `${enforced}; report-uri ${REPORT_PATH}`
: enforced
const reports = reportViolations ? [] : null
const server = createServer((req, res) =>
respond(req, res, { root, csp: policy, mounts, reports }),
)
return bindAddress(host).then(
({ address }) =>
new Promise((done, fail) => {
server.once('error', fail)
server.listen(port, address, () => {
// Belt and braces: the socket itself is never on a wildcard.
if (isWildcard(server.address())) {
server.close()
fail(new Error('the server bound a wildcard address'))
return
}
const shown = address.includes(':') ? `[${address}]` : address
const url = `http://${shown}:${server.address().port}`
done({ url, csp: policy, reports, 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 },
// The owner's device acceptance (J1): the production build behind the DEPLOY CSP on
// the DEV origin (scripts/dev-env.sh), never on every interface.
host: { type: 'string', default: HOST },
},
})
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 : {},
host: values.host,
})
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()