openredaction 1.0.8 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3932 @@
1
+ import { NextFunction, Request, Response } from "express";
2
+
3
+ //#region src/types.d.ts
4
+ /**
5
+ * Core types for PII Shield
6
+ */
7
+ /**
8
+ * PII pattern definition with validation
9
+ */
10
+ interface PIIPattern {
11
+ /** Pattern type identifier (e.g., "EMAIL", "PHONE_UK_MOBILE") */
12
+ type: string;
13
+ /** Regular expression for matching */
14
+ regex: RegExp;
15
+ /** Priority for detection order (higher = checked first) */
16
+ priority: number;
17
+ /** Optional validator function for false positive reduction */
18
+ validator?: (match: string, context: string) => boolean;
19
+ /** Placeholder template (e.g., "[EMAIL_{n}]") */
20
+ placeholder: string;
21
+ /** Optional description */
22
+ description?: string;
23
+ /** Severity level */
24
+ severity?: 'critical' | 'high' | 'medium' | 'low';
25
+ }
26
+ /**
27
+ * Detected PII instance
28
+ */
29
+ interface PIIDetection {
30
+ /** Type of PII detected */
31
+ type: string;
32
+ /** Original detected value */
33
+ value: string;
34
+ /** Placeholder used for redaction */
35
+ placeholder: string;
36
+ /** Position in text [start, end] */
37
+ position: [number, number];
38
+ /** Severity level */
39
+ severity: 'critical' | 'high' | 'medium' | 'low';
40
+ /** Confidence score (0-1) based on context analysis */
41
+ confidence?: number;
42
+ }
43
+ /**
44
+ * PII match (used internally for processing)
45
+ */
46
+ interface PIIMatch {
47
+ /** Type of PII */
48
+ type: string;
49
+ /** Matched value */
50
+ value: string;
51
+ /** Start position */
52
+ start: number;
53
+ /** End position */
54
+ end: number;
55
+ /** Confidence score (0-1) */
56
+ confidence: number;
57
+ /** Context around match */
58
+ context: {
59
+ before: string;
60
+ after: string;
61
+ };
62
+ }
63
+ /**
64
+ * Detection result
65
+ */
66
+ interface DetectionResult {
67
+ /** Original text */
68
+ original: string;
69
+ /** Redacted text */
70
+ redacted: string;
71
+ /** Array of detections */
72
+ detections: PIIDetection[];
73
+ /** Map of placeholders to original values for restoration */
74
+ redactionMap: Record<string, string>;
75
+ /** Statistics */
76
+ stats?: {
77
+ /** Processing time in milliseconds */processingTime?: number; /** Total PII count */
78
+ piiCount: number;
79
+ };
80
+ }
81
+ /**
82
+ * Redaction mode - controls how PII is replaced
83
+ */
84
+ type RedactionMode = 'placeholder' | 'mask-middle' | 'mask-all' | 'format-preserving' | 'token-replace';
85
+ /**
86
+ * Configuration options for OpenRedaction
87
+ */
88
+ type PresetName = 'gdpr' | 'hipaa' | 'ccpa' | 'healthcare' | 'healthcare-provider' | 'healthcare-research' | 'finance' | 'financial-services' | 'education' | 'transport-logistics' | 'transportation' | 'logistics';
89
+ interface OpenRedactionOptions {
90
+ /** Include name detection (default: true) */
91
+ includeNames?: boolean;
92
+ /** Include address detection (default: true) */
93
+ includeAddresses?: boolean;
94
+ /** Include phone detection (default: true) */
95
+ includePhones?: boolean;
96
+ /** Include email detection (default: true) */
97
+ includeEmails?: boolean;
98
+ /** Pattern categories to include (e.g., ['personal', 'financial']) */
99
+ categories?: string[];
100
+ /** Whitelist specific patterns only */
101
+ patterns?: string[];
102
+ /** Add custom patterns */
103
+ customPatterns?: PIIPattern[];
104
+ /** Whitelist of terms to ignore (e.g., company names) */
105
+ whitelist?: string[];
106
+ /** Enable deterministic placeholders (default: true) */
107
+ deterministic?: boolean;
108
+ /** Redaction mode (default: 'placeholder') */
109
+ redactionMode?: RedactionMode;
110
+ /** Compliance preset */
111
+ preset?: PresetName;
112
+ /** Enable context-aware detection (default: true) */
113
+ enableContextAnalysis?: boolean;
114
+ /** Minimum confidence threshold for detections (0-1, default: 0.5) */
115
+ confidenceThreshold?: number;
116
+ /** Enable false positive filtering (default: false, experimental) */
117
+ enableFalsePositiveFilter?: boolean;
118
+ /** False positive confidence threshold (0-1, default: 0.7) */
119
+ falsePositiveThreshold?: number;
120
+ /** Enable multi-pass detection for better accuracy (default: false, experimental) */
121
+ enableMultiPass?: boolean;
122
+ /** Number of detection passes (2-5, default: 3) */
123
+ multiPassCount?: number;
124
+ /** Enable result caching for repeated inputs (default: false) */
125
+ enableCache?: boolean;
126
+ /** Maximum cache size (default: 100) */
127
+ cacheSize?: number;
128
+ /** Enable debug logging (default: false) */
129
+ debug?: boolean;
130
+ /** Enable audit logging (default: false) */
131
+ enableAuditLog?: boolean;
132
+ /** Audit logger instance (optional, default: in-memory logger) */
133
+ auditLogger?: IAuditLogger;
134
+ /** User context for audit logs */
135
+ auditUser?: string;
136
+ /** Session ID for audit logs */
137
+ auditSessionId?: string;
138
+ /** Additional metadata for audit logs */
139
+ auditMetadata?: Record<string, unknown>;
140
+ /** Enable metrics collection (default: false) */
141
+ enableMetrics?: boolean;
142
+ /** Metrics collector instance (optional, default: in-memory collector) */
143
+ metricsCollector?: IMetricsCollector;
144
+ /** Enable RBAC (Role-Based Access Control) (default: false) */
145
+ enableRBAC?: boolean;
146
+ /** RBAC manager instance (optional, default: admin role) */
147
+ rbacManager?: IRBACManager;
148
+ /** Predefined role name (admin, analyst, operator, viewer) */
149
+ role?: RoleName;
150
+ /** Optional AI assist configuration */
151
+ ai?: AIOptions;
152
+ }
153
+ /**
154
+ * AI assist configuration options
155
+ */
156
+ interface AIOptions {
157
+ /** Enable AI assist mode (default: false) */
158
+ enabled?: boolean;
159
+ /** AI endpoint URL (defaults to OPENREDACTION_AI_ENDPOINT env var if available) */
160
+ endpoint?: string;
161
+ }
162
+ /**
163
+ * Validator function type
164
+ */
165
+ type Validator = (value: string, context?: string) => boolean;
166
+ /**
167
+ * Audit log entry for tracking redaction operations
168
+ */
169
+ interface AuditLogEntry {
170
+ /** Unique identifier for this audit entry */
171
+ id: string;
172
+ /** Timestamp of the operation (ISO 8601) */
173
+ timestamp: string;
174
+ /** Operation type */
175
+ operation: 'redact' | 'detect' | 'restore';
176
+ /** Number of PII items found/processed */
177
+ piiCount: number;
178
+ /** Types of PII detected (e.g., ["EMAIL", "SSN", "PHONE"]) */
179
+ piiTypes: string[];
180
+ /** Text length processed */
181
+ textLength: number;
182
+ /** Processing time in milliseconds */
183
+ processingTimeMs: number;
184
+ /** Redaction mode used */
185
+ redactionMode?: RedactionMode;
186
+ /** Success status */
187
+ success: boolean;
188
+ /** Error message if operation failed */
189
+ error?: string;
190
+ /** Optional user context */
191
+ user?: string;
192
+ /** Optional session/request identifier */
193
+ sessionId?: string;
194
+ /** Optional metadata */
195
+ metadata?: Record<string, unknown>;
196
+ }
197
+ /**
198
+ * Audit logger interface
199
+ */
200
+ interface IAuditLogger {
201
+ /** Log an audit entry */
202
+ log(entry: Omit<AuditLogEntry, 'id' | 'timestamp'>): void;
203
+ /** Get all audit logs */
204
+ getLogs(): AuditLogEntry[];
205
+ /** Get audit logs filtered by operation type */
206
+ getLogsByOperation(operation: AuditLogEntry['operation']): AuditLogEntry[];
207
+ /** Get audit logs filtered by date range */
208
+ getLogsByDateRange(startDate: Date, endDate: Date): AuditLogEntry[];
209
+ /** Export audit logs as JSON */
210
+ exportAsJson(): string;
211
+ /** Export audit logs as CSV */
212
+ exportAsCsv(): string;
213
+ /** Clear all audit logs */
214
+ clear(): void;
215
+ /** Get audit statistics */
216
+ getStats(): AuditStats;
217
+ }
218
+ /**
219
+ * Audit statistics
220
+ */
221
+ interface AuditStats {
222
+ /** Total number of operations */
223
+ totalOperations: number;
224
+ /** Total PII items detected */
225
+ totalPiiDetected: number;
226
+ /** Average processing time in milliseconds */
227
+ averageProcessingTime: number;
228
+ /** Most common PII types */
229
+ topPiiTypes: Array<{
230
+ type: string;
231
+ count: number;
232
+ }>;
233
+ /** Operations by type */
234
+ operationsByType: Record<string, number>;
235
+ /** Success rate (0-1) */
236
+ successRate: number;
237
+ }
238
+ /**
239
+ * Metrics for monitoring redaction operations
240
+ */
241
+ interface RedactionMetrics {
242
+ /** Total number of redaction operations */
243
+ totalRedactions: number;
244
+ /** Total number of PII items detected */
245
+ totalPiiDetected: number;
246
+ /** Total processing time in milliseconds */
247
+ totalProcessingTime: number;
248
+ /** Average processing time in milliseconds */
249
+ averageProcessingTime: number;
250
+ /** Total text length processed (characters) */
251
+ totalTextLength: number;
252
+ /** PII detection counts by type */
253
+ piiByType: Record<string, number>;
254
+ /** Operation counts by redaction mode */
255
+ byRedactionMode: Record<string, number>;
256
+ /** Error count */
257
+ totalErrors: number;
258
+ /** Timestamp of last update */
259
+ lastUpdated: string;
260
+ }
261
+ /**
262
+ * Metrics exporter interface
263
+ */
264
+ interface IMetricsExporter {
265
+ /** Export metrics in Prometheus format */
266
+ exportPrometheus(metrics: RedactionMetrics, prefix?: string): string;
267
+ /** Export metrics in StatsD format */
268
+ exportStatsD(metrics: RedactionMetrics, prefix?: string): string[];
269
+ /** Get current metrics snapshot */
270
+ getMetrics(): RedactionMetrics;
271
+ /** Reset all metrics */
272
+ reset(): void;
273
+ }
274
+ /**
275
+ * Metrics collector interface
276
+ */
277
+ interface IMetricsCollector {
278
+ /** Record a redaction operation */
279
+ recordRedaction(result: DetectionResult, processingTimeMs: number, redactionMode: RedactionMode): void;
280
+ /** Record an error */
281
+ recordError(): void;
282
+ /** Get metrics exporter */
283
+ getExporter(): IMetricsExporter;
284
+ }
285
+ /**
286
+ * RBAC Permission - granular access control
287
+ */
288
+ type Permission = 'pattern:read' | 'pattern:write' | 'pattern:delete' | 'detection:detect' | 'detection:redact' | 'detection:restore' | 'audit:read' | 'audit:export' | 'audit:delete' | 'metrics:read' | 'metrics:export' | 'metrics:reset' | 'config:read' | 'config:write';
289
+ /**
290
+ * RBAC Role - collection of permissions
291
+ */
292
+ interface Role {
293
+ /** Role identifier */
294
+ name: string;
295
+ /** Role description */
296
+ description?: string;
297
+ /** Permissions granted to this role */
298
+ permissions: Permission[];
299
+ }
300
+ /**
301
+ * Predefined role names
302
+ */
303
+ type RoleName = 'admin' | 'analyst' | 'operator' | 'viewer' | 'custom';
304
+ /**
305
+ * RBAC manager interface for access control
306
+ */
307
+ interface IRBACManager {
308
+ /** Check if user has specific permission */
309
+ hasPermission(permission: Permission): boolean;
310
+ /** Check if user has all specified permissions */
311
+ hasAllPermissions(permissions: Permission[]): boolean;
312
+ /** Check if user has any of the specified permissions */
313
+ hasAnyPermission(permissions: Permission[]): boolean;
314
+ /** Get current role */
315
+ getRole(): Role;
316
+ /** Set role */
317
+ setRole(role: Role): void;
318
+ /** Get all permissions for current role */
319
+ getPermissions(): Permission[];
320
+ /** Filter patterns based on read permissions */
321
+ filterPatterns(patterns: PIIPattern[]): PIIPattern[];
322
+ }
323
+ //#endregion
324
+ //#region src/document/types.d.ts
325
+ /**
326
+ * Supported document formats
327
+ */
328
+ type DocumentFormat = 'pdf' | 'docx' | 'txt' | 'image' | 'json' | 'csv' | 'xlsx';
329
+ /**
330
+ * Supported image formats for OCR
331
+ */
332
+ type ImageFormat = 'png' | 'jpg' | 'jpeg' | 'tiff' | 'bmp' | 'webp';
333
+ /**
334
+ * OCR language codes (Tesseract format)
335
+ */
336
+ type OCRLanguage = 'eng' | 'spa' | 'fra' | 'deu' | 'por' | 'ita' | 'rus' | 'chi_sim' | 'chi_tra' | 'jpn' | 'kor';
337
+ /**
338
+ * OCR options
339
+ */
340
+ interface OCROptions {
341
+ /** OCR language (default: 'eng' for English) */
342
+ language?: OCRLanguage | OCRLanguage[];
343
+ /** OCR engine mode (0-3, default: 3 for best accuracy) */
344
+ oem?: 0 | 1 | 2 | 3;
345
+ /** Page segmentation mode (0-13, default: 3 for automatic) */
346
+ psm?: number;
347
+ }
348
+ /**
349
+ * Document processing options
350
+ */
351
+ interface DocumentOptions {
352
+ /** Document format (auto-detected if not specified) */
353
+ format?: DocumentFormat;
354
+ /** Extract text from specific pages (PDF only, 1-indexed) */
355
+ pages?: number[];
356
+ /** Password for encrypted PDFs */
357
+ password?: string;
358
+ /** Maximum document size in bytes (default: 50MB) */
359
+ maxSize?: number;
360
+ /** Enable OCR for image-based content (default: false) */
361
+ enableOCR?: boolean;
362
+ /** OCR configuration options */
363
+ ocrOptions?: OCROptions;
364
+ }
365
+ /**
366
+ * Document processing result
367
+ */
368
+ interface DocumentResult {
369
+ /** Extracted text from document */
370
+ text: string;
371
+ /** Document metadata */
372
+ metadata: DocumentMetadata;
373
+ /** Detection result with PII findings */
374
+ detection: DetectionResult;
375
+ /** Original file size in bytes */
376
+ fileSize: number;
377
+ /** Text extraction time in milliseconds */
378
+ extractionTime: number;
379
+ }
380
+ /**
381
+ * Document metadata
382
+ */
383
+ interface DocumentMetadata {
384
+ /** Document format */
385
+ format: DocumentFormat;
386
+ /** Number of pages (if applicable) */
387
+ pages?: number;
388
+ /** Document title */
389
+ title?: string;
390
+ /** Document author */
391
+ author?: string;
392
+ /** Creation date */
393
+ creationDate?: Date;
394
+ /** Last modified date */
395
+ modifiedDate?: Date;
396
+ /** OCR confidence (0-100) if OCR was used */
397
+ ocrConfidence?: number;
398
+ /** Whether OCR was used for extraction */
399
+ usedOCR?: boolean;
400
+ /** Additional custom metadata */
401
+ custom?: Record<string, unknown>;
402
+ }
403
+ /**
404
+ * OCR processor interface
405
+ */
406
+ interface IOCRProcessor {
407
+ /** Extract text from image buffer using OCR */
408
+ recognizeText(buffer: Buffer, options?: OCROptions): Promise<OCRResult>;
409
+ /** Check if OCR is available (tesseract.js installed) */
410
+ isAvailable(): boolean;
411
+ }
412
+ /**
413
+ * OCR recognition result
414
+ */
415
+ interface OCRResult {
416
+ /** Recognized text */
417
+ text: string;
418
+ /** Confidence score (0-100) */
419
+ confidence: number;
420
+ /** Processing time in milliseconds */
421
+ processingTime: number;
422
+ }
423
+ /**
424
+ * Document processor interface
425
+ */
426
+ interface IDocumentProcessor {
427
+ /** Extract text from document buffer */
428
+ extractText(buffer: Buffer, options?: DocumentOptions): Promise<string>;
429
+ /** Get document metadata */
430
+ getMetadata(buffer: Buffer, options?: DocumentOptions): Promise<DocumentMetadata>;
431
+ /** Detect supported format from buffer */
432
+ detectFormat(buffer: Buffer): DocumentFormat | null;
433
+ /** Check if format is supported */
434
+ isFormatSupported(format: DocumentFormat): boolean;
435
+ }
436
+ //#endregion
437
+ //#region src/learning/LocalLearningStore.d.ts
438
+ interface WhitelistEntry {
439
+ pattern: string;
440
+ confidence: number;
441
+ occurrences: number;
442
+ firstSeen: number;
443
+ lastSeen: number;
444
+ contexts: string[];
445
+ }
446
+ interface PatternAdjustment {
447
+ type: string;
448
+ issue: string;
449
+ suggestion: string;
450
+ confidence: number;
451
+ examples: string[];
452
+ occurrences: number;
453
+ }
454
+ interface LearningStats {
455
+ totalDetections: number;
456
+ falsePositives: number;
457
+ falseNegatives: number;
458
+ accuracy: number;
459
+ lastUpdated: number;
460
+ }
461
+ interface LearningData {
462
+ version: string;
463
+ whitelist: WhitelistEntry[];
464
+ patternAdjustments: PatternAdjustment[];
465
+ stats: LearningStats;
466
+ }
467
+ declare class LocalLearningStore {
468
+ private filePath;
469
+ private data;
470
+ private autoSave;
471
+ private confidenceThreshold;
472
+ constructor(filePath?: string, options?: {
473
+ autoSave?: boolean;
474
+ confidenceThreshold?: number;
475
+ });
476
+ /**
477
+ * Load learning data from file
478
+ */
479
+ private load;
480
+ /**
481
+ * Save learning data to file
482
+ */
483
+ private save;
484
+ /**
485
+ * Record a false positive detection
486
+ */
487
+ recordFalsePositive(text: string, _type: string, context: string): void;
488
+ /**
489
+ * Record a false negative (missed detection)
490
+ */
491
+ recordFalseNegative(text: string, type: string, _context: string): void;
492
+ /**
493
+ * Record a correct detection
494
+ */
495
+ recordCorrectDetection(): void;
496
+ /**
497
+ * Update accuracy calculation
498
+ */
499
+ private updateAccuracy;
500
+ /**
501
+ * Get whitelist entries above confidence threshold
502
+ */
503
+ getWhitelist(): string[];
504
+ /**
505
+ * Get all whitelist entries with metadata
506
+ */
507
+ getWhitelistEntries(): WhitelistEntry[];
508
+ /**
509
+ * Get pattern adjustments above confidence threshold
510
+ */
511
+ getPatternAdjustments(): PatternAdjustment[];
512
+ /**
513
+ * Get all pattern adjustments
514
+ */
515
+ getAllPatternAdjustments(): PatternAdjustment[];
516
+ /**
517
+ * Get learning statistics
518
+ */
519
+ getStats(): LearningStats;
520
+ /**
521
+ * Get confidence score for a specific pattern
522
+ */
523
+ getConfidence(pattern: string): number;
524
+ /**
525
+ * Get occurrences count for a specific pattern
526
+ */
527
+ getOccurrences(pattern: string): number;
528
+ /**
529
+ * Manually add pattern to whitelist
530
+ */
531
+ addToWhitelist(pattern: string, confidence?: number): void;
532
+ /**
533
+ * Remove pattern from whitelist
534
+ */
535
+ removeFromWhitelist(pattern: string): void;
536
+ /**
537
+ * Clear all learning data
538
+ */
539
+ clear(): void;
540
+ /**
541
+ * Export learning data (for sharing)
542
+ */
543
+ export(options?: {
544
+ includeContexts?: boolean;
545
+ minConfidence?: number;
546
+ }): LearningData;
547
+ /**
548
+ * Import learning data (merge with existing)
549
+ */
550
+ import(data: LearningData, merge?: boolean): void;
551
+ /**
552
+ * Manually save data
553
+ */
554
+ flush(): void;
555
+ }
556
+ //#endregion
557
+ //#region src/context/ContextRules.d.ts
558
+ /**
559
+ * Proximity rule for context-based confidence adjustment
560
+ */
561
+ interface ProximityRule {
562
+ /** Pattern type this rule applies to (e.g., 'EMAIL', 'PHONE', 'SSN') */
563
+ patternType: string | string[];
564
+ /** Keywords to look for near the match */
565
+ keywords: string[];
566
+ /** Maximum word distance from match (default: 10) */
567
+ proximityWindow?: number;
568
+ /** Confidence boost if keyword found (0-1) */
569
+ confidenceBoost?: number;
570
+ /** Confidence penalty if keyword found (0-1) */
571
+ confidencePenalty?: number;
572
+ /** Whether match must come AFTER keyword (default: both directions) */
573
+ keywordBefore?: boolean;
574
+ /** Whether match must come BEFORE keyword (default: both directions) */
575
+ keywordAfter?: boolean;
576
+ /** Rule description */
577
+ description?: string;
578
+ }
579
+ /**
580
+ * Domain-specific vocabulary for context detection
581
+ */
582
+ interface DomainVocabulary {
583
+ /** Domain name */
584
+ domain: 'medical' | 'legal' | 'financial' | 'technical' | 'hr' | 'custom';
585
+ /** Domain-specific terms */
586
+ terms: string[];
587
+ /** Pattern types to boost in this domain */
588
+ boostPatterns?: string[];
589
+ /** Confidence boost amount (default: 0.15) */
590
+ boostAmount?: number;
591
+ }
592
+ /**
593
+ * Contextual rules configuration
594
+ */
595
+ interface ContextRulesConfig {
596
+ /** Proximity rules */
597
+ proximityRules?: ProximityRule[];
598
+ /** Domain vocabularies */
599
+ domainVocabularies?: DomainVocabulary[];
600
+ /** Enable default rules (default: true) */
601
+ useDefaultRules?: boolean;
602
+ }
603
+ /**
604
+ * Default proximity rules for common PII patterns
605
+ */
606
+ declare const DEFAULT_PROXIMITY_RULES: ProximityRule[];
607
+ /**
608
+ * Default domain vocabularies
609
+ */
610
+ declare const DEFAULT_DOMAIN_VOCABULARIES: DomainVocabulary[];
611
+ /**
612
+ * Contextual Rules Engine
613
+ */
614
+ declare class ContextRulesEngine {
615
+ private proximityRules;
616
+ private domainVocabularies;
617
+ constructor(config?: ContextRulesConfig);
618
+ /**
619
+ * Apply proximity rules to adjust confidence
620
+ */
621
+ applyProximityRules(match: PIIMatch, text: string): PIIMatch;
622
+ /**
623
+ * Apply domain vocabulary boosting
624
+ */
625
+ applyDomainBoosting(matches: PIIMatch[], text: string): PIIMatch[];
626
+ /**
627
+ * Check if keywords are within proximity window
628
+ */
629
+ private checkProximity;
630
+ /**
631
+ * Detect which domains the text belongs to
632
+ */
633
+ private detectDomains;
634
+ /**
635
+ * Add custom proximity rule
636
+ */
637
+ addProximityRule(rule: ProximityRule): void;
638
+ /**
639
+ * Add custom domain vocabulary
640
+ */
641
+ addDomainVocabulary(vocabulary: DomainVocabulary): void;
642
+ /**
643
+ * Get all proximity rules
644
+ */
645
+ getProximityRules(): ProximityRule[];
646
+ /**
647
+ * Get all domain vocabularies
648
+ */
649
+ getDomainVocabularies(): DomainVocabulary[];
650
+ }
651
+ /**
652
+ * Create a context rules engine instance
653
+ */
654
+ declare function createContextRulesEngine(config?: ContextRulesConfig): ContextRulesEngine;
655
+ //#endregion
656
+ //#region src/context/ContextAnalyzer.d.ts
657
+ /**
658
+ * Context Analysis for PII Detection
659
+ * Provides NLP-lite features to reduce false positives
660
+ */
661
+ interface ContextAnalysis {
662
+ /** 5 words before detection */
663
+ beforeWords: string[];
664
+ /** 5 words after detection */
665
+ afterWords: string[];
666
+ /** Full sentence containing detection */
667
+ sentence: string;
668
+ /** Inferred document type */
669
+ documentType: 'email' | 'document' | 'code' | 'chat' | 'unknown';
670
+ /** Confidence that this is actual PII (0-1) */
671
+ confidence: number;
672
+ }
673
+ interface ContextFeatures {
674
+ /** Contains technical terms */
675
+ hasTechnicalContext: boolean;
676
+ /** Contains business/corporate terms */
677
+ hasBusinessContext: boolean;
678
+ /** Contains medical/healthcare terms */
679
+ hasMedicalContext: boolean;
680
+ /** Contains financial terms */
681
+ hasFinancialContext: boolean;
682
+ /** Contains example/test indicators */
683
+ hasExampleContext: boolean;
684
+ /** Position in document (0-1, 0 = start, 1 = end) */
685
+ relativePosition: number;
686
+ }
687
+ /**
688
+ * Extract context around a detection
689
+ */
690
+ declare function extractContext(text: string, startPos: number, endPos: number, wordsBefore?: number, wordsAfter?: number): {
691
+ before: string;
692
+ after: string;
693
+ beforeWords: string[];
694
+ afterWords: string[];
695
+ sentence: string;
696
+ };
697
+ /**
698
+ * Infer document type from content
699
+ */
700
+ declare function inferDocumentType(text: string): ContextAnalysis['documentType'];
701
+ /**
702
+ * Extract context features for classification
703
+ */
704
+ declare function analyzeContextFeatures(fullContext: string): ContextFeatures;
705
+ /**
706
+ * Calculate confidence score for a detection based on context
707
+ */
708
+ declare function calculateContextConfidence(_value: string, patternType: string, context: {
709
+ before: string;
710
+ after: string;
711
+ sentence: string;
712
+ documentType: ContextAnalysis['documentType'];
713
+ features: ContextFeatures;
714
+ }): number;
715
+ /**
716
+ * Perform full context analysis
717
+ */
718
+ declare function analyzeFullContext(text: string, value: string, patternType: string, startPos: number, endPos: number): ContextAnalysis;
719
+ //#endregion
720
+ //#region src/explain/ExplainAPI.d.ts
721
+ /**
722
+ * Pattern match result for explain
723
+ */
724
+ interface PatternMatchResult {
725
+ /** Pattern that was tested */
726
+ pattern: PIIPattern;
727
+ /** Whether the pattern matched */
728
+ matched: boolean;
729
+ /** Matched value (if matched) */
730
+ matchedValue?: string;
731
+ /** Position of match (if matched) */
732
+ position?: [number, number];
733
+ /** Why it didn't match or was filtered */
734
+ reason?: string;
735
+ /** Validator result (if validator exists) */
736
+ validatorPassed?: boolean;
737
+ /** Context analysis (if enabled) */
738
+ contextAnalysis?: ContextAnalysis;
739
+ /** False positive check (if enabled) */
740
+ falsePositiveCheck?: {
741
+ isFalsePositive: boolean;
742
+ confidence: number;
743
+ reason?: string;
744
+ };
745
+ }
746
+ /**
747
+ * Explanation for a specific text
748
+ */
749
+ interface TextExplanation {
750
+ /** Original text */
751
+ text: string;
752
+ /** All pattern match results */
753
+ patternResults: PatternMatchResult[];
754
+ /** Patterns that matched */
755
+ matchedPatterns: PatternMatchResult[];
756
+ /** Patterns that didn't match */
757
+ unmatchedPatterns: PatternMatchResult[];
758
+ /** Patterns that matched but were filtered */
759
+ filteredPatterns: PatternMatchResult[];
760
+ /** Final detections */
761
+ detections: PIIDetection[];
762
+ /** Summary statistics */
763
+ summary: {
764
+ totalPatternsChecked: number;
765
+ patternsMatched: number;
766
+ patternsFiltered: number;
767
+ finalDetections: number;
768
+ };
769
+ }
770
+ /**
771
+ * Explain API for debugging
772
+ */
773
+ declare class ExplainAPI {
774
+ private detector;
775
+ private patterns;
776
+ private options;
777
+ constructor(detector: OpenRedaction);
778
+ /**
779
+ * Explain why text was or wasn't detected as PII
780
+ */
781
+ explain(text: string): Promise<TextExplanation>;
782
+ /**
783
+ * Explain a specific detection
784
+ */
785
+ explainDetection(detection: PIIDetection, text: string): Promise<{
786
+ detection: PIIDetection;
787
+ pattern?: PIIPattern;
788
+ contextAnalysis?: ContextAnalysis;
789
+ reasoning: string[];
790
+ suggestions: string[];
791
+ }>;
792
+ /**
793
+ * Suggest why text wasn't detected
794
+ */
795
+ suggestWhy(text: string, expectedType: string): Promise<{
796
+ text: string;
797
+ expectedType: string;
798
+ suggestions: string[];
799
+ similarPatterns: PIIPattern[];
800
+ }>;
801
+ /**
802
+ * Get debugging information for entire detection process
803
+ */
804
+ debug(text: string): Promise<{
805
+ text: string;
806
+ textLength: number;
807
+ enabledFeatures: string[];
808
+ patternCount: number;
809
+ explanation: TextExplanation;
810
+ performance: {
811
+ estimatedTime: string;
812
+ };
813
+ }>;
814
+ }
815
+ /**
816
+ * Helper to create explain API from detector
817
+ */
818
+ declare function createExplainAPI(detector: OpenRedaction): ExplainAPI;
819
+ //#endregion
820
+ //#region src/reports/ReportGenerator.d.ts
821
+ /**
822
+ * Report format options
823
+ */
824
+ type ReportFormat = 'html' | 'markdown';
825
+ /**
826
+ * Report type options
827
+ */
828
+ type ReportType = 'summary' | 'detailed' | 'compliance';
829
+ /**
830
+ * Report generation options
831
+ */
832
+ interface ReportOptions {
833
+ /** Report format */
834
+ format: ReportFormat;
835
+ /** Report type */
836
+ type?: ReportType;
837
+ /** Report title */
838
+ title?: string;
839
+ /** Include original text (default: false for privacy) */
840
+ includeOriginalText?: boolean;
841
+ /** Include redacted text (default: true) */
842
+ includeRedactedText?: boolean;
843
+ /** Include detection details (default: true) */
844
+ includeDetectionDetails?: boolean;
845
+ /** Include statistics (default: true) */
846
+ includeStatistics?: boolean;
847
+ /** Include explanation (requires ExplainAPI, default: false) */
848
+ includeExplanation?: boolean;
849
+ /** Company/project name for compliance reports */
850
+ organizationName?: string;
851
+ /** Additional metadata */
852
+ metadata?: Record<string, string>;
853
+ }
854
+ /**
855
+ * Report generator for PII detection results
856
+ */
857
+ declare class ReportGenerator {
858
+ constructor(_detector: OpenRedaction);
859
+ /**
860
+ * Generate a report from detection results
861
+ */
862
+ generate(result: DetectionResult, options: ReportOptions): string;
863
+ /**
864
+ * Generate HTML report
865
+ */
866
+ private generateHTML;
867
+ /**
868
+ * Generate Markdown report
869
+ */
870
+ private generateMarkdown;
871
+ /**
872
+ * Calculate statistics from detection results
873
+ */
874
+ private calculateStatistics;
875
+ /**
876
+ * Escape HTML special characters
877
+ */
878
+ private escapeHtml;
879
+ }
880
+ /**
881
+ * Helper to create report generator
882
+ */
883
+ declare function createReportGenerator(detector: OpenRedaction): ReportGenerator;
884
+ //#endregion
885
+ //#region src/optimizer/PriorityOptimizer.d.ts
886
+ interface PatternStats {
887
+ type: string;
888
+ totalDetections: number;
889
+ falsePositives: number;
890
+ falseNegatives: number;
891
+ accuracy: number;
892
+ priority: number;
893
+ adjustedPriority: number;
894
+ }
895
+ interface OptimizerOptions {
896
+ learningWeight: number;
897
+ minSampleSize: number;
898
+ maxPriorityAdjustment: number;
899
+ }
900
+ /**
901
+ * Priority Optimizer - Dynamically adjusts pattern priorities based on learning data
902
+ */
903
+ declare class PriorityOptimizer {
904
+ private learningStore;
905
+ private options;
906
+ constructor(learningStore: LocalLearningStore, options?: Partial<OptimizerOptions>);
907
+ /**
908
+ * Optimize pattern priorities based on learning data
909
+ */
910
+ optimizePatterns(patterns: PIIPattern[]): PIIPattern[];
911
+ /**
912
+ * Get pattern statistics with learning data
913
+ */
914
+ getPatternStats(patterns: PIIPattern[]): PatternStats[];
915
+ /**
916
+ * Infer pattern type from a whitelisted value
917
+ * This is a heuristic - in production we'd track this explicitly
918
+ */
919
+ private inferPatternType;
920
+ /**
921
+ * Reset all priority adjustments
922
+ */
923
+ resetPriorities(patterns: PIIPattern[]): PIIPattern[];
924
+ /**
925
+ * Get optimizer configuration
926
+ */
927
+ getOptions(): OptimizerOptions;
928
+ /**
929
+ * Update optimizer configuration
930
+ */
931
+ setOptions(options: Partial<OptimizerOptions>): void;
932
+ }
933
+ /**
934
+ * Create a priority optimizer instance
935
+ */
936
+ declare function createPriorityOptimizer(learningStore: LocalLearningStore, options?: Partial<OptimizerOptions>): PriorityOptimizer;
937
+ //#endregion
938
+ //#region src/detector.d.ts
939
+ declare class OpenRedaction {
940
+ private patterns;
941
+ private compiledPatterns;
942
+ private options;
943
+ private multiPassConfig?;
944
+ private resultCache?;
945
+ private valueToPlaceholder;
946
+ private placeholderCounter;
947
+ private learningStore?;
948
+ private priorityOptimizer?;
949
+ private enableLearning;
950
+ private auditLogger?;
951
+ private auditUser?;
952
+ private auditSessionId?;
953
+ private auditMetadata?;
954
+ private metricsCollector?;
955
+ private rbacManager?;
956
+ private nerDetector?;
957
+ private contextRulesEngine?;
958
+ private severityClassifier;
959
+ constructor(options?: OpenRedactionOptions & {
960
+ configPath?: string;
961
+ enableLearning?: boolean;
962
+ learningStorePath?: string;
963
+ enablePriorityOptimization?: boolean;
964
+ optimizerOptions?: Partial<OptimizerOptions>;
965
+ enableNER?: boolean;
966
+ enableContextRules?: boolean;
967
+ contextRulesConfig?: ContextRulesConfig;
968
+ maxInputSize?: number;
969
+ regexTimeout?: number;
970
+ });
971
+ /**
972
+ * Create OpenRedaction instance from config file
973
+ */
974
+ static fromConfig(configPath?: string): Promise<OpenRedaction>;
975
+ /**
976
+ * Build the list of patterns based on options
977
+ * Supports three filtering modes (in order of priority):
978
+ * 1. Specific pattern types (patterns option)
979
+ * 2. Pattern categories (categories option) - NEW!
980
+ * 3. All patterns with type-specific filters (includeNames, etc.)
981
+ */
982
+ private buildPatternList;
983
+ /**
984
+ * Validate all patterns to prevent malicious regex injection
985
+ * ONLY validates custom patterns - built-in patterns are already vetted
986
+ * Timeout protection in safeExec() is the primary defense against ReDoS
987
+ */
988
+ private validatePatterns;
989
+ /**
990
+ * Pre-compile all regex patterns for performance
991
+ * Avoids creating new RegExp objects on every detect() call
992
+ */
993
+ private precompilePatterns;
994
+ /**
995
+ * Process patterns and detect PII
996
+ * Used by both single-pass and multi-pass detection
997
+ */
998
+ private processPatterns;
999
+ /**
1000
+ * Detect PII in text
1001
+ * Now async to support optional AI assist
1002
+ */
1003
+ detect(text: string): Promise<DetectionResult>;
1004
+ /**
1005
+ * Restore redacted text using redaction map
1006
+ */
1007
+ restore(redactedText: string, redactionMap: Record<string, string>): string;
1008
+ /**
1009
+ * Generate placeholder for a detected value
1010
+ */
1011
+ private generatePlaceholder;
1012
+ /**
1013
+ * Check if a range overlaps with existing detections
1014
+ */
1015
+ private overlapsWithExisting;
1016
+ /**
1017
+ * Escape special regex characters
1018
+ */
1019
+ private escapeRegex;
1020
+ /**
1021
+ * Get the list of active patterns
1022
+ */
1023
+ getPatterns(): PIIPattern[];
1024
+ /**
1025
+ * Get severity-based scan results
1026
+ */
1027
+ scan(text: string): Promise<{
1028
+ high: PIIDetection[];
1029
+ medium: PIIDetection[];
1030
+ low: PIIDetection[];
1031
+ total: number;
1032
+ }>;
1033
+ /**
1034
+ * Record a false positive (incorrectly detected as PII)
1035
+ */
1036
+ recordFalsePositive(detection: PIIDetection, context?: string): void;
1037
+ /**
1038
+ * Record a false negative (missed PII that should have been detected)
1039
+ */
1040
+ recordFalseNegative(text: string, expectedType: string, context?: string): void;
1041
+ /**
1042
+ * Record a correct detection (for accuracy tracking)
1043
+ */
1044
+ recordCorrectDetection(): void;
1045
+ /**
1046
+ * Get learning statistics
1047
+ */
1048
+ getLearningStats(): LearningStats | null;
1049
+ /**
1050
+ * Get learned whitelist entries
1051
+ */
1052
+ getLearnedWhitelist(): WhitelistEntry[];
1053
+ /**
1054
+ * Get pattern adjustment suggestions
1055
+ */
1056
+ getPatternAdjustments(): PatternAdjustment[];
1057
+ /**
1058
+ * Export learned patterns for sharing
1059
+ */
1060
+ exportLearnings(options?: {
1061
+ includeContexts?: boolean;
1062
+ minConfidence?: number;
1063
+ }): LearningData | null;
1064
+ /**
1065
+ * Import learned patterns from another source
1066
+ */
1067
+ importLearnings(data: any, merge?: boolean): void;
1068
+ /**
1069
+ * Manually add a term to the whitelist
1070
+ */
1071
+ addToWhitelist(pattern: string, confidence?: number): void;
1072
+ /**
1073
+ * Remove a term from the whitelist
1074
+ */
1075
+ removeFromWhitelist(pattern: string): void;
1076
+ /**
1077
+ * Get the learning store instance
1078
+ */
1079
+ getLearningStore(): LocalLearningStore | undefined;
1080
+ /**
1081
+ * Get the priority optimizer instance
1082
+ */
1083
+ getPriorityOptimizer(): PriorityOptimizer | undefined;
1084
+ /**
1085
+ * Optimize pattern priorities based on learning data
1086
+ * Call this to re-optimize priorities after accumulating new learning data
1087
+ */
1088
+ optimizePriorities(): void;
1089
+ /**
1090
+ * Get pattern statistics with learning data
1091
+ */
1092
+ getPatternStats(): PatternStats[] | null;
1093
+ /**
1094
+ * Clear the result cache (if caching is enabled)
1095
+ */
1096
+ clearCache(): void;
1097
+ /**
1098
+ * Get cache statistics
1099
+ */
1100
+ getCacheStats(): {
1101
+ size: number;
1102
+ maxSize: number;
1103
+ enabled: boolean;
1104
+ };
1105
+ /**
1106
+ * Get the audit logger instance (if audit logging is enabled)
1107
+ */
1108
+ getAuditLogger(): IAuditLogger | undefined;
1109
+ /**
1110
+ * Get the metrics collector instance (if metrics collection is enabled)
1111
+ */
1112
+ getMetricsCollector(): IMetricsCollector | undefined;
1113
+ /**
1114
+ * Get the RBAC manager instance (if RBAC is enabled)
1115
+ */
1116
+ getRBACManager(): IRBACManager | undefined;
1117
+ /**
1118
+ * Create an explain API for debugging detections
1119
+ */
1120
+ explain(): ExplainAPI;
1121
+ /**
1122
+ * Generate a report from detection results
1123
+ */
1124
+ generateReport(result: DetectionResult, options: ReportOptions): string;
1125
+ /**
1126
+ * Export current configuration
1127
+ */
1128
+ exportConfig(metadata?: {
1129
+ description?: string;
1130
+ author?: string;
1131
+ tags?: string[];
1132
+ }): string;
1133
+ /**
1134
+ * Run health check
1135
+ */
1136
+ healthCheck(options?: {
1137
+ testDetection?: boolean;
1138
+ checkPerformance?: boolean;
1139
+ performanceThreshold?: number;
1140
+ memoryThreshold?: number;
1141
+ }): Promise<any>;
1142
+ /**
1143
+ * Quick health check (minimal overhead)
1144
+ */
1145
+ quickHealthCheck(): Promise<{
1146
+ status: 'healthy' | 'unhealthy';
1147
+ message: string;
1148
+ }>;
1149
+ /**
1150
+ * Detect PII in a document (PDF, DOCX, TXT)
1151
+ * Requires optional peer dependencies:
1152
+ * - pdf-parse for PDF support
1153
+ * - mammoth for DOCX support
1154
+ */
1155
+ detectDocument(buffer: Buffer, options?: DocumentOptions): Promise<DocumentResult>;
1156
+ /**
1157
+ * Detect PII in a document file from filesystem
1158
+ * Convenience method that reads file and calls detectDocument
1159
+ */
1160
+ detectDocumentFile(filePath: string, options?: DocumentOptions): Promise<DocumentResult>;
1161
+ /**
1162
+ * Batch detect PII in multiple texts using worker threads (parallel)
1163
+ * Significantly faster for processing many texts
1164
+ */
1165
+ static detectBatch(texts: string[], options?: OpenRedactionOptions & {
1166
+ numWorkers?: number;
1167
+ }): Promise<DetectionResult[]>;
1168
+ /**
1169
+ * Batch process multiple documents using worker threads (parallel)
1170
+ * Efficient for processing many documents at once
1171
+ */
1172
+ static detectDocumentsBatch(buffers: Buffer[], options?: DocumentOptions & {
1173
+ numWorkers?: number;
1174
+ }): Promise<DocumentResult[]>;
1175
+ }
1176
+ //#endregion
1177
+ //#region src/audit/AuditLogger.d.ts
1178
+ /**
1179
+ * In-memory audit logger implementation
1180
+ * Stores audit logs in memory with support for filtering, export, and statistics
1181
+ */
1182
+ declare class InMemoryAuditLogger implements IAuditLogger {
1183
+ private logs;
1184
+ private maxLogs;
1185
+ constructor(maxLogs?: number);
1186
+ /**
1187
+ * Log an audit entry
1188
+ */
1189
+ log(entry: Omit<AuditLogEntry, 'id' | 'timestamp'>): void;
1190
+ /**
1191
+ * Get all audit logs
1192
+ */
1193
+ getLogs(): AuditLogEntry[];
1194
+ /**
1195
+ * Get audit logs filtered by operation type
1196
+ */
1197
+ getLogsByOperation(operation: AuditLogEntry['operation']): AuditLogEntry[];
1198
+ /**
1199
+ * Get audit logs filtered by date range
1200
+ */
1201
+ getLogsByDateRange(startDate: Date, endDate: Date): AuditLogEntry[];
1202
+ /**
1203
+ * Export audit logs as JSON
1204
+ */
1205
+ exportAsJson(): string;
1206
+ /**
1207
+ * Export audit logs as CSV
1208
+ */
1209
+ exportAsCsv(): string;
1210
+ /**
1211
+ * Clear all audit logs
1212
+ */
1213
+ clear(): void;
1214
+ /**
1215
+ * Get audit statistics
1216
+ */
1217
+ getStats(): AuditStats;
1218
+ /**
1219
+ * Generate a unique ID for audit entries
1220
+ */
1221
+ private generateId;
1222
+ /**
1223
+ * Escape CSV values
1224
+ */
1225
+ private escapeCsv;
1226
+ }
1227
+ /**
1228
+ * Console audit logger implementation
1229
+ * Outputs audit logs to console (useful for debugging)
1230
+ */
1231
+ declare class ConsoleAuditLogger implements IAuditLogger {
1232
+ private delegate;
1233
+ constructor(maxLogs?: number);
1234
+ log(entry: Omit<AuditLogEntry, 'id' | 'timestamp'>): void;
1235
+ getLogs(): AuditLogEntry[];
1236
+ getLogsByOperation(operation: AuditLogEntry['operation']): AuditLogEntry[];
1237
+ getLogsByDateRange(startDate: Date, endDate: Date): AuditLogEntry[];
1238
+ exportAsJson(): string;
1239
+ exportAsCsv(): string;
1240
+ clear(): void;
1241
+ getStats(): AuditStats;
1242
+ }
1243
+ //#endregion
1244
+ //#region src/audit/PersistentAuditLogger.d.ts
1245
+ /**
1246
+ * Supported database backends
1247
+ */
1248
+ type AuditBackend = 'sqlite' | 'postgresql' | 'mongodb' | 's3' | 'file';
1249
+ /**
1250
+ * Database connection configuration
1251
+ */
1252
+ interface AuditDatabaseConfig {
1253
+ /** Backend type */
1254
+ backend: AuditBackend;
1255
+ /** Connection string (for PostgreSQL/MongoDB) */
1256
+ connectionString?: string;
1257
+ /** Database file path (for SQLite/file backend) */
1258
+ filePath?: string;
1259
+ /** S3 bucket configuration */
1260
+ s3Config?: {
1261
+ bucket: string;
1262
+ region: string;
1263
+ accessKeyId?: string;
1264
+ secretAccessKey?: string;
1265
+ prefix?: string;
1266
+ };
1267
+ /** Table/collection name (default: 'audit_logs') */
1268
+ tableName?: string;
1269
+ /** Enable compression (default: false) */
1270
+ enableCompression?: boolean;
1271
+ /** Batch size for bulk inserts (default: 100) */
1272
+ batchSize?: number;
1273
+ }
1274
+ /**
1275
+ * Retention policy configuration
1276
+ */
1277
+ interface RetentionPolicy {
1278
+ /** Maximum age of logs in days (default: 90) */
1279
+ maxAgeDays?: number;
1280
+ /** Maximum number of logs to keep (default: unlimited) */
1281
+ maxLogs?: number;
1282
+ /** Enable automatic cleanup (default: false) */
1283
+ autoCleanup?: boolean;
1284
+ /** Cleanup interval in hours (default: 24) */
1285
+ cleanupIntervalHours?: number;
1286
+ }
1287
+ /**
1288
+ * Persistent audit logger options
1289
+ */
1290
+ interface PersistentAuditLoggerOptions {
1291
+ /** Database configuration */
1292
+ database: AuditDatabaseConfig;
1293
+ /** Retention policy */
1294
+ retention?: RetentionPolicy;
1295
+ /** Enable cryptographic hashing for tamper detection (default: true) */
1296
+ enableHashing?: boolean;
1297
+ /** Hash algorithm (default: 'sha256') */
1298
+ hashAlgorithm?: 'sha256' | 'sha512';
1299
+ /** Enable write-ahead logging for crash recovery (default: true) */
1300
+ enableWAL?: boolean;
1301
+ /** Secret key for HMAC hashing (optional, recommended for production) */
1302
+ secretKey?: string;
1303
+ }
1304
+ /**
1305
+ * Audit log entry with cryptographic hash
1306
+ */
1307
+ interface HashedAuditLogEntry extends AuditLogEntry {
1308
+ /** Cryptographic hash of this entry */
1309
+ hash: string;
1310
+ /** Hash of previous entry for chain verification */
1311
+ previousHash?: string;
1312
+ /** Sequence number in the log chain */
1313
+ sequence: number;
1314
+ }
1315
+ /**
1316
+ * Audit database adapter interface
1317
+ */
1318
+ interface IAuditDatabaseAdapter {
1319
+ /** Initialize the database/table/collection */
1320
+ initialize(): Promise<void>;
1321
+ /** Insert a single log entry */
1322
+ insert(entry: HashedAuditLogEntry): Promise<void>;
1323
+ /** Batch insert multiple entries */
1324
+ batchInsert(entries: HashedAuditLogEntry[]): Promise<void>;
1325
+ /** Query logs with filters */
1326
+ query(filter: AuditQueryFilter): Promise<HashedAuditLogEntry[]>;
1327
+ /** Get total count of logs */
1328
+ count(filter?: Partial<AuditQueryFilter>): Promise<number>;
1329
+ /** Delete logs older than date */
1330
+ deleteOlderThan(date: Date): Promise<number>;
1331
+ /** Get the last log entry */
1332
+ getLastEntry(): Promise<HashedAuditLogEntry | null>;
1333
+ /** Verify log chain integrity */
1334
+ verifyChain(startSequence?: number, endSequence?: number): Promise<{
1335
+ valid: boolean;
1336
+ brokenAt?: number;
1337
+ }>;
1338
+ /** Close connection */
1339
+ close(): Promise<void>;
1340
+ }
1341
+ /**
1342
+ * Audit query filter
1343
+ */
1344
+ interface AuditQueryFilter {
1345
+ /** Filter by operation type */
1346
+ operation?: AuditLogEntry['operation'];
1347
+ /** Filter by user */
1348
+ user?: string;
1349
+ /** Filter by session ID */
1350
+ sessionId?: string;
1351
+ /** Filter by date range (start) */
1352
+ startDate?: Date;
1353
+ /** Filter by date range (end) */
1354
+ endDate?: Date;
1355
+ /** Filter by success status */
1356
+ success?: boolean;
1357
+ /** Limit results */
1358
+ limit?: number;
1359
+ /** Offset for pagination */
1360
+ offset?: number;
1361
+ /** Sort order */
1362
+ sort?: 'asc' | 'desc';
1363
+ }
1364
+ /**
1365
+ * Persistent Audit Logger with cryptographic chain verification
1366
+ */
1367
+ declare class PersistentAuditLogger implements IAuditLogger {
1368
+ private adapter;
1369
+ private options;
1370
+ private batchBuffer;
1371
+ private lastHash;
1372
+ private sequence;
1373
+ private cleanupTimer?;
1374
+ private initialized;
1375
+ constructor(options: PersistentAuditLoggerOptions);
1376
+ /**
1377
+ * Initialize the logger (must be called before use)
1378
+ */
1379
+ initialize(): Promise<void>;
1380
+ /**
1381
+ * Log an audit entry
1382
+ */
1383
+ log(entry: Omit<AuditLogEntry, 'id' | 'timestamp'>): void;
1384
+ /**
1385
+ * Get all audit logs
1386
+ */
1387
+ getLogs(): AuditLogEntry[];
1388
+ /**
1389
+ * Query logs with filters (async)
1390
+ */
1391
+ queryLogs(filter?: AuditQueryFilter): Promise<HashedAuditLogEntry[]>;
1392
+ /**
1393
+ * Get logs by operation type
1394
+ */
1395
+ getLogsByOperation(_operation: AuditLogEntry['operation']): AuditLogEntry[];
1396
+ /**
1397
+ * Get logs by date range
1398
+ */
1399
+ getLogsByDateRange(_startDate: Date, _endDate: Date): AuditLogEntry[];
1400
+ /**
1401
+ * Export logs as JSON
1402
+ */
1403
+ exportAsJson(): string;
1404
+ /**
1405
+ * Export logs as JSON (async)
1406
+ */
1407
+ exportAsJsonAsync(filter?: AuditQueryFilter): Promise<string>;
1408
+ /**
1409
+ * Export logs as CSV
1410
+ */
1411
+ exportAsCsv(): string;
1412
+ /**
1413
+ * Export logs as CSV (async)
1414
+ */
1415
+ exportAsCsvAsync(filter?: AuditQueryFilter): Promise<string>;
1416
+ /**
1417
+ * Clear all audit logs (dangerous!)
1418
+ */
1419
+ clear(): void;
1420
+ /**
1421
+ * Delete logs older than specified date
1422
+ */
1423
+ deleteOlderThan(date: Date): Promise<number>;
1424
+ /**
1425
+ * Get audit statistics
1426
+ */
1427
+ getStats(): AuditStats;
1428
+ /**
1429
+ * Get audit statistics (async)
1430
+ */
1431
+ getStatsAsync(filter?: AuditQueryFilter): Promise<AuditStats>;
1432
+ /**
1433
+ * Verify log chain integrity
1434
+ */
1435
+ verifyChainIntegrity(startSequence?: number, endSequence?: number): Promise<{
1436
+ valid: boolean;
1437
+ brokenAt?: number;
1438
+ message: string;
1439
+ }>;
1440
+ /**
1441
+ * Flush batch buffer to database
1442
+ */
1443
+ flushBatch(): Promise<void>;
1444
+ /**
1445
+ * Close the logger and flush any pending logs
1446
+ */
1447
+ close(): Promise<void>;
1448
+ /**
1449
+ * Create hashed entry with chain linking
1450
+ */
1451
+ private createHashedEntry;
1452
+ /**
1453
+ * Calculate cryptographic hash of entry
1454
+ */
1455
+ private calculateHash;
1456
+ /**
1457
+ * Generate unique ID
1458
+ */
1459
+ private generateId;
1460
+ /**
1461
+ * Create database adapter based on backend
1462
+ */
1463
+ private createAdapter;
1464
+ /**
1465
+ * Start automatic cleanup schedule
1466
+ */
1467
+ private startCleanupSchedule;
1468
+ /**
1469
+ * Run cleanup based on retention policy
1470
+ */
1471
+ private runCleanup;
1472
+ }
1473
+ /**
1474
+ * Create a persistent audit logger
1475
+ */
1476
+ declare function createPersistentAuditLogger(options: PersistentAuditLoggerOptions): PersistentAuditLogger;
1477
+ //#endregion
1478
+ //#region src/metrics/MetricsCollector.d.ts
1479
+ /**
1480
+ * In-memory metrics collector and exporter
1481
+ * Collects metrics and provides Prometheus and StatsD export formats
1482
+ */
1483
+ declare class InMemoryMetricsCollector implements IMetricsCollector, IMetricsExporter {
1484
+ private metrics;
1485
+ constructor();
1486
+ /**
1487
+ * Create empty metrics object
1488
+ */
1489
+ private createEmptyMetrics;
1490
+ /**
1491
+ * Record a redaction operation
1492
+ */
1493
+ recordRedaction(result: DetectionResult, processingTimeMs: number, redactionMode: RedactionMode): void;
1494
+ /**
1495
+ * Record an error
1496
+ */
1497
+ recordError(): void;
1498
+ /**
1499
+ * Get metrics exporter
1500
+ */
1501
+ getExporter(): IMetricsExporter;
1502
+ /**
1503
+ * Get current metrics snapshot
1504
+ */
1505
+ getMetrics(): RedactionMetrics;
1506
+ /**
1507
+ * Reset all metrics
1508
+ */
1509
+ reset(): void;
1510
+ /**
1511
+ * Export metrics in Prometheus format
1512
+ */
1513
+ exportPrometheus(metrics?: RedactionMetrics, prefix?: string): string;
1514
+ /**
1515
+ * Export metrics in StatsD format
1516
+ */
1517
+ exportStatsD(metrics?: RedactionMetrics, prefix?: string): string[];
1518
+ }
1519
+ //#endregion
1520
+ //#region src/metrics/PrometheusServer.d.ts
1521
+ /**
1522
+ * Prometheus server options
1523
+ */
1524
+ interface PrometheusServerOptions {
1525
+ /** Port to listen on (default: 9090) */
1526
+ port?: number;
1527
+ /** Host to bind to (default: '0.0.0.0') */
1528
+ host?: string;
1529
+ /** Metrics path (default: '/metrics') */
1530
+ metricsPath?: string;
1531
+ /** Metrics prefix (default: 'openredaction') */
1532
+ prefix?: string;
1533
+ /** Health check path (default: '/health') */
1534
+ healthPath?: string;
1535
+ /** Enable CORS (default: false) */
1536
+ enableCors?: boolean;
1537
+ /** Basic auth username (optional) */
1538
+ username?: string;
1539
+ /** Basic auth password (optional) */
1540
+ password?: string;
1541
+ }
1542
+ /**
1543
+ * Prometheus metrics HTTP server
1544
+ * Provides a lightweight HTTP server for exposing metrics to Prometheus
1545
+ */
1546
+ declare class PrometheusServer {
1547
+ private server?;
1548
+ private metricsCollector;
1549
+ private options;
1550
+ private isRunning;
1551
+ private requestCount;
1552
+ private lastScrapeTime?;
1553
+ constructor(metricsCollector: IMetricsCollector, options?: PrometheusServerOptions);
1554
+ /**
1555
+ * Start the Prometheus metrics server
1556
+ */
1557
+ start(): Promise<void>;
1558
+ /**
1559
+ * Stop the server
1560
+ */
1561
+ stop(): Promise<void>;
1562
+ /**
1563
+ * Handle incoming HTTP requests
1564
+ */
1565
+ private handleRequest;
1566
+ /**
1567
+ * Handle /metrics endpoint
1568
+ */
1569
+ private handleMetrics;
1570
+ /**
1571
+ * Handle /health endpoint
1572
+ */
1573
+ private handleHealth;
1574
+ /**
1575
+ * Handle / root endpoint
1576
+ */
1577
+ private handleRoot;
1578
+ /**
1579
+ * Validate basic authentication
1580
+ */
1581
+ private validateAuth;
1582
+ /**
1583
+ * Get server-specific metrics in Prometheus format
1584
+ */
1585
+ private getServerMetrics;
1586
+ /**
1587
+ * Get server statistics
1588
+ */
1589
+ getStats(): {
1590
+ isRunning: boolean;
1591
+ requestCount: number;
1592
+ lastScrapeTime?: Date;
1593
+ uptime: number;
1594
+ host: string;
1595
+ port: number;
1596
+ metricsPath: string;
1597
+ };
1598
+ }
1599
+ /**
1600
+ * Create a Prometheus server instance
1601
+ */
1602
+ declare function createPrometheusServer(metricsCollector: IMetricsCollector, options?: PrometheusServerOptions): PrometheusServer;
1603
+ /**
1604
+ * Example Grafana dashboard JSON for OpenRedaction metrics
1605
+ * Can be imported directly into Grafana
1606
+ */
1607
+ declare const GRAFANA_DASHBOARD_TEMPLATE: {
1608
+ dashboard: {
1609
+ title: string;
1610
+ tags: string[];
1611
+ timezone: string;
1612
+ panels: {
1613
+ id: number;
1614
+ title: string;
1615
+ type: string;
1616
+ targets: {
1617
+ expr: string;
1618
+ legendFormat: string;
1619
+ }[];
1620
+ }[];
1621
+ };
1622
+ };
1623
+ //#endregion
1624
+ //#region src/rbac/RBACManager.d.ts
1625
+ /**
1626
+ * Default RBAC Manager implementation
1627
+ * Provides role-based permission checking and pattern filtering
1628
+ */
1629
+ declare class RBACManager implements IRBACManager {
1630
+ private role;
1631
+ constructor(role?: Role);
1632
+ /**
1633
+ * Check if current role has a specific permission
1634
+ */
1635
+ hasPermission(permission: Permission): boolean;
1636
+ /**
1637
+ * Check if current role has all specified permissions
1638
+ */
1639
+ hasAllPermissions(permissions: Permission[]): boolean;
1640
+ /**
1641
+ * Check if current role has any of the specified permissions
1642
+ */
1643
+ hasAnyPermission(permissions: Permission[]): boolean;
1644
+ /**
1645
+ * Get current role
1646
+ */
1647
+ getRole(): Role;
1648
+ /**
1649
+ * Set role (updates permissions)
1650
+ */
1651
+ setRole(role: Role): void;
1652
+ /**
1653
+ * Get all permissions for current role
1654
+ */
1655
+ getPermissions(): Permission[];
1656
+ /**
1657
+ * Filter patterns based on read permissions
1658
+ * Returns empty array if user lacks pattern:read permission
1659
+ */
1660
+ filterPatterns(patterns: PIIPattern[]): PIIPattern[];
1661
+ }
1662
+ /**
1663
+ * Create RBAC manager with predefined or custom role
1664
+ */
1665
+ declare function createRBACManager(role: Role): RBACManager;
1666
+ //#endregion
1667
+ //#region src/rbac/roles.d.ts
1668
+ /**
1669
+ * All available permissions
1670
+ */
1671
+ declare const ALL_PERMISSIONS: Permission[];
1672
+ /**
1673
+ * Admin role - full access to all operations
1674
+ */
1675
+ declare const ADMIN_ROLE: Role;
1676
+ /**
1677
+ * Analyst role - can perform analysis and read audit/metrics
1678
+ */
1679
+ declare const ANALYST_ROLE: Role;
1680
+ /**
1681
+ * Operator role - can perform detections and basic operations
1682
+ */
1683
+ declare const OPERATOR_ROLE: Role;
1684
+ /**
1685
+ * Viewer role - read-only access to patterns, audit logs, and metrics
1686
+ */
1687
+ declare const VIEWER_ROLE: Role;
1688
+ /**
1689
+ * Get predefined role by name
1690
+ */
1691
+ declare function getPredefinedRole(roleName: string): Role | undefined;
1692
+ /**
1693
+ * Create a custom role with specific permissions
1694
+ */
1695
+ declare function createCustomRole(name: string, permissions: Permission[], description?: string): Role;
1696
+ //#endregion
1697
+ //#region src/document/OCRProcessor.d.ts
1698
+ /**
1699
+ * OCR processor with optional Tesseract.js support
1700
+ * Requires peer dependency: tesseract.js
1701
+ */
1702
+ declare class OCRProcessor implements IOCRProcessor {
1703
+ private tesseract?;
1704
+ private scheduler?;
1705
+ constructor();
1706
+ /**
1707
+ * Extract text from image buffer using OCR
1708
+ */
1709
+ recognizeText(buffer: Buffer, options?: OCROptions): Promise<OCRResult>;
1710
+ /**
1711
+ * Check if OCR is available (tesseract.js installed)
1712
+ */
1713
+ isAvailable(): boolean;
1714
+ /**
1715
+ * Create a scheduler for batch OCR processing
1716
+ * More efficient for processing multiple images
1717
+ */
1718
+ createScheduler(workerCount?: number): Promise<any>;
1719
+ /**
1720
+ * Batch process multiple images
1721
+ */
1722
+ recognizeBatch(buffers: Buffer[], _options?: OCROptions): Promise<OCRResult[]>;
1723
+ /**
1724
+ * Terminate any running scheduler
1725
+ */
1726
+ cleanup(): Promise<void>;
1727
+ }
1728
+ /**
1729
+ * Create an OCR processor instance
1730
+ */
1731
+ declare function createOCRProcessor(): OCRProcessor;
1732
+ //#endregion
1733
+ //#region src/document/JsonProcessor.d.ts
1734
+ /**
1735
+ * JSON processing options
1736
+ */
1737
+ interface JsonProcessorOptions {
1738
+ /** Maximum depth for nested object traversal (default: 100) */
1739
+ maxDepth?: number;
1740
+ /** Whether to scan object keys for PII (default: false) */
1741
+ scanKeys?: boolean;
1742
+ /** Field paths to always redact (e.g., ['user.password', 'auth.token']) */
1743
+ alwaysRedact?: string[];
1744
+ /** Field paths to never scan (e.g., ['metadata.id', 'timestamp']) */
1745
+ skipPaths?: string[];
1746
+ /** Field names that indicate PII (boost confidence) */
1747
+ piiIndicatorKeys?: string[];
1748
+ /** Preserve JSON structure in redacted output (default: true) */
1749
+ preserveStructure?: boolean;
1750
+ }
1751
+ /**
1752
+ * JSON detection result with path tracking
1753
+ */
1754
+ interface JsonDetectionResult extends DetectionResult {
1755
+ /** Paths where PII was detected (e.g., 'user.email', 'contacts[0].phone') */
1756
+ pathsDetected: string[];
1757
+ /** PII matches with path information */
1758
+ matchesByPath: Record<string, PIIDetection[]>;
1759
+ }
1760
+ /**
1761
+ * Processor for JSON documents
1762
+ */
1763
+ declare class JsonProcessor {
1764
+ private readonly defaultOptions;
1765
+ /**
1766
+ * Parse JSON from buffer or string
1767
+ */
1768
+ parse(input: Buffer | string): any;
1769
+ /**
1770
+ * Detect PII in JSON data
1771
+ */
1772
+ detect(data: any, detector: OpenRedaction, options?: JsonProcessorOptions): Promise<JsonDetectionResult>;
1773
+ /**
1774
+ * Redact PII in JSON data
1775
+ */
1776
+ redact(data: any, detectionResult: JsonDetectionResult, options?: JsonProcessorOptions): any;
1777
+ /**
1778
+ * Redact specific paths in JSON while preserving structure
1779
+ */
1780
+ private redactPreservingStructure;
1781
+ /**
1782
+ * Simple text-based redaction (fallback)
1783
+ */
1784
+ private redactText;
1785
+ /**
1786
+ * Traverse JSON structure and call callback for each value
1787
+ */
1788
+ private traverse;
1789
+ /**
1790
+ * Check if value is primitive (string, number, boolean)
1791
+ */
1792
+ private isPrimitive;
1793
+ /**
1794
+ * Check if path should be skipped
1795
+ */
1796
+ private shouldSkip;
1797
+ /**
1798
+ * Check if path should always be redacted
1799
+ */
1800
+ private shouldAlwaysRedact;
1801
+ /**
1802
+ * Boost confidence if key name indicates PII
1803
+ */
1804
+ private boostConfidenceFromKey;
1805
+ /**
1806
+ * Extract all text values from JSON for simple text-based detection
1807
+ */
1808
+ extractText(data: any, options?: JsonProcessorOptions): string;
1809
+ /**
1810
+ * Validate JSON buffer/string
1811
+ */
1812
+ isValid(input: Buffer | string): boolean;
1813
+ /**
1814
+ * Get JSON Lines (JSONL) support - split by newlines and parse each line
1815
+ */
1816
+ parseJsonLines(input: Buffer | string): any[];
1817
+ /**
1818
+ * Detect PII in JSON Lines format
1819
+ */
1820
+ detectJsonLines(input: Buffer | string, detector: OpenRedaction, options?: JsonProcessorOptions): Promise<JsonDetectionResult[]>;
1821
+ }
1822
+ /**
1823
+ * Create a JSON processor instance
1824
+ */
1825
+ declare function createJsonProcessor(): JsonProcessor;
1826
+ //#endregion
1827
+ //#region src/document/CsvProcessor.d.ts
1828
+ /**
1829
+ * CSV processing options
1830
+ */
1831
+ interface CsvProcessorOptions {
1832
+ /** CSV delimiter (default: auto-detect from ',', '\t', ';', '|') */
1833
+ delimiter?: string;
1834
+ /** Whether CSV has header row (default: auto-detect) */
1835
+ hasHeader?: boolean;
1836
+ /** Quote character (default: '"') */
1837
+ quote?: string;
1838
+ /** Escape character (default: '"') */
1839
+ escape?: string;
1840
+ /** Skip empty lines (default: true) */
1841
+ skipEmptyLines?: boolean;
1842
+ /** Maximum rows to process (default: unlimited) */
1843
+ maxRows?: number;
1844
+ /** Column indices to always redact (0-indexed) */
1845
+ alwaysRedactColumns?: number[];
1846
+ /** Column names to always redact (requires hasHeader: true) */
1847
+ alwaysRedactColumnNames?: string[];
1848
+ /** Column indices to skip scanning (0-indexed) */
1849
+ skipColumns?: number[];
1850
+ /** Column names that indicate PII (boost confidence) */
1851
+ piiIndicatorNames?: string[];
1852
+ /** Treat first row as header for detection purposes */
1853
+ treatFirstRowAsHeader?: boolean;
1854
+ }
1855
+ /**
1856
+ * CSV detection result with column tracking
1857
+ */
1858
+ interface CsvDetectionResult extends DetectionResult {
1859
+ /** Total rows processed */
1860
+ rowCount: number;
1861
+ /** Column count */
1862
+ columnCount: number;
1863
+ /** Column headers (if detected) */
1864
+ headers?: string[];
1865
+ /** PII statistics by column index */
1866
+ columnStats: Record<number, ColumnStats>;
1867
+ /** PII matches by row and column */
1868
+ matchesByCell: CellMatch[];
1869
+ /** Original text */
1870
+ original: string;
1871
+ /** Redacted text */
1872
+ redacted: string;
1873
+ /** Array of detections */
1874
+ detections: PIIDetection[];
1875
+ /** Redaction map */
1876
+ redactionMap: Record<string, string>;
1877
+ /** Statistics */
1878
+ stats?: {
1879
+ processingTime?: number;
1880
+ piiCount: number;
1881
+ };
1882
+ }
1883
+ /**
1884
+ * Column PII statistics
1885
+ */
1886
+ interface ColumnStats {
1887
+ /** Column index */
1888
+ columnIndex: number;
1889
+ /** Column name (if header available) */
1890
+ columnName?: string;
1891
+ /** Number of PII instances found */
1892
+ piiCount: number;
1893
+ /** Percentage of rows with PII (0-100) */
1894
+ piiPercentage: number;
1895
+ /** PII types found in this column */
1896
+ piiTypes: string[];
1897
+ }
1898
+ /**
1899
+ * Cell-level PII match
1900
+ */
1901
+ interface CellMatch {
1902
+ /** Row index (0-indexed, excluding header if present) */
1903
+ row: number;
1904
+ /** Column index (0-indexed) */
1905
+ column: number;
1906
+ /** Column name (if header available) */
1907
+ columnName?: string;
1908
+ /** Cell value */
1909
+ value: string;
1910
+ /** PII matches in this cell */
1911
+ matches: PIIDetection[];
1912
+ }
1913
+ /**
1914
+ * Parsed CSV row
1915
+ */
1916
+ interface CsvRow {
1917
+ /** Row index */
1918
+ index: number;
1919
+ /** Cell values */
1920
+ values: string[];
1921
+ }
1922
+ /**
1923
+ * CSV processor for tabular data
1924
+ */
1925
+ declare class CsvProcessor {
1926
+ private readonly defaultOptions;
1927
+ /**
1928
+ * Parse CSV from buffer or string
1929
+ */
1930
+ parse(input: Buffer | string, options?: CsvProcessorOptions): CsvRow[];
1931
+ /**
1932
+ * Detect PII in CSV data
1933
+ */
1934
+ detect(input: Buffer | string, detector: OpenRedaction, options?: CsvProcessorOptions): Promise<CsvDetectionResult>;
1935
+ /**
1936
+ * Redact PII in CSV data
1937
+ */
1938
+ redact(input: Buffer | string, detectionResult: CsvDetectionResult, options?: CsvProcessorOptions): string;
1939
+ /**
1940
+ * Parse a single CSV row
1941
+ */
1942
+ private parseRow;
1943
+ /**
1944
+ * Format a row as CSV
1945
+ */
1946
+ private formatRow;
1947
+ /**
1948
+ * Auto-detect CSV delimiter
1949
+ */
1950
+ private detectDelimiter;
1951
+ /**
1952
+ * Detect if first row is likely a header
1953
+ */
1954
+ private detectHeader;
1955
+ /**
1956
+ * Boost confidence if column name indicates PII
1957
+ */
1958
+ private boostConfidenceFromColumnName;
1959
+ /**
1960
+ * Extract all cell values as text
1961
+ */
1962
+ extractText(input: Buffer | string, options?: CsvProcessorOptions): string;
1963
+ /**
1964
+ * Get column statistics without full PII detection
1965
+ */
1966
+ getColumnInfo(input: Buffer | string, options?: CsvProcessorOptions): {
1967
+ columnCount: number;
1968
+ rowCount: number;
1969
+ headers?: string[];
1970
+ sampleRows: string[][];
1971
+ };
1972
+ }
1973
+ /**
1974
+ * Create a CSV processor instance
1975
+ */
1976
+ declare function createCsvProcessor(): CsvProcessor;
1977
+ //#endregion
1978
+ //#region src/document/XlsxProcessor.d.ts
1979
+ /**
1980
+ * XLSX processing options
1981
+ */
1982
+ interface XlsxProcessorOptions {
1983
+ /** Sheet names to process (default: all sheets) */
1984
+ sheets?: string[];
1985
+ /** Sheet indices to process (0-indexed, default: all sheets) */
1986
+ sheetIndices?: number[];
1987
+ /** Whether to treat first row as header (default: auto-detect) */
1988
+ hasHeader?: boolean;
1989
+ /** Maximum rows per sheet to process (default: unlimited) */
1990
+ maxRows?: number;
1991
+ /** Column indices to always redact (0-indexed) */
1992
+ alwaysRedactColumns?: number[];
1993
+ /** Column names to always redact (requires hasHeader: true) */
1994
+ alwaysRedactColumnNames?: string[];
1995
+ /** Column indices to skip scanning (0-indexed) */
1996
+ skipColumns?: number[];
1997
+ /** Column names that indicate PII (boost confidence) */
1998
+ piiIndicatorNames?: string[];
1999
+ /** Preserve cell formatting (default: true) */
2000
+ preserveFormatting?: boolean;
2001
+ /** Preserve formulas (default: true, redact values but keep formula) */
2002
+ preserveFormulas?: boolean;
2003
+ }
2004
+ /**
2005
+ * XLSX detection result with sheet and cell tracking
2006
+ */
2007
+ interface XlsxDetectionResult extends DetectionResult {
2008
+ /** Results by sheet */
2009
+ sheetResults: SheetDetectionResult[];
2010
+ /** Total sheets processed */
2011
+ sheetCount: number;
2012
+ }
2013
+ /**
2014
+ * Sheet-level detection result
2015
+ */
2016
+ interface SheetDetectionResult {
2017
+ /** Sheet name */
2018
+ sheetName: string;
2019
+ /** Sheet index */
2020
+ sheetIndex: number;
2021
+ /** Total rows in sheet */
2022
+ rowCount: number;
2023
+ /** Column count */
2024
+ columnCount: number;
2025
+ /** Column headers (if detected) */
2026
+ headers?: string[];
2027
+ /** Column statistics */
2028
+ columnStats: Record<number, ColumnStats$1>;
2029
+ /** Cell matches */
2030
+ matchesByCell: CellMatch$1[];
2031
+ }
2032
+ /**
2033
+ * Column PII statistics
2034
+ */
2035
+ interface ColumnStats$1 {
2036
+ /** Column index */
2037
+ columnIndex: number;
2038
+ /** Column letter (A, B, C, etc.) */
2039
+ columnLetter: string;
2040
+ /** Column name (if header available) */
2041
+ columnName?: string;
2042
+ /** Number of PII instances found */
2043
+ piiCount: number;
2044
+ /** Percentage of rows with PII (0-100) */
2045
+ piiPercentage: number;
2046
+ /** PII types found in this column */
2047
+ piiTypes: string[];
2048
+ }
2049
+ /**
2050
+ * Cell-level PII match
2051
+ */
2052
+ interface CellMatch$1 {
2053
+ /** Cell reference (e.g., 'A1', 'B5') */
2054
+ cell: string;
2055
+ /** Row index (1-indexed, Excel style) */
2056
+ row: number;
2057
+ /** Column index (0-indexed) */
2058
+ column: number;
2059
+ /** Column letter */
2060
+ columnLetter: string;
2061
+ /** Column name (if header available) */
2062
+ columnName?: string;
2063
+ /** Cell value */
2064
+ value: string;
2065
+ /** Cell formula (if any) */
2066
+ formula?: string;
2067
+ /** PII matches in this cell */
2068
+ matches: PIIDetection[];
2069
+ }
2070
+ /**
2071
+ * XLSX processor for spreadsheet data
2072
+ */
2073
+ declare class XlsxProcessor {
2074
+ private xlsx?;
2075
+ private readonly defaultOptions;
2076
+ constructor();
2077
+ /**
2078
+ * Check if XLSX support is available
2079
+ */
2080
+ isAvailable(): boolean;
2081
+ /**
2082
+ * Parse XLSX from buffer
2083
+ */
2084
+ parse(buffer: Buffer): any;
2085
+ /**
2086
+ * Detect PII in XLSX data
2087
+ */
2088
+ detect(buffer: Buffer, detector: OpenRedaction, options?: XlsxProcessorOptions): Promise<XlsxDetectionResult>;
2089
+ /**
2090
+ * Detect PII in a single sheet
2091
+ */
2092
+ private detectSheet;
2093
+ /**
2094
+ * Redact PII in XLSX data
2095
+ */
2096
+ redact(buffer: Buffer, detectionResult: XlsxDetectionResult, options?: XlsxProcessorOptions): Buffer;
2097
+ /**
2098
+ * Get cell value as string
2099
+ */
2100
+ private getCellValue;
2101
+ /**
2102
+ * Get row values
2103
+ */
2104
+ private getRowValues;
2105
+ /**
2106
+ * Detect if first row is likely a header
2107
+ */
2108
+ private detectHeader;
2109
+ /**
2110
+ * Convert column index to letter (0 = A, 25 = Z, 26 = AA)
2111
+ */
2112
+ private columnToLetter;
2113
+ /**
2114
+ * Get sheet names to process based on options
2115
+ */
2116
+ private getSheetNamesToProcess;
2117
+ /**
2118
+ * Boost confidence if column name indicates PII
2119
+ */
2120
+ private boostConfidenceFromColumnName;
2121
+ /**
2122
+ * Extract all cell values as text
2123
+ */
2124
+ extractText(buffer: Buffer, options?: XlsxProcessorOptions): string;
2125
+ /**
2126
+ * Get workbook metadata
2127
+ */
2128
+ getMetadata(buffer: Buffer): {
2129
+ sheetNames: string[];
2130
+ sheetCount: number;
2131
+ };
2132
+ }
2133
+ /**
2134
+ * Create an XLSX processor instance
2135
+ */
2136
+ declare function createXlsxProcessor(): XlsxProcessor;
2137
+ //#endregion
2138
+ //#region src/document/DocumentProcessor.d.ts
2139
+ /**
2140
+ * Document processor with optional PDF, DOCX, OCR, JSON, CSV, and XLSX support
2141
+ * Requires peer dependencies:
2142
+ * - pdf-parse (for PDF)
2143
+ * - mammoth (for DOCX)
2144
+ * - tesseract.js (for OCR/images)
2145
+ * - xlsx (for Excel/XLSX)
2146
+ */
2147
+ declare class DocumentProcessor implements IDocumentProcessor {
2148
+ private pdfParse?;
2149
+ private mammoth?;
2150
+ private ocrProcessor;
2151
+ private jsonProcessor;
2152
+ private csvProcessor;
2153
+ private xlsxProcessor;
2154
+ constructor();
2155
+ /**
2156
+ * Extract text from document buffer
2157
+ */
2158
+ extractText(buffer: Buffer, options?: DocumentOptions): Promise<string>;
2159
+ /**
2160
+ * Get document metadata
2161
+ */
2162
+ getMetadata(buffer: Buffer, options?: DocumentOptions): Promise<DocumentMetadata>;
2163
+ /**
2164
+ * Detect document format from buffer
2165
+ */
2166
+ detectFormat(buffer: Buffer): DocumentFormat | null;
2167
+ /**
2168
+ * Check if format is supported
2169
+ */
2170
+ isFormatSupported(format: DocumentFormat): boolean;
2171
+ /**
2172
+ * Extract text from PDF
2173
+ */
2174
+ private extractPdfText;
2175
+ /**
2176
+ * Extract text from DOCX
2177
+ */
2178
+ private extractDocxText;
2179
+ /**
2180
+ * Get PDF metadata
2181
+ */
2182
+ private getPdfMetadata;
2183
+ /**
2184
+ * Get DOCX metadata
2185
+ */
2186
+ private getDocxMetadata;
2187
+ /**
2188
+ * Extract text from image using OCR
2189
+ */
2190
+ private extractImageText;
2191
+ /**
2192
+ * Get image metadata
2193
+ */
2194
+ private getImageMetadata;
2195
+ /**
2196
+ * Extract text from JSON
2197
+ */
2198
+ private extractJsonText;
2199
+ /**
2200
+ * Extract text from CSV
2201
+ */
2202
+ private extractCsvText;
2203
+ /**
2204
+ * Extract text from XLSX
2205
+ */
2206
+ private extractXlsxText;
2207
+ /**
2208
+ * Get JSON metadata
2209
+ */
2210
+ private getJsonMetadata;
2211
+ /**
2212
+ * Get CSV metadata
2213
+ */
2214
+ private getCsvMetadata;
2215
+ /**
2216
+ * Get XLSX metadata
2217
+ */
2218
+ private getXlsxMetadata;
2219
+ /**
2220
+ * Get OCR processor instance
2221
+ */
2222
+ getOCRProcessor(): OCRProcessor;
2223
+ /**
2224
+ * Get JSON processor instance
2225
+ */
2226
+ getJsonProcessor(): JsonProcessor;
2227
+ /**
2228
+ * Get CSV processor instance
2229
+ */
2230
+ getCsvProcessor(): CsvProcessor;
2231
+ /**
2232
+ * Get XLSX processor instance
2233
+ */
2234
+ getXlsxProcessor(): XlsxProcessor;
2235
+ }
2236
+ /**
2237
+ * Create a document processor instance
2238
+ */
2239
+ declare function createDocumentProcessor(): DocumentProcessor;
2240
+ //#endregion
2241
+ //#region src/patterns/personal.d.ts
2242
+ declare const personalPatterns: PIIPattern[];
2243
+ //#endregion
2244
+ //#region src/patterns/financial.d.ts
2245
+ declare const financialPatterns: PIIPattern[];
2246
+ //#endregion
2247
+ //#region src/patterns/government.d.ts
2248
+ declare const governmentPatterns: PIIPattern[];
2249
+ //#endregion
2250
+ //#region src/patterns/contact.d.ts
2251
+ declare const contactPatterns: PIIPattern[];
2252
+ //#endregion
2253
+ //#region src/patterns/network.d.ts
2254
+ declare const networkPatterns: PIIPattern[];
2255
+ //#endregion
2256
+ //#region src/patterns/index.d.ts
2257
+ /**
2258
+ * All default PII patterns
2259
+ */
2260
+ declare const allPatterns: PIIPattern[];
2261
+ /**
2262
+ * Get patterns by category
2263
+ */
2264
+ declare function getPatternsByCategory(category: string): PIIPattern[];
2265
+ //#endregion
2266
+ //#region src/validators/index.d.ts
2267
+ /**
2268
+ * Validators for PII pattern matching
2269
+ */
2270
+ /**
2271
+ * Luhn algorithm validator for credit cards
2272
+ * https://en.wikipedia.org/wiki/Luhn_algorithm
2273
+ */
2274
+ declare function validateLuhn(cardNumber: string, _context?: string): boolean;
2275
+ /**
2276
+ * IBAN validator with checksum verification
2277
+ */
2278
+ declare function validateIBAN(iban: string, _context?: string): boolean;
2279
+ /**
2280
+ * UK National Insurance Number validator
2281
+ */
2282
+ declare function validateNINO(nino: string, _context?: string): boolean;
2283
+ /**
2284
+ * UK NHS Number validator with checksum
2285
+ */
2286
+ declare function validateNHS(nhs: string, _context?: string): boolean;
2287
+ /**
2288
+ * UK Passport validator
2289
+ */
2290
+ declare function validateUKPassport(passport: string, _context?: string): boolean;
2291
+ /**
2292
+ * US Social Security Number validator (format check only)
2293
+ */
2294
+ declare function validateSSN(ssn: string, _context?: string): boolean;
2295
+ /**
2296
+ * UK Sort Code validator (format check)
2297
+ */
2298
+ declare function validateSortCode(sortCode: string, _context?: string): boolean;
2299
+ /**
2300
+ * Context-aware name validator to reduce false positives
2301
+ */
2302
+ declare function validateName(name: string, context: string): boolean;
2303
+ /**
2304
+ * Email validator with DNS check capability
2305
+ */
2306
+ declare function validateEmail(email: string, _context?: string): boolean;
2307
+ //#endregion
2308
+ //#region src/utils/presets.d.ts
2309
+ /**
2310
+ * GDPR compliance preset - European Union data protection
2311
+ */
2312
+ declare const gdprPreset: Partial<OpenRedactionOptions>;
2313
+ /**
2314
+ * HIPAA compliance preset - US healthcare data protection
2315
+ */
2316
+ declare const hipaaPreset: Partial<OpenRedactionOptions>;
2317
+ /**
2318
+ * CCPA compliance preset - California consumer privacy
2319
+ */
2320
+ declare const ccpaPreset: Partial<OpenRedactionOptions>;
2321
+ /**
2322
+ * Healthcare operations preset - provider-centric coverage
2323
+ */
2324
+ declare const healthcarePreset: Partial<OpenRedactionOptions>;
2325
+ /**
2326
+ * Healthcare research preset - clinical research and trials
2327
+ */
2328
+ declare const healthcareResearchPreset: Partial<OpenRedactionOptions>;
2329
+ /**
2330
+ * Financial services preset - banking, trading, and payments
2331
+ */
2332
+ declare const financePreset: Partial<OpenRedactionOptions>;
2333
+ /**
2334
+ * Education preset - FERPA-style coverage for schools and universities
2335
+ */
2336
+ declare const educationPreset: Partial<OpenRedactionOptions>;
2337
+ /**
2338
+ * Transportation and logistics preset - fleet, shipping, and mobility
2339
+ */
2340
+ declare const transportLogisticsPreset: Partial<OpenRedactionOptions>;
2341
+ /**
2342
+ * Get preset configuration by name
2343
+ */
2344
+ declare function getPreset(name: string): Partial<OpenRedactionOptions>;
2345
+ //#endregion
2346
+ //#region src/config/ConfigLoader.d.ts
2347
+ interface OpenRedactionConfig extends OpenRedactionOptions {
2348
+ extends?: string | string[];
2349
+ learnedPatterns?: string;
2350
+ learningOptions?: {
2351
+ autoSave?: boolean;
2352
+ confidenceThreshold?: number;
2353
+ };
2354
+ }
2355
+ /**
2356
+ * Load configuration from .openredaction.config.js
2357
+ */
2358
+ declare class ConfigLoader {
2359
+ private configPath;
2360
+ private searchPaths;
2361
+ constructor(configPath?: string, cwd?: string);
2362
+ /**
2363
+ * Find config file in search paths
2364
+ */
2365
+ private findConfigFile;
2366
+ /**
2367
+ * Load config file
2368
+ */
2369
+ load(): Promise<OpenRedactionConfig | null>;
2370
+ /**
2371
+ * Resolve presets and extends
2372
+ */
2373
+ resolveConfig(config: OpenRedactionConfig): OpenRedactionOptions;
2374
+ /**
2375
+ * Load built-in preset
2376
+ */
2377
+ private loadPreset;
2378
+ /**
2379
+ * Create a default config file
2380
+ */
2381
+ static createDefaultConfig(outputPath?: string): void;
2382
+ }
2383
+ //#endregion
2384
+ //#region src/ml/NERDetector.d.ts
2385
+ /**
2386
+ * NER entity types supported
2387
+ */
2388
+ type NEREntityType = 'PERSON' | 'ORGANIZATION' | 'PLACE' | 'DATE' | 'MONEY' | 'PHONE' | 'EMAIL' | 'URL';
2389
+ /**
2390
+ * NER detection result
2391
+ */
2392
+ interface NERMatch {
2393
+ /** Entity type */
2394
+ type: NEREntityType;
2395
+ /** Matched text */
2396
+ text: string;
2397
+ /** Start position in text */
2398
+ start: number;
2399
+ /** End position in text */
2400
+ end: number;
2401
+ /** Confidence from NER (0-1) */
2402
+ confidence: number;
2403
+ /** Additional context */
2404
+ context?: {
2405
+ sentence?: string;
2406
+ tags?: string[];
2407
+ };
2408
+ }
2409
+ /**
2410
+ * Hybrid detection result (regex + NER)
2411
+ */
2412
+ interface HybridMatch extends PIIMatch {
2413
+ /** Whether this match was confirmed by NER */
2414
+ nerConfirmed: boolean;
2415
+ /** NER confidence if confirmed */
2416
+ nerConfidence?: number;
2417
+ }
2418
+ /**
2419
+ * NER Detector using compromise.js
2420
+ * Lightweight NLP library (7KB) for English text analysis
2421
+ */
2422
+ declare class NERDetector {
2423
+ private nlp?;
2424
+ private available;
2425
+ constructor();
2426
+ /**
2427
+ * Check if NER is available (compromise.js installed)
2428
+ */
2429
+ isAvailable(): boolean;
2430
+ /**
2431
+ * Detect named entities in text
2432
+ */
2433
+ detect(text: string): NERMatch[];
2434
+ /**
2435
+ * Check if a regex match is confirmed by NER
2436
+ */
2437
+ isConfirmedByNER(regexMatch: PIIMatch, nerMatches: NERMatch[]): {
2438
+ confirmed: boolean;
2439
+ confidence?: number;
2440
+ };
2441
+ /**
2442
+ * Boost confidence of regex matches that are confirmed by NER
2443
+ */
2444
+ hybridDetection(regexMatches: PIIMatch[], text: string): HybridMatch[];
2445
+ /**
2446
+ * Calculate overlap between two ranges (0-1)
2447
+ */
2448
+ private calculateOverlap;
2449
+ /**
2450
+ * Remove duplicate NER matches
2451
+ */
2452
+ private deduplicateMatches;
2453
+ /**
2454
+ * Extract sentence containing the match
2455
+ */
2456
+ private getSentence;
2457
+ /**
2458
+ * Find start of sentence
2459
+ */
2460
+ private findSentenceStart;
2461
+ /**
2462
+ * Find end of sentence
2463
+ */
2464
+ private findSentenceEnd;
2465
+ /**
2466
+ * Extract additional NER-only detections (entities not caught by regex)
2467
+ */
2468
+ extractNEROnly(nerMatches: NERMatch[], regexMatches: PIIMatch[]): NERMatch[];
2469
+ }
2470
+ /**
2471
+ * Create an NER detector instance
2472
+ */
2473
+ declare function createNERDetector(): NERDetector;
2474
+ //#endregion
2475
+ //#region src/severity/SeverityClassifier.d.ts
2476
+ /**
2477
+ * Severity level for PII types
2478
+ */
2479
+ type SeverityLevel = 'critical' | 'high' | 'medium' | 'low';
2480
+ /**
2481
+ * Severity classification with reasoning
2482
+ */
2483
+ interface SeverityClassification {
2484
+ /** Severity level */
2485
+ level: SeverityLevel;
2486
+ /** Numeric score (0-10) */
2487
+ score: number;
2488
+ /** Reasoning for classification */
2489
+ reason?: string;
2490
+ }
2491
+ /**
2492
+ * Risk score calculation result
2493
+ */
2494
+ interface RiskScore {
2495
+ /** Overall risk score (0-1) */
2496
+ score: number;
2497
+ /** Risk level */
2498
+ level: 'very-high' | 'high' | 'medium' | 'low' | 'minimal';
2499
+ /** Contributing factors */
2500
+ factors: {
2501
+ piiCount: number;
2502
+ avgSeverity: number;
2503
+ avgConfidence: number;
2504
+ criticalCount: number;
2505
+ highCount: number;
2506
+ };
2507
+ }
2508
+ /**
2509
+ * Default severity mappings by pattern type
2510
+ */
2511
+ declare const DEFAULT_SEVERITY_MAP: Record<string, SeverityLevel>;
2512
+ /**
2513
+ * Severity scores (for numeric calculations)
2514
+ */
2515
+ declare const SEVERITY_SCORES: Record<SeverityLevel, number>;
2516
+ /**
2517
+ * Severity Classifier
2518
+ */
2519
+ declare class SeverityClassifier {
2520
+ private severityMap;
2521
+ constructor(customMap?: Record<string, SeverityLevel>);
2522
+ /**
2523
+ * Classify severity for a pattern type
2524
+ */
2525
+ classify(patternType: string): SeverityClassification;
2526
+ /**
2527
+ * Ensure pattern has severity assigned
2528
+ */
2529
+ ensurePatternSeverity(pattern: PIIPattern): PIIPattern;
2530
+ /**
2531
+ * Ensure all patterns have severity
2532
+ */
2533
+ ensureAllSeverity(patterns: PIIPattern[]): PIIPattern[];
2534
+ /**
2535
+ * Calculate risk score for a set of detections
2536
+ */
2537
+ calculateRiskScore(detections: PIIDetection[]): RiskScore;
2538
+ /**
2539
+ * Get severity for a pattern type
2540
+ */
2541
+ getSeverity(patternType: string): SeverityLevel;
2542
+ /**
2543
+ * Get severity score for a pattern type
2544
+ */
2545
+ getSeverityScore(patternType: string): number;
2546
+ /**
2547
+ * Add custom severity mapping
2548
+ */
2549
+ addSeverityMapping(patternType: string, severity: SeverityLevel): void;
2550
+ /**
2551
+ * Get all severity mappings
2552
+ */
2553
+ getSeverityMap(): Record<string, SeverityLevel>;
2554
+ /**
2555
+ * Filter detections by severity threshold
2556
+ */
2557
+ filterBySeverity(detections: PIIDetection[], minSeverity: SeverityLevel): PIIDetection[];
2558
+ /**
2559
+ * Group detections by severity
2560
+ */
2561
+ groupBySeverity(detections: PIIDetection[]): Record<SeverityLevel, PIIDetection[]>;
2562
+ }
2563
+ /**
2564
+ * Create a severity classifier instance
2565
+ */
2566
+ declare function createSeverityClassifier(customMap?: Record<string, SeverityLevel>): SeverityClassifier;
2567
+ /**
2568
+ * Quick helper to get severity for a pattern type
2569
+ */
2570
+ declare function getSeverity(patternType: string): SeverityLevel;
2571
+ /**
2572
+ * Quick helper to calculate risk score
2573
+ */
2574
+ declare function calculateRisk(detections: PIIDetection[]): RiskScore;
2575
+ //#endregion
2576
+ //#region src/filters/FalsePositiveFilter.d.ts
2577
+ /**
2578
+ * False Positive Detection and Filtering
2579
+ * Identifies and filters out common false positives
2580
+ */
2581
+ interface FalsePositiveRule {
2582
+ /** Pattern type this rule applies to */
2583
+ patternType: string | string[];
2584
+ /** Matching function */
2585
+ matcher: (value: string, context: string) => boolean;
2586
+ /** Description of the false positive */
2587
+ description: string;
2588
+ /** Severity of the false positive (how confident we are it's not PII) */
2589
+ severity: 'high' | 'medium' | 'low';
2590
+ }
2591
+ /**
2592
+ * Common false positive rules
2593
+ */
2594
+ declare const commonFalsePositives: FalsePositiveRule[];
2595
+ /**
2596
+ * Check if a detection is a false positive
2597
+ */
2598
+ declare function isFalsePositive(value: string, patternType: string, context: string, rules?: FalsePositiveRule[]): {
2599
+ isFalsePositive: boolean;
2600
+ matchedRule?: FalsePositiveRule;
2601
+ confidence: number;
2602
+ };
2603
+ /**
2604
+ * Filter out false positives from detections
2605
+ */
2606
+ declare function filterFalsePositives<T extends {
2607
+ value: string;
2608
+ type: string;
2609
+ }>(detections: T[], getText: (detection: T) => {
2610
+ value: string;
2611
+ context: string;
2612
+ }, threshold?: number): T[];
2613
+ //#endregion
2614
+ //#region src/multipass/MultiPassDetector.d.ts
2615
+ /**
2616
+ * Detection pass configuration
2617
+ */
2618
+ interface DetectionPass {
2619
+ /** Pass name for debugging */
2620
+ name: string;
2621
+ /** Minimum priority for this pass */
2622
+ minPriority: number;
2623
+ /** Maximum priority for this pass */
2624
+ maxPriority: number;
2625
+ /** Pattern types to include (optional filter) */
2626
+ includeTypes?: string[];
2627
+ /** Pattern types to exclude (optional filter) */
2628
+ excludeTypes?: string[];
2629
+ /** Description of what this pass detects */
2630
+ description: string;
2631
+ }
2632
+ /**
2633
+ * Default multi-pass configuration
2634
+ * Processes patterns in priority order from highest to lowest
2635
+ */
2636
+ declare const defaultPasses: DetectionPass[];
2637
+ /**
2638
+ * Group patterns into passes based on priority
2639
+ */
2640
+ declare function groupPatternsByPass(patterns: PIIPattern[], passes?: DetectionPass[]): Map<string, PIIPattern[]>;
2641
+ /**
2642
+ * Statistics for multi-pass detection
2643
+ */
2644
+ interface MultiPassStats {
2645
+ /** Total passes executed */
2646
+ totalPasses: number;
2647
+ /** Detections per pass */
2648
+ detectionsPerPass: Map<string, number>;
2649
+ /** Patterns processed per pass */
2650
+ patternsPerPass: Map<string, number>;
2651
+ /** Time spent per pass (ms) */
2652
+ timePerPass: Map<string, number>;
2653
+ /** Total processing time (ms) */
2654
+ totalTime: number;
2655
+ }
2656
+ /**
2657
+ * Merge detections from multiple passes
2658
+ * Earlier passes (higher priority) take precedence for overlapping ranges
2659
+ */
2660
+ declare function mergePassDetections(passDetections: Map<string, PIIDetection[]>, passes: DetectionPass[]): PIIDetection[];
2661
+ /**
2662
+ * Create a simple multi-pass configuration for common use cases
2663
+ */
2664
+ declare function createSimpleMultiPass(options?: {
2665
+ /** Number of passes (2-5, default: 3) */numPasses?: number; /** Prioritize credentials first */
2666
+ prioritizeCredentials?: boolean;
2667
+ }): DetectionPass[];
2668
+ //#endregion
2669
+ //#region src/streaming/StreamingDetector.d.ts
2670
+ /**
2671
+ * Chunk result for streaming detection
2672
+ */
2673
+ interface ChunkResult {
2674
+ /** Chunk index */
2675
+ chunkIndex: number;
2676
+ /** Detections found in this chunk */
2677
+ detections: PIIDetection[];
2678
+ /** Redacted chunk text */
2679
+ redactedChunk: string;
2680
+ /** Original chunk text */
2681
+ originalChunk: string;
2682
+ /** Byte offset of this chunk in the original document */
2683
+ byteOffset: number;
2684
+ }
2685
+ /**
2686
+ * Streaming detection options
2687
+ */
2688
+ interface StreamingOptions {
2689
+ /** Chunk size in characters (default: 2048) */
2690
+ chunkSize?: number;
2691
+ /** Overlap between chunks to catch patterns at boundaries (default: 100) */
2692
+ overlap?: number;
2693
+ /** Enable progressive redaction (default: true) */
2694
+ progressiveRedaction?: boolean;
2695
+ }
2696
+ /**
2697
+ * Streaming detector for large documents
2698
+ */
2699
+ declare class StreamingDetector {
2700
+ private detector;
2701
+ private options;
2702
+ constructor(detector: OpenRedaction, options?: StreamingOptions);
2703
+ /**
2704
+ * Process a large text in chunks
2705
+ * Returns an async generator that yields chunk results
2706
+ */
2707
+ processStream(text: string): AsyncGenerator<ChunkResult, void, undefined>;
2708
+ /**
2709
+ * Process entire stream and collect all results
2710
+ */
2711
+ processComplete(text: string): Promise<DetectionResult>;
2712
+ /**
2713
+ * Process a file stream (Node.js only)
2714
+ */
2715
+ processFileStream(readableStream: ReadableStream<Uint8Array> | NodeJS.ReadableStream): AsyncGenerator<ChunkResult, void, undefined>;
2716
+ /**
2717
+ * Get chunk statistics
2718
+ */
2719
+ getChunkStats(textLength: number): {
2720
+ numChunks: number;
2721
+ chunkSize: number;
2722
+ overlap: number;
2723
+ estimatedMemory: number;
2724
+ };
2725
+ private escapeRegex;
2726
+ }
2727
+ /**
2728
+ * Helper to create a streaming detector from OpenRedaction instance
2729
+ */
2730
+ declare function createStreamingDetector(detector: OpenRedaction, options?: StreamingOptions): StreamingDetector;
2731
+ //#endregion
2732
+ //#region src/workers/types.d.ts
2733
+ /**
2734
+ * Worker task for text detection
2735
+ */
2736
+ interface DetectTask {
2737
+ type: 'detect';
2738
+ id: string;
2739
+ text: string;
2740
+ options?: OpenRedactionOptions;
2741
+ }
2742
+ /**
2743
+ * Worker task for document processing
2744
+ */
2745
+ interface DocumentTask {
2746
+ type: 'document';
2747
+ id: string;
2748
+ buffer: Buffer;
2749
+ options?: any;
2750
+ }
2751
+ /**
2752
+ * Worker task union type
2753
+ */
2754
+ type WorkerTask = DetectTask | DocumentTask;
2755
+ /**
2756
+ * Worker result
2757
+ */
2758
+ interface WorkerResult {
2759
+ id: string;
2760
+ result: DetectionResult | any;
2761
+ error?: string;
2762
+ processingTime: number;
2763
+ }
2764
+ /**
2765
+ * Worker pool configuration
2766
+ */
2767
+ interface WorkerPoolConfig {
2768
+ /** Number of worker threads (default: CPU count) */
2769
+ numWorkers?: number;
2770
+ /** Maximum queue size (default: 100) */
2771
+ maxQueueSize?: number;
2772
+ /** Worker idle timeout in ms (default: 30000) */
2773
+ idleTimeout?: number;
2774
+ }
2775
+ /**
2776
+ * Worker pool statistics
2777
+ */
2778
+ interface WorkerPoolStats {
2779
+ /** Number of active workers */
2780
+ activeWorkers: number;
2781
+ /** Number of idle workers */
2782
+ idleWorkers: number;
2783
+ /** Current queue size */
2784
+ queueSize: number;
2785
+ /** Total tasks processed */
2786
+ totalProcessed: number;
2787
+ /** Total errors */
2788
+ totalErrors: number;
2789
+ /** Average processing time */
2790
+ avgProcessingTime: number;
2791
+ }
2792
+ //#endregion
2793
+ //#region src/workers/WorkerPool.d.ts
2794
+ /**
2795
+ * Worker pool for parallel text detection and document processing
2796
+ */
2797
+ declare class WorkerPool {
2798
+ private workers;
2799
+ private availableWorkers;
2800
+ private taskQueue;
2801
+ private config;
2802
+ private stats;
2803
+ private workerPath;
2804
+ private totalProcessingTime;
2805
+ constructor(config?: WorkerPoolConfig);
2806
+ /**
2807
+ * Initialize worker pool
2808
+ */
2809
+ initialize(): Promise<void>;
2810
+ /**
2811
+ * Create a new worker
2812
+ */
2813
+ private createWorker;
2814
+ /**
2815
+ * Execute a task on the worker pool
2816
+ */
2817
+ execute<T = any>(task: WorkerTask): Promise<T>;
2818
+ /**
2819
+ * Process task queue
2820
+ */
2821
+ private processQueue;
2822
+ /**
2823
+ * Handle worker result
2824
+ */
2825
+ private handleWorkerResult;
2826
+ /**
2827
+ * Remove worker from pool
2828
+ */
2829
+ private removeWorker;
2830
+ /**
2831
+ * Get pool statistics
2832
+ */
2833
+ getStats(): WorkerPoolStats;
2834
+ /**
2835
+ * Terminate all workers
2836
+ */
2837
+ terminate(): Promise<void>;
2838
+ }
2839
+ /**
2840
+ * Create a worker pool instance
2841
+ */
2842
+ declare function createWorkerPool(config?: WorkerPoolConfig): WorkerPool;
2843
+ //#endregion
2844
+ //#region src/batch/BatchProcessor.d.ts
2845
+ /**
2846
+ * Batch processing options
2847
+ */
2848
+ interface BatchOptions {
2849
+ /** Enable parallel processing (default: false) */
2850
+ parallel?: boolean;
2851
+ /** Maximum concurrency for parallel processing (default: 4) */
2852
+ maxConcurrency?: number;
2853
+ /** Progress callback */
2854
+ onProgress?: (completed: number, total: number) => void;
2855
+ }
2856
+ /**
2857
+ * Batch processing result
2858
+ */
2859
+ interface BatchResult {
2860
+ /** Individual results for each document */
2861
+ results: DetectionResult[];
2862
+ /** Total processing stats */
2863
+ stats: {
2864
+ /** Total documents processed */totalDocuments: number; /** Total PII detections across all documents */
2865
+ totalDetections: number; /** Total processing time in milliseconds */
2866
+ totalTime: number; /** Average time per document */
2867
+ avgTimePerDocument: number;
2868
+ };
2869
+ }
2870
+ /**
2871
+ * Batch processor for processing multiple documents
2872
+ */
2873
+ declare class BatchProcessor {
2874
+ private detector;
2875
+ constructor(detector: OpenRedaction);
2876
+ /**
2877
+ * Process multiple documents sequentially
2878
+ */
2879
+ processSequential(documents: string[], options?: BatchOptions): Promise<BatchResult>;
2880
+ /**
2881
+ * Process multiple documents in parallel
2882
+ */
2883
+ processParallel(documents: string[], options?: BatchOptions): Promise<BatchResult>;
2884
+ /**
2885
+ * Process multiple documents (automatically chooses sequential or parallel)
2886
+ */
2887
+ process(documents: string[], options?: BatchOptions): Promise<BatchResult>;
2888
+ /**
2889
+ * Process documents with automatic batching
2890
+ * Useful for very large arrays of documents
2891
+ */
2892
+ processStream(documents: string[], batchSize?: number): AsyncGenerator<DetectionResult, void, undefined>;
2893
+ /**
2894
+ * Get aggregated statistics across multiple results
2895
+ */
2896
+ getAggregatedStats(results: DetectionResult[]): {
2897
+ totalDetections: number;
2898
+ detectionsByType: Record<string, number>;
2899
+ detectionsBySeverity: Record<string, number>;
2900
+ avgConfidence: number;
2901
+ };
2902
+ }
2903
+ /**
2904
+ * Helper to create a batch processor
2905
+ */
2906
+ declare function createBatchProcessor(detector: OpenRedaction): BatchProcessor;
2907
+ //#endregion
2908
+ //#region src/integrations/express.d.ts
2909
+ /**
2910
+ * Middleware options
2911
+ */
2912
+ interface OpenRedactionMiddlewareOptions extends OpenRedactionOptions {
2913
+ /** Auto-redact request body (default: false) */
2914
+ autoRedact?: boolean;
2915
+ /** Fields to check in request body (default: all) */
2916
+ fields?: string[];
2917
+ /** Skip detection for certain routes (regex patterns) */
2918
+ skipRoutes?: RegExp[];
2919
+ /** Add PII detection results to request object (default: true) */
2920
+ attachResults?: boolean;
2921
+ /** Custom handler for PII detection */
2922
+ onDetection?: (req: Request, result: DetectionResult) => void;
2923
+ /** Fail request if PII detected (default: false) */
2924
+ failOnPII?: boolean;
2925
+ /** Add response headers with PII info (default: false) */
2926
+ addHeaders?: boolean;
2927
+ }
2928
+ /**
2929
+ * Extended Express Request with PII detection results
2930
+ */
2931
+ interface OpenRedactionRequest extends Request {
2932
+ pii?: {
2933
+ detected: boolean;
2934
+ count: number;
2935
+ result: DetectionResult;
2936
+ redacted?: any;
2937
+ };
2938
+ }
2939
+ /**
2940
+ * Create Express middleware for PII detection
2941
+ */
2942
+ declare function openredactionMiddleware(options?: OpenRedactionMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void | Response<any, Record<string, any>>>;
2943
+ /**
2944
+ * Express route handler for PII detection
2945
+ */
2946
+ declare function detectPII(options?: OpenRedactionOptions): (req: Request, res: Response) => Promise<void>;
2947
+ /**
2948
+ * Express route handler for generating reports
2949
+ */
2950
+ declare function generateReport(options?: OpenRedactionOptions): (req: Request, res: Response) => Promise<void>;
2951
+ //#endregion
2952
+ //#region src/errors/OpenRedactionError.d.ts
2953
+ /**
2954
+ * Custom error class for OpenRedaction with helpful messages and suggestions
2955
+ */
2956
+ interface ErrorSuggestion {
2957
+ message: string;
2958
+ code?: string;
2959
+ docs?: string;
2960
+ }
2961
+ declare class OpenRedactionError extends Error {
2962
+ code: string;
2963
+ suggestion?: ErrorSuggestion;
2964
+ context?: Record<string, unknown>;
2965
+ constructor(message: string, code?: string, suggestion?: ErrorSuggestion, context?: Record<string, unknown>);
2966
+ /**
2967
+ * Get formatted error message with suggestions
2968
+ */
2969
+ getFormattedMessage(): string;
2970
+ }
2971
+ /**
2972
+ * Factory functions for common error scenarios
2973
+ */
2974
+ declare function createInvalidPatternError(patternType: string, reason: string): OpenRedactionError;
2975
+ declare function createValidationError(value: string, patternType: string): OpenRedactionError;
2976
+ declare function createHighMemoryError(textSize: number): OpenRedactionError;
2977
+ declare function createConfigLoadError(path: string, reason: string): OpenRedactionError;
2978
+ declare function createLearningDisabledError(): OpenRedactionError;
2979
+ declare function createOptimizationDisabledError(): OpenRedactionError;
2980
+ declare function createMultiPassDisabledError(): OpenRedactionError;
2981
+ declare function createCacheDisabledError(): OpenRedactionError;
2982
+ //#endregion
2983
+ //#region src/tenancy/TenantManager.d.ts
2984
+ /**
2985
+ * Tenant configuration
2986
+ */
2987
+ interface TenantConfig {
2988
+ /** Tenant unique identifier */
2989
+ tenantId: string;
2990
+ /** Tenant display name */
2991
+ name: string;
2992
+ /** Tenant-specific OpenRedaction options */
2993
+ options?: OpenRedactionOptions;
2994
+ /** Tenant-specific custom patterns */
2995
+ customPatterns?: PIIPattern[];
2996
+ /** Tenant-specific whitelist */
2997
+ whitelist?: string[];
2998
+ /** Tenant quota limits */
2999
+ quotas?: TenantQuotas;
3000
+ /** Tenant API key (for authentication) */
3001
+ apiKey?: string;
3002
+ /** Tenant metadata */
3003
+ metadata?: Record<string, unknown>;
3004
+ /** Tenant status */
3005
+ status: 'active' | 'suspended' | 'trial';
3006
+ /** Trial expiry date (for trial tenants) */
3007
+ trialExpiresAt?: Date;
3008
+ /** Created timestamp */
3009
+ createdAt: Date;
3010
+ /** Last updated timestamp */
3011
+ updatedAt: Date;
3012
+ }
3013
+ /**
3014
+ * Tenant quota limits
3015
+ */
3016
+ interface TenantQuotas {
3017
+ /** Maximum requests per month (undefined = unlimited) */
3018
+ maxRequestsPerMonth?: number;
3019
+ /** Maximum text length per request (characters) */
3020
+ maxTextLength?: number;
3021
+ /** Maximum patterns allowed */
3022
+ maxPatterns?: number;
3023
+ /** Maximum audit logs to retain */
3024
+ maxAuditLogs?: number;
3025
+ /** Rate limit: requests per minute */
3026
+ rateLimit?: number;
3027
+ }
3028
+ /**
3029
+ * Tenant usage statistics
3030
+ */
3031
+ interface TenantUsage {
3032
+ /** Tenant ID */
3033
+ tenantId: string;
3034
+ /** Total requests this month */
3035
+ requestsThisMonth: number;
3036
+ /** Total text processed this month (characters) */
3037
+ textProcessedThisMonth: number;
3038
+ /** Total PII detected this month */
3039
+ piiDetectedThisMonth: number;
3040
+ /** Last request timestamp */
3041
+ lastRequestAt?: Date;
3042
+ /** Monthly usage reset date */
3043
+ monthlyResetDate: Date;
3044
+ }
3045
+ /**
3046
+ * Tenant quota exceeded error
3047
+ */
3048
+ declare class TenantQuotaExceededError extends Error {
3049
+ tenantId: string;
3050
+ quota: string;
3051
+ limit: number;
3052
+ current: number;
3053
+ constructor(tenantId: string, quota: string, limit: number, current: number);
3054
+ }
3055
+ /**
3056
+ * Tenant not found error
3057
+ */
3058
+ declare class TenantNotFoundError extends Error {
3059
+ tenantId: string;
3060
+ constructor(tenantId: string);
3061
+ }
3062
+ /**
3063
+ * Tenant suspended error
3064
+ */
3065
+ declare class TenantSuspendedError extends Error {
3066
+ tenantId: string;
3067
+ constructor(tenantId: string);
3068
+ }
3069
+ /**
3070
+ * Multi-tenant manager for SaaS deployments
3071
+ */
3072
+ declare class TenantManager {
3073
+ private tenants;
3074
+ private usage;
3075
+ private detectors;
3076
+ private rateLimitTracking;
3077
+ private auditLoggers;
3078
+ private metricsCollectors;
3079
+ /**
3080
+ * Register a new tenant
3081
+ */
3082
+ registerTenant(config: Omit<TenantConfig, 'createdAt' | 'updatedAt'>): TenantConfig;
3083
+ /**
3084
+ * Update tenant configuration
3085
+ */
3086
+ updateTenant(tenantId: string, updates: Partial<Omit<TenantConfig, 'tenantId' | 'createdAt'>>): TenantConfig;
3087
+ /**
3088
+ * Get tenant configuration
3089
+ */
3090
+ getTenantConfig(tenantId: string): TenantConfig;
3091
+ /**
3092
+ * Get or create tenant-specific detector instance
3093
+ */
3094
+ getDetector(tenantId: string): OpenRedaction;
3095
+ /**
3096
+ * Perform detection with tenant isolation and quota checks
3097
+ */
3098
+ detect(tenantId: string, text: string): Promise<any>;
3099
+ /**
3100
+ * Validate tenant status (active, trial expiry)
3101
+ */
3102
+ private validateTenantStatus;
3103
+ /**
3104
+ * Check tenant quotas before processing
3105
+ */
3106
+ private checkQuotas;
3107
+ /**
3108
+ * Track request for usage and rate limiting
3109
+ */
3110
+ private trackRequest;
3111
+ /**
3112
+ * Get number of requests in last minute
3113
+ */
3114
+ private getRequestsInLastMinute;
3115
+ /**
3116
+ * Reset monthly usage statistics
3117
+ */
3118
+ private resetMonthlyUsage;
3119
+ /**
3120
+ * Get next monthly reset date (1st of next month)
3121
+ */
3122
+ private getNextMonthlyResetDate;
3123
+ /**
3124
+ * Get tenant usage statistics
3125
+ */
3126
+ getTenantUsage(tenantId: string): TenantUsage;
3127
+ /**
3128
+ * Get all tenants
3129
+ */
3130
+ getAllTenants(): TenantConfig[];
3131
+ /**
3132
+ * Get tenants by status
3133
+ */
3134
+ getTenantsByStatus(status: TenantConfig['status']): TenantConfig[];
3135
+ /**
3136
+ * Authenticate tenant by API key
3137
+ */
3138
+ authenticateByApiKey(apiKey: string): TenantConfig | null;
3139
+ /**
3140
+ * Suspend a tenant
3141
+ */
3142
+ suspendTenant(tenantId: string): void;
3143
+ /**
3144
+ * Activate a tenant
3145
+ */
3146
+ activateTenant(tenantId: string): void;
3147
+ /**
3148
+ * Delete a tenant and all associated data
3149
+ */
3150
+ deleteTenant(tenantId: string): void;
3151
+ /**
3152
+ * Set tenant-specific audit logger
3153
+ */
3154
+ setAuditLogger(tenantId: string, logger: IAuditLogger): void;
3155
+ /**
3156
+ * Get tenant-specific audit logger
3157
+ */
3158
+ getAuditLogger(tenantId: string): IAuditLogger | undefined;
3159
+ /**
3160
+ * Set tenant-specific metrics collector
3161
+ */
3162
+ setMetricsCollector(tenantId: string, collector: IMetricsCollector): void;
3163
+ /**
3164
+ * Get tenant-specific metrics collector
3165
+ */
3166
+ getMetricsCollector(tenantId: string): IMetricsCollector | undefined;
3167
+ /**
3168
+ * Get aggregate statistics across all tenants
3169
+ */
3170
+ getAggregateStats(): {
3171
+ totalTenants: number;
3172
+ activeTenants: number;
3173
+ trialTenants: number;
3174
+ suspendedTenants: number;
3175
+ totalRequestsThisMonth: number;
3176
+ totalTextProcessedThisMonth: number;
3177
+ totalPiiDetectedThisMonth: number;
3178
+ };
3179
+ /**
3180
+ * Validate tenant exists
3181
+ */
3182
+ private validateTenantExists;
3183
+ /**
3184
+ * Export tenant configuration as JSON
3185
+ */
3186
+ exportTenantConfig(tenantId: string): string;
3187
+ /**
3188
+ * Import tenant configuration from JSON
3189
+ */
3190
+ importTenantConfig(json: string): TenantConfig;
3191
+ }
3192
+ /**
3193
+ * Create a tenant manager instance
3194
+ */
3195
+ declare function createTenantManager(): TenantManager;
3196
+ /**
3197
+ * Default tenant quotas for different tiers
3198
+ */
3199
+ declare const DEFAULT_TIER_QUOTAS: {
3200
+ readonly free: {
3201
+ readonly maxRequestsPerMonth: 1000;
3202
+ readonly maxTextLength: 10000;
3203
+ readonly maxPatterns: 10;
3204
+ readonly maxAuditLogs: 100;
3205
+ readonly rateLimit: 10;
3206
+ };
3207
+ readonly starter: {
3208
+ readonly maxRequestsPerMonth: 10000;
3209
+ readonly maxTextLength: 50000;
3210
+ readonly maxPatterns: 50;
3211
+ readonly maxAuditLogs: 1000;
3212
+ readonly rateLimit: 50;
3213
+ };
3214
+ readonly professional: {
3215
+ readonly maxRequestsPerMonth: 100000;
3216
+ readonly maxTextLength: 100000;
3217
+ readonly maxPatterns: 200;
3218
+ readonly maxAuditLogs: 10000;
3219
+ readonly rateLimit: 200;
3220
+ };
3221
+ readonly enterprise: {
3222
+ readonly maxRequestsPerMonth: undefined;
3223
+ readonly maxTextLength: undefined;
3224
+ readonly maxPatterns: undefined;
3225
+ readonly maxAuditLogs: undefined;
3226
+ readonly rateLimit: undefined;
3227
+ };
3228
+ };
3229
+ //#endregion
3230
+ //#region src/webhooks/WebhookManager.d.ts
3231
+ /**
3232
+ * Webhook event types
3233
+ */
3234
+ type WebhookEventType = 'pii.detected.high_risk' | 'pii.detected.bulk' | 'pii.processing.failed' | 'pii.processing.slow' | 'quota.exceeded' | 'tenant.suspended' | 'audit.tamper_detected' | 'custom';
3235
+ /**
3236
+ * Webhook event payload
3237
+ */
3238
+ interface WebhookEvent {
3239
+ /** Event unique ID */
3240
+ id: string;
3241
+ /** Event type */
3242
+ type: WebhookEventType;
3243
+ /** Event timestamp (ISO 8601) */
3244
+ timestamp: string;
3245
+ /** Event severity */
3246
+ severity: 'critical' | 'high' | 'medium' | 'low' | 'info';
3247
+ /** Event data */
3248
+ data: Record<string, unknown>;
3249
+ /** Source identifier (e.g., tenant ID) */
3250
+ source?: string;
3251
+ /** Custom metadata */
3252
+ metadata?: Record<string, unknown>;
3253
+ }
3254
+ /**
3255
+ * Webhook configuration
3256
+ */
3257
+ interface WebhookConfig {
3258
+ /** Webhook unique ID */
3259
+ id: string;
3260
+ /** Webhook URL to POST events to */
3261
+ url: string;
3262
+ /** Event types to subscribe to (empty = all events) */
3263
+ events?: WebhookEventType[];
3264
+ /** Minimum severity to trigger webhook */
3265
+ minSeverity?: 'critical' | 'high' | 'medium' | 'low' | 'info';
3266
+ /** Custom headers to include in requests */
3267
+ headers?: Record<string, string>;
3268
+ /** Secret for HMAC signature (optional but recommended) */
3269
+ secret?: string;
3270
+ /** Enable webhook (default: true) */
3271
+ enabled?: boolean;
3272
+ /** Retry configuration */
3273
+ retry?: {
3274
+ /** Maximum retry attempts (default: 3) */maxAttempts?: number; /** Initial delay in ms (default: 1000) */
3275
+ initialDelay?: number; /** Maximum delay in ms (default: 60000) */
3276
+ maxDelay?: number; /** Backoff multiplier (default: 2) */
3277
+ backoffMultiplier?: number;
3278
+ };
3279
+ /** Timeout in ms (default: 5000) */
3280
+ timeout?: number;
3281
+ /** Tenant ID (for multi-tenant setups) */
3282
+ tenantId?: string;
3283
+ }
3284
+ /**
3285
+ * Webhook delivery status
3286
+ */
3287
+ type WebhookDeliveryStatus = 'pending' | 'success' | 'failed' | 'circuit_open';
3288
+ /**
3289
+ * Webhook delivery record
3290
+ */
3291
+ interface WebhookDelivery {
3292
+ /** Delivery ID */
3293
+ id: string;
3294
+ /** Webhook ID */
3295
+ webhookId: string;
3296
+ /** Event that was delivered */
3297
+ event: WebhookEvent;
3298
+ /** Delivery status */
3299
+ status: WebhookDeliveryStatus;
3300
+ /** HTTP status code */
3301
+ statusCode?: number;
3302
+ /** Delivery timestamp */
3303
+ timestamp: Date;
3304
+ /** Attempt number */
3305
+ attempt: number;
3306
+ /** Error message if failed */
3307
+ error?: string;
3308
+ /** Response body */
3309
+ responseBody?: string;
3310
+ /** Delivery duration in ms */
3311
+ durationMs?: number;
3312
+ }
3313
+ /**
3314
+ * Webhook statistics
3315
+ */
3316
+ interface WebhookStats {
3317
+ /** Webhook ID */
3318
+ webhookId: string;
3319
+ /** Total deliveries */
3320
+ totalDeliveries: number;
3321
+ /** Successful deliveries */
3322
+ successfulDeliveries: number;
3323
+ /** Failed deliveries */
3324
+ failedDeliveries: number;
3325
+ /** Average delivery time in ms */
3326
+ avgDeliveryTimeMs: number;
3327
+ /** Last delivery time */
3328
+ lastDeliveryTime?: Date;
3329
+ /** Circuit breaker state */
3330
+ circuitState: 'closed' | 'open' | 'half_open';
3331
+ }
3332
+ /**
3333
+ * Webhook Manager
3334
+ * Manages webhook subscriptions, delivery, retries, and circuit breaking
3335
+ */
3336
+ declare class WebhookManager {
3337
+ private webhooks;
3338
+ private deliveryHistory;
3339
+ private circuitBreakers;
3340
+ private pendingRetries;
3341
+ private maxHistorySize;
3342
+ private readonly FAILURE_THRESHOLD;
3343
+ private readonly RESET_TIMEOUT_MS;
3344
+ constructor(options?: {
3345
+ maxHistorySize?: number;
3346
+ });
3347
+ /**
3348
+ * Register a webhook
3349
+ */
3350
+ registerWebhook(config: WebhookConfig): void;
3351
+ /**
3352
+ * Update webhook configuration
3353
+ */
3354
+ updateWebhook(id: string, updates: Partial<Omit<WebhookConfig, 'id'>>): void;
3355
+ /**
3356
+ * Delete webhook
3357
+ */
3358
+ deleteWebhook(id: string): void;
3359
+ /**
3360
+ * Get webhook configuration
3361
+ */
3362
+ getWebhook(id: string): WebhookConfig | undefined;
3363
+ /**
3364
+ * Get all webhooks
3365
+ */
3366
+ getAllWebhooks(): WebhookConfig[];
3367
+ /**
3368
+ * Emit an event to all subscribed webhooks
3369
+ */
3370
+ emitEvent(event: Omit<WebhookEvent, 'id' | 'timestamp'>): Promise<void>;
3371
+ /**
3372
+ * Emit high-risk PII detection event
3373
+ */
3374
+ emitHighRiskPII(result: DetectionResult, tenantId?: string): Promise<void>;
3375
+ /**
3376
+ * Emit bulk PII detection event
3377
+ */
3378
+ emitBulkPII(result: DetectionResult, threshold?: number, tenantId?: string): Promise<void>;
3379
+ /**
3380
+ * Emit processing error event
3381
+ */
3382
+ emitProcessingError(error: Error, tenantId?: string): Promise<void>;
3383
+ /**
3384
+ * Emit slow processing event
3385
+ */
3386
+ emitSlowProcessing(durationMs: number, threshold?: number, tenantId?: string): Promise<void>;
3387
+ /**
3388
+ * Find webhooks that match the event
3389
+ */
3390
+ private findMatchingWebhooks;
3391
+ /**
3392
+ * Deliver webhook with retry logic
3393
+ */
3394
+ private deliverWebhook;
3395
+ /**
3396
+ * Make HTTP request to webhook URL
3397
+ */
3398
+ private makeHttpRequest;
3399
+ /**
3400
+ * Calculate HMAC signature for webhook verification
3401
+ */
3402
+ private calculateHmacSignature;
3403
+ /**
3404
+ * Calculate retry delay with exponential backoff
3405
+ */
3406
+ private calculateRetryDelay;
3407
+ /**
3408
+ * Record delivery in history
3409
+ */
3410
+ private recordDelivery;
3411
+ /**
3412
+ * Get delivery history for a webhook
3413
+ */
3414
+ getDeliveryHistory(webhookId: string, limit?: number): WebhookDelivery[];
3415
+ /**
3416
+ * Get webhook statistics
3417
+ */
3418
+ getWebhookStats(webhookId: string): WebhookStats;
3419
+ /**
3420
+ * Get aggregate statistics for all webhooks
3421
+ */
3422
+ getAggregateStats(): {
3423
+ totalWebhooks: number;
3424
+ enabledWebhooks: number;
3425
+ totalDeliveries: number;
3426
+ successfulDeliveries: number;
3427
+ failedDeliveries: number;
3428
+ avgDeliveryTimeMs: number;
3429
+ };
3430
+ /**
3431
+ * Clear delivery history
3432
+ */
3433
+ clearHistory(): void;
3434
+ /**
3435
+ * Generate unique ID
3436
+ */
3437
+ private generateId;
3438
+ }
3439
+ /**
3440
+ * Create a webhook manager instance
3441
+ */
3442
+ declare function createWebhookManager(options?: {
3443
+ maxHistorySize?: number;
3444
+ }): WebhookManager;
3445
+ /**
3446
+ * Verify webhook HMAC signature
3447
+ */
3448
+ declare function verifyWebhookSignature(payload: string, signature: string, secret: string, algorithm?: 'sha256' | 'sha512'): boolean;
3449
+ //#endregion
3450
+ //#region src/api/APIServer.d.ts
3451
+ /**
3452
+ * API Server configuration
3453
+ */
3454
+ interface APIServerConfig {
3455
+ /** Server port (default: 3000) */
3456
+ port?: number;
3457
+ /** Server host (default: '0.0.0.0') */
3458
+ host?: string;
3459
+ /** Enable CORS (default: true) */
3460
+ enableCors?: boolean;
3461
+ /** CORS origin (default: '*') */
3462
+ corsOrigin?: string | string[];
3463
+ /** API key for authentication (optional) */
3464
+ apiKey?: string;
3465
+ /** Enable rate limiting (default: true) */
3466
+ enableRateLimit?: boolean;
3467
+ /** Rate limit: requests per minute (default: 60) */
3468
+ rateLimit?: number;
3469
+ /** Request body size limit (default: '10mb') */
3470
+ bodyLimit?: string;
3471
+ /** Enable request logging (default: true) */
3472
+ enableLogging?: boolean;
3473
+ /** Tenant manager (for multi-tenant mode) */
3474
+ tenantManager?: TenantManager;
3475
+ /** Webhook manager */
3476
+ webhookManager?: WebhookManager;
3477
+ /** Persistent audit logger */
3478
+ auditLogger?: PersistentAuditLogger;
3479
+ /** Prometheus server */
3480
+ prometheusServer?: PrometheusServer;
3481
+ /** Default OpenRedaction options (for non-tenant mode) */
3482
+ defaultOptions?: OpenRedactionOptions;
3483
+ }
3484
+ /**
3485
+ * API request with authentication
3486
+ */
3487
+ interface APIRequest {
3488
+ /** Request body */
3489
+ body: any;
3490
+ /** Headers */
3491
+ headers: Record<string, string | string[] | undefined>;
3492
+ /** Query parameters */
3493
+ query: Record<string, string | string[] | undefined>;
3494
+ /** Path parameters */
3495
+ params: Record<string, string>;
3496
+ /** Authenticated tenant ID (if multi-tenant) */
3497
+ tenantId?: string;
3498
+ /** Client IP address */
3499
+ ip?: string;
3500
+ }
3501
+ /**
3502
+ * API response
3503
+ */
3504
+ interface APIResponse {
3505
+ /** Status code */
3506
+ status: number;
3507
+ /** Response body */
3508
+ body: any;
3509
+ /** Headers */
3510
+ headers?: Record<string, string>;
3511
+ }
3512
+ /**
3513
+ * REST API Server
3514
+ * Lightweight HTTP server for OpenRedaction with Express-like interface
3515
+ */
3516
+ declare class APIServer {
3517
+ private server?;
3518
+ private config;
3519
+ private detector?;
3520
+ private isRunning;
3521
+ private rateLimitTracking;
3522
+ constructor(config?: APIServerConfig);
3523
+ /**
3524
+ * Start the API server
3525
+ */
3526
+ start(): Promise<void>;
3527
+ /**
3528
+ * Stop the server
3529
+ */
3530
+ stop(): Promise<void>;
3531
+ /**
3532
+ * Handle incoming HTTP requests
3533
+ */
3534
+ private handleRequest;
3535
+ /**
3536
+ * Parse HTTP request
3537
+ */
3538
+ private parseRequest;
3539
+ /**
3540
+ * Parse request body
3541
+ */
3542
+ private parseBody;
3543
+ /**
3544
+ * Route request to appropriate handler
3545
+ */
3546
+ private routeRequest;
3547
+ /**
3548
+ * Handle POST /api/detect
3549
+ */
3550
+ private handleDetect;
3551
+ /**
3552
+ * Handle POST /api/redact
3553
+ */
3554
+ private handleRedact;
3555
+ /**
3556
+ * Handle POST /api/restore
3557
+ */
3558
+ private handleRestore;
3559
+ /**
3560
+ * Handle GET /api/audit/logs
3561
+ */
3562
+ private handleAuditLogs;
3563
+ /**
3564
+ * Handle GET /api/audit/stats
3565
+ */
3566
+ private handleAuditStats;
3567
+ /**
3568
+ * Handle GET /api/metrics
3569
+ */
3570
+ private handleMetrics;
3571
+ /**
3572
+ * Handle GET /api/patterns
3573
+ */
3574
+ private handleGetPatterns;
3575
+ /**
3576
+ * Handle GET /api/health
3577
+ */
3578
+ private handleHealth;
3579
+ /**
3580
+ * Handle GET /api/docs
3581
+ */
3582
+ private handleDocs;
3583
+ /**
3584
+ * Handle GET /
3585
+ */
3586
+ private handleRoot;
3587
+ /**
3588
+ * Send HTTP response
3589
+ */
3590
+ private sendResponse;
3591
+ /**
3592
+ * Check rate limit
3593
+ */
3594
+ private checkRateLimit;
3595
+ }
3596
+ /**
3597
+ * Create an API server instance
3598
+ */
3599
+ declare function createAPIServer(config?: APIServerConfig): APIServer;
3600
+ //#endregion
3601
+ //#region src/config/ConfigExporter.d.ts
3602
+ interface ExportedConfig {
3603
+ version: string;
3604
+ timestamp: string;
3605
+ options: {
3606
+ includeNames?: boolean;
3607
+ includeAddresses?: boolean;
3608
+ includePhones?: boolean;
3609
+ includeEmails?: boolean;
3610
+ patterns?: string[];
3611
+ categories?: string[];
3612
+ whitelist?: string[];
3613
+ deterministic?: boolean;
3614
+ redactionMode?: string;
3615
+ preset?: string;
3616
+ enableContextAnalysis?: boolean;
3617
+ confidenceThreshold?: number;
3618
+ enableFalsePositiveFilter?: boolean;
3619
+ falsePositiveThreshold?: number;
3620
+ enableMultiPass?: boolean;
3621
+ multiPassCount?: number;
3622
+ enableCache?: boolean;
3623
+ cacheSize?: number;
3624
+ maxInputSize?: number;
3625
+ regexTimeout?: number;
3626
+ };
3627
+ customPatterns?: Array<{
3628
+ type: string;
3629
+ regex: string;
3630
+ flags: string;
3631
+ priority: number;
3632
+ placeholder: string;
3633
+ description?: string;
3634
+ severity?: string;
3635
+ }>;
3636
+ metadata?: {
3637
+ description?: string;
3638
+ author?: string;
3639
+ tags?: string[];
3640
+ };
3641
+ }
3642
+ declare class ConfigExporter {
3643
+ private static readonly CONFIG_VERSION;
3644
+ /**
3645
+ * Export configuration to JSON
3646
+ */
3647
+ static exportConfig(options: OpenRedactionOptions & {
3648
+ categories?: string[];
3649
+ maxInputSize?: number;
3650
+ regexTimeout?: number;
3651
+ }, metadata?: {
3652
+ description?: string;
3653
+ author?: string;
3654
+ tags?: string[];
3655
+ }): ExportedConfig;
3656
+ /**
3657
+ * Import configuration from JSON
3658
+ */
3659
+ static importConfig(exported: ExportedConfig, _options?: {
3660
+ mergeWithDefaults?: boolean;
3661
+ validatePatterns?: boolean;
3662
+ }): OpenRedactionOptions & {
3663
+ categories?: string[];
3664
+ maxInputSize?: number;
3665
+ regexTimeout?: number;
3666
+ };
3667
+ /**
3668
+ * Export configuration to JSON string
3669
+ */
3670
+ static exportToString(options: OpenRedactionOptions & {
3671
+ categories?: string[];
3672
+ maxInputSize?: number;
3673
+ regexTimeout?: number;
3674
+ }, metadata?: {
3675
+ description?: string;
3676
+ author?: string;
3677
+ tags?: string[];
3678
+ }, pretty?: boolean): string;
3679
+ /**
3680
+ * Import configuration from JSON string
3681
+ */
3682
+ static importFromString(json: string): OpenRedactionOptions & {
3683
+ categories?: string[];
3684
+ maxInputSize?: number;
3685
+ regexTimeout?: number;
3686
+ };
3687
+ /**
3688
+ * Export configuration to file (Node.js only)
3689
+ */
3690
+ static exportToFile(filePath: string, options: OpenRedactionOptions & {
3691
+ categories?: string[];
3692
+ maxInputSize?: number;
3693
+ regexTimeout?: number;
3694
+ }, metadata?: {
3695
+ description?: string;
3696
+ author?: string;
3697
+ tags?: string[];
3698
+ }): Promise<void>;
3699
+ /**
3700
+ * Import configuration from file (Node.js only)
3701
+ */
3702
+ static importFromFile(filePath: string): Promise<OpenRedactionOptions & {
3703
+ categories?: string[];
3704
+ maxInputSize?: number;
3705
+ regexTimeout?: number;
3706
+ }>;
3707
+ /**
3708
+ * Validate exported config structure
3709
+ */
3710
+ static validateConfig(exported: ExportedConfig): {
3711
+ valid: boolean;
3712
+ errors: string[];
3713
+ };
3714
+ /**
3715
+ * Merge two configurations (useful for extending base configs)
3716
+ */
3717
+ static mergeConfigs(base: ExportedConfig, override: ExportedConfig): ExportedConfig;
3718
+ }
3719
+ /**
3720
+ * Convenience functions for common use cases
3721
+ */
3722
+ /**
3723
+ * Create a shareable config preset
3724
+ */
3725
+ declare function createConfigPreset(name: string, description: string, options: OpenRedactionOptions & {
3726
+ categories?: string[];
3727
+ maxInputSize?: number;
3728
+ regexTimeout?: number;
3729
+ }): string;
3730
+ /**
3731
+ * Quick export for version control
3732
+ */
3733
+ declare function exportForVersionControl(options: OpenRedactionOptions & {
3734
+ categories?: string[];
3735
+ maxInputSize?: number;
3736
+ regexTimeout?: number;
3737
+ }): string;
3738
+ //#endregion
3739
+ //#region src/health/HealthCheck.d.ts
3740
+ interface HealthCheckResult {
3741
+ status: 'healthy' | 'degraded' | 'unhealthy';
3742
+ timestamp: string;
3743
+ checks: {
3744
+ detector: HealthCheckStatus;
3745
+ patterns: HealthCheckStatus;
3746
+ performance: HealthCheckStatus;
3747
+ memory: HealthCheckStatus;
3748
+ };
3749
+ metrics: {
3750
+ totalPatterns: number;
3751
+ compiledPatterns: number;
3752
+ cacheSize?: number;
3753
+ cacheEnabled: boolean;
3754
+ uptime: number;
3755
+ };
3756
+ errors: string[];
3757
+ warnings: string[];
3758
+ }
3759
+ interface HealthCheckStatus {
3760
+ status: 'pass' | 'warn' | 'fail';
3761
+ message: string;
3762
+ value?: any;
3763
+ threshold?: any;
3764
+ }
3765
+ interface HealthCheckOptions {
3766
+ testDetection?: boolean;
3767
+ checkPerformance?: boolean;
3768
+ performanceThreshold?: number;
3769
+ memoryThreshold?: number;
3770
+ }
3771
+ declare class HealthChecker {
3772
+ private detector;
3773
+ private initTime;
3774
+ constructor(detector: OpenRedaction);
3775
+ /**
3776
+ * Run complete health check
3777
+ */
3778
+ check(options?: HealthCheckOptions): Promise<HealthCheckResult>;
3779
+ /**
3780
+ * Check detector functionality
3781
+ */
3782
+ private checkDetector;
3783
+ /**
3784
+ * Check patterns are loaded
3785
+ */
3786
+ private checkPatterns;
3787
+ /**
3788
+ * Check performance
3789
+ */
3790
+ private checkPerformance;
3791
+ /**
3792
+ * Check memory usage
3793
+ */
3794
+ private checkMemory;
3795
+ /**
3796
+ * Collect metrics
3797
+ */
3798
+ private collectMetrics;
3799
+ /**
3800
+ * Determine overall status
3801
+ */
3802
+ private determineOverallStatus;
3803
+ /**
3804
+ * Quick health check (minimal overhead)
3805
+ */
3806
+ quickCheck(): Promise<{
3807
+ status: 'healthy' | 'unhealthy';
3808
+ message: string;
3809
+ }>;
3810
+ /**
3811
+ * Get system info for debugging
3812
+ */
3813
+ getSystemInfo(): {
3814
+ version: string;
3815
+ patterns: {
3816
+ total: number;
3817
+ types: number;
3818
+ };
3819
+ cache: {
3820
+ enabled: boolean;
3821
+ size: number;
3822
+ maxSize: number;
3823
+ };
3824
+ uptime: number;
3825
+ timestamp: string;
3826
+ };
3827
+ }
3828
+ /**
3829
+ * Create health checker for a detector
3830
+ */
3831
+ declare function createHealthChecker(detector: OpenRedaction): HealthChecker;
3832
+ /**
3833
+ * Express middleware for health check endpoint
3834
+ */
3835
+ declare function healthCheckMiddleware(detector: OpenRedaction): (_req: any, res: any) => Promise<void>;
3836
+ //#endregion
3837
+ //#region src/utils/safe-regex.d.ts
3838
+ /**
3839
+ * Safe regex execution utilities with ReDoS protection
3840
+ * Zero-dependency implementation using time-based checks
3841
+ */
3842
+ interface SafeRegexOptions {
3843
+ timeout?: number;
3844
+ maxMatches?: number;
3845
+ }
3846
+ declare class RegexTimeoutError extends Error {
3847
+ constructor(pattern: string, timeout: number);
3848
+ }
3849
+ declare class RegexMaxMatchesError extends Error {
3850
+ constructor(pattern: string, maxMatches: number);
3851
+ }
3852
+ /**
3853
+ * Safely execute regex with timeout protection
3854
+ * Uses periodic time checks to prevent catastrophic backtracking
3855
+ *
3856
+ * Note: Does NOT reset lastIndex - caller is responsible for managing state
3857
+ */
3858
+ declare function safeExec(regex: RegExp, text: string, options?: SafeRegexOptions): RegExpExecArray | null;
3859
+ /**
3860
+ * Safely execute regex.exec() in a loop with timeout and match limit protection
3861
+ * Returns all matches or throws on timeout/limit exceeded
3862
+ */
3863
+ declare function safeExecAll(regex: RegExp, text: string, options?: SafeRegexOptions): RegExpExecArray[];
3864
+ /**
3865
+ * Test if a regex pattern is potentially unsafe (basic static analysis)
3866
+ * Detects common ReDoS patterns
3867
+ *
3868
+ * Note: This is a very basic heuristic check. The real protection comes from
3869
+ * the execution timeout in safeExec(). This just catches obvious mistakes.
3870
+ */
3871
+ declare function isUnsafePattern(pattern: string): boolean;
3872
+ /**
3873
+ * Validate a regex pattern before use
3874
+ * Throws error if pattern is potentially unsafe
3875
+ */
3876
+ declare function validatePattern(pattern: string | RegExp): void;
3877
+ /**
3878
+ * Compile a regex with validation and return a safe wrapper
3879
+ */
3880
+ declare function compileSafeRegex(pattern: string | RegExp, flags?: string): RegExp;
3881
+ //#endregion
3882
+ //#region src/utils/ai-assist.d.ts
3883
+ /**
3884
+ * AI endpoint response entity structure
3885
+ */
3886
+ interface AIEntity {
3887
+ type: string;
3888
+ value: string;
3889
+ start: number;
3890
+ end: number;
3891
+ confidence?: number;
3892
+ }
3893
+ /**
3894
+ * AI endpoint response structure
3895
+ */
3896
+ interface AIResponse {
3897
+ entities: AIEntity[];
3898
+ aiUsed: boolean;
3899
+ }
3900
+ /**
3901
+ * Get the AI endpoint URL from options or environment
3902
+ */
3903
+ declare function getAIEndpoint(aiOptions?: {
3904
+ enabled?: boolean;
3905
+ endpoint?: string;
3906
+ }): string | null;
3907
+ /**
3908
+ * Call the AI endpoint to get additional PII entities
3909
+ * Returns null if AI is disabled, endpoint unavailable, or on error
3910
+ */
3911
+ declare function callAIDetect(text: string, endpoint: string, debug?: boolean): Promise<AIEntity[] | null>;
3912
+ /**
3913
+ * Validate an AI entity
3914
+ */
3915
+ declare function validateAIEntity(entity: AIEntity, textLength: number): boolean;
3916
+ /**
3917
+ * Check if two detections overlap significantly
3918
+ * Returns true if they overlap by more than 50% of the shorter detection
3919
+ */
3920
+ declare function detectionsOverlap(det1: PIIDetection, det2: PIIDetection): boolean;
3921
+ /**
3922
+ * Convert AI entity to PIIDetection format
3923
+ */
3924
+ declare function convertAIEntityToDetection(entity: AIEntity, text: string): PIIDetection | null;
3925
+ /**
3926
+ * Merge AI entities with regex detections
3927
+ * Prefers regex detections on conflicts
3928
+ */
3929
+ declare function mergeAIEntities(regexDetections: PIIDetection[], aiEntities: AIEntity[], text: string): PIIDetection[];
3930
+ //#endregion
3931
+ export { ADMIN_ROLE, type AIEntity, type AIOptions, type AIResponse, ALL_PERMISSIONS, ANALYST_ROLE, type APIRequest, type APIResponse, APIServer, type APIServerConfig, type AuditBackend, type AuditDatabaseConfig, type AuditLogEntry, type AuditQueryFilter, type AuditStats, type BatchOptions, BatchProcessor, type BatchResult, type CellMatch, type ChunkResult, type ColumnStats, ConfigExporter, ConfigLoader, ConsoleAuditLogger, type ContextAnalysis, type ContextFeatures, type ContextRulesConfig, ContextRulesEngine, type CsvDetectionResult, CsvProcessor, type CsvProcessorOptions, DEFAULT_DOMAIN_VOCABULARIES, DEFAULT_PROXIMITY_RULES, DEFAULT_SEVERITY_MAP, DEFAULT_TIER_QUOTAS, type DetectTask, type DetectionPass, type DetectionResult, type DocumentFormat, type DocumentMetadata, type DocumentOptions, DocumentProcessor, type DocumentResult, type DocumentTask, type DomainVocabulary, type ErrorSuggestion, ExplainAPI, type ExportedConfig, type FalsePositiveRule, GRAFANA_DASHBOARD_TEMPLATE, type HashedAuditLogEntry, type HealthCheckOptions, type HealthCheckResult, type HealthCheckStatus, HealthChecker, type HybridMatch, type IAuditDatabaseAdapter, type IAuditLogger, type IDocumentProcessor, type IMetricsCollector, type IMetricsExporter, type IOCRProcessor, type IRBACManager, type ImageFormat, InMemoryAuditLogger, InMemoryMetricsCollector, type JsonDetectionResult, JsonProcessor, type JsonProcessorOptions, type LearningData, type LearningStats, LocalLearningStore, type MultiPassStats, NERDetector, type NEREntityType, type NERMatch, type OCRLanguage, type OCROptions, OCRProcessor, type OCRResult, OPERATOR_ROLE, OpenRedaction, type OpenRedactionConfig, OpenRedactionError, type OpenRedactionMiddlewareOptions, type OpenRedactionOptions, type OpenRedactionRequest, type OptimizerOptions, type PIIDetection, type PIIMatch, type PIIPattern, type PatternAdjustment, type PatternMatchResult, type PatternStats, type Permission, PersistentAuditLogger, type PersistentAuditLoggerOptions, type PresetName, PriorityOptimizer, PrometheusServer, type PrometheusServerOptions, type ProximityRule, RBACManager, type RedactionMetrics, type RedactionMode, RegexMaxMatchesError, RegexTimeoutError, type ReportFormat, ReportGenerator, type ReportOptions, type ReportType, type RetentionPolicy, type RiskScore, type Role, type RoleName, SEVERITY_SCORES, type SafeRegexOptions, type SeverityClassification, SeverityClassifier, type SeverityLevel, type SheetDetectionResult, StreamingDetector, type StreamingOptions, type TenantConfig, TenantManager, TenantNotFoundError, TenantQuotaExceededError, type TenantQuotas, TenantSuspendedError, type TenantUsage, type TextExplanation, VIEWER_ROLE, type Validator, type WebhookConfig, type WebhookDelivery, type WebhookDeliveryStatus, type WebhookEvent, type WebhookEventType, WebhookManager, type WebhookStats, type WhitelistEntry, WorkerPool, type WorkerPoolConfig, type WorkerPoolStats, type WorkerResult, type WorkerTask, type XlsxDetectionResult, XlsxProcessor, type XlsxProcessorOptions, allPatterns, analyzeContextFeatures, analyzeFullContext, calculateContextConfidence, calculateRisk, callAIDetect, ccpaPreset, commonFalsePositives, compileSafeRegex, contactPatterns, convertAIEntityToDetection, createAPIServer, createBatchProcessor, createCacheDisabledError, createConfigLoadError, createConfigPreset, createContextRulesEngine, createCsvProcessor, createCustomRole, createDocumentProcessor, createExplainAPI, createHealthChecker, createHighMemoryError, createInvalidPatternError, createJsonProcessor, createLearningDisabledError, createMultiPassDisabledError, createNERDetector, createOCRProcessor, createOptimizationDisabledError, createPersistentAuditLogger, createPriorityOptimizer, createPrometheusServer, createRBACManager, createReportGenerator, createSeverityClassifier, createSimpleMultiPass, createStreamingDetector, createTenantManager, createValidationError, createWebhookManager, createWorkerPool, createXlsxProcessor, defaultPasses, detectPII, detectionsOverlap, educationPreset, exportForVersionControl, extractContext, filterFalsePositives, financePreset, financialPatterns, gdprPreset, generateReport, getAIEndpoint, getPatternsByCategory, getPredefinedRole, getPreset, getSeverity, governmentPatterns, groupPatternsByPass, healthCheckMiddleware, healthcarePreset, healthcareResearchPreset, hipaaPreset, inferDocumentType, isFalsePositive, isUnsafePattern, mergeAIEntities, mergePassDetections, networkPatterns, openredactionMiddleware, personalPatterns, safeExec, safeExecAll, transportLogisticsPreset, validateAIEntity, validateEmail, validateIBAN, validateLuhn, validateNHS, validateNINO, validateName, validatePattern, validateSSN, validateSortCode, validateUKPassport, verifyWebhookSignature };
3932
+ //# sourceMappingURL=index.d.mts.map