diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2809e3cfb4..6bd5bd0497 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -626,7 +626,10 @@ jobs: # And Report a bug, Your bug reports and Admin's Bug reports, wide and on a phone, light and dark, # held against Add credential and the Vault: a file taken, one refused, the report saved. # And the account menu with OpenBot on this computer saying so in place of the stand-in email, - # and its Connect to an OpenBot opening Settings → Computer at Connection. In the image, as above: + # and its Connect to an OpenBot opening Settings → Computer at Connection. + # And an error made in a same-origin frame reported as itself, never "A object was thrown", and + # on a page Cloudflare wrote its script into, Cloudflare's own errors left out while OpenBot's + # own Trusted Types refusals are still reported. In the image, as above: # WebKit's system packages are about 94 MB, which took nine minutes from the mirror on a slow day. # # The files run side by side, like the Chromium list's, but eight at a time rather than a worker @@ -690,6 +693,7 @@ jobs: app/tests/admin-path-layout.test.tsx app/tests/admin-request-notify-layout.test.tsx app/tests/another-account-layout.test.tsx + app/tests/app-error-reporting-browser.test.ts app/tests/app-frame-skeleton-still.test.tsx app/tests/approval-answered-layout.test.tsx app/tests/approval-left-carry-on-browser.test.tsx diff --git a/app/src/lib/error-reporting.tsx b/app/src/lib/error-reporting.tsx index 648b686bf6..4394b633d8 100644 --- a/app/src/lib/error-reporting.tsx +++ b/app/src/lib/error-reporting.tsx @@ -56,17 +56,57 @@ export function resetAppErrorReports(): void { uninstall = null; } +const objectToString = Object.prototype.toString; + +/** + * Whether `value` is an error, made in this window or in another one. + * + * Each frame has its own `Error`, so an error a same-origin frame made (the browser refusing + * something inside the frame, or code here handed one of the frame's errors) is not `instanceof` + * this window's. It was sent as "A object was thrown", with nothing to go on. So, as Sentry, + * PostHog's own SDK and Bugsnag read it, an error is what the engine says it is by its built-in tag + * (`[object Error]`, a DOMException's, and the like), whichever window made it, and `instanceof` + * only after that; the browser's own `Error.isError` first where it has one. + */ +function isAnError(value: unknown): boolean { + const isError = (Error as { isError?: (value: unknown) => boolean }).isError; + if (typeof isError === "function" && isError(value)) return true; + switch (objectToString.call(value)) { + case "[object Error]": + case "[object Exception]": + case "[object DOMException]": + case "[object DOMError]": + case "[object WebAssembly.Exception]": + return true; + default: + try { + return value instanceof Error; + } catch { + return false; + } + } +} + function described(error: unknown): { type: string; message: string; stack?: string; } { - if (error instanceof Error) { + if (isAnError(error)) { + // Read by field, not through this window's `Error`: it may be another window's. + const { name, message, stack } = error as { + name?: unknown; + message?: unknown; + stack?: unknown; + }; return { - type: (error.name || "Error").slice(0, 128), - message: String(error.message ?? "").slice(0, MAX_MESSAGE), - ...(typeof error.stack === "string" && error.stack - ? { stack: error.stack.slice(0, MAX_STACK) } + type: ((typeof name === "string" && name) || "Error").slice(0, 128), + message: (typeof message === "string" ? message : "").slice( + 0, + MAX_MESSAGE, + ), + ...(typeof stack === "string" && stack + ? { stack: stack.slice(0, MAX_STACK) } : {}), }; } @@ -129,15 +169,111 @@ export function thrownAt(event: ErrorEvent): string | undefined { return event.lineno ? `${file}:${event.lineno}:${event.colno ?? 0}` : file; } +/* + * CLOUDFLARE'S OWN ERRORS ARE NOT OPENBOT'S, AND ARE NOT TOLD TO IT. + * + * Where OpenBot is served through Cloudflare with its JavaScript detections on (OpenBot Cloud), + * Cloudflare writes a script into every page: a hidden frame on the page's own address, and its + * loader (`/cdn-cgi/challenge-platform/…`) written into the frame with `innerHTML`. The frame keeps + * the page's Trusted Types rule but not OpenBot's policies (`trusted-types.ts`), so the browser + * refuses the write, in Chromium and in WebKit, and the refusal reaches this window as an error + * nobody caught: from nearly every page load on OpenBot Cloud from 3 December 2026. Nothing in + * OpenBot can act on it, and OpenBot doesn't loosen Trusted Types for it. + * + * Two kinds are left out, as Sentry's `denyUrls` and its third-party error filter leave out errors + * from code that isn't the app's: + * + * - an error thrown in one of Cloudflare's files, which it serves under `/cdn-cgi/` on the page's + * address (where the browser says it was thrown, else the top of its stack); + * - that refusal: a Trusted Types refusal made in another frame, every line of whose stack is in + * the page's own markup rather than one of OpenBot's files, on a page Cloudflare wrote its + * loader into. Chromium reads it as `at HTMLDocument.c (https://…/sign:291:154)`, WebKit as + * `c@https://…/sign:291:145`. + * + * Narrow on purpose: OpenBot's own Trusted Types refusals are thrown from its own files, in this + * window or in a frame of its own, and are reported as before. + */ +const CLOUDFLARE_FILES = /^\/cdn-cgi\//; +const TRUSTED_TYPES_REFUSAL = /\bTrusted(?:HTML|Script|ScriptURL)\b/; +/** Cloudflare's loader, as its script in the page names it. */ +const CLOUDFLARE_LOADER = "/cdn-cgi/challenge-platform/"; + +/** + * The addresses a stack's lines are in, from its top: Chromium writes `at f (url:1:2)` or + * `at url:1:2`, WebKit and Firefox `f@url:1:2`. + */ +export function stackFiles(stack: string | undefined): string[] { + return (stack ?? "").split("\n").flatMap((line) => { + const found = /([a-z][\w+.-]*:\/\/[^\s()]+?):\d+(?::\d+)?\)?\s*$/i.exec( + line, + ); + return found?.[1] ? [found[1]] : []; + }); +} + +function pathOf(address: string): string { + try { + return new URL(address, window.location.href).pathname; + } catch { + return ""; + } +} + +const withoutQuery = (address: string) => address.split(/[?#]/, 1)[0] ?? ""; + +/** + * The page's own addresses: the one it was loaded from, which a script in its markup is named by, + * and the one it shows now, which the app's router may have changed since. + */ +function pageAddresses(): string[] { + const loaded = performance.getEntriesByType?.("navigation")[0]?.name; + return [loaded, window.location.href] + .filter((address): address is string => Boolean(address)) + .map(withoutQuery); +} + +function cloudflareLoaderInPage(): boolean { + return [...document.scripts].some( + (script) => !script.src && script.text.includes(CLOUDFLARE_LOADER), + ); +} + +/** Whether this error is Cloudflare's own, and not OpenBot's to report. */ +function fromCloudflare( + error: unknown, + report: { message: string; stack?: string }, + where: string | undefined, +): boolean { + if (typeof window === "undefined" || typeof document === "undefined") + return false; + const thrownIn = where?.replace(/:\d+(?::\d+)?$/, ""); + const files = stackFiles(report.stack); + const top = thrownIn ?? files[0]; + if (top && CLOUDFLARE_FILES.test(pathOf(top))) return true; + if (!TRUSTED_TYPES_REFUSAL.test(report.message)) return false; + // Made in another frame: not this window's own error. + if (error instanceof Error) return false; + const lines = thrownIn ? [thrownIn, ...files] : files; + if (lines.length === 0) return false; + const page = pageAddresses(); + if (!lines.every((line) => page.includes(withoutQuery(line)))) return false; + return cloudflareLoaderInPage(); +} + /** * Tell OpenBot about an error the app did not handle. Never throws, never waits. `where` is where it - * was thrown, when known (`thrownAt`). + * was thrown, when known (`thrownAt`). Cloudflare's own errors are left out (`fromCloudflare`). */ export function reportAppError( source: AppErrorSource, error: unknown, where?: string, ): void { + try { + if (fromCloudflare(error, described(error), where)) return; + } catch { + // Reading the page went wrong: the error is told, as any other. + } recordForTroubleshooting(source, error, where); if (typeof error === "object" && error !== null) { if (seenErrors.has(error)) return; diff --git a/app/tests/app-error-reporting-browser.fixture.ts b/app/tests/app-error-reporting-browser.fixture.ts new file mode 100644 index 0000000000..794d6bed21 --- /dev/null +++ b/app/tests/app-error-reporting-browser.fixture.ts @@ -0,0 +1,72 @@ +import "@/lib/trusted-types"; +import { installAppErrorReporting } from "@/lib/error-reporting"; + +/** + * The app's error reporting in a real page, for app-error-reporting-browser.test.ts to bundle. + * The Trusted Types policies first, as `main.tsx` makes them, then the reporting, then what the + * page's `?case=` asks for, each thrown from this file (OpenBot's own code) once the page has + * loaded, the way an error nobody caught reaches the window. + * + * - `frame`: errors made in a same-origin frame, which are not this window's `Error`: the frame's + * TypeError thrown at the window, and the frame's RangeError a promise was rejected with that + * nobody handled. + * - `cloudflare`: on a page Cloudflare wrote its script into (the test serves it), OpenBot's own + * Trusted Types refusals, in this window and in a frame (the frame's own native TypeError, the + * same kind of error as Cloudflare's), then one last error that says the page is done. + */ + +installAppErrorReporting(); + +type FrameWindow = Window & { + TypeError: TypeErrorConstructor; + RangeError: RangeErrorConstructor; +}; + +/** A hidden frame with no address of its own, as Cloudflare makes: on the page's origin. */ +function sameOriginFrame(): FrameWindow { + const frame = document.createElement("iframe"); + frame.style.visibility = "hidden"; + document.body.append(frame); + const inside = frame.contentWindow; + if (!inside) throw new Error("the frame has no window"); + return inside as FrameWindow; +} + +/** Each in a task of its own, so each reaches the window as an error nobody caught. */ +function throwInTurn(steps: (() => void)[]) { + for (const step of steps) setTimeout(step, 0); +} + +const which = new URLSearchParams(window.location.search).get("case"); + +window.addEventListener("load", () => { + if (which === "frame") { + const inside = sameOriginFrame(); + throwInTurn([ + () => { + throw new inside.TypeError("a frame's error thrown at the window"); + }, + () => { + void Promise.reject( + new inside.RangeError("a frame's error nobody handled"), + ); + }, + ]); + } + if (which === "cloudflare") { + const inside = sameOriginFrame(); + throwInTurn([ + // A script's text from a string: OpenBot's `default` policy refuses it. + () => { + document.createElement("script").text = "window.ran = true"; + }, + // Markup into a frame of OpenBot's own, which has the page's rule but not its policies. + () => { + inside.document.createElement("div").innerHTML = "drawn"; + }, + () => { + throw new Error("the page is done"); + }, + ]); + } +}); diff --git a/app/tests/app-error-reporting-browser.test.ts b/app/tests/app-error-reporting-browser.test.ts new file mode 100644 index 0000000000..94b58507ce --- /dev/null +++ b/app/tests/app-error-reporting-browser.test.ts @@ -0,0 +1,233 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { readFileSync } from "node:fs"; +import { basename, join } from "node:path"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { test } from "./renderer-crash"; + +/** + * AN ERROR FROM ANOTHER FRAME IS REPORTED AS ITSELF, AND CLOUDFLARE'S OWN ARE NOT REPORTED. + * + * FOUND ON OPENBOT CLOUD, 3 December 2026. Cloudflare's bot detection writes a script into every + * page it serves: it makes a hidden frame on the page's own address and writes its loader into the + * frame with `innerHTML`. The frame keeps the page's Trusted Types rule but none of OpenBot's + * policies, so the browser refuses the write, and the refusal reaches OpenBot's window as an error + * nobody caught. That error was made in the frame, so it is not this window's `Error`, and the + * reporter, which only knew this window's, sent "A object was thrown" from nearly every page load: + * 575 reports in a day, none of them OpenBot's and none it could act on, hiding the real ones. + * + * In a real browser, with the app's own Trusted Types `` and Cloudflare's script as Cloudflare + * writes it (read from OpenBot Cloud's page in Chrome and in WebKit, which both refuse it): + * + * 1. An error made in a same-origin frame is reported with its own name, message and stack. + * 2. Cloudflare's refusal, and an error thrown in a script of Cloudflare's under /cdn-cgi/, are not + * reported. + * 3. OpenBot's own Trusted Types refusals on that same page still are, in its window and in a frame. + * + * OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/app-error-reporting-browser.test.ts + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; + +const APP = join(import.meta.dir, ".."); +const ORIGIN = "https://openbot.test"; +/** Where a report goes before the person's organization is known, as on this page. */ +const SIGNED_OUT_APP_ERRORS = "/api/v2/app-errors"; + +/** The Content-Security-Policy `` in the app's `index.html`, as written. */ +function cspMeta(): string { + const html = readFileSync(join(APP, "index.html"), "utf8"); + const meta = /]*>/i.exec( + html, + )?.[0]; + if (!meta) throw new Error("index.html has no Content-Security-Policy"); + return meta; +} + +/** + * Cloudflare's JavaScript detections, as Cloudflare writes them at the end of a page's body: a + * hidden frame, and once the page has been read its loader written into the frame with + * `innerHTML`. The parameters are made up; the rest is as OpenBot Cloud's page carried it. + */ +const CLOUDFLARE_SCRIPT = ``; + +/** One of Cloudflare's own scripts on the page's address, throwing as it runs. */ +const CLOUDFLARE_FILE = + "/cdn-cgi/challenge-platform/h/g/scripts/jsd/orchestrate.js"; + +function html(which: string): string { + const cloudflare = + which === "cloudflare" + ? `${CLOUDFLARE_SCRIPT}` + : ""; + // The app's code first, as the app's page has it; Cloudflare's after, at the end of the body. + return `${cspMeta()}
${cloudflare}`; +} + +let files: Map; +const browsers = new Map(); + +beforeAll(async () => { + if (!asked) return; + const built = await Bun.build({ + entrypoints: [ + join(import.meta.dir, "app-error-reporting-browser.fixture.ts"), + ], + target: "browser", + naming: { entry: "fixture.[ext]", asset: "[name].[ext]" }, + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + plugins: [ + { + name: "no-marks", + setup(build) { + build.onResolve({ filter: /^@\/lib\/marks$/ }, () => ({ + path: "marks", + namespace: "no-marks", + })); + build.onLoad({ filter: /.*/, namespace: "no-marks" }, () => ({ + contents: "export const markFor = () => null;", + loader: "js", + })); + }, + }, + ], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + files = new Map(); + for (const output of built.outputs) + files.set(`/${basename(output.path)}`, await output.text()); + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + browsers.set( + engine, + // The CI job installs full Chromium without the headless shell. + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); +}, 30_000); + +type Report = { + source: string; + type: string; + message: string; + stack?: string; +}; + +/** The page for `which`, and every report it sends, in the order it sends them. */ +async function open( + engine: string, + which: string, +): Promise<{ page: Page; reports: Report[] }> { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage(); + const reports: Report[] = []; + await page.route(`${ORIGIN}/**`, (route) => { + const request = route.request(); + const path = new URL(request.url()).pathname; + if (path === SIGNED_OUT_APP_ERRORS) { + reports.push(request.postDataJSON() as Report); + return route.fulfill({ status: 204 }); + } + if (path.startsWith("/api/")) + return route.fulfill({ status: 404, body: "" }); + if (path === CLOUDFLARE_FILE) + return route.fulfill({ + contentType: "text/javascript", + body: 'throw new TypeError("Cloudflare\'s own script failed");', + }); + const file = files.get(path); + if (file) + return route.fulfill({ contentType: "text/javascript", body: file }); + if (path.includes(".")) return route.fulfill({ status: 404, body: "" }); + return route.fulfill({ contentType: "text/html", body: html(which) }); + }); + await page.goto(`${ORIGIN}/sign?case=${which}`); + return { page, reports }; +} + +/** Wait for a report whose message is `message`, then every report sent before it. */ +async function reportsUpTo( + reports: Report[], + message: string, +): Promise { + const deadline = Date.now() + 15_000; + for (;;) { + const at = reports.findIndex((report) => report.message === message); + if (at >= 0) return reports.slice(0, at + 1); + if (Date.now() > deadline) + throw new Error( + `no report of "${message}"; sent: ${JSON.stringify(reports)}`, + ); + await Bun.sleep(25); + } +} + +const TRUSTED_TYPES_REFUSAL = /Trusted(HTML|Script)/; + +describe.skipIf(!asked)("Errors the page did not handle", () => { + for (const engine of engines) { + test(`${engine}: an error made in a same-origin frame is reported as itself`, async () => { + const { page, reports } = await open(engine, "frame"); + try { + const sent = await reportsUpTo( + reports, + "a frame's error nobody handled", + ); + expect(sent).toHaveLength(2); + const [thrown, rejected] = sent; + expect(thrown).toMatchObject({ + source: "window_error", + type: "TypeError", + message: "a frame's error thrown at the window", + }); + expect(thrown?.stack).toContain("/fixture.js"); + expect(rejected).toMatchObject({ + source: "unhandled_rejection", + type: "RangeError", + message: "a frame's error nobody handled", + }); + expect(rejected?.stack).toContain("/fixture.js"); + } finally { + await page.close(); + } + }, 60_000); + + test(`${engine}: Cloudflare's errors are not reported, and OpenBot's own Trusted Types refusals are`, async () => { + const { page, reports } = await open(engine, "cloudflare"); + try { + const sent = await reportsUpTo(reports, "the page is done"); + // Cloudflare's refusal in its frame and its own script's error: neither was sent. + expect( + sent.some((report) => report.message.includes("Cloudflare")), + ).toBe(false); + expect(sent.map((report) => report.type)).toEqual([ + "TypeError", + "TypeError", + "Error", + ]); + // OpenBot's own: refused in its window, and refused in a frame of its own. + const [inWindow, inFrame] = sent; + for (const own of [inWindow, inFrame]) { + expect(own?.source).toBe("window_error"); + expect(own?.message).toMatch(TRUSTED_TYPES_REFUSAL); + expect(own?.stack).toContain("/fixture.js"); + } + expect(inWindow?.message).toMatch(/TrustedScript/); + expect(inFrame?.message).toMatch(/TrustedHTML/); + } finally { + await page.close(); + } + }, 60_000); + } +}); diff --git a/app/tests/app-error-reporting.test.tsx b/app/tests/app-error-reporting.test.tsx index cd70080651..8443ccdbf8 100644 --- a/app/tests/app-error-reporting.test.tsx +++ b/app/tests/app-error-reporting.test.tsx @@ -20,6 +20,7 @@ import { installAppErrorReporting, ReportedErrorComponent, resetAppErrorReports, + stackFiles, } from "@/lib/error-reporting"; import { setCurrentOrganization } from "@/lib/organizations/current"; import { router as appRouter } from "@/router"; @@ -90,6 +91,31 @@ function renderBrokenScreen(message: string) { return render(); } +test("a stack's addresses are read as Chromium and WebKit write them, top first", () => { + // Cloudflare's refusal on OpenBot Cloud, 3 December 2026, as each engine wrote it. + expect( + stackFiles( + "TypeError: This document requires 'TrustedHTML' assignment.\n at HTMLDocument.c (https://my.open.bot/sign:291:154)", + ), + ).toEqual(["https://my.open.bot/sign"]); + expect(stackFiles("c@https://my.open.bot/sign:291:145")).toEqual([ + "https://my.open.bot/sign", + ]); + // OpenBot's own files, on a port, a frame with no name, and a line the engine wrote no address for. + expect( + stackFiles( + "TypeError: x\n at https://openbot.test/fixture.js:18441:15\n at f (http://localhost:5173/src/lib/a.tsx?t=1:3:9)\n at new Promise ()", + ), + ).toEqual([ + "https://openbot.test/fixture.js", + "http://localhost:5173/src/lib/a.tsx?t=1", + ]); + expect( + stackFiles("parse@[native code]\n@https://openbot.test/fixture.js:1:2"), + ).toEqual(["https://openbot.test/fixture.js"]); + expect(stackFiles(undefined)).toEqual([]); +}); + test("the app's error screen is the reporting one", () => { expect(appRouter.options.defaultErrorComponent).toBe(ReportedErrorComponent); });