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
3 changes: 0 additions & 3 deletions .cursor/BUGBOT.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,6 @@ Keep reviews high-signal. Prefer actionable, high-confidence findings over specu
- Generally, errors in instrumented code should be allowed to bubble up so the end user can handle them. If they remain unhandled, they will eventually be captured by Sentry through the SDK's global error handlers — so instrumentation code should typically **not** call `captureException` itself.
- Only consider calling `captureException` if the instrumentation prevents errors from bubbling up (e.g. by swallowing them in a `try/catch` or an error event listener). Doing so is generally discouraged — prefer to let the error propagate instead.
- Flag any instrumentation that swallows errors without calling `captureException`, and any instrumentation that calls `captureException` even though the error would still bubble up to the user (which causes double-reporting).
- Flag direct `console.log` / `console.warn` / `console.error` / `console.info` / `console.debug` calls in SDK source. The accepted patterns are:
- The SDK's `debug` logger (gated with `DEBUG_BUILD && debug.*`) for SDK-internal diagnostics.
- `consoleSandbox(() => { console.warn(...) })` for intentional user-facing warnings (e.g. init-time misconfiguration messages). The `consoleSandbox` wrapper prevents the SDK's own console instrumentation from intercepting the call. Bare `console.*` calls outside very early init paths (e.g. before the logger is available) should be flagged.
- Flag `url.full`, `url.query`, `http.target` or `request.query_string` being set from a URL that isn't filtered. Wrap the value in `filterCollectedUrl()` (or `filterCollectedUrlQuery()` for a bare query string), passing the `client` if one is in scope, so `dataCollection.urlQueryParams` applies. Values that can't contain a query (a bare pathname, a queue URL) are fine. The `sdk/no-unfiltered-url-attributes` lint rule catches direct attribute writes, so look for what it can't: URLs passed through a helper or variable first, deprecated aliases set next to a filtered attribute, and URLs on breadcrumbs or events instead of spans.
- Flag span names built from a raw URL. Names follow `METHOD scheme://host/path` and must never contain a query string, so they need `stripUrlQueryAndFragment()`, not `filterCollectedUrl()`.
- Flag a SQL statement that reaches telemetry unsanitized. `db.query.text`, `db.query.summary`, a DB span name, and a breadcrumb carrying a statement all have to come from `sanitizeSqlQuery()` or `sanitizeSqlQueryWithSummary()` (`@sentry/server-utils`). Inline literals are user data, and OTel allows collecting query text only once they are replaced with `?`. This is deliberately not gated on `dataCollection.databaseQueryData`, which does not cover query text.
Expand Down
15 changes: 15 additions & 0 deletions .oxlintrc.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,21 @@
"no-this-alias": "off"
}
},
{
// SDK source may only call `console.*` inside `consoleSandbox()`, see `no-unsandboxed-console.js`.
"files": ["**/src/**"],
"rules": {
"no-console": "off",
"sdk/no-unsandboxed-console": "error"
}
},
{
// Vite plugins run at build time and log to the terminal, not through an instrumented `console`.
"files": ["**/src/vite/**"],
"rules": {
"sdk/no-unsandboxed-console": "off"
}
},
{
"files": ["**/scenarios/**", "**/rollup-utils/**"],
"rules": {
Expand Down
5 changes: 4 additions & 1 deletion dev-packages/.oxlintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
{
"files": ["**/src/**"],
"rules": {
"typescript/no-non-null-assertion": "off"
"typescript/no-non-null-assertion": "off",
// Test utilities are not SDK code, so `consoleSandbox()` does not apply.
"no-console": "error",
"sdk/no-unsandboxed-console": "off"
}
}
],
Expand Down
1 change: 0 additions & 1 deletion packages/angular/src/errorhandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ class SentryErrorHandler implements AngularErrorHandler, OnDestroy {

// When in development mode, log the error to console for immediate feedback.
if (this._options.logErrors) {
// eslint-disable-next-line no-console
consoleSandbox(() => console.error(extractedError));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,6 @@ export class AwsLambdaExtension {

if (!allowedDsnComponents) {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(
'Sentry Lambda extension: SENTRY_DSN is not set or is invalid. The /envelope tunnel will forward ' +
'any DSN in the envelope header without allowlist validation. Set SENTRY_DSN to the same DSN as ' +
Expand Down
1 change: 0 additions & 1 deletion packages/aws-serverless/src/lambda-extension/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ async function main(): Promise<void> {

main().catch(err => {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.error('Error in Lambda Extension', err);
});
process.exit(1);
Expand Down
1 change: 0 additions & 1 deletion packages/browser/src/tracing/browserTracingIntegration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,6 @@ const DEFAULT_FORWARDED_OPTIONS = {
const browserTracingIntegrationFn = ((options: Partial<BrowserTracingOptions> = {}) => {
if ('enableElementTiming' in options) {
consoleSandbox(() => {
// oxlint-disable-next-line no-console
console.warn(
'[Sentry] `enableElementTiming` is deprecated and no longer has any effect. Use the standalone `elementTimingIntegration` instead.',
);
Expand Down
1 change: 0 additions & 1 deletion packages/browser/src/utils/detectBrowserExtension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export function checkAndWarnIfIsEmbeddedBrowserExtension(): boolean {
if (_isEmbeddedBrowserExtension()) {
if (DEBUG_BUILD) {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.error(
'[Sentry] You cannot use Sentry.init() in a browser extension, see: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/',
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function createComponentNameAnnotateHooks(
if (options.logger) {
options.logger.warn(PARSER_UNAVAILABLE_MESSAGE);
} else {
// eslint-disable-next-line no-console
// oxlint-disable-next-line sdk/no-unsandboxed-console -- build-time plugin output
console.warn(`[@sentry/bundler-plugins] ${PARSER_UNAVAILABLE_MESSAGE}`);
}
}
Expand Down
8 changes: 4 additions & 4 deletions packages/bundler-plugins/src/core/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,25 @@ export function createLogger(options: LoggerOptions): Logger {
return {
info(message: string, ...params: unknown[]) {
if (!options.silent) {
// eslint-disable-next-line no-console
// oxlint-disable-next-line sdk/no-unsandboxed-console -- build-time plugin output
console.info(`${options.prefix} Info: ${message}`, ...params);
}
},
warn(message: string, ...params: unknown[]) {
if (!options.silent) {
// eslint-disable-next-line no-console
// oxlint-disable-next-line sdk/no-unsandboxed-console -- build-time plugin output
console.warn(`${options.prefix} Warning: ${message}`, ...params);
}
},
error(message: string, ...params: unknown[]) {
if (!options.silent) {
// eslint-disable-next-line no-console
// oxlint-disable-next-line sdk/no-unsandboxed-console -- build-time plugin output
console.error(`${options.prefix} Error: ${message}`, ...params);
}
},
debug(message: string, ...params: unknown[]) {
if (!options.silent && options.debug) {
// eslint-disable-next-line no-console
// oxlint-disable-next-line sdk/no-unsandboxed-console -- build-time plugin output
console.debug(`${options.prefix} Debug: ${message}`, ...params);
}
},
Expand Down
2 changes: 1 addition & 1 deletion packages/bundler-plugins/src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ function warnAboutPlaceholderCommitEnvVar(name: string): void {
warnedPlaceholderEnvVars.add(name);
// This runs before the plugin logger exists, so `silent: true` does not suppress it. That is
// deliberate: a warning that is easy to miss is how this misconfiguration went unnoticed.
// eslint-disable-next-line no-console
// oxlint-disable-next-line sdk/no-unsandboxed-console -- build-time plugin output
console.warn(
`[@sentry/bundler-plugins] Ignoring the ${name} environment variable as a release name, because its value is its own name. Set the release explicitly, or fix the variable in your build environment.`,
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ export function warnOnConflictingSourceMapOptions(
sourcemaps: ConflictingSourceMapOptions | undefined,
logWarning: (message: string) => void = message =>
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(`[Sentry] ${message}`);
}),
): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export function warnOnRemovedBuildOptions(
removedKeys: string[],
logWarning: (message: string) => void = message =>
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(message);
}),
): void {
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,6 @@ export abstract class Client<O extends ClientOptions = ClientOptions> {
isStaticBeforeSendSpanCallback(beforeSendSpan) !== (traceLifecycle === 'static')
) {
consoleSandbox(() => {
// oxlint-disable-next-line no-console
console.warn(
`Ignoring \`beforeSendSpan\`: ${
traceLifecycle === 'static' ? 'wrap it with' : 'remove'
Expand Down
2 changes: 0 additions & 2 deletions packages/core/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ export function initAndBind<F extends Client, O extends ClientOptions>(
} else {
// use `console.warn` rather than `debug.warn` since by non-debug bundles have all `debug.x` statements stripped
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');
});
}
Expand All @@ -50,7 +49,6 @@ export function warnIfClientIsActive(): void {
consoleSandbox(() => {
// TODO(#24883): Point apps that share a page with another app to the
// isolated client helper, once that PR settles its name.
// eslint-disable-next-line no-console
console.warn(
'[Sentry] `Sentry.init()` was called more than once. The new client replaces the active client, but the active client is not closed, so state from both can mix. Call `Sentry.init()` only once, or call `await Sentry.close()` before you call it again.',
);
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/utils/commitEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ export type PlaceholderCommitEnvVarHandler = (name: string) => void;

function warnAboutPlaceholderCommitEnvVar(name: string): void {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(
`[Sentry] Ignoring the ${name} environment variable as a release name, because its value is its own name. Set the release explicitly, or fix the variable in your build environment.`,
);
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/utils/dsn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ export function dsnFromString(str: string): DsnComponents | undefined {
if (!match) {
// This should be logged to the console
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.error(`Invalid Sentry Dsn: ${str}`);
});
return undefined;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export function maybeWarnAboutIgnoredTransactionOptions(options: ClientOptions):
}

consoleSandbox(() => {
// oxlint-disable-next-line no-console
console.warn(
"[Sentry] `beforeSendTransaction` and `ignoreTransactions` are ignored with `traceLifecycle: 'stream'` (enabled by default). Use `beforeSendSpan` and `ignoreSpans` instead, or set `traceLifecycle: 'static'`.",
);
Expand Down
1 change: 0 additions & 1 deletion packages/deno/src/integrations/breadcrumbs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ const INTEGRATION_NAME = 'Breadcrumbs' as const;
const _breadcrumbsIntegration = ((options: Partial<BreadcrumbsOptions> = {}) => {
if ('fetch' in options) {
consoleSandbox(() => {
// oxlint-disable-next-line no-console
console.warn(
'[Sentry] `breadcrumbsIntegration({ fetch })` is deprecated and no longer has any effect. Fetch breadcrumbs are recorded by `fetchIntegration`; disable them with `fetchIntegration({ breadcrumbs: false })`.',
);
Expand Down
4 changes: 2 additions & 2 deletions packages/deno/src/integrations/denoRuntimeMetrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@ export const denoRuntimeMetricsIntegration = defineIntegration((options: DenoRun
const rawInterval = options.collectionIntervalMs ?? DEFAULT_INTERVAL_MS;
let collectionIntervalMs: number;
if (!Number.isFinite(rawInterval)) {
// eslint-disable-next-line no-console
// oxlint-disable-next-line sdk/no-unsandboxed-console -- runs when the integration is created, usually before `init()` instruments the console
console.warn(
`[Sentry] denoRuntimeMetricsIntegration: collectionIntervalMs (${rawInterval}) is invalid. Using default of ${DEFAULT_INTERVAL_MS}ms.`,
);
collectionIntervalMs = DEFAULT_INTERVAL_MS;
} else if (rawInterval < MIN_INTERVAL_MS) {
// eslint-disable-next-line no-console
// oxlint-disable-next-line sdk/no-unsandboxed-console -- runs when the integration is created, usually before `init()` instruments the console
console.warn(
`[Sentry] denoRuntimeMetricsIntegration: collectionIntervalMs (${rawInterval}) is below the minimum of ${MIN_INTERVAL_MS}ms. Using minimum of ${MIN_INTERVAL_MS}ms.`,
);
Expand Down
1 change: 0 additions & 1 deletion packages/deno/src/transports/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ export function makeFetchTransport(options: BaseTransportOptions): Transport {
.then(({ state }) => {
if (state !== 'granted') {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(`Sentry SDK requires 'net' permission to send events.
Run with '--allow-net=${url.host}' to grant the required permissions.`);
});
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin-sdk/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ module.exports = {
'no-focused-tests': require('./rules/no-focused-tests'),
'no-skipped-tests': require('./rules/no-skipped-tests'),
'no-unsafe-random-apis': require('./rules/no-unsafe-random-apis'),
'no-unsandboxed-console': require('./rules/no-unsandboxed-console'),
'no-unfiltered-url-attributes': require('./rules/no-unfiltered-url-attributes'),
'no-unguarded-span-apis': require('./rules/no-unguarded-span-apis'),
'no-unsafe-html-writes': require('./rules/no-unsafe-html-writes'),
Expand Down
106 changes: 106 additions & 0 deletions packages/eslint-plugin-sdk/src/rules/no-unsandboxed-console.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
'use strict';

/**
* @fileoverview Rule to allow direct `console.*` calls only inside a `consoleSandbox()` callback.
*
* The SDK instruments `console` to record breadcrumbs and logs. A direct `console.*` call from SDK
* code goes through that instrumentation, so the SDK records its own output. `consoleSandbox()`
* restores the original console methods while its callback runs. Debug output belongs on the
* `debug` logger instead, which is stripped from non-debug builds.
*/

const FUNCTION_TYPES = ['ArrowFunctionExpression', 'FunctionExpression'];

const TRANSPARENT_WRAPPERS = [
'ChainExpression',
'ParenthesizedExpression',
'TSNonNullExpression',
'TSAsExpression',
'TSSatisfiesExpression',
'TSTypeAssertion',
];

function unwrap(node) {
let current = node;
while (current && TRANSPARENT_WRAPPERS.includes(current.type)) {
current = current.expression;
}
return current;
}

/** Matches `consoleSandbox(...)` and `<anything>.consoleSandbox(...)`. */
function isConsoleSandboxCall(node) {
if (node.type !== 'CallExpression') {
return false;
}
const callee = unwrap(node.callee);
if (callee.type === 'Identifier') {
return callee.name === 'consoleSandbox';
}
return (
callee.type === 'MemberExpression' &&
!callee.computed &&
callee.property.type === 'Identifier' &&
callee.property.name === 'consoleSandbox'
);
}

function isInsideConsoleSandbox(node) {
let child = node;
let current = node.parent;
while (current) {
if (FUNCTION_TYPES.includes(child.type) && isConsoleSandboxCall(current) && current.arguments[0] === child) {
return true;
}
child = current;
current = current.parent;
}
return false;
}

/** A `console` that the file declares itself (e.g. `const console = GLOBAL_OBJ.console`) is not the global. */
function isShadowed(context, node) {
let scope = context.sourceCode.getScope(node);
while (scope) {
const variable = scope.set.get('console');
if (variable?.defs.length) {
return true;
}
scope = scope.upper;
}
return false;
}

module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Allow direct `console.*` calls only inside a `consoleSandbox()` callback',
category: 'Best Practices',
recommended: true,
},
fixable: null,
schema: [],
messages: {
unsandboxedConsole:
'`console.{{method}}` is only allowed inside a `consoleSandbox(() => ...)` callback, so the SDK does not capture its own output. Use the `debug` logger for debug output.',
},
},
create: function (context) {
return {
MemberExpression(node) {
const object = unwrap(node.object);
if (object.type !== 'Identifier' || object.name !== 'console') {
return;
}

if (isInsideConsoleSandbox(node) || isShadowed(context, node)) {
return;
}

const method = !node.computed && node.property.type === 'Identifier' ? node.property.name : '*';
context.report({ node, messageId: 'unsandboxedConsole', data: { method } });
},
};
},
};
Loading
Loading