lever-ui-logger
Version:
Zero-dependency logging library with optional EventBus integration. Built-in PII redaction, multiple transports, and comprehensive logging capabilities.
367 lines • 11.9 kB
TypeScript
/**
* Comprehensive PII Redaction System
*
* Advanced data protection system that automatically detects and redacts personally
* identifiable information (PII) from log messages, structured data, and function
* arguments. Uses pattern matching, field name detection, and customizable rules.
*
* Features:
* - Built-in patterns for emails, phones, SSN, credit cards, API keys
* - Field name detection (password, email, token, etc.)
* - Configurable redaction modes (balanced, strict, permissive)
* - Custom redaction patterns and functions
* - Hash-based redaction for analytics preservation
* - Performance monitoring and statistics
* - Support for nested objects and arrays
*
* @example
* ```typescript
* import { RedactionEngine, redactString, redactObject } from '@nuanced-labs/lever-ui-logger';
*
* // Global redaction functions
* const safe = redactString('Contact user@example.com for help');
* // Result: "Contact <email> for help"
*
* const safeData = redactObject({
* username: 'john_doe',
* password: 'secret123',
* email: 'john@example.com',
* age: 30
* });
* // Result: { username: '<redacted>', password: '<redacted>', email: '<redacted>', age: 30 }
*
* // Custom redaction engine
* const engine = new RedactionEngine({
* enabled: true,
* mode: 'strict',
* hashRedaction: false,
* customPatterns: [{
* name: 'internal-id',
* pattern: /ID-\d{6}/g,
* replacement: '<internal-id>',
* priority: 100
* }]
* });
*
* const result = engine.redactString('User ID-123456 logged in');
* // Result: "User <internal-id> logged in"
* ```
*/
import type { RedactionConfig } from './types.js';
/**
* Redaction modes with different levels of protection
*/
export type RedactionMode = 'strict' | 'balanced' | 'permissive' | 'off';
/**
* Performance statistics for redaction operations
*/
export interface RedactionStats {
/** Total redaction operations performed */
totalOperations: number;
/** Total time spent on redaction (ms) */
totalTimeMs: number;
/** Average time per operation (ms) */
averageTimeMs: number;
/** Redactions performed by pattern name */
patternHits: Record<string, number>;
/** Field redactions by field name */
fieldHits: Record<string, number>;
}
/**
* Core redaction engine with pattern matching and field detection.
*
* Provides comprehensive PII redaction capabilities including:
* - Pattern-based string redaction (emails, phones, API keys, etc.)
* - Field name detection for sensitive data
* - Configurable redaction modes
* - Performance monitoring and statistics
* - Hash-based redaction for analytics
* - Differential privacy support
*
* @example
* ```typescript
* const engine = new RedactionEngine({
* mode: 'balanced',
* enabled: true,
* disabledPatterns: ['ipv4'] // Keep IP addresses for debugging
* });
*
* // Redact strings
* const safe = engine.redactString('Contact user@example.com for help');
* // Result: 'Contact <email> for help'
*
* // Redact objects
* const safeObj = engine.redactObject({
* username: 'john_doe',
* password: 'secret123',
* email: 'john@example.com'
* });
* // Result: { username: '<redacted>', password: '<redacted>', email: '<redacted>' }
* ```
*/
export declare class RedactionEngine {
private readonly patterns;
private readonly config;
private readonly stats;
private performanceWarningThreshold;
constructor(config?: RedactionConfig);
/**
* Redacts PII from a string value using configured patterns and custom redactor.
*
* @param value - The string to redact PII from
* @returns The string with PII replaced by redaction tokens
*
* @example
* ```typescript
* const engine = new RedactionEngine();
* engine.redactString('Contact user@example.com for help');
* // Returns: 'Contact <email> for help'
*
* engine.redactString('Call us at (555) 123-4567');
* // Returns: 'Call us at <phone>'
* ```
*/
redactString(value: string): string;
/**
* Redacts PII from an object, handling nested structures and circular references.
*
* @param obj - The object to redact PII from
* @param visited - Internal WeakSet for tracking circular references
* @returns The object with PII fields and string values redacted
*
* @example
* ```typescript
* const engine = new RedactionEngine();
* const user = {
* name: 'John Doe',
* email: 'john@example.com',
* password: 'secret123',
* profile: {
* phone: '555-1234',
* bio: 'Contact me at john@example.com'
* }
* };
*
* engine.redactObject(user);
* // Returns: {
* // name: 'John Doe',
* // email: '<redacted>', // Field name detected
* // password: '<redacted>', // Field name detected
* // profile: {
* // phone: '<redacted>', // Field name detected
* // bio: 'Contact me at <email>' // Pattern matched
* // }
* // }
* ```
*/
redactObject(obj: unknown, visited?: WeakSet<object>): unknown;
/**
* Redacts PII from log arguments array, processing each argument as an object.
*
* @param args - Array of log arguments to redact
* @returns Array with PII redacted from each argument
*
* @example
* ```typescript
* const engine = new RedactionEngine();
* const logArgs = [
* 'User logged in',
* { email: 'user@example.com', token: 'abc123' },
* 'Session started at user@example.com'
* ];
*
* engine.redactArgs(logArgs);
* // Returns: [
* // 'User logged in',
* // { email: '<redacted>', token: '<redacted>' },
* // 'Session started at <email>'
* // ]
* ```
*/
redactArgs(args: readonly unknown[]): readonly unknown[];
/**
* Adds Laplace noise to numeric values for differential privacy protection.
*
* @param value - The numeric value to add noise to
* @param epsilon - Privacy budget parameter (default: 1.0, lower = more privacy)
* @returns The value with differential privacy noise added
*
* @example
* ```typescript
* const engine = new RedactionEngine({ differentialPrivacy: true });
*
* // Add noise with default epsilon (1.0)
* const noisyValue = engine.addDifferentialPrivacyNoise(100);
* // Returns: ~99.83 (varies each call)
*
* // More privacy (more noise) with lower epsilon
* const privateValue = engine.addDifferentialPrivacyNoise(100, 0.1);
* // Returns: ~107.42 (varies each call, larger deviation)
* ```
*/
addDifferentialPrivacyNoise(value: number, epsilon?: number): number;
/**
* Gets current redaction statistics including operation counts and performance metrics.
*
* @returns Copy of current redaction statistics
*
* @example
* ```typescript
* const engine = new RedactionEngine();
* engine.redactString('Contact user@example.com');
* engine.redactString('Call (555) 123-4567');
*
* const stats = engine.getStats();
* // Returns: {
* // totalOperations: 2,
* // totalTimeMs: 0.43,
* // averageTimeMs: 0.215,
* // patternHits: { email: 1, 'phone-us': 1 },
* // fieldHits: {}
* // }
* ```
*/
getStats(): RedactionStats;
/**
* Resets redaction statistics to initial values.
*
* @example
* ```typescript
* const engine = new RedactionEngine();
* engine.redactString('user@example.com'); // Creates stats
*
* console.log(engine.getStats().totalOperations); // 1
* engine.resetStats();
* console.log(engine.getStats().totalOperations); // 0
* ```
*/
resetStats(): void;
/**
* Validates potential PII in development mode, checking against all patterns.
*
* @param value - String to validate for potential PII
* @param context - Optional context description for warnings
* @returns Array of warning messages for detected PII patterns
*
* @example
* ```typescript
* const engine = new RedactionEngine();
* const warnings = engine.validateForPII(
* 'Contact user@example.com or call 555-1234',
* 'user input'
* );
*
* // Returns: [
* // 'Potential Email addresses detected in user input: email',
* // 'Potential US phone numbers detected in user input: phone-us'
* // ]
* ```
*/
validateForPII(value: string, context?: string): string[];
/**
* Merges user configuration with defaults
*/
private mergeConfig;
/**
* Initializes redaction patterns based on configuration
*/
private initializePatterns;
/**
* Filters patterns based on redaction mode
*/
private filterPatternsByMode;
/**
* Hash-based redaction for analytics preservation
*/
private hashValue;
/**
* Updates performance statistics
*/
private updateStats;
/**
* Initializes statistics tracking
*/
private initializeStats;
}
/**
* Gets or creates the global redaction engine instance.
*
* @param config - Optional configuration to create new engine with
* @returns Global redaction engine instance
*
* @example
* ```typescript
* // Get default engine
* const engine = getRedactionEngine();
*
* // Create new engine with custom config
* const strictEngine = getRedactionEngine({ mode: 'strict' });
* ```
*/
export declare function getRedactionEngine(config?: RedactionConfig): RedactionEngine;
/**
* Convenience function for redacting strings using the global engine.
*
* @param value - String to redact PII from
* @param config - Optional configuration for custom redaction behavior
* @returns String with PII redacted
*
* @example
* ```typescript
* import { redactString } from '@nuanced-labs/lever-ui-logger';
*
* const safe = redactString('Contact user@example.com for help');
* // Returns: 'Contact <email> for help'
*
* const strictSafe = redactString('Call 555-1234', { mode: 'strict' });
* // Returns: 'Call <phone>'
* ```
*/
export declare function redactString(value: string, config?: RedactionConfig): string;
/**
* Convenience function for redacting objects using the global engine.
*
* @param obj - Object to redact PII from
* @param config - Optional configuration for custom redaction behavior
* @returns Object with PII redacted
*
* @example
* ```typescript
* import { redactObject } from '@nuanced-labs/lever-ui-logger';
*
* const user = { email: 'user@example.com', password: 'secret' };
* const safe = redactObject(user);
* // Returns: { email: '<redacted>', password: '<redacted>' }
*
* const hashRedacted = redactObject(user, { hashRedaction: true });
* // Returns: { email: '<hash:a1b2c3d4>', password: '<hash:e5f6g7h8>' }
* ```
*/
export declare function redactObject(obj: unknown, config?: RedactionConfig): unknown;
/**
* Convenience function for redacting log arguments using the global engine.
*
* @param args - Array of log arguments to redact
* @param config - Optional configuration for custom redaction behavior
* @returns Array with PII redacted from each argument
*
* @example
* ```typescript
* import { redactArgs } from '@nuanced-labs/lever-ui-logger';
*
* const logArgs = [
* 'Login attempt',
* { user: 'john@example.com', ip: '192.168.1.1' },
* 'Session token: abc123xyz'
* ];
*
* const safe = redactArgs(logArgs);
* // Returns: [
* // 'Login attempt',
* // { user: '<redacted>', ip: '192.168.1.1' }, // IP not redacted in balanced mode
* // 'Session token: abc123xyz'
* // ]
* ```
*/
export declare function redactArgs(args: readonly unknown[], config?: RedactionConfig): readonly unknown[];
//# sourceMappingURL=redaction.d.ts.map