33 lines
1.1 KiB
TypeScript
33 lines
1.1 KiB
TypeScript
const SENSITIVE_KEY_PATTERN = /authorization|cookie|password|secret|token|api[-_]?key|payload|body|header/i;
|
|
|
|
export function redactDiagnosticText(value: string): string {
|
|
return value
|
|
.replace(/(authorization)\s*=\s*Bearer\s+\S+/gi, "$1=Bearer [REDACTED]")
|
|
.replace(/Bearer\s+\S+/gi, "Bearer [REDACTED]")
|
|
.replace(/(password|secret|token|api[-_]?key)=\S+/gi, "$1=[REDACTED]");
|
|
}
|
|
|
|
export function redactDiagnosticJsonString(value: string | null | undefined): string {
|
|
if (!value) {
|
|
return "";
|
|
}
|
|
|
|
try {
|
|
return JSON.stringify(redactDiagnosticValue(JSON.parse(value)), null, 2);
|
|
} catch {
|
|
return redactDiagnosticText(value);
|
|
}
|
|
}
|
|
|
|
function redactDiagnosticValue(value: unknown): unknown {
|
|
if (Array.isArray(value)) {
|
|
return value.map(redactDiagnosticValue);
|
|
}
|
|
if (value && typeof value === "object") {
|
|
return Object.fromEntries(
|
|
Object.entries(value as Record<string, unknown>).map(([key, entry]) => [key, SENSITIVE_KEY_PATTERN.test(key) ? "[REDACTED]" : redactDiagnosticValue(entry)]),
|
|
);
|
|
}
|
|
return typeof value === "string" ? redactDiagnosticText(value) : value;
|
|
}
|