fwdloop 0.10.0 → 0.12.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.
@@ -28,7 +28,8 @@
28
28
  // nothing new. The writes are `POST /api/answer`, a thin client of the
29
29
  // library's `answerAsk` (the panel is never a second arbiter), and
30
30
  // `POST /api/resume`, which only re-starts a resume for a run that already has
31
- // a saved, unconsumed answer. Both are refused by name unless the request is
31
+ // a saved, unconsumed answer. M4c-fix amendment 1 adds `POST /api/reopen`, the human's one button on an expired ask
32
+ // (`reopenAsk`, `src/ask.js`). All three are refused by name unless the request is
32
33
  // a real click from the served page — own `Host` and `Origin`, the per-process
33
34
  // token (embedded only in the served page), a small JSON body. An answer must
34
35
  // name its `askId`. `Host` is checked on EVERY route, GET included
@@ -47,24 +48,33 @@
47
48
 
48
49
  import { createServer } from 'node:http';
49
50
  import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
50
- import { readFileSync } from 'node:fs';
51
- import { dirname, join } from 'node:path';
51
+ import {
52
+ chmodSync, closeSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeSync,
53
+ } from 'node:fs';
54
+ import { homedir } from 'node:os';
55
+ import path, { dirname, join } from 'node:path';
52
56
  import { fileURLToPath } from 'node:url';
53
57
 
54
58
  import { loadCatalogue } from '../catalogue.js';
55
- import { answerAsk, normalizeDecision } from '../ask.js';
56
- import { checkFlowName, resolveRunDir } from '../flow.js';
59
+ import { answerAsk, reopenAsk, normalizeDecision } from '../ask.js';
60
+ import { readHistory } from '../books.js';
61
+ import { resolveRunDir } from '../flow.js';
62
+ import { readAsk } from '../runner.js';
57
63
  import {
58
- listRuns, getRunDetail, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer,
64
+ listRuns, getRunDetail, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
59
65
  } from './data.js';
60
66
  import { createResumer } from './resume.js';
67
+ import { keysForDoor } from '../keysfile.js';
68
+ import { configDoorHome } from '../config.js';
69
+ import { createSettings } from './settings.js';
70
+ import { removeOldLock } from './lock.js';
61
71
 
62
72
  const HERE = dirname(fileURLToPath(import.meta.url));
63
73
 
64
74
  /** Cap on the answer body — a decision and a short reason, nothing more. */
65
75
  const MAX_BODY_BYTES = 8 * 1024;
66
- /** Header the page sends its token in. */
67
- const TOKEN_HEADER = 'x-fwdloop-token';
76
+ /** Cookie the panel link sets; `<name>_<port>` so two panels on one host never clobber each other. */
77
+ const cookieName = (port) => `fwdloop_panel_${port}`;
68
78
 
69
79
  /** Default bind port. Ruling, hamr 2026-09-27: fwdloop's panel default port
70
80
  * is 4800 — bareloop owns 4700, and the two panels must be able to run
@@ -84,6 +94,24 @@ function sendText(res, code, text) {
84
94
  res.end(text);
85
95
  }
86
96
 
97
+ /**
98
+ * M4c-fix item 5: no absolute path in any error body. A path under `--root` is shown relative to
99
+ * it; any other absolute path (a symlink's far end, a system dir) is shown as `<outside root>`.
100
+ * Throws away: the machine's directory layout above `--root`.
101
+ * @param {string} text @param {string} root
102
+ */
103
+ function cleanPaths(text, root) {
104
+ const bases = [path.resolve(root)];
105
+ try { bases.push(realpathSync(root)); } catch { /* root gone: the lexical base still applies */ }
106
+ return String(text).replace(/(?<![\w:/.])\/[^\s\x22\x27\x60()<>,;]+/g, (m) => {
107
+ for (const b of bases) {
108
+ if (m === b) return '.';
109
+ if (m.startsWith(`${b}/`)) return m.slice(b.length + 1);
110
+ }
111
+ return '<outside root>';
112
+ });
113
+ }
114
+
87
115
  /** A refusal, by name. `refused` is the stable machine name, `red` the words.
88
116
  * @param {any} res @param {number} code @param {string} name @param {string} [detail] */
