"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const vitest_1 = require("vitest");
const errorSanitizer_js_1 = require("./errorSanitizer.js");
(0, vitest_1.describe)('Error Sanitization', () => {
    (0, vitest_1.it)('should redact JWT tokens from error messages', () => {
        const error = new Error('Invalid token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c');
        const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
        (0, vitest_1.expect)(sanitized.message).toBe('Invalid token: [REDACTED]');
        (0, vitest_1.expect)(sanitized.message).not.toContain('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9');
    });
    (0, vitest_1.it)('should redact bearer tokens from error messages', () => {
        const error = new Error('Authentication failed with bearer abc123token456');
        const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
        (0, vitest_1.expect)(sanitized.message).toBe('Authentication failed with bearer [REDACTED]');
    });
    (0, vitest_1.it)('should redact API keys from error messages', () => {
        const error = new Error('API request failed: api_key=sk_live_abc123def456');
        const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
        (0, vitest_1.expect)(sanitized.message).toBe('API request failed: api_key=[REDACTED]');
    });
    (0, vitest_1.it)('should remove sensitive fields from error objects', () => {
        const error = new Error('Test error');
        error.token = 'secret-token-123';
        error.apiKey = 'api-key-456';
        error.password = 'mypassword';
        error.requestData = {
            username: 'john',
            authorization: 'Bearer token123'
        };
        const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
        (0, vitest_1.expect)(sanitized.token).toBe('[REDACTED]');
        (0, vitest_1.expect)(sanitized.apiKey).toBe('[REDACTED]');
        (0, vitest_1.expect)(sanitized.password).toBe('[REDACTED]');
        (0, vitest_1.expect)(sanitized.requestData.username).toBe('john'); // Non-sensitive field preserved
        (0, vitest_1.expect)(sanitized.requestData.authorization).toBe('Bearer [REDACTED]');
    });
    (0, vitest_1.it)('should sanitize stack traces', () => {
        const error = new Error('Test error');
        error.stack = `Error: Invalid token eyJhbGciOiJIUzI1NiI...
    at AuthService.validateToken (/app/src/auth.js:42:15)
    at api_key=sk_live_abc123 (/app/src/api.js:20:10)`;
        const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
        (0, vitest_1.expect)(sanitized.stack).toContain('[REDACTED]');
        (0, vitest_1.expect)(sanitized.stack).not.toContain('eyJhbGciOiJIUzI1NiI');
        (0, vitest_1.expect)(sanitized.stack).not.toContain('sk_live_abc123');
    });
    (0, vitest_1.it)('should preserve error type and non-sensitive properties', () => {
        const error = new TypeError('Invalid token: abc123def456ghi789');
        error.statusCode = 401;
        error.userId = 'user-123';
        const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
        (0, vitest_1.expect)(sanitized.name).toBe('TypeError');
        (0, vitest_1.expect)(sanitized.statusCode).toBe(401);
        (0, vitest_1.expect)(sanitized.userId).toBe('user-123');
        (0, vitest_1.expect)(sanitized.message).toBe('Invalid token: [REDACTED]');
    });
    (0, vitest_1.it)('should handle non-Error objects', () => {
        const errorObj = {
            message: 'Auth failed with token abc123',
            token: 'secret-token',
            data: {
                user: 'john',
                password: 'secret123'
            }
        };
        const sanitized = (0, errorSanitizer_js_1.sanitizeError)(errorObj);
        (0, vitest_1.expect)(sanitized.message).toBe('Auth failed with token [REDACTED]');
        (0, vitest_1.expect)(sanitized.token).toBe('[REDACTED]');
        (0, vitest_1.expect)(sanitized.data.user).toBe('john');
        (0, vitest_1.expect)(sanitized.data.password).toBe('[REDACTED]');
    });
    (0, vitest_1.it)('should not double-sanitize already sanitized errors', () => {
        const error = new Error('Invalid token: eyJhbGciOiJIUzI1NiI...');
        const firstSanitization = (0, errorSanitizer_js_1.sanitizeError)(error);
        const secondSanitization = (0, errorSanitizer_js_1.sanitizeError)(firstSanitization);
        (0, vitest_1.expect)(firstSanitization.message).toBe(secondSanitization.message);
        (0, vitest_1.expect)(firstSanitization._sanitized).toBe(true);
    });
    (0, vitest_1.it)('should handle null and undefined gracefully', () => {
        (0, vitest_1.expect)((0, errorSanitizer_js_1.sanitizeError)(null)).toBe(null);
        (0, vitest_1.expect)((0, errorSanitizer_js_1.sanitizeError)(undefined)).toBe(undefined);
    });
    (0, vitest_1.describe)('Headers Sanitization', () => {
        (0, vitest_1.it)('should sanitize authorization headers while preserving structure', () => {
            const error = new Error('Request failed');
            error.headers = {
                authorization: 'Bearer eyJhbGciOiJIUzI1NiI...',
                'content-type': 'application/json',
                'x-api-key': 'sk_live_abc123'
            };
            const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
            (0, vitest_1.expect)(sanitized.headers.authorization).toBe('Bearer [REDACTED]');
            (0, vitest_1.expect)(sanitized.headers['content-type']).toBe('application/json'); // Non-sensitive preserved
            (0, vitest_1.expect)(sanitized.headers['x-api-key']).toBe('[REDACTED]'); // Contains 'key' -> completely redacted
        });
        (0, vitest_1.it)('should sanitize headers in HTTP request/response objects', () => {
            const error = new Error('HTTP request failed');
            error.request = {
                url: 'https://api.example.com/users',
                method: 'GET',
                headers: {
                    Authorization: 'Bearer token123',
                    Cookie: 'session=abc123; auth_token=xyz789',
                    'User-Agent': 'MyApp/1.0'
                }
            };
            error.response = {
                status: 401,
                headers: {
                    'WWW-Authenticate': 'Bearer realm="api"',
                    'Set-Cookie': 'refresh_token=def456; HttpOnly',
                    'Content-Type': 'application/json'
                }
            };
            const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
            // Request headers
            (0, vitest_1.expect)(sanitized.request.headers.Authorization).toBe('Bearer [REDACTED]');
            (0, vitest_1.expect)(sanitized.request.headers.Cookie).toBe('[REDACTED]'); // Contains 'cookie' -> completely redacted
            (0, vitest_1.expect)(sanitized.request.headers['User-Agent']).toBe('MyApp/1.0');
            // Response headers
            (0, vitest_1.expect)(sanitized.response.headers['WWW-Authenticate']).toBe('[REDACTED]'); // Contains 'bearer' pattern -> redacted
            (0, vitest_1.expect)(sanitized.response.headers['Set-Cookie']).toBe('[REDACTED]'); // Contains 'cookie' -> completely redacted
            (0, vitest_1.expect)(sanitized.response.headers['Content-Type']).toBe('application/json');
        });
        (0, vitest_1.it)('should handle case-insensitive header names', () => {
            const error = new Error('Request failed');
            error.Headers = {
                // Capital H - this field name doesn't contain sensitive keywords
                AUTHORIZATION: 'Bearer token123',
                authorization: 'Basic user:pass',
                'X-API-KEY': 'secret-key'
            };
            const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
            // Headers (capital H) is not in VALUE_SANITIZED_FIELDS, so individual fields get processed normally
            // But Basic auth pattern still applies for string value sanitization
            (0, vitest_1.expect)(sanitized.Headers.AUTHORIZATION).toBe('Bearer [REDACTED]'); // Pattern matching on string value
            (0, vitest_1.expect)(sanitized.Headers.authorization).toBe('Basic [REDACTED]'); // Basic auth pattern applies
            (0, vitest_1.expect)(sanitized.Headers['X-API-KEY']).toBe('[REDACTED]'); // Contains 'key' -> completely redacted
        });
        (0, vitest_1.it)('should sanitize headers with various token formats', () => {
            const errorObj = {
                message: 'Authentication failed',
                headers: {
                    authorization: 'JWT eyJhbGciOiJIUzI1NiI...',
                    'x-auth-token': 'Bearer abc123def456',
                    'api-key': 'sk_test_1234567890',
                    cookie: 'sessionId=sess_abc123; csrfToken=csrf_xyz789',
                    'x-forwarded-for': '192.168.1.1' // Should be preserved
                }
            };
            const sanitized = (0, errorSanitizer_js_1.sanitizeError)(errorObj);
            (0, vitest_1.expect)(sanitized.headers.authorization).toBe('JWT [REDACTED]');
            (0, vitest_1.expect)(sanitized.headers['x-auth-token']).toBe('[REDACTED]'); // Contains 'auth' -> completely redacted
            (0, vitest_1.expect)(sanitized.headers['api-key']).toBe('[REDACTED]'); // Contains 'key' -> completely redacted
            (0, vitest_1.expect)(sanitized.headers.cookie).toBe('[REDACTED]'); // Contains 'cookie' -> completely redacted
            (0, vitest_1.expect)(sanitized.headers['x-forwarded-for']).toBe('192.168.1.1');
        });
        (0, vitest_1.it)('should handle nested headers in complex objects', () => {
            const error = new Error('Network error');
            error.requestConfig = {
                baseURL: 'https://api.example.com',
                timeout: 5000,
                headers: {
                    Authorization: 'Bearer eyJhbGciOiJIUzI1NiI...',
                    'Content-Type': 'application/json'
                },
                data: {
                    username: 'john',
                    password: 'secret123'
                }
            };
            const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
            (0, vitest_1.expect)(sanitized.requestConfig.baseURL).toBe('https://api.example.com');
            (0, vitest_1.expect)(sanitized.requestConfig.timeout).toBe(5000);
            (0, vitest_1.expect)(sanitized.requestConfig.headers.Authorization).toBe('Bearer [REDACTED]');
            (0, vitest_1.expect)(sanitized.requestConfig.headers['Content-Type']).toBe('application/json');
            (0, vitest_1.expect)(sanitized.requestConfig.data.username).toBe('john');
            (0, vitest_1.expect)(sanitized.requestConfig.data.password).toBe('[REDACTED]');
        });
        (0, vitest_1.it)('should handle headers as strings vs objects', () => {
            const error = new Error('Invalid headers');
            error.headers = 'Authorization: Bearer token123\r\nContent-Type: application/json';
            error.requestHeaders = {
                authorization: 'Basic dXNlcjpwYXNz', // base64 encoded user:pass
                'user-agent': 'MyApp/1.0'
            };
            const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
            // String headers get pattern-based sanitization (Bearer preserves prefix)
            (0, vitest_1.expect)(sanitized.headers).toBe('Authorization: Bearer [REDACTED]\r\nContent-Type: application/json');
            // Any field named 'authorization' should be value-sanitized regardless of parent object name
            (0, vitest_1.expect)(sanitized.requestHeaders.authorization).toBe('Basic [REDACTED]');
            (0, vitest_1.expect)(sanitized.requestHeaders['user-agent']).toBe('MyApp/1.0');
        });
        (0, vitest_1.it)('should redact GitHub tokens', () => {
            const errorObj = {
                message: 'GitHub API failed',
                personalToken: 'ghp_1234567890abcdef1234567890abcdef12345678',
                appToken: 'ghs_abcdef1234567890abcdef1234567890abcdef12',
                finegrainedToken: 'github_pat_11ABCDEFG0001234567890_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
                config: {
                    auth: 'token ghp_1234567890abcdef1234567890abcdef12345678'
                }
            };
            const sanitized = (0, errorSanitizer_js_1.sanitizeError)(errorObj);
            (0, vitest_1.expect)(sanitized.personalToken).toBe('[REDACTED]');
            (0, vitest_1.expect)(sanitized.appToken).toBe('[REDACTED]');
            (0, vitest_1.expect)(sanitized.finegrainedToken).toBe('[REDACTED]');
            (0, vitest_1.expect)(sanitized.config.auth).toBe('[REDACTED]'); // "token <value>" pattern matches the whole thing
        });
        (0, vitest_1.it)('should handle mixed secrets in complex error objects', () => {
            const error = new Error('Multiple services failed');
            error.aws = {
                accessKeyId: 'AKIAIOSFODNN7EXAMPLE',
                secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
                sessionToken: 'aws_session_token_12345abcdef'
            };
            error.github = {
                token: 'ghp_1234567890abcdef1234567890abcdef12345678'
            };
            error.nonSensitive = {
                userId: 'user123',
                timestamp: '2023-01-01T00:00:00Z'
            };
            const sanitized = (0, errorSanitizer_js_1.sanitizeError)(error);
            // AWS credentials should be redacted
            (0, vitest_1.expect)(sanitized.aws.accessKeyId).toBe('[REDACTED]');
            (0, vitest_1.expect)(sanitized.aws.secretAccessKey).toBe('[REDACTED]');
            (0, vitest_1.expect)(sanitized.aws.sessionToken).toBe('[REDACTED]');
            // GitHub token should be redacted
            (0, vitest_1.expect)(sanitized.github.token).toBe('[REDACTED]');
            // Non-sensitive data should be preserved
            (0, vitest_1.expect)(sanitized.nonSensitive.userId).toBe('user123');
            (0, vitest_1.expect)(sanitized.nonSensitive.timestamp).toBe('2023-01-01T00:00:00Z');
        });
    });
});
//# sourceMappingURL=errorSanitizer.test.js.map