unfold-deploy 0.0.0-stage → 0.1.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.
@@ -0,0 +1,200 @@
1
+ const MAX_EVIDENCE = 40;
2
+ const DEFAULT_NOTES = {
3
+ interrupted: 'You pressed Ctrl+C while this stage was in progress, so its outcome was never reported.',
4
+ unverified: "This run's output never confirmed this stage.",
5
+ };
6
+ /**
7
+ * Pure reducer from RunEvents to FlowState plus the log. Rules:
8
+ * - Stages only move forward on explicit signals from the provider parser; a later
9
+ * stage starting never implies an earlier one finished.
10
+ * - When the run ends, anything not confirmed becomes `unverified` (or `failed` for
11
+ * the stage the failure is attributed to).
12
+ */
13
+ export class FlowReducer {
14
+ state;
15
+ logs = new Map();
16
+ notes = DEFAULT_NOTES;
17
+ apply(event) {
18
+ if (event.type === 'run.started') {
19
+ this.notes = { ...DEFAULT_NOTES, ...event.notes };
20
+ this.logs.clear();
21
+ this.state = {
22
+ runId: event.runId,
23
+ provider: event.provider,
24
+ title: event.title,
25
+ command: event.command,
26
+ cwd: event.cwd,
27
+ mode: event.mode,
28
+ startedAt: event.at,
29
+ outcome: 'running',
30
+ exitCode: null,
31
+ exitSignal: null,
32
+ stages: event.stages.map((d) => ({ ...d, status: 'pending', evidence: [] })),
33
+ facts: [],
34
+ errors: [],
35
+ lineCount: 0,
36
+ };
37
+ return;
38
+ }
39
+ const s = this.state;
40
+ if (!s)
41
+ return;
42
+ switch (event.type) {
43
+ case 'log':
44
+ this.logs.set(event.line.seq, event.line);
45
+ s.lineCount = this.logs.size;
46
+ return;
47
+ case 'signal':
48
+ this.signal(s, event);
49
+ return;
50
+ case 'run.ended':
51
+ this.end(s, event);
52
+ return;
53
+ case 'fix.ready':
54
+ s.fix = event.fix;
55
+ return;
56
+ }
57
+ }
58
+ stage(s, id) {
59
+ return id ? s.stages.find((st) => st.id === id) : undefined;
60
+ }
61
+ addEvidence(st, seq, at, note) {
62
+ const text = this.logs.get(seq)?.text ?? '';
63
+ const existing = st.evidence.find((e) => e.seq === seq);
64
+ if (existing) {
65
+ // Same line redrawn (e.g. a progress bar): keep the latest version.
66
+ existing.text = text;
67
+ existing.note = note;
68
+ existing.at = at;
69
+ return;
70
+ }
71
+ st.evidence.push({ seq, at, text, note });
72
+ if (st.evidence.length > MAX_EVIDENCE)
73
+ st.evidence.splice(1, 1); // keep the first line
74
+ }
75
+ signal(s, e) {
76
+ const sig = e.signal;
77
+ switch (sig.kind) {
78
+ case 'stage': {
79
+ const st = this.stage(s, sig.stage);
80
+ if (!st)
81
+ return;
82
+ if (sig.status === 'active') {
83
+ if (st.status === 'pending' || st.status === 'active') {
84
+ st.status = 'active';
85
+ st.startedAt ??= e.at;
86
+ st.note = sig.note;
87
+ }
88
+ }
89
+ else if (sig.status === 'confirmed') {
90
+ if (st.status !== 'failed') {
91
+ st.status = 'confirmed';
92
+ st.startedAt ??= e.at;
93
+ st.endedAt = e.at;
94
+ st.note = sig.note;
95
+ }
96
+ }
97
+ else if (st.status !== 'confirmed') {
98
+ st.status = 'failed';
99
+ st.endedAt = e.at;
100
+ st.note = sig.note;
101
+ s.failedStage = st.id;
102
+ }
103
+ this.addEvidence(st, e.seq, e.at, sig.note);
104
+ this.updateLastConfirmed(s);
105
+ return;
106
+ }
107
+ case 'evidence': {
108
+ const st = this.stage(s, sig.stage);
109
+ if (st)
110
+ this.addEvidence(st, e.seq, e.at, sig.note);
111
+ return;
112
+ }
113
+ case 'fact': {
114
+ const existing = s.facts.find((f) => f.key === sig.key);
115
+ const fact = { key: sig.key, label: sig.label, value: sig.value, stage: sig.stage, href: sig.href, seq: e.seq };
116
+ if (existing)
117
+ Object.assign(existing, fact);
118
+ else
119
+ s.facts.push(fact);
120
+ return;
121
+ }
122
+ case 'error': {
123
+ const info = { severity: sig.severity, priority: sig.priority, stage: sig.stage, message: sig.message, seq: e.seq, at: e.at };
124
+ if (!s.errors.some((x) => x.seq === e.seq && x.message === sig.message))
125
+ s.errors.push(info);
126
+ if (sig.severity === 'fatal') {
127
+ const st = this.stage(s, sig.stage) ?? this.currentStage(s);
128
+ if (st && st.status !== 'confirmed') {
129
+ st.status = 'failed';
130
+ st.endedAt = e.at;
131
+ st.note = sig.message;
132
+ s.failedStage = st.id;
133
+ info.stage = st.id;
134
+ this.addEvidence(st, e.seq, e.at, 'Error reported here');
135
+ }
136
+ }
137
+ return;
138
+ }
139
+ }
140
+ }
141
+ /** The stage work is most plausibly happening in right now. */
142
+ currentStage(s) {
143
+ const active = [...s.stages].reverse().find((st) => st.status === 'active');
144
+ if (active)
145
+ return active;
146
+ const lastIdx = s.stages.findLastIndex((st) => st.status === 'confirmed');
147
+ return s.stages[lastIdx + 1] ?? s.stages[lastIdx];
148
+ }
149
+ updateLastConfirmed(s) {
150
+ const idx = s.stages.findLastIndex((st) => st.status === 'confirmed');
151
+ s.lastConfirmed = idx >= 0 ? s.stages[idx].id : undefined;
152
+ }
153
+ end(s, e) {
154
+ s.endedAt = e.at;
155
+ s.exitCode = e.exitCode;
156
+ s.exitSignal = e.signal;
157
+ const failed = e.exitCode !== 0 || e.signal !== null;
158
+ const finished = s.stages.at(-1)?.status === 'confirmed';
159
+ // Ctrl+C after the workflow already finished successfully does not change the outcome.
160
+ if (e.interrupted && (failed || !finished)) {
161
+ s.outcome = 'interrupted';
162
+ }
163
+ else if (failed) {
164
+ s.outcome = 'failure';
165
+ if (!s.failedStage) {
166
+ const st = this.stage(s, s.errors.find((x) => x.severity === 'fatal')?.stage) ?? this.currentStage(s);
167
+ if (st && st.status !== 'confirmed') {
168
+ st.status = 'failed';
169
+ st.endedAt = e.at;
170
+ st.note ??= `The command exited with code ${e.exitCode ?? e.signal} during this stage.`;
171
+ s.failedStage = st.id;
172
+ }
173
+ }
174
+ }
175
+ else {
176
+ s.outcome = 'success';
177
+ }
178
+ // Index of the furthest stage the run is known to have reached.
179
+ const reached = s.stages.findLastIndex((st) => st.status !== 'pending');
180
+ s.stages.forEach((st, i) => {
181
+ if (st.status === 'active') {
182
+ st.status = 'unverified';
183
+ st.note = s.outcome === 'interrupted' ? this.notes.interrupted : this.notes.unverified;
184
+ }
185
+ else if (st.status === 'pending') {
186
+ st.status = 'unverified';
187
+ // A stage skipped over by later ones: prefer the parser's own explanation, if it gave one.
188
+ if (i < reached)
189
+ st.note = st.evidence.at(-1)?.note ?? this.notes.unverified;
190
+ else if (s.outcome === 'interrupted')
191
+ st.note = 'The run stopped before this stage was observed.';
192
+ else if (s.outcome === 'failure')
193
+ st.note = 'Not reached: the run failed before this stage.';
194
+ else
195
+ st.note = this.notes.unverified;
196
+ }
197
+ });
198
+ this.updateLastConfirmed(s);
199
+ }
200
+ }
@@ -0,0 +1,196 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { chmodSync, existsSync, statSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { delimiter, dirname, isAbsolute, join } from 'node:path';
5
+ import { onRestore } from '../tui/restore.js';
6
+ const require = createRequire(import.meta.url);
7
+ /** Finds an executable on PATH without running a shell. */
8
+ export function which(bin) {
9
+ if (isAbsolute(bin) || bin.includes('/'))
10
+ return existsSync(bin) ? bin : undefined;
11
+ const exts = process.platform === 'win32' ? ['.cmd', '.exe', ''] : [''];
12
+ for (const dir of (process.env.PATH ?? '').split(delimiter)) {
13
+ for (const ext of exts) {
14
+ const p = join(dir, bin + ext);
15
+ try {
16
+ if (statSync(p).isFile())
17
+ return p;
18
+ }
19
+ catch {
20
+ // not here
21
+ }
22
+ }
23
+ }
24
+ return undefined;
25
+ }
26
+ /** `UNFOLD_TERMINAL=script|pipe` forces a fallback (for troubleshooting and tests). */
27
+ const forced = () => process.env.UNFOLD_TERMINAL;
28
+ function loadPty() {
29
+ if (forced() === 'script' || forced() === 'pipe')
30
+ return undefined;
31
+ try {
32
+ const pty = require('node-pty');
33
+ // node-pty 1.1.0 prebuilds can ship spawn-helper without its execute bit.
34
+ const root = dirname(require.resolve('node-pty/package.json'));
35
+ const helper = join(root, 'prebuilds', `${process.platform}-${process.arch}`, 'spawn-helper');
36
+ if (existsSync(helper) && !(statSync(helper).mode & 0o111))
37
+ chmodSync(helper, 0o755);
38
+ return pty;
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ /**
45
+ * Runs the command attached to the user's terminal. With node-pty the child sees a
46
+ * real TTY, so prompts, colors and spinners behave exactly as they would without
47
+ * Unfold; all keystrokes (including Ctrl+C) are forwarded to it.
48
+ *
49
+ * The child inherits the environment so it can use the existing login and project
50
+ * config. Unfold never records the environment.
51
+ */
52
+ export function launch(opts) {
53
+ const pty = loadPty();
54
+ if (pty)
55
+ return launchPty(pty, opts);
56
+ if (terminalMode() === 'script')
57
+ return launchScript(opts);
58
+ return launchPiped(opts);
59
+ }
60
+ /**
61
+ * How the wrapped command will be attached to the terminal:
62
+ * - `pty`: node-pty, full control (live panel supported)
63
+ * - `script`: the system `script` command gives the child a real TTY; used when node-pty
64
+ * isn't installed (e.g. Linux without build tools). The panel is off because the child
65
+ * sizes itself to the whole terminal.
66
+ * - `pipe`: no TTY for the child; prompts and spinners may behave differently.
67
+ */
68
+ export function terminalMode() {
69
+ if (loadPty())
70
+ return 'pty';
71
+ if (forced() !== 'pipe' && process.platform !== 'win32' && process.stdin.isTTY && which('script'))
72
+ return 'script';
73
+ return 'pipe';
74
+ }
75
+ const shQuote = (s) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
76
+ function launchScript({ bin, args, cwd, term: io, onOutput }) {
77
+ // BSD/macOS: script -q file cmd args… util-linux: script -qefc "cmd args…" file
78
+ const scriptArgs = process.platform === 'darwin' || process.platform.endsWith('bsd')
79
+ ? ['-q', '/dev/null', bin, ...args]
80
+ : ['-qefc', [bin, ...args].map(shQuote).join(' '), '/dev/null'];
81
+ const child = spawn('script', scriptArgs, { cwd, env: process.env, stdio: ['inherit', 'pipe', 'inherit'] });
82
+ let interrupted = false;
83
+ const onSignal = (sig) => {
84
+ interrupted = true;
85
+ child.kill(sig);
86
+ };
87
+ process.on('SIGINT', onSignal);
88
+ process.on('SIGTERM', onSignal);
89
+ // `script` puts the terminal in raw mode itself; make sure it's undone if we die first.
90
+ const release = onRestore(() => process.stdin.isTTY && process.stdin.setRawMode(false));
91
+ child.stdout.on('data', (d) => {
92
+ const text = d.toString('utf8');
93
+ io.write(text);
94
+ onOutput(text);
95
+ });
96
+ return new Promise((resolve) => {
97
+ child.on('error', (err) => onOutput(`Error: ${err.message}\n`));
98
+ child.on('close', (code, signal) => {
99
+ release();
100
+ process.off('SIGINT', onSignal);
101
+ process.off('SIGTERM', onSignal);
102
+ // Ctrl+C reaches the child through the TTY, so infer it from the exit status.
103
+ resolve({ exitCode: code, signal, interrupted: interrupted || code === 130 || signal === 'SIGINT' });
104
+ });
105
+ });
106
+ }
107
+ function launchPty(pty, { bin, args, cwd, term: io, onOutput }) {
108
+ const stdin = process.stdin;
109
+ const stdout = process.stdout;
110
+ const term = pty.spawn(bin, args, {
111
+ name: process.env.TERM || 'xterm-256color',
112
+ cols: stdout.columns || 100,
113
+ rows: io.rows(),
114
+ cwd,
115
+ env: process.env,
116
+ });
117
+ let interrupted = false;
118
+ const onInput = (data) => {
119
+ if (data.includes(0x03))
120
+ interrupted = true;
121
+ term.write(data.toString('utf8'));
122
+ };
123
+ let alive = true;
124
+ const onResize = () => alive && term.resize(stdout.columns || 100, io.rows());
125
+ io.onRowsChange(onResize);
126
+ // Signals that reach Unfold directly (not via the TTY) are passed on.
127
+ const onSignal = (sig) => {
128
+ interrupted = true;
129
+ try {
130
+ term.kill(sig);
131
+ }
132
+ catch {
133
+ // already gone
134
+ }
135
+ };
136
+ if (stdin.isTTY)
137
+ stdin.setRawMode(true);
138
+ const release = onRestore(() => stdin.isTTY && stdin.setRawMode(false));
139
+ stdin.resume();
140
+ stdin.on('data', onInput);
141
+ stdout.on('resize', onResize);
142
+ process.on('SIGINT', onSignal);
143
+ process.on('SIGTERM', onSignal);
144
+ term.onData((d) => {
145
+ io.write(d);
146
+ onOutput(d);
147
+ });
148
+ return new Promise((resolve) => {
149
+ term.onExit(({ exitCode, signal }) => {
150
+ alive = false;
151
+ release();
152
+ stdin.off('data', onInput);
153
+ if (stdin.isTTY)
154
+ stdin.setRawMode(false);
155
+ stdin.pause();
156
+ stdout.off('resize', onResize);
157
+ process.off('SIGINT', onSignal);
158
+ process.off('SIGTERM', onSignal);
159
+ const sig = signal ? signalName(signal) : null;
160
+ resolve({ exitCode: sig ? null : exitCode, signal: sig, interrupted });
161
+ });
162
+ });
163
+ }
164
+ function launchPiped({ bin, args, cwd, term: io, onOutput }) {
165
+ process.stderr.write('[unfold] No pseudo-terminal available (node-pty is not installed); prompts and spinners may look different.\n');
166
+ const child = spawn(bin, args, { cwd, env: process.env, stdio: ['inherit', 'pipe', 'pipe'] });
167
+ let interrupted = false;
168
+ const onSignal = (sig) => {
169
+ interrupted = true;
170
+ child.kill(sig);
171
+ };
172
+ process.on('SIGINT', onSignal);
173
+ process.on('SIGTERM', onSignal);
174
+ child.stdout.on('data', (d) => {
175
+ io.write(d.toString('utf8'));
176
+ onOutput(d.toString('utf8'));
177
+ });
178
+ child.stderr.on('data', (d) => {
179
+ process.stderr.write(d);
180
+ onOutput(d.toString('utf8'));
181
+ });
182
+ return new Promise((resolve) => {
183
+ child.on('error', (err) => {
184
+ onOutput(`Error: ${err.message}\n`);
185
+ });
186
+ child.on('close', (code, signal) => {
187
+ process.off('SIGINT', onSignal);
188
+ process.off('SIGTERM', onSignal);
189
+ resolve({ exitCode: code, signal, interrupted });
190
+ });
191
+ });
192
+ }
193
+ function signalName(n) {
194
+ const names = { 1: 'SIGHUP', 2: 'SIGINT', 9: 'SIGKILL', 15: 'SIGTERM' };
195
+ return names[n] ?? `signal ${n}`;
196
+ }
@@ -0,0 +1,3 @@
1
+ // Shared, provider-agnostic event model. Providers (vercel today, gcloud later)
2
+ // only produce `Signal`s from log lines; everything else lives here.
3
+ export {};
@@ -0,0 +1,79 @@
1
+ // Redacts secrets from captured output before it is displayed or saved.
2
+ // Pattern based, plus exact values of secret-looking environment variables.
3
+ // Env values are only held in memory for matching; they are never stored.
4
+ const R = '[REDACTED]';
5
+ const SECRET_NAME = /(SECRET|TOKEN|PASSWORD|PASSWD|PASSPHRASE|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CREDENTIAL|AUTH|COOKIE|SESSION|DSN|DATABASE_URL|CONNECTION_STRING|WEBHOOK|SIGNING)/i;
6
+ const TOKEN_PATTERNS = [
7
+ /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b/g, // GitHub
8
+ /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
9
+ /\bglpat-[A-Za-z0-9_-]{20,}\b/g, // GitLab
10
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, // AWS access key id
11
+ /\bxox[abposr]-[A-Za-z0-9-]{10,}\b/g, // Slack
12
+ /\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{10,}\b/g, // Stripe
13
+ /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/g, // OpenAI / Anthropic style
14
+ /\bAIza[0-9A-Za-z_-]{35}\b/g, // Google API key
15
+ /\bnpm_[A-Za-z0-9]{36}\b/g, // npm
16
+ /\b(?:vcp|vck|vci|vca|vcr)_[A-Za-z0-9]{20,}\b/g, // Vercel-style prefixed tokens
17
+ /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, // JWT
18
+ ];
19
+ const KEY_VALUE = new RegExp(String.raw `\b([A-Za-z0-9_.-]*` + SECRET_NAME.source.replace(/^\(/, '(?:') + String.raw `[A-Za-z0-9_.-]*)(\s*[=:]\s*)(["']?)([^\s"']{3,})\3`, 'gi');
20
+ export class Redactor {
21
+ envSecrets = [];
22
+ inPrivateKey = false;
23
+ constructor(opts = {}) {
24
+ for (const [name, value] of Object.entries(opts.env ?? {})) {
25
+ if (value && value.length >= 8 && SECRET_NAME.test(name))
26
+ this.envSecrets.push({ name, value });
27
+ }
28
+ // Longest first so overlapping values are fully replaced.
29
+ this.envSecrets.sort((a, b) => b.value.length - a.value.length);
30
+ }
31
+ line(input) {
32
+ if (/-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(input)) {
33
+ this.inPrivateKey = !/-----END [A-Z ]*PRIVATE KEY-----/.test(input);
34
+ return '-----BEGIN PRIVATE KEY----- ' + R;
35
+ }
36
+ if (this.inPrivateKey) {
37
+ if (/-----END [A-Z ]*PRIVATE KEY-----/.test(input))
38
+ this.inPrivateKey = false;
39
+ return R;
40
+ }
41
+ let out = input;
42
+ for (const { name, value } of this.envSecrets) {
43
+ if (out.includes(value))
44
+ out = out.split(value).join(`[REDACTED:${name}]`);
45
+ }
46
+ // user:password@host in URLs
47
+ out = out.replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s:@/]+):([^\s@/]+)@/gi, `$1$2:${R}@`);
48
+ // Authorization headers / bearer tokens
49
+ out = out.replace(/\b(Bearer|Basic|token)\s+([A-Za-z0-9._~+/=-]{12,})/g, `$1 ${R}`);
50
+ // CLI flags carrying tokens
51
+ out = out.replace(/(--token[=\s]+|\s-t\s+)(\S+)/g, `$1${R}`);
52
+ for (const re of TOKEN_PATTERNS)
53
+ out = out.replace(re, R);
54
+ out = out.replace(KEY_VALUE, (m, key, sep, q, val) => val.startsWith('[REDACTED') || /^(Bearer|Basic|token)$/i.test(val) ? m : `${key}${sep}${q}${R}${q}`);
55
+ return out;
56
+ }
57
+ }
58
+ /** Redacts command-line args before they are shown (token flags, env values). */
59
+ export function redactArgs(args) {
60
+ const out = [];
61
+ let hideNext = 'none';
62
+ for (const arg of args) {
63
+ if (hideNext !== 'none') {
64
+ out.push(hideNext === 'value' && arg.includes('=') ? `${arg.split('=')[0]}=${R}` : R);
65
+ hideNext = 'none';
66
+ continue;
67
+ }
68
+ if (arg === '--token' || arg === '-t')
69
+ hideNext = 'all';
70
+ else if (['--env', '-e', '--build-env', '-b'].includes(arg))
71
+ hideNext = 'value';
72
+ const m = /^(--token|--env|--build-env)=(.*)$/.exec(arg);
73
+ if (m)
74
+ out.push(m[1] === '--token' ? `--token=${R}` : `${m[1]}=${(m[2] ?? '').split('=')[0]}=${R}`);
75
+ else
76
+ out.push(arg);
77
+ }
78
+ return out;
79
+ }
@@ -0,0 +1,109 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { createServer } from 'node:http';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ const UI_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'ui');
6
+ const STATIC = {
7
+ '/': ['index.html', 'text/html; charset=utf-8'],
8
+ '/app.js': ['app.js', 'text/javascript; charset=utf-8'],
9
+ '/styles.css': ['styles.css', 'text/css; charset=utf-8'],
10
+ };
11
+ /** Serves the UI and streams state over SSE. Binds to loopback only. */
12
+ export async function startServer(session, port = Number(process.env.UNFOLD_PORT) || 4317) {
13
+ const clients = new Set();
14
+ let clientWaiters = [];
15
+ let pendingLogs = new Map();
16
+ let flushTimer;
17
+ let actualPort = port;
18
+ const send = (res, type, data) => res.write(`event: ${type}\ndata: ${JSON.stringify(data)}\n\n`);
19
+ const broadcast = (type, data) => clients.forEach((c) => send(c, type, data));
20
+ const flush = () => {
21
+ flushTimer = undefined;
22
+ if (pendingLogs.size)
23
+ broadcast('logs', [...pendingLogs.values()]);
24
+ pendingLogs = new Map();
25
+ broadcast('state', session.state);
26
+ };
27
+ session.subscribe((event) => {
28
+ if (event.type === 'log')
29
+ pendingLogs.set(event.line.seq, event.line);
30
+ if (event.type === 'run.started' || event.type === 'run.ended' || event.type === 'fix.ready') {
31
+ if (flushTimer)
32
+ clearTimeout(flushTimer);
33
+ if (event.type === 'run.started')
34
+ broadcast('reset', null);
35
+ flush();
36
+ }
37
+ else {
38
+ flushTimer ??= setTimeout(flush, 60);
39
+ }
40
+ });
41
+ const handler = async (req, res) => {
42
+ // Reject requests addressed to other hostnames (DNS-rebinding protection).
43
+ const host = (req.headers.host ?? '').replace(/:\d+$/, '');
44
+ if (host !== '127.0.0.1' && host !== 'localhost') {
45
+ res.writeHead(403).end('Forbidden');
46
+ return;
47
+ }
48
+ const path = (req.url ?? '/').split('?')[0];
49
+ if (path === '/api/events') {
50
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' });
51
+ clients.add(res);
52
+ send(res, 'snapshot', { state: session.state, logs: session.logs });
53
+ clientWaiters.forEach((w) => w());
54
+ clientWaiters = [];
55
+ req.on('close', () => clients.delete(res));
56
+ return;
57
+ }
58
+ if (path === '/api/state') {
59
+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ state: session.state, logs: session.logs }));
60
+ return;
61
+ }
62
+ const file = STATIC[path];
63
+ if (req.method === 'GET' && file) {
64
+ try {
65
+ const body = await readFile(join(UI_DIR, file[0]));
66
+ res.writeHead(200, { 'content-type': file[1], 'cache-control': 'no-store' }).end(body);
67
+ }
68
+ catch {
69
+ res.writeHead(500).end('UI assets missing. Run `npm run build`.');
70
+ }
71
+ return;
72
+ }
73
+ res.writeHead(404).end('Not found');
74
+ };
75
+ const server = createServer((req, res) => void handler(req, res));
76
+ await new Promise((resolve, reject) => {
77
+ const tryListen = (p, attempts) => {
78
+ server.once('error', (err) => {
79
+ if (err.code === 'EADDRINUSE' && attempts > 0)
80
+ tryListen(p === 0 ? 0 : p + 1, attempts - 1);
81
+ else
82
+ reject(err);
83
+ });
84
+ server.listen(p, '127.0.0.1', () => {
85
+ actualPort = server.address().port;
86
+ resolve();
87
+ });
88
+ };
89
+ tryListen(port, 20);
90
+ });
91
+ return {
92
+ url: `http://127.0.0.1:${actualPort}/`,
93
+ waitForClient(ms) {
94
+ if (clients.size)
95
+ return Promise.resolve(true);
96
+ return new Promise((resolve) => {
97
+ const t = setTimeout(() => resolve(false), ms);
98
+ clientWaiters.push(() => {
99
+ clearTimeout(t);
100
+ resolve(true);
101
+ });
102
+ });
103
+ },
104
+ close() {
105
+ clients.forEach((c) => c.end());
106
+ return new Promise((resolve) => server.close(() => resolve()));
107
+ },
108
+ };
109
+ }