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.
Files changed (49) hide show
  1. package/LICENSE +43 -18
  2. package/README.md +55 -2
  3. package/SECURITY.md +25 -0
  4. package/engine-release.json +1 -1
  5. package/log-session.mjs +6 -6
  6. package/package-release.json +1 -1
  7. package/package.json +43 -2
  8. package/remote-adapter-claude-code.mjs +113 -0
  9. package/remote-adapter-codex.mjs +159 -0
  10. package/remote-adapter-terminal.mjs +248 -0
  11. package/remote-approval-bridge.mjs +145 -0
  12. package/remote-approvals.mjs +134 -0
  13. package/remote-attachments.mjs +129 -0
  14. package/remote-cdp.mjs +60 -0
  15. package/remote-changes.mjs +94 -0
  16. package/remote-claude-events.mjs +212 -0
  17. package/remote-claude-progress.mjs +328 -0
  18. package/remote-cli.mjs +330 -0
  19. package/remote-coalesce.mjs +40 -0
  20. package/remote-codex-events.mjs +153 -0
  21. package/remote-daemon.mjs +220 -0
  22. package/remote-inventory.mjs +143 -0
  23. package/remote-journal.mjs +155 -0
  24. package/remote-live-preview.mjs +205 -0
  25. package/remote-pairing.mjs +104 -0
  26. package/remote-pipeline-config.mjs +177 -0
  27. package/remote-pipeline-parsers.mjs +121 -0
  28. package/remote-pipeline.mjs +234 -0
  29. package/remote-policy.mjs +199 -0
  30. package/remote-preview.mjs +146 -0
  31. package/remote-projects.mjs +87 -0
  32. package/remote-protocol.mjs +4010 -0
  33. package/remote-qr.mjs +175 -0
  34. package/remote-release-plans.mjs +88 -0
  35. package/remote-releases.mjs +297 -0
  36. package/remote-run.mjs +189 -0
  37. package/remote-screen-approvals.mjs +79 -0
  38. package/remote-screen-push.mjs +76 -0
  39. package/remote-screen-states.mjs +113 -0
  40. package/remote-service.mjs +101 -0
  41. package/remote-session-list.mjs +48 -0
  42. package/remote-sessions.mjs +337 -0
  43. package/remote-steered.mjs +114 -0
  44. package/remote-steering.mjs +97 -0
  45. package/remote-store.mjs +124 -0
  46. package/remote-terminal-cli.mjs +85 -0
  47. package/remote-terminal-sessions.mjs +291 -0
  48. package/remote-transport.mjs +88 -0
  49. package/worktrust.mjs +11 -4
