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