fwdloop 0.11.0 → 0.13.0

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.
Files changed (62) hide show
  1. package/bin/fwdloop +248 -27
  2. package/package.json +1 -1
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +103 -13
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +36 -0
  7. package/src/config.js +256 -0
  8. package/src/declaration.js +72 -2
  9. package/src/drafter.js +53 -11
  10. package/src/draftspend.js +70 -0
  11. package/src/flow.js +43 -0
  12. package/src/keysfile.js +180 -0
  13. package/src/liveness.js +1 -1
  14. package/src/model-step.js +43 -8
  15. package/src/monthly.js +276 -0
  16. package/src/panel/author.js +482 -0
  17. package/src/panel/authorcard.js +297 -0
  18. package/src/panel/authorflows.js +312 -0
  19. package/src/panel/authorresume.js +149 -0
  20. package/src/panel/authorstart.js +257 -0
  21. package/src/panel/authorvalues.js +110 -0
  22. package/src/panel/data.js +228 -34
  23. package/src/panel/index.html +2073 -124
  24. package/src/panel/resume.js +14 -11
  25. package/src/panel/server.js +150 -117
  26. package/src/panel/settings.js +270 -0
  27. package/src/panel/spawn.js +77 -0
  28. package/src/provider.js +189 -43
  29. package/src/providershapes.js +19 -0
  30. package/src/runner.js +639 -85
  31. package/src/runvalues.js +178 -0
  32. package/src/send.js +10 -3
  33. package/src/setup.js +120 -0
  34. package/types/authoring.d.ts +24 -2
  35. package/types/books.d.ts +14 -2
  36. package/types/canrun.d.ts +32 -0
  37. package/types/config.d.ts +52 -0
  38. package/types/declaration.d.ts +9 -1
  39. package/types/drafter.d.ts +18 -2
  40. package/types/draftspend.d.ts +21 -0
  41. package/types/flow.d.ts +23 -0
  42. package/types/keysfile.d.ts +90 -0
  43. package/types/liveness.d.ts +2 -2
  44. package/types/model-step.d.ts +6 -2
  45. package/types/monthly.d.ts +130 -0
  46. package/types/panel/author.d.ts +335 -0
  47. package/types/panel/authorcard.d.ts +120 -0
  48. package/types/panel/authorflows.d.ts +175 -0
  49. package/types/panel/authorresume.d.ts +32 -0
  50. package/types/panel/authorstart.d.ts +115 -0
  51. package/types/panel/authorvalues.d.ts +62 -0
  52. package/types/panel/data.d.ts +103 -12
  53. package/types/panel/resume.d.ts +8 -1
  54. package/types/panel/server.d.ts +19 -33
  55. package/types/panel/settings.d.ts +23 -0
  56. package/types/panel/spawn.d.ts +30 -0
  57. package/types/provider.d.ts +123 -70
  58. package/types/providershapes.d.ts +11 -0
  59. package/types/runner.d.ts +120 -5
  60. package/types/runvalues.d.ts +97 -0
  61. package/types/send.d.ts +5 -1
  62. package/types/setup.d.ts +83 -0
@@ -34,16 +34,16 @@
34
34
  // redact: it prints only its own error messages (never the key), so a key
35
35
  // could reach the log only through a provider error body that echoes it.
36
36
 
37
- import { spawn } from 'node:child_process';
38
37
  import { createHash, randomBytes } from 'node:crypto';
39
38
  import {
40
- closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync,
39
+ existsSync, lstatSync, mkdirSync, readFileSync, statSync, unlinkSync,
41
40
  } from 'node:fs';
42
41
  import { tmpdir } from 'node:os';
43
42
  import { dirname, join } from 'node:path';
44
43
  import { fileURLToPath } from 'node:url';
45
44
  import { scrub } from '../authoring.js';
46
45
  import { PROVIDER_SLOTS } from '../provider.js';
46
+ import { spawnDetached } from './spawn.js';
47
47
 
48
48
  const HERE = dirname(fileURLToPath(import.meta.url));
49
49
  const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
@@ -76,8 +76,10 @@ function ensureLogDir(dir) {
76
76
  }
77
77
 
