ShtukbaseStandard
package file→ .shtukbase/packages/live/server/server.ts

server/server.ts

364 lines, 19.5 KB.

  1. // The live server: the project folder as a static site plus a small API to read and change records, run allowed
  2. // actions and hear about changed files. Only on this computer (127.0.0.1); every write needs the session token.
  3. // Bun only, no dependencies. The pieces: fm.ts (front matter in place), records.ts (collections and the schema),
  4. // run.ts (allowed actions), settings.ts (the page /base/live.md).
  5. import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
  6. import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, watch, writeFileSync, type FSWatcher } from 'node:fs';
  7. import { dirname, extname, join } from 'node:path';
  8. import { pystr } from '../../collections/checks/lib/pages.ts';
  9. import { fields, join as joinPage, setBody, setFields, split } from './fm.ts';
  10. import { type Collection, Invalid, NotFound, Refused, collection, collectionOf, collections, phasesOf, readRecord, recordPaths, safePath, slug, validate } from './records.ts';
  11. import { execute, plan } from './run.ts';
  12. import { LOOPBACK, PAGE, readSettings } from './settings.ts';
  13. export const VERSION = '0.1.0';
  14. const COOKIE = 'live_token';
  15. export type Options = { root: string; port?: number; host?: string; token?: string; build?: boolean; quiet?: boolean };
  16. export type Live = { url: string; link: string; token: string; port: number; host: string; stop: () => void };
  17. class Unauthorized extends Error {}
  18. class Conflict extends Error {}
  19. class BadRequest extends Error {}
  20. const TYPES: Record<string, string> = {
  21. '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
  22. '.css': 'text/css; charset=utf-8', '.md': 'text/plain; charset=utf-8', '.txt': 'text/plain; charset=utf-8',
  23. '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
  24. '.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon', '.pdf': 'application/pdf', '.woff2': 'font/woff2',
  25. };
  26. const redirect = (location: string) => new Response(null, { status: 302, headers: { location } });
  27. const etagOf = (text: string) => createHash('sha1').update(text).digest('hex').slice(0, 16);
  28. /** Writes through a temporary file in the same folder and a rename: a reader never sees half a file. */
  29. function writeAtomic(file: string, text: string): void {
  30. mkdirSync(dirname(file), { recursive: true });
  31. const tmp = join(dirname(file), `.${Date.now().toString(36)}-${randomBytes(4).toString('hex')}.live.tmp`);
  32. writeFileSync(tmp, text);
  33. renameSync(tmp, file);
  34. }
  35. const json = (data: unknown, status = 200, headers: Record<string, string> = {}) =>
  36. new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...headers } });
  37. function errorResponse(e: unknown): Response {
  38. if (e instanceof Invalid) return json({ error: e.message, field: e.errors[0]?.field ?? null, errors: e.errors }, 422);
  39. if (e instanceof Unauthorized) return json({ error: e.message }, 401);
  40. if (e instanceof Refused) return json({ error: e.message }, 403);
  41. if (e instanceof NotFound) return json({ error: e.message }, 404);
  42. if (e instanceof Conflict) return json({ error: e.message }, 409);
  43. if (e instanceof BadRequest) return json({ error: e.message }, 400);
  44. return json({ error: `server error: ${(e as Error).message ?? e}` }, 500);
  45. }
  46. export function start(opts: Options): Live {
  47. const root = opts.root.replace(/\/+$/, '');
  48. const settings = readSettings(root);
  49. if (settings.problems.length) throw new Error(`the settings of ${PAGE} break the norms:\n ${settings.problems.join('\n ')}`);
  50. const host = opts.host ?? settings.host;
  51. if (!LOOPBACK.has(host)) throw new Error(`host ${host}: the server listens only on this computer (127.0.0.1, localhost, ::1)`);
  52. const token = opts.token ?? randomBytes(18).toString('base64url');
  53. const tokenBuf = Buffer.from(token);
  54. const lensBuild = join(root, '.shtukbase', 'packages', 'lenses', 'actions', 'build.mjs');
  55. const build = opts.build !== false && existsSync(lensBuild);
  56. const log = (s: string) => { if (!opts.quiet) console.log(s); };
  57. let port = 0;
  58. const hosts = () => new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
  59. const tokenOk = (t: string | null | undefined) => !!t && t.length === token.length && timingSafeEqual(Buffer.from(t), tokenBuf);
  60. const authorized = (req: Request) => {
  61. const auth = req.headers.get('authorization');
  62. if (auth?.startsWith('Bearer ') && tokenOk(auth.slice(7).trim())) return true;
  63. if (tokenOk(req.headers.get('x-live-token'))) return true;
  64. const cookie = req.headers.get('cookie') ?? '';
  65. const m = new RegExp(`(?:^|;\\s*)${COOKIE}=([^;]+)`).exec(cookie);
  66. return !!m && tokenOk(decodeURIComponent(m[1]));
  67. };
  68. const needToken = (req: Request) => {
  69. 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>');
  70. };
  71. const body = async (req: Request): Promise<Record<string, any>> => {
  72. if (!(req.headers.get('content-type') ?? '').includes('application/json')) throw new BadRequest('the request body must be JSON (Content-Type: application/json)');
  73. try {
  74. const v = await req.json();
  75. if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error();
  76. return v as Record<string, any>;
  77. } catch {
  78. throw new BadRequest('the request body is not a JSON object');
  79. }
  80. };
  81. // ---------- events ----------
  82. const clients = new Set<ReadableStreamDefaultController<Uint8Array>>();
  83. const enc = new TextEncoder();
  84. const send = (event: string, data: unknown) => {
  85. const chunk = enc.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
  86. for (const c of clients) {
  87. try { c.enqueue(chunk); } catch { clients.delete(c); }
  88. }
  89. };
  90. const pending = new Set<string>();
  91. let timer: ReturnType<typeof setTimeout> | null = null;
  92. let building = false;
  93. const flush = async () => {
  94. timer = null;
  95. if (building) { timer = setTimeout(flush, 100); return; }
  96. const paths = [...pending].sort();
  97. pending.clear();
  98. if (!paths.length) return;
  99. let built = false;
  100. if (build && paths.some((p) => p.endsWith('.md') || p.endsWith('.html'))) {
  101. building = true;
  102. const p = Bun.spawn([process.execPath, lensBuild], { cwd: root, stdout: 'ignore', stderr: 'pipe' });
  103. const code = await p.exited;
  104. building = false;
  105. built = code === 0;
  106. if (!built) log(`building the lenses failed (code ${code}): ${(await new Response(p.stderr).text()).trim().split('\n')[0] ?? ''}`);
  107. }
  108. send('change', { paths, built });
  109. };
  110. let watcher: FSWatcher | null = null;
  111. try {
  112. watcher = watch(root, { recursive: true }, (_ev, name) => {
  113. if (!name) return;
  114. const rel = String(name).split(/[\\/]/);
  115. if (rel.some((s) => s.startsWith('.')) || ['lib', 'node_modules'].includes(rel[0])) return;
  116. pending.add('/' + rel.join('/'));
  117. if (timer) clearTimeout(timer);
  118. timer = setTimeout(flush, 200);
  119. });
  120. } catch (e) {
  121. log(`watching the files did not start: ${(e as Error).message}`);
  122. }
  123. const heartbeat = setInterval(() => {
  124. for (const c of clients) try { c.enqueue(enc.encode(': ping\n\n')); } catch { clients.delete(c); }
  125. }, 15_000);
  126. // ---------- API ----------
  127. const recordOut = (path: string, withBody: boolean) => {
  128. const r = readRecord(root, path);
  129. return { path, title: pystr(r.fm.title ?? path.split('/').pop()!.replace(/\.md$/, '')), fields: r.fm, ...(withBody ? { body: r.body } : {}), etag: etagOf(r.text) };
  130. };
  131. 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 });
  132. const ownRecord = (p: unknown): [string, Collection] => {
  133. const path = safePath(p);
  134. if (!path.endsWith('.md')) throw new Refused('only records of collections (.md) can be changed');
  135. const c = collectionOf(root, path);
  136. if (!c) throw new Refused(`${path} is not a record of a collection: only records of collections can be changed`);
  137. return [path, c];
  138. };
  139. async function api(req: Request, url: URL): Promise<Response> {
  140. const route = `${req.method} ${url.pathname}`;
  141. const q = url.searchParams;
  142. switch (route) {
  143. case 'GET /api/hello': {
  144. const index = existsSync(join(root, 'index.md')) ? readRecord(root, '/index.md').fm : {};
  145. return json({ live: true, server: 'live', version: VERSION, project: pystr(index.title ?? ''), write: authorized(req), run: readSettings(root).run, lenses: build });
  146. }
  147. case 'GET /api/collections':
  148. return json({ collections: collections(root).map(collOut) });
  149. case 'GET /api/records': {
  150. const c = collection(root, q.get('collection'));
  151. return json({ collection: collOut(c), records: recordPaths(root, c).map((p) => recordOut(p, q.get('body') === '1')) });
  152. }
  153. case 'GET /api/record':
  154. return json(recordOut(safePath(q.get('path')), true));
  155. case 'GET /api/search': {
  156. const words = (q.get('q') ?? '').toLowerCase().split(/\s+/).filter(Boolean);
  157. if (!words.length) throw new BadRequest('q is what to search for');
  158. const limit = Math.min(Number(q.get('limit') ?? 50) || 50, 500);
  159. const cols = q.get('collection') ? [collection(root, q.get('collection'))] : collections(root);
  160. const out: unknown[] = [];
  161. for (const c of cols)
  162. for (const p of recordPaths(root, c)) {
  163. const r = readRecord(root, p);
  164. const title = pystr(r.fm.title ?? p);
  165. const text = (title + ' — ' + r.body).replace(/\s+/g, ' ');
  166. const hay = text.toLowerCase();
  167. if (!words.every((w) => hay.includes(w))) continue;
  168. const at = hay.indexOf(words[0]);
  169. out.push({ path: p, collection: c.path, title, snippet: text.slice(Math.max(0, at - 60), at + 100).trim() });
  170. if (out.length >= limit) return json({ results: out, more: true });
  171. }
  172. return json({ results: out, more: false });
  173. }
  174. case 'GET /api/events': {
  175. let ctl: ReadableStreamDefaultController<Uint8Array>;
  176. const stream = new ReadableStream<Uint8Array>({
  177. start(c) { ctl = c; clients.add(c); c.enqueue(enc.encode(`retry: 1500\nevent: hello\ndata: {"live":true}\n\n`)); },
  178. cancel() { clients.delete(ctl); },
  179. });
  180. req.signal.addEventListener('abort', () => clients.delete(ctl));
  181. return new Response(stream, { headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' } });
  182. }
  183. case 'POST /api/records': {
  184. needToken(req);
  185. const b = await body(req);
  186. const c = collection(root, b.collection);
  187. const given = b.fields && typeof b.fields === 'object' && !Array.isArray(b.fields) ? b.fields : {};
  188. const ordered: Record<string, unknown> = {};
  189. if (c.itemType) ordered.type = c.itemType;
  190. if (given.title !== undefined) ordered.title = given.title;
  191. Object.assign(ordered, given);
  192. const ok = validate(root, c, null, ordered);
  193. let name = b.name !== undefined ? pystr(b.name).replace(/\.md$/, '') : slug(pystr(ok.title ?? ''));
  194. 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 -.` }]);
  195. const dir = join(root, c.dir.slice(1));
  196. let file = join(dir, name + '.md');
  197. if (b.name !== undefined && existsSync(file)) throw new Conflict(`the record ${c.dir}/${name}.md already exists`);
  198. for (let i = 2; existsSync(file); i++) file = join(dir, `${name}-${i}.md`);
  199. let s = setFields({ has: false, lines: [], gap: '', body: '' }, Object.fromEntries(Object.entries(ok).filter(([, v]) => v !== null && v !== undefined)));
  200. s = setBody(s, typeof b.body === 'string' ? b.body : '');
  201. writeAtomic(file, joinPage(s));
  202. const path = file.slice(root.length);
  203. return json(recordOut(path, true), 201);
  204. }
  205. case 'PATCH /api/record': {
  206. needToken(req);
  207. const b = await body(req);
  208. const [path, c] = ownRecord(b.path);
  209. const r = readRecord(root, path);
  210. if (b.etag !== undefined && b.etag !== etagOf(r.text)) throw new Conflict('the record changed since it was read: read it again and retry');
  211. let s = split(r.text);
  212. let old: Record<string, unknown>;
  213. try { old = fields(s); } catch (e) { throw new Invalid([{ field: null, message: `The record header cannot be read: ${(e as Error).message}` }]); }
  214. if (b.set !== undefined) {
  215. if (!b.set || typeof b.set !== 'object' || Array.isArray(b.set)) throw new BadRequest('set must be an object {field: value}');
  216. try { s = setFields(s, b.set); } catch (e) { throw new Invalid([{ field: Object.keys(b.set)[0] ?? null, message: (e as Error).message }]); }
  217. validate(root, c, old, fields(s));
  218. }
  219. if (b.body !== undefined) {
  220. if (typeof b.body !== 'string') throw new BadRequest('body must be a string');
  221. s = setBody(s, b.body);
  222. }
  223. if (b.set === undefined && b.body === undefined) throw new BadRequest('nothing to change: set and/or body is needed');
  224. writeAtomic(join(root, path.slice(1)), joinPage(s));
  225. return json(recordOut(path, true));
  226. }
  227. case 'POST /api/move': {
  228. needToken(req);
  229. const b = await body(req);
  230. const [path, from] = ownRecord(b.path);
  231. const to = collection(root, b.to);
  232. const r = readRecord(root, path);
  233. let s = split(r.text);
  234. const fm = fields(s);
  235. if (from.itemType && to.itemType && fm.type === from.itemType && from.itemType !== to.itemType) s = setFields(s, { type: to.itemType });
  236. const name = path.split('/').pop()!;
  237. const file = join(root, to.dir.slice(1), name);
  238. if (existsSync(file)) throw new Conflict(`${to.path} already has ${name}`);
  239. validate(root, to, fields(s), fields(s));
  240. writeAtomic(file, joinPage(s));
  241. unlinkSync(join(root, path.slice(1)));
  242. return json({ path: `${to.dir}/${name}`, from: path });
  243. }
  244. case 'DELETE /api/record': {
  245. needToken(req);
  246. const [path] = ownRecord(q.get('path'));
  247. const src = join(root, path.slice(1));
  248. if (!existsSync(src)) throw new NotFound(`there is no record ${path}`);
  249. let dest = join(root, 'deleted', path.slice(1));
  250. for (let i = 2; existsSync(dest); i++) dest = join(root, 'deleted', path.slice(1).replace(/\.md$/, `-${i}.md`));
  251. mkdirSync(dirname(dest), { recursive: true });
  252. renameSync(src, dest);
  253. return json({ path, deletedTo: dest.slice(root.length) });
  254. }
  255. case 'POST /api/run': {
  256. needToken(req);
  257. const b = await body(req);
  258. const steps = plan(root, readSettings(root).run, b.package, b.action, b.args);
  259. if (b.stream) {
  260. const stream = new ReadableStream<Uint8Array>({
  261. async start(c) {
  262. await execute(root, steps, (e) => { try { c.enqueue(enc.encode(JSON.stringify(e) + '\n')); } catch {} }, req.signal);
  263. try { c.close(); } catch {}
  264. },
  265. });
  266. return new Response(stream, { headers: { 'content-type': 'application/x-ndjson; charset=utf-8', 'cache-control': 'no-store' } });
  267. }
  268. const lines: string[] = [];
  269. const results: { step: string; code: number }[] = [];
  270. const code = await execute(root, steps, (e) => {
  271. if (e.type === 'out') lines.push(e.text);
  272. else if (e.type === 'end') results.push({ step: e.step, code: e.code });
  273. }, req.signal);
  274. return json({ code, ok: code === 0, steps: results, output: lines.join('\n') });
  275. }
  276. }
  277. if (url.pathname.startsWith('/api/')) {
  278. const known = ['/api/hello', '/api/collections', '/api/records', '/api/record', '/api/search', '/api/events', '/api/move', '/api/run'];
  279. 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);
  280. }
  281. return json({ error: 'no such method' }, 404);
  282. }
  283. // ---------- static ----------
  284. function staticFile(url: URL): Response {
  285. let rel: string;
  286. try { rel = decodeURIComponent(url.pathname); } catch { return new Response('bad path', { status: 400 }); }
  287. const steps = rel.split('/').filter(Boolean);
  288. if (steps.some((s) => s.startsWith('.') || s === '..')) return new Response('not found', { status: 404 });
  289. let file = join(root, ...steps);
  290. const st = statSync(file, { throwIfNoEntry: false });
  291. if (st?.isDirectory()) {
  292. if (!url.pathname.endsWith('/')) return redirect(url.pathname + '/' + url.search);
  293. if (!steps.length && existsSync(join(root, 'lib', 'index.html'))) return redirect('/lib/index.html' + url.search);
  294. if (existsSync(join(file, 'index.html'))) file = join(file, 'index.html');
  295. else {
  296. const items = readdirSync(file).filter((n) => !n.startsWith('.')).sort();
  297. const li = items.map((n) => `<li><a href="${encodeURI(n)}${statSync(join(file, n)).isDirectory() ? '/' : ''}">${Bun.escapeHTML(n)}</a></li>`).join('');
  298. 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' } });
  299. }
  300. } else if (!st?.isFile()) return new Response('not found', { status: 404 });
  301. const type = TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream';
  302. return new Response(Bun.file(file), { headers: { 'content-type': type, 'cache-control': 'no-store' } });
  303. }
  304. const server = Bun.serve({
  305. hostname: host,
  306. port: opts.port ?? settings.port,
  307. idleTimeout: 60,
  308. async fetch(req) {
  309. const url = new URL(req.url);
  310. // a page that reached us under another name (DNS rebinding) is not ours
  311. if (!hosts().has(req.headers.get('host') ?? '')) return json({ error: 'foreign server name: open 127.0.0.1' }, 403);
  312. const origin = req.headers.get('origin');
  313. if (origin && req.method !== 'GET' && req.method !== 'HEAD' && ![...hosts()].some((h) => origin === `http://${h}`))
  314. return json({ error: 'request from a foreign page' }, 403);
  315. // the link the server printed: put the token into a cookie and drop it from the address
  316. const t = url.searchParams.get('token');
  317. if (t !== null && req.method === 'GET') {
  318. url.searchParams.delete('token');
  319. const to = url.pathname + (url.search || '') + url.hash;
  320. if (!tokenOk(t)) return new Response(null, { status: 302, headers: { location: to } });
  321. return new Response(null, { status: 302, headers: { location: to, 'set-cookie': `${COOKIE}=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Strict` } });
  322. }
  323. try {
  324. if (url.pathname.startsWith('/api/') || url.pathname === '/api') return await api(req, url);
  325. if (req.method !== 'GET' && req.method !== 'HEAD') return new Response('read only', { status: 405 });
  326. return staticFile(url);
  327. } catch (e) {
  328. return errorResponse(e);
  329. }
  330. },
  331. });
  332. port = server.port;
  333. const base = `http://${host.includes(':') ? `[${host}]` : host}:${port}`;
  334. return {
  335. url: base + '/',
  336. link: `${base}/?token=${token}`,
  337. token,
  338. port,
  339. host,
  340. stop: () => {
  341. clearInterval(heartbeat);
  342. watcher?.close();
  343. for (const c of clients) try { c.close(); } catch {}
  344. clients.clear();
  345. server.stop(true);
  346. },
  347. };
  348. }