@jjanczur/tyran 0.1.23 → 0.1.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/scripts/board.mjs CHANGED
@@ -20,7 +20,7 @@
20
20
  * initiative reads as "all is well" exactly when it is not.
21
21
  *
22
22
  * CLI:
23
- * node board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>]]
23
+ * node board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>] [--write]]
24
24
  * Exit: 0 ok · 1 drift (--check) · 2 usage/IO
25
25
  */
26
26
  import { existsSync, readdirSync, statSync, readFileSync } from 'node:fs';
@@ -39,10 +39,12 @@ import {
39
39
  inline,
40
40
  warnings,
41
41
  writeAllAtomic,
42
+ writeAtomic,
42
43
  } from './project.mjs';
43
44
  import { jsonEscapeInvisible } from './invisible.mjs';
44
45
  import { renderBoardError, renderBoardHtml } from './board-html.mjs';
45
46
  import { COST_SCHEMA, costJson, costReport } from './cost.mjs';
47
+ import { SettingsError, applyPolicyClass, applySetting, readSettings } from './settings.mjs';
46
48
 
47
49
  export const BOARD_HTML_FILE = 'board.html';
48
50
 
@@ -136,8 +138,10 @@ export function readInitiativeBoards(tyranDir) {
136
138
  * rather than embedded. Relative is also the more useful form — it is what
137
139
  * the reader pastes, from the repo root, into an editor.
138
140
  *
139
- * Nothing is served: `--serve` routes three URLs and derives a filesystem
140
- * path from none of them, which is worth more than a clickable link.
141
+ * Nothing is served from here: `--serve` derives a filesystem path from no
142
+ * URL at all, which is worth more than a clickable link. The one route that
143
+ * writes — Settings, behind `--write` — reaches two fixed files named in
144
+ * `settings.mjs` and takes a KEY from the request, never a path.
141
145
  */
142
146
  export const INITIATIVE_FILES = Object.freeze(['PLAN.md', 'NOTES.md', 'RETRO.md', 'STATE.md', 'PROGRESS.md']);
143
147
 
@@ -289,13 +293,116 @@ export function renderAll(tyranDir) {
289
293
  };
290
294
  }
291
295
 
296
+ // ------------------------------------------------------- the write channel
297
+
298
+ /** A request body big enough for any setting and small enough to ignore. */
299
+ const MAX_BODY_BYTES = 64 * 1024;
300
+
301
+ /**
302
+ * Read a JSON request body, or reject it.
303
+ *
304
+ * Three refusals, all deliberate. A body over the cap is dropped rather than
305
+ * buffered, because this server has no reason to hold a megabyte of anything.
306
+ * A body that is not `application/json` is refused BEFORE it is read — that
307
+ * content type is what forces a browser to preflight a cross-origin POST, and
308
+ * accepting `text/plain` here would hand back the exact hole the preflight
309
+ * closes. And anything that is not a JSON object is refused, so a handler
310
+ * never reasons about a string that happens to have a `.value`.
311
+ */
312
+ function readJsonBody(req) {
313
+ return new Promise((resolve_, reject) => {
314
+ const type = String(req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase();
315
+ if (type !== 'application/json') {
316
+ reject(new SettingsError('this route takes application/json'));
317
+ return;
318
+ }
319
+ let size = 0;
320
+ const chunks = [];
321
+ req.on('data', (chunk) => {
322
+ size += chunk.length;
323
+ if (size > MAX_BODY_BYTES) {
324
+ reject(new SettingsError('request body is too large'));
325
+ req.destroy();
326
+ return;
327
+ }
328
+ chunks.push(chunk);
329
+ });
330
+ req.on('error', (err) => reject(err));
331
+ req.on('end', () => {
332
+ let parsed;
333
+ try {
334
+ parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
335
+ } catch {
336
+ reject(new SettingsError('request body is not JSON'));
337
+ return;
338
+ }
339
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
340
+ reject(new SettingsError('request body must be a JSON object'));
341
+ return;
342
+ }
343
+ resolve_(parsed);
344
+ });
345
+ });
346
+ }
347
+
348
+ /**
349
+ * `Origin`, on top of the `Host` pin the whole server already carries.
350
+ *
351
+ * The two answer different questions and neither covers the other. `Host` says
352
+ * which name the client dialled, which stops DNS rebinding. `Origin` says
353
+ * which page is asking, which is the only thing that distinguishes the board's
354
+ * own fetch from a POST issued by some other tab the operator has open. A
355
+ * request with no `Origin` at all is allowed: that is `curl`, and a local
356
+ * process that can reach loopback needs no browser's help — see the honest
357
+ * statement of what this does and does not defend in `docs/board.md`.
358
+ */
359
+ function originAllowed(req) {
360
+ const origin = req.headers.origin;
361
+ if (origin === undefined || origin === 'null') return true;
362
+ try {
363
+ const { hostname } = new URL(String(origin));
364
+ return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]' || hostname === '::1';
365
+ } catch {
366
+ return false;
367
+ }
368
+ }
369
+
370
+ const sendJson = (res, status, body) => {
371
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
372
+ res.end(JSON.stringify(body) + '\n');
373
+ };
374
+
375
+ /**
376
+ * Apply one edit and write it, or change nothing and say why.
377
+ *
378
+ * The write itself is `writeAtomic` — the same rename-into-place the
379
+ * projections use — so a config file can never be found half-written, however
380
+ * the process dies.
381
+ */
382
+ function handleSettingsWrite(dir, route, body) {
383
+ // `confirm` is only ever compared for equality against the value the server
384
+ // itself computed, so a caller cannot widen anything by sending a truthy
385
+ // flag — it has to name the exact change it is making.
386
+ const confirm = typeof body.confirm === 'string' ? body.confirm : null;
387
+ const applied =
388
+ route === 'config'
389
+ ? applySetting(dir, String(body.id ?? ''), body.value, confirm)
390
+ : applyPolicyClass(dir, body.path === null || body.path === undefined ? null : String(body.path), String(body.class ?? ''), confirm);
391
+ writeAtomic(applied.file, applied.text);
392
+ // The operator's terminal is the audit trail. A change made from a web page
393
+ // that left no trace anywhere a person looks is how a settings screen turns
394
+ // into a thing nobody trusts.
395
+ console.log(`board: wrote ${applied.file} — ${applied.path.join('.')}: ${JSON.stringify(applied.before)} -> ${JSON.stringify(applied.after)}`);
396
+ return { ok: true, file: applied.file, path: applied.path, before: applied.before, after: applied.after };
397
+ }
398
+
292
399
  // ------------------------------------------------------------------- CLI
