Files
supabase/apps/studio/lib/sentry-client-options.test.ts
Drew McLellan 8f73c10ce1 feat(studio): sample browser-translation DOM errors in Sentry (#53600)
## Problem

Browser translation (e.g. Chrome Translate) and some extensions rewrite
DOM text nodes, which makes React throw `insertBefore` / `removeChild`
errors. We drop all of these via `ignoreErrors`, so we have no signal on
how often they still happen after the dynamic-text ESLint rule (#52949).

Linear:
[FE-5008](https://linear.app/supabase/issue/FE-5008/sample-sentry-events-for-browser-translation-crashes-instead-of),
from the investigation in
[FE-5013](https://linear.app/supabase/issue/FE-5013/investigate-how-we-currently-hide-browser-translation-insertremove).

## Solution

Stop ignoring these errors in Studio and send a 5% sample, tagged so
they are easy to find in Sentry.

- Move the insert/remove node messages from
`BROWSER_NOISE_IGNORE_ERRORS` into a new
`BROWSER_TRANSLATION_DOM_ERRORS` list in `packages/common/sentry.ts`.
`docs` and `www` add it to `ignoreErrors`, so their behavior is
unchanged.
- In Studio's `beforeSend`, tag matching events with
`browser_translation`, `page_translated` and `sample_rate`. The existing
`shouldDropForSampleRate` applies the rate.
- `page_translated` is best effort: it checks for the `translated-ltr` /
`translated-rtl` class on `<html>` and Google Translate `<font>`
wrappers. Firefox and Edge are less reliable, so `false` is not proof.
- `filterSentryEvent` skips its 1% non-crash sampling for tagged events.
Without this the rates would multiply and 5% would really be 0.05%.
- The generic `parentNode` / `removeChild` null reads stay ignored. They
have many unrelated causes, so tagging them as translation would
mislead.

Not in this PR:

- The `text content does not match` and hydration ignores. They are
related symptoms and should be a follow-up.
- The user-facing fallback in `InsertBeforeRemoveChildErrorHandler`.

## Review instructions

1. Check that `docs` and `www` still ignore the five DOM messages, via
`BROWSER_TRANSLATION_DOM_ERRORS` in their `instrumentation-client.ts`.
2. Run `pnpm exec vitest run lib/sentry-client-options.test.ts` from
`apps/studio`, and `pnpm exec vitest run sentry.test.ts` from
`packages/common`.
3. After merge, filter Sentry for `browser_translation:true` on the
production Studio project and compare `page_translated` true against
false.

## Before merging

Sentry also has server-side inbound filters on the production Studio
project. Someone with project access should confirm the `error-message`
filter doesn't match these messages. If it does, the sampled events will
be dropped on arrival.

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill (not applicable)
2026-11-20 13:40:23 +00:00

668 lines
22 KiB
TypeScript

import type { Event as SentryEvent, StackFrame } from '@sentry/react'
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import {
buildSentryClientOptions,
isBrowserWalletExtensionError,
isCancellationRejection,
isChallengeExpiredError,
isUserAbortedOperation,
shouldDropForSampleRate,
tagBrowserTranslationError,
} from './sentry-client-options'
describe('Sentry beforeSend filtering functions', () => {
describe('isBrowserWalletExtensionError', () => {
it('returns true for wallet-provider in abs_path', () => {
const event: SentryEvent = {
exception: {
values: [
{
type: 'Error',
value: 'wallet error',
stacktrace: {
frames: [
{ abs_path: 'chrome-extension://abc123/wallet-provider.js' } as StackFrame,
],
},
},
],
},
}
expect(isBrowserWalletExtensionError(event)).toBe(true)
})
it('returns false for regular application errors', () => {
const event: SentryEvent = {
exception: {
values: [
{
type: 'Error',
value: 'Regular error',
stacktrace: {
frames: [
{ filename: 'app:///_next/static/chunks/main.js' } as StackFrame,
{ filename: 'app:///_next/static/chunks/pages/index.js' } as StackFrame,
],
},
},
],
},
}
expect(isBrowserWalletExtensionError(event)).toBe(false)
})
it('returns false for empty event', () => {
const event: SentryEvent = {}
expect(isBrowserWalletExtensionError(event)).toBe(false)
})
it('returns false when exception values are empty', () => {
const event: SentryEvent = {
exception: {
values: [],
},
}
expect(isBrowserWalletExtensionError(event)).toBe(false)
})
it('returns false when stacktrace frames are undefined', () => {
const event: SentryEvent = {
exception: {
values: [
{
type: 'Error',
value: 'Error without stacktrace',
},
],
},
}
expect(isBrowserWalletExtensionError(event)).toBe(false)
})
})
describe('isUserAbortedOperation', () => {
it.each([
// SUPABASE-APP-BG6
'The operation was aborted.',
// SUPABASE-APP-BG7
'signal is aborted without reason',
'operation is manually canceled',
'AbortError: The operation was aborted',
])('returns true for an error with message %o', (message) => {
expect(isUserAbortedOperation(new Error(message), {})).toBe(true)
})
it('returns true when message is in event.message (no error object)', () => {
const error = null
const event: SentryEvent = {
message: '[CRITICAL][sign in via EP] Failed: The operation was aborted.',
}
expect(isUserAbortedOperation(error, event)).toBe(true)
})
it('returns true for event message with "signal is aborted"', () => {
const event: SentryEvent = {
message: '[CRITICAL][sign in via EP] Failed: signal is aborted without reason',
}
expect(isUserAbortedOperation(undefined, event)).toBe(true)
})
it('returns false for regular errors', () => {
const error = new Error('Something went wrong')
const event: SentryEvent = {}
expect(isUserAbortedOperation(error, event)).toBe(false)
})
it('returns false for empty inputs', () => {
expect(isUserAbortedOperation(null, {})).toBe(false)
expect(isUserAbortedOperation(undefined, {})).toBe(false)
})
it('handles non-Error objects gracefully', () => {
const error = { message: 'The operation was aborted.' }
const event: SentryEvent = {}
// Non-Error objects should not match since we check instanceof Error
expect(isUserAbortedOperation(error, event)).toBe(false)
})
})
describe('isCancellationRejection', () => {
it('returns true for cancellation type in extra.__serialized__', () => {
const event: SentryEvent = {
extra: {
__serialized__: {
msg: 'operation is manually canceled',
type: 'cancelation',
},
},
}
expect(isCancellationRejection(event)).toBe(true)
})
it('returns false when type is not cancelation', () => {
const event: SentryEvent = {
extra: {
__serialized__: {
msg: 'some error',
type: 'error',
},
},
}
expect(isCancellationRejection(event)).toBe(false)
})
it('returns false when __serialized__ is undefined', () => {
const event: SentryEvent = {
extra: {},
}
expect(isCancellationRejection(event)).toBe(false)
})
it('returns false when extra is undefined', () => {
const event: SentryEvent = {}
expect(isCancellationRejection(event)).toBe(false)
})
it('returns false when __serialized__ has no type property', () => {
const event: SentryEvent = {
extra: {
__serialized__: {
msg: 'some message',
},
},
}
expect(isCancellationRejection(event)).toBe(false)
})
})
describe('isChallengeExpiredError', () => {
it('returns true for challenge-expired error message', () => {
const error = new Error('Non-Error promise rejection captured with value: challenge-expired')
const event: SentryEvent = {}
expect(isChallengeExpiredError(error, event)).toBe(true)
})
it('returns true when challenge-expired is in event.message', () => {
const event: SentryEvent = {
message: 'challenge-expired',
}
expect(isChallengeExpiredError(null, event)).toBe(true)
})
it('returns false for regular errors', () => {
const error = new Error('Something went wrong')
const event: SentryEvent = {}
expect(isChallengeExpiredError(error, event)).toBe(false)
})
it('returns false for empty inputs', () => {
expect(isChallengeExpiredError(null, {})).toBe(false)
expect(isChallengeExpiredError(undefined, {})).toBe(false)
})
it('returns false for similar but different messages', () => {
const error = new Error('challenge expired') // No hyphen
const event: SentryEvent = {}
expect(isChallengeExpiredError(error, event)).toBe(false)
})
})
describe('integration scenarios', () => {
it('correctly identifies SUPABASE-APP-353 pattern (cancellation rejection)', () => {
// Based on actual Sentry issue SUPABASE-APP-353
const event: SentryEvent = {
exception: {
values: [
{
type: 'UnhandledRejection',
value: 'Object captured as promise rejection with keys: msg, type',
},
],
},
extra: {
__serialized__: {
msg: 'operation is manually canceled',
type: 'cancelation',
},
},
}
expect(isCancellationRejection(event)).toBe(true)
})
it('correctly identifies SUPABASE-APP-AFC pattern (wallet extension)', () => {
// Based on actual Sentry issue SUPABASE-APP-AFC
const event: SentryEvent = {
exception: {
values: [
{
type: 'TypeError',
value: 'f.shouldSetTallyForCurrentProvider is not a function',
stacktrace: {
frames: [
{
filename:
'node_modules/.pnpm/@sentry+browser@10.27.0/node_modules/@sentry/browser/src/helpers.ts',
function: 'n',
} as StackFrame,
{
filename: 'app:///gt-window-provider-btc.js',
function: 'GateWindowProvider.internalListener',
} as StackFrame,
],
},
},
],
},
}
expect(isBrowserWalletExtensionError(event)).toBe(true)
})
it('correctly identifies SUPABASE-APP-92A pattern (wallet extension)', () => {
// Based on actual Sentry issue SUPABASE-APP-92A
const event: SentryEvent = {
exception: {
values: [
{
type: 'TypeError',
value: 'en.shouldSetTallyForCurrentProvider is not a function',
stacktrace: {
frames: [
{
filename:
'node_modules/.pnpm/@sentry+browser@10.27.0/node_modules/@sentry/browser/src/helpers.ts',
function: 'n',
} as StackFrame,
{
filename: 'app:///gt-window-provider.js',
function: 'GateWindowProvider.internalListener',
} as StackFrame,
],
},
},
],
},
}
expect(isBrowserWalletExtensionError(event)).toBe(true)
})
it('correctly identifies SUPABASE-APP-ACC pattern (challenge expired)', () => {
// Based on actual Sentry issue SUPABASE-APP-ACC
const error = new Error('Non-Error promise rejection captured with value: challenge-expired')
const event: SentryEvent = {
exception: {
values: [
{
type: 'UnhandledRejection',
value: 'Non-Error promise rejection captured with value: challenge-expired',
},
],
},
}
expect(isChallengeExpiredError(error, event)).toBe(true)
})
it('does not filter legitimate errors', () => {
const error = new Error('Cannot read property "foo" of undefined')
const event: SentryEvent = {
exception: {
values: [
{
type: 'TypeError',
value: 'Cannot read property "foo" of undefined',
stacktrace: {
frames: [{ filename: 'app:///_next/static/chunks/pages/index.js' } as StackFrame],
},
},
],
},
}
expect(isBrowserWalletExtensionError(event)).toBe(false)
expect(isUserAbortedOperation(error, event)).toBe(false)
expect(isCancellationRejection(event)).toBe(false)
expect(isChallengeExpiredError(error, event)).toBe(false)
})
})
})
describe('shouldDropForSampleRate', () => {
it('keeps events without a sample_rate tag', () => {
expect(shouldDropForSampleRate({}, () => 0.99)).toBe(false)
})
it('keeps events with rate 1', () => {
expect(shouldDropForSampleRate({ tags: { sample_rate: 1 } }, () => 0.99)).toBe(false)
})
it('keeps or drops sampled events depending on the random draw', () => {
const event = { tags: { sample_rate: 0.1 } }
expect(shouldDropForSampleRate(event, () => 0.05)).toBe(false)
expect(shouldDropForSampleRate(event, () => 0.5)).toBe(true)
})
it('accepts numeric string rates', () => {
expect(shouldDropForSampleRate({ tags: { sample_rate: '0.1' } }, () => 0.5)).toBe(true)
})
})
describe('tagBrowserTranslationError', () => {
const domError = (): SentryEvent => ({
exception: {
values: [
{
type: 'NotFoundError',
value: "Failed to execute 'removeChild' on 'Node': The node is not a child of this node.",
},
],
},
})
it('tags the error and sets the sample rate', () => {
const event = domError()
tagBrowserTranslationError(event, true)
expect(event.tags).toEqual({
sample_rate: 0.05,
browser_translation: true,
page_translated: true,
})
})
it('records when the page was not translated', () => {
const event = domError()
tagBrowserTranslationError(event, false)
expect(event.tags?.page_translated).toBe(false)
})
it('looks the page up itself when no answer is passed in', () => {
// Node test environment: there is no document, so the page counts as untranslated
const event = domError()
tagBrowserTranslationError(event)
expect(event.tags?.page_translated).toBe(false)
})
it('detects a translated page when no answer is passed in', () => {
vi.stubGlobal('document', {
documentElement: { classList: { contains: (cls: string) => cls === 'translated-ltr' } },
querySelector: () => null,
})
try {
const event = domError()
tagBrowserTranslationError(event)
expect(event.tags?.page_translated).toBe(true)
} finally {
vi.unstubAllGlobals()
}
})
it('uses the default rate when sample_rate is explicitly undefined', () => {
const event = { ...domError(), tags: { sample_rate: undefined } }
tagBrowserTranslationError(event, false)
expect(event.tags.sample_rate).toBe(0.05)
})
it('keeps tags that are already set', () => {
const event = { ...domError(), tags: { globalErrorBoundary: true, sample_rate: 1 } }
tagBrowserTranslationError(event, false)
expect(event.tags).toMatchObject({ globalErrorBoundary: true, sample_rate: 1 })
})
it('leaves other errors alone', () => {
const event: SentryEvent = {
exception: { values: [{ type: 'Error', value: 'Application error' }] },
}
tagBrowserTranslationError(event, true)
expect(event.tags).toBeUndefined()
})
})
describe('buildSentryClientOptions', () => {
// Representative subset of Sentry's default integrations. `integrations`
// is the function form: Sentry.init calls it with the defaults and installs
// whatever it returns, so dropping these here would disable session
// envelopes (BrowserSession) and window.onerror capture (GlobalHandlers).
const fakeDefaultIntegrations = [{ name: 'BrowserSession' }, { name: 'GlobalHandlers' }]
const getIntegrationNames = (options: ReturnType<typeof buildSentryClientOptions>) => {
const integrations = options.integrations
if (typeof integrations !== 'function') {
throw new Error('expected the function form of integrations')
}
return integrations(fakeDefaultIntegrations).map((integration) => integration.name)
}
it('preserves the default integrations passed in by Sentry.init', () => {
for (const includeThirdPartyErrorFilter of [true, false]) {
const names = getIntegrationNames(buildSentryClientOptions({ includeThirdPartyErrorFilter }))
// browserSessionIntegration is what sends the session envelope on every
// page load; globalHandlers is window.onerror / unhandledrejection.
expect(names).toContain('BrowserSession')
expect(names).toContain('GlobalHandlers')
}
})
it('sets the release only when one is provided', () => {
const withRelease = buildSentryClientOptions({
includeThirdPartyErrorFilter: false,
release: 'abc123',
})
expect(withRelease.release).toBe('abc123')
// The key is absent when no release is passed.
const withoutRelease = buildSentryClientOptions({ includeThirdPartyErrorFilter: true })
expect('release' in withoutRelease).toBe(false)
})
it('includes the third-party error filter only when the build annotates frames', () => {
// Builds whose bundler annotates frames with the applicationKey.
expect(
getIntegrationNames(buildSentryClientOptions({ includeThirdPartyErrorFilter: true }))
).toContain('ThirdPartyErrorsFilter')
// TanStack/Vite build: no bundler metadata — including the integration
// would tag every event third_party_code=true and beforeSend would drop
// them all.
expect(
getIntegrationNames(buildSentryClientOptions({ includeThirdPartyErrorFilter: false }))
).not.toContain('ThirdPartyErrorsFilter')
})
it('appends build-specific extra integrations', () => {
const options = buildSentryClientOptions({
includeThirdPartyErrorFilter: false,
extraIntegrations: [{ name: 'FakeRouterTracing' }],
})
expect(getIntegrationNames(options)).toContain('FakeRouterTracing')
})
it('no longer ignores insert/remove node errors, so beforeSend can sample them', () => {
const { ignoreErrors = [] } = buildSentryClientOptions({ includeThirdPartyErrorFilter: true })
expect(ignoreErrors).not.toContain("NotFoundError: Failed to execute 'removeChild' on 'Node'")
expect(ignoreErrors).not.toContain('NotFoundError: The object can not be found here.')
expect(ignoreErrors).toContain("Cannot read properties of null (reading 'parentNode')")
})
it('builds the same shared options for both builds (parity)', () => {
const nextOptions = buildSentryClientOptions({ includeThirdPartyErrorFilter: true })
const tanstackOptions = buildSentryClientOptions({ includeThirdPartyErrorFilter: false })
// Everything except the integrations array must be identical between the
// two runtimes.
const { integrations: _next, ...nextRest } = nextOptions
const { integrations: _tanstack, ...tanstackRest } = tanstackOptions
expect(Object.keys(nextRest)).toEqual(Object.keys(tanstackRest))
expect(nextRest.tracesSampleRate).toBe(tanstackRest.tracesSampleRate)
expect(nextRest.allowUrls).toEqual(tanstackRest.allowUrls)
expect(nextRest.ignoreErrors).toEqual(tanstackRest.ignoreErrors)
})
})
describe('which errors Studio sends to Sentry', () => {
let beforeSend: NonNullable<ReturnType<typeof buildSentryClientOptions>['beforeSend']>
let restoreConsent: () => void
beforeAll(async () => {
vi.spyOn(Math, 'random').mockReturnValue(0)
vi.stubEnv('NEXT_PUBLIC_IS_PLATFORM', 'true')
vi.resetModules()
const { consentState } = await import('common')
const previousConsent = consentState.hasConsented
consentState.hasConsented = true
restoreConsent = () => {
consentState.hasConsented = previousConsent
}
const { buildSentryClientOptions } = await import('./sentry-client-options')
const options = buildSentryClientOptions({ includeThirdPartyErrorFilter: true })
if (!options.beforeSend) throw new Error('Missing Sentry beforeSend')
beforeSend = options.beforeSend
})
beforeEach(() => {
vi.clearAllMocks()
})
afterAll(() => {
vi.restoreAllMocks()
restoreConsent?.()
vi.unstubAllEnvs()
vi.resetModules()
})
it('drops errors from outside the app', async () => {
expect(await beforeSend({ type: undefined, tags: { third_party_code: true } }, {})).toBeNull()
})
it.each([true, 'true'])(
'sends page crashes even when the code location is missing: %s',
async (tag) => {
const event: Parameters<typeof beforeSend>[0] = {
type: undefined,
tags: { third_party_code: true, globalErrorBoundary: tag },
exception: { values: [{ value: 'Page crashed' }] },
}
expect(await beforeSend(event, {})).toBe(event)
}
)
it('samples errors that did not crash the page once', async () => {
const event: Parameters<typeof beforeSend>[0] = {
type: undefined,
exception: {
values: [{ value: 'Application error', stacktrace: { frames: [{ filename: 'app.js' }] } }],
},
}
expect(await beforeSend(event, {})).toBe(event)
expect(Math.random).toHaveBeenCalledOnce()
expect(event.tags?.codeSampleRate).toBe('0.01')
})
it('still applies Studio filters to page crashes', async () => {
const event: Parameters<typeof beforeSend>[0] = {
type: undefined,
tags: { globalErrorBoundary: true },
exception: {
values: [
{
value: 'captcha.render is not a function',
stacktrace: { frames: [{ filename: 'api.js' }] },
},
],
},
}
expect(await beforeSend(event, {})).toBeNull()
expect(Math.random).not.toHaveBeenCalled()
})
it('drops user SQL errors even when something else captured them', async () => {
const { UserSqlError } = await import('@/lib/errors/studio-errors')
const event: Parameters<typeof beforeSend>[0] = {
type: undefined,
exception: {
values: [
{ value: 'Failed to run sql query', stacktrace: { frames: [{ filename: 'app.js' }] } },
],
},
}
const hint = { originalException: new UserSqlError({ message: 'Failed to run sql query' }) }
expect(await beforeSend(event, hint)).toBeNull()
})
it('drops errors with no code location when they did not crash the page', async () => {
expect(
await beforeSend({ type: undefined, exception: { values: [{ value: 'No stack' }] } }, {})
).toBeNull()
})
describe('browser-translation DOM errors', () => {
const domErrorEvent = (): Parameters<typeof beforeSend>[0] => ({
type: undefined,
exception: {
values: [
{
type: 'NotFoundError',
value:
"Failed to execute 'removeChild' on 'Node': The node is not a child of this node.",
stacktrace: { frames: [{ filename: 'app.js' }] },
},
],
},
})
it('sends the sampled share, tagged, without the extra 1% sampling', async () => {
vi.mocked(Math.random).mockReturnValueOnce(0.04)
const event = domErrorEvent()
expect(await beforeSend(event, {})).toBe(event)
expect(Math.random).toHaveBeenCalledOnce()
expect(event.tags).toMatchObject({
browser_translation: true,
sample_rate: 0.05,
codeSampleRate: '1',
})
})
it('samples them even when the event has no stack frames', async () => {
vi.mocked(Math.random).mockReturnValueOnce(0.04)
const event = domErrorEvent()
event.exception!.values![0].stacktrace = undefined
expect(await beforeSend(event, {})).toBe(event)
})
it('still drops other errors that have no stack frames', async () => {
const event: Parameters<typeof beforeSend>[0] = {
type: undefined,
exception: { values: [{ type: 'Error', value: 'Application error' }] },
}
expect(await beforeSend(event, {})).toBeNull()
})
it('drops the rest of them', async () => {
vi.mocked(Math.random).mockReturnValueOnce(0.5)
expect(await beforeSend(domErrorEvent(), {})).toBeNull()
})
})
})