Files
STCourses/packages/feature-learner/test/chrome.ts
T
Lucas WintherandClaude Opus 5.5 c7b9e1f98e fix(learner): review round 1: sanitize-html, sandboxed runner frame, one visibility rule, no Tab capture
C1: lesson HTML goes through a sanitize-html allowlist on the fully rendered output (no on* attributes, no
style, no svg/math/iframe/object/embed/form; URLs limited to http(s), mailto, relative and anchors). Raw tags
outside the allowlist are escaped as text. The SPA document is served with a CSP (script-src 'self', no inline
script) through spaWithCsp in main.ts; contract request §5 asks core to own it.

C2: exercises run in <iframe sandbox="allow-scripts"> (opaque origin, no cookies) loaded from
/api/learner/runner-frame, whose CSP allows only its own script (by hash) and blob: workers, and connect-src
'none'. postMessage only, both sides check event.source; the timeout removes the frame. The worker stubs now
also cover Worker, SharedWorker and caches.

I1: learner visibility calls core canView with per-course authorship only, like /api/media (contract request §6).
I2: Tab and Shift+Tab move focus; Enter keeps the previous line's indentation.

Tests: XSS unit cases, headless-Chrome checks for the exploit lesson and for fetch, import, Cache.add, nested
Worker, img, EventSource, WebSocket, XHR and sendBeacon from learner and test code (plus a negative control),
visibility on both dialects, SPA and runner-frame CSP headers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 05:20:43 +01:00

69 lines
3.3 KiB
TypeScript

import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
/** Path of a usable Chrome, or null (the browser tests are skipped without one). */
export const chromePath = Bun.which("google-chrome") ?? Bun.which("chromium") ?? Bun.which("chromium-browser");
/** A minimal Chrome DevTools Protocol driver for headless end-to-end checks. */
export class Chrome {
private ws!: WebSocket;
private id = 0;
private pending = new Map<number, (v: { result?: any; error?: any }) => void>();
readonly console: string[] = [];
readonly dialogs: string[] = [];
private proc!: Bun.Subprocess;
private dir!: string;
static async launch(): Promise<Chrome> {
const c = new Chrome();
c.dir = mkdtempSync(join(tmpdir(), "stc-chrome-"));
const port = 9400 + Math.floor(Math.random() * 500);
c.proc = Bun.spawn([chromePath!, "--headless=new", "--no-sandbox", "--disable-gpu", "--no-first-run", `--remote-debugging-port=${port}`, `--user-data-dir=${c.dir}`, "about:blank"], { stdout: "ignore", stderr: "ignore" });
let url: string | null = null;
for (let i = 0; i < 100 && !url; i++) {
await Bun.sleep(100);
try {
const list = (await (await fetch(`http://127.0.0.1:${port}/json`)).json()) as { type: string; webSocketDebuggerUrl: string }[];
url = list.find((t) => t.type === "page")?.webSocketDebuggerUrl ?? null;
} catch { /* not up yet */ }
}
if (!url) throw new Error("chrome did not start");
c.ws = new WebSocket(url);
await new Promise((r) => c.ws.addEventListener("open", r, { once: true }));
c.ws.addEventListener("message", (ev) => {
const m = JSON.parse(String(ev.data));
if (m.id && c.pending.has(m.id)) { c.pending.get(m.id)!(m); c.pending.delete(m.id); }
if (m.method === "Runtime.consoleAPICalled") c.console.push(`${m.params.type}: ${m.params.args.map((a: any) => a.value ?? a.description).join(" ")}`);
if (m.method === "Runtime.exceptionThrown") c.console.push(`exception: ${m.params.exceptionDetails.exception?.description ?? m.params.exceptionDetails.text}`);
if (m.method === "Page.javascriptDialogOpening") { c.dialogs.push(m.params.message); void c.send("Page.handleJavaScriptDialog", { accept: true }); }
});
await c.send("Page.enable");
await c.send("Runtime.enable");
return c;
}
send(method: string, params: object = {}): Promise<{ result?: any; error?: any }> {
return new Promise((r) => { const i = ++this.id; this.pending.set(i, r); this.ws.send(JSON.stringify({ id: i, method, params })); });
}
async goto(url: string, settleMs = 1500) {
await this.send("Page.navigate", { url });
await Bun.sleep(settleMs);
}
/** Evaluates `js` in the page (awaiting promises) and returns the JSON value. */
async eval<T = unknown>(js: string): Promise<T> {
const r = await this.send("Runtime.evaluate", { expression: js, awaitPromise: true, returnByValue: true });
if (r.result?.exceptionDetails) throw new Error(r.result.exceptionDetails.exception?.description ?? "evaluation failed");
return r.result?.result?.value as T;
}
async close() {
try { this.ws.close(); } catch { /* closed */ }
this.proc.kill();
await this.proc.exited;
rmSync(this.dir, { recursive: true, force: true });
}
}