293
400
 
294
- const BOOLEAN_FLAGS = ['check', 'serve'];
401
+ const BOOLEAN_FLAGS = ['check', 'serve', 'write'];
295
402
  const VALUE_FLAGS = ['dir', 'port'];
296
403
 
297
404
  function parseArgs(argv) {
298
- const flags = { dir: '.tyran', port: 4173, check: false, serve: false };
405
+ const flags = { dir: '.tyran', port: 4173, check: false, serve: false, write: false };
299
406
  for (let i = 0; i < argv.length; i += 1) {
300
407
  const arg = argv[i];
301
408
  if (!arg.startsWith('--')) throw new UsageError(`unexpected argument "${arg}"`);
@@ -321,7 +428,11 @@ function main() {
321
428
  } catch (err) {
322
429
  if (!(err instanceof UsageError)) throw err;
323
430
  console.error(`board: ${err.message}`);
324
- console.error('usage: board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>]]');
431
+ console.error('usage: board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>] [--write]]');
432
+ process.exit(2);
433
+ }
434
+ if (flags.write && !flags.serve) {
435
+ console.error('board: --write only means anything with --serve (it is what the served page may edit)');
325
436
  process.exit(2);
326
437
  }
327
438
  const dir = resolve(flags.dir);
@@ -354,6 +465,55 @@ function main() {
354
465
  res.end('forbidden: this board answers to 127.0.0.1 only\n');
355
466
  return;
356
467
  }
468
+ // ---- settings: the routes that read and write config -----------
469
+ //
470
+ // Config is served rather than embedded for the same reason spend is:
471
+ // it is not journal state, it is not a projection, and writing it into
472
+ // `board.json` would break the byte-exact `--check` contract. Over
473
+ // `file://` the fetch fails and the tab says how to open the board
474
+ // with a server, which is the honest answer.
475
+ if (req.url === '/settings.json') {
476
+ sendJson(res, 200, { ...readSettings(dir), writable: flags.write });
477
+ return;
478
+ }
479
+ if (req.url === '/settings/config' || req.url === '/settings/policy') {
480
+ const route = req.url.slice('/settings/'.length);
481
+ if (req.method !== 'POST') {
482
+ sendJson(res, 405, { ok: false, error: 'this route takes POST' });
483
+ return;
484
+ }
485
+ // Writes are OFF unless the operator asked for them on the command
486
+ // line. A board someone left running is a board that can be reached
487
+ // by anything on this machine, and the difference between reading
488
+ // that and editing the autonomy policy through it is the difference
489
+ // this flag exists to make. The refusal names the flag, because a
490
+ // 403 an operator cannot act on is just a bug report.
491
+ if (!flags.write) {
492
+ sendJson(res, 403, {
493
+ ok: false,
494
+ error: 'this board is read-only. Restart it with: npx @jjanczur/tyran board --serve --write',
495
+ });
496
+ return;
497
+ }
498
+ if (!originAllowed(req)) {
499
+ sendJson(res, 403, { ok: false, error: 'forbidden: this board answers its own pages only' });
500
+ return;
501
+ }
502
+ readJsonBody(req)
503
+ .then((body) => sendJson(res, 200, handleSettingsWrite(dir, route, body)))
504
+ .catch((err) => {
505
+ const known = err instanceof SettingsError;
506
+ if (!known) console.error(`board: settings write failed: ${String(err?.message ?? err)}`);
507
+ sendJson(res, known ? 400 : 500, {
508
+ ok: false,
509
+ error: String(err?.message ?? err),
510
+ // Present only on a refusal the operator can answer, and it
511
+ // carries the exact token that answers it.
512
+ ...(err?.widens === true ? { widens: true, confirm_with: err.confirm_with } : {}),
513
+ });
514
+ });
515
+ return;
516
+ }
357
517
  // Spend is served, never rendered into the artefacts. It is derived
358
518
  // from transcripts under the operator's home directory — machine-local
359
519
  // by nature — so putting it in board.json would make two clones of one
@@ -409,7 +569,10 @@ function main() {
409
569
  process.exitCode = 2;
410
570
  });
411
571
  server.listen(flags.port, '127.0.0.1', () => {
412
- console.log(`board: serving http://127.0.0.1:${flags.port}/ (read-only; Ctrl-C to stop)`);
572
+ console.log(
573
+ `board: serving http://127.0.0.1:${flags.port}/ ` +
574
+ `(${flags.write ? 'Settings can edit config.yaml and autonomy.yaml' : 'read-only'}; Ctrl-C to stop)`,
575
+ );
413
576
  });
414
577
  return;
415
578
  }
