@revealui/security 0.0.0-canary-20260409021642

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,1507 @@
1
+ /**
2
+ * Audit Logging System
3
+ *
4
+ * Track security-relevant events and user actions for compliance
5
+ */
6
+ type AuditEventType = 'auth.login' | 'auth.logout' | 'auth.failed_login' | 'auth.password_change' | 'auth.password_reset' | 'auth.mfa_enabled' | 'auth.mfa_disabled' | 'user.create' | 'user.update' | 'user.delete' | 'user.view' | 'data.create' | 'data.read' | 'data.update' | 'data.delete' | 'data.export' | 'permission.grant' | 'permission.revoke' | 'role.assign' | 'role.remove' | 'config.change' | 'security.violation' | 'security.alert' | 'gdpr.consent' | 'gdpr.data_request' | 'gdpr.data_deletion' | `data.${string}` | `permission.${string}` | `security.${string}` | `gdpr.${string}`;
7
+ type AuditSeverity = 'low' | 'medium' | 'high' | 'critical';
8
+ interface AuditEvent {
9
+ id: string;
10
+ timestamp: string;
11
+ type: AuditEventType;
12
+ severity: AuditSeverity;
13
+ actor: {
14
+ id: string;
15
+ type: 'user' | 'system' | 'api';
16
+ ip?: string;
17
+ userAgent?: string;
18
+ };
19
+ resource?: {
20
+ type: string;
21
+ id: string;
22
+ name?: string;
23
+ };
24
+ action: string;
25
+ result: 'success' | 'failure' | 'partial';
26
+ changes?: {
27
+ before?: Record<string, unknown>;
28
+ after?: Record<string, unknown>;
29
+ };
30
+ metadata?: Record<string, unknown>;
31
+ message?: string;
32
+ }
33
+ interface AuditQuery {
34
+ types?: AuditEventType[];
35
+ actorId?: string;
36
+ resourceType?: string;
37
+ resourceId?: string;
38
+ startDate?: Date;
39
+ endDate?: Date;
40
+ severity?: AuditSeverity[];
41
+ result?: ('success' | 'failure' | 'partial')[];
42
+ limit?: number;
43
+ offset?: number;
44
+ }
45
+ interface AuditStorage {
46
+ write(event: AuditEvent): Promise<void>;
47
+ query(query: AuditQuery): Promise<AuditEvent[]>;
48
+ count(query: AuditQuery): Promise<number>;
49
+ }
50
+ /**
51
+ * Audit logging system
52
+ */
53
+ declare class AuditSystem {
54
+ private storage;
55
+ private filters;
56
+ constructor(storage: AuditStorage);
57
+ /**
58
+ * Replace the backing storage (e.g. swap InMemory for Postgres at startup).
59
+ * Events already written to the old storage are NOT migrated.
60
+ */
61
+ setStorage(storage: AuditStorage): void;
62
+ /**
63
+ * Log audit event
64
+ */
65
+ log(event: Omit<AuditEvent, 'id' | 'timestamp'>): Promise<void>;
66
+ /**
67
+ * Log authentication event
68
+ */
69
+ logAuth(type: Extract<AuditEventType, 'auth.login' | 'auth.logout' | 'auth.failed_login' | 'auth.password_change'>, actorId: string, result: 'success' | 'failure', metadata?: Record<string, unknown>): Promise<void>;
70
+ /**
71
+ * Log data access event
72
+ */
73
+ logDataAccess(action: 'create' | 'read' | 'update' | 'delete', actorId: string, resourceType: string, resourceId: string, result: 'success' | 'failure', changes?: {
74
+ before?: Record<string, unknown>;
75
+ after?: Record<string, unknown>;
76
+ }): Promise<void>;
77
+ /**
78
+ * Log permission change
79
+ */
80
+ logPermissionChange(action: 'grant' | 'revoke', actorId: string, targetUserId: string, permission: string, result: 'success' | 'failure'): Promise<void>;
81
+ /**
82
+ * Log security event
83
+ */
84
+ logSecurityEvent(type: 'violation' | 'alert', severity: AuditSeverity, actorId: string, message: string, metadata?: Record<string, unknown>): Promise<void>;
85
+ /**
86
+ * Log GDPR event
87
+ */
88
+ logGDPREvent(type: 'consent' | 'data_request' | 'data_deletion', actorId: string, result: 'success' | 'failure', metadata?: Record<string, unknown>): Promise<void>;
89
+ /**
90
+ * Query audit logs
91
+ */
92
+ query(query: AuditQuery): Promise<AuditEvent[]>;
93
+ /**
94
+ * Count audit logs
95
+ */
96
+ count(query: AuditQuery): Promise<number>;
97
+ /**
98
+ * Add filter
99
+ */
100
+ addFilter(filter: (event: AuditEvent) => boolean): void;
101
+ /**
102
+ * Remove filter
103
+ */
104
+ removeFilter(filter: (event: AuditEvent) => boolean): void;
105
+ }
106
+ /**
107
+ * In-memory audit storage (for development)
108
+ */
109
+ declare class InMemoryAuditStorage implements AuditStorage {
110
+ private events;
111
+ private maxEvents;
112
+ constructor(maxEvents?: number);
113
+ write(event: AuditEvent): Promise<void>;
114
+ query(query: AuditQuery): Promise<AuditEvent[]>;
115
+ count(query: AuditQuery): Promise<number>;
116
+ /**
117
+ * Clear all events
118
+ */
119
+ clear(): void;
120
+ /**
121
+ * Get all events
122
+ */
123
+ getAll(): AuditEvent[];
124
+ }
125
+ /**
126
+ * Audit trail decorator
127
+ */
128
+ declare function AuditTrail(type: AuditEventType, action: string, options?: {
129
+ severity?: AuditSeverity;
130
+ captureChanges?: boolean;
131
+ resourceType?: string;
132
+ }): (_target: object, _propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
133
+ /**
134
+ * Audit middleware
135
+ */
136
+ declare function createAuditMiddleware<TRequest = unknown, TResponse = unknown>(audit: AuditSystem, getUser: (request: TRequest) => {
137
+ id: string;
138
+ ip?: string;
139
+ userAgent?: string;
140
+ }): (request: TRequest & {
141
+ method: string;
142
+ url: string;
143
+ }, next: () => Promise<TResponse & {
144
+ status?: number;
145
+ }>) => Promise<TResponse & {
146
+ status?: number;
147
+ }>;
148
+ /**
149
+ * Audit report generator
150
+ */
151
+ declare class AuditReportGenerator {
152
+ private audit;
153
+ constructor(audit: AuditSystem);
154
+ /**
155
+ * Generate security report
156
+ */
157
+ generateSecurityReport(startDate: Date, endDate: Date): Promise<{
158
+ totalEvents: number;
159
+ securityViolations: number;
160
+ failedLogins: number;
161
+ permissionChanges: number;
162
+ dataExports: number;
163
+ criticalEvents: AuditEvent[];
164
+ }>;
165
+ /**
166
+ * Generate user activity report
167
+ */
168
+ generateUserActivityReport(userId: string, startDate: Date, endDate: Date): Promise<{
169
+ totalActions: number;
170
+ actionsByType: Record<string, number>;
171
+ failedActions: number;
172
+ recentActions: AuditEvent[];
173
+ }>;
174
+ /**
175
+ * Generate compliance report
176
+ */
177
+ generateComplianceReport(startDate: Date, endDate: Date): Promise<{
178
+ dataAccesses: number;
179
+ dataModifications: number;
180
+ dataDeletions: number;
181
+ gdprRequests: number;
182
+ auditTrailComplete: boolean;
183
+ }>;
184
+ /**
185
+ * Check audit trail continuity
186
+ */
187
+ private checkAuditTrailContinuity;
188
+ }
189
+ /** Fields included in the HMAC signature for tamper detection. */
190
+ interface SignableFields {
191
+ timestamp: string;
192
+ eventType: string;
193
+ severity: string;
194
+ agentId: string;
195
+ payload: unknown;
196
+ }
197
+ /**
198
+ * Compute an HMAC-SHA256 signature over the canonical fields of an audit entry.
199
+ *
200
+ * The signature covers `timestamp`, `eventType`, `severity`, `agentId`, and
201
+ * `payload` — the immutable core of every audit record. Changing any of
202
+ * these fields after signing will cause verification to fail.
203
+ *
204
+ * @param entry - The audit entry fields to sign
205
+ * @param secret - The HMAC secret key
206
+ * @returns Hex-encoded HMAC-SHA256 signature
207
+ */
208
+ declare function signAuditEntry(entry: SignableFields, secret: string): Promise<string>;
209
+ /**
210
+ * Verify an HMAC-SHA256 signature against the canonical fields of an audit entry.
211
+ *
212
+ * Uses timing-safe comparison to prevent timing attacks.
213
+ *
214
+ * @param entry - The audit entry fields to verify
215
+ * @param signature - The hex-encoded HMAC-SHA256 signature to verify
216
+ * @param secret - The HMAC secret key
217
+ * @returns True if the signature is valid
218
+ */
219
+ declare function verifyAuditEntry(entry: SignableFields, signature: string, secret: string): Promise<boolean>;
220
+ /**
221
+ * Global audit system
222
+ */
223
+ declare const audit: AuditSystem;
224
+
225
+ /**
226
+ * Security Alerting Service
227
+ *
228
+ * Evaluates audit events against configurable threshold rules and
229
+ * dispatches alerts through pluggable handlers (logging, audit trail,
230
+ * webhook / SIEM integration).
231
+ */
232
+
233
+ /** A security alert produced when a threshold is breached. */
234
+ interface SecurityAlert {
235
+ /** Alert rule that triggered (e.g. 'failedLogins', 'accountLockout'). */
236
+ type: string;
237
+ /** Severity of the alert. */
238
+ severity: AuditSeverity;
239
+ /** Human-readable description. */
240
+ message: string;
241
+ /** Contextual data attached to the alert. */
242
+ context: Record<string, unknown>;
243
+ /** When the alert was raised (ISO-8601). */
244
+ timestamp: string;
245
+ }
246
+ /** Handler that receives dispatched security alerts. */
247
+ interface AlertHandler {
248
+ /** Process a single alert. */
249
+ handle(alert: SecurityAlert): Promise<void>;
250
+ }
251
+ /** Configuration for a single threshold rule. */
252
+ interface ThresholdRule {
253
+ /** Maximum event count before an alert fires. */
254
+ maxCount: number;
255
+ /** Sliding window duration in milliseconds. */
256
+ windowMs: number;
257
+ /** Severity assigned to alerts from this rule. */
258
+ severity: AuditSeverity;
259
+ /** Human-readable message template — `{count}` is replaced at runtime. */
260
+ messageTemplate: string;
261
+ }
262
+ /** Top-level configuration for the alerting service. */
263
+ interface AlertingConfig {
264
+ /** Threshold rules keyed by rule name. */
265
+ thresholds: Record<string, ThresholdRule>;
266
+ /** Handlers that receive dispatched alerts. */
267
+ handlers: AlertHandler[];
268
+ }
269
+ /** Default threshold rules aligned with SOC2 6.2 requirements. */
270
+ declare const DEFAULT_THRESHOLDS: Record<string, ThresholdRule>;
271
+ /**
272
+ * Logs alerts to the structured security logger.
273
+ */
274
+ declare class LogAlertHandler implements AlertHandler {
275
+ /** Write alert details to the configured security logger. */
276
+ handle(alert: SecurityAlert): Promise<void>;
277
+ }
278
+ /**
279
+ * Writes alerts as critical audit events into the audit log.
280
+ */
281
+ declare class AuditAlertHandler implements AlertHandler {
282
+ /** Record the alert in the audit trail with severity 'critical'. */
283
+ handle(alert: SecurityAlert): Promise<void>;
284
+ }
285
+ /**
286
+ * POSTs alerts to a configurable webhook URL for SIEM integration.
287
+ */
288
+ declare class WebhookAlertHandler implements AlertHandler {
289
+ private url;
290
+ private headers;
291
+ /**
292
+ * Create a webhook alert handler.
293
+ *
294
+ * @param url - The webhook endpoint URL
295
+ * @param headers - Additional HTTP headers (e.g. authorization)
296
+ */
297
+ constructor(url: string, headers?: Record<string, string>);
298
+ /** POST the alert payload to the configured webhook URL. */
299
+ handle(alert: SecurityAlert): Promise<void>;
300
+ }
301
+ /**
302
+ * Evaluates audit events against threshold rules and dispatches alerts.
303
+ *
304
+ * Maintains an in-memory sliding window per rule/group key. When the
305
+ * event count within the window exceeds the threshold, an alert is
306
+ * dispatched to all configured handlers.
307
+ */
308
+ declare class SecurityAlertService {
309
+ private config;
310
+ private windows;
311
+ /**
312
+ * Create a new SecurityAlertService.
313
+ *
314
+ * @param config - Alerting configuration with thresholds and handlers
315
+ */
316
+ constructor(config: AlertingConfig);
317
+ /**
318
+ * Evaluate a single audit event against all threshold rules.
319
+ * If a threshold is breached, dispatches alerts to all handlers.
320
+ *
321
+ * @param event - The audit event to evaluate
322
+ * @returns The alert that was dispatched, or null if no threshold was breached
323
+ */
324
+ evaluateEvent(event: AuditEvent): Promise<SecurityAlert | null>;
325
+ /**
326
+ * Clear all sliding window state. Useful for testing.
327
+ */
328
+ reset(): void;
329
+ /**
330
+ * Dispatch an alert to all configured handlers.
331
+ * Errors in individual handlers are logged but do not prevent
332
+ * other handlers from receiving the alert.
333
+ */
334
+ private dispatchAlert;
335
+ }
336
+
337
+ /**
338
+ * Authentication Utilities
339
+ *
340
+ * OAuth support, password hashing, and two-factor authentication.
341
+ * JWT-based auth was removed — session auth is handled by @revealui/auth.
342
+ */
343
+ interface User {
344
+ id: string;
345
+ email: string;
346
+ username?: string;
347
+ roles: string[];
348
+ permissions: string[];
349
+ metadata?: Record<string, unknown>;
350
+ }
351
+ /**
352
+ * OAuth configuration
353
+ */
354
+ interface OAuthConfig {
355
+ provider: 'google' | 'github' | 'microsoft' | 'custom';
356
+ clientId: string;
357
+ clientSecret: string;
358
+ redirectUri: string;
359
+ scope?: string[];
360
+ authorizationUrl?: string;
361
+ tokenUrl?: string;
362
+ userInfoUrl?: string;
363
+ }
364
+ /**
365
+ * OAuth provider configurations
366
+ */
367
+ declare const OAuthProviders: {
368
+ google: {
369
+ authorizationUrl: string;
370
+ tokenUrl: string;
371
+ userInfoUrl: string;
372
+ scope: string[];
373
+ };
374
+ github: {
375
+ authorizationUrl: string;
376
+ tokenUrl: string;
377
+ userInfoUrl: string;
378
+ scope: string[];
379
+ };
380
+ microsoft: {
381
+ authorizationUrl: string;
382
+ tokenUrl: string;
383
+ userInfoUrl: string;
384
+ scope: string[];
385
+ };
386
+ };
387
+ /**
388
+ * OAuth client
389
+ */
390
+ declare class OAuthClient {
391
+ private config;
392
+ constructor(config: OAuthConfig);
393
+ /**
394
+ * Get authorization URL
395
+ */
396
+ getAuthorizationUrl(state?: string): string;
397
+ /**
398
+ * Exchange code for token
399
+ */
400
+ exchangeCodeForToken(code: string): Promise<{
401
+ access_token: string;
402
+ refresh_token?: string;
403
+ expires_in: number;
404
+ token_type: string;
405
+ }>;
406
+ /**
407
+ * Get user info
408
+ */
409
+ getUserInfo(accessToken: string): Promise<{
410
+ id: string;
411
+ email: string;
412
+ name?: string;
413
+ picture?: string;
414
+ }>;
415
+ }
416
+ /**
417
+ * Hash password with PBKDF2 and random salt
418
+ */
419
+ declare function hashPassword(password: string): Promise<string>;
420
+ /**
421
+ * Verify password against stored hash
422
+ */
423
+ declare function verifyPassword(password: string, storedHash: string): Promise<boolean>;
424
+ declare const PasswordHasher: {
425
+ readonly hash: typeof hashPassword;
426
+ readonly verify: typeof verifyPassword;
427
+ };
428
+ /**
429
+ * Generate TOTP secret
430
+ */
431
+ declare function generateSecret(): string;
432
+ /**
433
+ * Generate TOTP code (RFC 6238 compliant).
434
+ * Secret is base32-encoded — decoded before HMAC.
435
+ * Counter is encoded as 8-byte big-endian — matches all standard authenticator apps.
436
+ */
437
+ declare function generateCode(secret: string, timestamp?: number): string;
438
+ /**
439
+ * Verify TOTP code
440
+ */
441
+ declare function verifyCode(secret: string, code: string, window?: number): boolean;
442
+ declare const TwoFactorAuth: {
443
+ readonly generateSecret: typeof generateSecret;
444
+ readonly generateCode: typeof generateCode;
445
+ readonly verifyCode: typeof verifyCode;
446
+ };
447
+
448
+ /**
449
+ * Authorization System
450
+ *
451
+ * Role-Based Access Control (RBAC) and Attribute-Based Access Control (ABAC)
452
+ */
453
+ interface Permission {
454
+ resource: string;
455
+ action: string;
456
+ conditions?: Record<string, unknown>;
457
+ }
458
+ interface Role {
459
+ id: string;
460
+ name: string;
461
+ description?: string;
462
+ permissions: Permission[];
463
+ inherits?: string[];
464
+ }
465
+ interface Policy {
466
+ id: string;
467
+ name: string;
468
+ effect: 'allow' | 'deny';
469
+ resources: string[];
470
+ actions: string[];
471
+ conditions?: PolicyCondition[];
472
+ priority?: number;
473
+ }
474
+ interface PolicyCondition {
475
+ field: string;
476
+ operator: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'contains';
477
+ value: unknown;
478
+ }
479
+ interface AuthorizationContext {
480
+ user: {
481
+ id: string;
482
+ roles: string[];
483
+ attributes?: Record<string, unknown>;
484
+ };
485
+ resource?: {
486
+ type: string;
487
+ id?: string;
488
+ owner?: string;
489
+ attributes?: Record<string, unknown>;
490
+ };
491
+ environment?: {
492
+ time?: Date;
493
+ ip?: string;
494
+ userAgent?: string;
495
+ };
496
+ }
497
+ /**
498
+ * Authorization system
499
+ */
500
+ declare class AuthorizationSystem {
501
+ private roles;
502
+ private policies;
503
+ /**
504
+ * Register role
505
+ */
506
+ registerRole(role: Role): void;
507
+ /**
508
+ * Get role
509
+ */
510
+ getRole(roleId: string): Role | undefined;
511
+ /**
512
+ * Register policy
513
+ */
514
+ registerPolicy(policy: Policy): void;
515
+ /**
516
+ * Check if user has permission (RBAC)
517
+ */
518
+ hasPermission(userRoles: string[], resource: string, action: string): boolean;
519
+ /**
520
+ * Check access with policies (ABAC)
521
+ */
522
+ checkAccess(context: AuthorizationContext, resource: string, action: string): {
523
+ allowed: boolean;
524
+ reason?: string;
525
+ };
526
+ /**
527
+ * Get all permissions for roles
528
+ */
529
+ private getUserPermissions;
530
+ /**
531
+ * Get applicable policies
532
+ */
533
+ private getApplicablePolicies;
534
+ /**
535
+ * Match resource pattern
536
+ */
537
+ private matchesResource;
538
+ /**
539
+ * Match action pattern
540
+ */
541
+ private matchesAction;
542
+ /**
543
+ * Evaluate policy conditions
544
+ */
545
+ private evaluateConditions;
546
+ /**
547
+ * Get value from context
548
+ */
549
+ private getContextValue;
550
+ /**
551
+ * Evaluate single condition
552
+ */
553
+ private evaluateCondition;
554
+ /**
555
+ * Check if user owns resource
556
+ */
557
+ ownsResource(userId: string, resource: {
558
+ owner?: string;
559
+ }): boolean;
560
+ /**
561
+ * Clear all roles and policies
562
+ */
563
+ clear(): void;
564
+ }
565
+ /**
566
+ * Global authorization instance
567
+ */
568
+ declare const authorization: AuthorizationSystem;
569
+ /**
570
+ * Common roles — aligned with DB schema (`users.role` column)
571
+ * and `UserRoleSchema` in @revealui/contracts.
572
+ *
573
+ * Values: owner | admin | editor | viewer | agent | contributor
574
+ */
575
+ declare const CommonRoles: Record<string, Role>;
576
+ /**
577
+ * Permission builder
578
+ */
579
+ declare class PermissionBuilder {
580
+ private permission;
581
+ resource(resource: string): this;
582
+ action(action: string): this;
583
+ conditions(conditions: Record<string, unknown>): this;
584
+ build(): Permission;
585
+ }
586
+ /**
587
+ * Policy builder
588
+ */
589
+ declare class PolicyBuilder {
590
+ private policy;
591
+ id(id: string): this;
592
+ name(name: string): this;
593
+ allow(): this;
594
+ deny(): this;
595
+ resources(...resources: string[]): this;
596
+ actions(...actions: string[]): this;
597
+ condition(field: string, operator: PolicyCondition['operator'], value: unknown): this;
598
+ priority(priority: number): this;
599
+ build(): Policy;
600
+ }
601
+ /**
602
+ * Authorization decorators
603
+ */
604
+ declare function RequirePermission(resource: string, action: string): (_target: object, _propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
605
+ declare function RequireRole(requiredRole: string): (_target: object, _propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
606
+ /**
607
+ * Authorization middleware
608
+ */
609
+ declare function createAuthorizationMiddleware<TRequest = unknown>(getUser: (request: TRequest) => {
610
+ id: string;
611
+ roles: string[];
612
+ }, resource: string, action: string): (request: TRequest, next: () => Promise<unknown>) => Promise<unknown>;
613
+ /**
614
+ * Resource ownership check
615
+ */
616
+ declare function canAccessResource(userId: string, userRoles: string[], resource: {
617
+ type: string;
618
+ id?: string;
619
+ owner?: string;
620
+ }, action: string): boolean;
621
+ /**
622
+ * Attribute-based access control helper
623
+ */
624
+ declare function checkAttributeAccess(context: AuthorizationContext, resource: string, action: string, requiredAttributes?: Record<string, unknown>): boolean;
625
+ /**
626
+ * Permission cache for performance
627
+ */
628
+ declare class PermissionCache {
629
+ private cache;
630
+ private ttl;
631
+ private maxEntries;
632
+ constructor(ttl?: number, maxEntries?: number);
633
+ /**
634
+ * Get cached permission
635
+ */
636
+ get(userId: string, resource: string, action: string): boolean | undefined;
637
+ /**
638
+ * Set cached permission
639
+ */
640
+ set(userId: string, resource: string, action: string, allowed: boolean): void;
641
+ /**
642
+ * Clear cache for user
643
+ */
644
+ clearUser(userId: string): void;
645
+ /**
646
+ * Clear all cache
647
+ */
648
+ clear(): void;
649
+ /**
650
+ * Get cache key
651
+ */
652
+ private getCacheKey;
653
+ }
654
+ /**
655
+ * Global permission cache
656
+ */
657
+ declare const permissionCache: PermissionCache;
658
+
659
+ /**
660
+ * Encryption Utilities
661
+ *
662
+ * Data encryption for at-rest and in-transit protection
663
+ */
664
+ interface EncryptionConfig {
665
+ algorithm: 'AES-GCM' | 'AES-CTR';
666
+ keySize: 128 | 192 | 256;
667
+ ivSize?: number;
668
+ /** Allow key export via exportKey(). Default: false (keys are non-extractable). */
669
+ extractable?: boolean;
670
+ }
671
+ interface EncryptedData {
672
+ data: string;
673
+ iv: string;
674
+ tag?: string;
675
+ algorithm: string;
676
+ }
677
+ /**
678
+ * Encryption system
679
+ */
680
+ declare class EncryptionSystem {
681
+ private config;
682
+ private keys;
683
+ constructor(config?: Partial<EncryptionConfig>);
684
+ /**
685
+ * Generate encryption key
686
+ */
687
+ generateKey(keyId?: string): Promise<CryptoKey>;
688
+ /**
689
+ * Import key from raw data
690
+ */
691
+ importKey(keyData: ArrayBuffer, keyId?: string): Promise<CryptoKey>;
692
+ /**
693
+ * Export key to raw data
694
+ */
695
+ exportKey(key: CryptoKey): Promise<ArrayBuffer>;
696
+ /**
697
+ * Encrypt data
698
+ */
699
+ encrypt(data: string, keyOrId: CryptoKey | string): Promise<EncryptedData>;
700
+ /**
701
+ * Decrypt data
702
+ */
703
+ decrypt(encryptedData: EncryptedData, keyOrId: CryptoKey | string): Promise<string>;
704
+ /**
705
+ * Encrypt object
706
+ */
707
+ encryptObject<T extends Record<string, unknown>>(obj: T, keyOrId: CryptoKey | string): Promise<EncryptedData>;
708
+ /**
709
+ * Decrypt object
710
+ */
711
+ decryptObject<T extends Record<string, unknown>>(encryptedData: EncryptedData, keyOrId: CryptoKey | string): Promise<T>;
712
+ /**
713
+ * Hash data
714
+ */
715
+ hash(data: string, algorithm?: 'SHA-256' | 'SHA-384' | 'SHA-512'): Promise<string>;
716
+ /**
717
+ * Generate random bytes
718
+ */
719
+ randomBytes(length: number): Uint8Array;
720
+ /**
721
+ * Generate random string
722
+ */
723
+ randomString(length: number, charset?: string): string;
724
+ /**
725
+ * Convert ArrayBuffer to base64
726
+ */
727
+ private arrayBufferToBase64;
728
+ /**
729
+ * Convert base64 to ArrayBuffer
730
+ */
731
+ private base64ToArrayBuffer;
732
+ /**
733
+ * Store key
734
+ */
735
+ storeKey(keyId: string, key: CryptoKey): void;
736
+ /**
737
+ * Get key
738
+ */
739
+ getKey(keyId: string): CryptoKey | undefined;
740
+ /**
741
+ * Remove key
742
+ */
743
+ removeKey(keyId: string): void;
744
+ /**
745
+ * Clear all keys
746
+ */
747
+ clearKeys(): void;
748
+ }
749
+ /**
750
+ * Global encryption instance
751
+ */
752
+ declare const encryption: EncryptionSystem;
753
+ /**
754
+ * Field-level encryption
755
+ */
756
+ declare class FieldEncryption {
757
+ private encryption;
758
+ private key;
759
+ constructor(encryption: EncryptionSystem);
760
+ /**
761
+ * Initialize with key
762
+ */
763
+ initialize(key: CryptoKey): Promise<void>;
764
+ /**
765
+ * Encrypt field
766
+ */
767
+ encryptField(value: unknown): Promise<EncryptedData>;
768
+ /**
769
+ * Decrypt field
770
+ */
771
+ decryptField(encryptedData: EncryptedData): Promise<unknown>;
772
+ /**
773
+ * Encrypt object fields
774
+ */
775
+ encryptFields<T extends Record<string, unknown>>(obj: T, fields: (keyof T)[]): Promise<T>;
776
+ /**
777
+ * Decrypt object fields
778
+ */
779
+ decryptFields<T extends Record<string, unknown>>(obj: T, fields: (keyof T)[]): Promise<T>;
780
+ }
781
+ /**
782
+ * Key rotation
783
+ */
784
+ declare class KeyRotationManager {
785
+ private encryption;
786
+ private currentKeyId;
787
+ private oldKeys;
788
+ private keyCreationDates;
789
+ constructor(encryption: EncryptionSystem, initialKeyId: string);
790
+ /**
791
+ * Rotate to new key
792
+ */
793
+ rotate(newKeyId: string, newKey: CryptoKey): Promise<void>;
794
+ /**
795
+ * Re-encrypt data with new key
796
+ */
797
+ reencrypt(encryptedData: EncryptedData, oldKeyId: string): Promise<EncryptedData>;
798
+ /**
799
+ * Get current key ID
800
+ */
801
+ getCurrentKeyId(): string;
802
+ /**
803
+ * Clean up old keys created before the specified date.
804
+ * Never removes the current active key.
805
+ */
806
+ cleanupOldKeys(olderThan: Date): void;
807
+ }
808
+ /**
809
+ * Envelope encryption for large data
810
+ */
811
+ declare class EnvelopeEncryption {
812
+ private encryption;
813
+ private masterKey;
814
+ constructor(encryption: EncryptionSystem, masterKey: CryptoKey);
815
+ /**
816
+ * Encrypt with envelope encryption
817
+ */
818
+ encrypt(data: string): Promise<{
819
+ encryptedData: EncryptedData;
820
+ encryptedKey: EncryptedData;
821
+ }>;
822
+ /**
823
+ * Decrypt with envelope encryption
824
+ */
825
+ decrypt(encryptedData: EncryptedData, encryptedKey: EncryptedData): Promise<string>;
826
+ private arrayBufferToBase64;
827
+ private base64ToArrayBuffer;
828
+ }
829
+ /**
830
+ * Data masking utilities
831
+ */
832
+ /**
833
+ * Mask email
834
+ */
835
+ declare function maskEmail(email: string): string;
836
+ /**
837
+ * Mask phone number
838
+ */
839
+ declare function maskPhone(phone: string): string;
840
+ /**
841
+ * Mask credit card
842
+ */
843
+ declare function maskCreditCard(card: string): string;
844
+ /**
845
+ * Mask SSN
846
+ */
847
+ declare function maskSSN(ssn: string): string;
848
+ /**
849
+ * Mask string (keep first and last character)
850
+ */
851
+ declare function maskString(str: string, keepChars?: number): string;
852
+ declare const DataMasking: {
853
+ readonly maskEmail: typeof maskEmail;
854
+ readonly maskPhone: typeof maskPhone;
855
+ readonly maskCreditCard: typeof maskCreditCard;
856
+ readonly maskSSN: typeof maskSSN;
857
+ readonly maskString: typeof maskString;
858
+ };
859
+ /**
860
+ * Secure random token generator
861
+ */
862
+ /**
863
+ * Generate secure token. `length` is the number of random bytes;
864
+ * the returned string is hex-encoded, so it will be `length * 2` characters.
865
+ */
866
+ declare function generateToken(length?: number): string;
867
+ /**
868
+ * Generate UUID v4
869
+ */
870
+ declare function generateUUID(): string;
871
+ /**
872
+ * Generate API key
873
+ */
874
+ declare function generateAPIKey(prefix?: string): string;
875
+ /**
876
+ * Generate session ID
877
+ */
878
+ declare function generateSessionID(): string;
879
+ declare const TokenGenerator: {
880
+ readonly generate: typeof generateToken;
881
+ readonly generateUUID: typeof generateUUID;
882
+ readonly generateAPIKey: typeof generateAPIKey;
883
+ readonly generateSessionID: typeof generateSessionID;
884
+ };
885
+
886
+ /**
887
+ * GDPR Storage Abstraction
888
+ *
889
+ * Record-oriented storage interface for GDPR compliance data.
890
+ * Provides a clean seam for replacing the default in-memory implementation
891
+ * with a database-backed store in production.
892
+ */
893
+
894
+ /**
895
+ * Storage interface for GDPR consent records and deletion requests.
896
+ *
897
+ * All methods are async to support database-backed implementations.
898
+ * The default `InMemoryGDPRStorage` is suitable for testing and development
899
+ * but must be replaced with a persistent store for production use.
900
+ */
901
+ interface GDPRStorage {
902
+ /**
903
+ * Store or update a consent record, keyed by `userId:consentType`.
904
+ */
905
+ setConsent(userId: string, type: ConsentType, record: ConsentRecord): Promise<void>;
906
+ /**
907
+ * Retrieve a consent record by user and type. Returns `undefined` if not found.
908
+ */
909
+ getConsent(userId: string, type: ConsentType): Promise<ConsentRecord | undefined>;
910
+ /**
911
+ * Retrieve all consent records for a given user.
912
+ */
913
+ getConsentsByUser(userId: string): Promise<ConsentRecord[]>;
914
+ /**
915
+ * Retrieve every consent record in storage (used for aggregate statistics).
916
+ */
917
+ getAllConsents(): Promise<ConsentRecord[]>;
918
+ /**
919
+ * Store a deletion request, keyed by its `id`.
920
+ */
921
+ setDeletionRequest(request: DataDeletionRequest): Promise<void>;
922
+ /**
923
+ * Retrieve a deletion request by ID. Returns `undefined` if not found.
924
+ */
925
+ getDeletionRequest(requestId: string): Promise<DataDeletionRequest | undefined>;
926
+ /**
927
+ * Retrieve all deletion requests for a given user.
928
+ */
929
+ getDeletionRequestsByUser(userId: string): Promise<DataDeletionRequest[]>;
930
+ }
931
+ /**
932
+ * Storage interface for data breach records.
933
+ *
934
+ * All methods are async to support database-backed implementations.
935
+ * The default `InMemoryBreachStorage` is suitable for testing and development
936
+ * but must be replaced with a persistent store for production GDPR compliance.
937
+ */
938
+ interface BreachStorage {
939
+ /**
940
+ * Store a data breach record.
941
+ */
942
+ setBreach(breach: DataBreach): Promise<void>;
943
+ /**
944
+ * Retrieve a breach by ID. Returns `undefined` if not found.
945
+ */
946
+ getBreach(id: string): Promise<DataBreach | undefined>;
947
+ /**
948
+ * Retrieve all breach records.
949
+ */
950
+ getAllBreaches(): Promise<DataBreach[]>;
951
+ /**
952
+ * Update an existing breach record (e.g., status change, add mitigation).
953
+ */
954
+ updateBreach(id: string, updates: Partial<DataBreach>): Promise<void>;
955
+ }
956
+ /**
957
+ * In-memory implementation of `BreachStorage`.
958
+ *
959
+ * WARNING: All data is lost on process restart or serverless cold start.
960
+ * GDPR requires breach records be retained — use database-backed storage in production.
961
+ */
962
+ declare class InMemoryBreachStorage implements BreachStorage {
963
+ private breaches;
964
+ setBreach(breach: DataBreach): Promise<void>;
965
+ getBreach(id: string): Promise<DataBreach | undefined>;
966
+ getAllBreaches(): Promise<DataBreach[]>;
967
+ updateBreach(id: string, updates: Partial<DataBreach>): Promise<void>;
968
+ }
969
+ /**
970
+ * In-memory implementation of `GDPRStorage`.
971
+ *
972
+ * WARNING: All data is lost on process restart or serverless cold start.
973
+ * Use this only for development, testing, or as a reference implementation.
974
+ * Production deployments MUST supply a database-backed `GDPRStorage`.
975
+ */
976
+ declare class InMemoryGDPRStorage implements GDPRStorage {
977
+ private consents;
978
+ private deletionRequests;
979
+ setConsent(userId: string, type: ConsentType, record: ConsentRecord): Promise<void>;
980
+ getConsent(userId: string, type: ConsentType): Promise<ConsentRecord | undefined>;
981
+ getConsentsByUser(userId: string): Promise<ConsentRecord[]>;
982
+ getAllConsents(): Promise<ConsentRecord[]>;
983
+ setDeletionRequest(request: DataDeletionRequest): Promise<void>;
984
+ getDeletionRequest(requestId: string): Promise<DataDeletionRequest | undefined>;
985
+ getDeletionRequestsByUser(userId: string): Promise<DataDeletionRequest[]>;
986
+ }
987
+
988
+ /**
989
+ * GDPR Compliance Utilities
990
+ *
991
+ * Data privacy, consent management, data export, and right to be forgotten
992
+ */
993
+
994
+ type ConsentType = 'necessary' | 'functional' | 'analytics' | 'marketing' | 'personalization';
995
+ type DataCategory = 'personal' | 'sensitive' | 'financial' | 'health' | 'behavioral' | 'location';
996
+ interface ConsentRecord {
997
+ id: string;
998
+ userId: string;
999
+ type: ConsentType;
1000
+ granted: boolean;
1001
+ timestamp: string;
1002
+ expiresAt?: string;
1003
+ source: 'explicit' | 'implicit' | 'legitimate_interest';
1004
+ version: string;
1005
+ metadata?: Record<string, unknown>;
1006
+ }
1007
+ interface DataProcessingPurpose {
1008
+ id: string;
1009
+ name: string;
1010
+ description: string;
1011
+ legalBasis: 'consent' | 'contract' | 'legal_obligation' | 'vital_interest' | 'public_interest' | 'legitimate_interest';
1012
+ dataCategories: DataCategory[];
1013
+ retentionPeriod: number;
1014
+ consentRequired: boolean;
1015
+ }
1016
+ interface PersonalDataExport {
1017
+ userId: string;
1018
+ exportedAt: string;
1019
+ data: {
1020
+ profile: Record<string, unknown>;
1021
+ activities: Record<string, unknown>[];
1022
+ consents: ConsentRecord[];
1023
+ dataProcessing: DataProcessingPurpose[];
1024
+ };
1025
+ format: 'json' | 'csv' | 'pdf';
1026
+ }
1027
+ interface DataDeletionRequest {
1028
+ id: string;
1029
+ userId: string;
1030
+ requestedAt: string;
1031
+ processedAt?: string;
1032
+ status: 'pending' | 'processing' | 'completed' | 'failed';
1033
+ dataCategories: DataCategory[];
1034
+ reason?: string;
1035
+ retainedData?: string[];
1036
+ deletedData?: string[];
1037
+ }
1038
+ /**
1039
+ * Consent management system
1040
+ */
1041
+ declare class ConsentManager {
1042
+ private readonly storage;
1043
+ private consentVersion;
1044
+ constructor(storage: GDPRStorage);
1045
+ /**
1046
+ * Grant consent
1047
+ */
1048
+ grantConsent(userId: string, type: ConsentType, source?: ConsentRecord['source'], expiresIn?: number): Promise<ConsentRecord>;
1049
+ /**
1050
+ * Revoke consent
1051
+ */
1052
+ revokeConsent(userId: string, type: ConsentType): Promise<void>;
1053
+ /**
1054
+ * Check if consent is granted
1055
+ */
1056
+ hasConsent(userId: string, type: ConsentType): Promise<boolean>;
1057
+ /**
1058
+ * Get all consents for user
1059
+ */
1060
+ getUserConsents(userId: string): Promise<ConsentRecord[]>;
1061
+ /**
1062
+ * Update consent version
1063
+ */
1064
+ setConsentVersion(version: string): void;
1065
+ /**
1066
+ * Check if consent needs renewal
1067
+ */
1068
+ needsRenewal(userId: string, type: ConsentType, maxAge: number): Promise<boolean>;
1069
+ /**
1070
+ * Get consent statistics
1071
+ */
1072
+ getStatistics(): Promise<{
1073
+ total: number;
1074
+ granted: number;
1075
+ revoked: number;
1076
+ expired: number;
1077
+ byType: Record<ConsentType, number>;
1078
+ }>;
1079
+ }
1080
+ /**
1081
+ * Data export system
1082
+ */
1083
+ declare class DataExportSystem {
1084
+ /**
1085
+ * Export user data
1086
+ */
1087
+ exportUserData(userId: string, getUserData: (userId: string) => Promise<{
1088
+ profile: Record<string, unknown>;
1089
+ activities: Record<string, unknown>[];
1090
+ consents: ConsentRecord[];
1091
+ }>, format?: PersonalDataExport['format']): Promise<PersonalDataExport>;
1092
+ /**
1093
+ * Format export as JSON
1094
+ */
1095
+ formatAsJSON(exportData: PersonalDataExport): string;
1096
+ /**
1097
+ * Format export as CSV
1098
+ */
1099
+ formatAsCSV(exportData: PersonalDataExport): string;
1100
+ /**
1101
+ * Create download link
1102
+ */
1103
+ createDownloadLink(content: string, _filename: string, mimeType: string): string;
1104
+ }
1105
+ /**
1106
+ * Data deletion system (Right to be Forgotten)
1107
+ */
1108
+ declare class DataDeletionSystem {
1109
+ private readonly storage;
1110
+ constructor(storage: GDPRStorage);
1111
+ /**
1112
+ * Request data deletion
1113
+ */
1114
+ requestDeletion(userId: string, dataCategories: DataCategory[], reason?: string): Promise<DataDeletionRequest>;
1115
+ /**
1116
+ * Process deletion request
1117
+ */
1118
+ processDeletion(requestId: string, deleteData: (userId: string, categories: DataCategory[]) => Promise<{
1119
+ deleted: string[];
1120
+ retained: string[];
1121
+ }>): Promise<void>;
1122
+ /**
1123
+ * Get deletion request
1124
+ */
1125
+ getRequest(requestId: string): Promise<DataDeletionRequest | undefined>;
1126
+ /**
1127
+ * Get user deletion requests
1128
+ */
1129
+ getUserRequests(userId: string): Promise<DataDeletionRequest[]>;
1130
+ /**
1131
+ * Check if data can be deleted
1132
+ */
1133
+ canDelete(_dataCategory: DataCategory, legalBasis: DataProcessingPurpose['legalBasis']): boolean;
1134
+ /**
1135
+ * Calculate retention period
1136
+ */
1137
+ calculateRetentionEnd(createdAt: Date, retentionPeriod: number): Date;
1138
+ /**
1139
+ * Check if data should be deleted (retention period expired)
1140
+ */
1141
+ shouldDelete(createdAt: Date, retentionPeriod: number): boolean;
1142
+ }
1143
+ /**
1144
+ * Data anonymization utilities
1145
+ */
1146
+ /**
1147
+ * Hash value (irreversible) using SHA-256
1148
+ */
1149
+ declare function hashValue(value: string): string;
1150
+ /**
1151
+ * Anonymize user data
1152
+ */
1153
+ declare function anonymizeUser(user: Record<string, unknown>): Record<string, unknown>;
1154
+ /**
1155
+ * Pseudonymize data (one-way, key-dependent)
1156
+ *
1157
+ * Uses HMAC-SHA256 — cryptographically bound to the key, resistant to
1158
+ * length-extension attacks and GPU brute-force (unlike plain SHA-256).
1159
+ */
1160
+ declare function pseudonymize(value: string, key: string): string;
1161
+ /**
1162
+ * Anonymize dataset
1163
+ */
1164
+ declare function anonymizeDataset<T extends Record<string, unknown>>(data: T[], sensitiveFields: (keyof T)[]): T[];
1165
+ /**
1166
+ * K-anonymity check
1167
+ */
1168
+ declare function checkKAnonymity<T extends Record<string, unknown>>(data: T[], quasiIdentifiers: (keyof T)[], k: number): boolean;
1169
+ declare const DataAnonymization: {
1170
+ readonly anonymizeUser: typeof anonymizeUser;
1171
+ readonly pseudonymize: typeof pseudonymize;
1172
+ readonly hashValue: typeof hashValue;
1173
+ readonly anonymizeDataset: typeof anonymizeDataset;
1174
+ readonly checkKAnonymity: typeof checkKAnonymity;
1175
+ };
1176
+ /**
1177
+ * Privacy policy manager
1178
+ */
1179
+ declare class PrivacyPolicyManager {
1180
+ private policies;
1181
+ private currentVersion;
1182
+ /**
1183
+ * Add policy version
1184
+ */
1185
+ addPolicy(version: string, content: string, effectiveDate: Date): void;
1186
+ /**
1187
+ * Get current policy
1188
+ */
1189
+ getCurrentPolicy(): {
1190
+ version: string;
1191
+ content: string;
1192
+ effectiveDate: Date;
1193
+ } | undefined;
1194
+ /**
1195
+ * Get policy by version
1196
+ */
1197
+ getPolicy(version: string): {
1198
+ version: string;
1199
+ content: string;
1200
+ effectiveDate: Date;
1201
+ } | undefined;
1202
+ /**
1203
+ * Check if user accepted current policy
1204
+ */
1205
+ hasAcceptedCurrent(userAcceptedVersion: string): boolean;
1206
+ /**
1207
+ * Get all versions
1208
+ */
1209
+ getAllVersions(): string[];
1210
+ }
1211
+ /**
1212
+ * Cookie consent banner
1213
+ */
1214
+ interface CookieConsentConfig {
1215
+ necessary: boolean;
1216
+ functional: boolean;
1217
+ analytics: boolean;
1218
+ marketing: boolean;
1219
+ }
1220
+ declare class CookieConsentManager {
1221
+ private config;
1222
+ /**
1223
+ * Set consent configuration
1224
+ */
1225
+ setConsent(config: Partial<CookieConsentConfig>): void;
1226
+ /**
1227
+ * Get consent configuration
1228
+ */
1229
+ getConsent(): CookieConsentConfig;
1230
+ /**
1231
+ * Check if specific consent is granted
1232
+ */
1233
+ hasConsent(type: keyof CookieConsentConfig): boolean;
1234
+ /**
1235
+ * Save to storage
1236
+ */
1237
+ private saveToStorage;
1238
+ /**
1239
+ * Load from storage
1240
+ */
1241
+ loadFromStorage(): void;
1242
+ /**
1243
+ * Clear consent
1244
+ */
1245
+ clearConsent(): void;
1246
+ }
1247
+ /**
1248
+ * Data breach notification system
1249
+ */
1250
+ interface DataBreach {
1251
+ id: string;
1252
+ detectedAt: string;
1253
+ reportedAt?: string;
1254
+ type: 'unauthorized_access' | 'data_loss' | 'data_leak' | 'system_compromise';
1255
+ severity: 'low' | 'medium' | 'high' | 'critical';
1256
+ affectedUsers: string[];
1257
+ dataCategories: DataCategory[];
1258
+ description: string;
1259
+ mitigation?: string;
1260
+ status: 'detected' | 'investigating' | 'notified' | 'resolved';
1261
+ }
1262
+ declare class DataBreachManager {
1263
+ private readonly storage;
1264
+ constructor(storage: BreachStorage);
1265
+ /**
1266
+ * Report data breach
1267
+ */
1268
+ reportBreach(breach: Omit<DataBreach, 'id' | 'detectedAt' | 'status'>): Promise<DataBreach>;
1269
+ /**
1270
+ * Notify authorities (required within 72 hours under GDPR)
1271
+ */
1272
+ notifyAuthorities(breach: DataBreach): Promise<void>;
1273
+ /**
1274
+ * Notify affected users
1275
+ */
1276
+ notifyAffectedUsers(breachId: string, notifyFn: (userId: string, breach: DataBreach) => Promise<void>): Promise<void>;
1277
+ /**
1278
+ * Check if breach notification is required
1279
+ */
1280
+ requiresNotification(breach: DataBreach): boolean;
1281
+ /**
1282
+ * Get breach
1283
+ */
1284
+ getBreach(id: string): Promise<DataBreach | undefined>;
1285
+ /**
1286
+ * Get all breaches
1287
+ */
1288
+ getAllBreaches(): Promise<DataBreach[]>;
1289
+ }
1290
+ /**
1291
+ * Factory functions for GDPR subsystems.
1292
+ *
1293
+ * `ConsentManager` and `DataDeletionSystem` require a `GDPRStorage` implementation.
1294
+ * Use `InMemoryGDPRStorage` only in tests — production MUST use a database-backed store.
1295
+ *
1296
+ * `DataExportSystem`, `PrivacyPolicyManager`, `CookieConsentManager`, and
1297
+ * `DataBreachManager` are stateless or client-side only, so singletons are safe.
1298
+ */
1299
+ declare function createConsentManager(storage: GDPRStorage): ConsentManager;
1300
+ declare function createDataDeletionSystem(storage: GDPRStorage): DataDeletionSystem;
1301
+ declare const dataExportSystem: DataExportSystem;
1302
+ declare const privacyPolicyManager: PrivacyPolicyManager;
1303
+ declare const cookieConsentManager: CookieConsentManager;
1304
+ declare function createDataBreachManager(storage: BreachStorage): DataBreachManager;
1305
+
1306
+ /**
1307
+ * Security Headers and CORS Configuration
1308
+ *
1309
+ * HTTP security headers and CORS policy management
1310
+ */
1311
+ interface SecurityHeadersConfig {
1312
+ contentSecurityPolicy?: string | ContentSecurityPolicyConfig;
1313
+ strictTransportSecurity?: boolean | HSTSConfig;
1314
+ xFrameOptions?: 'DENY' | 'SAMEORIGIN' | string;
1315
+ xContentTypeOptions?: boolean;
1316
+ referrerPolicy?: ReferrerPolicyValue;
1317
+ permissionsPolicy?: string | PermissionsPolicyConfig;
1318
+ crossOriginEmbedderPolicy?: 'require-corp' | 'credentialless';
1319
+ crossOriginOpenerPolicy?: 'same-origin' | 'same-origin-allow-popups' | 'unsafe-none';
1320
+ crossOriginResourcePolicy?: 'same-origin' | 'same-site' | 'cross-origin';
1321
+ }
1322
+ interface ContentSecurityPolicyConfig {
1323
+ defaultSrc?: string[];
1324
+ scriptSrc?: string[];
1325
+ styleSrc?: string[];
1326
+ imgSrc?: string[];
1327
+ fontSrc?: string[];
1328
+ connectSrc?: string[];
1329
+ frameSrc?: string[];
1330
+ objectSrc?: string[];
1331
+ mediaSrc?: string[];
1332
+ workerSrc?: string[];
1333
+ childSrc?: string[];
1334
+ formAction?: string[];
1335
+ frameAncestors?: string[];
1336
+ baseUri?: string[];
1337
+ manifestSrc?: string[];
1338
+ upgradeInsecureRequests?: boolean;
1339
+ blockAllMixedContent?: boolean;
1340
+ reportUri?: string;
1341
+ reportTo?: string;
1342
+ }
1343
+ interface HSTSConfig {
1344
+ maxAge: number;
1345
+ includeSubDomains?: boolean;
1346
+ preload?: boolean;
1347
+ }
1348
+ type ReferrerPolicyValue = 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url';
1349
+ interface PermissionsPolicyConfig {
1350
+ accelerometer?: string[];
1351
+ ambientLightSensor?: string[];
1352
+ autoplay?: string[];
1353
+ battery?: string[];
1354
+ camera?: string[];
1355
+ displayCapture?: string[];
1356
+ documentDomain?: string[];
1357
+ encryptedMedia?: string[];
1358
+ fullscreen?: string[];
1359
+ geolocation?: string[];
1360
+ gyroscope?: string[];
1361
+ magnetometer?: string[];
1362
+ microphone?: string[];
1363
+ midi?: string[];
1364
+ payment?: string[];
1365
+ pictureInPicture?: string[];
1366
+ publicKeyCredentials?: string[];
1367
+ screenWakeLock?: string[];
1368
+ syncXhr?: string[];
1369
+ usb?: string[];
1370
+ webShare?: string[];
1371
+ xrSpatialTracking?: string[];
1372
+ }
1373
+ interface CORSConfig {
1374
+ origin?: string | string[] | ((origin: string) => boolean);
1375
+ methods?: string[];
1376
+ allowedHeaders?: string[];
1377
+ exposedHeaders?: string[];
1378
+ credentials?: boolean;
1379
+ maxAge?: number;
1380
+ preflightContinue?: boolean;
1381
+ optionsSuccessStatus?: number;
1382
+ }
1383
+ /**
1384
+ * Security headers manager
1385
+ */
1386
+ declare class SecurityHeaders {
1387
+ private config;
1388
+ constructor(config?: SecurityHeadersConfig);
1389
+ /**
1390
+ * Get all security headers
1391
+ */
1392
+ getHeaders(): Record<string, string>;
1393
+ /**
1394
+ * Build Content Security Policy header
1395
+ */
1396
+ private buildCSP;
1397
+ /**
1398
+ * Build HSTS header
1399
+ */
1400
+ private buildHSTS;
1401
+ /**
1402
+ * Build Permissions-Policy header
1403
+ */
1404
+ private buildPermissionsPolicy;
1405
+ /**
1406
+ * Apply headers to response
1407
+ */
1408
+ applyHeaders(response: Response): Response;
1409
+ }
1410
+ /**
1411
+ * CORS manager
1412
+ */
1413
+ declare class CORSManager {
1414
+ private config;
1415
+ constructor(config?: CORSConfig);
1416
+ /**
1417
+ * Check if origin is allowed
1418
+ */
1419
+ isOriginAllowed(origin: string): boolean;
1420
+ /**
1421
+ * Get CORS headers
1422
+ */
1423
+ getCORSHeaders(origin: string): Record<string, string>;
1424
+ /**
1425
+ * Get preflight headers
1426
+ */
1427
+ getPreflightHeaders(origin: string): Record<string, string>;
1428
+ /**
1429
+ * Handle CORS request
1430
+ */
1431
+ handleRequest(request: Request): Response | null;
1432
+ /**
1433
+ * Handle preflight request
1434
+ */
1435
+ handlePreflight(_request: Request, origin: string): Response;
1436
+ /**
1437
+ * Apply CORS headers to response
1438
+ */
1439
+ applyHeaders(response: Response, origin: string): Response;
1440
+ }
1441
+ /**
1442
+ * Common security header presets
1443
+ */
1444
+ declare const SecurityPresets: {
1445
+ /**
1446
+ * Strict security (recommended for production)
1447
+ */
1448
+ strict: () => SecurityHeadersConfig;
1449
+ /**
1450
+ * Moderate security (balanced)
1451
+ */
1452
+ moderate: () => SecurityHeadersConfig;
1453
+ /**
1454
+ * Development (permissive)
1455
+ */
1456
+ development: () => SecurityHeadersConfig;
1457
+ };
1458
+ /**
1459
+ * Common CORS presets
1460
+ */
1461
+ declare const CORSPresets: {
1462
+ /**
1463
+ * Strict CORS (same origin only)
1464
+ */
1465
+ strict: () => CORSConfig;
1466
+ /**
1467
+ * Moderate CORS (specific origins)
1468
+ */
1469
+ moderate: (allowedOrigins: string[]) => CORSConfig;
1470
+ /**
1471
+ * Permissive CORS (all origins) — development only.
1472
+ * Logs a warning if used when NODE_ENV === 'production'.
1473
+ */
1474
+ permissive: () => CORSConfig;
1475
+ /**
1476
+ * API CORS (public read-only APIs) — credentials disabled.
1477
+ * Logs a warning if used when NODE_ENV === 'production'.
1478
+ */
1479
+ api: () => CORSConfig;
1480
+ };
1481
+ /**
1482
+ * Security middleware creator
1483
+ */
1484
+ declare function createSecurityMiddleware(securityConfig?: SecurityHeadersConfig, corsConfig?: CORSConfig): (request: Request, next: () => Promise<Response>) => Promise<Response>;
1485
+ /**
1486
+ * Rate limiting headers
1487
+ */
1488
+ declare function setRateLimitHeaders(response: Response, limit: number, remaining: number, reset: number): void;
1489
+
1490
+ /**
1491
+ * Internal logger for @revealui/security.
1492
+ *
1493
+ * Defaults to `console`. Consumers should call `configureSecurityLogger()`
1494
+ * to supply a structured logger (e.g. from `@revealui/utils/logger`).
1495
+ */
1496
+ interface SecurityLogger {
1497
+ warn(message: string, ...args: unknown[]): void;
1498
+ error(message: string, ...args: unknown[]): void;
1499
+ info(message: string, ...args: unknown[]): void;
1500
+ debug(message: string, ...args: unknown[]): void;
1501
+ }
1502
+ /**
1503
+ * Replace the default console logger with a structured logger.
1504
+ */
1505
+ declare function configureSecurityLogger(logger: SecurityLogger): void;
1506
+
1507
+ export { type AlertHandler, type AlertingConfig, AuditAlertHandler, type AuditEvent, type AuditEventType, type AuditQuery, AuditReportGenerator, type AuditSeverity, type AuditStorage, AuditSystem, AuditTrail, type AuthorizationContext, AuthorizationSystem, type BreachStorage, type CORSConfig, CORSManager, CORSPresets, CommonRoles, ConsentManager, type ConsentRecord, type ConsentType, type ContentSecurityPolicyConfig, type CookieConsentConfig, CookieConsentManager, DEFAULT_THRESHOLDS, DataAnonymization, type DataBreach, DataBreachManager, type DataCategory, type DataDeletionRequest, DataDeletionSystem, DataExportSystem, DataMasking, type DataProcessingPurpose, type EncryptedData, type EncryptionConfig, EncryptionSystem, EnvelopeEncryption, FieldEncryption, type GDPRStorage, type HSTSConfig, InMemoryAuditStorage, InMemoryBreachStorage, InMemoryGDPRStorage, KeyRotationManager, LogAlertHandler, OAuthClient, type OAuthConfig, OAuthProviders, PasswordHasher, type Permission, PermissionBuilder, PermissionCache, type PermissionsPolicyConfig, type PersonalDataExport, type Policy, PolicyBuilder, type PolicyCondition, PrivacyPolicyManager, type ReferrerPolicyValue, RequirePermission, RequireRole, type Role, type SecurityAlert, SecurityAlertService, SecurityHeaders, type SecurityHeadersConfig, type SecurityLogger, SecurityPresets, type ThresholdRule, TokenGenerator, TwoFactorAuth, type User, WebhookAlertHandler, audit, authorization, canAccessResource, checkAttributeAccess, configureSecurityLogger, cookieConsentManager, createAuditMiddleware, createAuthorizationMiddleware, createConsentManager, createDataBreachManager, createDataDeletionSystem, createSecurityMiddleware, dataExportSystem, encryption, permissionCache, privacyPolicyManager, setRateLimitHeaders, signAuditEntry, verifyAuditEntry };