import { createNoopErrorReporter, sanitizeErrorReportValue, type ErrorReportEvent, type ErrorReportSeverity, type ErrorReporter } from "./index.js"; export type SentryErrorReporterOptions = { dsn: string; environment?: string; release?: string; tracesSampleRate?: number; profilesSampleRate?: number; maxBreadcrumbs?: number; integrations?: unknown[]; beforeSend?: (event: ErrorReportEvent) => ErrorReportEvent | null; /** * Internal hook so tests can substitute a fake `@sentry/node` module without installing the real * dependency. Production callers should never supply this — the adapter dynamic-imports the SDK * itself and falls back to a no-op reporter when it is not installed. */ loadSentry?: () => Promise; /** * Optional logger used to surface the dynamic-import fallback. Defaults to `console.warn` so the * runtime never silently swallows a misconfiguration. */ onMissingDependency?: (message: string) => void; }; export type SentryLikeModule = { init: (options: SentryInitOptions) => void; captureException: (error: unknown, captureContext?: Record) => void; captureMessage: (message: string, captureContext?: Record) => void; }; export type SentryInitOptions = { dsn: string; environment?: string; release?: string; tracesSampleRate?: number; profilesSampleRate?: number; maxBreadcrumbs?: number; integrations?: unknown[]; beforeSend?: (event: Record, hint?: Record) => Record | null; }; /** * Allowlist of headers we forward to Sentry. Everything else is stripped before * the event leaves the runtime. Lower-case keys; the sanitizer normalises * incoming headers to lower-case before checking. */ export const SENTRY_HEADER_ALLOWLIST = new Set([ "content-type", "user-agent", "accept-language", "accept-encoding", "x-request-id", "x-forwarded-for", "referer", ]); /** * Exception types we always drop on the floor: client disconnects, intentional * aborts, and similar non-actionable noise. */ export const SENTRY_DROP_EXCEPTION_TYPES = new Set([ "AbortError", "RequestAbortedError", ]); const SEVERITY_TO_LEVEL: Record = { debug: "debug", info: "info", warn: "warning", error: "error", fatal: "fatal", }; /** * Creates a Sentry-backed error reporter. The `@sentry/node` package is loaded via dynamic import so * it stays an optional peer dependency: when it is not installed (or when the DSN is empty), the * factory returns the safe no-op reporter instead of throwing. */ export function createSentryErrorReporter(options: SentryErrorReporterOptions): ErrorReporter { const onMissing = options.onMissingDependency ?? defaultMissingDependencyLogger; if (!options.dsn) { onMissing("@toolctrl/error-reporter: SENTRY_DSN is empty; falling back to noop reporter."); return createNoopErrorReporter(); } let initialized = false; let sentry: SentryLikeModule | undefined; let initPromise: Promise | undefined; const ensureInitialized = async (): Promise => { if (initialized) { return sentry; } if (!initPromise) { initPromise = (async () => { try { const loader = options.loadSentry ?? loadSentryFromNodeModules; const loaded = await loader(); if (!loaded) { onMissing("@toolctrl/error-reporter: @sentry/node is not installed; falling back to noop reporter."); return; } loaded.init({ dsn: options.dsn, environment: options.environment, release: options.release, tracesSampleRate: options.tracesSampleRate, profilesSampleRate: options.profilesSampleRate, maxBreadcrumbs: options.maxBreadcrumbs ?? 50, integrations: options.integrations, beforeSend: (raw) => sanitizeSentryEvent(raw), }); sentry = loaded; } catch (cause) { onMissing(`@toolctrl/error-reporter: failed to initialize @sentry/node (${describeCause(cause)}); falling back to noop reporter.`); } finally { initialized = true; } })(); } await initPromise; return sentry; }; return { async report(event: ErrorReportEvent) { const sanitizedEvent = sanitizeErrorReportValue(event) as ErrorReportEvent; let finalEvent: ErrorReportEvent | null = sanitizedEvent; if (options.beforeSend) { try { finalEvent = options.beforeSend(sanitizedEvent); } catch { return; } } if (!finalEvent) { return; } const sentryModule = await ensureInitialized(); if (!sentryModule) { return; } const level = finalEvent.severity ? SEVERITY_TO_LEVEL[finalEvent.severity] ?? "error" : "error"; const captureContext = { level, extra: finalEvent, tags: { component: finalEvent.component, operation: finalEvent.operation, }, }; try { if (finalEvent.error !== undefined) { sentryModule.captureException(finalEvent.error, captureContext); return; } const message = finalEvent.errorMessage ?? `${finalEvent.component}:${finalEvent.operation}`; sentryModule.captureMessage(message, captureContext); } catch { // Sentry transport failures must never mask the runtime failure being reported. } }, }; } async function loadSentryFromNodeModules(): Promise { try { // Use a dynamic expression so the bundler/typechecker does not eagerly resolve `@sentry/node`. const moduleName = "@sentry/node"; const loaded = (await import(/* @vite-ignore */ moduleName)) as SentryLikeModule | { default?: SentryLikeModule }; if (loaded && typeof (loaded as SentryLikeModule).init === "function") { return loaded as SentryLikeModule; } if (loaded && typeof (loaded as { default?: SentryLikeModule }).default?.init === "function") { return (loaded as { default: SentryLikeModule }).default; } return undefined; } catch { return undefined; } } function defaultMissingDependencyLogger(message: string): void { const consoleRef: Console | undefined = typeof globalThis !== "undefined" ? (globalThis as { console?: Console }).console : undefined; consoleRef?.warn?.(message); } function describeCause(cause: unknown): string { if (cause instanceof Error) { return cause.message; } return String(cause); } /** * Hardened `beforeSend` for the Sentry SDK. Applied recursively to every * field that may carry user-controlled data, plus header allowlist filtering * and a drop-list for non-actionable exception types. * * Exported for unit tests; production callers should not invoke it directly. */ export function sanitizeSentryEvent(raw: Record): Record | null { if (shouldDropEvent(raw)) { return null; } const result: Record = { ...raw }; if (raw.request && typeof raw.request === "object") { result.request = sanitizeRequest(raw.request as Record); } if (raw.user && typeof raw.user === "object") { result.user = sanitizeErrorReportValue(raw.user) as Record; } if (Array.isArray(raw.breadcrumbs)) { result.breadcrumbs = (raw.breadcrumbs as unknown[]).map((crumb) => sanitizeErrorReportValue(crumb)); } if (raw.tags && typeof raw.tags === "object") { result.tags = sanitizeErrorReportValue(raw.tags) as Record; } if (raw.contexts && typeof raw.contexts === "object") { result.contexts = sanitizeErrorReportValue(raw.contexts) as Record; } if (raw.extra && typeof raw.extra === "object") { result.extra = sanitizeErrorReportValue(raw.extra) as Record; } return result; } function shouldDropEvent(raw: Record): boolean { const exception = raw.exception; if (!exception || typeof exception !== "object") { return false; } const values = (exception as { values?: unknown[] }).values; if (!Array.isArray(values) || values.length === 0) { return false; } const first = values[0]; if (!first || typeof first !== "object") { return false; } const type = (first as { type?: unknown }).type; return typeof type === "string" && SENTRY_DROP_EXCEPTION_TYPES.has(type); } function sanitizeRequest(request: Record): Record { const sanitized: Record = { ...request }; if (request.headers && typeof request.headers === "object") { sanitized.headers = filterAllowedHeaders(request.headers as Record); } if (typeof request.cookies !== "undefined") { sanitized.cookies = "[Redacted]"; } if (typeof request.data !== "undefined") { sanitized.data = sanitizeErrorReportValue(request.data); } if (typeof request.query_string === "string") { sanitized.query_string = sanitizeQueryString(request.query_string); } return sanitized; } function filterAllowedHeaders(headers: Record): Record { const allowed: Record = {}; for (const [rawKey, value] of Object.entries(headers)) { const normalised = rawKey.toLowerCase(); if (!SENTRY_HEADER_ALLOWLIST.has(normalised)) { continue; } allowed[rawKey] = sanitizeErrorReportValue(value); } return allowed; } const QUERY_REDACT_KEYS = new Set(["token", "accesstoken", "refreshtoken", "apikey", "secret", "password"]); function sanitizeQueryString(value: string): string { return value.replace(/([?&]?)([^=&]+)=([^&]*)/g, (_match, sep: string, key: string, rawValue: string) => { const compact = key.toLowerCase().replace(/[-_]/g, ""); if (QUERY_REDACT_KEYS.has(compact)) { return `${sep}${key}=[Redacted]`; } return `${sep}${key}=${rawValue}`; }); }