import { redactHighEntropy } from '../redact';

describe('redactHighEntropy (AUDIT-2 #9)', () => {
    it('passes plain English prose through unchanged', () => {
        const s = 'Internal server error: unable to reach upstream service';
        expect(redactHighEntropy(s)).toBe(s);
    });

    it('redacts a sha256 hex digest', () => {
        const sha256 = 'a'.repeat(64);
        const out = redactHighEntropy(`signature mismatch: got ${sha256}`);
        expect(out).toBe('signature mismatch: got [REDACTED]');
    });

    it('redacts a base64 HMAC value', () => {
        // 44 chars, mixed case + digits — looks like HMAC-sha256 base64
        const hmac = 'oXY3Lwq8aB2cD3eF4gH5iJ6kL7mN8oP9qR0sT1uV2wY=';
        const out = redactHighEntropy(`X-Sentinel-Signature mismatch: ${hmac}`);
        expect(out).toBe('X-Sentinel-Signature mismatch: [REDACTED]');
    });

    it('redacts JWT body + signature segments (long enough to look base64)', () => {
        const jwtBody = 'eyJzdWIiOiIxMjM0NSIsIm5hbWUiOiJKb2huIERvZSIsImlhdCI6MTUxNjIzOTAyMn0';
        const out = redactHighEntropy(`token rejected: ${jwtBody}`);
        expect(out).toContain('[REDACTED]');
        expect(out).not.toContain(jwtBody);
    });

    it('redacts multiple high-entropy substrings in the same string', () => {
        const a = 'a'.repeat(40);
        const b = 'b'.repeat(40);
        const out = redactHighEntropy(`first ${a} second ${b}`);
        expect(out).toBe('first [REDACTED] second [REDACTED]');
    });

    it('does not redact short hex strings (< 32 chars)', () => {
        const s = 'error code abc123: short hex is fine';
        expect(redactHighEntropy(s)).toBe(s);
    });

    it('does not redact short alphanumeric strings', () => {
        const s = 'requestId=req_8a3b9c1d2e';
        expect(redactHighEntropy(s)).toBe(s);
    });

    // AUDIT-2 #9 (2026-05-24): the motivating scenario — receiver echoes
    // the X-Sentinel-Signature header back in its error response, the
    // channel wraps that in Error.message, the outbox writes it to
    // lastError. Verify the signature value is gone before it can land
    // in the DB.
    it('redacts a 64-char hex HMAC echoed by a misconfigured receiver', () => {
        const sig = 'b'.repeat(64);
        const body = `{"error":"invalid signature","received":"sha256=${sig}"}`;
        const out = redactHighEntropy(body);
        expect(out).not.toContain(sig);
        expect(out).toContain('[REDACTED]');
    });

    it('preserves status code + short text around the redaction', () => {
        const secret = 'A'.repeat(32);
        const out = redactHighEntropy(`Bearer ${secret} rejected (401 Unauthorized)`);
        expect(out).toContain('rejected (401 Unauthorized)');
        expect(out).not.toContain(secret);
    });
});
