diff --git a/api/openapi.yaml b/api/openapi.yaml index 0e2470c3a0..a2ac49e826 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -47224,7 +47224,7 @@ components: description: Where the caller saw or copied it. AppError: type: object - description: An error the app hit and did not handle, as the app saw it. OpenBot scrubs and bounds it again before it is sent anywhere. + description: An error the app hit and did not handle, as the app saw it. OpenBot scrubs and bounds it again before it is sent anywhere. Where it happened is said only by the route's pattern, the page's and browser's languages and the browser's and operating system's names and major versions, never by an address, an ID or anything on the page. additionalProperties: false required: - source @@ -47265,6 +47265,51 @@ components: minLength: 1 maxLength: 32 pattern: ^v?\d+(?:\.\d+){1,3}(?:-[a-z]+(?:\.\d{1,9})?)?$ + route: + type: string + description: The pattern of the app's route the page was on, such as /bots/$botId, never its address. No IDs, query or fragment. + minLength: 1 + maxLength: 200 + pattern: ^/[A-Za-z0-9_$./~{}*-]*$ + pageLanguage: + type: string + description: The page's language, from the lang attribute of its html element, such as en. A page translated in the browser often says the language it was translated into. + minLength: 1 + maxLength: 35 + pattern: ^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4}$ + pageTranslated: + type: boolean + description: Whether the browser had translated the page when the error happened, by the marks a page translator leaves on it. + browserLanguage: + type: string + description: The browser's preferred language, such as pt-BR. + minLength: 1 + maxLength: 35 + pattern: ^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4}$ + browserName: + type: string + description: The browser's name, such as Chrome or Safari. + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9 ._()-]+$ + browserVersion: + type: string + description: The browser's major version, such as 141. + minLength: 1 + maxLength: 6 + pattern: ^\d{1,6}$ + osName: + type: string + description: The operating system's name, such as Windows or macOS. + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9 ._()-]+$ + osVersion: + type: string + description: The operating system's major version, such as 11, when the browser says it. + minLength: 1 + maxLength: 6 + pattern: ^\d{1,6}$ NudgeEvent: type: object description: What the caller did with a nudge, and where. Names nothing about the person, who is the caller. The moment that made the nudge due is added by OpenBot, not sent. @@ -64899,6 +64944,14 @@ components: at BotCard (/assets/route-app-secondary.js:12:345) surface: web appVersion: 1.1.0-rc.2 + route: /bots/$botId + pageLanguage: ja + pageTranslated: true + browserLanguage: ja-JP + browserName: Chrome + browserVersion: '141' + osName: Windows + osVersion: '11' NudgeClicked: summary: The caller opened OpenBot's repository from the star card, in OpenBot Desktop. value: diff --git a/api/openapi/conversations.yaml b/api/openapi/conversations.yaml index f31c723e12..2e205f14b5 100644 --- a/api/openapi/conversations.yaml +++ b/api/openapi/conversations.yaml @@ -2800,7 +2800,10 @@ components: AppError: type: object description: An error the app hit and did not handle, as the app saw it. - OpenBot scrubs and bounds it again before it is sent anywhere. + OpenBot scrubs and bounds it again before it is sent anywhere. Where it + happened is said only by the route's pattern, the page's and browser's + languages and the browser's and operating system's names and major + versions, never by an address, an ID or anything on the page. additionalProperties: false required: - source @@ -2844,6 +2847,56 @@ components: minLength: 1 maxLength: 32 pattern: ^v?\d+(?:\.\d+){1,3}(?:-[a-z]+(?:\.\d{1,9})?)?$ + route: + type: string + description: The pattern of the app's route the page was on, such as + /bots/$botId, never its address. No IDs, query or fragment. + minLength: 1 + maxLength: 200 + pattern: ^/[A-Za-z0-9_$./~{}*-]*$ + pageLanguage: + type: string + description: The page's language, from the lang attribute of its html + element, such as en. A page translated in the browser often says the + language it was translated into. + minLength: 1 + maxLength: 35 + pattern: ^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4}$ + pageTranslated: + type: boolean + description: Whether the browser had translated the page when the error + happened, by the marks a page translator leaves on it. + browserLanguage: + type: string + description: The browser's preferred language, such as pt-BR. + minLength: 1 + maxLength: 35 + pattern: ^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4}$ + browserName: + type: string + description: The browser's name, such as Chrome or Safari. + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9 ._()-]+$ + browserVersion: + type: string + description: The browser's major version, such as 141. + minLength: 1 + maxLength: 6 + pattern: ^\d{1,6}$ + osName: + type: string + description: The operating system's name, such as Windows or macOS. + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9 ._()-]+$ + osVersion: + type: string + description: The operating system's major version, such as 11, when the + browser says it. + minLength: 1 + maxLength: 6 + pattern: ^\d{1,6}$ RouteMessageRequest: type: object additionalProperties: false @@ -4226,4 +4279,4 @@ components: value: {"nudge": "star-on-github", "action": "clicked", "place": "card", "surface": "desktop"} AppErrorBoundary: summary: "An error the web app's error screen caught." - value: {"source": "error_boundary", "type": "TypeError", "message": "Cannot read properties of undefined (reading 'title')", "stack": "TypeError: Cannot read properties of undefined (reading 'title')\n at BotCard (/assets/route-app-secondary.js:12:345)", "surface": "web", "appVersion": "1.1.0-rc.2"} + value: {"source": "error_boundary", "type": "TypeError", "message": "Cannot read properties of undefined (reading 'title')", "stack": "TypeError: Cannot read properties of undefined (reading 'title')\n at BotCard (/assets/route-app-secondary.js:12:345)", "surface": "web", "appVersion": "1.1.0-rc.2", "route": "/bots/$botId", "pageLanguage": "ja", "pageTranslated": true, "browserLanguage": "ja-JP", "browserName": "Chrome", "browserVersion": "141", "osName": "Windows", "osVersion": "11"} diff --git a/app/package.json b/app/package.json index 962891b1f3..26f8b10789 100644 --- a/app/package.json +++ b/app/package.json @@ -37,6 +37,7 @@ "@xterm/xterm": "6.0.0", "better-auth": "^1.6.27", "boring-avatars": "^2.0.4", + "bowser": "^2.15.1", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "colorjs.io": "0.7.1", diff --git a/app/src/lib/api/generated/model/appError.ts b/app/src/lib/api/generated/model/appError.ts index af6dc5405b..b4a329bd34 100644 --- a/app/src/lib/api/generated/model/appError.ts +++ b/app/src/lib/api/generated/model/appError.ts @@ -5,7 +5,7 @@ import type { AppErrorSource } from "./appErrorSource"; import type { AppErrorSurface } from "./appErrorSurface"; /** - * An error the app hit and did not handle, as the app saw it. OpenBot scrubs and bounds it again before it is sent anywhere. + * An error the app hit and did not handle, as the app saw it. OpenBot scrubs and bounds it again before it is sent anywhere. Where it happened is said only by the route's pattern, the page's and browser's languages and the browser's and operating system's names and major versions, never by an address, an ID or anything on the page. */ export interface AppError { /** How the app caught it. error_boundary when its error screen was shown, window_error for an error the page threw, and unhandled_rejection for a promise nobody handled. */ @@ -35,4 +35,55 @@ export interface AppError { * @pattern ^v?\d+(?:\.\d+){1,3}(?:-[a-z]+(?:\.\d{1,9})?)?$ */ appVersion?: string; + /** + * The pattern of the app's route the page was on, such as /bots/$botId, never its address. No IDs, query or fragment. + * @minLength 1 + * @maxLength 200 + * @pattern ^/[A-Za-z0-9_$./~{}*-]*$ + */ + route?: string; + /** + * The page's language, from the lang attribute of its html element, such as en. A page translated in the browser often says the language it was translated into. + * @minLength 1 + * @maxLength 35 + * @pattern ^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4}$ + */ + pageLanguage?: string; + /** Whether the browser had translated the page when the error happened, by the marks a page translator leaves on it. */ + pageTranslated?: boolean; + /** + * The browser's preferred language, such as pt-BR. + * @minLength 1 + * @maxLength 35 + * @pattern ^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4}$ + */ + browserLanguage?: string; + /** + * The browser's name, such as Chrome or Safari. + * @minLength 1 + * @maxLength 64 + * @pattern ^[A-Za-z0-9 ._()-]+$ + */ + browserName?: string; + /** + * The browser's major version, such as 141. + * @minLength 1 + * @maxLength 6 + * @pattern ^\d{1,6}$ + */ + browserVersion?: string; + /** + * The operating system's name, such as Windows or macOS. + * @minLength 1 + * @maxLength 64 + * @pattern ^[A-Za-z0-9 ._()-]+$ + */ + osName?: string; + /** + * The operating system's major version, such as 11, when the browser says it. + * @minLength 1 + * @maxLength 6 + * @pattern ^\d{1,6}$ + */ + osVersion?: string; } diff --git a/app/src/lib/api/generated/product-events/product-events.zod.ts b/app/src/lib/api/generated/product-events/product-events.zod.ts index 96e7e21885..e195e0c822 100644 --- a/app/src/lib/api/generated/product-events/product-events.zod.ts +++ b/app/src/lib/api/generated/product-events/product-events.zod.ts @@ -118,6 +118,37 @@ export const recordAppErrorBodyAppVersionMax = 32; export const recordAppErrorBodyAppVersionRegExp = new RegExp( "^v?\\d+(?:\\.\\d+){1,3}(?:-[a-z]+(?:\\.\\d{1,9})?)?$", ); +export const recordAppErrorBodyRouteMax = 200; + +export const recordAppErrorBodyRouteRegExp = new RegExp( + "^/[A-Za-z0-9_$./~{}*-]*$", +); +export const recordAppErrorBodyPageLanguageMax = 35; + +export const recordAppErrorBodyPageLanguageRegExp = new RegExp( + "^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4}$", +); +export const recordAppErrorBodyBrowserLanguageMax = 35; + +export const recordAppErrorBodyBrowserLanguageRegExp = new RegExp( + "^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4}$", +); +export const recordAppErrorBodyBrowserNameMax = 64; + +export const recordAppErrorBodyBrowserNameRegExp = new RegExp( + "^[A-Za-z0-9 ._()-]+$", +); +export const recordAppErrorBodyBrowserVersionMax = 6; + +export const recordAppErrorBodyBrowserVersionRegExp = new RegExp("^\\d{1,6}$"); +export const recordAppErrorBodyOsNameMax = 64; + +export const recordAppErrorBodyOsNameRegExp = new RegExp( + "^[A-Za-z0-9 ._()-]+$", +); +export const recordAppErrorBodyOsVersionMax = 6; + +export const recordAppErrorBodyOsVersionRegExp = new RegExp("^\\d{1,6}$"); export const RecordAppErrorBody = zod .object({ @@ -152,9 +183,70 @@ export const RecordAppErrorBody = zod .describe( "The release the app was built for, such as 1.1.0-rc.2, when the build knows it.", ), + route: zod + .string() + .min(1) + .max(recordAppErrorBodyRouteMax) + .regex(recordAppErrorBodyRouteRegExp) + .optional() + .describe( + "The pattern of the app's route the page was on, such as /bots/$botId, never its address. No IDs, query or fragment.", + ), + pageLanguage: zod + .string() + .min(1) + .max(recordAppErrorBodyPageLanguageMax) + .regex(recordAppErrorBodyPageLanguageRegExp) + .optional() + .describe( + "The page's language, from the lang attribute of its html element, such as en. A page translated in the browser often says the language it was translated into.", + ), + pageTranslated: zod + .boolean() + .optional() + .describe( + "Whether the browser had translated the page when the error happened, by the marks a page translator leaves on it.", + ), + browserLanguage: zod + .string() + .min(1) + .max(recordAppErrorBodyBrowserLanguageMax) + .regex(recordAppErrorBodyBrowserLanguageRegExp) + .optional() + .describe("The browser's preferred language, such as pt-BR."), + browserName: zod + .string() + .min(1) + .max(recordAppErrorBodyBrowserNameMax) + .regex(recordAppErrorBodyBrowserNameRegExp) + .optional() + .describe("The browser's name, such as Chrome or Safari."), + browserVersion: zod + .string() + .min(1) + .max(recordAppErrorBodyBrowserVersionMax) + .regex(recordAppErrorBodyBrowserVersionRegExp) + .optional() + .describe("The browser's major version, such as 141."), + osName: zod + .string() + .min(1) + .max(recordAppErrorBodyOsNameMax) + .regex(recordAppErrorBodyOsNameRegExp) + .optional() + .describe("The operating system's name, such as Windows or macOS."), + osVersion: zod + .string() + .min(1) + .max(recordAppErrorBodyOsVersionMax) + .regex(recordAppErrorBodyOsVersionRegExp) + .optional() + .describe( + "The operating system's major version, such as 11, when the browser says it.", + ), }) .describe( - "An error the app hit and did not handle, as the app saw it. OpenBot scrubs and bounds it again before it is sent anywhere.", + "An error the app hit and did not handle, as the app saw it. OpenBot scrubs and bounds it again before it is sent anywhere. Where it happened is said only by the route's pattern, the page's and browser's languages and the browser's and operating system's names and major versions, never by an address, an ID or anything on the page.", ); export const RecordAppErrorResponse = zod.void(); @@ -186,6 +278,41 @@ export const recordSignedOutAppErrorBodyAppVersionMax = 32; export const recordSignedOutAppErrorBodyAppVersionRegExp = new RegExp( "^v?\\d+(?:\\.\\d+){1,3}(?:-[a-z]+(?:\\.\\d{1,9})?)?$", ); +export const recordSignedOutAppErrorBodyRouteMax = 200; + +export const recordSignedOutAppErrorBodyRouteRegExp = new RegExp( + "^/[A-Za-z0-9_$./~{}*-]*$", +); +export const recordSignedOutAppErrorBodyPageLanguageMax = 35; + +export const recordSignedOutAppErrorBodyPageLanguageRegExp = new RegExp( + "^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4}$", +); +export const recordSignedOutAppErrorBodyBrowserLanguageMax = 35; + +export const recordSignedOutAppErrorBodyBrowserLanguageRegExp = new RegExp( + "^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4}$", +); +export const recordSignedOutAppErrorBodyBrowserNameMax = 64; + +export const recordSignedOutAppErrorBodyBrowserNameRegExp = new RegExp( + "^[A-Za-z0-9 ._()-]+$", +); +export const recordSignedOutAppErrorBodyBrowserVersionMax = 6; + +export const recordSignedOutAppErrorBodyBrowserVersionRegExp = new RegExp( + "^\\d{1,6}$", +); +export const recordSignedOutAppErrorBodyOsNameMax = 64; + +export const recordSignedOutAppErrorBodyOsNameRegExp = new RegExp( + "^[A-Za-z0-9 ._()-]+$", +); +export const recordSignedOutAppErrorBodyOsVersionMax = 6; + +export const recordSignedOutAppErrorBodyOsVersionRegExp = new RegExp( + "^\\d{1,6}$", +); export const RecordSignedOutAppErrorBody = zod .object({ @@ -220,9 +347,70 @@ export const RecordSignedOutAppErrorBody = zod .describe( "The release the app was built for, such as 1.1.0-rc.2, when the build knows it.", ), + route: zod + .string() + .min(1) + .max(recordSignedOutAppErrorBodyRouteMax) + .regex(recordSignedOutAppErrorBodyRouteRegExp) + .optional() + .describe( + "The pattern of the app's route the page was on, such as /bots/$botId, never its address. No IDs, query or fragment.", + ), + pageLanguage: zod + .string() + .min(1) + .max(recordSignedOutAppErrorBodyPageLanguageMax) + .regex(recordSignedOutAppErrorBodyPageLanguageRegExp) + .optional() + .describe( + "The page's language, from the lang attribute of its html element, such as en. A page translated in the browser often says the language it was translated into.", + ), + pageTranslated: zod + .boolean() + .optional() + .describe( + "Whether the browser had translated the page when the error happened, by the marks a page translator leaves on it.", + ), + browserLanguage: zod + .string() + .min(1) + .max(recordSignedOutAppErrorBodyBrowserLanguageMax) + .regex(recordSignedOutAppErrorBodyBrowserLanguageRegExp) + .optional() + .describe("The browser's preferred language, such as pt-BR."), + browserName: zod + .string() + .min(1) + .max(recordSignedOutAppErrorBodyBrowserNameMax) + .regex(recordSignedOutAppErrorBodyBrowserNameRegExp) + .optional() + .describe("The browser's name, such as Chrome or Safari."), + browserVersion: zod + .string() + .min(1) + .max(recordSignedOutAppErrorBodyBrowserVersionMax) + .regex(recordSignedOutAppErrorBodyBrowserVersionRegExp) + .optional() + .describe("The browser's major version, such as 141."), + osName: zod + .string() + .min(1) + .max(recordSignedOutAppErrorBodyOsNameMax) + .regex(recordSignedOutAppErrorBodyOsNameRegExp) + .optional() + .describe("The operating system's name, such as Windows or macOS."), + osVersion: zod + .string() + .min(1) + .max(recordSignedOutAppErrorBodyOsVersionMax) + .regex(recordSignedOutAppErrorBodyOsVersionRegExp) + .optional() + .describe( + "The operating system's major version, such as 11, when the browser says it.", + ), }) .describe( - "An error the app hit and did not handle, as the app saw it. OpenBot scrubs and bounds it again before it is sent anywhere.", + "An error the app hit and did not handle, as the app saw it. OpenBot scrubs and bounds it again before it is sent anywhere. Where it happened is said only by the route's pattern, the page's and browser's languages and the browser's and operating system's names and major versions, never by an address, an ID or anything on the page.", ); export const RecordSignedOutAppErrorResponse = zod.void(); diff --git a/app/src/lib/error-context.ts b/app/src/lib/error-context.ts new file mode 100644 index 0000000000..e7343517a5 --- /dev/null +++ b/app/src/lib/error-context.ts @@ -0,0 +1,174 @@ +import type { AppError } from "@/lib/api/generated/model"; + +/** + * WHERE AN ERROR HAPPENED, WITHOUT SAYING WHO OR WHAT WAS ON THE PAGE. + * + * A report reaches PostHog through this OpenBot's own server, so PostHog sees the server's user agent + * and the server's address, and nothing of the browser. That left errors no one could act on: React's + * `NotFoundError` from `insertBefore` and `removeChild`, which a page translator (Google Translate, + * Chrome's and Edge's built-in translation) causes by rewriting the text React drew, could not be told + * apart from a bug in OpenBot, or tied to a screen. So each report says, as Sentry, PostHog's own SDK + * and Datadog RUM attach to every error: + * + * - the route's pattern (`/bots/$botId`), as Sentry's parameterised transaction names and Datadog's + * view names group pages, never the address: no IDs, no query, no fragment; + * - the page's language (``), and whether a translator has rewritten the page, by the marks + * it leaves: `translated-ltr`/`translated-rtl` on `` and its `` wrappers for Google's, + * `_msttexthash` for Microsoft's; + * - the browser's preferred language (`navigator.language`); + * - the browser's and the operating system's names and major versions: from the browser's client + * hints where it has them (Chromium), since Chromium's user agent string is frozen at Windows 10 + * and macOS 10.15, else from the user agent string, read by Bowser. A Windows or macOS version the + * string alone gives is frozen in every browser, so it is left out. + * + * Each value is held to the pattern the API gives it (`AppError` in api/openapi.yaml) and left out + * when it doesn't fit, so a report is never refused for what it says about the page. + */ + +type Device = Pick< + AppError, + "browserName" | "browserVersion" | "osName" | "osVersion" +>; +type Page = Pick< + AppError, + "route" | "pageLanguage" | "pageTranslated" | "browserLanguage" +>; + +/** The patterns `AppError` holds these to. */ +const ROUTE = /^\/[A-Za-z0-9_$./~{}*-]*$/; +const LANGUAGE = /^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8}){0,4}$/; +const NAME = /^[A-Za-z0-9 ._()-]{1,64}$/; +const MAJOR = /^\d{1,6}$/; + +function fits(value: string | undefined, pattern: RegExp, max: number) { + return value && value.length <= max && pattern.test(value) + ? value + : undefined; +} + +/** `{ key: value }` when there is a value, `{}` when there isn't. */ +function only(key: K, value: V | undefined) { + return (value === undefined ? {} : { [key]: value }) as Partial>; +} + +/** Where the app's router is, for the route's pattern (`reportRoutesOf`). */ +let routeNow: (() => string | undefined) | null = null; + +/** + * Report the route the router is on with each error. The deepest match's pattern + * (`/bots/$botId`), never its address. + */ +export function reportRoutesOf(router: { + state: { matches: readonly { fullPath: string }[] }; +}): void { + routeNow = () => router.state.matches.at(-1)?.fullPath; +} + +/** Whether a page translator has rewritten the page, by the marks it leaves. */ +function translated(): boolean { + const html = document.documentElement; + if ( + html.classList.contains("translated-ltr") || + html.classList.contains("translated-rtl") + ) + return true; + return ( + document.querySelector('font[style*="vertical-align"], [_msttexthash]') !== + null + ); +} + +/** What the page is, read as the error is reported. */ +export function pageContext(): Page { + if (typeof document === "undefined") return {}; + let route: string | undefined; + try { + route = routeNow?.(); + } catch { + // The router could not say: the report goes without it. + } + return { + ...only("route", fits(route, ROUTE, 200)), + ...only( + "pageLanguage", + fits(document.documentElement.lang || undefined, LANGUAGE, 35), + ), + pageTranslated: translated(), + ...only( + "browserLanguage", + fits( + typeof navigator === "undefined" ? undefined : navigator.language, + LANGUAGE, + 35, + ), + ), + }; +} + +type UserAgentData = { + brands?: { brand: string; version: string }[]; + mobile?: boolean; + platform?: string; + getHighEntropyValues?: ( + hints: string[], + ) => Promise<{ platformVersion?: string }>; +}; + +const majorOf = (version: string | undefined) => + fits(/^\d+/.exec(version ?? "")?.[0], MAJOR, 6); + +/** + * The operating system's major version from Chromium's client hints. Windows says its own + * numbering: a platform version of 13 or more is Windows 11, 1 to 10 is Windows 10 + * (https://learn.microsoft.com/microsoft-edge/web-platform/how-to-detect-win11). + */ +function osVersionFromHints(os: string | undefined, platformVersion: string) { + const major = majorOf(platformVersion); + if (major === undefined) return undefined; + if (os === "Windows") { + const number = Number(major); + return number >= 13 ? "11" : number >= 1 ? "10" : undefined; + } + return major === "0" ? undefined : major; +} + +async function readDevice(): Promise { + if (typeof navigator === "undefined") return {}; + const hints = (navigator as Navigator & { userAgentData?: UserAgentData }) + .userAgentData; + const { default: Bowser } = await import("bowser"); + const parsed = Bowser.parse( + navigator.userAgent, + hints?.brands ? { brands: hints.brands } : undefined, + ); + const osName = fits(parsed.os.name, NAME, 64); + let osVersion: string | undefined; + if (hints?.getHighEntropyValues) { + try { + const { platformVersion } = await hints.getHighEntropyValues([ + "platformVersion", + ]); + if (platformVersion) + osVersion = osVersionFromHints(osName, platformVersion); + } catch { + // The browser would not say. + } + } else if (osName === "iOS" || osName === "Android") { + // Only these keep a true version in the string. + osVersion = majorOf(parsed.os.version); + } + return { + ...only("browserName", fits(parsed.browser.name, NAME, 64)), + ...only("browserVersion", majorOf(parsed.browser.version)), + ...only("osName", osName), + ...only("osVersion", osVersion), + }; +} + +let device: Promise | null = null; + +/** The browser and the operating system, read once a page and kept. Never rejects. */ +export function deviceContext(): Promise { + device ??= readDevice().catch(() => ({})); + return device; +} diff --git a/app/src/lib/error-reporting.tsx b/app/src/lib/error-reporting.tsx index 4394b633d8..072ab58382 100644 --- a/app/src/lib/error-reporting.tsx +++ b/app/src/lib/error-reporting.tsx @@ -15,6 +15,7 @@ import { idempotencyKey } from "@/lib/api/request"; import { heldOutBySso } from "@/lib/auth/held-out"; import { recordProblem } from "@/lib/desktop/problems"; import { desktopShell } from "@/lib/desktop/shell"; +import { deviceContext, pageContext } from "@/lib/error-context"; import { appVersion } from "@/lib/error-details"; import { askAgainAfterMs, unavailableSaid } from "@/lib/load-failure"; import { currentOrganizationId } from "@/lib/organizations/current"; @@ -35,6 +36,10 @@ import { inNoOrganization } from "@/lib/organizations/in-no-organization"; * the person's organization is known (signing in, the sign-in page) the report goes to the address * that names no organization (recordSignedOutAppError), under the same bounds: signing in can break * too, and the server attaches nobody to it. + * + * Each report also says where it happened, without saying who or what was on the page: the route's + * pattern, the page's and the browser's languages, whether a translator had rewritten the page, and + * the browser's and operating system's names and major versions (`lib/error-context.ts`). */ const MAX_REPORTS = 10; @@ -285,22 +290,33 @@ export function reportAppError( seenKinds.add(kind); sentCount += 1; const version = appVersion(); + // The page as it is now, and where the report goes now: both can change while the browser is read. + let page: ReturnType = {}; + try { + page = pageContext(); + } catch { + // Reading the page went wrong: the error is told without it. + } const appError: AppError = { source, ...report, surface: desktopShell() ? "desktop" : "web", ...(version ? { appVersion: version } : {}), + ...page, }; const headers = { "Idempotency-Key": idempotencyKey() }; const organization = currentOrganizationId(); - // Before an organization is known (signing in), to the address that names none. - const sent = - organization === undefined - ? recordSignedOutAppError(appError, headers, { keepalive: true }) - : recordAppError(organization, appError, headers, { keepalive: true }); - sent.catch(() => { - // A report that could not be delivered is not the person's problem, and is not retried. - }); + void deviceContext() + .then((device) => { + const told = { ...appError, ...device }; + // Before an organization is known (signing in), to the address that names none. + return organization === undefined + ? recordSignedOutAppError(told, headers, { keepalive: true }) + : recordAppError(organization, told, headers, { keepalive: true }); + }) + .catch(() => { + // A report that could not be delivered is not the person's problem, and is not retried. + }); } /** Stops the listening `installAppErrorReporting` started, or null while it has not. */ @@ -309,6 +325,8 @@ let uninstall: (() => void) | null = null; /** Listens, once per page, for errors the page threw and promises nobody handled. */ export function installAppErrorReporting(): void { if (uninstall || typeof window === "undefined") return; + // The browser is read once, ahead of any error, so a report waits on nothing. + void deviceContext(); const onError = (event: ErrorEvent) => reportAppError( "window_error", diff --git a/app/src/router.tsx b/app/src/router.tsx index 78656697fe..f7051d4396 100644 --- a/app/src/router.tsx +++ b/app/src/router.tsx @@ -1,5 +1,6 @@ import { createRouter } from "@tanstack/react-router"; import { restoreParkedReturn } from "./lib/auth/return-address"; +import { reportRoutesOf } from "./lib/error-context"; import { ReportedErrorComponent } from "./lib/error-reporting"; import { loadCodeEarly } from "./lib/route-code"; import { parseSearchText } from "./lib/search-text"; @@ -37,6 +38,9 @@ export const router = createRouter({ */ loadCodeEarly(router); +// Each error report says the route's pattern the page was on, never its address (lib/error-context.ts). +reportRoutesOf(router); + declare module "@tanstack/react-router" { interface Register { router: typeof router; diff --git a/app/tests/app-error-context-browser.fixture.tsx b/app/tests/app-error-context-browser.fixture.tsx new file mode 100644 index 0000000000..c9eeca5334 --- /dev/null +++ b/app/tests/app-error-context-browser.fixture.tsx @@ -0,0 +1,48 @@ +import "@/lib/trusted-types"; +import { + createRootRoute, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { useEffect } from "react"; +import { createRoot } from "react-dom/client"; +import { reportRoutesOf } from "@/lib/error-context"; +import { + installAppErrorReporting, + reportAppError, +} from "@/lib/error-reporting"; + +/** + * A screen that throws as it draws, under the app's router and its error reporting, for + * app-error-reporting-browser.test.ts to bundle. As the app's router does (`router.tsx`), the router + * is handed to the reporting, and the route's error screen reports what it caught, as + * `ReportedErrorComponent` does. The page is opened at a Bot's address with an ID, a query and a + * fragment, none of which may reach the report. + */ + +installAppErrorReporting(); + +function BrokenBot(): never { + throw new TypeError("Failed to draw the Bot's page"); +} + +function Reported({ error }: { error: Error }) { + useEffect(() => reportAppError("error_boundary", error), [error]); + return