89
117
  function refuse(res, code, name, detail) {
@@ -100,6 +128,94 @@ function tokenMatches(a, b) {
100
128
  return timingSafeEqual(x, y);
101
129
  }
102
130
 
131
+ const tokenDir = (dir, env) => dir ?? (env.XDG_RUNTIME_DIR ? join(env.XDG_RUNTIME_DIR, 'fwdloop') : join(homedir(), '.cache', 'fwdloop'));
132
+
133
+ /**
134
+ * hamr's 2026-10-03 ruling "1A": the panel token is REUSED across restarts, so a bookmark of
135
+ * `http://127.0.0.1:<port>/` keeps working once the link was opened. Reads the token file (same path
136
+ * `writeTokenFile` writes); a new token only when the file is missing, unreadable, not a regular file,
137
+ * not mode 0600, not ours, or not 64 hex chars (the caller then rewrites it 0600).
138
+ * @param {{ port: number, dir?: string, env?: Record<string, string|undefined> }} a
139
+ * @returns {string}
140
+ */
141
+ export function loadOrMakeToken({ port, dir, env = process.env }) {
142
+ try {
143
+ const d = tokenDir(dir, env);
144
+ const file = join(d, `panel-${port}.token`);
145
+ const st = lstatSync(file);
146
+ const dst = lstatSync(d);
147
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null;
148
+ if (dst.isDirectory() && (dst.mode & 0o777) === 0o700 && st.isFile() && (st.mode & 0o777) === 0o600 && (uid === null || st.uid === uid)) {
149
+ const t = readFileSync(file, 'utf8').trim();
150
+ if (/^[0-9a-f]{64}$/.test(t)) return t;
151
+ }
152
+ } catch { /* missing or unreadable: a new one */ }
153
+ return randomBytes(32).toString('hex');
154
+ }
155
+
156
+ /**
157
+ * M4c-fix item 2: the token's one on-disk home — `<dir>/panel-<port>.token`, dir 0700, file 0600,
158
+ * `dir` = `$XDG_RUNTIME_DIR/fwdloop`, else `~/.cache/fwdloop`. Refuses a dir that is a symlink or
159
+ * not ours. The file is replaced (unlink, then exclusive create at 0600), never rewritten in place,
160
+ * so it never exists with a looser mode. Returns the file's path.
161
+ * @param {{ port: number, token: string, dir?: string, env?: Record<string, string|undefined> }} a
162
+ */
163
+ export function writeTokenFile({
164
+ port, token, dir, env = process.env,
165
+ }) {
166
+ const d = tokenDir(dir, env);
167
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null;
168
+ mkdirSync(d, { recursive: true, mode: 0o700 });
169
+ const st = lstatSync(d);
170
+ if (!st.isDirectory() || (uid !== null && st.uid !== uid)) throw new Error('token dir is not a directory owned by this user');
171
+ chmodSync(d, 0o700);
172
+ const file = join(d, `panel-${port}.token`);
173
+ try { unlinkSync(file); } catch { /* none yet */ }
174
+ const fd = openSync(file, 'wx', 0o600);
175
+ try { writeSync(fd, `${token}\n`); } finally { closeSync(fd); }
176
+ return file;
177
+ }
178
+
179
+ /** 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] */
180
+ function settingsReply(res, pending, headOnly = false) {
181
+ pending.then((r) => {
182
+ if (!headOnly) { sendJson(res, r.status, r.body); return; }
183
+ res.writeHead(r.status, { 'content-type': 'application/json; charset=utf-8' });
184
+ res.end();
185
+ }, () => sendJson(res, 500, { ok: false, refused: 'internal', say: 'Something went wrong inside the panel. Nothing was changed.' }));
186
+ }
187
+
188
+ /** @param {any} res */
189
+ function refuseBusy(res) {
190
+ refuse(res, 409, 'already-resuming', 'already resuming — this run has a resume in progress; wait for it to end');
191
+ }
192
+
193
+ /**
194
+ * The ONE place a write route turns `{flow, runId}` into a run dir: the flow must really sit inside
195
+ * `--root` (`resolveFlowDir`, realpath at use time — a symlinked flow outside root is refused by
196
+ * name), then the runId resolves inside that flow's runs/. On a refusal it has already replied.
197
+ * @param {any} res @param {string} root @param {unknown} flow @param {unknown} runId
198
+ * @returns {string|null} the run dir, or null (already replied)
199
+ */
200
+ function resolveRun(res, root, flow, runId) {
201
+ const fd = resolveFlowDir(root, /** @type {string} */ (flow));
202
+ if (!fd.ok) {
203
+ if (fd.why === 'outside-root') refuse(res, 403, 'flow-outside-root', cleanPaths(fd.red, root));
204
+ else refuse(res, 400, 'bad-flow', cleanPaths(fd.red, root));
205
+ return null;
206
+ }
207
+ const rd = resolveRunDir(fd.flowDir, runId);
208
+ if (!rd.ok) { refuse(res, 400, 'bad-runId', cleanPaths(rd.red, root)); return null; }
209
+ return rd.runDir;
210
+ }
211
+
212
+ /** Is the run already parked on `askId` and waiting on the human: it is the open `ask.json`, no answer is saved
213
+ * for it and none was consumed? Then a resume child still alive for the run is only closing.
214
+ * @param {string} runDir @param {string} askId */
215
+ function parkedOnYou(runDir, askId) {
216
+ return readAsk(runDir)?.askId === askId && readSavedAnswer(runDir) === null && !hasConsumedAnswer(runDir, askId);
217
+ }
218
+
103
219
  /**
104
220
  * `POST /api/answer` — runs after the gates. Wraps `answerAsk` with exactly
105
221
  * the arguments `bin/fwdloop`'s `cmdAnswer` passes ({ runDir, askId, decision,
@@ -117,26 +233,88 @@ function answerRoute(res, body, root, resumer) {
117
233
  refuse(res, 400, 'askid-required', 'an answer must name the askId the page was showing');
118
234
  return;
119
235
  }
120
- const fc = checkFlowName(flow);
121
- if (!fc.ok) { refuse(res, 400, 'bad-flow', fc.red); return; }
122
- const rd = resolveRunDir(join(root, flow), runId);
123
- if (!rd.ok) { refuse(res, 400, 'bad-runId', rd.red); return; }
236
+ const runDir = resolveRun(res, root, flow, runId);
237
+ if (runDir === null) return;
238
+ // One resume at a time per run (M4c-fix item 1): refused BEFORE the answer is written, so a refused
239
+ // click leaves the books as they were.
240
+ // Only a real concurrent resume is blocked. A previous resume child that is merely closing — the run has already
241
+ // parked on THIS ask, nothing answered or consumed for it — does not block the human's answer (amendment 1 (e)(1)).
242
+ if (resumer.busy(flow, runId) && !parkedOnYou(runDir, askId)) { refuseBusy(res); return; }
124
243
  const result = answerAsk({
125
- runDir: rd.runDir, askId, decision, reason,
244
+ runDir, askId, decision, reason,
126
245
  });
127
246
  if (!result.ok) {
128
- sendJson(res, 409, { ok: false, refused: 'library', red: result.red });
247
+ sendJson(res, 409, { ok: false, refused: 'library', red: cleanPaths(result.red, root) });
129
248
  return;
130
249
  }
131
250
  const attempt = resumer.start({
132
- flow, runId, runDir: rd.runDir, askId,
251
+ flow, runId, runDir, askId,
133
252
  });
134
253
  sendJson(res, 202, {
135
- ok: true, answered: true, askId, decision: normalizeDecision(decision), resume: 'started', tries: attempt.tries, maxTries: attempt.maxTries,
254
+ ok: true, answered: true, askId, decision: normalizeDecision(decision), setAside: result.setAside, resume: 'started', tries: attempt.tries, maxTries: attempt.maxTries,
136
255
  note: 'answer saved; the resume was started in the background — its state is in the run\'s data (`resume`), not in this reply',
137
256
  });
138
257
  }
139
258
 
259
+ /**
260
+ * `POST /api/reopen` — runs after the same gates as the answer (cookie, own Host, own Origin). The human's
261
+ * "Reopen for another <wait>" on an expired ask (M4c-fix amendment 1 (b)): `reopenAsk` writes the reopen record
262
+ * (a fresh window of the same signed length, on the same ask) and moves a late answer aside. Nothing else reopens:
263
+ * no runner or agent path calls it. Refused 409 while a resume of the run is alive, and for a run that has ended.
264
+ * @param {any} res @param {any} body @param {string} root @param {ReturnType<typeof createResumer>} resumer
265
+ */
266
+ function reopenRoute(res, body, root, resumer) {
267
+ const b = body !== null && typeof body === 'object' ? body : {};
268
+ const { flow, runId, askId } = b;
269
+ if (typeof askId !== 'string' || askId.length === 0) {
270
+ refuse(res, 400, 'askid-required', 'a reopen must name the askId the page was showing');
271
+ return;
272
+ }
273
+ const runDir = resolveRun(res, root, flow, runId);
274
+ if (runDir === null) return;
275
+ if (resumer.busy(flow, runId)) { refuseBusy(res); return; }
276
+ if (readHistory(dirname(dirname(runDir))).some((r) => r && r.runId === runId)) {
277
+ refuse(res, 409, 'run-ended', 'this run has ended — there is nothing to reopen');
278
+ return;
279
+ }
280
+ const result = reopenAsk({ runDir, askId, by: 'human via panel' });
281
+ if (!result.ok) {
282
+ sendJson(res, 409, { ok: false, refused: 'library', red: cleanPaths(result.red, root) });
283
+ return;
284
+ }
285
+ sendJson(res, 200, {
286
+ ok: true, reopened: true, askId, expiresAt: result.expiresAt, n: result.n, setAside: result.setAside,
287
+ });
288
+ }
289
+
290
+ /**
291
+ * `POST /api/remove-lock` — runs after the same gates as the answer (cookie, own Host, own Origin). The human's
292
+ * "Remove the old lock" (M4c-fix amendment 2 (h)): only for a run with a saved answer and no resume alive; `removeOldLock`
293
+ * re-checks at this moment that the lock still has no recorded holder, removes it and writes the one audit row; then the
294
+ * run continues exactly like "Continue the run" (the same `resumer.start`). Nothing else calls the remover.
295
+ * @param {any} res @param {any} body @param {string} root @param {ReturnType<typeof createResumer>} resumer
296
+ */
297
+ function removeLockRoute(res, body, root, resumer) {
298
+ const b = body !== null && typeof body === 'object' ? body : {};
299
+ const { flow, runId } = b;
300
+ const runDir = resolveRun(res, root, flow, runId);
301
+ if (runDir === null) return;
302
+ const saved = readSavedAnswer(runDir);
303
+ if (!saved) {
304
+ refuse(res, 409, 'no-saved-answer', 'this run has no saved, unconsumed answer — a resume would have nothing to apply');
305
+ return;
306
+ }
307
+ if (resumer.busy(flow, runId)) { refuseBusy(res); return; }
308
+ const removed = removeOldLock({ root, runDir });
309
+ if (!removed.ok) { refuse(res, 409, removed.refused, cleanPaths(removed.red, root)); return; }
310
+ const attempt = resumer.start({
311
+ flow, runId, runDir, askId: saved.askId,
312
+ });
313
+ sendJson(res, 202, {
314
+ ok: true, lockRemoved: true, resume: 'started', askId: saved.askId, tries: attempt.tries, maxTries: attempt.maxTries,
315
+ });
316
+ }
317
+
140
318
  /**
141
319
  * `POST /api/resume` — runs after the same gates as the answer. Starts a
142
320
  * resume ONLY for a run that has a saved, unconsumed answer; it takes no
@@ -146,22 +324,16 @@ function answerRoute(res, body, root, resumer) {
146
324
  function resumeRoute(res, body, root, resumer) {
147
325
  const b = body !== null && typeof body === 'object' ? body : {};
148
326
  const { flow, runId } = b;
149
- const fc = checkFlowName(flow);
150
- if (!fc.ok) { refuse(res, 400, 'bad-flow', fc.red); return; }
151
- const rd = resolveRunDir(join(root, flow), runId);
152
- if (!rd.ok) { refuse(res, 400, 'bad-runId', rd.red); return; }
153
- const saved = readSavedAnswer(rd.runDir);
327
+ const runDir = resolveRun(res, root, flow, runId);
328
+ if (runDir === null) return;
329
+ const saved = readSavedAnswer(runDir);
154
330
  if (!saved) {
155
331
  refuse(res, 409, 'no-saved-answer', 'this run has no saved, unconsumed answer — a resume would have nothing to apply');
156
332
  return;
157
333
  }
158
- const current = resumer.get(flow, runId);
159
- if (current && current.state === 'in-flight') {
160
- refuse(res, 409, 'resume-in-flight', `a resume for this run is already being started (try ${current.tries} of ${current.maxTries})`);
161
- return;
162
- }
334
+ if (resumer.busy(flow, runId)) { refuseBusy(res); return; }
163
335
  const attempt = resumer.start({
164
- flow, runId, runDir: rd.runDir, askId: saved.askId,
336
+ flow, runId, runDir, askId: saved.askId,
165
337
  });
166
338
  sendJson(res, 202, {
167
339
  ok: true, resume: 'started', askId: saved.askId, tries: attempt.tries, maxTries: attempt.maxTries,
@@ -174,11 +346,17 @@ function resumeRoute(res, body, root, resumer) {
174
346
  * real listening socket where that is simpler.
175
347
  * @param {import('node:http').IncomingMessage} req
176
348
  * @param {import('node:http').ServerResponse} res
177
- * @param {{ root: string, port: number, token: string, resumer: ReturnType<typeof createResumer> }} opts
349
+ * @param {{ root: string, port: number, token: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings> }} opts
178
350
  */
179
351
  export function handleRequest(req, res, opts) {
180
352
  const method = req.method ?? 'GET';
181
353
 
354
+ // M4c-fix item 3: EVERY response — refusals, redirects, errors, the page — says it must not be
355
+ // framed or cached. Set first, before any branch can write; `writeHead` merges these in.
356
+ res.setHeader('X-Frame-Options', 'DENY');
357
+ res.setHeader('Content-Security-Policy', "frame-ancestors 'none'");
358
+ res.setHeader('Cache-Control', 'no-store');
359
+
182
360
  // Gate 1 — EVERY route, every method: `Host` must be this server's own
183
361
  // address. A foreign Host (DNS rebinding) is refused by name, never 200.
184
362
  const host = req.headers.host;
@@ -187,36 +365,81 @@ export function handleRequest(req, res, opts) {
187
365
  return;
188
366
  }
189
367
 
190
- if (method === 'POST' && (req.url === '/api/answer' || req.url === '/api/resume')) {
368
+ // Gate 2 — EVERY route, every method (the page included): the panel's own cookie, set by opening
369
+ // the printed `/?t=<token>` link. Without it: 403 by name, and nothing in the body is a token.
370
+ const cookies = Object.fromEntries(String(req.headers.cookie ?? '').split(';').map((c) => {
371
+ const i = c.indexOf('=');
372
+ return i < 0 ? ['', ''] : [c.slice(0, i).trim(), c.slice(i + 1).trim()];
373
+ }));
374
+ if (!tokenMatches(cookies[cookieName(opts.port)], opts.token)) {
375
+ const link = method === 'GET' || method === 'HEAD' ? new URL(String(req.url), 'http://127.0.0.1') : null;
376
+ if (link && link.pathname === '/' && tokenMatches(link.searchParams.get('t'), opts.token)) {
377
+ res.writeHead(302, {
378
+ 'set-cookie': `${cookieName(opts.port)}=${opts.token}; HttpOnly; SameSite=Strict; Path=/`, location: '/', 'content-length': 0,
379
+ });
380
+ res.end();
381
+ return;
382
+ }
383
+ // A browser opening the bare page sees a plain page that says what to do, not a blank JSON "forbidden"
384
+ // that reads as "the panel is down". No token, no script. API routes keep the JSON 403.
385
+ if (link && link.pathname === '/' && /text\/html/.test(String(req.headers.accept ?? ''))) {
386
+ const html = '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>fwdloop panel</title>'
387
+ + '<p style="font:16px/1.5 system-ui,sans-serif;max-width:40em;margin:2em auto;padding:0 1em">'
388
+ + 'fwdloop panel: open the link printed in the terminal where you started <code>fwdloop panel</code> (it ends in ?t=…). '
389
+ + 'Restarted the panel? Open its new link.</p>';
390
+ res.writeHead(403, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
391
+ res.end(method === 'HEAD' ? undefined : html);
392
+ return;
393
+ }
394
+ refuse(res, 403, 'cookie-missing-or-wrong', 'open the link `fwdloop panel` printed');
395
+ return;
396
+ }
397
+
398
+ // M4d piece 4: every `/api/settings/...` POST (a known one or not) goes through the same Origin + body-cap gates.
399
+ const isSettingsPost = method === 'POST' && String(req.url).startsWith('/api/settings/');
400
+ if (method === 'POST' && (isSettingsPost || req.url === '/api/answer' || req.url === '/api/resume' || req.url === '/api/reopen' || req.url === '/api/remove-lock')) {
191
401
  const isResume = req.url === '/api/resume';
402
+ const isReopen = req.url === '/api/reopen';
403
+ const isRemoveLock = req.url === '/api/remove-lock';
192
404
  const origin = req.headers.origin;
193
405
  if (origin !== `http://127.0.0.1:${opts.port}` && origin !== `http://localhost:${opts.port}`) {
194
406
  refuse(res, 403, 'origin-not-own', String(origin));
195
407
  return;
196
408
  }
197
- if (!tokenMatches(req.headers[TOKEN_HEADER], opts.token)) {
198
- refuse(res, 403, 'token-missing-or-wrong');
199
- return;
200
- }
201
409
  let size = 0;
202
410
  const parts = [];
203
- req.on('data', (c) => { size += c.length; if (size <= MAX_BODY_BYTES) parts.push(c); });
411
+ let tooBig = false;
412
+ req.on('data', (c) => {
413
+ if (tooBig) return;
414
+ size += c.length;
415
+ if (size <= MAX_BODY_BYTES) { parts.push(c); return; }
416
+ // M4c-fix item 6: over the limit — stop at once. Drop what was collected, refuse (413, then the
417
+ // connection closes), and cut the request off; the rest of the body is never read.
418
+ tooBig = true;
419
+ parts.length = 0;
420
+ res.setHeader('Connection', 'close');
421
+ refuse(res, 413, 'body-too-large');
422
+ res.once('finish', () => req.destroy());
423
+ });
204
424
  req.on('end', () => {
205
425
  try {
206
- if (size > MAX_BODY_BYTES) { refuse(res, 413, 'body-too-large'); return; }
426
+ if (tooBig) return;
207
427
  let body;
208
428
  try { body = JSON.parse(Buffer.concat(parts).toString('utf8')); } catch { refuse(res, 400, 'body-not-json'); return; }
429
+ if (isSettingsPost) { settingsReply(res, opts.settings.handle({ method, pathname: String(req.url), query: new URLSearchParams(), body })); return; }
209
430
  if (isResume) resumeRoute(res, body, opts.root, opts.resumer);
431
+ else if (isReopen) reopenRoute(res, body, opts.root, opts.resumer);
432
+ else if (isRemoveLock) removeLockRoute(res, body, opts.root, opts.resumer);
210
433
  else answerRoute(res, body, opts.root, opts.resumer);
211
434
  } catch (e) {
212
- refuse(res, 500, 'internal', /** @type {Error} */ (e).message);
435
+ sendJson(res, 500, { ok: false, refused: 'internal', red: 'internal error' });
213
436
  }
214
437
  });
215
438
  return;
216
439
  }
217
440
 
218
441
  if (method !== 'GET' && method !== 'HEAD') {
219
- sendText(res, 405, 'method not allowed — GET/HEAD for reads; the only writes are POST /api/answer and POST /api/resume');
442
+ 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');
220
443
  return;
221
444
  }
222
445
 
@@ -239,6 +462,13 @@ export function handleRequest(req, res, opts) {
239
462
  sendJson(res, code, body);
240
463
  };
241
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
+
242
472
  if (pathname === '/' || pathname === '/index.html') {
243
473
  const indexPath = join(HERE, 'index.html');
244
474
  let html;
@@ -249,7 +479,6 @@ export function handleRequest(req, res, opts) {
249
479
  return;
250
480
  }
251
481
  html = html.replace(/__FWDLOOP_PANEL_PORT__/g, String(opts.port));
252
- html = html.replace(/__FWDLOOP_PANEL_TOKEN__/g, opts.token);
253
482
  if (method === 'HEAD') {
254
483
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
255
484
  res.end();
@@ -262,7 +491,7 @@ export function handleRequest(req, res, opts) {
262
491
 
263
492
  const loaded = loadCatalogue();
264
493
  if (!loaded.ok) {
265
- sendText(res, 500, `catalogue failed to load: ${loaded.reds.join('; ')}`);
494
+ sendText(res, 500, `catalogue failed to load: ${cleanPaths(loaded.reds.join('; '), opts.root)}`);
266
495
  return;
267
496
  }
268
497
  const catalogue = loaded.primitives;
@@ -293,6 +522,11 @@ export function handleRequest(req, res, opts) {
293
522
  }
294
523
  const sub = runMatch[4] ?? null;
295
524
 
525
+ // A flow symlinked outside --root is refused BY NAME for every read (the data layer alone would
526
+ // only say "no such run"). Anything else about the flow still falls through to the 404.
527
+ const fd = resolveFlowDir(opts.root, flow);
528
+ if (!fd.ok && fd.why === 'outside-root') { refuse(res, 403, 'flow-outside-root', cleanPaths(fd.red, opts.root)); return; }
529
+
296
530
  if (sub === 'audit') {
297
531
  const result = getRunAudit({ root: opts.root, flow, runId });
298
532
  if (!result) { sendText(res, 404, 'no such run'); return; }
@@ -332,9 +566,9 @@ export function handleRequest(req, res, opts) {
332
566
  * header). Resolves once actually listening; rejects on a bind error
333
567
  * (including `EADDRINUSE`) with a `.port` field on the error for the
334
568
  * caller's message.
335
- * @param {{ port?: number, root: string, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
569
+ * @param {{ port?: number, root: string, token?: 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 } }} opts
336
570
  * `resume` is for tests only (a fake env/bin, a short retry window); the CLI passes none.
337
- * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
571
+ * @returns {Promise<{ server: import('node:http').Server, port: number, token: string, close: () => Promise<void> }>}
338
572
  */
339
573
  export function createPanelServer(opts) {
340
574
  if (typeof opts?.root !== 'string' || opts.root.length === 0) {
@@ -343,10 +577,17 @@ export function createPanelServer(opts) {
343
577
  const requestedPort = opts.port ?? DEFAULT_PORT;
344
578
  const { root } = opts;
345
579
  // One resumer per server: the one owner of every run's resume-attempt record.
346
- const resumer = createResumer({ root, ...opts.resume });
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
+ // Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
583
+ // process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
584
+ const door = configDoorHome();
585
+ const settings = createSettings({
586
+ 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,
587
+ });
347
588
  // One token per server process, made once, held only here and in the served
348
589
  // page — never logged, never in any /api response.
349
- const token = randomBytes(32).toString('hex');
590
+ const token = typeof opts.token === 'string' && /^[0-9a-f]{64}$/.test(opts.token) ? opts.token : randomBytes(32).toString('hex');
350
591
  return new Promise((resolve, reject) => {
351
592
  // Bound port is resolved from the live socket (`server.address().port`)
352
593
  // once listening starts, not the requested value — this is what makes
@@ -357,10 +598,10 @@ export function createPanelServer(opts) {
357
598
  const server = createServer((req, res) => {
358
599
  try {
359
600
  handleRequest(req, res, {
360
- root, port: boundPort, token, resumer,
601
+ root, port: boundPort, token, resumer, settings,
361
602
  });
362
603
  } catch (e) {
363
- sendText(res, 500, `internal error: ${/** @type {Error} */ (e).message}`);
604
+ sendText(res, 500, 'internal error');
364
605
  }
365
606
  });
366
607
  server.once('error', (e) => {
@@ -374,6 +615,7 @@ export function createPanelServer(opts) {
374
615
  resolve({
375
616
  server,
376
617
  port: boundPort,
618
+ token,
377
619
  close: () => new Promise((res2) => { server.close(() => res2(undefined)); }),
378
620
  });
379
621
  });
@@ -403,8 +645,14 @@ export async function panelMain(argv, ctx) {
403
645
  }
404
646
  }
405
647
  try {
406
- const { port: boundPort } = await createPanelServer({ port, root });
407
- ctx.out(`fwdloop panel — http://127.0.0.1:${boundPort} (root: ${root}) (Ctrl-C to stop)`);
648
+ const { port: boundPort, token } = await createPanelServer({ port, root, token: loadOrMakeToken({ port }) });
649
+ writeTokenFile({ port: boundPort, token });
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));
654
+ ctx.out(`fwdloop panel — (root: ${root}) (Ctrl-C to stop)`);
655
+ ctx.out(`open this link (it sets the panel's cookie): http://127.0.0.1:${boundPort}/?t=${token}`);
408
656
  // never resolves on its own — the process stays up until killed, same
409
657
  // shape any other long-running dev server takes.
410
658
  await new Promise(() => {});