@zintrust/workers 0.1.27

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.
Files changed (178) hide show
  1. package/README.md +861 -0
  2. package/dist/AnomalyDetection.d.ts +102 -0
  3. package/dist/AnomalyDetection.js +321 -0
  4. package/dist/AutoScaler.d.ts +127 -0
  5. package/dist/AutoScaler.js +425 -0
  6. package/dist/BroadcastWorker.d.ts +21 -0
  7. package/dist/BroadcastWorker.js +24 -0
  8. package/dist/CanaryController.d.ts +103 -0
  9. package/dist/CanaryController.js +380 -0
  10. package/dist/ChaosEngineering.d.ts +79 -0
  11. package/dist/ChaosEngineering.js +216 -0
  12. package/dist/CircuitBreaker.d.ts +106 -0
  13. package/dist/CircuitBreaker.js +374 -0
  14. package/dist/ClusterLock.d.ts +90 -0
  15. package/dist/ClusterLock.js +385 -0
  16. package/dist/ComplianceManager.d.ts +177 -0
  17. package/dist/ComplianceManager.js +556 -0
  18. package/dist/DatacenterOrchestrator.d.ts +133 -0
  19. package/dist/DatacenterOrchestrator.js +404 -0
  20. package/dist/DeadLetterQueue.d.ts +122 -0
  21. package/dist/DeadLetterQueue.js +539 -0
  22. package/dist/HealthMonitor.d.ts +42 -0
  23. package/dist/HealthMonitor.js +301 -0
  24. package/dist/MultiQueueWorker.d.ts +89 -0
  25. package/dist/MultiQueueWorker.js +277 -0
  26. package/dist/NotificationWorker.d.ts +21 -0
  27. package/dist/NotificationWorker.js +23 -0
  28. package/dist/Observability.d.ts +153 -0
  29. package/dist/Observability.js +530 -0
  30. package/dist/PluginManager.d.ts +123 -0
  31. package/dist/PluginManager.js +392 -0
  32. package/dist/PriorityQueue.d.ts +117 -0
  33. package/dist/PriorityQueue.js +244 -0
  34. package/dist/ResourceMonitor.d.ts +164 -0
  35. package/dist/ResourceMonitor.js +605 -0
  36. package/dist/SLAMonitor.d.ts +110 -0
  37. package/dist/SLAMonitor.js +274 -0
  38. package/dist/WorkerFactory.d.ts +193 -0
  39. package/dist/WorkerFactory.js +1507 -0
  40. package/dist/WorkerInit.d.ts +85 -0
  41. package/dist/WorkerInit.js +223 -0
  42. package/dist/WorkerMetrics.d.ts +114 -0
  43. package/dist/WorkerMetrics.js +509 -0
  44. package/dist/WorkerRegistry.d.ts +145 -0
  45. package/dist/WorkerRegistry.js +319 -0
  46. package/dist/WorkerShutdown.d.ts +61 -0
  47. package/dist/WorkerShutdown.js +159 -0
  48. package/dist/WorkerVersioning.d.ts +107 -0
  49. package/dist/WorkerVersioning.js +300 -0
  50. package/dist/build-manifest.json +462 -0
  51. package/dist/config/workerConfig.d.ts +3 -0
  52. package/dist/config/workerConfig.js +19 -0
  53. package/dist/createQueueWorker.d.ts +23 -0
  54. package/dist/createQueueWorker.js +113 -0
  55. package/dist/dashboard/index.d.ts +1 -0
  56. package/dist/dashboard/index.js +1 -0
  57. package/dist/dashboard/types.d.ts +117 -0
  58. package/dist/dashboard/types.js +1 -0
  59. package/dist/dashboard/workers-api.d.ts +4 -0
  60. package/dist/dashboard/workers-api.js +638 -0
  61. package/dist/dashboard/workers-dashboard-ui.d.ts +3 -0
  62. package/dist/dashboard/workers-dashboard-ui.js +1026 -0
  63. package/dist/dashboard/workers-dashboard.d.ts +4 -0
  64. package/dist/dashboard/workers-dashboard.js +904 -0
  65. package/dist/helper/index.d.ts +5 -0
  66. package/dist/helper/index.js +10 -0
  67. package/dist/http/WorkerApiController.d.ts +38 -0
  68. package/dist/http/WorkerApiController.js +312 -0
  69. package/dist/http/WorkerController.d.ts +374 -0
  70. package/dist/http/WorkerController.js +1351 -0
  71. package/dist/http/middleware/CustomValidation.d.ts +92 -0
  72. package/dist/http/middleware/CustomValidation.js +270 -0
  73. package/dist/http/middleware/DatacenterValidator.d.ts +3 -0
  74. package/dist/http/middleware/DatacenterValidator.js +94 -0
  75. package/dist/http/middleware/EditWorkerValidation.d.ts +7 -0
  76. package/dist/http/middleware/EditWorkerValidation.js +55 -0
  77. package/dist/http/middleware/FeaturesValidator.d.ts +3 -0
  78. package/dist/http/middleware/FeaturesValidator.js +60 -0
  79. package/dist/http/middleware/InfrastructureValidator.d.ts +31 -0
  80. package/dist/http/middleware/InfrastructureValidator.js +226 -0
  81. package/dist/http/middleware/OptionsValidator.d.ts +3 -0
  82. package/dist/http/middleware/OptionsValidator.js +112 -0
  83. package/dist/http/middleware/PayloadSanitizer.d.ts +7 -0
  84. package/dist/http/middleware/PayloadSanitizer.js +42 -0
  85. package/dist/http/middleware/ProcessorPathSanitizer.d.ts +3 -0
  86. package/dist/http/middleware/ProcessorPathSanitizer.js +74 -0
  87. package/dist/http/middleware/QueueNameSanitizer.d.ts +3 -0
  88. package/dist/http/middleware/QueueNameSanitizer.js +45 -0
  89. package/dist/http/middleware/ValidateDriver.d.ts +7 -0
  90. package/dist/http/middleware/ValidateDriver.js +20 -0
  91. package/dist/http/middleware/VersionSanitizer.d.ts +3 -0
  92. package/dist/http/middleware/VersionSanitizer.js +25 -0
  93. package/dist/http/middleware/WorkerNameSanitizer.d.ts +3 -0
  94. package/dist/http/middleware/WorkerNameSanitizer.js +46 -0
  95. package/dist/http/middleware/WorkerValidationChain.d.ts +27 -0
  96. package/dist/http/middleware/WorkerValidationChain.js +185 -0
  97. package/dist/index.d.ts +46 -0
  98. package/dist/index.js +48 -0
  99. package/dist/routes/workers.d.ts +12 -0
  100. package/dist/routes/workers.js +81 -0
  101. package/dist/storage/WorkerStore.d.ts +45 -0
  102. package/dist/storage/WorkerStore.js +195 -0
  103. package/dist/type.d.ts +76 -0
  104. package/dist/type.js +1 -0
  105. package/dist/ui/router/ui.d.ts +3 -0
  106. package/dist/ui/router/ui.js +83 -0
  107. package/dist/ui/types/worker-ui.d.ts +229 -0
  108. package/dist/ui/types/worker-ui.js +5 -0
  109. package/package.json +53 -0
  110. package/src/AnomalyDetection.ts +434 -0
  111. package/src/AutoScaler.ts +654 -0
  112. package/src/BroadcastWorker.ts +34 -0
  113. package/src/CanaryController.ts +531 -0
  114. package/src/ChaosEngineering.ts +301 -0
  115. package/src/CircuitBreaker.ts +495 -0
  116. package/src/ClusterLock.ts +499 -0
  117. package/src/ComplianceManager.ts +815 -0
  118. package/src/DatacenterOrchestrator.ts +561 -0
  119. package/src/DeadLetterQueue.ts +733 -0
  120. package/src/HealthMonitor.ts +390 -0
  121. package/src/MultiQueueWorker.ts +431 -0
  122. package/src/NotificationWorker.ts +33 -0
  123. package/src/Observability.ts +696 -0
  124. package/src/PluginManager.ts +551 -0
  125. package/src/PriorityQueue.ts +351 -0
  126. package/src/ResourceMonitor.ts +769 -0
  127. package/src/SLAMonitor.ts +408 -0
  128. package/src/WorkerFactory.ts +2108 -0
  129. package/src/WorkerInit.ts +313 -0
  130. package/src/WorkerMetrics.ts +709 -0
  131. package/src/WorkerRegistry.ts +443 -0
  132. package/src/WorkerShutdown.ts +210 -0
  133. package/src/WorkerVersioning.ts +422 -0
  134. package/src/config/workerConfig.ts +25 -0
  135. package/src/createQueueWorker.ts +174 -0
  136. package/src/dashboard/index.ts +6 -0
  137. package/src/dashboard/types.ts +141 -0
  138. package/src/dashboard/workers-api.ts +785 -0
  139. package/src/dashboard/zintrust.svg +30 -0
  140. package/src/helper/index.ts +11 -0
  141. package/src/http/WorkerApiController.ts +369 -0
  142. package/src/http/WorkerController.ts +1512 -0
  143. package/src/http/middleware/CustomValidation.ts +360 -0
  144. package/src/http/middleware/DatacenterValidator.ts +124 -0
  145. package/src/http/middleware/EditWorkerValidation.ts +74 -0
  146. package/src/http/middleware/FeaturesValidator.ts +82 -0
  147. package/src/http/middleware/InfrastructureValidator.ts +295 -0
  148. package/src/http/middleware/OptionsValidator.ts +144 -0
  149. package/src/http/middleware/PayloadSanitizer.ts +52 -0
  150. package/src/http/middleware/ProcessorPathSanitizer.ts +86 -0
  151. package/src/http/middleware/QueueNameSanitizer.ts +55 -0
  152. package/src/http/middleware/ValidateDriver.ts +29 -0
  153. package/src/http/middleware/VersionSanitizer.ts +30 -0
  154. package/src/http/middleware/WorkerNameSanitizer.ts +56 -0
  155. package/src/http/middleware/WorkerValidationChain.ts +230 -0
  156. package/src/index.ts +98 -0
  157. package/src/routes/workers.ts +154 -0
  158. package/src/storage/WorkerStore.ts +240 -0
  159. package/src/type.ts +89 -0
  160. package/src/types/queue-monitor.d.ts +38 -0
  161. package/src/types/queue-redis.d.ts +38 -0
  162. package/src/ui/README.md +13 -0
  163. package/src/ui/components/JsonEditor.js +670 -0
  164. package/src/ui/components/JsonViewer.js +387 -0
  165. package/src/ui/components/WorkerCard.js +178 -0
  166. package/src/ui/components/WorkerExpandPanel.js +257 -0
  167. package/src/ui/components/fetcher.js +42 -0
  168. package/src/ui/components/sla-scorecard.js +32 -0
  169. package/src/ui/components/styles.css +30 -0
  170. package/src/ui/components/table-expander.js +34 -0
  171. package/src/ui/integration/worker-ui-integration.js +565 -0
  172. package/src/ui/router/ui.ts +99 -0
  173. package/src/ui/services/workerApi.js +240 -0
  174. package/src/ui/types/worker-ui.ts +283 -0
  175. package/src/ui/utils/jsonValidator.js +444 -0
  176. package/src/ui/workers/index.html +202 -0
  177. package/src/ui/workers/main.js +1781 -0
  178. package/src/ui/workers/styles.css +1350 -0