78
78
  /**
79
- * @param {{ root: string, env?: Record<string, string|undefined>, bin?: string, logDir?: string,
79
+ * @param {{ root: string, env?: Record<string, string|undefined>, loadEnv?: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, bin?: string, logDir?: string,
80
80
  * maxTries?: number, windowMs?: number, slotMs?: number }} opts
81
+ * `loadEnv` (M4d: the keys-file door, called before EVERY spawn so editing the file needs no panel restart) returns the merged env
82
+ * that is BOTH the child's spawn env AND its scrub list, or a refusal sentence that becomes the attempt's refusal (nothing spawns).
81
83
  * `env`/`bin`/`logDir`/`maxTries`/`windowMs`/`slotMs` are injectable so tests neither sleep 10 s
82
84
  * nor need a live key; production passes none of them. `slotMs` (default `windowMs / maxTries`,
83
85
  * i.e. 2000 ms) is only the spacing between tries: a test sets it small and `windowMs` (the
@@ -86,7 +88,7 @@ function ensureLogDir(dir) {
86
88
  */
87
89
  export function createResumer(opts) {
88
90
  const {
89
- root, env = process.env, bin = BIN, maxTries = RESUME_MAX_TRIES, windowMs = RESUME_WINDOW_MS, slotMs = windowMs / maxTries,
91
+ root, env = process.env, loadEnv, bin = BIN, maxTries = RESUME_MAX_TRIES, windowMs = RESUME_WINDOW_MS, slotMs = windowMs / maxTries,
90
92
  } = opts;
91
93
  const rootTag = createHash('sha256').update(root).digest('hex').slice(0, 8);
92
94
  /** @type {Map<string, any>} */
@@ -100,13 +102,14 @@ export function createResumer(opts) {
100
102
  * or the child exited, or `deadline` passed — never waits for a long resume. */
101
103
  function tryOnce({ flow, runId, runDir, askId, logPath, deadline }) {
102
104
  const consumedPath = join(runDir, `answer.${askId}.consumed.json`);
103
- const fd = openSync(logPath, 'a', 0o600);
104
- const offset = statSync(logPath).size;
105
- const child = spawn(process.execPath, [bin, 'resume', runId, '--flow', flow, '--root', root], {
106
- detached: true, stdio: ['ignore', fd, fd], env,
105
+ const loaded = loadEnv ? loadEnv() : { ok: true, env, refusal: null };
106
+ if (!loaded.ok) return Promise.resolve({ kind: 'exited', code: null, sig: null, text: String(loaded.refusal) });
107
+ const runEnv = loaded.env; // ONE object: the spawn env below AND the scrub list further down (POC (a) wiring rule)
108
+ let offset = 0; // the log may not exist yet: the one spawn creates it
109
+ try { offset = statSync(logPath).size; } catch { /* a new log starts at 0 */ }
110
+ const child = spawnDetached({
111
+ bin, argv: ['resume', runId, '--flow', flow, '--root', root], env: runEnv, logPath,
107
112
  });
108
- child.unref();
109
- closeSync(fd);
110
113
  const runKey = keyOf(flow, runId);
111
114
  live.set(runKey, (live.get(runKey) ?? 0) + 1);
112
115
  let released = false;
@@ -120,7 +123,7 @@ export function createResumer(opts) {
120
123
  child.once('error', release);
121
124
  // The child's output is quoted in a refusal (`reason`) that reaches HTTP responses and the books: the
122
125
  // provider key(s) of this panel's env are scrubbed here, the one place that reads the log slice (amendment 1 (e)(3)).
123
- const keys = Object.values(PROVIDER_SLOTS).map((p) => env[p.envVar]).filter(Boolean);
126
+ const keys = Object.values(PROVIDER_SLOTS).map((p) => runEnv[p.envVar]).filter(Boolean);
124
127
  const sliceOfLog = () => {
125
128
  try { return scrub(readFileSync(logPath).subarray(offset).toString('utf8').trim(), keys); } catch { return ''; } // offset is in BYTES
126
129
  };
@@ -30,8 +30,8 @@
30
30
  // `POST /api/resume`, which only re-starts a resume for a run that already has
31
31
  // a saved, unconsumed answer. M4c-fix amendment 1 adds `POST /api/reopen`, the human's one button on an expired ask
32
32
  // (`reopenAsk`, `src/ask.js`). All three are refused by name unless the request is
33
- // a real click from the served page — own `Host` and `Origin`, the per-process
34
- // token (embedded only in the served page), a small JSON body. An answer must
33
+ // a real click from the served page — own `Host` and `Origin` (no token, no
34
+ // cookie: M4e amendment 4 item 8), a small JSON body. An answer must
35
35
  // name its `askId`. `Host` is checked on EVERY route, GET included
36
36
  // (DNS-rebinding read). After an accepted answer the panel starts the resume
37
37
  // as a separate detached process and checks from the books that it took over
@@ -47,32 +47,31 @@
47
47
  // directory's own `index.html`, never a URL-derived filename.
48
48
 
49
49
  import { createServer } from 'node:http';
50
- import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
51
- import {
52
- chmodSync, closeSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeSync,
53
- } from 'node:fs';
54
- import { homedir } from 'node:os';
50
+ import { readFileSync, realpathSync } from 'node:fs';
55
51
  import path, { dirname, join } from 'node:path';
56
52
  import { fileURLToPath } from 'node:url';
57
53
 
58
54
  import { loadCatalogue } from '../catalogue.js';
59
55
  import { answerAsk, reopenAsk, normalizeDecision } from '../ask.js';
60
- import { readHistory } from '../books.js';
56
+ import { readHistory, endRow } from '../books.js';
61
57
  import { resolveRunDir } from '../flow.js';
62
- import { readAsk } from '../runner.js';
58
+ import { readAsk, requestStop, stopParkedRun } from '../runner.js';
63
59
  import {
64
- listRuns, getRunDetail, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
60
+ listRuns, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
65
61
  } from './data.js';
66
62
  import { createResumer } from './resume.js';
63
+ import { createAuthor } from './author.js';
64
+ import { keysForDoor } from '../keysfile.js';
65
+ import { configDoorHome } from '../config.js';
66
+ import { createSettings } from './settings.js';
67
67
  import { removeOldLock } from './lock.js';
68
68
 
69
69
  const HERE = dirname(fileURLToPath(import.meta.url));
70
70
 
71
71
  /** Cap on the answer body — a decision and a short reason, nothing more. */
72
72
  const MAX_BODY_BYTES = 8 * 1024;
73
- /** Cookie the panel link sets; `<name>_<port>` so two panels on one host never clobber each other. */
74
- const cookieName = (port) => `fwdloop_panel_${port}`;
75
-
73
+ /** Cap on a draft-card body — a few numbered job lines, not a document (M4e). */
74
+ const MAX_AUTHOR_BODY_BYTES = 64 * 1024;
76
75
  /** Default bind port. Ruling, hamr 2026-09-27: fwdloop's panel default port
77
76
  * is 4800 — bareloop owns 4700, and the two panels must be able to run
78
77
  * side by side. */
@@ -115,62 +114,13 @@ function refuse(res, code, name, detail) {
115
114
  sendJson(res, code, { ok: false, refused: name, red: detail ? `${name}: ${detail}` : name });
116
115
  }
117
116
 
118
- /** Constant-time compare: both sides hashed to equal length first, so neither
119
- * the content nor the length of the real token leaks through timing.
120
- * @param {unknown} a @param {string} b */
121
- function tokenMatches(a, b) {
122
- if (typeof a !== 'string') return false;
123
- const x = createHash('sha256').update(a).digest();
124
- const y = createHash('sha256').update(b).digest();
125
- return timingSafeEqual(x, y);
126
- }
127
-
128
- const tokenDir = (dir, env) => dir ?? (env.XDG_RUNTIME_DIR ? join(env.XDG_RUNTIME_DIR, 'fwdloop') : join(homedir(), '.cache', 'fwdloop'));
129
-
130
- /**
131
- * hamr's 2026-10-03 ruling "1A": the panel token is REUSED across restarts, so a bookmark of
132
- * `http://127.0.0.1:<port>/` keeps working once the link was opened. Reads the token file (same path
133
- * `writeTokenFile` writes); a new token only when the file is missing, unreadable, not a regular file,
134
- * not mode 0600, not ours, or not 64 hex chars (the caller then rewrites it 0600).
135
- * @param {{ port: number, dir?: string, env?: Record<string, string|undefined> }} a
136
- * @returns {string}
137
- */
138
- export function loadOrMakeToken({ port, dir, env = process.env }) {
139
- try {
140
- const d = tokenDir(dir, env);
141
- const file = join(d, `panel-${port}.token`);
142
- const st = lstatSync(file);
143
- const dst = lstatSync(d);
144
- const uid = typeof process.getuid === 'function' ? process.getuid() : null;
145
- if (dst.isDirectory() && (dst.mode & 0o777) === 0o700 && st.isFile() && (st.mode & 0o777) === 0o600 && (uid === null || st.uid === uid)) {
146
- const t = readFileSync(file, 'utf8').trim();
147
- if (/^[0-9a-f]{64}$/.test(t)) return t;
148
- }
149
- } catch { /* missing or unreadable: a new one */ }
150
- return randomBytes(32).toString('hex');
151
- }
152
-
153
- /**
154
- * M4c-fix item 2: the token's one on-disk home — `<dir>/panel-<port>.token`, dir 0700, file 0600,
155
- * `dir` = `$XDG_RUNTIME_DIR/fwdloop`, else `~/.cache/fwdloop`. Refuses a dir that is a symlink or
156
- * not ours. The file is replaced (unlink, then exclusive create at 0600), never rewritten in place,
157
- * so it never exists with a looser mode. Returns the file's path.
158
- * @param {{ port: number, token: string, dir?: string, env?: Record<string, string|undefined> }} a
159
- */
160
- export function writeTokenFile({
161
- port, token, dir, env = process.env,
162
- }) {
163
- const d = tokenDir(dir, env);
164
- const uid = typeof process.getuid === 'function' ? process.getuid() : null;
165
- mkdirSync(d, { recursive: true, mode: 0o700 });
166
- const st = lstatSync(d);
167
- if (!st.isDirectory() || (uid !== null && st.uid !== uid)) throw new Error('token dir is not a directory owned by this user');
168
- chmodSync(d, 0o700);
169
- const file = join(d, `panel-${port}.token`);
170
- try { unlinkSync(file); } catch { /* none yet */ }
171
- const fd = openSync(file, 'wx', 0o600);
172
- try { writeSync(fd, `${token}\n`); } finally { closeSync(fd); }
173
- return file;
117
+ /** Send a Settings handler's `{status, body}`; a throw is a plain 500, never a stack. @param {any} res @param {Promise<{status:number, body:any}>} pending @param {boolean} [headOnly] */
118
+ function settingsReply(res, pending, headOnly = false) {
119
+ pending.then((r) => {
120
+ if (!headOnly) { sendJson(res, r.status, r.body); return; }
121
+ res.writeHead(r.status, { 'content-type': 'application/json; charset=utf-8' });
122
+ res.end();
123
+ }, () => sendJson(res, 500, { ok: false, refused: 'internal', say: 'Something went wrong inside the panel. Nothing was changed.' }));
174
124
  }
175
125
 
176
126
  /** @param {any} res */
@@ -245,7 +195,7 @@ function answerRoute(res, body, root, resumer) {
245
195
  }
246
196
 
247
197
  /**
248
- * `POST /api/reopen` — runs after the same gates as the answer (cookie, own Host, own Origin). The human's
198
+ * `POST /api/reopen` — runs after the same gates as the answer (own Host, own Origin). The human's
249
199
  * "Reopen for another <wait>" on an expired ask (M4c-fix amendment 1 (b)): `reopenAsk` writes the reopen record
250
200
  * (a fresh window of the same signed length, on the same ask) and moves a late answer aside. Nothing else reopens:
251
201
  * no runner or agent path calls it. Refused 409 while a resume of the run is alive, and for a run that has ended.
@@ -261,7 +211,7 @@ function reopenRoute(res, body, root, resumer) {
261
211
  const runDir = resolveRun(res, root, flow, runId);
262
212
  if (runDir === null) return;
263
213
  if (resumer.busy(flow, runId)) { refuseBusy(res); return; }
264
- if (readHistory(dirname(dirname(runDir))).some((r) => r && r.runId === runId)) {
214
+ if (endRow(readHistory(dirname(dirname(runDir))), runDir, runId) !== null) {
265
215
  refuse(res, 409, 'run-ended', 'this run has ended — there is nothing to reopen');
266
216
  return;
267
217
  }
@@ -276,7 +226,7 @@ function reopenRoute(res, body, root, resumer) {
276
226
  }
277
227
 
278
228
  /**
279
- * `POST /api/remove-lock` — runs after the same gates as the answer (cookie, own Host, own Origin). The human's
229
+ * `POST /api/remove-lock` — runs after the same gates as the answer (own Host, own Origin). The human's
280
230
  * "Remove the old lock" (M4c-fix amendment 2 (h)): only for a run with a saved answer and no resume alive; `removeOldLock`
281
231
  * re-checks at this moment that the lock still has no recorded holder, removes it and writes the one audit row; then the
282
232
  * run continues exactly like "Continue the run" (the same `resumer.start`). Nothing else calls the remover.
@@ -303,6 +253,45 @@ function removeLockRoute(res, body, root, resumer) {
303
253
  });
304
254
  }
305
255
 
256
+ /** The two words of a refused Stop (bareloop's texts, M4e amendment 4 item 4). */
257
+ const NOT_RUNNING_SAY = 'This run is not running, so there is nothing to stop.';
258
+ const STARTING_SAY = 'The run is still starting — it has not written its log yet. Try again in a moment.';
259
+
260
+ /**
261
+ * `POST /api/stop` — runs after the same gates as the answer (own Host, own Origin). The human's Stop (M4e amendment 4
262
+ * item 4): writes the run's stop file; the runner reads it at the seam after the current step closes. Only a run that is
263
+ * running is stopped; a parked, ended or not-yet-started run is refused in words and nothing is written. The same
264
+ * decision (`runControls`) the Run tab's button reads.
265
+ * @param {any} res @param {any} body @param {string} root
266
+ */
267
+ async function stopRoute(res, body, root) {
268
+ const b = body !== null && typeof body === 'object' ? body : {};
269
+ const { flow, runId } = b;
270
+ const runDir = resolveRun(res, root, flow, runId);
271
+ if (runDir === null) return;
272
+ const loaded = loadCatalogue();
273
+ if (!loaded.ok) { refuse(res, 500, 'catalogue', 'the catalogue failed to load'); return; }
274
+ const controls = getRunControls({
275
+ root, flow, runId, catalogue: loaded.primitives,
276
+ });
277
+ if (controls === null) { refuse(res, 404, 'no-such-run', 'there is no such run'); return; }
278
+ if (controls.starting) { sendJson(res, 409, { ok: false, refused: 'starting', say: STARTING_SAY }); return; }
279
+ if (!controls.canStop) { sendJson(res, 409, { ok: false, refused: 'not-running', say: NOT_RUNNING_SAY }); return; }
280
+ // Amendment 13: a run waiting at its ask is stopped at the ask now; a running one is asked to stop and ends at its next seam.
281
+ // The write comes first and the parked check after it, so a park landing between the two is still caught (the runner checks
282
+ // the request after it writes the ask; whichever sees both wins the rename, the other finds nothing to do).
283
+ const written = requestStop(runDir);
284
+ const ask = readAsk(runDir);
285
+ if (controls.atAsk || (ask && parkedOnYou(runDir, ask.askId))) {
286
+ const stopped = await stopParkedRun({
287
+ root, name: flow, runId, catalogue: loaded.primitives,
288
+ });
289
+ if (stopped.outcome === 'stopped') { sendJson(res, 202, { ok: true, stopping: false, stopped: true }); return; }
290
+ // not parked after all (a resume took its answer) or a resume still closing: the request stays for the runner's own seam
291
+ }
292
+ sendJson(res, 202, { ok: true, stopping: true, already: written === 'exists' });
293
+ }
294
+
306
295
  /**
307
296
  * `POST /api/resume` — runs after the same gates as the answer. Starts a
308
297
  * resume ONLY for a run that has a saved, unconsumed answer; it takes no
@@ -328,13 +317,38 @@ function resumeRoute(res, body, root, resumer) {
328
317
  });
329
318
  }
330
319
 
320
+ /**
321
+ * `POST /api/author/{draft,run,resume-prepare,resume,<id>/sign-prepare,<id>/sign,<id>/revise,<id>/abandon,start/<id>/clear}` — run after the same gates as every other POST.
322
+ * Anything else under `/api/author/` is a 404 by name.
323
+ * @param {any} res @param {string} url @param {any} body @param {ReturnType<typeof createAuthor>} author
324
+ */
325
+ function authorPost(res, url, body, author) {
326
+ const send = (r) => sendJson(res, r.status, r.body);
327
+ if (url === '/api/author/draft') { send(author.start(body)); return; }
328
+ if (url === '/api/author/run') { send(author.run(body)); return; }
329
+ if (url === '/api/author/run-prepare') { send(author.runPrepare(body)); return; }
330
+ if (url === '/api/author/resume-prepare') { send(author.resumePrepare(body)); return; }
331
+ if (url === '/api/author/resume') { send(author.resume(body)); return; }
332
+ const sp = /^\/api\/author\/([^/]+)\/sign-prepare$/.exec(url);
333
+ if (sp) { send(author.signPrepare(sp[1])); return; }
334
+ const sg = /^\/api\/author\/([^/]+)\/sign$/.exec(url);
335
+ if (sg) { send(author.sign(sg[1], body)); return; }
336
+ const rv = /^\/api\/author\/([^/]+)\/revise$/.exec(url);
337
+ if (rv) { send(author.revise(rv[1], body)); return; }
338
+ const sc = /^\/api\/author\/start\/([^/]+)\/clear$/.exec(url);
339
+ if (sc) { send(author.startClear(sc[1])); return; }
340
+ const m = /^\/api\/author\/([^/]+)\/abandon$/.exec(url);
341
+ if (m) { author.abandon(m[1]).then(send, () => sendJson(res, 500, { ok: false, refused: 'internal', red: 'internal error' })); return; }
342
+ refuse(res, 404, 'not-found', url);
343
+ }
344
+
331
345
  /**
332
346
  * Handle one request against the API + the page. Exported
333
347
  * separately from {@link createPanelServer} so tests can drive it without a
334
348
  * real listening socket where that is simpler.
335
349
  * @param {import('node:http').IncomingMessage} req
336
350
  * @param {import('node:http').ServerResponse} res
337
- * @param {{ root: string, port: number, token: string, resumer: ReturnType<typeof createResumer> }} opts
351
+ * @param {{ root: string, port: number, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor> }} opts
338
352
  */
339
353
  export function handleRequest(req, res, opts) {
340
354
  const method = req.method ?? 'GET';
@@ -353,40 +367,18 @@ export function handleRequest(req, res, opts) {
353
367
  return;
354
368
  }
355
369
 
356
- // Gate 2 — EVERY route, every method (the page included): the panel's own cookie, set by opening
357
- // the printed `/?t=<token>` link. Without it: 403 by name, and nothing in the body is a token.
358
- const cookies = Object.fromEntries(String(req.headers.cookie ?? '').split(';').map((c) => {
359
- const i = c.indexOf('=');
360
- return i < 0 ? ['', ''] : [c.slice(0, i).trim(), c.slice(i + 1).trim()];
361
- }));
362
- if (!tokenMatches(cookies[cookieName(opts.port)], opts.token)) {
363
- const link = method === 'GET' || method === 'HEAD' ? new URL(String(req.url), 'http://127.0.0.1') : null;
364
- if (link && link.pathname === '/' && tokenMatches(link.searchParams.get('t'), opts.token)) {
365
- res.writeHead(302, {
366
- 'set-cookie': `${cookieName(opts.port)}=${opts.token}; HttpOnly; SameSite=Strict; Path=/`, location: '/', 'content-length': 0,
367
- });
368
- res.end();
369
- return;
370
- }
371
- // A browser opening the bare page sees a plain page that says what to do, not a blank JSON "forbidden"
372
- // that reads as "the panel is down". No token, no script. API routes keep the JSON 403.
373
- if (link && link.pathname === '/' && /text\/html/.test(String(req.headers.accept ?? ''))) {
374
- const html = '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>fwdloop panel</title>'
375
- + '<p style="font:16px/1.5 system-ui,sans-serif;max-width:40em;margin:2em auto;padding:0 1em">'
376
- + 'fwdloop panel: open the link printed in the terminal where you started <code>fwdloop panel</code> (it ends in ?t=…). '
377
- + 'Restarted the panel? Open its new link.</p>';
378
- res.writeHead(403, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
379
- res.end(method === 'HEAD' ? undefined : html);
380
- return;
381
- }
382
- refuse(res, 403, 'cookie-missing-or-wrong', 'open the link `fwdloop panel` printed');
383
- return;
384
- }
370
+ // No token, no cookie (M4e amendment 4 item 8): the panel is local and trusted. What guards it is Gate 1 above
371
+ // (own Host, so a DNS-rebinding name is refused), the 127.0.0.1-only bind, and the Origin check on every POST below.
385
372
 
386
- if (method === 'POST' && (req.url === '/api/answer' || req.url === '/api/resume' || req.url === '/api/reopen' || req.url === '/api/remove-lock')) {
373
+ // M4d piece 4: every `/api/settings/...` POST (a known one or not) goes through the same Origin + body-cap gates.
374
+ const isSettingsPost = method === 'POST' && String(req.url).startsWith('/api/settings/');
375
+ // M4e piece 2a: every `/api/author/...` POST goes through the SAME door (own Host, own Origin, body cap) — no second guard.
376
+ const isAuthorPost = method === 'POST' && String(req.url).startsWith('/api/author/');
377
+ if (method === 'POST' && (isSettingsPost || isAuthorPost || req.url === '/api/answer' || req.url === '/api/resume' || req.url === '/api/reopen' || req.url === '/api/remove-lock' || req.url === '/api/stop')) {
387
378
  const isResume = req.url === '/api/resume';
388
379
  const isReopen = req.url === '/api/reopen';
389
380
  const isRemoveLock = req.url === '/api/remove-lock';
381
+ const isStop = req.url === '/api/stop';
390
382
  const origin = req.headers.origin;
391
383
  if (origin !== `http://127.0.0.1:${opts.port}` && origin !== `http://localhost:${opts.port}`) {
392
384
  refuse(res, 403, 'origin-not-own', String(origin));
@@ -398,7 +390,7 @@ export function handleRequest(req, res, opts) {
398
390
  req.on('data', (c) => {
399
391
  if (tooBig) return;
400
392
  size += c.length;
401
- if (size <= MAX_BODY_BYTES) { parts.push(c); return; }
393
+ if (size <= (isAuthorPost ? MAX_AUTHOR_BODY_BYTES : MAX_BODY_BYTES)) { parts.push(c); return; }
402
394
  // M4c-fix item 6: over the limit — stop at once. Drop what was collected, refuse (413, then the
403
395
  // connection closes), and cut the request off; the rest of the body is never read.
404
396
  tooBig = true;
@@ -412,9 +404,16 @@ export function handleRequest(req, res, opts) {
412
404
  if (tooBig) return;
413
405
  let body;
414
406
  try { body = JSON.parse(Buffer.concat(parts).toString('utf8')); } catch { refuse(res, 400, 'body-not-json'); return; }
407
+ if (isAuthorPost) { authorPost(res, String(req.url), body, opts.author); return; }
408
+ if (isSettingsPost) { settingsReply(res, opts.settings.handle({ method, pathname: String(req.url), query: new URLSearchParams(), body })); return; }
415
409
  if (isResume) resumeRoute(res, body, opts.root, opts.resumer);
416
410
  else if (isReopen) reopenRoute(res, body, opts.root, opts.resumer);
417
411
  else if (isRemoveLock) removeLockRoute(res, body, opts.root, opts.resumer);
412
+ else if (isStop) {
413
+ stopRoute(res, body, opts.root).catch(() => {
414
+ if (!res.headersSent) sendJson(res, 500, { ok: false, refused: 'internal', red: 'internal error' });
415
+ });
416
+ }
418
417
  else answerRoute(res, body, opts.root, opts.resumer);
419
418
  } catch (e) {
420
419
  sendJson(res, 500, { ok: false, refused: 'internal', red: 'internal error' });
@@ -424,7 +423,7 @@ export function handleRequest(req, res, opts) {
424
423
  }
425
424
 
426
425
  if (method !== 'GET' && method !== 'HEAD') {
427
- sendText(res, 405, 'method not allowed — GET/HEAD for reads; the only writes are POST /api/answer, POST /api/resume, POST /api/reopen and POST /api/remove-lock');
426
+ sendText(res, 405, 'method not allowed — GET/HEAD for reads; the only writes are POST /api/answer, POST /api/resume, POST /api/reopen, POST /api/remove-lock, POST /api/stop, POST /api/settings/... and POST /api/author/...');
428
427
  return;
429
428
  }
430
429
 
@@ -447,6 +446,29 @@ export function handleRequest(req, res, opts) {
447
446
  sendJson(res, code, body);
448
447
  };
449
448
 
449
+ if (pathname.startsWith('/api/author/')) {
450
+ const am = /^\/api\/author\/([^/]+)$/.exec(pathname);
451
+ const sm = /^\/api\/author\/start\/([^/]+)$/.exec(pathname);
452
+ let r = { status: 404, body: /** @type {any} */ ({ ok: false, refused: 'not-found' }) };
453
+ if (pathname === '/api/author/live') r = opts.author.live();
454
+ else if (pathname === '/api/author/flows') r = opts.author.flows();
455
+ else if (pathname === '/api/author/run-again') r = opts.author.runAgain(url.searchParams.get('flow'), url.searchParams.get('runId'));
456
+ else if (pathname === '/api/author/monthly-check') r = opts.author.monthlyCheck(url.searchParams.get('cap'), url.searchParams.get('spent'));
457
+ else if (pathname === '/api/author/resume-form') r = opts.author.resumeForm(url.searchParams.get('flow'), url.searchParams.get('runId'));
458
+ else if (sm) r = opts.author.startGet(sm[1]);
459
+ else if (am) r = opts.author.get(am[1]);
460
+ if (method === 'HEAD') { res.writeHead(r.status, { 'content-type': 'application/json; charset=utf-8' }); res.end(); return; }
461
+ sendJson(res, r.status, r.body);
462
+ return;
463
+ }
464
+
465
+ if (pathname.startsWith('/api/settings/')) {
466
+ settingsReply(res, opts.settings.handle({
467
+ method: 'GET', pathname, query: url.searchParams, body: null,
468
+ }), method === 'HEAD');
469
+ return;
470
+ }
471
+
450
472
  if (pathname === '/' || pathname === '/index.html') {
451
473
  const indexPath = join(HERE, 'index.html');
452
474
  let html;
@@ -544,9 +566,9 @@ export function handleRequest(req, res, opts) {
544
566
  * header). Resolves once actually listening; rejects on a bind error
545
567
  * (including `EADDRINUSE`) with a `.port` field on the error for the
546
568
  * caller's message.
547
- * @param {{ port?: number, root: string, token?: string, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
548
- * `resume` is for tests only (a fake env/bin, a short retry window); the CLI passes none.
549
- * @returns {Promise<{ server: import('node:http').Server, port: number, token: string, close: () => Promise<void> }>}
569
+ * @param {{ port?: number, root: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string } }} opts
570
+ * `resume` and `author` are for tests only (a fake env/bin, a short retry window); the CLI passes none.
571
+ * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
550
572
  */
551
573
  export function createPanelServer(opts) {
552
574
  if (typeof opts?.root !== 'string' || opts.root.length === 0) {
@@ -555,10 +577,19 @@ export function createPanelServer(opts) {
555
577
  const requestedPort = opts.port ?? DEFAULT_PORT;
556
578
  const { root } = opts;
557
579
  // One resumer per server: the one owner of every run's resume-attempt record.
558
- const resumer = createResumer({ root, ...opts.resume });
559
- // One token per server process, made once, held only here and in the served
560
- // page — never logged, never in any /api response.
561
- const token = typeof opts.token === 'string' && /^[0-9a-f]{64}$/.test(opts.token) ? opts.token : randomBytes(32).toString('hex');
580
+ // M4d: the keys file is re-read before EVERY resume spawn (editing it needs no restart); an env injected by a test is the shell side.
581
+ const resumer = createResumer({ root, loadEnv: () => keysForDoor({ env: opts.resume?.env }), ...opts.resume });
582
+ // M4e piece 2a: the draft door. Same keys door as the resumer: the merged env is re-read before every spawn and every log quote.
583
+ // The courtesy "left this month" line reads the SAME home the CLI's monthly check does (injected, else the door's).
584
+ const door = configDoorHome();
585
+ const author = createAuthor({
586
+ root, home: opts.settings?.home ?? door.home, skipMonthly: opts.settings?.home === undefined && door.skip, loadEnv: () => keysForDoor({ env: opts.author?.env }), ...opts.author,
587
+ });
588
+ // Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
589
+ // process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
590
+ const settings = createSettings({
591
+ home: opts.settings?.home ?? door.home, skip: opts.settings?.home === undefined && door.skip, env: opts.settings?.env, fetch: opts.settings?.fetch, now: opts.settings?.now,
592
+ });
562
593
  return new Promise((resolve, reject) => {
563
594
  // Bound port is resolved from the live socket (`server.address().port`)
564
595
  // once listening starts, not the requested value — this is what makes
@@ -569,7 +600,7 @@ export function createPanelServer(opts) {
569
600
  const server = createServer((req, res) => {
570
601
  try {
571
602
  handleRequest(req, res, {
572
- root, port: boundPort, token, resumer,
603
+ root, port: boundPort, resumer, settings, author,
573
604
  });
574
605
  } catch (e) {
575
606
  sendText(res, 500, 'internal error');
@@ -586,7 +617,6 @@ export function createPanelServer(opts) {
586
617
  resolve({
587
618
  server,
588
619
  port: boundPort,
589
- token,
590
620
  close: () => new Promise((res2) => { server.close(() => res2(undefined)); }),
591
621
  });
592
622
  });
@@ -616,10 +646,13 @@ export async function panelMain(argv, ctx) {
616
646
  }
617
647
  }
618
648
  try {
619
- const { port: boundPort, token } = await createPanelServer({ port, root, token: loadOrMakeToken({ port }) });
620
- writeTokenFile({ port: boundPort, token });
649
+ const { port: boundPort } = await createPanelServer({ port, root });
650
+ // M4d: read the keys file at start (creates it when missing). The panel itself needs no key, so a file other users can
651
+ // read is only announced here; every resume re-reads it and refuses by itself.
652
+ const keys = keysForDoor();
653
+ if (!keys.ok) ctx.err(String(keys.refusal));
621
654
  ctx.out(`fwdloop panel — (root: ${root}) (Ctrl-C to stop)`);
622
- ctx.out(`open this link (it sets the panel's cookie): http://127.0.0.1:${boundPort}/?t=${token}`);
655
+ ctx.out(`http://127.0.0.1:${boundPort}/`);
623
656
  // never resolves on its own — the process stays up until killed, same
624
657
  // shape any other long-running dev server takes.
625
658
  await new Promise(() => {});