Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import * as Sentry from '@sentry/browser';

window.Sentry = {
...Sentry,
// Ensure this is _not_ set
httpClientIntegration: undefined,
};

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
integrations: [],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
window._testLazyLoadIntegration = async function run() {
const integration = await window.Sentry.lazyLoadIntegration('httpClientIntegration');

window.Sentry.getClient()?.addIntegration(integration());

window._integrationLoaded = true;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'; trusted-types sentry-sdk" />
</head>
<body></body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { expect } from '@playwright/test';
import { SDK_VERSION } from '@sentry/browser';
import { sentryTest } from '../../../../utils/fixtures';

sentryTest('lazy loads an integration on pages that enforce Trusted Types', async ({ getLocalTestUrl, page }) => {
const url = await getLocalTestUrl({ testDir: __dirname });

await page.route(`https://browser.sentry-cdn.com/${SDK_VERSION}/httpclient.min.js`, route => {
return route.fulfill({
status: 200,
contentType: 'application/javascript;',
body: "window.Sentry.httpClientIntegration = () => ({ name: 'HttpClient' })",
});
});

await page.addInitScript(() => {
(window as any)._violations = [];
document.addEventListener('securitypolicyviolation', event => {
(window as any)._violations.push(`${event.violatedDirective}: ${event.sample}`);
});
});

await page.goto(url);

await page.evaluate(() => (window as any)._testLazyLoadIntegration());

expect(await page.evaluate(() => (window as any)._integrationLoaded)).toBe(true);
expect(await page.evaluate(() => (window as any)._violations)).toEqual([]);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
try {
Sentry.showReportDialog({
eventId: 'test_id',
onError: error => {
window._reportDialogError = error.message;
},
});
} catch (error) {
window._thrownError = error.message;
}
window._subjectDone = true;
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta
http-equiv="Content-Security-Policy"
content="require-trusted-types-for 'script'; trusted-types other-policy"
/>
</head>
<body></body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { expect } from '@playwright/test';
import { sentryTest } from '../../../../utils/fixtures';

sentryTest(
'calls `onError` instead of throwing when the Trusted Types policy is not allowed',
async ({ browserName, getLocalTestUrl, page }) => {
sentryTest.skip(browserName !== 'chromium', 'Not all tested browser versions enforce Trusted Types');

const url = await getLocalTestUrl({ testDir: __dirname });

await page.goto(url);
await page.waitForFunction(() => (window as any)._subjectDone);

expect(await page.evaluate(() => (window as any)._thrownError)).toBeUndefined();
expect(await page.evaluate(() => (window as any)._reportDialogError)).toBe(
'Failed to load the report dialog script',
);
},
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
window._reportDialogLoaded = false;
Sentry.showReportDialog({
eventId: 'test_id',
onLoad: () => {
window._reportDialogLoaded = true;
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'; trusted-types sentry-sdk" />
</head>
<body></body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { expect } from '@playwright/test';
import { sentryTest } from '../../../../utils/fixtures';

sentryTest('loads the dialog script on pages that enforce Trusted Types', async ({ getLocalTestUrl, page }) => {
const url = await getLocalTestUrl({ testDir: __dirname });

// Registered after `getLocalTestUrl` so it takes precedence over the fixture's ingest route
await page.route(/\/api\/embed\/error-page\//, route =>
route.fulfill({ contentType: 'text/javascript', body: '', headers: { 'Access-Control-Allow-Origin': '*' } }),
);

await page.addInitScript(() => {
(window as any)._violations = [];
document.addEventListener('securitypolicyviolation', event => {
(window as any)._violations.push(`${event.violatedDirective}: ${event.sample}`);
});
});

await page.goto(url);

await page.waitForFunction(() => (window as any)._reportDialogLoaded);
expect(await page.evaluate(() => (window as any)._violations)).toEqual([]);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;
window.Replay = Sentry.replayIntegration({
flushMinDelay: 200,
flushMaxDelay: 200,
minReplayDuration: 0,
useCompression: true,
});

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
sampleRate: 0,
replaysSessionSampleRate: 1.0,
replaysOnErrorSampleRate: 0.0,

integrations: [window.Replay],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'; trusted-types sentry-sdk" />
</head>
<body></body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { expect } from '@playwright/test';
import { sentryTest } from '../../../utils/fixtures';
import { replayEnvelopeIsCompressed, shouldSkipReplayTest, waitForReplayRequest } from '../../../utils/replayHelpers';

sentryTest(
'compresses the recording on pages that enforce Trusted Types',
async ({ getLocalTestUrl, page, forceFlushReplay }) => {
sentryTest.skip(shouldSkipReplayTest());

await page.addInitScript(() => {
(window as any)._violations = [];
document.addEventListener('securitypolicyviolation', event => {
(window as any)._violations.push(`${event.violatedDirective}: ${event.sample}`);
});
});

const reqPromise0 = waitForReplayRequest(page, 0);

await page.goto(await getLocalTestUrl({ testDir: __dirname }));
await forceFlushReplay();

expect(replayEnvelopeIsCompressed(await reqPromise0)).toBe(true);
expect(await page.evaluate(() => (window as any)._violations)).toEqual([]);
},
);
2 changes: 2 additions & 0 deletions packages/browser-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ export { isBotUserAgent } from './isBotUserAgent';

export { getLocationHref } from './getLocationHref';

export { getCdnBaseUrl, getTrustedScriptURL } from './trustedTypes';

export {
createCachedRouteProvider,
createUrlRouteProvider,
Expand Down
69 changes: 69 additions & 0 deletions packages/browser-utils/src/trustedTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type { ScriptURLPolicy } from '@sentry/core';
import { debug, getClient, getGlobalSingleton, getReportDialogEndpoint, SDK_VERSION } from '@sentry/core';
import { DEBUG_BUILD } from './debug-build';
import { WINDOW } from './types';

// Part of the public contract: pages allow this name in their `trusted-types` CSP directive.
const POLICY_NAME = 'sentry-sdk';

interface TrustedTypesWindow {
trustedTypes?: {
createPolicy(name: string, rules: { createScriptURL(input: string): string }): ScriptURLPolicy;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m: above in ScriptURLPolicy, createScriptURL returns unknown. Here it returns string. Is the divergence intentional?

@msonnb msonnb Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

our policy returns a string, which the browser then wraps in aTrustedScriptURL, the unknown was sort of hiding that. Added a named type to make it more clear.

};
}

/** The base URL that `lazyLoadIntegration` loads bundles from. */
export function getCdnBaseUrl(): string {
const options = getClient()?.getOptions() as { cdnBaseUrl?: string } | undefined;
return options?.cdnBaseUrl || 'https://browser.sentry-cdn.com';
}

function isReportDialogURL(input: string): boolean {
const dsn = getClient()?.getDsn();
// Matching up to and including the `?` pins the origin and the full path, so only the query can vary.
return !!dsn && input.startsWith(`${getReportDialogEndpoint(dsn, {}).split('?')[0]}?`);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Policy looks up the current client

Low Severity

This is more an “is this necessary” check than a hard violation: getCdnBaseUrl and isReportDialogURL call getClient() for cdnBaseUrl and the DSN. The Trusted Types policy is a process-wide singleton, so a multi-client page can validate a URL against a different client than the one that built it and reject a legitimate script.

Additional Locations (1)
Fix in Cursor Fix in Web

Triggered by project rule: PR Review Guidelines for Cursor Bot

Reviewed by Cursor Bugbot for commit 7e5046b. Configure here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

both callers build the URL and pass it here synchronously, so i don't think it can happen that it's a different client here

}

function isCdnBundleURL(input: string): boolean {
const prefix = new URL(`/${SDK_VERSION}/`, getCdnBaseUrl()).toString();
return input.startsWith(prefix) && /^[a-z-]+\.min\.js$/.test(input.slice(prefix.length));
}

// The policy can't know which blob URLs the SDK created: they may come from another copy of the SDK that shares it.
// Creating one for this origin already requires running script in it.
function isBlobURL(input: string): boolean {
return input.startsWith(`blob:${WINDOW.origin}/`);
}

function createScriptURL(input: string): string {
if (!isBlobURL(input) && !isReportDialogURL(input) && !isCdnBundleURL(input)) {
throw new TypeError(`Refusing to load ${input} as a Sentry SDK script`);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m/q: Would our SDK throw an error to the user application if we throw here? If so, is this expected behavior for policies?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, throwing is how policies should reject invalid values (example). Since we only call this with URLs we build ourselves, it should never happen in practice though. If it does, it's either 1) a bug on our side, where we changed a URL so it no longer matches, or 2) something untrusted got into the URL or is calling our policy directly (e.g. XSS), in which case we want to reject it. I added a test that checks all lazy-loaded bundle URLs against the policy to catch 1) better.

showReportDialog would indeed have thrown into the user app, also when the CSP doesn't allow our policy and the browser itself throws. I updated it to call onError instead. Replay and lazyLoadIntegration already catch this correctly.

}
return input;
}

function createPolicy(): ScriptURLPolicy {
try {
const policy = (WINDOW as TrustedTypesWindow).trustedTypes?.createPolicy(POLICY_NAME, { createScriptURL });
if (policy) {
return policy;
}
} catch (error) {
DEBUG_BUILD &&
debug.warn(
`Could not create the "${POLICY_NAME}" Trusted Types policy. Add it to your \`trusted-types\` CSP directive (with \`'allow-duplicates'\` if the policy is created more than once, e.g. by different SDK versions on the same page).`,
error,
);
}
return { createScriptURL: input => input };
}

/**
* Returns `url` as a value for script URL sinks (`script.src`, `new Worker()`) on pages that enforce Trusted Types.
*
* This is a `TrustedScriptURL` (typed as `string`, like the sinks in the DOM lib) if the policy could be created, and
* the unchanged string otherwise. With a policy, it throws for URLs the SDK is not expected to load.
*/
export function getTrustedScriptURL(url: string): string {
return getGlobalSingleton('trustedTypesPolicy', createPolicy).createScriptURL(url) as string;
}
Loading
Loading