okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
5.1 KiB147 linesraw
1/** Shared helpers for the Strata host. */
2import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
3import { execFile } from 'node:child_process';
4import { promisify } from 'node:util';
5import { whichCommand } from './platform-paths.mjs';
6
7export const exec = promisify(execFile);
8export const uid = (prefix = 'id') => `${prefix}_${randomUUID().slice(0, 8)}`;
9export const nowIso = () => new Date().toISOString();
10export const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
11export const round = (n, d = 1) => Number(n.toFixed(d));
12
13export function json(res, status, body) {
14  const payload = JSON.stringify(body);
15  res.writeHead(status, {
16    'content-type': 'application/json; charset=utf-8',
17    'content-length': Buffer.byteLength(payload),
18    'cache-control': 'no-store',
19  });
20  res.end(payload);
21}
22
23export function error(res, status, message, extra = {}) {
24  json(res, status, { error: message, ...extra });
25}
26
27/**
28 * Two secrets compared in constant time (#4535). Both sides are hashed first, so the comparison always runs over two
29 * 32-byte digests: neither the content nor the length of the given value can end it early. Anything that is not a
30 * non-empty string never matches (an empty secret is "not set", not "equal to an empty header").
31 */
32export function sameSecret(given, wanted) {
33  const ok = typeof given === 'string' && typeof wanted === 'string' && given.length > 0 && wanted.length > 0;
34  const digest = value => createHash('sha256').update(typeof value === 'string' ? value : '', 'utf8').digest();
35  return timingSafeEqual(digest(given), digest(wanted)) && ok;
36}
37
38/**
39 * The request's URL, or null when the request cannot be read as one (#4397). The Host header is the caller's: an empty
40 * value, one with a space, a path, credentials or an unclosed bracket used to make `new URL` throw before the routing
41 * try/catch and end the whole process. A missing Host (HTTP/1.0) is read as localhost; a good one keeps its port and IPv6 form.
42 */
43export function requestUrl(req) {
44  const host = req.headers?.host;
45  try {
46    let authority = 'localhost';
47    if (host !== undefined) {
48      if (typeof host !== 'string' || !host.trim() || /[\s/?#@\\]/.test(host)) return null;
49      const base = new URL(`http://${host}`);
50      if (!base.host || base.username || base.password || base.search || base.hash || base.pathname !== '/') return null;
51      authority = host;
52    }
53    return new URL(req.url ?? '/', `http://${authority}`);
54  } catch {
55    return null;
56  }
57}
58
59/** The answer to a request that could not be read as a URL: bounded, and the connection closes. */
60export function badRequest(res) {
61  if (res.headersSent) return res.end();
62  const payload = '{"error":"bad_host"}';
63  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(payload), 'cache-control': 'no-store', connection: 'close' });
64  res.end(payload);
65}
66
67export async function readBody(req, limit = 4 * 1024 * 1024) {
68  const chunks = [];
69  let size = 0;
70  for await (const chunk of req) {
71    size += chunk.length;
72    if (size > limit) throw new Error('Request body too large');
73    chunks.push(chunk);
74  }
75  if (!chunks.length) return {};
76  const raw = Buffer.concat(chunks).toString('utf8');
77  try {
78    return JSON.parse(raw);
79  } catch {
80    throw new Error('Body must be JSON');
81  }
82}
83
84/** Run a command, returning stdout or '' when it is missing or fails. */
85export async function probe(cmd, args = [], timeout = 4000) {
86  try {
87    const { stdout } = await exec(cmd, args, { timeout, maxBuffer: 4 * 1024 * 1024 });
88    return stdout.trim();
89  } catch {
90    return '';
91  }
92}
93
94/** Where `binary` is on PATH, or null. `/usr/bin/env which` on POSIX, System32\where.exe on Windows (first match). */
95export async function which(binary, { env = process.env, platform = process.platform, run = probe } = {}) {
96  const { command, args } = whichCommand(binary, env, platform);
97  const out = await run(command, args);
98  return out.split(/\r?\n/)[0].trim() || null;
99}
100
101/** Minimal SSE hub. */
102export class EventHub {
103  #clients = new Set();
104
105  add(res) {
106    res.writeHead(200, {
107      'content-type': 'text/event-stream; charset=utf-8',
108      'cache-control': 'no-cache, no-transform',
109      connection: 'keep-alive',
110      'x-accel-buffering': 'no',
111    });
112    res.write(': connected\n\n');
113    this.#clients.add(res);
114    const ping = setInterval(() => res.write(': ping\n\n'), 15000);
115    res.on('close', () => {
116      clearInterval(ping);
117      this.#clients.delete(res);
118    });
119  }
120
121  send(event, payload) {
122    const frame = `event: ${event}\ndata: ${JSON.stringify(payload)}\n\n`;
123    for (const res of this.#clients) {
124      try {
125        res.write(frame);
126      } catch {
127        this.#clients.delete(res);
128      }
129    }
130  }
131
132  get size() {
133    return this.#clients.size;
134  }
135}
136
137/** The raw bytes of a request body (an upload), up to `limit`. */
138export async function readRaw(req, limit = 16 * 1024 * 1024) {
139  const chunks = [];
140  let size = 0;
141  for await (const chunk of req) {
142    size += chunk.length;
143    if (size > limit) throw new Error('That upload is too big.');
144    chunks.push(chunk);
145  }
146  return Buffer.concat(chunks);
147}