@@ -1210,6 +1210,13 @@ export function writeAllAtomic(entries) {
1210
1210
  const staged = [];
1211
1211
  try {
1212
1212
  for (const [path, content] of entries) {
1213
+ // The directory may not exist yet, and the first time that matters is
1214
+ // the worst time: `.tyran/state/` is created by the first initiative, so
1215
+ // `board.mjs --dir .tyran` on a freshly set-up repo — the command the
1216
+ // README leads with — died with an ENOENT naming a temp file nobody had
1217
+ // heard of. Staging into a directory is not a decision, it is what
1218
+ // writing a file there means.
1219
+ mkdirSync(dirname(path), { recursive: true });
1213
1220
  const tmp = tempPathFor(path);
1214
1221
  writeFileSync(tmp, content, 'utf8');
1215
1222
  staged.push([tmp, path]);
@@ -355,6 +355,26 @@ export function scanRepo(dir, { run = gitRunner(dir) } = {}) {
355
355
  tiers: { cheap: 'haiku', work: 'sonnet', deep: 'opus', top: 'fable' },
356
356
  validation,
357
357
  shared_zones: [],
358
+ // Written out in full, every value at its shipped default, with the
359
+ // feature OFF. Nothing here enables anything — `mode: 'off'` is the same
360
+ // inert state as omitting the block entirely.
361
+ //
362
+ // The difference is that an absent key cannot be edited. The board's
363
+ // Settings tab patches values that exist and deliberately refuses to
364
+ // invent keys (choosing where a key goes and what comment explains it is
365
+ // authoring, not editing), so a scanned config with no `limits:` rendered
366
+ // the whole Overnight section as dead text on every fresh install. So did
367
+ // doctor's `limit-telemetry-missing`, which is conditioned on a mode that
368
+ // was never written.
369
+ limits: {
370
+ mode: 'off',
371
+ pause_at_percent: 97,
372
+ weekly_pause_at_percent: 97,
373
+ wait_max_hours: 5,
374
+ long_wait: 'hold',
375
+ resume_margin_minutes: 5,
376
+ keep_awake: false,
377
+ },
358
378
  };
359
379
 
360
380
  const questions = [];