/**
 * High-entropy substring redactor for outbound-channel error bodies.
 *
 * Background (AUDIT-2 #9, 2026-05-24): when a notification channel
 * (webhook / Telegram / PagerDuty / Teams) hits a non-2xx response, the
 * response body is sliced and embedded in the Error message, which the
 * outbox writes to `lastError`. A misconfigured receiver that echoes
 * the request payload back in its error response (common at the
 * "Internal Server Error: <request body>" anti-pattern) could leak
 * high-entropy secret-shaped substrings — e.g. an HMAC signature header
 * value the receiver mirrored — into the audit table.
 *
 * The redactor replaces any base64-ish run of 32+ chars or hex run of
 * 32+ chars with `[REDACTED]`. SHA-256 (64 hex), JWT segments (64+
 * base64url), HMAC sha256 hex (64), AWS access-key-ID secret (40 chars
 * base64) all match. Plain English prose and stack traces do not.
 *
 * Pure function. Tested in `__tests__/redact.test.ts`.
 */

/**
 * 32+ chars of base64 alphabet (incl. +/=). Catches HMAC-sha256-base64
 * (44 chars), JWT body segments, generic API tokens that look base64.
 */
const BASE64_RE = /[A-Za-z0-9+/=_-]{32,}/g;

/**
 * 32+ contiguous hex chars. Catches sha-256 (64), sha-1 (40), md5 (32),
 * HMAC-sha256-hex (64), session-cookie hex, etc.
 */
const HEX_RE = /[A-Fa-f0-9]{32,}/g;

export function redactHighEntropy(input: string): string {
    // Apply hex first so a hex string isn't partially matched by the
    // base64 alphabet (hex chars ⊂ base64 alphabet).
    return input.replace(HEX_RE, '[REDACTED]').replace(BASE64_RE, '[REDACTED]');
}