@@ -0,0 +1,815 @@
1
+ /**
2
+ * Compliance Manager
3
+ * GDPR, HIPAA, and SOC2 compliance enforcement
4
+ * Sealed namespace for immutability
5
+ */
6
+
7
+ import {
8
+ ErrorFactory,
9
+ Logger,
10
+ NodeSingletons,
11
+ createRedisConnection,
12
+ type RedisConfig,
13
+ } from '@zintrust/core';
14
+ import type IORedis from 'ioredis';
15
+
16
+ type CryptoAdapter = {
17
+ createCipheriv: typeof NodeSingletons.createCipheriv;
18
+ createDecipheriv: typeof NodeSingletons.createDecipheriv;
19
+ pbkdf2Sync: typeof NodeSingletons.pbkdf2Sync;
20
+ randomBytes: typeof NodeSingletons.randomBytes;
21
+ };
22
+
23
+ // Access NodeSingletons lazily to avoid initialization errors in test environments
24
+ const getCrypto = (): CryptoAdapter => {
25
+ if (!NodeSingletons) {
26
+ throw ErrorFactory.createWorkerError('NodeSingletons not available');
27
+ }
28
+ return {
29
+ createCipheriv: NodeSingletons.createCipheriv,
30
+ createDecipheriv: NodeSingletons.createDecipheriv,
31
+ pbkdf2Sync: NodeSingletons.pbkdf2Sync,
32
+ randomBytes: NodeSingletons.randomBytes,
33
+ };
34
+ };
35
+
36
+ export type ComplianceStandard = 'gdpr' | 'hipaa' | 'soc2';
37
+
38
+ export type DataClassification = 'public' | 'internal' | 'confidential' | 'restricted';
39
+
40
+ export type ComplianceConfig = {
41
+ gdpr: {
42
+ enabled: boolean;
43
+ dataRetentionDays: number; // Maximum data retention (default: 365)
44
+ requireConsent: boolean;
45
+ enableRightToForgotten: boolean;
46
+ enableDataPortability: boolean;
47
+ enableAccessRequest: boolean;
48
+ };
49
+ hipaa: {
50
+ enabled: boolean;
51
+ requireEncryptionAtRest: boolean;
52
+ requireEncryptionInTransit: boolean;
53
+ auditRetentionYears: number; // Minimum 6 years required
54
+ requireAccessControls: boolean;
55
+ enableBreachNotification: boolean;
56
+ };
57
+ soc2: {
58
+ enabled: boolean;
59
+ requireChangeLogging: boolean;
60
+ requireAccessReviews: boolean;
61
+ accessReviewIntervalDays: number; // Default: 90 days
62
+ requireIncidentResponse: boolean;
63
+ requireDisasterRecovery: boolean;
64
+ };
65
+ };
66
+
67
+ export type DataSubject = {
68
+ id: string;
69
+ email?: string;
70
+ consentGiven: boolean;
71
+ consentDate?: Date;
72
+ consentWithdrawnDate?: Date;
73
+ dataClassification: DataClassification;
74
+ retentionPeriod?: number; // Days
75
+ deletionScheduled?: Date;
76
+ };
77
+
78
+ export type ComplianceAuditLog = {
79
+ id: string;
80
+ timestamp: Date;
81
+ standard: ComplianceStandard;
82
+ action: string;
83
+ userId: string;
84
+ userRole?: string;
85
+ dataSubjectId?: string;
86
+ resourceId: string;
87
+ resourceType: string;
88
+ ipAddress?: string;
89
+ userAgent?: string;
90
+ changes?: Record<string, { before: unknown; after: unknown }>;
91
+ result: 'success' | 'failure' | 'blocked';
92
+ reason?: string;
93
+ severity: 'info' | 'warning' | 'critical';
94
+ };
95
+
96
+ export type AccessRequest = {
97
+ id: string;
98
+ dataSubjectId: string;
99
+ requestType: 'access' | 'deletion' | 'portability' | 'rectification';
100
+ requestDate: Date;
101
+ status: 'pending' | 'approved' | 'rejected' | 'completed';
102
+ requestedBy: string;
103
+ approvedBy?: string;
104
+ completedBy?: string;
105
+ completedDate?: Date;
106
+ reason?: string;
107
+ dataExport?: string; // File path or URL
108
+ };
109
+
110
+ export type EncryptionMetadata = {
111
+ algorithm: string;
112
+ keyId: string;
113
+ encryptedAt: Date;
114
+ encryptedBy: string;
115
+ };
116
+
117
+ export type ComplianceViolation = {
118
+ id: string;
119
+ timestamp: Date;
120
+ standard: ComplianceStandard;
121
+ violationType: string;
122
+ severity: 'low' | 'medium' | 'high' | 'critical';
123
+ description: string;
124
+ affectedResources: string[];
125
+ remediation: string;
126
+ status: 'open' | 'in-progress' | 'resolved' | 'accepted-risk';
127
+ };
128
+
129
+ // Redis key prefixes
130
+ const AUDIT_LOG_PREFIX = 'compliance:audit:';
131
+ const DATA_SUBJECT_PREFIX = 'compliance:subject:';
132
+ const ACCESS_REQUEST_PREFIX = 'compliance:request:';
133
+ const VIOLATION_PREFIX = 'compliance:violation:';
134
+ const CONSENT_PREFIX = 'compliance:consent:';
135
+
136
+ // Internal state
137
+ let redisClient: IORedis | null = null;
138
+ let complianceConfig: ComplianceConfig | null = null;
139
+
140
+ // Default configuration
141
+ const DEFAULT_CONFIG: ComplianceConfig = {
142
+ gdpr: {
143
+ enabled: true,
144
+ dataRetentionDays: 365,
145
+ requireConsent: true,
146
+ enableRightToForgotten: true,
147
+ enableDataPortability: true,
148
+ enableAccessRequest: true,
149
+ },
150
+ hipaa: {
151
+ enabled: false,
152
+ requireEncryptionAtRest: true,
153
+ requireEncryptionInTransit: true,
154
+ auditRetentionYears: 6,
155
+ requireAccessControls: true,
156
+ enableBreachNotification: true,
157
+ },
158
+ soc2: {
159
+ enabled: true,
160
+ requireChangeLogging: true,
161
+ requireAccessReviews: true,
162
+ accessReviewIntervalDays: 90,
163
+ requireIncidentResponse: true,
164
+ requireDisasterRecovery: true,
165
+ },
166
+ };
167
+
168
+ /**
169
+ * Helper: Generate unique ID
170
+ */
171
+ const generateId = (): string => {
172
+ const { randomBytes } = getCrypto();
173
+ return randomBytes(16).toString('hex');
174
+ };
175
+
176
+ /**
177
+ * Helper: Encrypt data (AES-256-GCM)
178
+ */
179
+ const encryptData = (
180
+ data: string,
181
+ keyId: string
182
+ ): { encrypted: string; iv: string; authTag: string } => {
183
+ const { createCipheriv, pbkdf2Sync, randomBytes } = getCrypto();
184
+ // In production, retrieve key from secure key management service (AWS KMS, HashiCorp Vault, etc.)
185
+ const key = pbkdf2Sync(keyId, 'salt', 100_000, 32, 'sha256');
186
+ const iv = randomBytes(16);
187
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
188
+
189
+ let encrypted = cipher.update(data, 'utf8', 'hex');
190
+ encrypted += cipher.final('hex');
191
+
192
+ const authTag = cipher.getAuthTag();
193
+
194
+ return {
195
+ encrypted,
196
+ iv: iv.toString('hex'),
197
+ authTag: authTag.toString('hex'),
198
+ };
199
+ };
200
+
201
+ /**
202
+ * Helper: Decrypt data (AES-256-GCM)
203
+ */
204
+ const decryptData = (encrypted: string, iv: string, authTag: string, keyId: string): string => {
205
+ const { createDecipheriv, pbkdf2Sync } = getCrypto();
206
+ const key = pbkdf2Sync(keyId, 'salt', 100_000, 32, 'sha256');
207
+ const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(iv, 'hex'));
208
+ decipher.setAuthTag(Buffer.from(authTag, 'hex'));
209
+
210
+ let decrypted = decipher.update(encrypted, 'hex', 'utf8');
211
+ decrypted += decipher.final('utf8');
212
+
213
+ return decrypted;
214
+ };
215
+
216
+ /**
217
+ * Helper: Check if consent is required and valid
218
+ */
219
+ const checkConsent = async (
220
+ dataSubjectId: string
221
+ ): Promise<{ valid: boolean; reason?: string }> => {
222
+ const gdprConfig = complianceConfig?.gdpr;
223
+ if (gdprConfig?.enabled !== true || gdprConfig?.requireConsent !== true) {
224
+ return { valid: true };
225
+ }
226
+
227
+ if (!redisClient) {
228
+ return { valid: false, reason: 'Compliance system not initialized' };
229
+ }
230
+
231
+ const key = `${DATA_SUBJECT_PREFIX}${dataSubjectId}`;
232
+ const subjectJson = await redisClient.get(key);
233
+
234
+ if (subjectJson === null) {
235
+ return { valid: false, reason: 'Data subject not found' };
236
+ }
237
+
238
+ const subject = JSON.parse(subjectJson) as DataSubject;
239
+
240
+ if (!subject.consentGiven) {
241
+ return { valid: false, reason: 'Consent not given' };
242
+ }
243
+
244
+ if (subject.consentWithdrawnDate) {
245
+ return { valid: false, reason: 'Consent withdrawn' };
246
+ }
247
+
248
+ return { valid: true };
249
+ };
250
+
251
+ /**
252
+ * Helper: Store audit log
253
+ */
254
+ const storeAuditLog = async (log: ComplianceAuditLog): Promise<void> => {
255
+ if (!redisClient) return;
256
+
257
+ try {
258
+ const key = `${AUDIT_LOG_PREFIX}${log.standard}`;
259
+ const score = log.timestamp.getTime();
260
+ const data = JSON.stringify(log);
261
+
262
+ await redisClient.zadd(key, score, data);
263
+
264
+ // Set retention based on standard
265
+ let retentionDays = 365; // Default 1 year
266
+
267
+ if (log.standard === 'hipaa' && complianceConfig?.hipaa.enabled === true) {
268
+ retentionDays = complianceConfig.hipaa.auditRetentionYears * 365;
269
+ }
270
+
271
+ await redisClient.expire(key, retentionDays * 24 * 60 * 60);
272
+
273
+ Logger.debug('Compliance audit log stored', {
274
+ standard: log.standard,
275
+ action: log.action,
276
+ userId: log.userId,
277
+ });
278
+ } catch (error) {
279
+ Logger.error('Failed to store compliance audit log', error);
280
+ }
281
+ };
282
+
283
+ const hasNonEmptyString = (value?: string): value is string => {
284
+ return typeof value === 'string' && value.length > 0;
285
+ };
286
+
287
+ const runGdprChecks = async (dataSubjectId?: string): Promise<string[]> => {
288
+ if (complianceConfig?.gdpr.enabled !== true) {
289
+ return [];
290
+ }
291
+
292
+ if (!hasNonEmptyString(dataSubjectId)) {
293
+ return [];
294
+ }
295
+
296
+ const consentCheck = await checkConsent(dataSubjectId);
297
+ if (consentCheck.valid) {
298
+ return [];
299
+ }
300
+
301
+ return [`GDPR: ${consentCheck.reason}`];
302
+ };
303
+
304
+ const runHipaaChecks = (action: string, userId: string, resourceId?: string): string[] => {
305
+ if (complianceConfig?.hipaa.enabled !== true) {
306
+ return [];
307
+ }
308
+
309
+ if (complianceConfig.hipaa.requireAccessControls !== true) {
310
+ return [];
311
+ }
312
+
313
+ Logger.debug('HIPAA access control check', { action, userId, resourceId });
314
+ return [];
315
+ };
316
+
317
+ const runSoc2Checks = (action: string): string[] => {
318
+ if (complianceConfig?.soc2.enabled !== true) {
319
+ return [];
320
+ }
321
+
322
+ if (complianceConfig.soc2.requireChangeLogging !== true) {
323
+ return [];
324
+ }
325
+
326
+ if (action.includes('modify') || action.includes('delete') || action.includes('update')) {
327
+ return [];
328
+ }
329
+
330
+ return [];
331
+ };
332
+
333
+ /**
334
+ * Compliance Manager - Sealed namespace
335
+ */
336
+ export const ComplianceManager = Object.freeze({
337
+ /**
338
+ * Initialize compliance manager
339
+ */
340
+ initialize(redisConfig: RedisConfig, config?: Partial<ComplianceConfig>): void {
341
+ if (redisClient) {
342
+ Logger.warn('ComplianceManager already initialized');
343
+ return;
344
+ }
345
+
346
+ redisClient = createRedisConnection(redisConfig);
347
+ complianceConfig = {
348
+ gdpr: { ...DEFAULT_CONFIG.gdpr, ...config?.gdpr },
349
+ hipaa: { ...DEFAULT_CONFIG.hipaa, ...config?.hipaa },
350
+ soc2: { ...DEFAULT_CONFIG.soc2, ...config?.soc2 },
351
+ };
352
+
353
+ Logger.info('ComplianceManager initialized', {
354
+ gdpr: complianceConfig.gdpr.enabled,
355
+ hipaa: complianceConfig.hipaa.enabled,
356
+ soc2: complianceConfig.soc2.enabled,
357
+ });
358
+ },
359
+
360
+ /**
361
+ * Register data subject
362
+ */
363
+ async registerDataSubject(subject: DataSubject): Promise<void> {
364
+ if (!redisClient) {
365
+ throw ErrorFactory.createConfigError('ComplianceManager not initialized');
366
+ }
367
+
368
+ const key = `${DATA_SUBJECT_PREFIX}${subject.id}`;
369
+ await redisClient.set(key, JSON.stringify(subject));
370
+
371
+ // Set expiry based on retention period
372
+ if (subject.retentionPeriod !== undefined) {
373
+ await redisClient.expire(key, subject.retentionPeriod * 24 * 60 * 60);
374
+ }
375
+
376
+ await storeAuditLog({
377
+ id: generateId(),
378
+ timestamp: new Date(),
379
+ standard: 'gdpr',
380
+ action: 'data-subject-registered',
381
+ userId: 'system',
382
+ dataSubjectId: subject.id,
383
+ resourceId: subject.id,
384
+ resourceType: 'data-subject',
385
+ result: 'success',
386
+ severity: 'info',
387
+ });
388
+
389
+ Logger.info('Data subject registered', { id: subject.id });
390
+ },
391
+
392
+ /**
393
+ * Record consent
394
+ */
395
+ async recordConsent(dataSubjectId: string, consentGiven: boolean, userId: string): Promise<void> {
396
+ const client = redisClient;
397
+ const gdprConfig = complianceConfig?.gdpr;
398
+ if (!client || gdprConfig?.enabled !== true) {
399
+ throw ErrorFactory.createConfigError('GDPR compliance not enabled');
400
+ }
401
+
402
+ const subjectKey = `${DATA_SUBJECT_PREFIX}${dataSubjectId}`;
403
+ const subjectJson = await client.get(subjectKey);
404
+
405
+ if (subjectJson === null) {
406
+ throw ErrorFactory.createNotFoundError(`Data subject not found: ${dataSubjectId}`);
407
+ }
408
+
409
+ const subject = JSON.parse(subjectJson) as DataSubject;
410
+ subject.consentGiven = consentGiven;
411
+
412
+ if (consentGiven) {
413
+ subject.consentDate = new Date();
414
+ subject.consentWithdrawnDate = undefined;
415
+ } else {
416
+ subject.consentWithdrawnDate = new Date();
417
+ }
418
+
419
+ await client.set(subjectKey, JSON.stringify(subject));
420
+
421
+ // Store consent in separate key for auditing
422
+ const consentKey = `${CONSENT_PREFIX}${dataSubjectId}`;
423
+ const consentRecord = {
424
+ dataSubjectId,
425
+ consentGiven,
426
+ timestamp: new Date(),
427
+ recordedBy: userId,
428
+ };
429
+
430
+ await client.zadd(consentKey, Date.now(), JSON.stringify(consentRecord));
431
+
432
+ await storeAuditLog({
433
+ id: generateId(),
434
+ timestamp: new Date(),
435
+ standard: 'gdpr',
436
+ action: consentGiven ? 'consent-given' : 'consent-withdrawn',
437
+ userId,
438
+ dataSubjectId,
439
+ resourceId: dataSubjectId,
440
+ resourceType: 'consent',
441
+ result: 'success',
442
+ severity: 'info',
443
+ });
444
+
445
+ Logger.info('Consent recorded', { dataSubjectId, consentGiven });
446
+ },
447
+
448
+ /**
449
+ * Check if action is compliant
450
+ */
451
+ async checkCompliance(
452
+ action: string,
453
+ userId: string,
454
+ dataSubjectId?: string,
455
+ resourceId?: string
456
+ ): Promise<{ compliant: boolean; violations: string[] }> {
457
+ const violations: string[] = [];
458
+
459
+ const gdprViolations = await runGdprChecks(dataSubjectId);
460
+ violations.push(...gdprViolations);
461
+
462
+ const hipaaViolations = runHipaaChecks(action, userId, resourceId);
463
+ violations.push(...hipaaViolations);
464
+
465
+ const soc2Violations = runSoc2Checks(action);
466
+ violations.push(...soc2Violations);
467
+
468
+ const compliant = violations.length === 0;
469
+
470
+ if (!compliant) {
471
+ await storeAuditLog({
472
+ id: generateId(),
473
+ timestamp: new Date(),
474
+ standard: 'gdpr', // Primary standard for consent
475
+ action,
476
+ userId,
477
+ dataSubjectId,
478
+ resourceId: resourceId ?? 'unknown',
479
+ resourceType: 'compliance-check',
480
+ result: 'blocked',
481
+ reason: violations.join('; '),
482
+ severity: 'warning',
483
+ });
484
+ }
485
+
486
+ return { compliant, violations };
487
+ },
488
+
489
+ /**
490
+ * Create access request (GDPR Right to Access, Deletion, etc.)
491
+ */
492
+ async createAccessRequest(
493
+ request: Omit<AccessRequest, 'id' | 'requestDate' | 'status'>
494
+ ): Promise<string> {
495
+ if (!redisClient) {
496
+ throw ErrorFactory.createConfigError('ComplianceManager not initialized');
497
+ }
498
+
499
+ const requestId = generateId();
500
+ const fullRequest: AccessRequest = {
501
+ id: requestId,
502
+ requestDate: new Date(),
503
+ status: 'pending',
504
+ ...request,
505
+ };
506
+
507
+ const key = `${ACCESS_REQUEST_PREFIX}${requestId}`;
508
+ await redisClient.set(key, JSON.stringify(fullRequest));
509
+
510
+ await storeAuditLog({
511
+ id: generateId(),
512
+ timestamp: new Date(),
513
+ standard: 'gdpr',
514
+ action: `access-request-${request.requestType}`,
515
+ userId: request.requestedBy,
516
+ dataSubjectId: request.dataSubjectId,
517
+ resourceId: requestId,
518
+ resourceType: 'access-request',
519
+ result: 'success',
520
+ severity: 'info',
521
+ });
522
+
523
+ Logger.info('Access request created', {
524
+ id: requestId,
525
+ type: request.requestType,
526
+ dataSubjectId: request.dataSubjectId,
527
+ });
528
+
529
+ return requestId;
530
+ },
531
+
532
+ /**
533
+ * Process access request
534
+ */
535
+ async processAccessRequest(
536
+ requestId: string,
537
+ status: AccessRequest['status'],
538
+ processedBy: string
539
+ ): Promise<void> {
540
+ if (!redisClient) {
541
+ throw ErrorFactory.createConfigError('ComplianceManager not initialized');
542
+ }
543
+
544
+ const key = `${ACCESS_REQUEST_PREFIX}${requestId}`;
545
+ const requestJson = await redisClient.get(key);
546
+
547
+ if (requestJson === null) {
548
+ throw ErrorFactory.createNotFoundError(`Access request not found: ${requestId}`);
549
+ }
550
+
551
+ const request = JSON.parse(requestJson) as AccessRequest;
552
+ request.status = status;
553
+
554
+ if (status === 'approved') {
555
+ request.approvedBy = processedBy;
556
+ } else if (status === 'completed') {
557
+ request.completedBy = processedBy;
558
+ request.completedDate = new Date();
559
+ }
560
+
561
+ await redisClient.set(key, JSON.stringify(request));
562
+
563
+ await storeAuditLog({
564
+ id: generateId(),
565
+ timestamp: new Date(),
566
+ standard: 'gdpr',
567
+ action: `access-request-${status}`,
568
+ userId: processedBy,
569
+ dataSubjectId: request.dataSubjectId,
570
+ resourceId: requestId,
571
+ resourceType: 'access-request',
572
+ result: 'success',
573
+ severity: status === 'rejected' ? 'warning' : 'info',
574
+ });
575
+
576
+ Logger.info('Access request processed', { id: requestId, status });
577
+ },
578
+
579
+ /**
580
+ * Encrypt sensitive data (HIPAA compliance)
581
+ */
582
+ encryptSensitiveData(
583
+ data: string,
584
+ userId: string,
585
+ keyId = 'default-key'
586
+ ): {
587
+ encrypted: string;
588
+ metadata: EncryptionMetadata;
589
+ } {
590
+ if (
591
+ complianceConfig?.hipaa.enabled === true &&
592
+ complianceConfig.hipaa.requireEncryptionAtRest !== true
593
+ ) {
594
+ Logger.warn('HIPAA encryption not enforced by configuration');
595
+ }
596
+
597
+ const { encrypted, iv, authTag } = encryptData(data, keyId);
598
+
599
+ const metadata: EncryptionMetadata = {
600
+ algorithm: 'aes-256-gcm',
601
+ keyId,
602
+ encryptedAt: new Date(),
603
+ encryptedBy: userId,
604
+ };
605
+
606
+ // Store IV and authTag with encrypted data
607
+ const encryptedPackage = JSON.stringify({ encrypted, iv, authTag, metadata });
608
+
609
+ return {
610
+ encrypted: encryptedPackage,
611
+ metadata,
612
+ };
613
+ },
614
+
615
+ /**
616
+ * Decrypt sensitive data
617
+ */
618
+ decryptSensitiveData(encryptedPackage: string, userId: string): string {
619
+ const parsed = JSON.parse(encryptedPackage) as Partial<{
620
+ encrypted: string;
621
+ iv: string;
622
+ authTag: string;
623
+ metadata: EncryptionMetadata;
624
+ }>;
625
+
626
+ if (
627
+ typeof parsed.encrypted !== 'string' ||
628
+ typeof parsed.iv !== 'string' ||
629
+ typeof parsed.authTag !== 'string' ||
630
+ typeof parsed.metadata?.keyId !== 'string'
631
+ ) {
632
+ throw ErrorFactory.createValidationError('Invalid encrypted payload');
633
+ }
634
+
635
+ const { encrypted, iv, authTag, metadata } = parsed;
636
+
637
+ storeAuditLog({
638
+ id: generateId(),
639
+ timestamp: new Date(),
640
+ standard: 'hipaa',
641
+ action: 'data-decrypted',
642
+ userId,
643
+ resourceId: metadata.keyId,
644
+ resourceType: 'encrypted-data',
645
+ result: 'success',
646
+ severity: 'info',
647
+ });
648
+
649
+ return decryptData(encrypted, iv, authTag, metadata.keyId);
650
+ },
651
+
652
+ /**
653
+ * Record compliance violation
654
+ */
655
+ async recordViolation(violation: Omit<ComplianceViolation, 'id' | 'timestamp'>): Promise<string> {
656
+ if (!redisClient) {
657
+ throw ErrorFactory.createConfigError('ComplianceManager not initialized');
658
+ }
659
+
660
+ const violationId = generateId();
661
+ const fullViolation: ComplianceViolation = {
662
+ id: violationId,
663
+ timestamp: new Date(),
664
+ ...violation,
665
+ };
666
+
667
+ const key = `${VIOLATION_PREFIX}${violationId}`;
668
+ await redisClient.set(key, JSON.stringify(fullViolation));
669
+
670
+ await storeAuditLog({
671
+ id: generateId(),
672
+ timestamp: new Date(),
673
+ standard: violation.standard,
674
+ action: 'violation-recorded',
675
+ userId: 'system',
676
+ resourceId: violationId,
677
+ resourceType: 'compliance-violation',
678
+ result: 'success',
679
+ severity: 'critical',
680
+ reason: violation.description,
681
+ });
682
+
683
+ Logger.error('Compliance violation recorded', {
684
+ id: violationId,
685
+ standard: violation.standard,
686
+ type: violation.violationType,
687
+ severity: violation.severity,
688
+ });
689
+
690
+ return violationId;
691
+ },
692
+
693
+ /**
694
+ * Get audit logs
695
+ */
696
+ async getAuditLogs(
697
+ standard: ComplianceStandard,
698
+ startDate?: Date,
699
+ endDate?: Date,
700
+ limit = 1000
701
+ ): Promise<ReadonlyArray<ComplianceAuditLog>> {
702
+ if (!redisClient) {
703
+ throw ErrorFactory.createConfigError('ComplianceManager not initialized');
704
+ }
705
+
706
+ try {
707
+ const key = `${AUDIT_LOG_PREFIX}${standard}`;
708
+ const minScore = startDate ? startDate.getTime() : '-inf';
709
+ const maxScore = endDate ? endDate.getTime() : '+inf';
710
+
711
+ const logs = await redisClient.zrangebyscore(key, minScore, maxScore, 'LIMIT', 0, limit);
712
+
713
+ return logs.map((log) => JSON.parse(log) as ComplianceAuditLog);
714
+ } catch (error) {
715
+ Logger.error('Failed to retrieve audit logs', error);
716
+ return [];
717
+ }
718
+ },
719
+
720
+ /**
721
+ * Get compliance summary
722
+ */
723
+ async getComplianceSummary(): Promise<{
724
+ gdpr: { enabled: boolean; dataSubjects: number; pendingRequests: number };
725
+ hipaa: { enabled: boolean; encryptedResources: number; auditLogRetention: string };
726
+ soc2: { enabled: boolean; violations: number; lastAccessReview?: Date };
727
+ }> {
728
+ if (!redisClient || !complianceConfig) {
729
+ throw ErrorFactory.createConfigError('ComplianceManager not initialized');
730
+ }
731
+
732
+ const client = redisClient;
733
+ const config = complianceConfig;
734
+
735
+ // Count data subjects
736
+ const subjectKeys = await client.keys(`${DATA_SUBJECT_PREFIX}*`);
737
+
738
+ // Count pending access requests
739
+ const requestKeys = await client.keys(`${ACCESS_REQUEST_PREFIX}*`);
740
+ let pendingRequests = 0;
741
+
742
+ const requestEntries = await Promise.all(requestKeys.map(async (key) => client.get(key)));
743
+
744
+ requestEntries.forEach((requestJson) => {
745
+ if (requestJson !== null) {
746
+ const request = JSON.parse(requestJson) as AccessRequest;
747
+ if (request.status === 'pending') {
748
+ pendingRequests++;
749
+ }
750
+ }
751
+ });
752
+
753
+ // Count violations
754
+ const violationKeys = await client.keys(`${VIOLATION_PREFIX}*`);
755
+
756
+ return {
757
+ gdpr: {
758
+ enabled: config.gdpr.enabled,
759
+ dataSubjects: subjectKeys.length,
760
+ pendingRequests,
761
+ },
762
+ hipaa: {
763
+ enabled: config.hipaa.enabled,
764
+ encryptedResources: 0, // Would need to track this separately
765
+ auditLogRetention: `${config.hipaa.auditRetentionYears} years`,
766
+ },
767
+ soc2: {
768
+ enabled: config.soc2.enabled,
769
+ violations: violationKeys.length,
770
+ },
771
+ };
772
+ },
773
+
774
+ /**
775
+ * Get configuration
776
+ */
777
+ getConfig(): ComplianceConfig | null {
778
+ return complianceConfig ? { ...complianceConfig } : null;
779
+ },
780
+
781
+ /**
782
+ * Update configuration
783
+ */
784
+ updateConfig(config: Partial<ComplianceConfig>): void {
785
+ if (!complianceConfig) {
786
+ throw ErrorFactory.createConfigError('ComplianceManager not initialized');
787
+ }
788
+
789
+ complianceConfig = {
790
+ gdpr: { ...complianceConfig.gdpr, ...config.gdpr },
791
+ hipaa: { ...complianceConfig.hipaa, ...config.hipaa },
792
+ soc2: { ...complianceConfig.soc2, ...config.soc2 },
793
+ };
794
+
795
+ Logger.info('Compliance configuration updated', { config });
796
+ },
797
+
798
+ /**
799
+ * Shutdown
800
+ */
801
+ async shutdown(): Promise<void> {
802
+ Logger.info('ComplianceManager shutting down...');
803
+
804
+ if (redisClient) {
805
+ await redisClient.quit();
806
+ redisClient = null;
807
+ }
808
+
809
+ complianceConfig = null;
810
+
811
+ Logger.info('ComplianceManager shutdown complete');
812
+ },
813
+ });
814
+
815
+ // Graceful shutdown handled by WorkerShutdown