customer/src/sentry.ts
2026-11-14 22:49:40 +05:00

90 lines
2.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import * as Sentry from "@sentry/node";
import type { ErrorEvent, NodeOptions } from "@sentry/node";
import type { DataCollection } from "@sentry/core";
const SENSITIVE_HEADERS = new Set([
"authorization",
"cookie",
"set-cookie",
"proxy-authorization",
"x-forwarded-for",
"x-real-ip",
"forwarded",
]);
/** Удаляет из события ПДн: IP, cookies, заголовки авторизации, query и тело запроса. */
export function scrubEvent(event: ErrorEvent): ErrorEvent {
if (event.user) {
delete event.user.ip_address;
delete event.user.email;
delete event.user.username;
}
const req = event.request;
if (req) {
delete req.cookies;
delete req.data;
delete req.query_string;
delete req.env;
if (req.url) req.url = req.url.split("?")[0];
if (req.headers) {
req.headers = Object.fromEntries(
Object.entries(req.headers).filter(([name]) => !SENSITIVE_HEADERS.has(name.toLowerCase())),
);
}
}
return event;
}
/** Не собирать ПДн автоматически: пользователь, cookies, заголовки, тела, query, переменные стека. */
export const PRIVACY_DATA_COLLECTION: DataCollection = {
userInfo: false,
cookies: false,
httpHeaders: false,
httpBodies: [],
urlQueryParams: false,
graphQL: { document: false, variables: false },
genAI: { inputs: false, outputs: false },
mcp: { inputs: false, outputs: false },
databaseQueryData: false,
queues: false,
stackFrameVariables: false,
};
let enabled = false;
/** Инициализирует SDK Sentry (Bugsink), только если задан SENTRY_DSN. */
export function initSentry(
env: NodeJS.ProcessEnv = process.env,
extra: Partial<NodeOptions> = {},
): boolean {
const dsn = env.SENTRY_DSN;
if (!dsn) return false;
Sentry.init({
dsn,
release: env.SENTRY_RELEASE || undefined,
environment: env.SENTRY_ENVIRONMENT || "dev",
// Sentry v11: вместо sendDefaultPii — dataCollection, по умолчанию собирает всё. Запрещаем ПДн.
dataCollection: PRIVACY_DATA_COLLECTION,
tracesSampleRate: 0,
beforeSend: scrubEvent,
...extra,
});
enabled = true;
return true;
}
export function captureError(err: unknown, request?: { method: string; url: string }): void {
if (!enabled) return;
Sentry.withScope((scope) => {
if (request) {
// Только метод и путь: без query, заголовков и тела.
scope.setContext("request", { method: request.method, path: request.url.split("?")[0] });
}
Sentry.captureException(err);
});
}
export async function flushSentry(timeoutMs = 2000): Promise<void> {
if (enabled) await Sentry.flush(timeoutMs);
}