Skip to content
Merged
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
1 change: 1 addition & 0 deletions .cursor/BUGBOT.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Keep reviews high-signal. Prefer actionable, high-confidence findings over specu
- Exposed **real** secrets, API keys, tokens, or credentials in production code, comments, logs, or committed configs. Do **not** flag test fixtures, unit/integration/E2E helpers, or docs/examples that use obviously fake / placeholder DSNs and credentials (bogus DSNs in tests are expected).
- Unsafe use of `eval()`, `Function()`, or `innerHTML`
- Unsafe regular expressions that could cause ReDoS attacks
- `JSON.stringify` output that goes into generated code (bundler plugins, loaders, virtual modules, `define` values). Use `stringifyForCodeInjection` from `@sentry/core` instead. It escapes `<`, `>`, U+2028 and U+2029, so the code stays safe when inlined in a `<script>` element. Do not flag log messages, boolean `define` values, or other output that never reaches generated code.
- Sensitive data collection must go through the SDK's `dataCollection` options (and helpers like `filterCollectedUrl` / `filterCollectedUrlQuery`) where applicable. Flag new instrumentation that attaches request/response bodies, cookies, headers, URL query params, user info, DB query data, GraphQL variables, GenAI I/O, or similar without honoring the relevant `dataCollection.*` knobs — or that hard-codes collection on when those options would disable or filter it. Prefer linking reviewers to the existing URL-attribute filtering rules below rather than inventing parallel guidance.
- Diagnostics, sampling overrides, verbose logging, or feature flags accidentally enabled in production defaults

Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ Uses **Git Flow** (see `docs/gitflow.md`).

- Follow existing conventions — check neighboring files
- Reach for existing utils before writing a new one. Most shared helpers live in `@sentry/core` (`packages/core/src/utils/`), with browser helpers in `packages/browser-utils/`. Search first (LSP `workspaceSymbol` or grep) for common needs (type guards in `is.ts`, object/array helpers, `normalize`, `dsn`, `merge`, string/url helpers). Reuse or extend the existing util rather than adding a near-duplicate; only introduce a new util when nothing fits.
- When `JSON.stringify` output goes into generated code (bundler plugins, loaders, virtual modules, `define`), use `stringifyForCodeInjection` from `@sentry/core` instead. It escapes `<`, `>`, U+2028 and U+2029, so the code stays safe when inlined in a `<script>` element.
Comment thread
isaacs marked this conversation as resolved.
Resolved
- Only use libraries already in the codebase
- Never expose secrets or keys
- When modifying files, cover all occurrences (including `src/` and `test/`)
Expand Down
5 changes: 4 additions & 1 deletion packages/astro/src/integration/snippets.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as path from 'path';
import type { SentryOptions } from './types';
import { stringifyForCodeInjection } from '@sentry/core';

