Files
loki/scripts/inspection-worker.ts
CatoandClaude Opus 5.5 dd44fac73e feat(review): take over the browser, hand it back, and see what comes next (#1545)
* feat(orangecat): a bot can ask Loki, as the person

POST /api/orangecat/ask on the signed OrangeCat rail: one of the person's
OrangeCat bots asks Loki a question and the turn runs as the Loki user
linked to that actor, read-only, so a relayed question can never dispatch,
approve or spend. An unlinked actor is told the one step that links it.
Door test: no secret, no signature, a tampered or oversize body are all
refused before a database or a model is reached.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmrXvMqAqZtbpQ4x3et

* feat(review): take over the browser, hand it back, and see what comes next

The owner, 2026-11-02, beside Grok Bot's live Handler: "I want to see how
the machine is being used and click through", led through it and in
control, "and it should be objectively so". The project review's browser is
the fleet's one agent-driven browser, so it gets that first.

- Take over: the person's clicks on the picture, wheel scrolls, typed text,
  Enter and Back reach the page; each answers with a fresh picture, and the
  screen polls faster while they drive. Hand back returns it: the worker
  goes back to the page and scroll it was on, finishes that page so its
  notes stay about the right page, then reviews the person's page next.
- Inputs are data (two coordinates, at most 200 characters, one of ten
  keys), queued atomically in site_reviews.control (migration 0132, one
  column) and taken by the worker in one statement at its checkpoint. The
  read-only guard is unchanged for the person: a form button sends nothing.
- Under the picture: Live/You, what Loki does now, the next page, pages done.
- Tests: real-Chromium take over (inspection-takeover-browser.ts); the
  workspace test drives take over at 320/390/768/1440 in both themes and
  checks a click on the scaled picture lands on the same page point.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmrXvMqAqZtbpQ4x3et

* style(review): format the generated migration snapshot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmrXvMqAqZtbpQ4x3et

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-02 10:24:49 +01:00

401 lines
16 KiB
TypeScript

/** Downloadable, review-scoped browser worker. Never accepts shell/page actions from the server. */
import { readFile, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { randomUUID } from "node:crypto";
import { lookup } from "node:dns/promises";
import { pathToFileURL } from "node:url";
import type { Browser, Page, Request } from "playwright";
import {
describeInput,
reviewUrl,
type ReviewFrame,
type ReviewInput,
type ReviewWorkerEvent,
type ReviewStatus,
} from "../src/lib/inspection/contract";
import { isPrivateAddress } from "../src/lib/private-address";
type Config = { endpoint: string; token: string; workerId?: string };
type Reply = {
status: ReviewStatus;
accepted: boolean;
mode: string;
url: string;
paths: string[];
limits: { pages: number; scrolls: number; findings: number; lifetimeMs: number };
/** Who has the browser; "you" while the person has taken over. */
control?: "you" | "loki";
/** What the person did since the last checkpoint, oldest first. */
inputs?: ReviewInput[];
};
/**
* Apply the person's inputs to the page, each on its own: a click that lands
* on nothing, or a back with no history, is skipped rather than ending the
* review. The request guard still decides what any of them may load or send.
*/
export async function applyInputs(page: Page, inputs: ReviewInput[]) {
for (const input of inputs) {
try {
if (input.type === "click") await page.mouse.click(input.x, input.y);
else if (input.type === "scroll") await page.mouse.wheel(0, input.dy);
else if (input.type === "type") await page.keyboard.type(input.text, { delay: 15 });
else if (input.type === "key") await page.keyboard.press(input.key);
else await page.goBack({ timeout: 8000 });
} catch {
// The page did not take this one; the next picture shows what happened.
}
}
await page.waitForLoadState("domcontentloaded", { timeout: 5000 }).catch(() => undefined);
await page.waitForTimeout(450);
}
export class ReviewStopped extends Error {}
export async function reviewRequestAllowed(
request: Pick<Request, "url" | "method" | "isNavigationRequest">,
origin: string,
lookupHost = lookup,
): Promise<boolean> {
try {
const url = new URL(request.url());
if (
!/^https?:$/.test(url.protocol) ||
url.username ||
url.password ||
!["", "80", "443"].includes(url.port)
)
return false;
if (!["GET", "HEAD"].includes(request.method())) return false;
if (request.isNavigationRequest() && !reviewUrl(url.href, origin)) return false;
const addresses = await lookupHost(url.hostname.replace(/^\[|\]$/g, ""), { all: true });
return !!addresses.length && addresses.every((answer) => !isPrivateAddress(answer.address));
} catch {
return false;
}
}
export async function runInspection(configPath: string, requestAllowed = reviewRequestAllowed) {
const config: Config = JSON.parse(await readFile(configPath, "utf8"));
config.workerId ??= randomUUID();
await writeFile(configPath, JSON.stringify(config), { mode: 0o600 });
const send = async (event: ReviewWorkerEvent): Promise<Reply> => {
const response = await fetch(config.endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${config.token}`,
"X-Review-Worker": config.workerId!,
},
body: JSON.stringify(event),
signal: AbortSignal.timeout(60000),
});
if (!response.ok) throw new Error(`Review connection failed (${response.status})`);
return response.json();
};
const started = Date.now();
// Set once the browser is open: what the person drives when they take over.
let page: Page | undefined;
let siteOrigin = "";
// The page the person left open when they handed back, for Loki to look at next.
let detour: string | null = null;
/** A picture of what the person's input did. No viewing interval, no commentary. */
const takeoverFrame = async (action: string) => {
if (!page) return;
const viewport = page.viewportSize()!;
const image = (
await page.screenshot({ type: "jpeg", quality: 48, animations: "disabled", timeout: 10000 })
).toString("base64");
await send({
kind: "frame",
frame: {
url: page.url(),
image: `data:image/jpeg;base64,${image}`,
width: viewport.width,
height: viewport.height,
scrollY: await page.evaluate(() => window.scrollY),
action,
},
text: action,
analyze: false,
});
};
const checkpoint = async (): Promise<Reply> => {
// Where Loki was when the person took over, so it can return there after.
let before: { url: string; scrollY: number } | null = null;
let drove = false;
for (;;) {
const reply = await send({ kind: "checkpoint", workerId: config.workerId! });
if (!reply.accepted || ["stopped", "finished", "failed"].includes(reply.status))
throw new ReviewStopped("Review ended");
if (Date.now() - started > reply.limits.lifetimeMs)
throw new Error("Review time limit reached");
if (reply.status !== "paused") {
if (drove && page && before) {
const theirs = page.url();
if (theirs !== before.url) {
if (reviewUrl(theirs, siteOrigin)) detour = theirs;
await page.goto(before.url, { waitUntil: "domcontentloaded", timeout: 20000 });
}
await page.evaluate((y) => window.scrollTo(0, y), before.scrollY);
}
return reply;
}
if (reply.control === "you" && page) {
if (!before) {
before = { url: page.url(), scrollY: await page.evaluate(() => window.scrollY) };
await takeoverFrame("You have the browser");
}
const inputs = reply.inputs ?? [];
if (inputs.length) {
drove = true;
await applyInputs(page, inputs);
// The guard keeps navigation on the site; this keeps the picture there too.
if (!reviewUrl(page.url(), siteOrigin)) await page.goBack().catch(() => undefined);
await takeoverFrame(describeInput(inputs.at(-1)!));
continue;
}
await new Promise((resolve) => setTimeout(resolve, 400));
continue;
}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
};
const plan = await checkpoint();
siteOrigin = plan.url;
if (plan.mode === "code") {
await send({
kind: "message",
text: "Browser inspection was not selected. The engineer will now review the project's code and record file-level evidence.",
});
return;
}
let browser: Browser | undefined;
let findings = 0;
try {
const require = createRequire(`${process.cwd()}/package.json`);
const loaded = await import(pathToFileURL(require.resolve("playwright")).href);
const { chromium } = (loaded.default ?? loaded) as typeof import("playwright");
browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ serviceWorkers: "block", acceptDownloads: false });
// Resolve every host before each request, including redirects and subresources.
// Like the existing site consultation guard, DNS rebinding remains a platform limitation.
await context.route("**/*", async (route) => {
if (await requestAllowed(route.request(), plan.url)) return route.continue();
return route.abort();
});
page = await context.newPage();
const opened = page;
const livePage = () => opened;
page.setDefaultTimeout(12000);
await page.addInitScript(() => {
// Show where the reviewer navigates without modifying the site's application state.
const style = document.createElement("style");
style.textContent = "html{scroll-behavior:auto!important}";
document.addEventListener("DOMContentLoaded", () => document.head.appendChild(style), {
once: true,
});
});
const queue = [
...new Set([
plan.url,
...plan.paths.map((p) => reviewUrl(p, plan.url)).filter((p): p is string => !!p),
]),
];
const visited = new Set<string>();
// Which planned page is open, for the "now · next" line under the picture.
let cursor = 0;
const recordFinding = async (
title: string,
detail: string,
evidence: string,
location: string,
) => {
if (findings >= plan.limits.findings) return;
await checkpoint();
await send({
kind: "finding",
finding: { title, detail, evidence, location, category: "functional" },
});
findings++;
};
const frame = async (action: string, analyze: boolean, target?: ReviewFrame["target"]) => {
await checkpoint();
const page = livePage();
const viewport = page.viewportSize()!;
const image = (
await page.screenshot({ type: "jpeg", quality: 48, animations: "disabled", timeout: 10000 })
).toString("base64");
const data: ReviewFrame = {
url: page.url(),
image: `data:image/jpeg;base64,${image}`,
width: viewport.width,
height: viewport.height,
scrollY: await page.evaluate(() => window.scrollY),
action,
...(target ? { target } : {}),
...(queue[cursor + 1] ? { next: new URL(queue[cursor + 1]!).pathname.slice(0, 200) } : {}),
progress: { done: visited.size - 1, total: Math.min(queue.length, plan.limits.pages) },
};
await send({ kind: "frame", frame: data, text: action, analyze });
// A deliberate viewing interval, interruptible on the next checkpoint.
for (let i = 0; i < 2; i++) {
await checkpoint();
await new Promise((resolve) => setTimeout(resolve, 1000));
}
};
for (let index = 0; index < queue.length && visited.size < plan.limits.pages; index++) {
// A page the person opened while they had the browser comes first.
if (detour) {
if (!visited.has(detour)) queue.splice(index, 0, detour);
detour = null;
}
cursor = index;
const url = reviewUrl(queue[index]!, plan.url);
if (!url || visited.has(url)) continue;
visited.add(url);
for (const width of [390, 1440]) {
await checkpoint();
await page.setViewportSize({ width, height: width === 390 ? 760 : 900 });
const errors: string[] = [];
const onError = (error: Error) => {
if (errors.length < 8) errors.push(error.message.slice(0, 250));
};
page.on("pageerror", onError);
try {
// Use a visible link where it exists; otherwise open the discovered route directly.
const link = page.locator("a[href]").filter({ visible: true });
let clicked = false;
for (const candidate of (await link.all()).slice(0, 100)) {
if (
reviewUrl((await candidate.getAttribute("href")) ?? "", page.url()) === url &&
page.url() !== "about:blank"
) {
await checkpoint();
await candidate.evaluate((el) => {
(el as HTMLElement).style.outline = "3px solid #ff5c00";
el.scrollIntoView({ block: "center" });
});
// Where the press lands, in viewport pixels — the frame's own —
// so the page can show the pointer going there.
const box = await candidate.boundingBox().catch(() => null);
await frame(
`Following ${(await candidate.innerText().then((t) => t.slice(0, 70))) || "a page link"}`,
false,
box ?? undefined,
);
await checkpoint();
await candidate.click({ timeout: 5000, noWaitAfter: true });
await page.waitForURL(url, { timeout: 12000 });
clicked = true;
break;
}
}
const response = clicked
? null
: await page.goto(url, { waitUntil: "domcontentloaded", timeout: 20000 });
await page.waitForLoadState("domcontentloaded");
await page.waitForTimeout(700);
if (!reviewUrl(page.url(), plan.url))
throw new Error("The page redirected outside the review site");
if (response && response.status() >= 400)
await recordFinding(
`Page returned ${response.status()}`,
"Visitors cannot open this page normally.",
`HTTP ${response.status()} at ${width}px`,
url,
);
await frame(
`Checking ${new URL(url).pathname} on ${width === 390 ? "phone" : "desktop"}`,
true,
);
const links = await page
.locator("a[href]")
.evaluateAll((els) => els.map((el) => (el as HTMLAnchorElement).href));
for (const href of links) {
const next = reviewUrl(href, plan.url);
if (next && !queue.includes(next) && queue.length < plan.limits.pages * 4)
queue.push(next);
}
const size = await page.evaluate(() => ({
height: document.documentElement.scrollHeight,
overflow: document.documentElement.scrollWidth > innerWidth + 2,
signIn: /\/(login|signin|sign-in|auth)(\/|\?|$)/i.test(location.pathname),
}));
if (size.overflow)
await recordFinding(
"The page scrolls sideways",
"The layout extends beyond the screen, making content harder to read and controls harder to reach.",
`document width exceeds ${width}px viewport`,
url,
);
let bottom = 0;
for (
let scroll = 1;
scroll < plan.limits.scrolls && bottom + page.viewportSize()!.height < size.height;
scroll++
) {
await checkpoint();
bottom = Math.min(
size.height - page.viewportSize()!.height,
scroll * (page.viewportSize()!.height - 100),
);
await page.evaluate((y) => window.scrollTo(0, y), bottom);
await frame(
`Reading further down ${new URL(url).pathname}`,
plan.mode !== "functional",
);
}
if (errors.length)
await recordFinding(
"A page error interrupted the app",
"The browser reported an application error on this page.",
errors.join("\n"),
url,
);
await send({
kind: "page",
url,
width,
result: size.signIn ? "blocked" : "visited",
detail: size.signIn
? "Sign-in required. Private pages and flows were not inspected."
: `Navigation and ${Math.min(size.height, bottom + page.viewportSize()!.height)} of ${size.height}px viewed. Forms, purchases and other changes were not submitted.`,
});
} catch (error) {
if (error instanceof ReviewStopped) throw error;
await checkpoint();
const detail =
error instanceof Error ? error.message.slice(0, 900) : "Could not open this page";
await send({ kind: "page", url, width, result: "failed", detail });
await recordFinding(
"This page could not be reviewed",
"The browser could not finish loading or navigating this page.",
detail,
url,
);
} finally {
page.off("pageerror", onError);
}
}
}
await checkpoint();
const summary = `Browser review visited ${visited.size} distinct URLs. ${queue.length > visited.size ? `${queue.length - visited.size} discovered URLs remain outside this review's ${plan.limits.pages}-page limit. ` : ""}Unlinked routes, signed-in flows and actions that change data remain untested. Screenshots are sampled viewports, not proof that every interaction works.`;
await send({
kind: plan.mode === "full" ? "message" : "finished",
text: summary + (plan.mode === "full" ? " Code review is next." : ""),
});
} catch (error) {
if (error instanceof ReviewStopped) return;
await send({
kind: "failed",
text: `Browser review stopped: ${error instanceof Error ? error.message.slice(0, 800) : "unknown error"}. Coverage is incomplete.`,
}).catch(() => undefined);
throw error;
} finally {
await browser?.close();
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
runInspection(process.argv[2] ?? "").catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
}