import cluster from "node:cluster"; import type * as SentryNode from "@sentry/node"; import env from "@server/env"; import type { AppContext } from "@server/types"; // Sentry is only loaded in worker processes, as it is comparatively expensive // and the cluster primary only supervises the forked workers. const Sentry = env.SENTRY_DSN && cluster.isWorker ? loadSentry(env.SENTRY_DSN) : undefined; // oxlint-disable-next-line @typescript-eslint/no-explicit-any export function requestErrorHandler(error: any, ctx: AppContext) { // we don't need to report every time a request stops to the bug tracker if (error.code === "EPIPE" || error.code === "ECONNRESET") { return; } if (Sentry) { Sentry.withScope(function (scope) { const requestId = ctx.headers["x-request-id"]; if (requestId) { scope.setTag("request_id", requestId as string); } const authType = ctx.auth?.type ?? undefined; if (authType) { scope.setTag("auth_type", authType); } const teamId = ctx.auth?.user?.teamId ?? undefined; if (teamId) { scope.setTag("team_id", teamId); } const userId = ctx.auth?.user?.id ?? undefined; if (userId) { scope.setUser({ id: userId, }); } scope.setSDKProcessingMetadata({ request: ctx.req }); Sentry.captureException(error); }); } else if (env.ENVIRONMENT !== "test") { // oxlint-disable-next-line no-console console.error(error); } } export default Sentry; function loadSentry(dsn: string): typeof SentryNode { // oxlint-disable-next-line typescript/no-require-imports -- kept lazy so Sentry stays off the startup path const sentry = require("@sentry/node") as typeof SentryNode; sentry.init({ dsn, environment: env.ENVIRONMENT, release: env.RELEASE, maxBreadcrumbs: 0, integrations: [ // Request bodies can contain document content and credentials. sentry.httpIntegration({ maxIncomingRequestBodySize: "none" }), ], ignoreErrors: [ // These errors are expected in normal running of the application and // don't need to be reported. // Validation "BadRequestError", "SequelizeValidationError", "SequelizeEmptyResultError", "ValidationError", "ForbiddenError", // Authentication "UnauthorizedError", "TeamDomainRequiredError", "AuthRedirectError", "UserSuspendedError", "TooManyRequestsError", // Client disconnects "Premature close", ], beforeSend(event) { scrubRequest(event); try { switch (event.level) { case "warning": // Sample warnings to reduce noise if (Math.random() < 0.1) { return null; } break; } return event; } catch (_) { return event; } }, }); return sentry; } const SensitiveHeaderPattern = /auth|cookie|token|secret|key|session|signature/i; /** * Removes the request body, cookies, and sensitive headers from an event. * * @param event the event to scrub in place. */ function scrubRequest(event: SentryNode.ErrorEvent) { const { request } = event; if (!request) { return; } delete request.data; delete request.cookies; if (request.headers) { request.headers = Object.fromEntries( Object.entries(request.headers).filter( ([name]) => !SensitiveHeaderPattern.test(name) ) ); } }