This page couldn't be shown

; +} + +const root = createRootRoute({ component: Outlet }); +const bot = createRoute({ + getParentRoute: () => root, + path: "/bots/$botId", + component: BrokenBot, + errorComponent: Reported, +}); +const router = createRouter({ routeTree: root.addChildren([bot]) }); +reportRoutesOf(router); + +const element = document.getElementById("root"); +if (!element) throw new Error("no root"); +createRoot(element).render(); diff --git a/app/tests/app-error-reporting-browser.test.ts b/app/tests/app-error-reporting-browser.test.ts index 94b58507ce..89820108a0 100644 --- a/app/tests/app-error-reporting-browser.test.ts +++ b/app/tests/app-error-reporting-browser.test.ts @@ -23,6 +23,16 @@ import { test } from "./renderer-crash"; * reported. * 3. OpenBot's own Trusted Types refusals on that same page still are, in its window and in a frame. * + * AND A REPORT SAYS WHERE IT HAPPENED, WITHOUT THE ADDRESS. React's `NotFoundError` from + * `insertBefore` and `removeChild` reached PostHog from Cloud and from Desktop installs in China, + * Brazil and Japan from 3 December 2026, with nothing to say whether a page translator had rewritten + * the page or which screen it was. So, on a Bot's page with an ID, a query and a fragment in its + * address, a screen that throws is reported with: + * + * 4. the route's pattern, the page's language, whether it was translated (as Google Translate marks + * ``), the browser's language, and the browser and operating system; and none of the + * address. + * * 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"; @@ -61,6 +71,9 @@ const CLOUDFLARE_FILE = "/cdn-cgi/challenge-platform/h/g/scripts/jsd/orchestrate.js"; function html(which: string): string { + if (which === "translated" || which === "untranslated") + // As Google Translate leaves a page it translated into Japanese: `lang` and a class on ``. + return `${cspMeta()}
`; const cloudflare = which === "cloudflare" ? `${CLOUDFLARE_SCRIPT}` @@ -72,14 +85,12 @@ function html(which: string): string { let files: Map; const browsers = new Map(); -beforeAll(async () => { - if (!asked) return; +/** A fixture bundled as the app's page loads it, served as `/.js`. */ +async function bundle(fixture: string, name: string) { const built = await Bun.build({ - entrypoints: [ - join(import.meta.dir, "app-error-reporting-browser.fixture.ts"), - ], + entrypoints: [join(import.meta.dir, fixture)], target: "browser", - naming: { entry: "fixture.[ext]", asset: "[name].[ext]" }, + naming: { entry: `${name}.[ext]`, asset: "[name].[ext]" }, define: { "process.env.NODE_ENV": JSON.stringify("production") }, plugins: [ { @@ -98,8 +109,16 @@ beforeAll(async () => { ], }); if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + return built.outputs; +} + +beforeAll(async () => { + if (!asked) return; files = new Map(); - for (const output of built.outputs) + for (const output of [ + ...(await bundle("app-error-reporting-browser.fixture.ts", "fixture")), + ...(await bundle("app-error-context-browser.fixture.tsx", "context")), + ]) files.set(`/${basename(output.path)}`, await output.text()); const playwright = await import("playwright-core"); for (const engine of engines) { @@ -121,16 +140,18 @@ type Report = { type: string; message: string; stack?: string; -}; +} & Record; /** The page for `which`, and every report it sends, in the order it sends them. */ async function open( engine: string, which: string, + address = `/sign?case=${which}`, ): Promise<{ page: Page; reports: Report[] }> { const browser = browsers.get(engine); if (!browser) throw new Error(`no ${engine}`); - const page = await browser.newPage(); + // A person in Brazil, whose browser prefers Brazilian Portuguese. + const page = await browser.newPage({ locale: "pt-BR" }); const reports: Report[] = []; await page.route(`${ORIGIN}/**`, (route) => { const request = route.request(); @@ -152,10 +173,14 @@ async function open( 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}`); + await page.goto(`${ORIGIN}${address}`); return { page, reports }; } +/** A Bot's address, with what may never reach a report: its ID, a query and a fragment. */ +const BOT_ID = "bot_8f3a9c2e"; +const BOT_ADDRESS = `/bots/${BOT_ID}?q=private-search#section-2`; + /** Wait for a report whose message is `message`, then every report sent before it. */ async function reportsUpTo( reports: Report[], @@ -229,5 +254,54 @@ describe.skipIf(!asked)("Errors the page did not handle", () => { await page.close(); } }, 60_000); + + test(`${engine}: a report says the route's pattern, the languages, a translated page and the browser, and never the address`, async () => { + const { page, reports } = await open(engine, "translated", BOT_ADDRESS); + try { + const [report] = await reportsUpTo( + reports, + "Failed to draw the Bot's page", + ); + expect(report).toMatchObject({ + source: "error_boundary", + type: "TypeError", + route: "/bots/$botId", + pageLanguage: "ja", + pageTranslated: true, + browserLanguage: "pt-BR", + }); + // The engine as Bowser reads it, from client hints in Chromium and the string in WebKit. + expect(String(report?.browserName)).toMatch( + engine === "chromium" ? /^Chrom/ : /^Safari$/, + ); + expect(String(report?.browserVersion)).toMatch(/^\d+$/); + expect(String(report?.osName)).toMatch(/^(Linux|macOS|Windows)$/); + // Nothing of the address: not the ID, the query, the fragment or the host. The stack names + // the script it ran in, which the server cuts to its path. + const { stack: _stack, ...said } = report ?? {}; + const text = JSON.stringify(said); + for (const never of [BOT_ID, "private-search", "section-2", ORIGIN]) + expect(text).not.toContain(never); + } finally { + await page.close(); + } + }, 60_000); + + test(`${engine}: a page nobody translated is reported as not translated`, async () => { + const { page, reports } = await open(engine, "untranslated", BOT_ADDRESS); + try { + const [report] = await reportsUpTo( + reports, + "Failed to draw the Bot's page", + ); + expect(report).toMatchObject({ + route: "/bots/$botId", + pageLanguage: "en", + pageTranslated: false, + }); + } finally { + await page.close(); + } + }, 60_000); } }); diff --git a/bun.lock b/bun.lock index efb3239876..a4a8f845dc 100644 --- a/bun.lock +++ b/bun.lock @@ -47,6 +47,7 @@ "@xterm/xterm": "6.0.0", "better-auth": "^1.6.27", "boring-avatars": "^2.0.4", + "bowser": "^2.15.1", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "colorjs.io": "0.7.1", @@ -1169,6 +1170,8 @@ "boring-avatars": ["boring-avatars@2.0.4", "", { "peerDependencies": { "react": ">=18.0.0", "react-dom": ">=18.0.0" } }, "sha512-xhZO/w/6aFmRfkaWohcl2NfyIy87gK5SBbys8kctZeTGF1Apjpv/10pfUuv+YEfVPkESU/h2Y6tt/Dwp+bIZPw=="], + "bowser": ["bowser@2.15.1", "", {}, "sha512-ma47ABeUiTsmG4McKDtGCgQSiTCatM97Mlbn13K42N1kPSFE14oN3WFMjtyL4KubhGvQTqYheKl4Qx2bJtMXLQ=="], + "brace-expansion": ["brace-expansion@5.0.12", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="], "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 2b23bf2636..2b7f346b27 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -61,7 +61,7 @@ Tool/activity-only outputs, nested code/table copy controls, native mobile and e The server sends one for an exception nothing caught (`uncaught_exception`, level `fatal`; the server still logs it and exits as before, after waiting at most two seconds for the send), a promise nobody handled (`unhandled_rejection`; the server keeps running, as before), and a request the server answered with a 5xx because a route threw (`http_5xx`, with `http_method` and the route's pattern as `http_route`, such as `/api/v2/organizations/:organizationId/bots/:botId`, never its address). -The web app reports what its error screen caught (`error_boundary`), an error the page threw (`window_error`) and a promise nobody handled (`unhandled_rejection`) to its own server, at `POST /api/v2/organizations/{organizationId}/app-errors` (`recordAppError`), with keepalive and no retry. The server forwards it under the signed-in person's `user_id` pseudonym, with `app_surface` and the release the app was built for as `app_version`, so the browser never holds a telemetry key. A page sends the same error once and at most ten in all, and nothing before the person's organization is known. Like a result view, the report is accepted and dropped where telemetry is off. +The web app reports what its error screen caught (`error_boundary`), an error the page threw (`window_error`) and a promise nobody handled (`unhandled_rejection`) to its own server, at `POST /api/v2/organizations/{organizationId}/app-errors` (`recordAppError`), with keepalive and no retry. The server forwards it under the signed-in person's `user_id` pseudonym, with `app_surface` and the release the app was built for as `app_version`, so the browser never holds a telemetry key. The report also says where it happened, under the names PostHog's browser SDK uses: the route's pattern as `$pathname` and `app_route` (`/bots/$botId`, never the page's address), the browser's language as `$browser_language`, the browser's and operating system's names and major versions as `$browser`, `$browser_version`, `$os` and `$os_version` (from the browser's client hints where it has them, else its user agent string, which is never sent), and the page's `lang` as `page_language` with `page_translated` when a page translator had rewritten the page. These are the browser's own, never the server's user agent. A page sends the same error once and at most ten in all, and nothing before the person's organization is known. Like a result view, the report is accepted and dropped where telemetry is off. Nothing personal is sent. A message is scrubbed of secrets (the token shapes and credential names the command scrubber knows), email addresses, URLs past their scheme and host, IPv4 addresses, runs of seven or more digits, home directories' owners and anything quoted that is not a short identifier, so `reading 'map'` stays and `Unexpected token "what somebody wrote"` does not; then it is cut to 512 characters. A frame keeps the path of its file, never the deployment's host or a query. Request bodies, prompts, messages, tokens, emails and names are never read into an exception. An event holds at most four chained exceptions, thirty frames for the one thrown and ten for each cause, and is cut to fit the sink. Each server process sends at most five of one kind and fifty in all in any ten minutes.