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: 'https://supabase.com/dashboard/assets/main-abc123.js', } as StackFrame, { filename: 'https://supabase.com/dashboard/assets/index-def456.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: 'https://supabase.com/dashboard/assets/index-def456.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) => { 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', () => { const names = getIntegrationNames(buildSentryClientOptions()) // 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({ release: 'abc123' }) expect(withRelease.release).toBe('abc123') // The key is absent when no release is passed. const withoutRelease = buildSentryClientOptions() expect('release' in withoutRelease).toBe(false) }) it('appends build-specific extra integrations', () => { const options = buildSentryClientOptions({ extraIntegrations: [{ name: 'FakeRouterTracing' }], }) expect(getIntegrationNames(options)).toContain('FakeRouterTracing') }) it('no longer ignores insert/remove node errors, so beforeSend can sample them', () => { const { ignoreErrors = [] } = buildSentryClientOptions() 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')") }) }) describe('which errors Studio sends to Sentry', () => { let beforeSend: NonNullable['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() 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[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[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[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[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[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[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() }) }) })