/**
* Creates a snippet that imports a Sentry.init file.
Expand Down Expand Up @@ -39,7 +40,9 @@ const buildCommonInitOptions = (options: SentryOptions): string => `dsn: import.
debug: ${options.debug ? true : false},
environment: import.meta.env.PUBLIC_VERCEL_ENV,
release: ${
options.release?.name ? JSON.stringify(options.release.name) : 'import.meta.env.PUBLIC_VERCEL_GIT_COMMIT_SHA'
options.release?.name
? stringifyForCodeInjection(options.release.name)
: 'import.meta.env.PUBLIC_VERCEL_GIT_COMMIT_SHA'
},
tracesSampleRate: 1.0,`;

Expand Down
5 changes: 3 additions & 2 deletions packages/astro/src/integration/tunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { BrowserTunnelOptions } from '@sentry/core';
import type { AstroConfig } from 'astro';
import { TUNNEL_OPTIONS_GLOBAL } from '../tunnel';
import { WORKER_ENTRY_IDS, type VitePlugin } from './cloudflare';
import { stringifyForCodeInjection } from '@sentry/core';

const TUNNEL_OPTIONS_MODULE = 'virtual:@sentry/astro/tunnel-options';
const RESOLVED_TUNNEL_OPTIONS_MODULE = `\0${TUNNEL_OPTIONS_MODULE}`;
Expand Down Expand Up @@ -36,8 +37,8 @@ export function makeTunnelOptionsVitePlugin(tunnelOptions: BrowserTunnelOptions)
}

return options?.ssr
? `import { _INTERNAL_setTunnelDefaults } from '@sentry/astro/middleware';\n_INTERNAL_setTunnelDefaults(${JSON.stringify({ basePath: tunnelOptions.basePath })});`
: `globalThis[${JSON.stringify(TUNNEL_OPTIONS_GLOBAL)}] = ${JSON.stringify(tunnelOptions)};`;
? `import { _INTERNAL_setTunnelDefaults } from '@sentry/astro/middleware';\n_INTERNAL_setTunnelDefaults(${stringifyForCodeInjection({ basePath: tunnelOptions.basePath })});`
: `globalThis[${stringifyForCodeInjection(TUNNEL_OPTIONS_GLOBAL)}] = ${stringifyForCodeInjection(tunnelOptions)};`;
},
transform: (code, id) =>
WORKER_ENTRY_IDS.some(entryId => id.includes(entryId)) ? TUNNEL_OPTIONS_IMPORT + code : null,
Expand Down
6 changes: 1 addition & 5 deletions packages/bundler-plugins/src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
_INTERNAL_getReleaseFromCommitEnv as getReleaseFromCommitEnv,
_INTERNAL_readCommitEnvVar as readCoreCommitEnvVar,
} from '@sentry/core/server';
import { stringifyForCodeInjection } from '@sentry/core';

/**
* Checks whether the given input is already an array, and if it isn't, wraps it in one.
Expand Down Expand Up @@ -278,11 +279,6 @@ export function readCommitEnvVar(name: string): string | undefined {
return readCoreCommitEnvVar(name, warnAboutPlaceholderCommitEnvVar);
}

function stringifyForCodeInjection(value: unknown): string | undefined {
// Bundles may be inlined in HTML, where JSON quoting does not escape script tags or HTML comments.
return JSON.stringify(value)?.replace(/</g, '\\u003c');
}

/**
* Generates code for the global injector which is responsible for setting the global
* `SENTRY_RELEASE` & `SENTRY_BUILD_INFO` variables.
Expand Down
6 changes: 4 additions & 2 deletions packages/bundler-plugins/src/esbuild/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* oxlint-disable max-lines */
import type { InternalOptions, SourceMapDecision, SourceMapKind } from '../core';
import {
createSentryBuildPluginManager,
Expand All @@ -12,6 +13,7 @@ import {
import * as path from 'node:path';
import { createRequire } from 'node:module';
import { randomUUID } from 'node:crypto';
import { stringifyForCodeInjection } from '@sentry/core';

interface EsbuildOnResolveArgs {
path: string;
Expand Down Expand Up @@ -281,9 +283,9 @@ export function sentryEsbuildPlugin(userOptions: InternalOptions = {}): any {
pluginName,
contents: `
import "_sentry-debug-id-injection-stub";
import * as OriginalModule from ${JSON.stringify(originalPath)};
import * as OriginalModule from ${stringifyForCodeInjection(originalPath)};
export default OriginalModule.default;
export * from ${JSON.stringify(originalPath)};`,
export * from ${stringifyForCodeInjection(originalPath)};`,
resolveDir: originalResolveDir,
};
});
Expand Down
3 changes: 2 additions & 1 deletion packages/cloudflare/src/vite/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import MagicString from 'magic-string';
import { DEFAULT_EXPORT, type ExportName, type SameWorkerBinding } from './wranglerConfig';
import { detectWorkerEntrypointClasses } from './workerEntrypoint';
import { stringifyForCodeInjection } from '@sentry/core';

const MERGED_OPTIONS_IDENTIFIER = '__SENTRY_OPTIONS__';

Expand Down Expand Up @@ -284,7 +285,7 @@ function buildMergedOptionsDeclaration(
return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};\n`;
}

const names = bindingNames.map(name => JSON.stringify(name)).join(', ');

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Missed stringify in generated code

Low Severity

This is flagged because the review guideline requires stringifyForCodeInjection whenever JSON.stringify output goes into generated code. These files already switched other injections over, but ctx.workerInfo, instrumentStoragePath, and driverName are still stringified with JSON.stringify and inlined into emitted modules.

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 cb6d5bd. Configure here.

const names = bindingNames.map(name => stringifyForCodeInjection(name)).join(', ');
return (
`const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { ` +
`const opts = (${optionsFn})(env); ` +
Expand Down
33 changes: 33 additions & 0 deletions packages/core/src/build-time-plugins/stringifyForCodeInjection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const UNSAFE_CHARS = /[<>\u2028\u2029]/g;

const ESCAPED_CHARS: Record<string, string> = {
'<': '\\u003c',
'>': '\\u003e',
'\u2028': '\\u2028',
'\u2029': '\\u2029',
};

/**
* A drop-in replacement for `JSON.stringify`, for values that go into generated JavaScript code.
*
* `JSON.stringify` output is a valid JavaScript expression, but it does not escape `<` and `>`, so
* a value with `</script>` or `<!--` breaks out of a `<script>` element when the code is inlined in
* HTML. It also does not escape U+2028 and U+2029, which end a line in JavaScript before ES2019.
* These characters only occur inside JSON strings, where their `\u` escapes have the same value.
*
* Use this every time `JSON.stringify` output is put into code, for example in a bundler plugin.
*
* @internal Only meant for Sentry-internal SDK usage.
* @hidden
*/
export function stringifyForCodeInjection(
value: unknown,
replacer?: ((this: unknown, key: string, value: unknown) => unknown) | (number | string)[] | null,
space?: string | number,
): string {
// Each branch matches one `JSON.stringify` overload.
const json =
typeof replacer === 'function' ? JSON.stringify(value, replacer, space) : JSON.stringify(value, replacer, space);
// `JSON.stringify` returns `undefined` for `undefined` and functions, although its type says `string`.
return json?.replace(UNSAFE_CHARS, char => ESCAPED_CHARS[char] as string);
}
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -566,4 +566,5 @@ export {
safeDateNow as _INTERNAL_safeDateNow,
} from './utils/randomSafeContext';
export { warnOnRemovedBuildOptions } from './build-time-plugins/warnOnRemovedBuildOptions';
export { stringifyForCodeInjection } from './build-time-plugins/stringifyForCodeInjection';
export { startSpan, startInactiveSpan, startSpanManual } from './tracing/trace';
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* @vitest-environment node
*/
import { JSDOM } from 'jsdom';
import { runInNewContext } from 'node:vm';
import { describe, expect, it } from 'vitest';
import { stringifyForCodeInjection } from '../../../src/build-time-plugins/stringifyForCodeInjection';

describe('stringifyForCodeInjection', () => {
it.each([
'</script><script>globalThis.injected = true</script>',
'</ScRiPt \n><script>globalThis.injected = true</script>',
'<!--<script>',
'--> after a comment',
'quotes "\' and backslashes \\u003c with whitespace \n\r\t\u2028\u2029 and <>&',
])('keeps %j inside one script element, with the same value', value => {
const input = { [value]: [value, { nested: value }] };
const code = `globalThis.result = ${stringifyForCodeInjection(input)};`;

const dom = new JSDOM(`<script>${code}</script>`);
const scripts = dom.window.document.querySelectorAll('script');
dom.window.close();

expect(scripts).toHaveLength(1);
expect(scripts[0]?.textContent).toBe(code);

const context: { result?: unknown } = {};
runInNewContext(code, context);
expect(context.result).toEqual(input);
});

it('escapes the unsafe characters', () => {
expect(stringifyForCodeInjection('<>\u2028\u2029')).toBe('"\\u003c\\u003e\\u2028\\u2029"');
});

it('gives the same result as JSON.stringify for other values', () => {
const value = { a: [1, 'two', null, true], b: { c: 'd/e\\f' } };
expect(stringifyForCodeInjection(value)).toBe(JSON.stringify(value));
expect(stringifyForCodeInjection(value, null, 2)).toBe(JSON.stringify(value, null, 2));
expect(stringifyForCodeInjection(value, ['a'])).toBe(JSON.stringify(value, ['a']));
expect(stringifyForCodeInjection(value, (_key, v) => (v === 'two' ? 2 : v))).toBe(
JSON.stringify(value, (_key, v) => (v === 'two' ? 2 : v)),
);
});

it('returns undefined where JSON.stringify does', () => {
expect(stringifyForCodeInjection(undefined)).toBeUndefined();
expect(stringifyForCodeInjection(() => undefined)).toBeUndefined();
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getCodeInjectionPosition } from '@sentry/bundler-plugins/loader-utils';
import type { LoaderThis } from './types';
import { stringifyForCodeInjection } from '@sentry/core';

export type ModuleMetadataInjectionLoaderOptions = {
applicationKey: string;
Expand Down Expand Up @@ -31,7 +32,7 @@ export default function moduleMetadataInjectionLoader(
// The IIFE resolves the global object and stores metadata keyed by (new Error).stack
// so the SDK can map chunk filenames to metadata at runtime.
// Not putting any newlines in the generated code will decrease the likelihood of sourcemaps breaking.
const metadata = JSON.stringify({ [`_sentryBundlerPluginAppKey:${applicationKey}`]: true });
const metadata = stringifyForCodeInjection({ [`_sentryBundlerPluginAppKey:${applicationKey}`]: true });
const injectedCode =
';!function(){try{' +
'var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};' +
Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/src/config/loaders/valueInjectionLoader.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getCodeInjectionPosition } from '@sentry/bundler-plugins/loader-utils';
import type { LoaderThis } from './types';
import { stringifyForCodeInjection } from '@sentry/core';

export type ValueInjectionLoaderOptions = {
values: Record<string, unknown>;
Expand All @@ -24,7 +25,7 @@ export default function valueInjectionLoader(this: LoaderThis<ValueInjectionLoad
// eslint-disable-next-line prefer-template
';' +
Object.entries(values)
.map(([key, value]) => `globalThis["${key}"] = ${JSON.stringify(value)};`)
.map(([key, value]) => `globalThis["${key}"] = ${stringifyForCodeInjection(value)};`)
.join('');

const injectionIndex = getCodeInjectionPosition(userCode);
Expand Down
7 changes: 5 additions & 2 deletions packages/nextjs/src/config/loaders/wrappingLoader.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import commonjs from '@rollup/plugin-commonjs';
import { stringMatchesSomePattern } from '@sentry/core';
import { stringifyForCodeInjection, stringMatchesSomePattern } from '@sentry/core';
import * as fs from 'fs';
import * as path from 'path';
import type { RollupBuild, RollupError } from 'rollup';
Expand Down Expand Up @@ -119,7 +119,10 @@ export default function wrappingLoader(
throw new Error(`Invariant: Could not get template code of unknown kind "${wrappingTargetKind}"`);
}

templateCode = templateCode.replace(/__VERCEL_CRONS_CONFIGURATION__/g, JSON.stringify(vercelCronsConfig));
templateCode = templateCode.replace(
/__VERCEL_CRONS_CONFIGURATION__/g,
stringifyForCodeInjection(vercelCronsConfig),
);

// Inject the route and the path to the file we're wrapping into the template
templateCode = templateCode.replace(/__ROUTE__/g, parameterizedPagesRoute.replace(/\\/g, '\\\\'));
Expand Down
7 changes: 5 additions & 2 deletions packages/nuxt/src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { setupOrchestrion } from './vite/orchestrion';
import { setupSourceMaps } from './vite/sourceMaps';
import { findDefaultSdkInitFile, resolveServerApi } from './vite/utils';
import { setupViteServer } from './vite/viteServer';
import { stringifyForCodeInjection } from '@sentry/core';

export type ModuleOptions = SentryNuxtModuleOptions;
type NuxtPageSubset = { file?: string; path: string };
Expand Down Expand Up @@ -128,13 +129,15 @@ export default defineNuxtModule<ModuleOptions>({
name: 'sentry-nuxt-pages-data-virtual',
resolveId: (id: string) => (id === pagesDataVirtualModuleId ? `\0${pagesDataVirtualModuleId}` : null),
load: (id: string) =>
id === `\0${pagesDataVirtualModuleId}` ? `export default ${JSON.stringify(pagesData, null, 2)};` : undefined,
id === `\0${pagesDataVirtualModuleId}`
? `export default ${stringifyForCodeInjection(pagesData, null, 2)};`
: undefined,
});
} else {
// Nuxt v3: register as a build template (accessible via #build/)
addTemplate({
filename: 'sentry--nuxt-pages-data.mjs',
getContents: () => `export default ${JSON.stringify(pagesData, null, 2)};`,
getContents: () => `export default ${stringifyForCodeInjection(pagesData, null, 2)};`,
});
}

Expand Down
8 changes: 4 additions & 4 deletions packages/nuxt/src/vite/addServerConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { basename } from 'node:path';
import { pathToFileURL } from 'node:url';
import { addNitroPlugin, addTemplate, createResolver } from '@nuxt/kit';
import type { Nuxt } from '@nuxt/schema';
import { consoleSandbox, debug } from '@sentry/core';
import { consoleSandbox, debug, stringifyForCodeInjection } from '@sentry/core';
import * as fs from 'fs';
import type { Nitro } from 'nitropack';
import type { InputPluginOption } from 'rollup';
Expand Down Expand Up @@ -116,7 +116,7 @@ export function addServerConfigPlugin(nuxt: Nuxt, serverConfigFile: string, isLe
filename: 'sentry-server-config-plugin.mjs',
write: true,
getContents: () =>
`import ${JSON.stringify(runtimeFlagsTemplate.dst)};\nimport ${JSON.stringify(configPath)};\nexport default () => {};\n`,
`import ${stringifyForCodeInjection(runtimeFlagsTemplate.dst)};\nimport ${stringifyForCodeInjection(configPath)};\nexport default () => {};\n`,
});

addNitroPlugin(configPluginTemplate.dst);
Expand Down Expand Up @@ -368,10 +368,10 @@ export function wrapEntryWithDynamicImport({

return (
// Regular `import` of the Sentry config
`import ${JSON.stringify(configUrl)};\n` +
`import ${stringifyForCodeInjection(configUrl)};\n` +
// Dynamic `import()` for the previous, actual entry point.
// `import()` can be used for any code that should be run after the hooks are registered (https://nodejs.org/api/module.html#enabling)
`import(${JSON.stringify(entryIdUrl)});\n` +
`import(${stringifyForCodeInjection(entryIdUrl)});\n` +
`${reExportedFunctions}\n`
);
}
Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt/src/vite/databaseConfig.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { addNitroPlugin, createResolver } from '@nuxt/kit';
import { consoleSandbox } from '@sentry/core';
import { consoleSandbox, stringifyForCodeInjection } from '@sentry/core';
import type { NitroConfig } from 'nitropack/types';
import type { SentryNuxtModuleOptions } from '../common/types';
import { addServerTemplate } from '../vendor/server-template';
Expand Down Expand Up @@ -38,7 +38,7 @@ export function addDatabaseInstrumentation(
addServerTemplate({
filename: '#sentry/database-config.mjs',
getContents: () => {
return `export const databaseConfig = ${JSON.stringify(databaseConfig)};`;
return `export const databaseConfig = ${stringifyForCodeInjection(databaseConfig)};`;
},
});

Expand Down
3 changes: 2 additions & 1 deletion packages/nuxt/src/vite/storageConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { Nuxt } from '@nuxt/schema';
import type { Nitro } from 'nitropack/types';
import type { InputPluginOption } from 'rollup';
import { addServerTemplate } from '../vendor/server-template';
import { stringifyForCodeInjection } from '@sentry/core';

const NITRO_CACHE_VIRTUAL_MODULE_ID = '#nitro/virtual/cache';
const CREATE_CACHE_STORAGE_EXPORT = 'export const createCacheStorage =';
Expand All @@ -18,7 +19,7 @@ export function addStorageInstrumentation(nuxt: Nuxt, isLegacyNitro: boolean): v
addServerTemplate({
filename: '#sentry/storage-config.mjs',
getContents: () => {
return `export const userStorageMounts = ${JSON.stringify(userStorageMounts)};`;
return `export const userStorageMounts = ${stringifyForCodeInjection(userStorageMounts)};`;
},
});

Expand Down
6 changes: 3 additions & 3 deletions packages/nuxt/src/vite/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Nuxt, ResolvedNuxtTemplate } from '@nuxt/schema';
import { consoleSandbox } from '@sentry/core';
import { consoleSandbox, stringifyForCodeInjection } from '@sentry/core';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'node:url';
Expand Down Expand Up @@ -186,7 +186,7 @@ export function constructFunctionReExport(pathWithQuery: string, entryId: string
(functionsCode, currFunctionName) =>
functionsCode.concat(
`async function ${currFunctionName}_sentryWrapped(...args) {\n` +
` const res = await import(${JSON.stringify(entryId)});\n` +
` const res = await import(${stringifyForCodeInjection(entryId)});\n` +
` return res.${currFunctionName}.call(this, ...args);\n` +
'}\n' +
`export { ${currFunctionName}_sentryWrapped as ${currFunctionName} };\n`,
Expand All @@ -196,7 +196,7 @@ export function constructFunctionReExport(pathWithQuery: string, entryId: string
.concat(
reexportFunctions.reduce(
(functionsCode, currFunctionName) =>
functionsCode.concat(`export { ${currFunctionName} } from ${JSON.stringify(entryId)};`),
functionsCode.concat(`export { ${currFunctionName} } from ${stringifyForCodeInjection(entryId)};`),
'',
),
);
Expand Down
Loading
Loading