@@ -0,0 +1,205 @@
1
+ /**
2
+ * THE LIVE PREVIEW (release 19, 2026-11-09; owner's preview option A; PROTOCOL.md "The live preview"). The session's
3
+ * granted dev page, live and touchable on the phone: the person's own Chrome, headless, in a throw-away profile, driven over
4
+ * its PIPE (remote-cdp.mjs: never a debugging port), its screencast sent as JPEG frames on the session's transient lane, the
5
+ * phone's taps, scrolls and literal text applied as input events.
6
+ *
7
+ * THE PAGE STAYS ON THE GRANTED ORIGIN, held three ways (each one tested):
8
+ * 1. the network: every request goes to a dead proxy except the granted origin (`--proxy-server` with
9
+ * `--proxy-bypass-list=<-loopback>;127.0.0.1:<port>`), so nothing else is reachable, not even another local port;
10
+ * 2. the DevTools protocol: every request of every frame and worker is paused (Fetch) and continued only for the granted
11
+ * origin; anything else is failed and counted (a document as a navigation, the rest as requests); a page that still
12
+ * lands elsewhere (file://, a scheme) is sent back and counted; a new page (a popup) is closed; a download is denied;
13
+ * a dialog is dismissed; permission prompts are denied by the browser's own switch;
14
+ * 3. the phone: it names a PATH on the granted target, never a URL; input coordinates must lie inside the viewport;
15
+ * text is inserted literally; keys come from a list of three.
16
+ * One live preview per computer. It stops when nobody follows it (LIVE_FOLLOW_MS), when its session closes, when the
17
+ * browser exits, or on follow:false; the browser is ended and its profile and the file server removed.
18
+ */
19
+ import { mkdtempSync, rmSync } from "node:fs";
20
+ import { tmpdir } from "node:os";
21
+ import { join } from "node:path";
22
+ import * as P from "./remote-protocol.mjs";
23
+ import { createCdp, spawnBrowserOnPipe } from "./remote-cdp.mjs";
24
+ import { findBrowser, listening, serveProject } from "./remote-preview.mjs";
25
+
26
+ export const FRAME_MS = 200;
27
+ export const LIVE_FOLLOW_MS = 90_000;
28
+ const KEYCODE = { Enter: 13, Backspace: 8, Tab: 9 };
29
+
30
+ /** The command line: headless, its own profile, on its pipe, and a network that reaches the granted origin only. */
31
+ export function liveArgs({ profile, port }) {
32
+ return ["--headless=new", "--remote-debugging-pipe", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", "--disable-extensions", "--disable-sync",
33
+ "--mute-audio", "--hide-scrollbars", "--disable-background-networking", "--disable-component-update", "--disable-default-apps", "--deny-permission-prompts", "--block-new-web-contents",
34
+ "--proxy-server=127.0.0.1:9", `--proxy-bypass-list=<-loopback>;127.0.0.1:${port}`, "about:blank"];
35
+ }
36
+
37
+ /** The one origin a page may load from: http, 127.0.0.1, the granted (or file server's) port. */
38
+ export const originOk = (url, port) => { try { const u = new URL(url); return u.protocol === "http:" && u.hostname === "127.0.0.1" && u.port === String(port); } catch { return false; } };
39
+ const toB64Url = (s) => s.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
40
+
41
+ // ctx: { emit, projects(), grants(), sessionProject(id), env(), log, now, spawnBrowser?, browser?(), listening?(port), serve?(root), followMs?, frameMs? }
42
+ export function createLivePreview(ctx) {
43
+ let live = null; // one per computer
44
+ const followMs = ctx.followMs ?? LIVE_FOLLOW_MS, frameMs = ctx.frameMs ?? FRAME_MS;
45
+ const later = (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; };
46
+ const state = (l, s, reason = null) => {
47
+ l.state = s;
48
+ ctx.emit(l.session_id, "preview.live", { state: s, viewport: l.viewport, width: l.vp.width, height: l.vp.height, title: l.title, path: l.path, blocked: { ...l.blocked }, reason }, null);
49
+ };
50
+ const block = (l, kind) => { l.blocked[kind] += 1; if (!l.stopped) l.dirty(); };
51
+
52
+ async function stop(l, reason) {
53
+ if (!l || l.stopped) return;
54
+ l.stopped = true;
55
+ clearTimeout(l.expiry); clearTimeout(l.frameTimer);
56
+ if (live === l) live = null;
57
+ // The browser first, then its files: it asked to close, then its process group ended, each with a grace, and only
58
+ // once it is gone the profile is removed (a browser still writing into it would leave it behind).
59
+ const gone = (ms) => { let t; return Promise.race([l.proc.exited.then(() => true), new Promise((r) => { t = setTimeout(() => r(false), ms); })]).finally(() => clearTimeout(t)); }; // held: a stop finishes
60
+ await Promise.race([l.cdp.send("Browser.close").catch(() => {}), gone(2000)]);
61
+ l.cdp.close();
62
+ if (!(await gone(2000))) { l.proc.kill("SIGTERM"); if (!(await gone(2000))) { l.proc.kill("SIGKILL"); await gone(2000); } }
63
+ l.proc.kill("SIGKILL"); // what is left of its group (a renderer, a helper)
64
+ l.server?.close();
65
+ try { rmSync(l.profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch { ctx.log("live_profile_left", {}); }
66
+ state(l, reason === "browser_exited" || reason === "failed" ? "failed" : "stopped", reason);
67
+ }
68
+
69
+ /** Newest frame wins; at most one per frameMs; none unless someone follows (an expired follow stops the preview). */
70
+ function offerFrame(l, frame) {
71
+ l.frame = frame;
72
+ if (l.frameTimer) return;
73
+ const wait = l.sentAt + frameMs - ctx.now();
74
+ const go = () => { l.frameTimer = null; const f = l.frame; l.frame = null; if (!f || l.stopped) return; l.sentAt = ctx.now(); ctx.emit(l.session_id, "preview.frame", f, null, "none", { transient: true }); };
75
+ if (wait <= 0) go(); else l.frameTimer = later(go, wait);
76
+ }
77
+
78
+ async function onEvent(l, method, p, sessionId) {
79
+ const cdp = l.cdp;
80
+ if (method === "Target.attachedToTarget") {
81
+ const sid = p.sessionId, info = p.targetInfo ?? {};
82
+ // The browser's own first page (no opener) is the preview's page; any other page is a popup, closed.
83
+ if (info.type === "page" && !l.targetId && !info.openerId) l.targetId = info.targetId;
84
+ else if (info.type === "page" && info.targetId !== l.targetId) { block(l, "popup"); await cdp.send("Target.closeTarget", { targetId: info.targetId }).catch(() => {}); return; }
85
+ // Every frame and worker of the page passes the same interception, and so do the ones they start.
86
+ await cdp.send("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, sid).catch(() => {});
87
+ await cdp.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }, sid).catch(() => {});
88
+ if (info.targetId === l.targetId && !l.pageSession) await page(l, sid);
89
+ await cdp.send("Runtime.runIfWaitingForDebugger", {}, sid).catch(() => {});
90
+ return;
91
+ }
92
+ if (method === "Fetch.requestPaused") {
93
+ if (originOk(p.request?.url, l.port)) return void cdp.send("Fetch.continueRequest", { requestId: p.requestId }, sessionId).catch(() => {});
94
+ block(l, p.resourceType === "Document" ? "navigation" : "request");
95
+ return void cdp.send("Fetch.failRequest", { requestId: p.requestId, errorReason: "BlockedByClient" }, sessionId).catch(() => {});
96
+ }
97
+ if (method === "Page.frameNavigated" && sessionId === l.pageSession && !p.frame?.parentId) {
98
+ const url = String(p.frame?.url ?? "");
99
+ if (url === "about:blank") return;
100
+ if (originOk(url, l.port)) { l.path = new URL(url).pathname.slice(0, 300) || "/"; l.good = url; return; }
101
+ // A navigation the interception failed lands on the browser's error page: back, counted once (by the interception).
102
+ if (!url.startsWith("chrome-error:")) block(l, url.startsWith("file:") ? "file" : "navigation");
103
+ return void cdp.send("Page.navigate", { url: l.good }, l.pageSession).catch(() => {});
104
+ }
105
+ if (method === "Page.screencastFrame" && sessionId === l.pageSession) {
106
+ cdp.send("Page.screencastFrameAck", { sessionId: p.sessionId }, l.pageSession).catch(() => {});
107
+ const data = toB64Url(String(p.data ?? ""));
108
+ if (Math.floor(data.length * 3 / 4) > P.MAX_FRAME_BYTES) return ctx.log("live_frame_dropped", {});
109
+ const m = p.metadata ?? {};
110
+ offerFrame(l, { width: Math.max(1, Math.min(4096, Math.round(m.deviceWidth ?? l.vp.width))), height: Math.max(1, Math.min(16_384, Math.round(m.deviceHeight ?? l.vp.height))), data });
111
+ if (l.state !== "live") { l.state = "live"; l.dirty(); }
112
+ return;
113
+ }
114
+ if (method === "Page.loadEventFired" && sessionId === l.pageSession) {
115
+ const r = await cdp.send("Runtime.evaluate", { expression: "document.title", returnByValue: true }, l.pageSession).catch(() => null);
116
+ const t = typeof r?.result?.value === "string" ? r.result.value.trim().slice(0, 300) : "";
117
+ l.title = t || null; l.dirty();
118
+ return;
119
+ }
120
+ if (method === "Page.javascriptDialogOpening" && sessionId === l.pageSession) { block(l, "popup"); return void cdp.send("Page.handleJavaScriptDialog", { accept: false }, l.pageSession).catch(() => {}); }
121
+ if (method === "Browser.downloadWillBegin") block(l, "download");
122
+ }
123
+
124
+ async function viewportOf(l) {
125
+ const mobile = l.viewport !== "desktop";
126
+ await l.cdp.send("Page.stopScreencast", {}, l.pageSession).catch(() => {}); // a second start alone keeps the old size
127
+ await l.cdp.send("Emulation.setDeviceMetricsOverride", { width: l.vp.width, height: l.vp.height, deviceScaleFactor: 1, mobile }, l.pageSession).catch(() => {});
128
+ await l.cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: l.vp.width, maxHeight: l.vp.height, everyNthFrame: 1 }, l.pageSession).catch(() => {});
129
+ }
130
+
131
+ async function page(l, sid) {
132
+ l.pageSession = sid;
133
+ await l.cdp.send("Page.enable", {}, sid).catch(() => {});
134
+ await viewportOf(l);
135
+ l.cdp.send("Page.navigate", { url: l.url }, sid).catch(() => {});
136
+ }
137
+
138
+ async function start(env, p) {
139
+ const project = ctx.sessionProject(env.session_id);
140
+ if (!project) return "not_found";
141
+ const g = ctx.grants()[project.project_id] ?? { ports: [], files: [] };
142
+ if (p.target === "port" ? !(g.ports ?? []).includes(p.port) : !(g.files ?? []).includes(p.path)) return "unsupported"; // granted at the keyboard only
143
+ const browser = (ctx.browser ?? (() => findBrowser(ctx.env())))();
144
+ if (!browser) return "unsupported";
145
+ if (live && live.session_id !== env.session_id) return "busy"; // one live preview per computer
146
+ if (live) await stop(live, "stopped");
147
+ if (p.target === "port" && !(await (ctx.listening ?? listening)(p.port))) return "not_found";
148
+ const server = p.target === "file" ? await (ctx.serve ?? serveProject)(project.path) : null;
149
+ const port = p.target === "port" ? p.port : server.port;
150
+ const profile = mkdtempSync(join(tmpdir(), "wt-live-"));
151
+ const l = { session_id: env.session_id, viewport: p.viewport, vp: P.PREVIEW_VIEWPORTS[p.viewport], port, server, profile, title: null, path: p.target === "port" ? p.path : `/${p.path}`, url: `http://127.0.0.1:${port}${p.target === "port" ? p.path : `/${p.path}`}`,
152
+ good: "about:blank", blocked: { ...P.NO_BLOCKS }, state: "starting", stopped: false, sentAt: -Infinity, frame: null, frameTimer: null, expiry: null, pageSession: null, targetId: null };
153
+ let dirtyTimer = null;
154
+ l.dirty = () => { if (!dirtyTimer) dirtyTimer = later(() => { dirtyTimer = null; if (!l.stopped) state(l, l.state); }, 250); };
155
+ l.proc = (ctx.spawnBrowser ?? spawnBrowserOnPipe)(browser, liveArgs({ profile: join(profile, "p"), port }), ctx.env());
156
+ l.cdp = createCdp({ write: l.proc.write, onEvent: (m, params, sid) => { onEvent(l, m, params, sid).catch(() => {}); } });
157
+ l.proc.onData((chunk) => l.cdp.feed(chunk));
158
+ l.proc.exited.then(() => { if (!l.stopped) stop(l, "browser_exited"); });
159
+ live = l;
160
+ l.expiry = later(() => stop(l, "unfollowed"), followMs);
161
+ state(l, "starting");
162
+ try {
163
+ await l.cdp.send("Browser.setDownloadBehavior", { behavior: "deny", eventsEnabled: true });
164
+ await l.cdp.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
165
+ // A browser that attached no first page of its own is given one (its attach event makes it the preview's page).
166
+ later(() => { if (!l.targetId && !l.stopped) l.cdp.send("Target.createTarget", { url: "about:blank" }).catch(() => {}); }, 1500);
167
+ } catch { await stop(l, "failed"); return "unsupported"; }
168
+ return "taken";
169
+ }
170
+
171
+ async function input(l, i) {
172
+ if (i.kind === "tap" || i.kind === "scroll") {
173
+ if (i.x >= l.vp.width || i.y >= l.vp.height) return "unsupported"; // inside the viewport only
174
+ if (i.kind === "scroll") return (await l.cdp.send("Input.dispatchMouseEvent", { type: "mouseWheel", x: i.x, y: i.y, deltaX: 0, deltaY: i.dy }, l.pageSession).then(() => "taken", () => "not_found"));
175
+ for (const type of ["mousePressed", "mouseReleased"]) await l.cdp.send("Input.dispatchMouseEvent", { type, x: i.x, y: i.y, button: "left", clickCount: 1 }, l.pageSession).catch(() => {});
176
+ return "taken";
177
+ }
178
+ if (i.kind === "text") { if (!P.liveTextOk(i.text)) return "unsupported"; return l.cdp.send("Input.insertText", { text: i.text }, l.pageSession).then(() => "taken", () => "not_found"); }
179
+ if (!Object.hasOwn(KEYCODE, i.key)) return "unsupported";
180
+ const code = KEYCODE[i.key];
181
+ await l.cdp.send("Input.dispatchKeyEvent", { type: "keyDown", key: i.key, code: i.key, windowsVirtualKeyCode: code, ...(i.key === "Enter" ? { text: "\r" } : {}) }, l.pageSession).catch(() => {});
182
+ await l.cdp.send("Input.dispatchKeyEvent", { type: "keyUp", key: i.key, code: i.key, windowsVirtualKeyCode: code }, l.pageSession).catch(() => {});
183
+ return "taken";
184
+ }
185
+
186
+ return {
187
+ current: () => live,
188
+ async handle(env, payload) {
189
+ if (env.type === "preview.live_start") return start(env, payload);
190
+ const l = live && live.session_id === env.session_id ? live : null;
191
+ if (!l || l.stopped) return "not_found";
192
+ if (env.type === "preview.live_follow") {
193
+ if (!payload.follow) { await stop(l, "stopped"); return "taken"; }
194
+ clearTimeout(l.expiry); l.expiry = later(() => stop(l, "unfollowed"), followMs);
195
+ return "taken";
196
+ }
197
+ if (env.type === "preview.live_viewport") { l.viewport = payload.viewport; l.vp = P.PREVIEW_VIEWPORTS[payload.viewport]; await viewportOf(l); l.dirty(); return "taken"; }
198
+ if (env.type === "preview.live_input") return input(l, payload);
199
+ return "unsupported";
200
+ },
201
+ /** The session closed: its live preview ends. */
202
+ sessionClosed: (sessionId) => (live && live.session_id === sessionId ? stop(live, "closed") : undefined),
203
+ stopAll: () => (live ? stop(live, "stopped") : undefined),
204
+ };
205
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * BINDING THIS COMPUTER'S REMOTE KEYS TO THE PERSON'S ACCOUNT (2026-11-07; docs/remote-agents/ISSUER.md is the contract).
3
+ *
4
+ * The same shape as `worktrust connect`, on its own audience and with its own key: this terminal listens on 127.0.0.1 for
5
+ * one answer, holds a PKCE verifier, and sends only the PUBLIC halves of a fresh remote key pair with a proof that it holds
6
+ * them. The person approves in the Passport app, signed in, with their second factor; the browser comes back to
7
+ * 127.0.0.1 with a one-time code that only this terminal, with its verifier, can exchange for the issuer's signed binding.
8
+ * Without a browser (`--device`, SSH) a typed code instead. The binding is verified against the issuer keys pinned in this
9
+ * release before anything is saved. A Passport app without the issuer answers 404, and this says so and changes nothing.
10
+ * The measurement key is never read, sent or used here.
11
+ */
12
+ import { createHash, randomBytes } from "node:crypto";
13
+ import { createServer } from "node:http";
14
+ import * as P from "./remote-protocol.mjs";
15
+
16
+ const PROOF = P.utf8Encode("worktrust-remote/v1/pair-request\n");
17
+ const RENEW = P.utf8Encode("worktrust-remote/v1/renew\n");
18
+ export const pairProofBytes = (body) => P.concatBytes(PROOF, P.canonicalBytes(body));
19
+ export const renewBytes = (body) => P.concatBytes(RENEW, P.canonicalBytes(body));
20
+
21
+ export class IssuerMissing extends Error {}
22
+ export class PairingRefused extends Error {}
23
+
24
+ async function post(origin, path, body) {
25
+ const response = await fetch(`${origin}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(20_000) });
26
+ return { status: response.status, json: await response.json().catch(() => ({})) };
27
+ }
28
+
29
+ /** Pair, and return the verified binding. `keys` holds the secret pair (never sent), `issuerKeys` the pinned keys. */
30
+ export async function pairComputer({ origin, secret, publicKeys, host, os, device = false, issuerKeys, say, openBrowser, now = Date.now }) {
31
+ const verifier = randomBytes(32).toString("base64url");
32
+ const code_challenge = createHash("sha256").update(verifier).digest("base64url");
33
+ const state = randomBytes(24).toString("base64url");
34
+ const claim = { code_challenge, ed25519_pub: publicKeys.ed25519_pub, kind: "computer", x25519_pub: publicKeys.x25519_pub };
35
+ const proof = P.toBase64Url(P.ed25519Sign(pairProofBytes(claim), secret.ed25519));
36
+ let server = null, deliver = null;
37
+ const answer = new Promise((resolve) => { deliver = resolve; });
38
+ if (!device) {
39
+ server = createServer((request, response) => {
40
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
41
+ if (url.pathname !== "/callback" || url.searchParams.get("state") !== state || !url.searchParams.get("code")) { response.writeHead(404).end(); return; }
42
+ response.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" }).end("This computer is approved for WorkTrust remote. Return to your terminal.");
43
+ deliver(url.searchParams.get("code"));
44
+ });
45
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
46
+ }
47
+ try {
48
+ const pairing = await post(origin, "/api/remote/pair", { flow: device ? "device" : "loopback", host, os, ...claim, code_challenge_method: "S256", proof, ...(device ? {} : { port: server.address().port, state }) }).catch(() => null);
49
+ if (!pairing) throw new PairingRefused(`cannot reach ${origin}`);
50
+ if (pairing.status === 404) throw new IssuerMissing(`${origin} has no remote-key issuer yet (POST /api/remote/pair answered 404). Nothing was changed; remote control needs a Passport app with the issuer (docs/remote-agents/ISSUER.md).`);
51
+ if (pairing.status !== 200) throw new PairingRefused(`pairing refused (${pairing.json.error ?? pairing.status})`);
52
+ const { device_code, user_code, expires_in = 600, interval = 3, authorize_url, verification_uri, features = [] } = pairing.json;
53
+ if (!features.includes("remote-binding-v1")) throw new PairingRefused(`${origin} does not offer remote bindings (remote-binding-v1)`);
54
+ const fingerprint = P.deviceFingerprint(publicKeys);
55
+ say(` Your code: ${user_code} This computer's remote key: ${fingerprint}`);
56
+ say(" Approve only if the WorkTrust page shows the same code and key.");
57
+ let exchanged = null;
58
+ if (!device) {
59
+ say(` Approve in your browser (opening it). If it does not open: ${authorize_url}`);
60
+ openBrowser(authorize_url);
61
+ const timer = setTimeout(() => deliver(null), expires_in * 1000);
62
+ const code = await answer;
63
+ clearTimeout(timer);
64
+ if (!code) throw new PairingRefused("no approval arrived in time");
65
+ exchanged = await post(origin, "/api/remote/token", { device_code, code, code_verifier: verifier });
66
+ } else {
67
+ say(` On any device open ${verification_uri} and type the code.`);
68
+ const until = now() + expires_in * 1000;
69
+ let wait = interval * 1000;
70
+ while (now() < until) {
71
+ await new Promise((resolve) => setTimeout(resolve, wait));
72
+ const reply = await post(origin, "/api/remote/token", { device_code, code_verifier: verifier }).catch(() => null);
73
+ if (reply?.status === 200) { exchanged = reply; break; }
74
+ if (reply?.json?.error === "slow_down") wait += 2000;
75
+ else if (reply?.json?.error && reply.json.error !== "authorization_pending") throw new PairingRefused(`pairing ended (${reply.json.error})`);
76
+ }
77
+ }
78
+ if (!exchanged || exchanged.status !== 200 || typeof exchanged.json.binding !== "string") throw new PairingRefused(`the approval could not be exchanged (${exchanged?.json?.error ?? "no answer"})`);
79
+ if (Object.keys(issuerKeys).length === 0) throw new PairingRefused("this release pins no WorkTrust issuer key yet, so the binding cannot be verified; nothing was saved");
80
+ const verified = P.verifyBinding(exchanged.json.binding, { issuerKeys, now: now(), kind: "computer", deviceId: exchanged.json.device_id });
81
+ if (!verified.ok) throw new PairingRefused(`the binding does not verify (${verified.code}); nothing was saved`);
82
+ if (verified.value.ed25519_pub !== publicKeys.ed25519_pub || verified.value.x25519_pub !== publicKeys.x25519_pub) throw new PairingRefused("the binding names other keys; nothing was saved");
83
+ return { binding: exchanged.json.binding, device_id: verified.value.device_id, sub: verified.value.sub, exp: verified.value.exp, account: typeof exchanged.json.account === "string" ? exchanged.json.account.slice(0, 120) : null };
84
+ } finally { server?.close(); }
85
+ }
86
+
87
+ /** A fresh binding for the same keys before the old one ends (POST /api/remote/renew). Null when the issuer has none. */
88
+ export async function renewBinding({ origin, identity, secret, now = Date.now }) {
89
+ const jti = JSON.parse(Buffer.from(identity.binding.split(".")[1], "base64url").toString("utf8")).jti;
90
+ const body = { binding_jti: jti, device_id: identity.device_id, iat: now() };
91
+ const reply = await post(origin, "/api/remote/renew", { binding: identity.binding, iat: body.iat, signature: P.toBase64Url(P.ed25519Sign(renewBytes(body), secret.ed25519)) }).catch(() => null);
92
+ return reply?.status === 200 && typeof reply.json.binding === "string" ? reply.json.binding : null;
93
+ }
94
+
95
+ /**
96
+ * A FIVE-MINUTE GATEWAY ASSERTION (POST /api/remote/assertion, ISSUER.md §5): asked fresh for every gateway challenge,
97
+ * signed by this computer's REMOTE key over its device id, the time and a fresh nonce. Null when the issuer refuses or is
98
+ * unreachable: the gateway then refuses this connection and the transport backs off; nothing else changes.
99
+ */
100
+ export async function requestAssertion({ origin, deviceId, secret, now = Date.now, random = (n) => new Uint8Array(randomBytes(n)) }) {
101
+ const body = { device_id: deviceId, iat: now(), nonce: P.toBase64Url(random(32)) };
102
+ const reply = await post(origin, "/api/remote/assertion", { ...body, signature: P.toBase64Url(P.ed25519Sign(P.assertionRequestBytes(body), secret.ed25519)) }).catch(() => null);
103
+ return reply?.status === 200 && typeof reply.json.assertion === "string" && reply.json.assertion.length <= 4096 ? reply.json.assertion : null;
104
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * THE PERSON'S PIPELINE FILE, READ AND HELD TO AN ALLOWLIST (owner, 2026-11-07; docs/remote-agents/PROTOCOL.md "Pipelines").
3
+ *
4
+ * A project's stages live in `.worktrust/pipeline.json`, which the PERSON writes and reviews at the keyboard
5
+ * (`worktrust remote pipeline review <folder>` prints every stage and command and pins a hash of the file and of the
6
+ * package.json scripts it names). The daemon runs a pipeline only while that hash still holds: an agent (or anyone) that
7
+ * edits the file or a named script after the review makes the pipeline `unreviewed` until the person looks again.
8
+ *
9
+ * A stage's `run` is one of five forms, split on single spaces, no quoting, no shell, every token from a safe character
10
+ * set and no `..` segment:
11
+ * pnpm <script> | pnpm run <script> | npm run <script> a script the project's package.json names, always run as
12
+ * `<pnpm|npm> run <script>` (never a package manager built-in such
13
+ * as install, add or publish)
14
+ * node scripts/<file>.(mjs|js|cjs) [args] a file inside the project's scripts folder
15
+ * semgrep [scan] <flags> [target] a local scan; `semgrep ci` (which uploads) is refused
16
+ * zap-baseline.py <flags> against a loopback target only (http://localhost, 127.0.0.1)
17
+ * A stage of kind deploy or publish has no `run`: it is a step at the desk, never run by the daemon. A stage whose script
18
+ * or file is named like a deploy (deploy, publish, ship, push, promote, rollout, upload) is refused as well, whatever its
19
+ * kind: those stay in the ship scripts at the computer (owner rule). Pure: the caller passes the file's text and the
20
+ * package.json scripts.
21
+ */
22
+ import { createHash } from "node:crypto";
23
+ import * as P from "./remote-protocol.mjs";
24
+
25
+ export const PIPELINE_FILE = ".worktrust/pipeline.json";
26
+ export const MAX_CONFIG_BYTES = 65_536;
27
+ const TOP_KEYS = new Set(["version", "run_after_tasks", "path_prepend", "stages"]);
28
+ const STAGE_KEYS = new Set(["id", "label", "kind", "run", "parser", "report", "timeout_min", "fail_on"]);
29
+ const STAGE_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
30
+ const SAFE_TOKEN = /^[A-Za-z0-9@%+=:,./_-]+$/;
31
+ const SCRIPT_NAME = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,99}$/;
32
+ const NODE_FILE = /^scripts\/[A-Za-z0-9._/-]+\.(mjs|js|cjs)$/;
33
+ const REPORT = /^[A-Za-z0-9._/-]+\.(json|xml)$/;
34
+ const DEPLOY_WORDS = /(^|[:._/-])(deploy|deployment|publish|ship|push|promote|rollout|upload)([:._/-]|$)/i;
35
+ /**
36
+ * A deploy or a publish in a script's TEXT (review 2026-11-07, P2-3): a deploy tool in command position, a package
37
+ * manager's publish or deploy, a git push, a GitHub release. Applied to the named script and its pre/post hooks.
38
+ */
39
+ const DEPLOY_TEXT = /(^|&&|\|\||[;|(]|\bnpx\s+|\bdlx\s+)\s*(vercel|netlify|fly|flyctl|firebase|heroku|wrangler|serverless|sls|kubectl|helm|terraform|pulumi|eas|railway|render)(\s|$)|\b(npm|pnpm|yarn|bun)\s+(run\s+)?(publish|deploy)\b|\bgit\s+push\b|\bgh\s+release\b/;
40
+ const SEVERITIES = ["high", "medium", "low", "none"];
41
+ const SEMGREP_FLAGS = new Set(["--json", "--metrics=off", "--error", "--quiet", "-q", "--no-git-ignore", "--disable-version-check", "--oss-only"]);
42
+ /** A rules source semgrep reads: a registry pack by name, or a file inside the project; never a URL or `auto` (P3-10). */
43
+ const SEMGREP_CONFIG = /^(p\/[a-z0-9][a-z0-9_-]{0,63}|[A-Za-z0-9._/-]+\.(ya?ml))$/;
44
+ const SEMGREP_VALUED = new Set(["--config", "--exclude", "--include", "--severity", "--timeout", "--jobs", "--max-target-bytes"]);
45
+ const ZAP_FLAGS = new Set(["-I", "-j", "-a", "-s", "-d"]);
46
+ const ZAP_VALUED = new Set(["-t", "-J", "-x", "-m", "-T"]); // no -c (a rules file) or -z (raw ZAP options): the list stays this short
47
+ const LOOPBACK = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?(\/[A-Za-z0-9._~/%-]*)?$/;
48
+
49
+ const refuse = (detail) => ({ ok: false, detail });
50
+ const relativeOk = (p) => typeof p === "string" && !p.startsWith("/") && !p.split("/").some((s) => s === ".." || s === "") && SAFE_TOKEN.test(p);
51
+
52
+ /**
53
+ * One stage's command as argv, or why not. `scripts` is package.json's scripts object (or null). Run time calls this
54
+ * again on every stage, so a config read earlier cannot smuggle a command past a later check.
55
+ */
56
+ export function allowCommand(run, scripts) {
57
+ if (typeof run !== "string" || run.length === 0 || run.length > 500) return refuse("run: not a command line");
58
+ const tokens = run.split(" ");
59
+ if (tokens.some((t) => t === "" || !SAFE_TOKEN.test(t) || t.split("/").includes(".."))) return refuse("run: only plain words, single spaces, no shell characters, no ..");
60
+ const [head, ...rest] = tokens;
61
+ const scriptOf = (name) => {
62
+ if (!SCRIPT_NAME.test(name ?? "")) return refuse("run: not a script name");
63
+ if (!scripts || typeof scripts[name] !== "string") return refuse(`run: package.json names no script ${name}`);
64
+ if (DEPLOY_WORDS.test(name)) return refuse(`run: ${name} is a deploy or publish; it stays at your desk`);
65
+ for (const hook of [name, `pre${name}`, `post${name}`]) if (typeof scripts[hook] === "string" && DEPLOY_TEXT.test(scripts[hook])) return refuse(`run: the script ${hook} deploys or publishes; it stays at your desk`);
66
+ return null;
67
+ };
68
+ if (head === "pnpm" || head === "npm") {
69
+ const name = rest[0] === "run" ? rest[1] : head === "pnpm" ? rest[0] : undefined;
70
+ const used = rest[0] === "run" ? 2 : 1;
71
+ if (name === undefined || rest.length !== used) return refuse(`run: ${head} takes exactly one script${head === "npm" ? " (npm run <script>)" : ""}`);
72
+ const bad = scriptOf(name);
73
+ return bad ?? { ok: true, file: head, args: ["run", name], form: "script", script: name };
74
+ }
75
+ if (head === "node") {
76
+ const [file, ...args] = rest;
77
+ if (!NODE_FILE.test(file ?? "")) return refuse("run: node runs a file under scripts/ only");
78
+ if (DEPLOY_WORDS.test(file)) return refuse(`run: ${file} is a deploy or publish; it stays at your desk`);
79
+ if (args.some((a) => a.startsWith("--") && /^--(eval|require|import|loader|inspect)/.test(a))) return refuse("run: no node flags");
80
+ return { ok: true, file: "node", args: [file, ...args], form: "node", script: file };
81
+ }
82
+ if (head === "semgrep") {
83
+ const args = rest[0] === "scan" ? rest.slice(1) : rest;
84
+ if (rest[0] === "ci" || rest[0] === "login" || rest[0] === "publish") return refuse("run: semgrep scans locally only");
85
+ for (let i = 0; i < args.length; i += 1) {
86
+ const a = args[i];
87
+ const [flag, value] = a.includes("=") ? [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)] : [a, null];
88
+ if (SEMGREP_FLAGS.has(a)) continue;
89
+ if (SEMGREP_VALUED.has(flag)) {
90
+ const v = value ?? args[++i];
91
+ if (!v || v.startsWith("-")) return refuse(`run: ${flag} needs a value`);
92
+ if (flag === "--config" && !(SEMGREP_CONFIG.test(v) && (v.startsWith("p/") || relativeOk(v)))) return refuse("run: --config is a registry pack (p/<name>) or a rules file in the project");
93
+ continue;
94
+ }
95
+ if (i === args.length - 1 && !a.startsWith("-") && relativeOk(a)) continue; // the target folder
96
+ return refuse(`run: semgrep ${a} is not on the list`);
97
+ }
98
+ if (!args.includes("--metrics=off")) return refuse("run: semgrep runs with --metrics=off");
99
+ return { ok: true, file: "semgrep", args: rest[0] === "scan" ? rest : ["scan", ...rest], form: "semgrep", script: null };
100
+ }
101
+ if (head === "zap-baseline.py") {
102
+ let target = null;
103
+ for (let i = 0; i < rest.length; i += 1) {
104
+ const a = rest[i];
105
+ if (ZAP_FLAGS.has(a)) continue;
106
+ if (!ZAP_VALUED.has(a)) return refuse(`run: zap-baseline.py ${a} is not on the list`);
107
+ const v = rest[++i];
108
+ if (!v) return refuse(`run: ${a} needs a value`);
109
+ if (a === "-t") target = v;
110
+ if ((a === "-J" || a === "-x") && !relativeOk(v)) return refuse(`run: ${a} writes or reads inside the project only`);
111
+ }
112
+ if (!target || !LOOPBACK.test(target)) return refuse("run: ZAP scans a loopback target only (http://localhost or 127.0.0.1)");
113
+ return { ok: true, file: "zap-baseline.py", args: rest, form: "zap", script: null };
114
+ }
115
+ return refuse(`run: ${head} is not on the allowlist (pnpm, npm run, node scripts/…, semgrep, zap-baseline.py)`);
116
+ }
117
+
118
+ /** The file's text and package.json's scripts → { ok, config } with every stage checked, or the first refusal. */
119
+ export function parsePipelineConfig(text, scripts) {
120
+ if (typeof text !== "string" || Buffer.byteLength(text) > MAX_CONFIG_BYTES) return refuse("the file is missing or larger than 64 KB");
121
+ let raw;
122
+ try { raw = JSON.parse(text); } catch { return refuse("the file is not JSON"); }
123
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return refuse("the file is not an object");
124
+ const extra = Object.keys(raw).find((k) => !TOP_KEYS.has(k));
125
+ if (extra) return refuse(`unknown key ${extra}`);
126
+ if (raw.version !== 1) return refuse("version must be 1");
127
+ if (raw.run_after_tasks !== undefined && typeof raw.run_after_tasks !== "boolean") return refuse("run_after_tasks is true or false");
128
+ const prepend = raw.path_prepend ?? [];
129
+ if (!Array.isArray(prepend) || prepend.length > 8 || prepend.some((d) => typeof d !== "string" || !d.startsWith("/") || !SAFE_TOKEN.test(d) || d.split("/").includes(".."))) return refuse("path_prepend is a list of absolute folders");
130
+ if (!Array.isArray(raw.stages) || raw.stages.length === 0 || raw.stages.length > P.MAX_PIPELINE_STAGES) return refuse(`stages: 1 to ${P.MAX_PIPELINE_STAGES}`);
131
+ const ids = new Set();
132
+ const stages = [];
133
+ for (const [n, s] of raw.stages.entries()) {
134
+ const at = `stages[${n}]`;
135
+ if (!s || typeof s !== "object" || Array.isArray(s)) return refuse(`${at}: not an object`);
136
+ const unknown = Object.keys(s).find((k) => !STAGE_KEYS.has(k));
137
+ if (unknown) return refuse(`${at}: unknown key ${unknown}`);
138
+ if (!STAGE_ID.test(s.id ?? "") || ids.has(s.id)) return refuse(`${at}.id: [a-z0-9_-], once`);
139
+ ids.add(s.id);
140
+ if (typeof s.label !== "string" || s.label.trim() === "" || s.label.length > 200) return refuse(`${at}.label: 1 to 200 characters`);
141
+ if (!P.STAGE_KINDS.includes(s.kind)) return refuse(`${at}.kind: one of ${P.STAGE_KINDS.join(", ")}`);
142
+ const desk = P.DESK_STAGE_KINDS.has(s.kind);
143
+ if (desk) {
144
+ if (Object.keys(s).some((k) => !["id", "label", "kind"].includes(k))) return refuse(`${at}: a ${s.kind} stage is a step at your desk; it has no run`);
145
+ stages.push({ id: s.id, label: s.label, kind: s.kind, desk: true });
146
+ continue;
147
+ }
148
+ const parser = s.parser ?? "none";
149
+ if (!P.PIPELINE_PARSERS.includes(parser)) return refuse(`${at}.parser: one of ${P.PIPELINE_PARSERS.join(", ")}`);
150
+ const cmd = allowCommand(s.run, scripts);
151
+ if (!cmd.ok) return refuse(`${at}.${cmd.detail}`);
152
+ if (s.report !== undefined && !(typeof s.report === "string" && REPORT.test(s.report) && relativeOk(s.report))) return refuse(`${at}.report: a .json or .xml file inside the project`);
153
+ const timeout = s.timeout_min ?? 30;
154
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 120) return refuse(`${at}.timeout_min: 1 to 120`);
155
+ const failOn = s.fail_on ?? (parser === "semgrep_json" || parser === "zap_json" ? "high" : "none");
156
+ if (!SEVERITIES.includes(failOn)) return refuse(`${at}.fail_on: high, medium, low or none`);
157
+ stages.push({ id: s.id, label: s.label, kind: s.kind, desk: false, run: s.run, parser, report: s.report ?? null, timeout_ms: timeout * 60_000, fail_on: failOn });
158
+ }
159
+ return { ok: true, config: { run_after_tasks: raw.run_after_tasks ?? true, path_prepend: prepend, stages } };
160
+ }
161
+
162
+ /** The project files a `node scripts/<file>` stage runs, so their bytes are part of what the person reviewed. */
163
+ export function namedFiles(text, scripts) {
164
+ const parsed = parsePipelineConfig(text, scripts);
165
+ return parsed.ok ? [...new Set(parsed.config.stages.flatMap((s) => { const c = s.desk ? null : allowCommand(s.run, scripts); return c?.form === "node" ? [c.script] : []; }))] : [];
166
+ }
167
+
168
+ /**
169
+ * What the person reviewed (review 2026-11-07, P2-1/P2-2): the file's bytes, package.json's WHOLE scripts object (so a new
170
+ * pre or post hook is a change), the project's .npmrc (script-shell, node-options), and the bytes of every file a
171
+ * `node scripts/<file>` stage runs. `extras` is { npmrc: text | null, files: { path: text | null } } from the project.
172
+ * A changed byte in any of them is a new pipeline that needs a new review.
173
+ */
174
+ export function reviewHash(text, scripts, extras = { npmrc: null, files: {} }) {
175
+ const files = Object.fromEntries(namedFiles(text, scripts).map((f) => [f, createHash("sha256").update(extras.files?.[f] ?? "\u0000absent").digest("hex")]));
176
+ return createHash("sha256").update(P.canonicalJson({ file: text, scripts: scripts ?? null, npmrc: extras.npmrc ?? null, files })).digest("hex");
177
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * WHAT A STAGE'S TOOL REPORTED, COUNTED (owner, 2026-11-07: "400 / 500 tests" only when a tool said so). Pure functions
3
+ * over a tool's own report text. Each returns `{ measured?, findings? }` with only what it could read: a report that does
4
+ * not parse gives `{}`, never a guess and never a zero. `measured` is { done, total, failed, unit }: tests that ran over
5
+ * the tests there are (done = passed + failed + skipped), failed among them. `findings` is { high, medium, low } from a
6
+ * scanner. Tested against recorded fixtures in scripts/fixtures/remote/pipeline/.
7
+ *
8
+ * tap TAP 13/14 (node --test --test-reporter=tap, tape, …): the `# tests/pass/fail` summary when present,
9
+ * else the top-level `ok`/`not ok` lines over the plan `1..N`; `createTapCounter` counts while it streams
10
+ * node_test the node test runner's spec summary (ℹ tests / pass / fail / skipped / todo / cancelled)
11
+ * junit_xml <testsuites tests failures errors skipped>, else the sum of its <testsuite> elements
12
+ * vitest_json Vitest's json reporter (Jest's shape): numTotalTests, numFailedTests …
13
+ * jest_json the same fields from Jest
14
+ * semgrep_json results[].extra.severity ERROR / WARNING / INFO → high / medium / low; paths.scanned as files
15
+ * zap_json site[].alerts[].riskcode 3 / 2 / 1 → high / medium / low (0, informational, is not a finding)
16
+ */
17
+ const int = (v) => (typeof v === "number" ? v : typeof v === "string" && /^\d+$/.test(v) ? Number(v) : null);
18
+ const measured = (total, failed, unit = "tests") => (Number.isSafeInteger(total) && total > 0 && Number.isSafeInteger(failed) && failed >= 0 && failed <= total ? { measured: { done: total, total, failed, unit } } : {});
19
+
20
+ function jsonOf(text) {
21
+ try { return JSON.parse(text); } catch { /* a reporter may print around its JSON */ }
22
+ const from = text.indexOf("{"), to = text.lastIndexOf("}");
23
+ if (from < 0 || to <= from) return null;
24
+ try { return JSON.parse(text.slice(from, to + 1)); } catch { return null; }
25
+ }
26
+
27
+ export function parseTap(text) {
28
+ const summary = {};
29
+ for (const m of text.matchAll(/^#\s+(tests|pass|fail|skipped|todo|cancelled)\s+(\d+)\s*$/gm)) summary[m[1]] = Number(m[2]);
30
+ if (summary.tests !== undefined) return measured(summary.tests, (summary.fail ?? 0) + (summary.cancelled ?? 0));
31
+ let ok = 0, notOk = 0, plan = null;
32
+ for (const line of text.split("\n")) {
33
+ if (/^ok\s+\d+/.test(line)) ok += 1;
34
+ else if (/^not ok\s+\d+/.test(line)) notOk += 1;
35
+ else if (/^1\.\.(\d+)\s*$/.test(line)) plan = Number(/^1\.\.(\d+)/.exec(line)[1]);
36
+ }
37
+ if (plan === null || ok + notOk !== plan) return {}; // a cut stream: the denominator is not known
38
+ return measured(plan, notOk);
39
+ }
40
+
41
+ /** While TAP streams: tests seen so far, and the plan once a producer printed it first. */
42
+ export function createTapCounter() {
43
+ let carry = "", ok = 0, notOk = 0, plan = null;
44
+ return {
45
+ feed(chunk) {
46
+ const lines = (carry + chunk).split("\n");
47
+ carry = lines.pop() ?? "";
48
+ for (const line of lines) {
49
+ if (/^ok\s+\d+/.test(line)) ok += 1;
50
+ else if (/^not ok\s+\d+/.test(line)) notOk += 1;
51
+ else if (/^1\.\.(\d+)\s*$/.test(line)) plan = Number(/^1\.\.(\d+)/.exec(line)[1]);
52
+ }
53
+ },
54
+ /** A measured count only with a plan that covers what was seen; else nothing (no bar from a guess). */
55
+ now: () => (plan !== null && plan > 0 && ok + notOk <= plan ? { done: ok + notOk, total: plan, failed: notOk, unit: "tests" } : null),
56
+ };
57
+ }
58
+
59
+ export function parseNodeTest(text) {
60
+ const s = {};
61
+ for (const m of text.matchAll(/^\s*(?:ℹ|#)\s+(tests|pass|fail|skipped|todo|cancelled)\s+(\d+)\s*$/gm)) s[m[1]] = Number(m[2]);
62
+ return s.tests === undefined ? {} : measured(s.tests, (s.fail ?? 0) + (s.cancelled ?? 0));
63
+ }
64
+
65
+ const attrs = (tag) => Object.fromEntries([...tag.matchAll(/\s([a-z]+)="([^"]*)"/gi)].map((m) => [m[1].toLowerCase(), m[2]]));
66
+ export function parseJunitXml(text) {
67
+ const root = /<testsuites\b[^>]*>/i.exec(text)?.[0];
68
+ const a = root ? attrs(root) : null;
69
+ if (a && int(a.tests) !== null) return measured(int(a.tests), (int(a.failures) ?? 0) + (int(a.errors) ?? 0));
70
+ let tests = 0, failed = 0, seen = 0;
71
+ for (const m of text.matchAll(/<testsuite\b[^>]*>/gi)) {
72
+ const s = attrs(m[0]);
73
+ if (int(s.tests) === null) return {};
74
+ seen += 1; tests += int(s.tests); failed += (int(s.failures) ?? 0) + (int(s.errors) ?? 0);
75
+ }
76
+ return seen === 0 ? {} : measured(tests, failed);
77
+ }
78
+
79
+ export function parseJestJson(text) {
80
+ const j = jsonOf(text);
81
+ if (!j || int(j.numTotalTests) === null || int(j.numFailedTests) === null) return {};
82
+ return measured(int(j.numTotalTests), int(j.numFailedTests));
83
+ }
84
+
85
+ export function parseSemgrepJson(text) {
86
+ const j = jsonOf(text);
87
+ if (!j || !Array.isArray(j.results)) return {};
88
+ const findings = { high: 0, medium: 0, low: 0 };
89
+ for (const r of j.results) {
90
+ const sev = String(r?.extra?.severity ?? "").toUpperCase();
91
+ if (sev === "ERROR" || sev === "CRITICAL" || sev === "HIGH") findings.high += 1;
92
+ else if (sev === "WARNING" || sev === "MEDIUM") findings.medium += 1;
93
+ else findings.low += 1;
94
+ }
95
+ const scanned = Array.isArray(j.paths?.scanned) ? j.paths.scanned.length : 0;
96
+ return { findings, ...(scanned > 0 ? { measured: { done: scanned, total: scanned, failed: 0, unit: "files" } } : {}) };
97
+ }
98
+
99
+ export function parseZapJson(text) {
100
+ const j = jsonOf(text);
101
+ if (!j || !Array.isArray(j.site)) return {};
102
+ const findings = { high: 0, medium: 0, low: 0 };
103
+ for (const site of j.site) for (const alert of Array.isArray(site?.alerts) ? site.alerts : []) {
104
+ const risk = int(alert?.riskcode);
105
+ if (risk === 3) findings.high += 1; else if (risk === 2) findings.medium += 1; else if (risk === 1) findings.low += 1;
106
+ }
107
+ return { findings };
108
+ }
109
+
110
+ export const PARSERS = { tap: parseTap, node_test: parseNodeTest, junit_xml: parseJunitXml, vitest_json: parseJestJson, jest_json: parseJestJson, semgrep_json: parseSemgrepJson, zap_json: parseZapJson };
111
+
112
+ /** The parser's reading of a report, `{}` for `none` or an unknown parser. */
113
+ export const readReport = (parser, text) => (typeof text === "string" && Object.hasOwn(PARSERS, parser) ? PARSERS[parser](text) : {});
114
+
115
+ /** A scanner stage fails on a finding at or above its threshold; `none` never fails on findings. */
116
+ export function findingsFail(findings, failOn) {
117
+ if (!findings || failOn === "none") return false;
118
+ if (failOn === "high") return findings.high > 0;
119
+ if (failOn === "medium") return findings.high + findings.medium > 0;
120
+ return findings.high + findings.medium + findings.low > 0;
121
+ }