anbot

root / test / browser / serve.mjs

2160 bytes

// Minimal read-only static server for the browser harness: serves the
// repository root over loopback HTTP. GET only, except for POSTs to
// /__harness-result, which record the harness outcome in a file for the
// test runner. Rejects path escapes.
import { createServer } from 'node:http'
import { readFile, writeFile } from 'node:fs/promises'
import { extname, join, normalize, resolve, sep } from 'node:path'

const args = process.argv.slice(2)
const get = name => {
  const index = args.indexOf(name)
  if (index === -1 || index + 1 >= args.length) throw new Error(`Missing ${name}`)
  return args[index + 1]
}
const root = resolve(get('--root'))
const port = Number(get('--port'))
const resultFile = args.includes('--result-file') ? resolve(get('--result-file')) : null
const types = {
  '.html': 'text/html; charset=utf-8',
  '.mjs': 'text/javascript; charset=utf-8',
  '.js': 'text/javascript; charset=utf-8',
  '.json': 'application/json',
  '.md': 'text/plain; charset=utf-8'
}

const server = createServer(async (request, response) => {
  try {
    if (request.method === 'POST' && request.url === '/__harness-result' && resultFile) {
      const chunks = []
      let bytes = 0
      for await (const chunk of request) {
        bytes += chunk.length
        if (bytes > 65536) {
          response.writeHead(413).end()
          return
        }
        chunks.push(chunk)
      }
      await writeFile(resultFile, Buffer.concat(chunks))
      response.writeHead(200).end()
      return
    }
    if (request.method !== 'GET') {
      response.writeHead(405).end()
      return
    }
    const pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname)
    const path = normalize(join(root, pathname))
    if (path !== root && !path.startsWith(root + sep)) {
      response.writeHead(404).end()
      return
    }
    const bytes = await readFile(path)
    response.writeHead(200, { 'Content-Type': types[extname(path)] ?? 'application/octet-stream' }).end(bytes)
  } catch {
    if (!response.headersSent) response.writeHead(404).end()
  }
})
server.listen(port, '127.0.0.1', () => console.log(`http://127.0.0.1:${port}`))

Git ยท Social feed