|
| 1 | +import Re2 from 're2'; |
| 2 | +import { DataFormatHandlers } from './shared'; |
| 3 | +import { RedactionConfig } from './types'; |
| 4 | +import { defaultRedactionConfigs } from './shared/default-decay.config'; |
| 5 | +import yaml from 'js-yaml'; |
| 6 | +import fs from 'fs'; |
| 7 | + |
| 8 | +process.removeAllListeners('warning'); |
| 9 | + |
| 10 | +interface YamlConfig { |
| 11 | + patterns: RedactionConfig; |
| 12 | + cache: { |
| 13 | + size: number; |
| 14 | + }; |
| 15 | +} |
| 16 | + |
| 17 | +export class Decay { |
| 18 | + private readonly configs: RedactionConfig; |
| 19 | + private readonly formatHandlers: DataFormatHandlers; |
| 20 | + private readonly compiledPatterns: Map<string, Re2>; |
| 21 | + private readonly cache: Map<string, string>; |
| 22 | + private readonly cacheSize: number; |
| 23 | + |
| 24 | + /** |
| 25 | + * Create a new Decay instance from YAML config file or default config |
| 26 | + * @param configPath Optional path to YAML config file |
| 27 | + */ |
| 28 | + constructor(configPath?: string) { |
| 29 | + const config = this.loadConfig(configPath); |
| 30 | + this.configs = config.patterns; |
| 31 | + this.formatHandlers = new DataFormatHandlers(); |
| 32 | + this.compiledPatterns = this.compilePatterns(); |
| 33 | + this.cache = new Map(); |
| 34 | + this.cacheSize = config.cache?.size || 1000; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Load configuration from YAML file or use defaults |
| 39 | + */ |
| 40 | + private loadConfig(configPath?: string): YamlConfig { |
| 41 | + if (!configPath) { |
| 42 | + return { |
| 43 | + patterns: defaultRedactionConfigs, |
| 44 | + cache: { size: 1000 } |
| 45 | + }; |
| 46 | + } |
| 47 | + |
| 48 | + try { |
| 49 | + const fileContents = fs.readFileSync(configPath, 'utf8'); |
| 50 | + const config = yaml.load(fileContents) as YamlConfig; |
| 51 | + |
| 52 | + // Validate the loaded config |
| 53 | + if (!config.patterns || typeof config.patterns !== 'object') { |
| 54 | + throw new Error('Invalid config: missing or invalid patterns section'); |
| 55 | + } |
| 56 | + |
| 57 | + // Validate each pattern |
| 58 | + for (const [key, value] of Object.entries(config.patterns)) { |
| 59 | + if (!value.pattern || !value.replacement) { |
| 60 | + throw new Error(`Invalid config for pattern ${key}: missing pattern or replacement`); |
| 61 | + } |
| 62 | + |
| 63 | + // Validate pattern can be compiled |
| 64 | + try { |
| 65 | + new Re2(value.pattern); |
| 66 | + } catch (error: any) { |
| 67 | + throw new Error(`Invalid regex pattern for ${key}: ${error.message}`); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return config; |
| 72 | + } catch (error) { |
| 73 | + console.error('Error loading config:', error); |
| 74 | + console.warn('Falling back to default configuration'); |
| 75 | + return { |
| 76 | + patterns: defaultRedactionConfigs, |
| 77 | + cache: { size: 1000 } |
| 78 | + }; |
| 79 | + } |
| 80 | + } |
| 81 | + /** |
| 82 | + * Compiles patterns using RE2 with optimization flags |
| 83 | + */ |
| 84 | + private compilePatterns(): Map<string, Re2> { |
| 85 | + const compiled = new Map(); |
| 86 | + for (const [key, config] of Object.entries(this.configs)) { |
| 87 | + try { |
| 88 | + // Use RE2 optimization flags |
| 89 | + compiled.set(key, new Re2(config.pattern)); |
| 90 | + } catch (error) { |
| 91 | + console.error(`Failed to compile pattern for ${key}:`, error); |
| 92 | + } |
| 93 | + } |
| 94 | + return compiled; |
| 95 | + } |
| 96 | + |
| 97 | + /** |
| 98 | + * Generates cache key for input data |
| 99 | + */ |
| 100 | + private generateCacheKey(data: any): string { |
| 101 | + if (typeof data === 'string') { |
| 102 | + return data; |
| 103 | + } |
| 104 | + try { |
| 105 | + return JSON.stringify(data); |
| 106 | + } catch { |
| 107 | + return String(data); |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + /** |
| 112 | + * Main redaction function with caching |
| 113 | + */ |
| 114 | + public redact(data: any): any { |
| 115 | + const cacheKey = this.generateCacheKey(data); |
| 116 | + |
| 117 | + // Check cache first |
| 118 | + const cached = this.cache.get(cacheKey); |
| 119 | + if (cached) { |
| 120 | + return this.intelligentParse(cached, 'string'); |
| 121 | + } |
| 122 | + |
| 123 | + try { |
| 124 | + const { stringified, format } = this.intelligentStringify(data); |
| 125 | + const redacted = this.redactSensitiveData(stringified); |
| 126 | + |
| 127 | + // Cache the result |
| 128 | + if (this.cache.size >= this.cacheSize) { |
| 129 | + const firstKey = this.cache.keys().next().value; |
| 130 | + if(firstKey) this.cache.delete(firstKey); |
| 131 | + } |
| 132 | + this.cache.set(cacheKey, redacted); |
| 133 | + |
| 134 | + return this.intelligentParse(redacted, format); |
| 135 | + } catch (error) { |
| 136 | + console.error('Error during redaction:', error); |
| 137 | + const fallback = this.redactSensitiveData(String(data)); |
| 138 | + return fallback; |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + /** |
| 143 | + * Optimized redaction using compiled RE2 patterns |
| 144 | + */ |
| 145 | + private redactSensitiveData(text: string): string { |
| 146 | + let redactedText = text; |
| 147 | + |
| 148 | + // Sort patterns by length for better matching |
| 149 | + const sortedPatterns = Array.from(this.compiledPatterns.entries()) |
| 150 | + .sort(([, a], [, b]) => b.toString().length - a.toString().length); |
| 151 | + |
| 152 | + for (const [key, pattern] of sortedPatterns) { |
| 153 | + const replacement = this.configs[key].replacement; |
| 154 | + try { |
| 155 | + redactedText = redactedText.replace(pattern, replacement); |
| 156 | + } catch (error) { |
| 157 | + console.warn(`Pattern ${key} failed:`, error); |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + return redactedText; |
| 162 | + } |
| 163 | + |
| 164 | + /** |
| 165 | + * Enhanced string conversion with format detection |
| 166 | + */ |
| 167 | + private intelligentStringify(data: any): { stringified: string; format: string } { |
| 168 | + if (typeof data === 'string') { |
| 169 | + const format = this.formatHandlers.detectFormat(data); |
| 170 | + return { stringified: data, format }; |
| 171 | + } |
| 172 | + |
| 173 | + const jsonString = JSON.stringify(data, null, 2); |
| 174 | + return { stringified: jsonString, format: 'json' }; |
| 175 | + } |
| 176 | + |
| 177 | + /** |
| 178 | + * Intelligent parsing based on detected format |
| 179 | + */ |
| 180 | + private intelligentParse(text: string, format: string): any { |
| 181 | + const handler = this.formatHandlers.getHandler(format); |
| 182 | + if (handler) { |
| 183 | + try { |
| 184 | + return handler.parse(text); |
| 185 | + } catch (error) { |
| 186 | + console.warn(`Failed to parse as ${format}, falling back to string`); |
| 187 | + } |
| 188 | + } |
| 189 | + return text; |
| 190 | + } |
| 191 | + |
| 192 | +} |
| 193 | + |
| 194 | +// Performance test suite |
| 195 | +function runPerformanceTest(redactor: Decay) { |
| 196 | + const testCases = { |
| 197 | + simple: "Email: test@example.com", |
| 198 | + complex: { |
| 199 | + users: Array(1000).fill(null).map((_, i) => ({ |
| 200 | + id: i, |
| 201 | + email: `user${i}@example.com`, |
| 202 | + password: `secret${i}`, |
| 203 | + ssn: "123-45-6789", |
| 204 | + creditCard: "4111-1111-1111-1111", |
| 205 | + address: "123 Main St, New York, NY 12345", |
| 206 | + })) |
| 207 | + }, |
| 208 | + nested: { |
| 209 | + level1: { |
| 210 | + level2: { |
| 211 | + level3: { |
| 212 | + data: Array(100).fill({ |
| 213 | + apiKey: "sk_test_123456789", |
| 214 | + jwt: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U" |
| 215 | + }) |
| 216 | + } |
| 217 | + } |
| 218 | + } |
| 219 | + } |
| 220 | + }; |
| 221 | + |
| 222 | + console.time('Initial redaction'); |
| 223 | + redactor.redact(testCases.complex); |
| 224 | + console.timeEnd('Initial redaction'); |
| 225 | + |
| 226 | + console.time('Cached redaction'); |
| 227 | + redactor.redact(testCases.complex); |
| 228 | + console.timeEnd('Cached redaction'); |
| 229 | + |
| 230 | + console.time('Nested redaction'); |
| 231 | + redactor.redact(testCases.nested); |
| 232 | + console.timeEnd('Nested redaction'); |
| 233 | +} |
| 234 | + |
| 235 | +export const decay = (config?: string)=> new Decay(config); |
0 commit comments