Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,378 @@
import { describe, expect, it, vi } from "vitest";
import {
createNoopErrorReporter,
createSentryErrorReporter,
initializeTracing,
reportError,
sanitizeErrorReportValue,
shutdownTracing,
type ErrorReportEvent,
type ErrorReporter,
type NodeSdkInstance,
type NodeSdkLikeModule,
type OtlpExporterLikeModule,
type SentryInitOptions,
type SentryLikeModule,
} from "./index.js";
describe("@toolctrl/error-reporter", () => {
it("redacts nested secrets and unsafe payload keys while preserving correlation fields", () => {
const rawSecrets = [
"Bearer auth-token",
"session=abc",
"plain-password",
"nested-token",
"top-secret",
"api-key-value",
"redis://:redis-password@localhost:6379",
"postgres://user:password@localhost/database",
"person@example.com",
"template-token",
"raw request body",
"raw headers payload",
"top-level-template-token",
"nested-array-cookie",
];
const sanitized = sanitizeErrorReportValue({
component: "worker",
operation: "job.failed",
severity: "error",
requestId: "req_123",
queueName: "email",
jobId: "job_456",
retryCount: 2,
authorization: rawSecrets[0],
headers: { cookie: rawSecrets[1], raw: rawSecrets[11] },
password: rawSecrets[2],
body: rawSecrets[10],
templateData: { token: rawSecrets[12] },
nested: [
{
token: rawSecrets[3],
secret: rawSecrets[4],
apiKey: rawSecrets[5],
redisUrl: rawSecrets[6],
connectionString: rawSecrets[7],
email: rawSecrets[8],
templateData: { token: rawSecrets[9] },
body: rawSecrets[10],
recipients: [{ cookie: rawSecrets[13] }],
},
],
});
expect(sanitized).toMatchObject({
component: "worker",
operation: "job.failed",
severity: "error",
requestId: "req_123",
queueName: "email",
jobId: "job_456",
retryCount: 2,
authorization: "[Redacted]",
headers: "[Redacted]",
password: "[Redacted]",
body: "[Redacted]",
templateData: "[Redacted]",
nested: [
{
token: "[Redacted]",
secret: "[Redacted]",
apiKey: "[Redacted]",
redisUrl: "[Redacted]",
connectionString: "[Redacted]",
email: "[Redacted]",
templateData: "[Redacted]",
body: "[Redacted]",
recipients: [{ cookie: "[Redacted]" }],
},
],
});
const serialized = JSON.stringify(sanitized);
for (const rawSecret of rawSecrets) {
expect(serialized).not.toContain(rawSecret);
}
});
it("serializes Error objects without leaking enumerable secret metadata", () => {
const error = new Error("database failed");
Object.assign(error, {
token: "error-token",
safeDetail: "kept",
});
expect(sanitizeErrorReportValue({ error })).toMatchObject({
error: {
errorName: "Error",
errorMessage: "database failed",
token: "[Redacted]",
safeDetail: "kept",
},
});
});
it("swallows sync throws and async rejections from reporters", async () => {
const syncReporter: ErrorReporter = {
report() {
throw new Error("transport unavailable");
},
};
const asyncReporter: ErrorReporter = {
async report() {
throw new Error("transport rejected");
},
};
expect(() => reportError(syncReporter, { component: "api", operation: "request", errorMessage: "failed" })).not.toThrow();
expect(() => reportError(asyncReporter, { component: "api", operation: "request", errorMessage: "failed" })).not.toThrow();
await Promise.resolve();
});
it("provides a safe no-op reporter", () => {
expect(() => reportError(createNoopErrorReporter(), { component: "api", operation: "request" })).not.toThrow();
});
});
describe("createSentryErrorReporter", () => {
it("falls back to noop when @sentry/node is not installed", async () => {
const warn = vi.fn();
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => undefined,
onMissingDependency: warn,
});
await reporter.report({ component: "api", operation: "request" });
expect(warn).toHaveBeenCalledWith(expect.stringContaining("@sentry/node is not installed"));
});
it("falls back to noop when the DSN is empty", async () => {
const warn = vi.fn();
const reporter = createSentryErrorReporter({ dsn: "", onMissingDependency: warn });
await reporter.report({ component: "api", operation: "request" });
expect(warn).toHaveBeenCalledWith(expect.stringContaining("SENTRY_DSN is empty"));
});
it("invokes beforeSend hook and suppresses delivery when it returns null", async () => {
const captureException = vi.fn();
const captureMessage = vi.fn();
const init = vi.fn();
const fakeSentry: SentryLikeModule = { init, captureException, captureMessage };
const beforeSend = vi.fn().mockReturnValue(null);
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
beforeSend,
loadSentry: async () => fakeSentry,
});
await reporter.report({ component: "api", operation: "request", errorMessage: "fail", token: "raw-token" });
expect(beforeSend).toHaveBeenCalledTimes(1);
const sanitizedArg = beforeSend.mock.calls[0]?.[0] as ErrorReportEvent | undefined;
expect(sanitizedArg?.token).toBe("[Redacted]");
expect(captureException).not.toHaveBeenCalled();
expect(captureMessage).not.toHaveBeenCalled();
});
it("sanitizes the event before forwarding it to Sentry capture", async () => {
const captureMessage = vi.fn();
const captureException = vi.fn();
let capturedInitOptions: SentryInitOptions | undefined;
const fakeSentry: SentryLikeModule = {
init: (opts) => {
capturedInitOptions = opts;
},
captureException,
captureMessage,
};
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
environment: "test",
release: "test-rev",
loadSentry: async () => fakeSentry,
});
await reporter.report({
component: "worker",
operation: "job.failed",
severity: "error",
errorMessage: "boom",
authorization: "Bearer raw-token",
password: "raw",
});
expect(capturedInitOptions?.dsn).toBe("https://example@sentry.io/1");
expect(capturedInitOptions?.environment).toBe("test");
expect(capturedInitOptions?.release).toBe("test-rev");
expect(captureMessage).toHaveBeenCalledTimes(1);
const [message, context] = captureMessage.mock.calls[0] ?? [];
expect(message).toBe("boom");
const extra = (context as { extra?: ErrorReportEvent } | undefined)?.extra;
expect(extra?.authorization).toBe("[Redacted]");
expect(extra?.password).toBe("[Redacted]");
expect(captureException).not.toHaveBeenCalled();
});
});
describe("initializeTracing", () => {
it("does nothing when tracing is explicitly disabled", async () => {
const warn = vi.fn();
const loadSdk = vi.fn(async () => {
throw new Error("should not load");
});
const loadOtlpExporter = vi.fn(async () => {
throw new Error("should not load");
});
await initializeTracing({
serviceName: "api",
enabled: false,
otlpEndpoint: "http://localhost:4318/v1/traces",
loadSdk,
loadOtlpExporter,
onMissingDependency: warn,
});
expect(loadSdk).not.toHaveBeenCalled();
expect(loadOtlpExporter).not.toHaveBeenCalled();
expect(warn).not.toHaveBeenCalled();
});
it("logs a warning and skips startup when no OTLP endpoint is configured", async () => {
const warn = vi.fn();
const previousEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
try {
await initializeTracing({ serviceName: "test", onMissingDependency: warn });
} finally {
if (previousEndpoint) {
process.env.OTEL_EXPORTER_OTLP_ENDPOINT = previousEndpoint;
}
}
expect(warn).toHaveBeenCalledWith(expect.stringContaining("OTEL_EXPORTER_OTLP_ENDPOINT"));
});
it("falls back to noop when OpenTelemetry SDK dependencies are missing", async () => {
const warn = vi.fn();
await initializeTracing({
serviceName: "test",
otlpEndpoint: "http://localhost:4318/v1/traces",
loadSdk: async () => undefined,
loadOtlpExporter: async () => undefined,
onMissingDependency: warn,
});
expect(warn).toHaveBeenCalledWith(expect.stringContaining("@opentelemetry/sdk-node"));
});
it("treats loader exceptions as missing OpenTelemetry dependencies", async () => {
const warn = vi.fn();
await initializeTracing({
serviceName: "api",
otlpEndpoint: "http://localhost:4318/v1/traces",
loadSdk: async () => {
throw new Error("sdk import failed");
},
loadOtlpExporter: async () => {
throw new Error("exporter import failed");
},
onMissingDependency: warn,
});
expect(warn).toHaveBeenCalledWith(expect.stringContaining("@opentelemetry/sdk-node or @opentelemetry/exporter-trace-otlp-http"));
});
it("logs startup failures without keeping an active tracing state", async () => {
const warn = vi.fn();
const start = vi.fn(() => {
throw new Error("start failed");
});
const shutdown = vi.fn(async () => undefined);
const sdkInstance: NodeSdkInstance = { start, shutdown };
const NodeSDK = vi.fn().mockImplementation(() => sdkInstance);
const OTLPTraceExporter = vi.fn().mockImplementation(() => ({}));
const sdkModule: NodeSdkLikeModule = { NodeSDK: NodeSDK as unknown as NodeSdkLikeModule["NodeSDK"] };
const exporterModule: OtlpExporterLikeModule = {
OTLPTraceExporter: OTLPTraceExporter as unknown as OtlpExporterLikeModule["OTLPTraceExporter"],
};
await initializeTracing({
serviceName: "api",
otlpEndpoint: "http://localhost:4318/v1/traces",
loadSdk: async () => sdkModule,
loadOtlpExporter: async () => exporterModule,
onMissingDependency: warn,
});
await shutdownTracing();
expect(warn).toHaveBeenCalledWith(expect.stringContaining("failed to start OpenTelemetry NodeSDK (start failed)"));
expect(shutdown).not.toHaveBeenCalled();
});
it("starts the NodeSDK once when both modules are present and shuts down cleanly", async () => {
const start = vi.fn();
const shutdown = vi.fn(async () => undefined);
const sdkInstance: NodeSdkInstance = { start, shutdown };
const NodeSDK = vi.fn().mockImplementation(() => sdkInstance);
const OTLPTraceExporter = vi.fn().mockImplementation(() => ({}));
const sdkModule: NodeSdkLikeModule = { NodeSDK: NodeSDK as unknown as NodeSdkLikeModule["NodeSDK"] };
const exporterModule: OtlpExporterLikeModule = {
OTLPTraceExporter: OTLPTraceExporter as unknown as OtlpExporterLikeModule["OTLPTraceExporter"],
};
await initializeTracing({
serviceName: "api",
otlpEndpoint: "http://localhost:4318/v1/traces",
loadSdk: async () => sdkModule,
loadOtlpExporter: async () => exporterModule,
});
expect(NodeSDK).toHaveBeenCalledTimes(1);
expect(OTLPTraceExporter).toHaveBeenCalledWith({ url: "http://localhost:4318/v1/traces" });
expect(start).toHaveBeenCalledTimes(1);
await initializeTracing({
serviceName: "api",
otlpEndpoint: "http://localhost:4318/v1/traces",
loadSdk: async () => sdkModule,
loadOtlpExporter: async () => exporterModule,
});
expect(NodeSDK).toHaveBeenCalledTimes(1);
await shutdownTracing();
expect(shutdown).toHaveBeenCalledTimes(1);
});
it("swallows shutdown failures", async () => {
const start = vi.fn();
const shutdown = vi.fn(async () => {
throw new Error("shutdown failed");
});
const sdkInstance: NodeSdkInstance = { start, shutdown };
const NodeSDK = vi.fn().mockImplementation(() => sdkInstance);
const OTLPTraceExporter = vi.fn().mockImplementation(() => ({}));
const sdkModule: NodeSdkLikeModule = { NodeSDK: NodeSDK as unknown as NodeSdkLikeModule["NodeSDK"] };
const exporterModule: OtlpExporterLikeModule = {
OTLPTraceExporter: OTLPTraceExporter as unknown as OtlpExporterLikeModule["OTLPTraceExporter"],
};
await initializeTracing({
serviceName: "api",
otlpEndpoint: "http://localhost:4318/v1/traces",
loadSdk: async () => sdkModule,
loadOtlpExporter: async () => exporterModule,
});
await expect(shutdownTracing()).resolves.toBeUndefined();
expect(shutdown).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,61 @@
import { sanitizeErrorReportValue } from "./sanitize.js";
export type ErrorReportSeverity = "debug" | "info" | "warn" | "error" | "fatal";
export interface ErrorReportContext {
component: string;
operation: string;
severity?: ErrorReportSeverity;
requestId?: string;
method?: string;
path?: string;
queueName?: string;
jobId?: string | number;
retryCount?: number;
[key: string]: unknown;
}
export interface ErrorReportEvent extends ErrorReportContext {
error?: unknown;
errorName?: string;
errorMessage?: string;
errorStack?: string;
}
export interface ErrorReporter {
report(event: ErrorReportEvent): void | Promise<void>;
}
export function createNoopErrorReporter(): ErrorReporter {
return {
report() {
// Intentionally empty: the no-op reporter is safe for tests and local defaults.
},
};
}
export function reportError(reporter: ErrorReporter | undefined | null, event: ErrorReportEvent): void {
if (!reporter) {
return;
}
try {
const result = reporter.report(sanitizeErrorReportValue(event) as ErrorReportEvent);
if (isPromiseLike(result)) {
result.catch(() => {
// Reporter failures must never mask the runtime failure being reported.
});
}
} catch {
// Reporter failures must never mask the runtime failure being reported.
}
}
function isPromiseLike(value: unknown): value is PromiseLike<void> {
return Boolean(value) && typeof (value as { catch?: unknown }).catch === "function";
}
export { sanitizeErrorReportValue } from "./sanitize.js";
export { createSentryErrorReporter, type SentryErrorReporterOptions, type SentryLikeModule, type SentryInitOptions } from "./sentry.js";
export { initializeTracing, shutdownTracing, type TracingOptions, type NodeSdkLikeModule, type NodeSdkInstance, type OtlpExporterLikeModule } from "./tracing.js";
@@ -0,0 +1,111 @@
import { describe, expect, it } from "vitest";
import { sanitizeErrorReportValue, __internal } from "./sanitize.js";
describe("sanitizeErrorReportValue (recursive)", () => {
it("redacts nested sensitive keys regardless of casing and separators", () => {
const sanitized = sanitizeErrorReportValue({
Authorization: "Bearer raw-token",
passWord: "raw",
X_API_Key: "x-key-value",
X_CSRF_Token: "csrf-value",
"Set-Cookie": "session=abc; Path=/",
access_token: "access-raw",
refreshToken: "refresh-raw",
session_id: "sess-id",
phone: "+49-30-12345",
Email: "person@example.com",
payload: {
nested: {
password: "deep-pw",
extras: [{ apiKey: "k1" }, { setCookie: "session=def" }],
},
},
}) as Record<string, unknown>;
expect(sanitized.Authorization).toBe("[Redacted]");
expect(sanitized.passWord).toBe("[Redacted]");
expect(sanitized.X_API_Key).toBe("[Redacted]");
expect(sanitized.X_CSRF_Token).toBe("[Redacted]");
expect(sanitized["Set-Cookie"]).toBe("[Redacted]");
expect(sanitized.access_token).toBe("[Redacted]");
expect(sanitized.refreshToken).toBe("[Redacted]");
expect(sanitized.session_id).toBe("[Redacted]");
expect(sanitized.phone).toBe("[Redacted]");
expect(sanitized.Email).toBe("[Redacted]");
const payload = sanitized.payload as { nested: { password: string; extras: Array<Record<string, string>> } };
expect(payload.nested.password).toBe("[Redacted]");
expect(payload.nested.extras[0]?.apiKey).toBe("[Redacted]");
expect(payload.nested.extras[1]?.setCookie).toBe("[Redacted]");
});
it("redacts scalar secret patterns embedded in free-form strings", () => {
const result = sanitizeErrorReportValue({
message: "Failed Authorization: Bearer eyJabc.def at postgres://user:password@db/host",
detail: "connection redis://:secret@redis:6379 fell over",
params: "token=abc123 went bad",
}) as Record<string, string>;
expect(result.message).toContain("Bearer [Redacted]");
expect(result.message).toContain("[Redacted]");
expect(result.message).not.toContain("eyJabc.def");
expect(result.message).not.toContain("user:password");
expect(result.detail).toContain("[Redacted]");
expect(result.detail).not.toContain(":secret@redis:6379");
expect(result.params).toContain("[Redacted]");
expect(result.params).not.toContain("abc123");
});
it("truncates strings larger than 8 KB with a length marker", () => {
const huge = "a".repeat(__internal.MAX_STRING_BYTES + 5);
const result = sanitizeErrorReportValue({ blob: huge }) as { blob: string };
expect(result.blob).toMatch(/^<string truncated, \d+ bytes>$/);
expect(result.blob).not.toContain("aaa");
});
it("does not truncate strings at or below the 8 KB boundary", () => {
const justFits = "a".repeat(__internal.MAX_STRING_BYTES);
const result = sanitizeErrorReportValue({ blob: justFits }) as { blob: string };
expect(result.blob).toBe(justFits);
});
it("handles circular references without overflowing", () => {
const circular: Record<string, unknown> = { a: 1 };
circular.self = circular;
const list: unknown[] = [];
list.push(list);
const result = sanitizeErrorReportValue({ root: circular, listy: list }) as { root: { a: number; self: string }; listy: string[] };
expect(result.root.a).toBe(1);
expect(result.root.self).toBe("[Circular]");
expect(result.listy[0]).toBe("[Circular]");
});
it("preserves Error metadata while redacting enumerable secret fields", () => {
const err = new Error("connection failed token=abc123");
Object.assign(err, { token: "raw", safe: "kept" });
const result = sanitizeErrorReportValue({ error: err }) as { error: Record<string, unknown> };
expect(result.error.errorName).toBe("Error");
expect(result.error.errorMessage).toContain("[Redacted]");
expect(result.error.errorMessage).not.toContain("abc123");
expect(result.error.token).toBe("[Redacted]");
expect(result.error.safe).toBe("kept");
});
it("redacts setCookie variants (Set-Cookie, set_cookie, setCookie)", () => {
const result = sanitizeErrorReportValue({
"Set-Cookie": "x",
set_cookie: "y",
setCookie: "z",
"X-Api-Key": "k",
"x-csrf-token": "c",
}) as Record<string, string>;
expect(result["Set-Cookie"]).toBe("[Redacted]");
expect(result.set_cookie).toBe("[Redacted]");
expect(result.setCookie).toBe("[Redacted]");
expect(result["X-Api-Key"]).toBe("[Redacted]");
expect(result["x-csrf-token"]).toBe("[Redacted]");
});
});
@@ -0,0 +1,167 @@
/**
* Recursive PII / secret sanitization used by the Sentry adapter and the runtime
* `reportError` helper. Lives in its own module so the Hono / BullMQ wiring can
* import it directly without pulling the Sentry adapter surface.
*/
const REDACTED = "[Redacted]";
const CIRCULAR = "[Circular]";
const MAX_STRING_BYTES = 8 * 1024;
/**
* Header / payload key denylist. Matching is case-insensitive against the trimmed
* key. Entries are matched both as exact equals and against canonicalised forms
* with `-` and `_` stripped, so `set-cookie`, `setCookie`, and `set_cookie` are
* all redacted.
*/
const SENSITIVE_KEY_DENYLIST = new Set<string>([
// Phase 02 / Sentry-wiring spec (#30)
"password",
"passwd",
"pwd",
"token",
"accesstoken",
"refreshtoken",
"idtoken",
"secret",
"apikey",
"authorization",
"cookie",
"setcookie",
"xapikey",
"xcsrftoken",
"csrftoken",
"sessionid",
"session",
"phone",
"phonenumber",
"email",
"emailaddress",
// Legacy denylist preserved from the previous flat sanitizer so existing
// call-sites (mail, workflow, queue payloads) keep their guarantees.
"body",
"headers",
"recipient",
"templatedata",
"to",
"connectionstring",
"redisurl",
]);
const BEARER_TOKEN_PATTERN = /bearer\s+[^\s,;]+/gi;
const POSTGRES_URL_PATTERN = /postgres(?:ql)?:\/\/[^\s,;]+/gi;
const REDIS_URL_PATTERN = /redis:\/\/[^\s,;]+/gi;
const KEY_VALUE_SECRET_PATTERN = /(?:token|secret|password|apiKey|connectionString|redisUrl)=([^\s,;]+)/gi;
export function sanitizeErrorReportValue(value: unknown): unknown {
return sanitizeValue(value, undefined, new WeakSet<object>());
}
function sanitizeValue(value: unknown, key: string | undefined, seen: WeakSet<object>): unknown {
if (key && isSensitiveKey(key)) {
return REDACTED;
}
if (value instanceof Error) {
return sanitizeError(value, seen);
}
if (Array.isArray(value)) {
if (seen.has(value)) {
return CIRCULAR;
}
seen.add(value);
const result = value.map((entry) => sanitizeValue(entry, undefined, seen));
seen.delete(value);
return result;
}
if (value && typeof value === "object") {
if (seen.has(value)) {
return CIRCULAR;
}
seen.add(value);
const sanitized: Record<string, unknown> = {};
for (const [entryKey, entryValue] of Object.entries(value)) {
sanitized[entryKey] = sanitizeValue(entryValue, entryKey, seen);
}
seen.delete(value);
return sanitized;
}
if (typeof value === "string") {
return truncateString(redactUnsafeScalar(value));
}
return value;
}
function isSensitiveKey(key: string): boolean {
const normalized = key.trim().toLowerCase();
if (SENSITIVE_KEY_DENYLIST.has(normalized)) {
return true;
}
const compact = normalized.replace(/[-_]/g, "");
return SENSITIVE_KEY_DENYLIST.has(compact);
}
function redactUnsafeScalar(value: string): string {
return value
.replace(BEARER_TOKEN_PATTERN, "Bearer [Redacted]")
.replace(POSTGRES_URL_PATTERN, "[Redacted]")
.replace(REDIS_URL_PATTERN, "[Redacted]")
.replace(KEY_VALUE_SECRET_PATTERN, () => "[Redacted]");
}
function truncateString(value: string): string {
// Byte-length aware truncation so multibyte characters never push us over the
// limit. We use UTF-8 byte counting through Buffer when available; the
// browser/edge runtimes that lack Buffer still get a safe `value.length`
// approximation.
const bytes = computeByteLength(value);
if (bytes <= MAX_STRING_BYTES) {
return value;
}
return `<string truncated, ${bytes} bytes>`;
}
function computeByteLength(value: string): number {
if (typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function") {
return Buffer.byteLength(value, "utf8");
}
// Fallback: TextEncoder is universally available in Node 18+ and browsers.
if (typeof TextEncoder !== "undefined") {
return new TextEncoder().encode(value).length;
}
return value.length;
}
function sanitizeError(error: Error, seen: WeakSet<object>): Record<string, unknown> {
const sanitized: Record<string, unknown> = {
errorName: error.name,
errorMessage: redactUnsafeScalar(error.message),
};
for (const [key, value] of Object.entries(error)) {
sanitized[key] = sanitizeValue(value, key, seen);
}
return sanitized;
}
export const __internal = {
MAX_STRING_BYTES,
REDACTED,
CIRCULAR,
isSensitiveKey,
redactUnsafeScalar,
truncateString,
};
@@ -0,0 +1,229 @@
import { describe, expect, it, vi } from "vitest";
import {
SENTRY_DROP_EXCEPTION_TYPES,
SENTRY_HEADER_ALLOWLIST,
createSentryErrorReporter,
sanitizeSentryEvent,
type SentryInitOptions,
type SentryLikeModule,
} from "./sentry.js";
describe("sanitizeSentryEvent", () => {
it("strips disallowed request headers and keeps the allowlist", () => {
const result = sanitizeSentryEvent({
request: {
url: "https://api.example.com/v1/widgets",
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": "vitest/1.0",
Authorization: "Bearer leaked",
"X-API-Key": "leaked",
"X-Csrf-Token": "csrf",
"Set-Cookie": "session=abc",
Cookie: "session=abc",
Referer: "https://example.com",
},
},
});
expect(result).not.toBeNull();
const headers = (result?.request as { headers: Record<string, unknown> }).headers;
expect(Object.keys(headers).map((k) => k.toLowerCase()).sort()).toEqual([
"content-type",
"referer",
"user-agent",
]);
expect(headers).not.toHaveProperty("Authorization");
expect(headers).not.toHaveProperty("X-API-Key");
expect(headers).not.toHaveProperty("Cookie");
});
it("recursively sanitizes user, extra, contexts, tags, breadcrumbs", () => {
const result = sanitizeSentryEvent({
user: { id: "u1", email: "alice@example.com", phone: "+1-555" },
extra: { token: "raw", payload: { password: "deep" } },
contexts: { custom: { secret: "leak" } },
tags: { apiKey: "x" },
breadcrumbs: [
{ category: "http", data: { body: { password: "hunter2" } } },
{ category: "auth", data: { token: "abc" } },
],
});
expect(result).not.toBeNull();
expect((result?.user as Record<string, unknown>).email).toBe("[Redacted]");
expect((result?.user as Record<string, unknown>).phone).toBe("[Redacted]");
expect((result?.user as Record<string, unknown>).id).toBe("u1");
expect((result?.extra as Record<string, unknown>).token).toBe("[Redacted]");
expect(((result?.extra as { payload: Record<string, unknown> }).payload).password).toBe("[Redacted]");
expect(((result?.contexts as { custom: Record<string, unknown> }).custom).secret).toBe("[Redacted]");
expect((result?.tags as Record<string, unknown>).apiKey).toBe("[Redacted]");
const breadcrumbs = result?.breadcrumbs as Array<Record<string, unknown>>;
expect((breadcrumbs[0]?.data as Record<string, unknown>).body).toBe("[Redacted]");
expect((breadcrumbs[1]?.data as Record<string, unknown>).token).toBe("[Redacted]");
});
it("drops AbortError and similar non-actionable exceptions", () => {
expect(
sanitizeSentryEvent({
exception: { values: [{ type: "AbortError", value: "client gone" }] },
})
).toBeNull();
expect(
sanitizeSentryEvent({
exception: { values: [{ type: "RequestAbortedError" }] },
})
).toBeNull();
expect(
sanitizeSentryEvent({
exception: { values: [{ type: "TypeError", value: "x.y is undefined" }] },
})
).not.toBeNull();
});
it("redacts known query-string secret keys without dropping other params", () => {
const result = sanitizeSentryEvent({
request: {
url: "https://api.example.com/x",
query_string: "id=42&token=abc&apiKey=xyz&page=2",
headers: {},
},
});
const q = (result?.request as { query_string: string }).query_string;
expect(q).toContain("id=42");
expect(q).toContain("page=2");
expect(q).toContain("token=[Redacted]");
expect(q).toContain("apiKey=[Redacted]");
expect(q).not.toContain("abc");
expect(q).not.toContain("xyz");
});
it("redacts request.cookies wholesale", () => {
const result = sanitizeSentryEvent({
request: { cookies: { session: "raw", csrf: "raw" }, headers: {} },
});
expect((result?.request as { cookies: unknown }).cookies).toBe("[Redacted]");
});
it("redacts request.data via the recursive sanitizer", () => {
const result = sanitizeSentryEvent({
request: {
data: { username: "alice", password: "hunter2", profile: { token: "deep" } },
headers: {},
},
});
const data = (result?.request as { data: Record<string, unknown> }).data;
expect(data.username).toBe("alice");
expect(data.password).toBe("[Redacted]");
expect((data.profile as Record<string, unknown>).token).toBe("[Redacted]");
});
it("exposes the canonical header allowlist", () => {
for (const h of ["content-type", "user-agent", "accept-language", "accept-encoding", "x-request-id", "x-forwarded-for", "referer"]) {
expect(SENTRY_HEADER_ALLOWLIST.has(h)).toBe(true);
}
});
it("exposes the canonical exception drop list", () => {
expect(SENTRY_DROP_EXCEPTION_TYPES.has("AbortError")).toBe(true);
expect(SENTRY_DROP_EXCEPTION_TYPES.has("RequestAbortedError")).toBe(true);
});
});
describe("createSentryErrorReporter init plumbing", () => {
it("forwards tracesSampleRate / profilesSampleRate / maxBreadcrumbs / integrations", async () => {
let captured: SentryInitOptions | undefined;
const fakeSentry: SentryLikeModule = {
init: (opts) => {
captured = opts;
},
captureException: vi.fn(),
captureMessage: vi.fn(),
};
const integrations = [{ name: "fake" }];
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
environment: "staging",
release: "abc123",
tracesSampleRate: 0.25,
profilesSampleRate: 0.1,
maxBreadcrumbs: 75,
integrations,
loadSentry: async () => fakeSentry,
});
await reporter.report({ component: "api", operation: "request", errorMessage: "boom" });
expect(captured?.dsn).toBe("https://example@sentry.io/1");
expect(captured?.environment).toBe("staging");
expect(captured?.release).toBe("abc123");
expect(captured?.tracesSampleRate).toBe(0.25);
expect(captured?.profilesSampleRate).toBe(0.1);
expect(captured?.maxBreadcrumbs).toBe(75);
expect(captured?.integrations).toBe(integrations);
expect(typeof captured?.beforeSend).toBe("function");
});
it("defaults maxBreadcrumbs to 50 when not provided", async () => {
let captured: SentryInitOptions | undefined;
const fakeSentry: SentryLikeModule = {
init: (opts) => {
captured = opts;
},
captureException: vi.fn(),
captureMessage: vi.fn(),
};
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => fakeSentry,
});
await reporter.report({ component: "api", operation: "request", errorMessage: "boom" });
expect(captured?.maxBreadcrumbs).toBe(50);
});
it("init.beforeSend runs the recursive sanitizer end-to-end", async () => {
let captured: SentryInitOptions | undefined;
const fakeSentry: SentryLikeModule = {
init: (opts) => {
captured = opts;
},
captureException: vi.fn(),
captureMessage: vi.fn(),
};
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => fakeSentry,
});
await reporter.report({ component: "api", operation: "request", errorMessage: "boom" });
expect(captured?.beforeSend).toBeDefined();
const transformed = captured?.beforeSend?.(
{
request: { headers: { Authorization: "Bearer x", "Content-Type": "application/json" } },
user: { email: "bob@example.com" },
},
undefined
);
expect(transformed).not.toBeNull();
const headers = ((transformed as { request: { headers: Record<string, unknown> } }).request).headers;
expect(headers).not.toHaveProperty("Authorization");
expect(headers["Content-Type"]).toBe("application/json");
expect(((transformed as { user: Record<string, unknown> }).user).email).toBe("[Redacted]");
});
});
@@ -0,0 +1,310 @@
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<SentryLikeModule | undefined>;
/**
* 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<string, unknown>) => void;
captureMessage: (message: string, captureContext?: Record<string, unknown>) => void;
};
export type SentryInitOptions = {
dsn: string;
environment?: string;
release?: string;
tracesSampleRate?: number;
profilesSampleRate?: number;
maxBreadcrumbs?: number;
integrations?: unknown[];
beforeSend?: (event: Record<string, unknown>, hint?: Record<string, unknown>) => Record<string, unknown> | 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<string>([
"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<string>([
"AbortError",
"RequestAbortedError",
]);
const SEVERITY_TO_LEVEL: Record<ErrorReportSeverity, string> = {
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<void> | undefined;
const ensureInitialized = async (): Promise<SentryLikeModule | undefined> => {
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<SentryLikeModule | undefined> {
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<string, unknown>): Record<string, unknown> | null {
if (shouldDropEvent(raw)) {
return null;
}
const result: Record<string, unknown> = { ...raw };
if (raw.request && typeof raw.request === "object") {
result.request = sanitizeRequest(raw.request as Record<string, unknown>);
}
if (raw.user && typeof raw.user === "object") {
result.user = sanitizeErrorReportValue(raw.user) as Record<string, unknown>;
}
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<string, unknown>;
}
if (raw.contexts && typeof raw.contexts === "object") {
result.contexts = sanitizeErrorReportValue(raw.contexts) as Record<string, unknown>;
}
if (raw.extra && typeof raw.extra === "object") {
result.extra = sanitizeErrorReportValue(raw.extra) as Record<string, unknown>;
}
return result;
}
function shouldDropEvent(raw: Record<string, unknown>): 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<string, unknown>): Record<string, unknown> {
const sanitized: Record<string, unknown> = { ...request };
if (request.headers && typeof request.headers === "object") {
sanitized.headers = filterAllowedHeaders(request.headers as Record<string, unknown>);
}
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<string, unknown>): Record<string, unknown> {
const allowed: Record<string, unknown> = {};
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<string>(["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}`;
});
}
@@ -0,0 +1,165 @@
export type TracingOptions = {
serviceName: string;
/** Falls back to OTEL_EXPORTER_OTLP_ENDPOINT environment variable when not provided. */
otlpEndpoint?: string;
enabled?: boolean;
/**
* Internal hooks used by tests to substitute the OpenTelemetry SDK without installing it.
* Production callers should never supply these.
*/
loadSdk?: () => Promise<NodeSdkLikeModule | undefined>;
loadOtlpExporter?: () => Promise<OtlpExporterLikeModule | undefined>;
/**
* Optional logger used to surface the dynamic-import fallback. Defaults to `console.warn`.
*/
onMissingDependency?: (message: string) => void;
};
export type NodeSdkLikeModule = {
NodeSDK: new (options: { serviceName?: string; traceExporter?: unknown }) => NodeSdkInstance;
};
export type NodeSdkInstance = {
start: () => void | Promise<void>;
shutdown: () => Promise<void>;
};
export type OtlpExporterLikeModule = {
OTLPTraceExporter: new (options: { url?: string }) => unknown;
};
type TracingState = {
sdk: NodeSdkInstance;
};
let activeState: TracingState | undefined;
/**
* Initializes an OpenTelemetry NodeSDK with an OTLP HTTP trace exporter. Both `@opentelemetry/sdk-node`
* and `@opentelemetry/exporter-trace-otlp-http` are loaded via dynamic import so they stay optional
* peer dependencies: when either is missing the helper logs a single warning and becomes a no-op.
*
* Safe to call multiple times — repeated calls after a successful start are ignored.
*/
export async function initializeTracing(options: TracingOptions): Promise<void> {
const onMissing = options.onMissingDependency ?? defaultMissingDependencyLogger;
if (options.enabled === false) {
return;
}
if (activeState) {
return;
}
const endpoint = options.otlpEndpoint ?? readEnv("OTEL_EXPORTER_OTLP_ENDPOINT");
if (!endpoint) {
onMissing("@toolctrl/error-reporter: OTEL_EXPORTER_OTLP_ENDPOINT is not set; tracing skeleton stays disabled.");
return;
}
const sdkLoader = options.loadSdk ?? loadSdkFromNodeModules;
const exporterLoader = options.loadOtlpExporter ?? loadOtlpExporterFromNodeModules;
let sdkModule: NodeSdkLikeModule | undefined;
let exporterModule: OtlpExporterLikeModule | undefined;
try {
sdkModule = await sdkLoader();
} catch {
sdkModule = undefined;
}
try {
exporterModule = await exporterLoader();
} catch {
exporterModule = undefined;
}
if (!sdkModule || !exporterModule) {
onMissing("@toolctrl/error-reporter: @opentelemetry/sdk-node or @opentelemetry/exporter-trace-otlp-http is not installed; tracing skeleton stays disabled.");
return;
}
try {
const traceExporter = new exporterModule.OTLPTraceExporter({ url: endpoint });
const sdk = new sdkModule.NodeSDK({
serviceName: options.serviceName,
traceExporter,
});
await sdk.start();
activeState = { sdk };
} catch (cause) {
onMissing(`@toolctrl/error-reporter: failed to start OpenTelemetry NodeSDK (${describeCause(cause)}); tracing skeleton stays disabled.`);
}
}
export async function shutdownTracing(): Promise<void> {
if (!activeState) {
return;
}
const current = activeState;
activeState = undefined;
try {
await current.sdk.shutdown();
} catch {
// Shutdown failures must not crash the runtime tear-down path.
}
}
async function loadSdkFromNodeModules(): Promise<NodeSdkLikeModule | undefined> {
try {
const moduleName = "@opentelemetry/sdk-node";
const loaded = (await import(/* @vite-ignore */ moduleName)) as NodeSdkLikeModule | { default?: NodeSdkLikeModule };
if (loaded && typeof (loaded as NodeSdkLikeModule).NodeSDK === "function") {
return loaded as NodeSdkLikeModule;
}
if (loaded && typeof (loaded as { default?: NodeSdkLikeModule }).default?.NodeSDK === "function") {
return (loaded as { default: NodeSdkLikeModule }).default;
}
return undefined;
} catch {
return undefined;
}
}
async function loadOtlpExporterFromNodeModules(): Promise<OtlpExporterLikeModule | undefined> {
try {
const moduleName = "@opentelemetry/exporter-trace-otlp-http";
const loaded = (await import(/* @vite-ignore */ moduleName)) as OtlpExporterLikeModule | { default?: OtlpExporterLikeModule };
if (loaded && typeof (loaded as OtlpExporterLikeModule).OTLPTraceExporter === "function") {
return loaded as OtlpExporterLikeModule;
}
if (loaded && typeof (loaded as { default?: OtlpExporterLikeModule }).default?.OTLPTraceExporter === "function") {
return (loaded as { default: OtlpExporterLikeModule }).default;
}
return undefined;
} catch {
return undefined;
}
}
function readEnv(name: string): string | undefined {
const env = typeof process !== "undefined" ? process.env : undefined;
if (!env) {
return undefined;
}
const raw = env[name];
if (!raw || raw.trim().length === 0) {
return undefined;
}
return raw.trim();
}
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);
}