fwdloop 0.8.1 → 0.10.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.
- package/bin/fwdloop +10 -8
- package/package.json +1 -1
- package/src/ask.js +130 -13
- package/src/books.js +20 -0
- package/src/liveness.js +160 -0
- package/src/panel/data.js +444 -73
- package/src/panel/index.html +604 -114
- package/src/panel/resume.js +197 -0
- package/src/panel/server.js +167 -14
- package/src/runner.js +115 -40
- package/src/send.js +19 -2
- package/types/ask.d.ts +75 -5
- package/types/books.d.ts +19 -0
- package/types/liveness.d.ts +69 -0
- package/types/panel/data.d.ts +183 -21
- package/types/panel/resume.d.ts +51 -0
- package/types/panel/server.d.ts +15 -3
- package/types/runner.d.ts +9 -7
- package/types/send.d.ts +4 -1
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// M4b piece 2 (docs/wiki/the-module-ladder.md, "M4b — inputs" scope 3 and
|
|
2
|
+
// "M4b amendment 1" scope 1-2): how the panel starts a resume and checks it
|
|
3
|
+
// took over. The proven shape is `poc/m4b/answer-door.mjs` (F51), ported, not
|
|
4
|
+
// imported.
|
|
5
|
+
//
|
|
6
|
+
// What happens after the library accepts an answer:
|
|
7
|
+
// 1. The panel spawns `fwdloop resume <runId> --flow <name> --root <root>` as
|
|
8
|
+
// its own detached process (own process group, `unref()`), env = the
|
|
9
|
+
// panel server's own env, stdout+stderr -> one log file. The HTTP reply
|
|
10
|
+
// never waits for it, and killing the panel (or closing the tab) does not
|
|
11
|
+
// stop it.
|
|
12
|
+
// 2. "Took over" is read from the BOOKS: the resume consumes `answer.json`
|
|
13
|
+
// by renaming it to `answer.<askId>.consumed.json` (F44) — never from the
|
|
14
|
+
// child's output. If the child exited, the answer is still unconsumed and
|
|
15
|
+
// its refusal is the run-lock one ("locked by another resumer"), start it
|
|
16
|
+
// again: up to `RESUME_MAX_TRIES` tries within `RESUME_WINDOW_MS` (signed
|
|
17
|
+
// numbers). Only the lock refusal is retried.
|
|
18
|
+
// 3. Still unconsumed after the last try (or a non-lock refusal): the attempt
|
|
19
|
+
// record says so, with the child's own refusal text verbatim; `data.js`
|
|
20
|
+
// turns that into "answer saved, resume not started".
|
|
21
|
+
//
|
|
22
|
+
// No second mutex: exactly one resume applies the answer because the resume's
|
|
23
|
+
// own rename-to-consume is atomic (F44). This module only decides whether to
|
|
24
|
+
// launch another process; it never consumes, deletes or writes a book.
|
|
25
|
+
//
|
|
26
|
+
// The per-run "resume attempt" record is written only inside `createResumer`;
|
|
27
|
+
// everything else reads a copy through `get`. `start` creates it and sets
|
|
28
|
+
// `superseded = true` on the run's previous record; the loop sets `logPath`
|
|
29
|
+
// and `tries`; `finish` sets `state`, `refusal` and `endedAt`.
|
|
30
|
+
//
|
|
31
|
+
// Log location: `<os tmpdir>/fwdloop-panel-logs-<uid>/`, mode 0700, files 0600
|
|
32
|
+
// — OUTSIDE the flows root and every run dir, so no step's sandboxed read/grep
|
|
33
|
+
// can reach it and it is never one of a run's frozen inputs. The CLI does not
|
|
34
|
+
// redact: it prints only its own error messages (never the key), so a key
|
|
35
|
+
// could reach the log only through a provider error body that echoes it.
|
|
36
|
+
|
|
37
|
+
import { spawn } from 'node:child_process';
|
|
38
|
+
import { createHash } from 'node:crypto';
|
|
39
|
+
import {
|
|
40
|
+
closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync,
|
|
41
|
+
} from 'node:fs';
|
|
42
|
+
import { tmpdir } from 'node:os';
|
|
43
|
+
import { dirname, join } from 'node:path';
|
|
44
|
+
import { fileURLToPath } from 'node:url';
|
|
45
|
+
|
|
46
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
47
|
+
const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
|
|
48
|
+
|
|
49
|
+
/** Signed with M4b amendment 1, scope 1: up to 5 tries within 10 seconds. */
|
|
50
|
+
export const RESUME_MAX_TRIES = 5;
|
|
51
|
+
export const RESUME_WINDOW_MS = 10_000;
|
|
52
|
+
|
|
53
|
+
/** The runner's own lock refusal (`src/runner.js` resumeRun) — the ONLY one retried. */
|
|
54
|
+
const LOCK_REFUSAL = /locked by another resumer/;
|
|
55
|
+
/** How often the books are checked for the consumed marker while a child runs. */
|
|
56
|
+
const POLL_MS = 20;
|
|
57
|
+
/** A refusal longer than this is cut (verbatim up to the cut). */
|
|
58
|
+
const MAX_REFUSAL_CHARS = 2000;
|
|
59
|
+
|
|
60
|
+
/** @param {number} ms */
|
|
61
|
+
const sleep = (ms) => new Promise((r) => { setTimeout(r, ms); });
|
|
62
|
+
|
|
63
|
+
/** The private log directory; refuses a directory we do not own or a symlink.
|
|
64
|
+
* @param {string|undefined} dir */
|
|
65
|
+
function ensureLogDir(dir) {
|
|
66
|
+
const uid = typeof process.getuid === 'function' ? process.getuid() : null;
|
|
67
|
+
const d = dir ?? join(tmpdir(), `fwdloop-panel-logs-${uid ?? 'user'}`);
|
|
68
|
+
mkdirSync(d, { recursive: true, mode: 0o700 });
|
|
69
|
+
const st = lstatSync(d);
|
|
70
|
+
if (!st.isDirectory() || (uid !== null && st.uid !== uid)) {
|
|
71
|
+
throw new Error(`resume log dir ${d} is not a directory owned by this user`);
|
|
72
|
+
}
|
|
73
|
+
return d;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* @param {{ root: string, env?: Record<string, string|undefined>, bin?: string, logDir?: string,
|
|
78
|
+
* maxTries?: number, windowMs?: number, slotMs?: number }} opts
|
|
79
|
+
* `env`/`bin`/`logDir`/`maxTries`/`windowMs`/`slotMs` are injectable so tests neither sleep 10 s
|
|
80
|
+
* nor need a live key; production passes none of them. `slotMs` (default `windowMs / maxTries`,
|
|
81
|
+
* i.e. 2000 ms) is only the spacing between tries: a test sets it small and `windowMs` (the
|
|
82
|
+
* per-try "did it take over" deadline) large, so CPU load cannot turn a slow child start into a
|
|
83
|
+
* false "stuck".
|
|
84
|
+
*/
|
|
85
|
+
export function createResumer(opts) {
|
|
86
|
+
const {
|
|
87
|
+
root, env = process.env, bin = BIN, maxTries = RESUME_MAX_TRIES, windowMs = RESUME_WINDOW_MS, slotMs = windowMs / maxTries,
|
|
88
|
+
} = opts;
|
|
89
|
+
const rootTag = createHash('sha256').update(root).digest('hex').slice(0, 8);
|
|
90
|
+
/** @type {Map<string, any>} */
|
|
91
|
+
const attempts = new Map();
|
|
92
|
+
const keyOf = (flow, runId) => `${flow}/${runId}`;
|
|
93
|
+
|
|
94
|
+
/** One resume process. Resolves as soon as the books show the answer consumed,
|
|
95
|
+
* or the child exited, or `deadline` passed — never waits for a long resume. */
|
|
96
|
+
function tryOnce({ flow, runId, runDir, askId, logPath, deadline }) {
|
|
97
|
+
const consumedPath = join(runDir, `answer.${askId}.consumed.json`);
|
|
98
|
+
const fd = openSync(logPath, 'a', 0o600);
|
|
99
|
+
const offset = statSync(logPath).size;
|
|
100
|
+
const child = spawn(process.execPath, [bin, 'resume', runId, '--flow', flow, '--root', root], {
|
|
101
|
+
detached: true, stdio: ['ignore', fd, fd], env,
|
|
102
|
+
});
|
|
103
|
+
child.unref();
|
|
104
|
+
closeSync(fd);
|
|
105
|
+
const sliceOfLog = () => {
|
|
106
|
+
try { return readFileSync(logPath).subarray(offset).toString('utf8').trim(); } catch { return ''; } // offset is in BYTES
|
|
107
|
+
};
|
|
108
|
+
const settled = new Promise((resolve) => {
|
|
109
|
+
let done = false;
|
|
110
|
+
const end = (v) => {
|
|
111
|
+
if (done) return;
|
|
112
|
+
done = true;
|
|
113
|
+
clearInterval(iv);
|
|
114
|
+
resolve(v);
|
|
115
|
+
};
|
|
116
|
+
child.once('exit', (code, sig) => end({ kind: 'exited', code, sig, text: sliceOfLog() }));
|
|
117
|
+
child.once('error', (e) => end({ kind: 'exited', code: null, sig: null, text: `spawn failed: ${e.message}` }));
|
|
118
|
+
const iv = setInterval(() => {
|
|
119
|
+
if (existsSync(consumedPath)) end({ kind: 'took-over' });
|
|
120
|
+
else if (Date.now() > deadline) end({ kind: 'slow', pid: child.pid, text: sliceOfLog() });
|
|
121
|
+
}, POLL_MS);
|
|
122
|
+
});
|
|
123
|
+
// A clean exit leaves nothing to explain, so its log goes (best effort); any other exit or a
|
|
124
|
+
// spawn failure keeps it. Registered after the listener above so that one reads the log first.
|
|
125
|
+
child.once('exit', (code) => {
|
|
126
|
+
if (code === 0) { try { unlinkSync(logPath); } catch { /* best effort */ } }
|
|
127
|
+
});
|
|
128
|
+
return settled;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** @param {any} rec @param {'took-over'|'stuck'} state @param {string|null} refusal */
|
|
132
|
+
function finish(rec, state, refusal) {
|
|
133
|
+
rec.state = state;
|
|
134
|
+
rec.refusal = refusal;
|
|
135
|
+
rec.endedAt = Date.now();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function loop(rec, runDir) {
|
|
139
|
+
const t0 = Date.now();
|
|
140
|
+
const logPath = join(ensureLogDir(opts.logDir), `resume-${rootTag}-${rec.flow}-${rec.runId}.log`);
|
|
141
|
+
rec.logPath = logPath;
|
|
142
|
+
const consumed = () => existsSync(join(runDir, `answer.${rec.askId}.consumed.json`));
|
|
143
|
+
for (let n = 1; n <= maxTries; n += 1) {
|
|
144
|
+
if (rec.superseded) return;
|
|
145
|
+
rec.tries = n;
|
|
146
|
+
// eslint-disable-next-line no-await-in-loop
|
|
147
|
+
const r = await tryOnce({
|
|
148
|
+
flow: rec.flow, runId: rec.runId, runDir, askId: rec.askId, logPath, deadline: Date.now() + windowMs,
|
|
149
|
+
});
|
|
150
|
+
if (rec.superseded) return;
|
|
151
|
+
if (r.kind === 'took-over' || consumed()) { finish(rec, 'took-over', null); return; }
|
|
152
|
+
if (r.kind === 'slow') {
|
|
153
|
+
finish(rec, 'stuck', `the resume process (pid ${r.pid}) had not taken over the answer within ${windowMs} ms${r.text ? `: ${r.text.slice(0, MAX_REFUSAL_CHARS)}` : ''}`);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const text = r.text.slice(0, MAX_REFUSAL_CHARS);
|
|
157
|
+
if (!LOCK_REFUSAL.test(r.text) || n === maxTries) {
|
|
158
|
+
finish(rec, 'stuck', text.length > 0 ? text : `the resume exited (code ${r.code}${r.sig ? `, signal ${r.sig}` : ''}) without taking over the answer and printed nothing`);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
// Locked: the next try starts at its slot, so the last one still lands inside the window.
|
|
162
|
+
// eslint-disable-next-line no-await-in-loop
|
|
163
|
+
await sleep(Math.max(0, t0 + n * slotMs - Date.now()));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
/**
|
|
169
|
+
* Start the detached resume for a saved answer and return at once with the
|
|
170
|
+
* attempt record (a copy); the verify/retry loop runs in the background.
|
|
171
|
+
* @param {{ flow: string, runId: string, runDir: string, askId: string }} a
|
|
172
|
+
*/
|
|
173
|
+
start({
|
|
174
|
+
flow, runId, runDir, askId,
|
|
175
|
+
}) {
|
|
176
|
+
const key = keyOf(flow, runId);
|
|
177
|
+
const old = attempts.get(key);
|
|
178
|
+
if (old) old.superseded = true;
|
|
179
|
+
const rec = {
|
|
180
|
+
flow, runId, askId, state: 'in-flight', tries: 0, maxTries, windowMs, refusal: null, startedAt: Date.now(), endedAt: null, logPath: null, superseded: false,
|
|
181
|
+
};
|
|
182
|
+
attempts.set(key, rec);
|
|
183
|
+
loop(rec, runDir).catch((e) => finish(rec, 'stuck', `the panel could not start the resume: ${e.message}`));
|
|
184
|
+
return { ...rec };
|
|
185
|
+
},
|
|
186
|
+
/** A copy of the run's attempt record, or null (none yet, or the panel restarted).
|
|
187
|
+
* @param {string} flow @param {string} runId */
|
|
188
|
+
get(flow, runId) {
|
|
189
|
+
const rec = attempts.get(keyOf(flow, runId));
|
|
190
|
+
return rec ? { ...rec } : null;
|
|
191
|
+
},
|
|
192
|
+
/** Every log file this resumer has written (for tests and hygiene checks). */
|
|
193
|
+
logPaths() {
|
|
194
|
+
return [...new Set([...attempts.values()].map((r) => r.logPath).filter(Boolean))];
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
package/src/panel/server.js
CHANGED
|
@@ -23,9 +23,21 @@
|
|
|
23
23
|
// `readSpendRows`, `readAskEvidence`, `loadCatalogue`) — this file is only
|
|
24
24
|
// the HTTP shell + route dispatch, never a second copy of any derivation.
|
|
25
25
|
//
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
//
|
|
26
|
+
// M4b pieces 1-2 (docs/wiki/the-module-ladder.md, "M4b — inputs" scope 1-3,
|
|
27
|
+
// "M4b amendment 1" scope 1-3): every read route is still GET/HEAD and derives
|
|
28
|
+
// nothing new. The writes are `POST /api/answer`, a thin client of the
|
|
29
|
+
// library's `answerAsk` (the panel is never a second arbiter), and
|
|
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
|
|
32
|
+
// a real click from the served page — own `Host` and `Origin`, the per-process
|
|
33
|
+
// token (embedded only in the served page), a small JSON body. An answer must
|
|
34
|
+
// name its `askId`. `Host` is checked on EVERY route, GET included
|
|
35
|
+
// (DNS-rebinding read). After an accepted answer the panel starts the resume
|
|
36
|
+
// as a separate detached process and checks from the books that it took over
|
|
37
|
+
// (`src/panel/resume.js`); the reply never waits for it.
|
|
38
|
+
// No endpoint runs a job itself, spends money itself, signs, or reads a
|
|
39
|
+
// key/.env: the resume child inherits the server's own env, and this file
|
|
40
|
+
// never looks inside it.
|
|
29
41
|
//
|
|
30
42
|
// PATH SAFETY: a URL may name a flow ONLY (checked with `checkFlowName`) and
|
|
31
43
|
// a runId ONLY (resolved with `resolveRunDir`, both `src/flow.js`) — a URL
|
|
@@ -34,17 +46,26 @@
|
|
|
34
46
|
// directory's own `index.html`, never a URL-derived filename.
|
|
35
47
|
|
|
36
48
|
import { createServer } from 'node:http';
|
|
49
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
37
50
|
import { readFileSync } from 'node:fs';
|
|
38
51
|
import { dirname, join } from 'node:path';
|
|
39
52
|
import { fileURLToPath } from 'node:url';
|
|
40
53
|
|
|
41
54
|
import { loadCatalogue } from '../catalogue.js';
|
|
55
|
+
import { answerAsk, normalizeDecision } from '../ask.js';
|
|
56
|
+
import { checkFlowName, resolveRunDir } from '../flow.js';
|
|
42
57
|
import {
|
|
43
|
-
listRuns, getRunDetail, getRunAudit, getRunJob, listStops, getRunAsks,
|
|
58
|
+
listRuns, getRunDetail, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer,
|
|
44
59
|
} from './data.js';
|
|
60
|
+
import { createResumer } from './resume.js';
|
|
45
61
|
|
|
46
62
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
47
63
|
|
|
64
|
+
/** Cap on the answer body — a decision and a short reason, nothing more. */
|
|
65
|
+
const MAX_BODY_BYTES = 8 * 1024;
|
|
66
|
+
/** Header the page sends its token in. */
|
|
67
|
+
const TOKEN_HEADER = 'x-fwdloop-token';
|
|
68
|
+
|
|
48
69
|
/** Default bind port. Ruling, hamr 2026-09-27: fwdloop's panel default port
|
|
49
70
|
* is 4800 — bareloop owns 4700, and the two panels must be able to run
|
|
50
71
|
* side by side. */
|
|
@@ -63,18 +84,139 @@ function sendText(res, code, text) {
|
|
|
63
84
|
res.end(text);
|
|
64
85
|
}
|
|
65
86
|
|
|
87
|
+
/** A refusal, by name. `refused` is the stable machine name, `red` the words.
|
|
88
|
+
* @param {any} res @param {number} code @param {string} name @param {string} [detail] */
|
|
89
|
+
function refuse(res, code, name, detail) {
|
|
90
|
+
sendJson(res, code, { ok: false, refused: name, red: detail ? `${name}: ${detail}` : name });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Constant-time compare: both sides hashed to equal length first, so neither
|
|
94
|
+
* the content nor the length of the real token leaks through timing.
|
|
95
|
+
* @param {unknown} a @param {string} b */
|
|
96
|
+
function tokenMatches(a, b) {
|
|
97
|
+
if (typeof a !== 'string') return false;
|
|
98
|
+
const x = createHash('sha256').update(a).digest();
|
|
99
|
+
const y = createHash('sha256').update(b).digest();
|
|
100
|
+
return timingSafeEqual(x, y);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* `POST /api/answer` — runs after the gates. Wraps `answerAsk` with exactly
|
|
105
|
+
* the arguments `bin/fwdloop`'s `cmdAnswer` passes ({ runDir, askId, decision,
|
|
106
|
+
* reason }); every library refusal is returned verbatim, non-2xx. On accept it
|
|
107
|
+
* starts the detached resume (M4b piece 2) and replies at once that the
|
|
108
|
+
* resume STARTED — never "done"; how it went is read from the run's data.
|
|
109
|
+
* @param {any} res @param {any} body @param {string} root @param {ReturnType<typeof createResumer>} resumer
|
|
110
|
+
*/
|
|
111
|
+
function answerRoute(res, body, root, resumer) {
|
|
112
|
+
const b = body !== null && typeof body === 'object' ? body : {};
|
|
113
|
+
const {
|
|
114
|
+
flow, runId, askId, decision, reason,
|
|
115
|
+
} = b;
|
|
116
|
+
if (typeof askId !== 'string' || askId.length === 0) {
|
|
117
|
+
refuse(res, 400, 'askid-required', 'an answer must name the askId the page was showing');
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
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; }
|
|
124
|
+
const result = answerAsk({
|
|
125
|
+
runDir: rd.runDir, askId, decision, reason,
|
|
126
|
+
});
|
|
127
|
+
if (!result.ok) {
|
|
128
|
+
sendJson(res, 409, { ok: false, refused: 'library', red: result.red });
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const attempt = resumer.start({
|
|
132
|
+
flow, runId, runDir: rd.runDir, askId,
|
|
133
|
+
});
|
|
134
|
+
sendJson(res, 202, {
|
|
135
|
+
ok: true, answered: true, askId, decision: normalizeDecision(decision), resume: 'started', tries: attempt.tries, maxTries: attempt.maxTries,
|
|
136
|
+
note: 'answer saved; the resume was started in the background — its state is in the run\'s data (`resume`), not in this reply',
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* `POST /api/resume` — runs after the same gates as the answer. Starts a
|
|
142
|
+
* resume ONLY for a run that has a saved, unconsumed answer; it takes no
|
|
143
|
+
* decision or reason and can answer nothing. Same start path as the answer.
|
|
144
|
+
* @param {any} res @param {any} body @param {string} root @param {ReturnType<typeof createResumer>} resumer
|
|
145
|
+
*/
|
|
146
|
+
function resumeRoute(res, body, root, resumer) {
|
|
147
|
+
const b = body !== null && typeof body === 'object' ? body : {};
|
|
148
|
+
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);
|
|
154
|
+
if (!saved) {
|
|
155
|
+
refuse(res, 409, 'no-saved-answer', 'this run has no saved, unconsumed answer — a resume would have nothing to apply');
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
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
|
+
}
|
|
163
|
+
const attempt = resumer.start({
|
|
164
|
+
flow, runId, runDir: rd.runDir, askId: saved.askId,
|
|
165
|
+
});
|
|
166
|
+
sendJson(res, 202, {
|
|
167
|
+
ok: true, resume: 'started', askId: saved.askId, tries: attempt.tries, maxTries: attempt.maxTries,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
66
171
|
/**
|
|
67
|
-
* Handle one request against the
|
|
172
|
+
* Handle one request against the API + the page. Exported
|
|
68
173
|
* separately from {@link createPanelServer} so tests can drive it without a
|
|
69
174
|
* real listening socket where that is simpler.
|
|
70
175
|
* @param {import('node:http').IncomingMessage} req
|
|
71
176
|
* @param {import('node:http').ServerResponse} res
|
|
72
|
-
* @param {{ root: string, port: number }} opts
|
|
177
|
+
* @param {{ root: string, port: number, token: string, resumer: ReturnType<typeof createResumer> }} opts
|
|
73
178
|
*/
|
|
74
179
|
export function handleRequest(req, res, opts) {
|
|
75
180
|
const method = req.method ?? 'GET';
|
|
181
|
+
|
|
182
|
+
// Gate 1 — EVERY route, every method: `Host` must be this server's own
|
|
183
|
+
// address. A foreign Host (DNS rebinding) is refused by name, never 200.
|
|
184
|
+
const host = req.headers.host;
|
|
185
|
+
if (host !== `127.0.0.1:${opts.port}` && host !== `localhost:${opts.port}`) {
|
|
186
|
+
refuse(res, 403, 'host-not-own-address', String(host));
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (method === 'POST' && (req.url === '/api/answer' || req.url === '/api/resume')) {
|
|
191
|
+
const isResume = req.url === '/api/resume';
|
|
192
|
+
const origin = req.headers.origin;
|
|
193
|
+
if (origin !== `http://127.0.0.1:${opts.port}` && origin !== `http://localhost:${opts.port}`) {
|
|
194
|
+
refuse(res, 403, 'origin-not-own', String(origin));
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (!tokenMatches(req.headers[TOKEN_HEADER], opts.token)) {
|
|
198
|
+
refuse(res, 403, 'token-missing-or-wrong');
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
let size = 0;
|
|
202
|
+
const parts = [];
|
|
203
|
+
req.on('data', (c) => { size += c.length; if (size <= MAX_BODY_BYTES) parts.push(c); });
|
|
204
|
+
req.on('end', () => {
|
|
205
|
+
try {
|
|
206
|
+
if (size > MAX_BODY_BYTES) { refuse(res, 413, 'body-too-large'); return; }
|
|
207
|
+
let body;
|
|
208
|
+
try { body = JSON.parse(Buffer.concat(parts).toString('utf8')); } catch { refuse(res, 400, 'body-not-json'); return; }
|
|
209
|
+
if (isResume) resumeRoute(res, body, opts.root, opts.resumer);
|
|
210
|
+
else answerRoute(res, body, opts.root, opts.resumer);
|
|
211
|
+
} catch (e) {
|
|
212
|
+
refuse(res, 500, 'internal', /** @type {Error} */ (e).message);
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
|
|
76
218
|
if (method !== 'GET' && method !== 'HEAD') {
|
|
77
|
-
sendText(res, 405, 'method not allowed —
|
|
219
|
+
sendText(res, 405, 'method not allowed — GET/HEAD for reads; the only writes are POST /api/answer and POST /api/resume');
|
|
78
220
|
return;
|
|
79
221
|
}
|
|
80
222
|
|
|
@@ -107,6 +249,7 @@ export function handleRequest(req, res, opts) {
|
|
|
107
249
|
return;
|
|
108
250
|
}
|
|
109
251
|
html = html.replace(/__FWDLOOP_PANEL_PORT__/g, String(opts.port));
|
|
252
|
+
html = html.replace(/__FWDLOOP_PANEL_TOKEN__/g, opts.token);
|
|
110
253
|
if (method === 'HEAD') {
|
|
111
254
|
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
|
|
112
255
|
res.end();
|
|
@@ -123,14 +266,16 @@ export function handleRequest(req, res, opts) {
|
|
|
123
266
|
return;
|
|
124
267
|
}
|
|
125
268
|
const catalogue = loaded.primitives;
|
|
269
|
+
const resumeAttempt = (f, r) => opts.resumer.get(f, r);
|
|
126
270
|
|
|
127
271
|
if (pathname === '/api/runs') {
|
|
128
|
-
send(200, { rows: listRuns({ root: opts.root, catalogue }) });
|
|
272
|
+
send(200, { rows: listRuns({ root: opts.root, catalogue, resumeAttempt }) });
|
|
129
273
|
return;
|
|
130
274
|
}
|
|
131
275
|
|
|
132
276
|
if (pathname === '/api/inbox') {
|
|
133
|
-
|
|
277
|
+
const rows = listStops({ root: opts.root, resumeAttempt });
|
|
278
|
+
send(200, { rows, openCount: inboxOpenCount(rows) });
|
|
134
279
|
return;
|
|
135
280
|
}
|
|
136
281
|
|
|
@@ -164,14 +309,14 @@ export function handleRequest(req, res, opts) {
|
|
|
164
309
|
}
|
|
165
310
|
if (sub === 'asks') {
|
|
166
311
|
const result = getRunAsks({
|
|
167
|
-
root: opts.root, flow, runId, catalogue,
|
|
312
|
+
root: opts.root, flow, runId, catalogue, resumeAttempt,
|
|
168
313
|
});
|
|
169
314
|
if (!result) { sendText(res, 404, 'no such run'); return; }
|
|
170
315
|
send(200, result);
|
|
171
316
|
return;
|
|
172
317
|
}
|
|
173
318
|
const result = getRunDetail({
|
|
174
|
-
root: opts.root, flow, runId, catalogue,
|
|
319
|
+
root: opts.root, flow, runId, catalogue, resumeAttempt,
|
|
175
320
|
});
|
|
176
321
|
if (!result) { sendText(res, 404, 'no such run'); return; }
|
|
177
322
|
send(200, result);
|
|
@@ -187,7 +332,8 @@ export function handleRequest(req, res, opts) {
|
|
|
187
332
|
* header). Resolves once actually listening; rejects on a bind error
|
|
188
333
|
* (including `EADDRINUSE`) with a `.port` field on the error for the
|
|
189
334
|
* caller's message.
|
|
190
|
-
* @param {{ port?: number, root: string }} opts
|
|
335
|
+
* @param {{ port?: number, root: string, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
|
|
336
|
+
* `resume` is for tests only (a fake env/bin, a short retry window); the CLI passes none.
|
|
191
337
|
* @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
|
|
192
338
|
*/
|
|
193
339
|
export function createPanelServer(opts) {
|
|
@@ -196,6 +342,11 @@ export function createPanelServer(opts) {
|
|
|
196
342
|
}
|
|
197
343
|
const requestedPort = opts.port ?? DEFAULT_PORT;
|
|
198
344
|
const { root } = opts;
|
|
345
|
+
// One resumer per server: the one owner of every run's resume-attempt record.
|
|
346
|
+
const resumer = createResumer({ root, ...opts.resume });
|
|
347
|
+
// One token per server process, made once, held only here and in the served
|
|
348
|
+
// page — never logged, never in any /api response.
|
|
349
|
+
const token = randomBytes(32).toString('hex');
|
|
199
350
|
return new Promise((resolve, reject) => {
|
|
200
351
|
// Bound port is resolved from the live socket (`server.address().port`)
|
|
201
352
|
// once listening starts, not the requested value — this is what makes
|
|
@@ -205,7 +356,9 @@ export function createPanelServer(opts) {
|
|
|
205
356
|
let boundPort = requestedPort;
|
|
206
357
|
const server = createServer((req, res) => {
|
|
207
358
|
try {
|
|
208
|
-
handleRequest(req, res, {
|
|
359
|
+
handleRequest(req, res, {
|
|
360
|
+
root, port: boundPort, token, resumer,
|
|
361
|
+
});
|
|
209
362
|
} catch (e) {
|
|
210
363
|
sendText(res, 500, `internal error: ${/** @type {Error} */ (e).message}`);
|
|
211
364
|
}
|
|
@@ -251,7 +404,7 @@ export async function panelMain(argv, ctx) {
|
|
|
251
404
|
}
|
|
252
405
|
try {
|
|
253
406
|
const { port: boundPort } = await createPanelServer({ port, root });
|
|
254
|
-
ctx.out(`fwdloop panel —
|
|
407
|
+
ctx.out(`fwdloop panel — http://127.0.0.1:${boundPort} (root: ${root}) (Ctrl-C to stop)`);
|
|
255
408
|
// never resolves on its own — the process stays up until killed, same
|
|
256
409
|
// shape any other long-running dev server takes.
|
|
257
410
|
await new Promise(() => {});
|