worktrust 0.10.38 → 0.11.1
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/LICENSE +43 -18
- package/README.md +55 -2
- package/SECURITY.md +25 -0
- package/engine-release.json +1 -1
- package/log-session.mjs +6 -6
- package/package-release.json +1 -1
- package/package.json +43 -2
- package/remote-adapter-claude-code.mjs +113 -0
- package/remote-adapter-codex.mjs +159 -0
- package/remote-adapter-terminal.mjs +248 -0
- package/remote-approval-bridge.mjs +145 -0
- package/remote-approvals.mjs +134 -0
- package/remote-attachments.mjs +129 -0
- package/remote-cdp.mjs +60 -0
- package/remote-changes.mjs +94 -0
- package/remote-claude-events.mjs +212 -0
- package/remote-claude-progress.mjs +328 -0
- package/remote-cli.mjs +330 -0
- package/remote-coalesce.mjs +40 -0
- package/remote-codex-events.mjs +153 -0
- package/remote-daemon.mjs +220 -0
- package/remote-inventory.mjs +143 -0
- package/remote-journal.mjs +155 -0
- package/remote-live-preview.mjs +205 -0
- package/remote-pairing.mjs +104 -0
- package/remote-pipeline-config.mjs +177 -0
- package/remote-pipeline-parsers.mjs +121 -0
- package/remote-pipeline.mjs +234 -0
- package/remote-policy.mjs +199 -0
- package/remote-preview.mjs +146 -0
- package/remote-projects.mjs +87 -0
- package/remote-protocol.mjs +4010 -0
- package/remote-qr.mjs +175 -0
- package/remote-release-plans.mjs +88 -0
- package/remote-releases.mjs +297 -0
- package/remote-run.mjs +189 -0
- package/remote-screen-approvals.mjs +79 -0
- package/remote-screen-push.mjs +76 -0
- package/remote-screen-states.mjs +113 -0
- package/remote-service.mjs +101 -0
- package/remote-session-list.mjs +48 -0
- package/remote-sessions.mjs +337 -0
- package/remote-steered.mjs +114 -0
- package/remote-steering.mjs +97 -0
- package/remote-store.mjs +124 -0
- package/remote-terminal-cli.mjs +85 -0
- package/remote-terminal-sessions.mjs +291 -0
- package/remote-transport.mjs +88 -0
- package/worktrust.mjs +11 -4
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A RELEASE'S PIPELINE, RUN ON THE COMPUTER (owner, 2026-11-07; docs/remote-agents/PROTOCOL.md "Pipelines").
|
|
3
|
+
*
|
|
4
|
+
* The phone starts or cancels a pipeline the computer already has: the stages of the project's reviewed
|
|
5
|
+
* `.worktrust/pipeline.json` (remote-pipeline-config.mjs). Stages run one after another, each command checked against the
|
|
6
|
+
* allowlist again right before it runs and spawned without a shell, in its own process group (so a cancel or a timeout
|
|
7
|
+
* ends everything it started), with the person's environment minus every WORKTRUST_ variable and stdin closed. Output goes
|
|
8
|
+
* to a local log (~/.worktrust/remote/pipelines/<run>/<stage>.log, mode 0600) for the person to read at the desk, and
|
|
9
|
+
* never to the phone: the phone gets the stage's state and what its parser read. A deploy or publish stage is never run:
|
|
10
|
+
* it is `at_desk`.
|
|
11
|
+
*
|
|
12
|
+
* At most once, as with commands: a run is journaled before its first stage starts, and a run a stopped daemon left
|
|
13
|
+
* running is closed `failed` / `interrupted` by the next daemon and never run again. Each run is marked in the steered
|
|
14
|
+
* ledger as non-agent work (`steered: "pipeline"`), which the hour readers skip: a pipeline is never Passport hours.
|
|
15
|
+
*/
|
|
16
|
+
import { spawn } from "node:child_process";
|
|
17
|
+
import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, writeSync, constants } from "node:fs";
|
|
18
|
+
import { join, sep } from "node:path";
|
|
19
|
+
import * as P from "./remote-protocol.mjs";
|
|
20
|
+
import { allowCommand, namedFiles, parsePipelineConfig, PIPELINE_FILE, reviewHash } from "./remote-pipeline-config.mjs";
|
|
21
|
+
import { createTapCounter, findingsFail, readReport } from "./remote-pipeline-parsers.mjs";
|
|
22
|
+
import { createCoalescer } from "./remote-sessions.mjs";
|
|
23
|
+
|
|
24
|
+
const MAX_KEEP = 256 * 1024; // the tail of stdout a parser reads when the stage names no report file
|
|
25
|
+
const MAX_REPORT = 16 * 1024 * 1024;
|
|
26
|
+
export const MAX_PIPELINES = 2;
|
|
27
|
+
const HISTORY = 40;
|
|
28
|
+
|
|
29
|
+
const inside = (root, path) => path === root || path.startsWith(root + sep);
|
|
30
|
+
|
|
31
|
+
/** A project file read safely: inside the project after every symlink, not a symlink itself, bounded. */
|
|
32
|
+
export function readProjectFile(projectPath, relative, max) {
|
|
33
|
+
try {
|
|
34
|
+
const root = realpathSync(projectPath);
|
|
35
|
+
const file = join(root, relative);
|
|
36
|
+
if (!existsSync(file) || lstatSync(file).isSymbolicLink() || !inside(root, realpathSync(file))) return null;
|
|
37
|
+
const text = readFileSync(file);
|
|
38
|
+
return text.length > max ? null : text.toString("utf8");
|
|
39
|
+
} catch { return null; }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const scriptsOf = (projectPath) => { try { return JSON.parse(readProjectFile(projectPath, "package.json", 1_048_576) ?? "null")?.scripts ?? null; } catch { return null; } };
|
|
43
|
+
|
|
44
|
+
/** The project-side inputs of reviewHash: its .npmrc and the files its node stages run. */
|
|
45
|
+
export function reviewExtras(projectPath, text, scripts) {
|
|
46
|
+
return { npmrc: readProjectFile(projectPath, ".npmrc", 65_536), files: Object.fromEntries(namedFiles(text, scripts).map((f) => [f, readProjectFile(projectPath, f, 4 * 1024 * 1024)])) };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The hash `worktrust remote pipeline review` pins, read from the project as it stands now. */
|
|
50
|
+
export function projectReviewHash(project) {
|
|
51
|
+
const text = readProjectFile(project.path, PIPELINE_FILE, 65_536);
|
|
52
|
+
if (text === null) return null;
|
|
53
|
+
const scripts = scriptsOf(project.path);
|
|
54
|
+
return reviewHash(text, scripts, reviewExtras(project.path, text, scripts));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** absent | unreviewed | reviewed, and the parsed config when it may run. */
|
|
58
|
+
export function pipelineState(project, reviews) {
|
|
59
|
+
const text = readProjectFile(project.path, PIPELINE_FILE, 65_536);
|
|
60
|
+
if (text === null) return { state: "absent", config: null };
|
|
61
|
+
const scripts = scriptsOf(project.path);
|
|
62
|
+
const parsed = parsePipelineConfig(text, scripts);
|
|
63
|
+
if (!parsed.ok) return { state: "unreviewed", config: null, detail: parsed.detail };
|
|
64
|
+
const hash = reviewHash(text, scripts, reviewExtras(project.path, text, scripts));
|
|
65
|
+
return reviews[project.project_id]?.sha256 === hash ? { state: "reviewed", config: parsed.config, scripts, hash } : { state: "unreviewed", config: null };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function createPipelines(ctx) {
|
|
69
|
+
// ctx: { journal, now, random, emit, projects(), reviews(), log, logDir, markLedger(record), env(prepend), onEnded(run), spawnImpl? }
|
|
70
|
+
const runs = new Map(); // live runs: id -> { body, child, cancelled }
|
|
71
|
+
const go = ctx.spawnImpl ?? spawn;
|
|
72
|
+
const coalesce = createCoalescer({ now: ctx.now });
|
|
73
|
+
|
|
74
|
+
const history = (projectId, stageId) => ctx.journal.pipelines().filter((p) => p.project_id === projectId && p.state === "passed").slice(-HISTORY)
|
|
75
|
+
.flatMap((p) => (stageId === null ? [(p.ended_at - p.started_at) / 1000] : p.stages.filter((s) => s.stage_id === stageId && s.state === "passed" && s.duration_ms !== undefined).map((s) => s.duration_ms / 1000)));
|
|
76
|
+
const etaFor = (durations, startedAt) => { const e = P.etaForDisplay(P.etaFromHistory(durations, Math.max(0, (ctx.now() - startedAt) / 1000))); return e.kind === "estimate" ? e : undefined; };
|
|
77
|
+
|
|
78
|
+
/** History's estimate where etaForDisplay keeps one, on live stages and a live run only; every other ETA dropped. */
|
|
79
|
+
function withEtas(body) {
|
|
80
|
+
const final = P.isFinalPipelineState(body.state);
|
|
81
|
+
const stages = body.stages.map((s) => {
|
|
82
|
+
const { eta: _drop, ...rest } = s;
|
|
83
|
+
if (final || (s.state !== "running" && s.state !== "queued")) return rest;
|
|
84
|
+
const eta = etaFor(history(body.project_id, s.stage_id), s.started_at ?? ctx.now());
|
|
85
|
+
return eta ? { ...rest, eta } : rest;
|
|
86
|
+
});
|
|
87
|
+
const { eta: _old, ...top } = body;
|
|
88
|
+
const eta = final ? undefined : etaFor(history(body.project_id, null), body.started_at);
|
|
89
|
+
return { ...top, stages, ...(eta ? { eta } : {}) };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Journal first, then the phone; a live count is coalesced to one per two seconds per run. */
|
|
93
|
+
function publish(run, { live = false } = {}) {
|
|
94
|
+
run.body = withEtas(run.body);
|
|
95
|
+
const shaped = P.validateEventBody("pipeline.updated", run.body);
|
|
96
|
+
if (!shaped.ok) { ctx.log("pipeline_refused", { detail: shaped.code }); return false; }
|
|
97
|
+
ctx.journal.recordPipeline(run.body);
|
|
98
|
+
const send = () => ctx.emit(null, "pipeline.updated", run.body);
|
|
99
|
+
if (live) coalesce.offer(run.body.pipeline_run_id, send); else coalesce.now(run.body.pipeline_run_id, send);
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** A stage an earlier daemon left running: its process group is ended when its command line is still that stage's. */
|
|
104
|
+
function reap(runId) {
|
|
105
|
+
const held = ctx.journal.pipelinePid?.(runId);
|
|
106
|
+
if (!held || process.platform === "win32" || !Number.isSafeInteger(held.pid) || held.pid <= 1) return false;
|
|
107
|
+
const command = ctx.commandOf?.(held.pid) ?? ""; // `ps` lives in remote-run.mjs: this file spawns stages only
|
|
108
|
+
if (!command.includes(held.file)) return false;
|
|
109
|
+
try { (ctx.kill ?? process.kill.bind(process))(-held.pid, "SIGTERM"); return true; } catch { return false; }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const setStage = (run, id, patch) => { run.body = { ...run.body, stages: run.body.stages.map((s) => (s.stage_id === id ? { ...s, ...patch } : s)) }; };
|
|
113
|
+
|
|
114
|
+
function finish(run, state, reason) {
|
|
115
|
+
run.body = { ...run.body, state, reason, ended_at: Math.max(ctx.now(), run.body.started_at),
|
|
116
|
+
stages: run.body.stages.map((s) => (s.state === "queued" || s.state === "running" ? { ...s, state: "skipped" } : s)) };
|
|
117
|
+
publish(run);
|
|
118
|
+
ctx.markLedger({ v: 1, steered: "pipeline", agent: false, pipeline_run_id: run.body.pipeline_run_id, release_id: run.body.release_id, project_id: run.body.project_id, started_at: run.body.started_at, ended_at: run.body.ended_at });
|
|
119
|
+
runs.delete(run.body.pipeline_run_id);
|
|
120
|
+
ctx.onEnded?.(run.body);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function runStage(run, stage, project, config) {
|
|
124
|
+
return new Promise((resolve) => {
|
|
125
|
+
const argv = allowCommand(stage.run, scriptsOf(project.path)); // again, at run time
|
|
126
|
+
if (!argv.ok) { resolve({ state: "failed" }); return; }
|
|
127
|
+
const started = ctx.now();
|
|
128
|
+
setStage(run, stage.id, { state: "running", started_at: started });
|
|
129
|
+
publish(run);
|
|
130
|
+
const dir = join(ctx.logDir, run.body.pipeline_run_id);
|
|
131
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
132
|
+
const log = openSync(join(dir, `${stage.id}.log`), constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
133
|
+
let tail = "";
|
|
134
|
+
const tap = stage.parser === "tap" ? createTapCounter() : null;
|
|
135
|
+
const child = go(argv.file, argv.args, { cwd: project.path, env: ctx.env(config.path_prepend), shell: false, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true });
|
|
136
|
+
run.child = child;
|
|
137
|
+
if (Number.isSafeInteger(child.pid)) ctx.journal.recordPipelinePid(run.body.pipeline_run_id, { pid: child.pid, file: argv.file }); // a later daemon ends it (P2-4)
|
|
138
|
+
const take = (chunk, out) => {
|
|
139
|
+
const text = chunk.toString("utf8");
|
|
140
|
+
try { writeSync(log, text); } catch { /* the log is the person's convenience */ }
|
|
141
|
+
if (!out) return;
|
|
142
|
+
tail = (tail + text).slice(-MAX_KEEP);
|
|
143
|
+
if (tap) { tap.feed(text); const m = tap.now(); if (m) { setStage(run, stage.id, { measured: m }); publish(run, { live: true }); } }
|
|
144
|
+
};
|
|
145
|
+
child.stdout?.on("data", (c) => take(c, true));
|
|
146
|
+
child.stderr?.on("data", (c) => take(c, false));
|
|
147
|
+
const timer = setTimeout(() => { run.timedOut = true; kill(child); }, stage.timeout_ms);
|
|
148
|
+
timer.unref?.();
|
|
149
|
+
const done = (code) => {
|
|
150
|
+
clearTimeout(timer);
|
|
151
|
+
try { closeSync(log); } catch { /* closed */ }
|
|
152
|
+
run.child = null;
|
|
153
|
+
const report = stage.report ? readProjectFile(project.path, stage.report, MAX_REPORT) : tail;
|
|
154
|
+
const read = readReport(stage.parser, report ?? "");
|
|
155
|
+
const exitOk = stage.parser === "zap_json" ? code === 0 || code === 1 || code === 2 : code === 0;
|
|
156
|
+
const failed = !exitOk || run.cancelled || run.timedOut || (read.measured?.unit === "tests" && read.measured.failed > 0) || findingsFail(read.findings, stage.fail_on);
|
|
157
|
+
const { measured: _live, ...rest } = run.body.stages.find((s) => s.stage_id === stage.id);
|
|
158
|
+
const result = { ...rest, ...(read.measured ? { measured: read.measured } : {}), ...(read.findings ? { findings: read.findings } : {}) };
|
|
159
|
+
const state = run.cancelled ? "skipped" : failed ? "failed" : "passed";
|
|
160
|
+
run.body = { ...run.body, stages: run.body.stages.map((s) => (s.stage_id === stage.id ? { ...result, state, duration_ms: Math.max(0, ctx.now() - started) } : s)) };
|
|
161
|
+
resolve({ state });
|
|
162
|
+
};
|
|
163
|
+
child.on("error", () => done(-1));
|
|
164
|
+
child.on("close", (code) => done(code ?? -1));
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const kill = (child) => { try { if (process.platform !== "win32" && child.pid) process.kill(-child.pid, "SIGTERM"); else child.kill("SIGTERM"); } catch { try { child.kill("SIGTERM"); } catch { /* gone */ } } };
|
|
169
|
+
|
|
170
|
+
async function drive(run, project, config, hash) {
|
|
171
|
+
for (const stage of config.stages) {
|
|
172
|
+
if (stage.desk) continue;
|
|
173
|
+
if (run.cancelled) break;
|
|
174
|
+
// Reviewed still? An earlier stage, a task or the desk may have changed the file, a script or a stage's code (P3-5).
|
|
175
|
+
if (pipelineState(project, ctx.reviews()).hash !== hash) return finish(run, "failed", "unreviewed");
|
|
176
|
+
const { state } = await runStage(run, stage, project, config);
|
|
177
|
+
if (state === "failed") return finish(run, "failed", run.timedOut ? "timeout" : "stage_failed");
|
|
178
|
+
publish(run);
|
|
179
|
+
}
|
|
180
|
+
if (run.cancelled) return finish(run, "cancelled", "cancelled");
|
|
181
|
+
finish(run, "passed", null);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
state: (project) => pipelineState(project, ctx.reviews()).state,
|
|
186
|
+
runsAfterTasks: (project) => pipelineState(project, ctx.reviews()).config?.run_after_tasks === true,
|
|
187
|
+
/** → { ok: true, run } or { ok: false, reason } with a protocol reject reason. Never a desk stage. */
|
|
188
|
+
start({ release_id, project_id }) {
|
|
189
|
+
const project = ctx.projects().find((p) => p.project_id === project_id);
|
|
190
|
+
if (!project) return { ok: false, reason: "not_found" };
|
|
191
|
+
const found = pipelineState(project, ctx.reviews());
|
|
192
|
+
if (found.state === "absent") return { ok: false, reason: "not_found" };
|
|
193
|
+
if (found.state !== "reviewed") return { ok: false, reason: "unreviewed" };
|
|
194
|
+
if ([...runs.values()].some((r) => r.body.project_id === project_id) || runs.size >= MAX_PIPELINES) return { ok: false, reason: "busy" };
|
|
195
|
+
const body = { pipeline_run_id: P.mintId("plr", ctx.random), release_id, project_id, state: "running", reason: null, started_at: ctx.now(), ended_at: null,
|
|
196
|
+
stages: found.config.stages.map((s) => ({ stage_id: s.id, label: s.label, kind: s.kind, state: s.desk ? "at_desk" : "queued" })) };
|
|
197
|
+
const run = { body, child: null, cancelled: false, timedOut: false };
|
|
198
|
+
if (!publish(run)) return { ok: false, reason: "unsupported" }; // journaled before the first stage runs, or nothing runs
|
|
199
|
+
runs.set(body.pipeline_run_id, run);
|
|
200
|
+
ctx.markLedger({ v: 1, steered: "pipeline", agent: false, pipeline_run_id: body.pipeline_run_id, release_id, project_id, started_at: body.started_at, ended_at: null });
|
|
201
|
+
// The first stage starts on the next turn of the loop, after the caller saved the release as verifying (P3-6).
|
|
202
|
+
run.done = new Promise((resolve) => setImmediate(resolve)).then(() => drive(run, project, found.config, found.hash))
|
|
203
|
+
.catch((e) => { ctx.log("pipeline_failed", { name: e?.name ?? "Error" }); if (runs.has(body.pipeline_run_id)) finish(run, "failed", "stage_failed"); });
|
|
204
|
+
return { ok: true, run: body };
|
|
205
|
+
},
|
|
206
|
+
cancel(runId) {
|
|
207
|
+
const run = runs.get(runId);
|
|
208
|
+
if (!run) return false;
|
|
209
|
+
run.cancelled = true;
|
|
210
|
+
if (run.child) kill(run.child);
|
|
211
|
+
return true;
|
|
212
|
+
},
|
|
213
|
+
/** Runs an earlier daemon left open: failed, interrupted, never run again. */
|
|
214
|
+
recover() {
|
|
215
|
+
let closed = 0;
|
|
216
|
+
for (const p of ctx.journal.pipelines()) {
|
|
217
|
+
if (P.isFinalPipelineState(p.state) || runs.has(p.pipeline_run_id)) continue;
|
|
218
|
+
reap(p.pipeline_run_id);
|
|
219
|
+
const ended = Math.max(ctx.now(), p.started_at);
|
|
220
|
+
const body = { ...p, state: "failed", reason: "interrupted", ended_at: ended, stages: p.stages.map((s) => { const { eta: _e, ...r } = s; return s.state === "running" ? { ...r, state: "failed", duration_ms: Math.max(0, ended - (s.started_at ?? ended)) } : s.state === "queued" ? { ...r, state: "skipped" } : r; }) };
|
|
221
|
+
const { eta: _top, ...clean } = body;
|
|
222
|
+
ctx.journal.recordPipeline(clean);
|
|
223
|
+
ctx.markLedger({ v: 1, steered: "pipeline", agent: false, pipeline_run_id: p.pipeline_run_id, release_id: p.release_id, project_id: p.project_id, started_at: p.started_at, ended_at: ended });
|
|
224
|
+
ctx.emit(null, "pipeline.updated", clean);
|
|
225
|
+
ctx.onEnded?.(clean);
|
|
226
|
+
closed += 1;
|
|
227
|
+
}
|
|
228
|
+
return closed;
|
|
229
|
+
},
|
|
230
|
+
running: () => [...runs.keys()],
|
|
231
|
+
get: (runId) => runs.get(runId)?.body ?? ctx.journal.pipelines().find((p) => p.pipeline_run_id === runId) ?? null,
|
|
232
|
+
async stopAll() { for (const run of runs.values()) { run.cancelled = true; if (run.child) kill(run.child); } await Promise.all([...runs.values()].map((r) => r.done)); },
|
|
233
|
+
};
|
|
234
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WHAT A PHONE MAY REACH ON THIS COMPUTER (2026-11-07; owner decisions, binding). The computer's own policy, never the
|
|
3
|
+
* phone's: the phone shows what this file decided and the computer refuses anything else however well it is signed.
|
|
4
|
+
*
|
|
5
|
+
* PROJECTS. A phone may steer an agent only inside a folder the person granted at this keyboard
|
|
6
|
+
* (`worktrust remote projects add`). A grant is the folder's canonical path (realpath: every symlink resolved), a
|
|
7
|
+
* directory, and never the home folder itself, a parent of it, the root, or a place that holds secrets (~/.ssh, ~/.gnupg,
|
|
8
|
+
* keychains, browser profiles, wallets, cloud credentials).
|
|
9
|
+
*
|
|
10
|
+
* APPROVALS. Every permission request an agent makes is put in ONE of the protocol's APPROVAL_CLASSES here. Only two
|
|
11
|
+
* may reach the phone (owner decision 6): `project_edit`, a file edit inside the granted project that touches no secret
|
|
12
|
+
* and no rule file, and `reviewed_command`, a command from the short reviewed list below (tests, builds, linters), run
|
|
13
|
+
* exactly as listed, with no shell syntax. Everything else is decided at the keyboard or not at all: an install from the
|
|
14
|
+
* network, git push, a deploy, deleting outside the project, reading a secret path, any "always allow" rule, and
|
|
15
|
+
* whatever this file cannot name (`other`). Unknown fails closed.
|
|
16
|
+
*/
|
|
17
|
+
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
18
|
+
import { homedir } from "node:os";
|
|
19
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
20
|
+
import * as P from "./remote-protocol.mjs";
|
|
21
|
+
|
|
22
|
+
const HOME = () => realpathOr(homedir());
|
|
23
|
+
function realpathOr(path) { try { return realpathSync(path); } catch { return resolve(path); } }
|
|
24
|
+
|
|
25
|
+
/** Inside `root` (both canonical): equal to it or below it, never through `..`. */
|
|
26
|
+
export const isInside = (root, path) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
|
|
27
|
+
|
|
28
|
+
/** Folders that hold secrets or another program's private state, relative to the home folder. */
|
|
29
|
+
const SECRET_DIRS = [".ssh", ".gnupg", ".aws", ".azure", ".config/gcloud", ".kube", ".docker", ".password-store", ".worktrust",
|
|
30
|
+
"Library/Keychains", "Library/Application Support/Google/Chrome", "Library/Application Support/Firefox", "Library/Application Support/BraveSoftware",
|
|
31
|
+
"Library/Application Support/Microsoft Edge", "Library/Safari", "Library/Cookies", ".mozilla", ".config/google-chrome", ".config/chromium",
|
|
32
|
+
".config/BraveSoftware", ".local/share/keyrings", ".electrum", ".bitcoin", ".ethereum", "Library/Ethereum", "Library/Application Support/Exodus", ".config/solana"];
|
|
33
|
+
/** File names that are secrets wherever they lie. `.env` and its variants, keys, credentials, token stores. */
|
|
34
|
+
const SECRET_FILE = /^(\.env(\..*)?|\.envrc|\.netrc|\.npmrc|\.pypirc|\.git-credentials|id_(rsa|ecdsa|ed25519|dsa)(\.pub)?|.*\.(pem|key|p12|pfx|keystore|jks|kdbx|ovpn)|credentials(\.json)?|secrets?\.(json|ya?ml|toml)|service-account.*\.json|wallet\.dat|keystore)$/i;
|
|
35
|
+
/** Files that change what an agent may do by itself: permission rules, hooks, MCP servers. Editing one is an "always allow". */
|
|
36
|
+
/** Files that change what an agent or a tool may do by itself: permission rules, hooks, MCP servers, the repository's own
|
|
37
|
+
* configuration (core.fsmonitor and sshCommand run code), editor tasks. Editing one is an "always allow". Case-insensitive:
|
|
38
|
+
* macOS and Windows disks are, and a path typed as .CLAUDE/SETTINGS.JSON is the same file (review 2026-11-07, P1-a). */
|
|
39
|
+
const RULE_FILE = /(^|[\\/])(\.claude[\\/].*|\.mcp\.json|\.claude\.json|\.codex[\\/].*|\.cursor[\\/].*|\.git([\\/].*)?|\.husky[\\/].*|\.vscode[\\/].*|\.idea[\\/].*|\.envrc|\.npmrc|\.yarnrc(\.yml)?|\.gitattributes|\.gitmodules)$/i;
|
|
40
|
+
/** Files that say what a reviewed command runs (scripts, targets, test setup): an edit to one from a phone would turn the next
|
|
41
|
+
* "npm test" into anything, so it is decided at the keyboard (P2-a). */
|
|
42
|
+
const SCRIPT_FILE = /(^|[\\/])(package\.json|makefile|gnumakefile|justfile|taskfile\.ya?ml|pyproject\.toml|setup\.py|setup\.cfg|tox\.ini|noxfile\.py|conftest\.py|pytest\.ini|cargo\.toml|build\.rs|go\.mod|deno\.jsonc?|bunfig\.toml|turbo\.json|nx\.json|(jest|vitest|vite|webpack|rollup|babel|eslint|prettier)\.config\.[cm]?[jt]s|\.eslintrc(\.[a-z]+)?)$/i;
|
|
43
|
+
|
|
44
|
+
export function isSecretPath(path) {
|
|
45
|
+
const canonical = realpathOr(path), home = HOME();
|
|
46
|
+
if (SECRET_FILE.test(basename(canonical))) return true;
|
|
47
|
+
return SECRET_DIRS.some((dir) => isInside(join(home, dir), canonical));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A folder a person asks to grant: its canonical form, or the reason it cannot be granted. */
|
|
51
|
+
export function canonicalProject(path) {
|
|
52
|
+
if (typeof path !== "string" || path.trim() === "") return { ok: false, reason: "name a folder" };
|
|
53
|
+
const given = resolve(path.replace(/^~(?=$|[\\/])/, homedir()));
|
|
54
|
+
if (!existsSync(given)) return { ok: false, reason: "that folder does not exist" };
|
|
55
|
+
const canonical = realpathSync(given);
|
|
56
|
+
if (!statSync(canonical).isDirectory()) return { ok: false, reason: "that is a file, not a folder" };
|
|
57
|
+
const home = HOME();
|
|
58
|
+
if (dirname(canonical) === canonical) return { ok: false, reason: "the root of the disk cannot be granted" };
|
|
59
|
+
if (isInside(canonical, home)) return { ok: false, reason: "your home folder, or a folder above it, cannot be granted: grant one project folder" };
|
|
60
|
+
if (isSecretPath(canonical) || SECRET_DIRS.some((dir) => isInside(canonical, join(home, dir)))) return { ok: false, reason: "that folder holds secrets (keys, keychains, browser profiles, wallets, credentials)" };
|
|
61
|
+
return { ok: true, path: canonical };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The project a path is in, by the canonical path of the path itself or, for a file not yet written, of its folder. */
|
|
65
|
+
export function canonicalTarget(path, cwd) {
|
|
66
|
+
if (typeof path !== "string" || path === "") return null;
|
|
67
|
+
// The nearest folder that exists, every symlink in it resolved, then the rest added back: a new file under a link that
|
|
68
|
+
// points outside the project is outside it (review 2026-11-07, P1-b).
|
|
69
|
+
let existing = resolve(cwd, path);
|
|
70
|
+
const rest = [];
|
|
71
|
+
while (!existsSync(existing) && dirname(existing) !== existing) { rest.unshift(basename(existing)); existing = dirname(existing); }
|
|
72
|
+
let base;
|
|
73
|
+
try { base = realpathSync.native(existing); } catch { base = realpathOr(existing); }
|
|
74
|
+
return rest.length ? join(base, ...rest) : base;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* THE REVIEWED COMMANDS: tests, builds and linters, exactly. A command is approvable from a phone only when its words,
|
|
79
|
+
* split on spaces, match one line here with nothing after it but plain arguments ([A-Za-z0-9_./:=@,+-], no `..`).
|
|
80
|
+
* No package runner that may download (`npx`, `pnpm dlx`, `bunx`), no install, no script that names a deploy.
|
|
81
|
+
*/
|
|
82
|
+
export const REVIEWED_COMMANDS = Object.freeze([
|
|
83
|
+
"npm test", "npm run test", "npm run build", "npm run lint", "npm run typecheck",
|
|
84
|
+
"pnpm test", "pnpm run test", "pnpm build", "pnpm run build", "pnpm lint", "pnpm run lint", "pnpm typecheck", "pnpm run typecheck",
|
|
85
|
+
"yarn test", "yarn build", "yarn lint", "bun test", "bun run test", "bun run build", "bun run lint",
|
|
86
|
+
"node --test", "pytest", "python -m pytest", "python3 -m pytest", "cargo test --offline", "cargo build --offline", "cargo check --offline", "cargo clippy --offline",
|
|
87
|
+
"make test", "make build", "make lint", "make check", "tsc --noEmit", "eslint", "ruff check", "mypy", "prettier --check",
|
|
88
|
+
]);
|
|
89
|
+
/** An argument after a reviewed line is a relative path or a test name inside the project: no flag, no assignment, no absolute
|
|
90
|
+
* path, no way up (review 2026-11-07, P2-a: `make test -C /x`, `npm test --prefix=/x`, `node --test --require=/x`). */
|
|
91
|
+
const PLAIN_ARG = /^[A-Za-z0-9_][A-Za-z0-9_./:@,+-]*$/;
|
|
92
|
+
const SHELL_SYNTAX = /[;&|`$<>(){}\\\n\r'"*?!~#]/;
|
|
93
|
+
const NETWORK = /^(npm|pnpm|yarn|bun)\s+(i|install|add|ci|update|upgrade|dlx|x|create|init)\b|^(npx|bunx|pip3?|pipx|uv|poetry|gem|brew|apt(-get)?|dnf|yum|cargo\s+install|go\s+(get|install)|curl|wget|git\s+(clone|fetch|pull)|docker\s+(pull|run))\b/;
|
|
94
|
+
const PUSH = /^git\s+push\b/;
|
|
95
|
+
const DEPLOY = /^(vercel|netlify|fly|flyctl|firebase|heroku|wrangler|serverless|sls|kubectl|helm|terraform|pulumi|eas|gcloud|aws|az|railway|render)\b|^(npm|pnpm|yarn)\s+(publish|run\s+deploy|deploy)\b|\bdeploy\b/;
|
|
96
|
+
|
|
97
|
+
export function reviewedCommand(command) {
|
|
98
|
+
if (typeof command !== "string" || SHELL_SYNTAX.test(command)) return false;
|
|
99
|
+
const words = command.trim().split(/\s+/);
|
|
100
|
+
return REVIEWED_COMMANDS.some((line) => {
|
|
101
|
+
const head = line.split(" ");
|
|
102
|
+
if (head.some((word, i) => words[i] !== word)) return false;
|
|
103
|
+
return words.slice(head.length).every((arg) => PLAIN_ARG.test(arg) && !arg.split("/").includes(".."));
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function classifyCommand(command, project) {
|
|
108
|
+
const text = String(command ?? "").trim();
|
|
109
|
+
if (PUSH.test(text)) return "git_push";
|
|
110
|
+
if (DEPLOY.test(text)) return "deploy";
|
|
111
|
+
if (NETWORK.test(text)) return "network_install";
|
|
112
|
+
if (/^(rm|rmdir|unlink|trash|shred)\b/.test(text)) {
|
|
113
|
+
const targets = text.split(/\s+/).slice(1).filter((w) => !w.startsWith("-"));
|
|
114
|
+
return targets.some((t) => !isInside(project, canonicalTarget(t, project) ?? "/")) ? "delete_outside_project" : "other";
|
|
115
|
+
}
|
|
116
|
+
if (/(^|\s)(cat|less|more|head|tail|grep|rg|cp|scp|base64)\s/.test(` ${text} `) && text.split(/\s+/).some((w) => SECRET_FILE.test(basename(w)) || w.includes(".ssh"))) return "secret_read";
|
|
117
|
+
return reviewedCommand(text) ? "reviewed_command" : "other";
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* AN OUTWARD MESSAGE (owner, 2026-11-07): a connector tool (mcp__<server>__<tool>) whose tool name says it sends (send,
|
|
122
|
+
* reply, post, publish) is `outward_message` ONLY when every field of the message can be read from its input and nothing
|
|
123
|
+
* else is in it: recipients (to, or a channel), cc, bcc, subject, the text, attachment names, and a thread to answer in.
|
|
124
|
+
* An input with any other field, no recipient, no text, or attachments it cannot name is `other`, denied locally: the
|
|
125
|
+
* phone must see the whole message it approves. Claude Code's permission request names the tool, not its description,
|
|
126
|
+
* so the name decides.
|
|
127
|
+
*/
|
|
128
|
+
const SENDS = /(^|_)(send|reply|post|publish)(_|$)/;
|
|
129
|
+
const MESSAGE_KEYS = new Set(["to", "recipients", "recipient", "channel", "cc", "bcc", "subject", "body", "text", "message", "content", "attachments", "thread_id", "threadId", "in_reply_to", "inReplyTo"]);
|
|
130
|
+
const snake = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
131
|
+
const addresses = (value) => (value === undefined ? [] : typeof value === "string" ? value.split(",").map((a) => a.trim()).filter(Boolean) : Array.isArray(value) && value.every((a) => typeof a === "string") ? value : null);
|
|
132
|
+
export function outwardMessageOf(tool, args, project) {
|
|
133
|
+
const m = /^mcp__([A-Za-z0-9_-]+?)__([A-Za-z0-9_-]+)$/.exec(String(tool));
|
|
134
|
+
if (!m || !SENDS.test(snake(m[2]))) return null;
|
|
135
|
+
if (Object.keys(args).some((k) => !MESSAGE_KEYS.has(k))) return { refused: "the message has fields the phone could not be shown" };
|
|
136
|
+
const to = addresses(args.to ?? args.recipients ?? args.recipient ?? args.channel), cc = addresses(args.cc), bcc = addresses(args.bcc);
|
|
137
|
+
const text = [args.body, args.text, args.message, args.content].filter((v) => v !== undefined);
|
|
138
|
+
const attachments = args.attachments === undefined ? [] : Array.isArray(args.attachments) ? args.attachments.map((a) => (typeof a === "string" ? a : a?.filename ?? a?.name ?? a?.path)) : null;
|
|
139
|
+
if (!to || to.length === 0 || to.length > 100 || !cc || !bcc || cc.length > 100 || bcc.length > 100) return { refused: "the message's recipients cannot all be shown" };
|
|
140
|
+
if (text.length !== 1 || typeof text[0] !== "string" || text[0].length > 65_536) return { refused: "the message's text cannot be shown whole" };
|
|
141
|
+
if (!attachments || attachments.length > 50 || attachments.some((a) => typeof a !== "string" || !a)) return { refused: "the message's attachments cannot all be named" };
|
|
142
|
+
if (attachments.some((a) => isSecretPath(canonicalTarget(a, project) ?? a) || !isInside(project, canonicalTarget(a, project) ?? "/"))) return { refused: "an attachment is a secret file or lies outside the project" };
|
|
143
|
+
if (args.subject !== undefined && (typeof args.subject !== "string" || args.subject.length > 998)) return { refused: "the message's subject cannot be shown" };
|
|
144
|
+
if ([...to, ...cc, ...bcc].some((a) => a.length > 320)) return { refused: "a recipient is too long to show" };
|
|
145
|
+
return { message: { channel: m[1].slice(0, 128), to, cc, bcc, subject: args.subject ?? null, text: text[0], attachments } };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const EDIT_TOOLS = new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
149
|
+
const READ_TOOLS = new Set(["Read", "Glob", "Grep", "LS", "NotebookRead"]);
|
|
150
|
+
export const MAX_SHOWN_INPUT = 16_384;
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* One permission request → the action the phone would see, with its class. `tool` is the agent's own tool name, `input`
|
|
154
|
+
* its exact arguments, `project` the canonical project folder. Pure apart from reading which paths exist.
|
|
155
|
+
*/
|
|
156
|
+
export function classifyAction(adapter, tool, input, project, rationale = null) {
|
|
157
|
+
const args = input && typeof input === "object" ? input : {};
|
|
158
|
+
const shown = JSON.stringify(args);
|
|
159
|
+
let kind = "tool", cls = "other", files = [];
|
|
160
|
+
if (tool === "Bash") {
|
|
161
|
+
kind = "command";
|
|
162
|
+
cls = classifyCommand(args.command, project);
|
|
163
|
+
} else if (EDIT_TOOLS.has(tool)) {
|
|
164
|
+
const target = canonicalTarget(args.file_path ?? args.notebook_path, project);
|
|
165
|
+
files = target ? [target] : [];
|
|
166
|
+
kind = tool === "Write" && target && !existsSync(target) ? "write" : "edit";
|
|
167
|
+
cls = !target ? "other" : RULE_FILE.test(target) ? "persistent_rule" : isSecretPath(target) ? "secret_read" : !isInside(project, target) ? "other" : SCRIPT_FILE.test(target) ? "other" : "project_edit";
|
|
168
|
+
} else if (READ_TOOLS.has(tool)) {
|
|
169
|
+
const target = canonicalTarget(args.file_path ?? args.path ?? args.notebook_path, project);
|
|
170
|
+
files = target ? [target] : [];
|
|
171
|
+
kind = "tool";
|
|
172
|
+
cls = target && isSecretPath(target) ? "secret_read" : "other";
|
|
173
|
+
} else if (tool === "WebFetch" || tool === "WebSearch") kind = "network";
|
|
174
|
+
const outward = outwardMessageOf(tool, args, project);
|
|
175
|
+
if (outward) {
|
|
176
|
+
const base = { kind: "message", adapter, tool: String(tool).slice(0, 128), files: [], rationale };
|
|
177
|
+
if (outward.refused || shown.length > MAX_SHOWN_INPUT) return { action: { ...base, class: "other", input: shown.slice(0, MAX_SHOWN_INPUT) }, reason: outward.refused ?? "the message is too long to show exactly" };
|
|
178
|
+
return { action: { ...base, class: "outward_message", input: shown, message: outward.message }, reason: null };
|
|
179
|
+
}
|
|
180
|
+
// What the phone shows is the exact input. When it cannot be shown whole, it cannot be approved from a phone.
|
|
181
|
+
if (shown.length > MAX_SHOWN_INPUT) return { action: { kind, class: "other", adapter, tool: String(tool).slice(0, 128) || "unknown", input: `${shown.slice(0, MAX_SHOWN_INPUT - 40)} [cut: too long to show exactly]`, files: files.slice(0, 100), rationale }, reason: "the request is too long to show exactly" };
|
|
182
|
+
const action = { kind, class: P.APPROVAL_CLASSES.includes(cls) ? cls : "other", adapter, tool: String(tool).slice(0, 128) || "unknown", input: shown.length > 0 ? shown : "{}", files: files.slice(0, 100), rationale };
|
|
183
|
+
return { action, reason: P.isRemoteApprovable(action.class) ? null : REASONS[action.class] };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export const REASONS = Object.freeze({
|
|
187
|
+
network_install: "installs from the network are approved at the computer, never from a phone",
|
|
188
|
+
git_push: "git push is approved at the computer, never from a phone",
|
|
189
|
+
deploy: "deploys are approved at the computer, never from a phone",
|
|
190
|
+
delete_outside_project: "deleting outside the project is never approved from a phone",
|
|
191
|
+
secret_read: "secret files (keys, .env, credentials) are never opened from a phone",
|
|
192
|
+
persistent_rule: "rules that let an agent act alone later are set at the computer, never from a phone",
|
|
193
|
+
other: "only edits inside the project, reviewed test, build and lint commands, and messages shown whole are approved from a phone",
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
/** The one gate between a classified action and the phone. Nothing else in the daemon may decide this. */
|
|
197
|
+
export const phoneMayDecide = (action) => P.APPROVAL_CLASSES.includes(action?.class) && P.isRemoteApprovable(action.class);
|
|
198
|
+
|
|
199
|
+
export const SEP = sep;
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A LOCAL PREVIEW FOR THE PHONE (owner, 2026-11-07: the phone's "Deploy" segment is a LOCAL preview, never a production
|
|
3
|
+
* deploy). docs/remote-agents/PROTOCOL.md "Local preview".
|
|
4
|
+
*
|
|
5
|
+
* The person grants, per project and at the keyboard, the dev-server PORTS and the built HTML FILES a phone may preview
|
|
6
|
+
* (`worktrust remote preview allow <port|file> <folder>`; ~/.worktrust/remote/previews.json). `preview.render` renders one
|
|
7
|
+
* of them with the person's installed Chrome or Chromium, headless (`--headless=new --screenshot --window-size`), in a
|
|
8
|
+
* throw-away profile, and answers with the PNG in sealed chunks and the page's title and HTTP status as the computer saw
|
|
9
|
+
* them. The URL is always built here: `http://127.0.0.1:<granted port><path>`, never a host or URL from the phone. A file
|
|
10
|
+
* is served to Chrome by a one-shot server on 127.0.0.1 that answers only files inside the project (no dotfile, no secret
|
|
11
|
+
* path, no link out), so Chrome never opens file:// and a page cannot pull another file of the computer into the picture.
|
|
12
|
+
* No browser installed: refused (`unsupported`); nothing is installed. One render at a time.
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from "node:child_process";
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { existsSync, lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs";
|
|
17
|
+
import { createServer, get } from "node:http";
|
|
18
|
+
import { connect } from "node:net";
|
|
19
|
+
import { tmpdir } from "node:os";
|
|
20
|
+
import { delimiter, extname, join, relative, sep } from "node:path";
|
|
21
|
+
import * as P from "./remote-protocol.mjs";
|
|
22
|
+
import { isSecretPath } from "./remote-policy.mjs";
|
|
23
|
+
|
|
24
|
+
const MAC_BROWSERS = ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"];
|
|
25
|
+
const PATH_BROWSERS = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge"];
|
|
26
|
+
const TYPES = { ".html": "text/html", ".htm": "text/html", ".css": "text/css", ".js": "text/javascript", ".mjs": "text/javascript", ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif", ".woff2": "font/woff2", ".woff": "font/woff", ".ico": "image/x-icon" };
|
|
27
|
+
const RENDER_MS = 30_000;
|
|
28
|
+
|
|
29
|
+
/** The person's own Chrome-family browser, or null. WORKTRUST_PREVIEW_BROWSER (the daemon's own environment) is for tests. */
|
|
30
|
+
export function findBrowser(env = process.env) {
|
|
31
|
+
const forced = process.env.WORKTRUST_PREVIEW_BROWSER;
|
|
32
|
+
if (forced) return existsSync(forced) ? forced : null;
|
|
33
|
+
// The repo's named Chromium (CI installs Playwright's and names it here, as every browser check does), then the computer's own.
|
|
34
|
+
const named = process.env.WORKTRUST_CHROME_BIN;
|
|
35
|
+
if (named && existsSync(named)) return named;
|
|
36
|
+
if (process.platform === "darwin") for (const f of MAC_BROWSERS) if (existsSync(f)) return f;
|
|
37
|
+
for (const dir of (env.PATH ?? "").split(delimiter)) for (const b of PATH_BROWSERS) if (dir && existsSync(join(dir, b))) return join(dir, b);
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Something listens on 127.0.0.1:port. */
|
|
42
|
+
export const listening = (port, ms = 500) => new Promise((resolve) => {
|
|
43
|
+
const s = connect({ host: "127.0.0.1", port });
|
|
44
|
+
const done = (v) => { s.destroy(); resolve(v); };
|
|
45
|
+
s.once("connect", () => done(true)); s.once("error", () => done(false)); s.setTimeout(ms, () => done(false));
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const inside = (root, p) => { const rel = relative(root, p); return rel === "" || (!rel.startsWith("..") && !rel.startsWith(sep) && !/^[A-Za-z]:/.test(rel)); };
|
|
49
|
+
|
|
50
|
+
/** A one-shot server for a project's files: inside the project only, no dotfile, no secret, no link out. */
|
|
51
|
+
export function serveProject(root) {
|
|
52
|
+
const base = realpathSync(root);
|
|
53
|
+
const server = createServer((req, res) => {
|
|
54
|
+
const path = decodeURIComponent(new URL(req.url, "http://127.0.0.1").pathname);
|
|
55
|
+
const file = join(base, path);
|
|
56
|
+
let ok = false;
|
|
57
|
+
try { ok = !path.split("/").some((seg) => seg.startsWith(".")) && existsSync(file) && lstatSync(file).isFile() && inside(base, realpathSync(file)) && !isSecretPath(realpathSync(file)); } catch { ok = false; }
|
|
58
|
+
if (!ok) { res.writeHead(404).end(); return; }
|
|
59
|
+
res.writeHead(200, { "content-type": TYPES[extname(file).toLowerCase()] ?? "application/octet-stream" }).end(readFileSync(file));
|
|
60
|
+
});
|
|
61
|
+
return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve({ port: server.address().port, close: () => server.close() })));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The status and <title> of the page as the computer reads it (256 KiB at most). */
|
|
65
|
+
export const pageFacts = (url) => new Promise((resolve) => {
|
|
66
|
+
const req = get(url, { timeout: 5000 }, (res) => {
|
|
67
|
+
let body = "";
|
|
68
|
+
res.setEncoding("utf8");
|
|
69
|
+
res.on("data", (c) => { if (body.length < 262_144) body += c; });
|
|
70
|
+
res.on("end", () => resolve({ status: res.statusCode ?? null, title: /<title[^>]*>([^<]{1,300})<\/title>/i.exec(body)?.[1]?.trim() || null }));
|
|
71
|
+
});
|
|
72
|
+
req.on("timeout", () => req.destroy());
|
|
73
|
+
req.on("error", () => resolve({ status: null, title: null }));
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** A PNG's own width and height (its IHDR), or null. */
|
|
77
|
+
export function pngSize(b) {
|
|
78
|
+
if (b.length < 24 || b.readUInt32BE(0) !== 0x89504e47 || b.toString("latin1", 12, 16) !== "IHDR") return null;
|
|
79
|
+
return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The fixed command line: headless, a throw-away profile, no first run, the window, the screenshot file, the URL. */
|
|
83
|
+
export function browserArgs({ profile, out, width, height, url }) {
|
|
84
|
+
return ["--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", "--disable-extensions", "--mute-audio", "--disable-sync",
|
|
85
|
+
`--user-data-dir=${profile}`, `--screenshot=${out}`, `--window-size=${width},${height}`, "--virtual-time-budget=5000", url];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function createPreview(ctx) {
|
|
89
|
+
// ctx: { emit, projects(), grants() → { [project_id]: { ports: [], files: [] } }, env(), log }
|
|
90
|
+
let busy = false;
|
|
91
|
+
const grantOf = (projectId) => ctx.grants()[projectId] ?? { ports: [], files: [] };
|
|
92
|
+
|
|
93
|
+
async function targets(env, p) {
|
|
94
|
+
const project = ctx.projects().find((x) => x.project_id === p.project_id);
|
|
95
|
+
if (!project) return "not_found";
|
|
96
|
+
const g = grantOf(p.project_id);
|
|
97
|
+
const ports = await Promise.all((g.ports ?? []).slice(0, 20).map(async (port) => ({ port, listening: await listening(port) })));
|
|
98
|
+
ctx.emit(null, "preview.targets", { project_id: p.project_id, ports, files: (g.files ?? []).slice(0, 50), browser: findBrowser(ctx.env()) !== null }, env.command_id);
|
|
99
|
+
return "taken";
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function render(env, p) {
|
|
103
|
+
const project = ctx.projects().find((x) => x.project_id === p.project_id);
|
|
104
|
+
if (!project) return "not_found";
|
|
105
|
+
const g = grantOf(p.project_id);
|
|
106
|
+
if (p.target === "port" ? !(g.ports ?? []).includes(p.port) : !(g.files ?? []).includes(p.path)) return "unsupported"; // granted at the keyboard only
|
|
107
|
+
const browser = findBrowser(ctx.env());
|
|
108
|
+
if (!browser) return "unsupported";
|
|
109
|
+
if (busy) return "busy";
|
|
110
|
+
if (p.target === "port" && !(await listening(p.port))) return "not_found";
|
|
111
|
+
busy = true;
|
|
112
|
+
const profile = mkdtempSync(join(tmpdir(), "wt-preview-"));
|
|
113
|
+
let server = null;
|
|
114
|
+
try {
|
|
115
|
+
let url;
|
|
116
|
+
if (p.target === "port") url = `http://127.0.0.1:${p.port}${p.path}`;
|
|
117
|
+
else { server = await serveProject(project.path); url = `http://127.0.0.1:${server.port}/${p.path}`; }
|
|
118
|
+
const facts = await pageFacts(url);
|
|
119
|
+
const vp = P.PREVIEW_VIEWPORTS[p.viewport];
|
|
120
|
+
const height = p.full_page ? Math.min(vp.height * 4, 6000) : vp.height; // a tall window, not a measured page: see PROTOCOL.md
|
|
121
|
+
const out = join(profile, "shot.png");
|
|
122
|
+
const code = await new Promise((resolve) => {
|
|
123
|
+
const child = spawn(browser, browserArgs({ profile: join(profile, "p"), out, width: vp.width, height, url }), { stdio: "ignore", detached: process.platform !== "win32", windowsHide: true, env: ctx.env() });
|
|
124
|
+
const timer = setTimeout(() => { try { process.kill(-child.pid, "SIGKILL"); } catch { child.kill("SIGKILL"); } }, RENDER_MS);
|
|
125
|
+
child.on("error", () => { clearTimeout(timer); resolve(-1); });
|
|
126
|
+
child.on("exit", (c) => { clearTimeout(timer); resolve(c ?? -1); });
|
|
127
|
+
});
|
|
128
|
+
const png = existsSync(out) ? readFileSync(out) : null;
|
|
129
|
+
const size = png && pngSize(png);
|
|
130
|
+
if (code !== 0 || !png || !size || png.length > P.MAX_PREVIEW_BYTES) { ctx.log("preview_failed", { code }); return "unsupported"; }
|
|
131
|
+
const chunks = Math.ceil(png.length / P.PREVIEW_CHUNK_BYTES);
|
|
132
|
+
for (let n = 0; n < chunks; n += 1)
|
|
133
|
+
ctx.emit(null, "preview.image", { preview_id: p.preview_id, chunk: n, chunks, data: P.toBase64Url(png.subarray(n * P.PREVIEW_CHUNK_BYTES, (n + 1) * P.PREVIEW_CHUNK_BYTES)) }, env.command_id);
|
|
134
|
+
ctx.emit(null, "preview.rendered", { preview_id: p.preview_id, project_id: p.project_id, viewport: p.viewport, width: Math.min(size.width, 4096), height: Math.min(size.height, 16_384),
|
|
135
|
+
title: facts.title ? facts.title.slice(0, 300) : null, http_status: p.target === "port" && facts.status >= 100 && facts.status <= 599 ? facts.status : null, bytes: png.length,
|
|
136
|
+
sha256: P.toBase64Url(createHash("sha256").update(png).digest()), chunks }, env.command_id);
|
|
137
|
+
return "taken";
|
|
138
|
+
} finally {
|
|
139
|
+
server?.close();
|
|
140
|
+
rmSync(profile, { recursive: true, force: true });
|
|
141
|
+
busy = false;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return { handle: (env, payload) => (env.type === "preview.targets" ? targets(env, payload) : render(env, payload)) };
|
|
146
|
+
}
|