package file→ .shtukbase/packages/live/server/server.ts
server/server.ts
364 lines, 19.5 KB.
- // The live server: the project folder as a static site plus a small API to read and change records, run allowed
- // actions and hear about changed files. Only on this computer (127.0.0.1); every write needs the session token.
- // Bun only, no dependencies. The pieces: fm.ts (front matter in place), records.ts (collections and the schema),
- // run.ts (allowed actions), settings.ts (the page /base/live.md).
- import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, watch, writeFileSync, type FSWatcher } from 'node:fs';
- import { dirname, extname, join } from 'node:path';
- import { pystr } from '../../collections/checks/lib/pages.ts';
- import { fields, join as joinPage, setBody, setFields, split } from './fm.ts';
- import { type Collection, Invalid, NotFound, Refused, collection, collectionOf, collections, phasesOf, readRecord, recordPaths, safePath, slug, validate } from './records.ts';
- import { execute, plan } from './run.ts';
- import { LOOPBACK, PAGE, readSettings } from './settings.ts';
- export const VERSION = '0.1.0';
- const COOKIE = 'live_token';
- export type Options = { root: string; port?: number; host?: string; token?: string; build?: boolean; quiet?: boolean };
- export type Live = { url: string; link: string; token: string; port: number; host: string; stop: () => void };
- class Unauthorized extends Error {}
- class Conflict extends Error {}
- class BadRequest extends Error {}
- const TYPES: Record<string, string> = {
- '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
- '.css': 'text/css; charset=utf-8', '.md': 'text/plain; charset=utf-8', '.txt': 'text/plain; charset=utf-8',
- '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
- '.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon', '.pdf': 'application/pdf', '.woff2': 'font/woff2',
- };
- const redirect = (location: string) => new Response(null, { status: 302, headers: { location } });
- const etagOf = (text: string) => createHash('sha1').update(text).digest('hex').slice(0, 16);
- /** Writes through a temporary file in the same folder and a rename: a reader never sees half a file. */
- function writeAtomic(file: string, text: string): void {
- mkdirSync(dirname(file), { recursive: true });
- const tmp = join(dirname(file), `.${Date.now().toString(36)}-${randomBytes(4).toString('hex')}.live.tmp`);
- writeFileSync(tmp, text);
- renameSync(tmp, file);
- }
- const json = (data: unknown, status = 200, headers: Record<string, string> = {}) =>
- new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...headers } });
- function errorResponse(e: unknown): Response {
- if (e instanceof Invalid) return json({ error: e.message, field: e.errors[0]?.field ?? null, errors: e.errors }, 422);
- if (e instanceof Unauthorized) return json({ error: e.message }, 401);
- if (e instanceof Refused) return json({ error: e.message }, 403);
- if (e instanceof NotFound) return json({ error: e.message }, 404);
- if (e instanceof Conflict) return json({ error: e.message }, 409);
- if (e instanceof BadRequest) return json({ error: e.message }, 400);
- return json({ error: `server error: ${(e as Error).message ?? e}` }, 500);
- }
- export function start(opts: Options): Live {
- const root = opts.root.replace(/\/+$/, '');
- const settings = readSettings(root);
- if (settings.problems.length) throw new Error(`the settings of ${PAGE} break the norms:\n ${settings.problems.join('\n ')}`);
- const host = opts.host ?? settings.host;
- if (!LOOPBACK.has(host)) throw new Error(`host ${host}: the server listens only on this computer (127.0.0.1, localhost, ::1)`);
- const token = opts.token ?? randomBytes(18).toString('base64url');
- const tokenBuf = Buffer.from(token);
- const lensBuild = join(root, '.shtukbase', 'packages', 'lenses', 'actions', 'build.mjs');
- const build = opts.build !== false && existsSync(lensBuild);
- const log = (s: string) => { if (!opts.quiet) console.log(s); };
- let port = 0;
- const hosts = () => new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
- const tokenOk = (t: string | null | undefined) => !!t && t.length === token.length && timingSafeEqual(Buffer.from(t), tokenBuf);
- const authorized = (req: Request) => {
- const auth = req.headers.get('authorization');
- if (auth?.startsWith('Bearer ') && tokenOk(auth.slice(7).trim())) return true;
- if (tokenOk(req.headers.get('x-live-token'))) return true;
- const cookie = req.headers.get('cookie') ?? '';
- const m = new RegExp(`(?:^|;\\s*)${COOKIE}=([^;]+)`).exec(cookie);
- return !!m && tokenOk(decodeURIComponent(m[1]));
- };
- const needToken = (req: Request) => {
- if (!authorized(req)) throw new Unauthorized('the session token is needed: open the link the server printed at start (it has ?token=...), or send the header Authorization: Bearer <token>');
- };
- const body = async (req: Request): Promise<Record<string, any>> => {
- if (!(req.headers.get('content-type') ?? '').includes('application/json')) throw new BadRequest('the request body must be JSON (Content-Type: application/json)');
- try {
- const v = await req.json();
- if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error();
- return v as Record<string, any>;
- } catch {
- throw new BadRequest('the request body is not a JSON object');
- }
- };
- // ---------- events ----------
- const clients = new Set<ReadableStreamDefaultController<Uint8Array>>();
- const enc = new TextEncoder();
- const send = (event: string, data: unknown) => {
- const chunk = enc.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
- for (const c of clients) {
- try { c.enqueue(chunk); } catch { clients.delete(c); }
- }
- };
- const pending = new Set<string>();
- let timer: ReturnType<typeof setTimeout> | null = null;
- let building = false;
- const flush = async () => {
- timer = null;
- if (building) { timer = setTimeout(flush, 100); return; }
- const paths = [...pending].sort();
- pending.clear();
- if (!paths.length) return;
- let built = false;
- if (build && paths.some((p) => p.endsWith('.md') || p.endsWith('.html'))) {
- building = true;
- const p = Bun.spawn([process.execPath, lensBuild], { cwd: root, stdout: 'ignore', stderr: 'pipe' });
- const code = await p.exited;
- building = false;
- built = code === 0;
- if (!built) log(`building the lenses failed (code ${code}): ${(await new Response(p.stderr).text()).trim().split('\n')[0] ?? ''}`);
- }
- send('change', { paths, built });
- };
- let watcher: FSWatcher | null = null;
- try {
- watcher = watch(root, { recursive: true }, (_ev, name) => {
- if (!name) return;
- const rel = String(name).split(/[\\/]/);
- if (rel.some((s) => s.startsWith('.')) || ['lib', 'node_modules'].includes(rel[0])) return;
- pending.add('/' + rel.join('/'));
- if (timer) clearTimeout(timer);
- timer = setTimeout(flush, 200);
- });
- } catch (e) {
- log(`watching the files did not start: ${(e as Error).message}`);
- }
- const heartbeat = setInterval(() => {
- for (const c of clients) try { c.enqueue(enc.encode(': ping\n\n')); } catch { clients.delete(c); }
- }, 15_000);
- // ---------- API ----------
- const recordOut = (path: string, withBody: boolean) => {
- const r = readRecord(root, path);
- return { path, title: pystr(r.fm.title ?? path.split('/').pop()!.replace(/\.md$/, '')), fields: r.fm, ...(withBody ? { body: r.body } : {}), etag: etagOf(r.text) };
- };
- const collOut = (c: Collection) => ({ path: c.path, title: c.title, itemType: c.itemType, properties: c.props, phases: phasesOf(root, c), count: recordPaths(root, c).length });
- const ownRecord = (p: unknown): [string, Collection] => {
- const path = safePath(p);
- if (!path.endsWith('.md')) throw new Refused('only records of collections (.md) can be changed');
- const c = collectionOf(root, path);
- if (!c) throw new Refused(`${path} is not a record of a collection: only records of collections can be changed`);
- return [path, c];
- };
- async function api(req: Request, url: URL): Promise<Response> {
- const route = `${req.method} ${url.pathname}`;
- const q = url.searchParams;
- switch (route) {
- case 'GET /api/hello': {
- const index = existsSync(join(root, 'index.md')) ? readRecord(root, '/index.md').fm : {};
- return json({ live: true, server: 'live', version: VERSION, project: pystr(index.title ?? ''), write: authorized(req), run: readSettings(root).run, lenses: build });
- }
- case 'GET /api/collections':
- return json({ collections: collections(root).map(collOut) });
- case 'GET /api/records': {
- const c = collection(root, q.get('collection'));
- return json({ collection: collOut(c), records: recordPaths(root, c).map((p) => recordOut(p, q.get('body') === '1')) });
- }
- case 'GET /api/record':
- return json(recordOut(safePath(q.get('path')), true));
- case 'GET /api/search': {
- const words = (q.get('q') ?? '').toLowerCase().split(/\s+/).filter(Boolean);
- if (!words.length) throw new BadRequest('q is what to search for');
- const limit = Math.min(Number(q.get('limit') ?? 50) || 50, 500);
- const cols = q.get('collection') ? [collection(root, q.get('collection'))] : collections(root);
- const out: unknown[] = [];
- for (const c of cols)
- for (const p of recordPaths(root, c)) {
- const r = readRecord(root, p);
- const title = pystr(r.fm.title ?? p);
- const text = (title + ' — ' + r.body).replace(/\s+/g, ' ');
- const hay = text.toLowerCase();
- if (!words.every((w) => hay.includes(w))) continue;
- const at = hay.indexOf(words[0]);
- out.push({ path: p, collection: c.path, title, snippet: text.slice(Math.max(0, at - 60), at + 100).trim() });
- if (out.length >= limit) return json({ results: out, more: true });
- }
- return json({ results: out, more: false });
- }
- case 'GET /api/events': {
- let ctl: ReadableStreamDefaultController<Uint8Array>;
- const stream = new ReadableStream<Uint8Array>({
- start(c) { ctl = c; clients.add(c); c.enqueue(enc.encode(`retry: 1500\nevent: hello\ndata: {"live":true}\n\n`)); },
- cancel() { clients.delete(ctl); },
- });
- req.signal.addEventListener('abort', () => clients.delete(ctl));
- return new Response(stream, { headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' } });
- }
- case 'POST /api/records': {
- needToken(req);
- const b = await body(req);
- const c = collection(root, b.collection);
- const given = b.fields && typeof b.fields === 'object' && !Array.isArray(b.fields) ? b.fields : {};
- const ordered: Record<string, unknown> = {};
- if (c.itemType) ordered.type = c.itemType;
- if (given.title !== undefined) ordered.title = given.title;
- Object.assign(ordered, given);
- const ok = validate(root, c, null, ordered);
- let name = b.name !== undefined ? pystr(b.name).replace(/\.md$/, '') : slug(pystr(ok.title ?? ''));
- if (!/^[a-z0-9][a-z0-9._-]{0,79}$/i.test(name)) throw new Invalid([{ field: 'name', message: `File name "${name}" does not fit: latin letters, digits, dot, _ and -.` }]);
- const dir = join(root, c.dir.slice(1));
- let file = join(dir, name + '.md');
- if (b.name !== undefined && existsSync(file)) throw new Conflict(`the record ${c.dir}/${name}.md already exists`);
- for (let i = 2; existsSync(file); i++) file = join(dir, `${name}-${i}.md`);
- let s = setFields({ has: false, lines: [], gap: '', body: '' }, Object.fromEntries(Object.entries(ok).filter(([, v]) => v !== null && v !== undefined)));
- s = setBody(s, typeof b.body === 'string' ? b.body : '');
- writeAtomic(file, joinPage(s));
- const path = file.slice(root.length);
- return json(recordOut(path, true), 201);
- }
- case 'PATCH /api/record': {
- needToken(req);
- const b = await body(req);
- const [path, c] = ownRecord(b.path);
- const r = readRecord(root, path);
- if (b.etag !== undefined && b.etag !== etagOf(r.text)) throw new Conflict('the record changed since it was read: read it again and retry');
- let s = split(r.text);
- let old: Record<string, unknown>;
- try { old = fields(s); } catch (e) { throw new Invalid([{ field: null, message: `The record header cannot be read: ${(e as Error).message}` }]); }
- if (b.set !== undefined) {
- if (!b.set || typeof b.set !== 'object' || Array.isArray(b.set)) throw new BadRequest('set must be an object {field: value}');
- try { s = setFields(s, b.set); } catch (e) { throw new Invalid([{ field: Object.keys(b.set)[0] ?? null, message: (e as Error).message }]); }
- validate(root, c, old, fields(s));
- }
- if (b.body !== undefined) {
- if (typeof b.body !== 'string') throw new BadRequest('body must be a string');
- s = setBody(s, b.body);
- }
- if (b.set === undefined && b.body === undefined) throw new BadRequest('nothing to change: set and/or body is needed');
- writeAtomic(join(root, path.slice(1)), joinPage(s));
- return json(recordOut(path, true));
- }
- case 'POST /api/move': {
- needToken(req);
- const b = await body(req);
- const [path, from] = ownRecord(b.path);
- const to = collection(root, b.to);
- const r = readRecord(root, path);
- let s = split(r.text);
- const fm = fields(s);
- if (from.itemType && to.itemType && fm.type === from.itemType && from.itemType !== to.itemType) s = setFields(s, { type: to.itemType });
- const name = path.split('/').pop()!;
- const file = join(root, to.dir.slice(1), name);
- if (existsSync(file)) throw new Conflict(`${to.path} already has ${name}`);
- validate(root, to, fields(s), fields(s));
- writeAtomic(file, joinPage(s));
- unlinkSync(join(root, path.slice(1)));
- return json({ path: `${to.dir}/${name}`, from: path });
- }
- case 'DELETE /api/record': {
- needToken(req);
- const [path] = ownRecord(q.get('path'));
- const src = join(root, path.slice(1));
- if (!existsSync(src)) throw new NotFound(`there is no record ${path}`);
- let dest = join(root, 'deleted', path.slice(1));
- for (let i = 2; existsSync(dest); i++) dest = join(root, 'deleted', path.slice(1).replace(/\.md$/, `-${i}.md`));
- mkdirSync(dirname(dest), { recursive: true });
- renameSync(src, dest);
- return json({ path, deletedTo: dest.slice(root.length) });
- }
- case 'POST /api/run': {
- needToken(req);
- const b = await body(req);
- const steps = plan(root, readSettings(root).run, b.package, b.action, b.args);
- if (b.stream) {
- const stream = new ReadableStream<Uint8Array>({
- async start(c) {
- await execute(root, steps, (e) => { try { c.enqueue(enc.encode(JSON.stringify(e) + '\n')); } catch {} }, req.signal);
- try { c.close(); } catch {}
- },
- });
- return new Response(stream, { headers: { 'content-type': 'application/x-ndjson; charset=utf-8', 'cache-control': 'no-store' } });
- }
- const lines: string[] = [];
- const results: { step: string; code: number }[] = [];
- const code = await execute(root, steps, (e) => {
- if (e.type === 'out') lines.push(e.text);
- else if (e.type === 'end') results.push({ step: e.step, code: e.code });
- }, req.signal);
- return json({ code, ok: code === 0, steps: results, output: lines.join('\n') });
- }
- }
- if (url.pathname.startsWith('/api/')) {
- const known = ['/api/hello', '/api/collections', '/api/records', '/api/record', '/api/search', '/api/events', '/api/move', '/api/run'];
- return json({ error: known.includes(url.pathname) ? `${req.method} ${url.pathname} is not supported` : `no such method: ${url.pathname}` }, known.includes(url.pathname) ? 405 : 404);
- }
- return json({ error: 'no such method' }, 404);
- }
- // ---------- static ----------
- function staticFile(url: URL): Response {
- let rel: string;
- try { rel = decodeURIComponent(url.pathname); } catch { return new Response('bad path', { status: 400 }); }
- const steps = rel.split('/').filter(Boolean);
- if (steps.some((s) => s.startsWith('.') || s === '..')) return new Response('not found', { status: 404 });
- let file = join(root, ...steps);
- const st = statSync(file, { throwIfNoEntry: false });
- if (st?.isDirectory()) {
- if (!url.pathname.endsWith('/')) return redirect(url.pathname + '/' + url.search);
- if (!steps.length && existsSync(join(root, 'lib', 'index.html'))) return redirect('/lib/index.html' + url.search);
- if (existsSync(join(file, 'index.html'))) file = join(file, 'index.html');
- else {
- const items = readdirSync(file).filter((n) => !n.startsWith('.')).sort();
- const li = items.map((n) => `<li><a href="${encodeURI(n)}${statSync(join(file, n)).isDirectory() ? '/' : ''}">${Bun.escapeHTML(n)}</a></li>`).join('');
- return new Response(`<!doctype html><meta charset="utf-8"><title>${Bun.escapeHTML(rel)}</title><ul>${li}</ul>`, { headers: { 'content-type': 'text/html; charset=utf-8' } });
- }
- } else if (!st?.isFile()) return new Response('not found', { status: 404 });
- const type = TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream';
- return new Response(Bun.file(file), { headers: { 'content-type': type, 'cache-control': 'no-store' } });
- }
- const server = Bun.serve({
- hostname: host,
- port: opts.port ?? settings.port,
- idleTimeout: 60,
- async fetch(req) {
- const url = new URL(req.url);
- // a page that reached us under another name (DNS rebinding) is not ours
- if (!hosts().has(req.headers.get('host') ?? '')) return json({ error: 'foreign server name: open 127.0.0.1' }, 403);
- const origin = req.headers.get('origin');
- if (origin && req.method !== 'GET' && req.method !== 'HEAD' && ![...hosts()].some((h) => origin === `http://${h}`))
- return json({ error: 'request from a foreign page' }, 403);
- // the link the server printed: put the token into a cookie and drop it from the address
- const t = url.searchParams.get('token');
- if (t !== null && req.method === 'GET') {
- url.searchParams.delete('token');
- const to = url.pathname + (url.search || '') + url.hash;
- if (!tokenOk(t)) return new Response(null, { status: 302, headers: { location: to } });
- return new Response(null, { status: 302, headers: { location: to, 'set-cookie': `${COOKIE}=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Strict` } });
- }
- try {
- if (url.pathname.startsWith('/api/') || url.pathname === '/api') return await api(req, url);
- if (req.method !== 'GET' && req.method !== 'HEAD') return new Response('read only', { status: 405 });
- return staticFile(url);
- } catch (e) {
- return errorResponse(e);
- }
- },
- });
- port = server.port;
- const base = `http://${host.includes(':') ? `[${host}]` : host}:${port}`;
- return {
- url: base + '/',
- link: `${base}/?token=${token}`,
- token,
- port,
- host,
- stop: () => {
- clearInterval(heartbeat);
- watcher?.close();
- for (const c of clients) try { c.close(); } catch {}
- clients.clear();
- server.stop(true);
- },
- };
- }