od-temp 1.0.4

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