beddel 0.1.0
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.
- package/README.md +297 -0
- package/dist/agents/agentRegistry.d.ts +68 -0
- package/dist/agents/agentRegistry.d.ts.map +1 -0
- package/dist/agents/agentRegistry.js +222 -0
- package/dist/agents/agentRegistry.js.map +1 -0
- package/dist/agents/formatter-agent.d.ts +10 -0
- package/dist/agents/formatter-agent.d.ts.map +1 -0
- package/dist/agents/formatter-agent.js +49 -0
- package/dist/agents/formatter-agent.js.map +1 -0
- package/dist/agents/genkit-agent.d.ts +12 -0
- package/dist/agents/genkit-agent.d.ts.map +1 -0
- package/dist/agents/genkit-agent.js +119 -0
- package/dist/agents/genkit-agent.js.map +1 -0
- package/dist/agents/i18n-messages.d.ts +17 -0
- package/dist/agents/i18n-messages.d.ts.map +1 -0
- package/dist/agents/i18n-messages.js +92 -0
- package/dist/agents/i18n-messages.js.map +1 -0
- package/dist/agents/index.d.ts +10 -0
- package/dist/agents/index.d.ts.map +1 -0
- package/dist/agents/index.js +26 -0
- package/dist/agents/index.js.map +1 -0
- package/dist/agents/pipeline.d.ts +15 -0
- package/dist/agents/pipeline.d.ts.map +1 -0
- package/dist/agents/pipeline.js +45 -0
- package/dist/agents/pipeline.js.map +1 -0
- package/dist/agents/schema-factory.d.ts +40 -0
- package/dist/agents/schema-factory.d.ts.map +1 -0
- package/dist/agents/schema-factory.js +121 -0
- package/dist/agents/schema-factory.js.map +1 -0
- package/dist/agents/translation-validators.d.ts +26 -0
- package/dist/agents/translation-validators.d.ts.map +1 -0
- package/dist/agents/translation-validators.js +77 -0
- package/dist/agents/translation-validators.js.map +1 -0
- package/dist/agents/translator-agents.d.ts +184 -0
- package/dist/agents/translator-agents.d.ts.map +1 -0
- package/dist/agents/translator-agents.js +613 -0
- package/dist/agents/translator-agents.js.map +1 -0
- package/dist/agents/types/translation.types.d.ts +100 -0
- package/dist/agents/types/translation.types.d.ts.map +1 -0
- package/dist/agents/types/translation.types.js +3 -0
- package/dist/agents/types/translation.types.js.map +1 -0
- package/dist/agents/validator-agent.d.ts +42 -0
- package/dist/agents/validator-agent.d.ts.map +1 -0
- package/dist/agents/validator-agent.js +122 -0
- package/dist/agents/validator-agent.js.map +1 -0
- package/dist/audit/auditTrail.d.ts +55 -0
- package/dist/audit/auditTrail.d.ts.map +1 -0
- package/dist/audit/auditTrail.js +93 -0
- package/dist/audit/auditTrail.js.map +1 -0
- package/dist/compliance/gdprEngine.d.ts +44 -0
- package/dist/compliance/gdprEngine.d.ts.map +1 -0
- package/dist/compliance/gdprEngine.js +178 -0
- package/dist/compliance/gdprEngine.js.map +1 -0
- package/dist/compliance/lgpdEngine.d.ts +51 -0
- package/dist/compliance/lgpdEngine.d.ts.map +1 -0
- package/dist/compliance/lgpdEngine.js +221 -0
- package/dist/compliance/lgpdEngine.js.map +1 -0
- package/dist/config.d.ts +78 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +77 -0
- package/dist/config.js.map +1 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +40 -0
- package/dist/errors.js.map +1 -0
- package/dist/firebase/tenantManager.d.ts +84 -0
- package/dist/firebase/tenantManager.d.ts.map +1 -0
- package/dist/firebase/tenantManager.js +378 -0
- package/dist/firebase/tenantManager.js.map +1 -0
- package/dist/index.d.ts +36 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +118 -0
- package/dist/index.js.map +1 -0
- package/dist/integration/secure-yaml-runtime.d.ts +68 -0
- package/dist/integration/secure-yaml-runtime.d.ts.map +1 -0
- package/dist/integration/secure-yaml-runtime.js +245 -0
- package/dist/integration/secure-yaml-runtime.js.map +1 -0
- package/dist/parser/secure-yaml-parser.d.ts +62 -0
- package/dist/parser/secure-yaml-parser.d.ts.map +1 -0
- package/dist/parser/secure-yaml-parser.js +234 -0
- package/dist/parser/secure-yaml-parser.js.map +1 -0
- package/dist/performance/autoscaling.d.ts +100 -0
- package/dist/performance/autoscaling.d.ts.map +1 -0
- package/dist/performance/autoscaling.js +339 -0
- package/dist/performance/autoscaling.js.map +1 -0
- package/dist/performance/benchmark.d.ts +104 -0
- package/dist/performance/benchmark.d.ts.map +1 -0
- package/dist/performance/benchmark.js +514 -0
- package/dist/performance/benchmark.js.map +1 -0
- package/dist/performance/index.d.ts +14 -0
- package/dist/performance/index.d.ts.map +1 -0
- package/dist/performance/index.js +35 -0
- package/dist/performance/index.js.map +1 -0
- package/dist/performance/monitor.d.ts +126 -0
- package/dist/performance/monitor.d.ts.map +1 -0
- package/dist/performance/monitor.js +324 -0
- package/dist/performance/monitor.js.map +1 -0
- package/dist/performance/streaming.d.ts +82 -0
- package/dist/performance/streaming.d.ts.map +1 -0
- package/dist/performance/streaming.js +287 -0
- package/dist/performance/streaming.js.map +1 -0
- package/dist/runtime/audit.d.ts +240 -0
- package/dist/runtime/audit.d.ts.map +1 -0
- package/dist/runtime/audit.js +641 -0
- package/dist/runtime/audit.js.map +1 -0
- package/dist/runtime/declarativeAgentRuntime.d.ts +123 -0
- package/dist/runtime/declarativeAgentRuntime.d.ts.map +1 -0
- package/dist/runtime/declarativeAgentRuntime.js +576 -0
- package/dist/runtime/declarativeAgentRuntime.js.map +1 -0
- package/dist/runtime/isolatedRuntime.d.ts +119 -0
- package/dist/runtime/isolatedRuntime.d.ts.map +1 -0
- package/dist/runtime/isolatedRuntime.js +425 -0
- package/dist/runtime/isolatedRuntime.js.map +1 -0
- package/dist/runtime/schemaCompiler.d.ts +35 -0
- package/dist/runtime/schemaCompiler.d.ts.map +1 -0
- package/dist/runtime/schemaCompiler.js +151 -0
- package/dist/runtime/schemaCompiler.js.map +1 -0
- package/dist/runtime/simpleRuntime.d.ts +57 -0
- package/dist/runtime/simpleRuntime.d.ts.map +1 -0
- package/dist/runtime/simpleRuntime.js +187 -0
- package/dist/runtime/simpleRuntime.js.map +1 -0
- package/dist/security/dashboard.d.ts +89 -0
- package/dist/security/dashboard.d.ts.map +1 -0
- package/dist/security/dashboard.js +300 -0
- package/dist/security/dashboard.js.map +1 -0
- package/dist/security/hardening.d.ts +130 -0
- package/dist/security/hardening.d.ts.map +1 -0
- package/dist/security/hardening.js +414 -0
- package/dist/security/hardening.js.map +1 -0
- package/dist/security/index.d.ts +128 -0
- package/dist/security/index.d.ts.map +1 -0
- package/dist/security/index.js +353 -0
- package/dist/security/index.js.map +1 -0
- package/dist/security/monitor.d.ts +88 -0
- package/dist/security/monitor.d.ts.map +1 -0
- package/dist/security/monitor.js +356 -0
- package/dist/security/monitor.js.map +1 -0
- package/dist/security/scanner.d.ts +104 -0
- package/dist/security/scanner.d.ts.map +1 -0
- package/dist/security/scanner.js +298 -0
- package/dist/security/scanner.js.map +1 -0
- package/dist/security/score.d.ts +150 -0
- package/dist/security/score.d.ts.map +1 -0
- package/dist/security/score.js +983 -0
- package/dist/security/score.js.map +1 -0
- package/dist/security/test-security.d.ts +22 -0
- package/dist/security/test-security.d.ts.map +1 -0
- package/dist/security/test-security.js +154 -0
- package/dist/security/test-security.js.map +1 -0
- package/dist/security/threatDetector.d.ts +39 -0
- package/dist/security/threatDetector.d.ts.map +1 -0
- package/dist/security/threatDetector.js +354 -0
- package/dist/security/threatDetector.js.map +1 -0
- package/dist/security/validation.d.ts +69 -0
- package/dist/security/validation.d.ts.map +1 -0
- package/dist/security/validation.js +286 -0
- package/dist/security/validation.js.map +1 -0
- package/dist/server/api/clientsRoute.d.ts +9 -0
- package/dist/server/api/clientsRoute.d.ts.map +1 -0
- package/dist/server/api/clientsRoute.js +71 -0
- package/dist/server/api/clientsRoute.js.map +1 -0
- package/dist/server/api/endpointsRoute.d.ts +8 -0
- package/dist/server/api/endpointsRoute.d.ts.map +1 -0
- package/dist/server/api/endpointsRoute.js +76 -0
- package/dist/server/api/endpointsRoute.js.map +1 -0
- package/dist/server/api/graphql.d.ts +9 -0
- package/dist/server/api/graphql.d.ts.map +1 -0
- package/dist/server/api/graphql.js +180 -0
- package/dist/server/api/graphql.js.map +1 -0
- package/dist/server/errors.d.ts +19 -0
- package/dist/server/errors.d.ts.map +1 -0
- package/dist/server/errors.js +42 -0
- package/dist/server/errors.js.map +1 -0
- package/dist/server/index.d.ts +7 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +24 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/kvStore.d.ts +27 -0
- package/dist/server/kvStore.d.ts.map +1 -0
- package/dist/server/kvStore.js +128 -0
- package/dist/server/kvStore.js.map +1 -0
- package/dist/server/runtimeSecurity.d.ts +28 -0
- package/dist/server/runtimeSecurity.d.ts.map +1 -0
- package/dist/server/runtimeSecurity.js +85 -0
- package/dist/server/runtimeSecurity.js.map +1 -0
- package/dist/server/types.d.ts +53 -0
- package/dist/server/types.d.ts.map +1 -0
- package/dist/server/types.js +8 -0
- package/dist/server/types.js.map +1 -0
- package/dist/types/executionContext.d.ts +16 -0
- package/dist/types/executionContext.d.ts.map +1 -0
- package/dist/types/executionContext.js +3 -0
- package/dist/types/executionContext.js.map +1 -0
- package/package.json +77 -0
- package/src/agents/agentRegistry.ts +272 -0
- package/src/agents/image-agent.yaml +86 -0
- package/src/agents/joker-agent.yaml +47 -0
- package/src/agents/translator-agent.yaml +80 -0
- package/src/audit/auditTrail.ts +134 -0
- package/src/compliance/gdprEngine.ts +209 -0
- package/src/compliance/lgpdEngine.ts +268 -0
- package/src/config.ts +179 -0
- package/src/errors.ts +35 -0
- package/src/firebase/tenantManager.ts +443 -0
- package/src/index.ts +125 -0
- package/src/integration/secure-yaml-runtime.ts +341 -0
- package/src/parser/secure-yaml-parser.ts +273 -0
- package/src/performance/autoscaling.ts +495 -0
- package/src/performance/benchmark.ts +644 -0
- package/src/performance/index.ts +34 -0
- package/src/performance/monitor.ts +469 -0
- package/src/performance/streaming.ts +317 -0
- package/src/runtime/audit.ts +907 -0
- package/src/runtime/declarativeAgentRuntime.ts +836 -0
- package/src/runtime/isolatedRuntime.ts +572 -0
- package/src/runtime/schemaCompiler.ts +228 -0
- package/src/runtime/simpleRuntime.ts +201 -0
- package/src/security/dashboard.ts +462 -0
- package/src/security/hardening.ts +560 -0
- package/src/security/index.ts +439 -0
- package/src/security/monitor.ts +490 -0
- package/src/security/scanner.ts +368 -0
- package/src/security/score.ts +1138 -0
- package/src/security/threatDetector.ts +481 -0
- package/src/security/validation.ts +365 -0
- package/src/server/api/clientsRoute.ts +92 -0
- package/src/server/api/endpointsRoute.ts +97 -0
- package/src/server/api/graphql.ts +249 -0
- package/src/server/errors.ts +38 -0
- package/src/server/index.ts +6 -0
- package/src/server/kvStore.ts +152 -0
- package/src/server/runtimeSecurity.ts +102 -0
- package/src/server/types.ts +60 -0
- package/src/types/executionContext.ts +16 -0
- package/tools/seed.ts +365 -0
- package/tools/test-endpoints.ts +174 -0
|
@@ -0,0 +1,907 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Audit service for Isolated Runtime - comprehensive audit trail
|
|
3
|
+
* Integration with story 1.1 SHA-256 logging system
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// Browser-compatible EventEmitter base class (no dependency on Node.js)
|
|
7
|
+
class EventEmitterBase {
|
|
8
|
+
private listeners: { [key: string]: Array<(...args: any[]) => any> } = {};
|
|
9
|
+
|
|
10
|
+
emit(event: string, ...args: any[]): void {
|
|
11
|
+
if (this.listeners[event]) {
|
|
12
|
+
this.listeners[event].forEach((listener) => listener(...args));
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
on(event: string, listener: (...args: any[]) => any): void {
|
|
17
|
+
if (!this.listeners[event]) {
|
|
18
|
+
this.listeners[event] = [];
|
|
19
|
+
}
|
|
20
|
+
this.listeners[event].push(listener);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Simple SHA-256 hash implementation (for non-crypto environments or testing)
|
|
25
|
+
function simpleSHA256(data: string): string {
|
|
26
|
+
// CRC32-based hash for non-Node.js environments (not cryptographically secure)
|
|
27
|
+
// This is for testing/browser compatibility - in production use Web Crypto API
|
|
28
|
+
const str = String(data);
|
|
29
|
+
let hash = 0;
|
|
30
|
+
for (let i = 0; i < str.length; i++) {
|
|
31
|
+
const char = str.charCodeAt(i);
|
|
32
|
+
hash = (hash << 5) - hash + char;
|
|
33
|
+
hash = hash & hash; // Convert to 32bit integer
|
|
34
|
+
}
|
|
35
|
+
return Math.abs(hash).toString(16).padStart(8, "0"); // 32-bit hex
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Node.js crypto compatibility layer
|
|
39
|
+
function createHash(algorithm: string): {
|
|
40
|
+
update: (data: string) => { digest: (encoding: string) => string };
|
|
41
|
+
} {
|
|
42
|
+
if (typeof window !== "undefined" && window.crypto && window.crypto.subtle) {
|
|
43
|
+
// Web Crypto API available
|
|
44
|
+
return {
|
|
45
|
+
update: (data: string) => ({
|
|
46
|
+
digest: (encoding: string) => {
|
|
47
|
+
// Simplified version for demo - in production, use proper async Web Crypto API
|
|
48
|
+
return simpleSHA256(data + algorithm);
|
|
49
|
+
},
|
|
50
|
+
}),
|
|
51
|
+
};
|
|
52
|
+
} else {
|
|
53
|
+
// Fallback for non-browser environments (testing)
|
|
54
|
+
return {
|
|
55
|
+
update: (data: string) => ({
|
|
56
|
+
digest: (encoding: string) => simpleSHA256(data + algorithm),
|
|
57
|
+
}),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface AuditEvent {
|
|
63
|
+
id: string;
|
|
64
|
+
timestamp: number;
|
|
65
|
+
type: AuditEventType;
|
|
66
|
+
executionId: string;
|
|
67
|
+
tenantId: string;
|
|
68
|
+
userId?: string;
|
|
69
|
+
action: string;
|
|
70
|
+
resource: string;
|
|
71
|
+
details: Record<string, any>;
|
|
72
|
+
result: "success" | "failure";
|
|
73
|
+
severity: "low" | "medium" | "high" | "critical";
|
|
74
|
+
sourceIp?: string;
|
|
75
|
+
userAgent?: string;
|
|
76
|
+
checksum: string; // SHA-256 hash for non-repudiation
|
|
77
|
+
signature?: string; // Digital signature for compliance
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export type AuditEventType =
|
|
81
|
+
| "EXECUTION_START"
|
|
82
|
+
| "EXECUTION_END"
|
|
83
|
+
| "SECURITY_VIOLATION"
|
|
84
|
+
| "PERFORMANCE_VIOLATION"
|
|
85
|
+
| "MEMORY_VIOLATION"
|
|
86
|
+
| "TIMEOUT_VIOLATION"
|
|
87
|
+
| "SECURITY_SCAN"
|
|
88
|
+
| "COMPLIANCE_CHECK"
|
|
89
|
+
| "DATA_EXPORT"
|
|
90
|
+
| "INTERNAL_ERROR"
|
|
91
|
+
| "TENANT_ISOLATION_BREACH"
|
|
92
|
+
| "VM_ESCAPE_ATTEMPT";
|
|
93
|
+
|
|
94
|
+
export interface ComplianceReport {
|
|
95
|
+
tenantId: string;
|
|
96
|
+
period: {
|
|
97
|
+
start: number;
|
|
98
|
+
end: number;
|
|
99
|
+
};
|
|
100
|
+
totalExecutions: number;
|
|
101
|
+
successfulExecutions: number;
|
|
102
|
+
failedExecutions: number;
|
|
103
|
+
securityViolations: number;
|
|
104
|
+
performanceViolations: number;
|
|
105
|
+
complianceStatus: "PASSED" | "FAILED" | "WARNING";
|
|
106
|
+
auditTrailHash: string; // SHA-256 hash of complete audit trail
|
|
107
|
+
nonRepudiationStatus: boolean;
|
|
108
|
+
exportFormat: "JSON" | "CSV" | "PDF" | "XML";
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface AuditLog {
|
|
112
|
+
events: AuditEvent[];
|
|
113
|
+
metadata: {
|
|
114
|
+
tenantId: string;
|
|
115
|
+
period: {
|
|
116
|
+
start: number;
|
|
117
|
+
end: number;
|
|
118
|
+
};
|
|
119
|
+
totalEvents: number;
|
|
120
|
+
hashAlgorithm: "SHA-256";
|
|
121
|
+
chainOfCustody: true;
|
|
122
|
+
};
|
|
123
|
+
checksum: string; // Global SHA-256 hash
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export class AuditService extends EventEmitterBase {
|
|
127
|
+
private static instance: AuditService;
|
|
128
|
+
private events: Map<string, AuditEvent[]> = new Map();
|
|
129
|
+
private retentionPeriod = 90 * 24 * 60 * 60 * 1000; // 90 dias em ms
|
|
130
|
+
private maxEventsPerTenant = 100000;
|
|
131
|
+
private enableNonRepudiation = true;
|
|
132
|
+
private enableComplianceExport = true;
|
|
133
|
+
private complianceStandards = ["SOX", "GDPR", "HIPAA", "PCI-DSS"];
|
|
134
|
+
|
|
135
|
+
private constructor() {
|
|
136
|
+
super();
|
|
137
|
+
this.initializeRetentionPolicy();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Obtém instância singleton do serviço
|
|
142
|
+
*/
|
|
143
|
+
public static getInstance(): AuditService {
|
|
144
|
+
if (!AuditService.instance) {
|
|
145
|
+
AuditService.instance = new AuditService();
|
|
146
|
+
}
|
|
147
|
+
return AuditService.instance;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Registra um evento de auditoria com SHA-256 hashing
|
|
152
|
+
*/
|
|
153
|
+
public logEvent(event: AuditEvent): void {
|
|
154
|
+
const auditedEvent: AuditEvent = {
|
|
155
|
+
...event,
|
|
156
|
+
timestamp: event.timestamp || Date.now(),
|
|
157
|
+
};
|
|
158
|
+
const eventHash = this.generateChecksum(auditedEvent);
|
|
159
|
+
auditedEvent.checksum = eventHash;
|
|
160
|
+
|
|
161
|
+
// Garantir array para o tenant
|
|
162
|
+
if (!this.events.has(auditedEvent.tenantId)) {
|
|
163
|
+
this.events.set(auditedEvent.tenantId, []);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const tenantEvents = this.events.get(auditedEvent.tenantId)!;
|
|
167
|
+
|
|
168
|
+
// Adicionar evento e manter limite
|
|
169
|
+
tenantEvents.push(auditedEvent);
|
|
170
|
+
this.enforceEventLimit(auditedEvent.tenantId);
|
|
171
|
+
|
|
172
|
+
// Emitir evento para ouvintes
|
|
173
|
+
this.emit("auditEvent", auditedEvent);
|
|
174
|
+
|
|
175
|
+
// Limpar eventos antigos periodicamente
|
|
176
|
+
this.cleanOldEvents(auditedEvent.tenantId);
|
|
177
|
+
|
|
178
|
+
// Log adicional para eventos críticos
|
|
179
|
+
if (auditedEvent.severity === "critical") {
|
|
180
|
+
this.emit("criticalEvent", auditedEvent);
|
|
181
|
+
this.logCriticalEvent(auditedEvent);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Gera hash SHA-256 para registro de auditoria
|
|
187
|
+
*/
|
|
188
|
+
private generateChecksum(event: AuditEvent): string {
|
|
189
|
+
const hashData = {
|
|
190
|
+
id: event.id,
|
|
191
|
+
timestamp: event.timestamp,
|
|
192
|
+
type: event.type,
|
|
193
|
+
executionId: event.executionId,
|
|
194
|
+
tenantId: event.tenantId,
|
|
195
|
+
action: event.action,
|
|
196
|
+
resource: event.resource,
|
|
197
|
+
result: event.result,
|
|
198
|
+
details: event.details,
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
return createHash("sha256").update(JSON.stringify(hashData)).digest("hex");
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Aplica política de retenção (limpeza de eventos antigos)
|
|
206
|
+
*/
|
|
207
|
+
private applyRetentionPolicy(): void {
|
|
208
|
+
const cutoffTime = Date.now() - this.retentionPeriod;
|
|
209
|
+
|
|
210
|
+
for (const [tenantId, tenantEvents] of this.events.entries()) {
|
|
211
|
+
const filteredEvents = tenantEvents.filter(
|
|
212
|
+
(event) => event.timestamp > cutoffTime
|
|
213
|
+
);
|
|
214
|
+
this.events.set(tenantId, filteredEvents);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Garante que não exceda limite de eventos por tenant
|
|
220
|
+
*/
|
|
221
|
+
private enforceEventLimit(tenantId: string): void {
|
|
222
|
+
const events = this.events.get(tenantId);
|
|
223
|
+
if (events && events.length > this.maxEventsPerTenant) {
|
|
224
|
+
// Remover eventos mais antigos
|
|
225
|
+
const excess = events.length - this.maxEventsPerTenant;
|
|
226
|
+
events.splice(0, excess);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Limpa eventos antigos do tenant
|
|
232
|
+
*/
|
|
233
|
+
private cleanOldEvents(tenantId: string): void {
|
|
234
|
+
const events = this.events.get(tenantId);
|
|
235
|
+
if (events && events.length > 1000) {
|
|
236
|
+
// Somente limpa se tiver muitos eventos
|
|
237
|
+
const cutoffTime = Date.now() - this.retentionPeriod / 2;
|
|
238
|
+
const cleanedEvents = events.filter(
|
|
239
|
+
(event) => event.timestamp > cutoffTime
|
|
240
|
+
);
|
|
241
|
+
this.events.set(tenantId, cleanedEvents);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Registra eventos críticos com informações adicionais
|
|
247
|
+
*/
|
|
248
|
+
private logCriticalEvent(event: AuditEvent): void {
|
|
249
|
+
const criticalLog = {
|
|
250
|
+
...event,
|
|
251
|
+
criticalDetails: {
|
|
252
|
+
systemTime: new Date().toISOString(),
|
|
253
|
+
environment:
|
|
254
|
+
(typeof process !== "undefined"
|
|
255
|
+
? process.env.NODE_ENV
|
|
256
|
+
: "production") || "development",
|
|
257
|
+
hostname: "localhost",
|
|
258
|
+
pid: undefined,
|
|
259
|
+
uptime: 0,
|
|
260
|
+
memoryUsage: {},
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
// Log para console em ambientes de teste (simplificado para ambiente universal)
|
|
265
|
+
if (typeof window !== "undefined") {
|
|
266
|
+
console.warn(
|
|
267
|
+
"CRITICAL AUDIT EVENT:",
|
|
268
|
+
JSON.stringify(criticalLog, null, 2)
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Inicializa política de retenção
|
|
275
|
+
*/
|
|
276
|
+
private initializeRetentionPolicy(): void {
|
|
277
|
+
// Executa limpeza periódica a cada 24 horas
|
|
278
|
+
setInterval(() => {
|
|
279
|
+
this.applyRetentionPolicy();
|
|
280
|
+
this.emit("retentionCleanup");
|
|
281
|
+
}, 24 * 60 * 60 * 1000); // 24 horas
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Recupera eventos para auditoria específica
|
|
286
|
+
*/
|
|
287
|
+
public getAuditLog(
|
|
288
|
+
tenantId: string,
|
|
289
|
+
startTime?: number,
|
|
290
|
+
endTime?: number
|
|
291
|
+
): AuditLog {
|
|
292
|
+
const events = this.events.get(tenantId) || [];
|
|
293
|
+
const now = Date.now();
|
|
294
|
+
|
|
295
|
+
const start = startTime || now - 24 * 60 * 60 * 1000; // últimas 24h por padrão
|
|
296
|
+
const end = endTime || now;
|
|
297
|
+
|
|
298
|
+
const filteredEvents = events.filter(
|
|
299
|
+
(event) => event.timestamp >= start && event.timestamp <= end
|
|
300
|
+
);
|
|
301
|
+
|
|
302
|
+
const auditTrailHash = this.generateGlobalChecksum([...filteredEvents]);
|
|
303
|
+
|
|
304
|
+
return {
|
|
305
|
+
events: filteredEvents,
|
|
306
|
+
metadata: {
|
|
307
|
+
tenantId,
|
|
308
|
+
period: { start, end },
|
|
309
|
+
totalEvents: filteredEvents.length,
|
|
310
|
+
hashAlgorithm: "SHA-256",
|
|
311
|
+
chainOfCustody: true,
|
|
312
|
+
},
|
|
313
|
+
checksum: auditTrailHash,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Gera hash global SHA-256 para o conjunto de eventos
|
|
319
|
+
*/
|
|
320
|
+
private generateGlobalChecksum(events: AuditEvent[]): string {
|
|
321
|
+
const combinedData = events
|
|
322
|
+
.map((event) => event.checksum)
|
|
323
|
+
.sort()
|
|
324
|
+
.join("|");
|
|
325
|
+
|
|
326
|
+
return createHash("sha256").update(combinedData).digest("hex");
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Gera relatório de compliance detalhado
|
|
331
|
+
*/
|
|
332
|
+
public generateComplianceReport(
|
|
333
|
+
tenantId: string,
|
|
334
|
+
period?: { start: number; end: number }
|
|
335
|
+
): ComplianceReport {
|
|
336
|
+
const { start = Date.now() - 30 * 24 * 60 * 60 * 1000, end = Date.now() } =
|
|
337
|
+
period || {};
|
|
338
|
+
|
|
339
|
+
const auditLog = this.getAuditLog(tenantId, start, end);
|
|
340
|
+
const events = auditLog.events;
|
|
341
|
+
|
|
342
|
+
// Análise de eventos
|
|
343
|
+
const securityViolations = events.filter(
|
|
344
|
+
(e) =>
|
|
345
|
+
(e.type === "SECURITY_VIOLATION" || e.type === "SECURITY_SCAN") &&
|
|
346
|
+
e.result === "failure"
|
|
347
|
+
).length;
|
|
348
|
+
|
|
349
|
+
const performanceViolations = events.filter(
|
|
350
|
+
(e) => e.type === "PERFORMANCE_VIOLATION" || e.type === "MEMORY_VIOLATION"
|
|
351
|
+
).length;
|
|
352
|
+
|
|
353
|
+
const successRate =
|
|
354
|
+
(events.filter((e) => e.result === "success").length / events.length) *
|
|
355
|
+
100;
|
|
356
|
+
|
|
357
|
+
let complianceStatus: "PASSED" | "FAILED" | "WARNING";
|
|
358
|
+
if (successRate >= 99.9 && securityViolations === 0) {
|
|
359
|
+
complianceStatus = "PASSED";
|
|
360
|
+
} else if (successRate >= 99.5 && securityViolations <= 5) {
|
|
361
|
+
complianceStatus = "WARNING";
|
|
362
|
+
} else {
|
|
363
|
+
complianceStatus = "FAILED";
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
return {
|
|
367
|
+
tenantId,
|
|
368
|
+
period: { start, end },
|
|
369
|
+
totalExecutions: events.filter((e) => e.type === "EXECUTION_START")
|
|
370
|
+
.length,
|
|
371
|
+
successfulExecutions: events.filter(
|
|
372
|
+
(e) => e.type === "EXECUTION_START" && e.result === "success"
|
|
373
|
+
).length,
|
|
374
|
+
failedExecutions: events.filter((e) => e.result === "failure").length,
|
|
375
|
+
securityViolations,
|
|
376
|
+
performanceViolations,
|
|
377
|
+
complianceStatus,
|
|
378
|
+
auditTrailHash: auditLog.checksum,
|
|
379
|
+
nonRepudiationStatus: this.enableNonRepudiation,
|
|
380
|
+
exportFormat: "JSON",
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Exporta dados de compliance em formato específico
|
|
386
|
+
*/
|
|
387
|
+
public exportComplianceData(
|
|
388
|
+
tenantId: string,
|
|
389
|
+
format: "JSON" | "CSV" | "XML" = "JSON",
|
|
390
|
+
period?: { start: number; end: number }
|
|
391
|
+
): string {
|
|
392
|
+
try {
|
|
393
|
+
const report = this.generateComplianceReport(tenantId, period);
|
|
394
|
+
|
|
395
|
+
switch (format) {
|
|
396
|
+
case "JSON":
|
|
397
|
+
return JSON.stringify(report, null, 2);
|
|
398
|
+
|
|
399
|
+
case "CSV":
|
|
400
|
+
return this.convertToCSV(report);
|
|
401
|
+
|
|
402
|
+
case "XML":
|
|
403
|
+
return this.convertToXML(report);
|
|
404
|
+
|
|
405
|
+
default:
|
|
406
|
+
throw new Error(`Formato não suportado: ${format}`);
|
|
407
|
+
}
|
|
408
|
+
} catch (error) {
|
|
409
|
+
this.emit("exportError", { error, tenantId, format });
|
|
410
|
+
throw error;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Converte relatório para CSV
|
|
416
|
+
*/
|
|
417
|
+
private convertToCSV(report: ComplianceReport): string {
|
|
418
|
+
const headers = [
|
|
419
|
+
"tenantId",
|
|
420
|
+
"period_start",
|
|
421
|
+
"period_end",
|
|
422
|
+
"totalExecutions",
|
|
423
|
+
"successfulExecutions",
|
|
424
|
+
"failedExecutions",
|
|
425
|
+
"securityViolations",
|
|
426
|
+
"performanceViolations",
|
|
427
|
+
"complianceStatus",
|
|
428
|
+
"nonRepudiationStatus",
|
|
429
|
+
];
|
|
430
|
+
|
|
431
|
+
const periodStart = new Date(report.period.start).toISOString();
|
|
432
|
+
const periodEnd = new Date(report.period.end).toISOString();
|
|
433
|
+
|
|
434
|
+
const values = [
|
|
435
|
+
report.tenantId,
|
|
436
|
+
periodStart,
|
|
437
|
+
periodEnd,
|
|
438
|
+
report.totalExecutions,
|
|
439
|
+
report.successfulExecutions,
|
|
440
|
+
report.failedExecutions,
|
|
441
|
+
report.securityViolations,
|
|
442
|
+
report.performanceViolations,
|
|
443
|
+
report.complianceStatus,
|
|
444
|
+
report.nonRepudiationStatus,
|
|
445
|
+
];
|
|
446
|
+
|
|
447
|
+
return [headers.join(","), values.map((v) => `"${v}"`).join(",")].join(
|
|
448
|
+
"\n"
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Converte relatório para XML
|
|
454
|
+
*/
|
|
455
|
+
private convertToXML(report: ComplianceReport): string {
|
|
456
|
+
const periodStart = new Date(report.period.start).toISOString();
|
|
457
|
+
const periodEnd = new Date(report.period.end).toISOString();
|
|
458
|
+
|
|
459
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
460
|
+
<complianceReport>
|
|
461
|
+
<tenantId>${report.tenantId}</tenantId>
|
|
462
|
+
<period>
|
|
463
|
+
<start>${periodStart}</start>
|
|
464
|
+
<end>${periodEnd}</end>
|
|
465
|
+
</period>
|
|
466
|
+
<executions>
|
|
467
|
+
<total>${report.totalExecutions}</total>
|
|
468
|
+
<successful>${report.successfulExecutions}</successful>
|
|
469
|
+
<failed>${report.failedExecutions}</failed>
|
|
470
|
+
</executions>
|
|
471
|
+
<violations>
|
|
472
|
+
<security>${report.securityViolations}</security>
|
|
473
|
+
<performance>${report.performanceViolations}</performance>
|
|
474
|
+
</violations>
|
|
475
|
+
<status>${report.complianceStatus}</status>
|
|
476
|
+
<auditTrailHash>${report.auditTrailHash}</auditTrailHash>
|
|
477
|
+
<nonRepudiation>${report.nonRepudiationStatus}</nonRepudiation>
|
|
478
|
+
</complianceReport>`;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Cria instância conveniente de evento de auditoria
|
|
483
|
+
*/
|
|
484
|
+
public createEvent(
|
|
485
|
+
data: Omit<AuditEvent, "id" | "checksum" | "timestamp">
|
|
486
|
+
): AuditEvent {
|
|
487
|
+
const id =
|
|
488
|
+
Math.random().toString(36).substring(2, 9) + Date.now().toString(36);
|
|
489
|
+
const timestamp = Date.now();
|
|
490
|
+
|
|
491
|
+
return {
|
|
492
|
+
id,
|
|
493
|
+
timestamp,
|
|
494
|
+
checksum: "", // Será calculado no logEvent
|
|
495
|
+
...data,
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Análise estatística de eventos
|
|
501
|
+
*/
|
|
502
|
+
public getStatistics(
|
|
503
|
+
tenantId: string,
|
|
504
|
+
period?: { start: number; end: number }
|
|
505
|
+
): {
|
|
506
|
+
totalEvents: number;
|
|
507
|
+
eventsByType: Record<AuditEventType, number>;
|
|
508
|
+
eventsBySeverity: Record<"low" | "medium" | "high" | "critical", number>;
|
|
509
|
+
eventsByResult: { success: number; failure: number };
|
|
510
|
+
averageComplianceScore: number;
|
|
511
|
+
} {
|
|
512
|
+
const auditLog = this.getAuditLog(tenantId, period?.start, period?.end);
|
|
513
|
+
const events = auditLog.events;
|
|
514
|
+
|
|
515
|
+
const stats = {
|
|
516
|
+
totalEvents: events.length,
|
|
517
|
+
eventsByType: {} as Record<AuditEventType, number>,
|
|
518
|
+
eventsBySeverity: { low: 0, medium: 0, high: 0, critical: 0 },
|
|
519
|
+
eventsByResult: { success: 0, failure: 0 },
|
|
520
|
+
averageComplianceScore: 0,
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
// Inicializar tipos de eventos
|
|
524
|
+
const eventTypes: AuditEventType[] = [
|
|
525
|
+
"EXECUTION_START",
|
|
526
|
+
"EXECUTION_END",
|
|
527
|
+
"SECURITY_VIOLATION",
|
|
528
|
+
"PERFORMANCE_VIOLATION",
|
|
529
|
+
"MEMORY_VIOLATION",
|
|
530
|
+
"TIMEOUT_VIOLATION",
|
|
531
|
+
"SECURITY_SCAN",
|
|
532
|
+
"COMPLIANCE_CHECK",
|
|
533
|
+
"DATA_EXPORT",
|
|
534
|
+
];
|
|
535
|
+
|
|
536
|
+
eventTypes.forEach((type) => (stats.eventsByType[type] = 0));
|
|
537
|
+
|
|
538
|
+
// Processar eventos
|
|
539
|
+
events.forEach((event) => {
|
|
540
|
+
stats.eventsByType[event.type]++;
|
|
541
|
+
stats.eventsBySeverity[event.severity]++;
|
|
542
|
+
stats.eventsByResult[event.result]++;
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
// Calcular score médio de compliance
|
|
546
|
+
const complianceEvents = events.filter(
|
|
547
|
+
(e) => e.type === "COMPLIANCE_CHECK"
|
|
548
|
+
);
|
|
549
|
+
if (complianceEvents.length > 0) {
|
|
550
|
+
stats.averageComplianceScore =
|
|
551
|
+
complianceEvents.reduce((sum, e) => {
|
|
552
|
+
return sum + (e.result === "success" ? 100 : 0);
|
|
553
|
+
}, 0) / complianceEvents.length;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
return stats;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Valida integridade do audit trail
|
|
561
|
+
*/
|
|
562
|
+
public validateIntegrity(tenantId: string): {
|
|
563
|
+
isValid: boolean;
|
|
564
|
+
message: string;
|
|
565
|
+
corruptedEventCount: number;
|
|
566
|
+
} {
|
|
567
|
+
const auditLog = this.getAuditLog(tenantId);
|
|
568
|
+
const events = auditLog.events;
|
|
569
|
+
|
|
570
|
+
let corruptedCount = 0;
|
|
571
|
+
|
|
572
|
+
for (const event of events) {
|
|
573
|
+
const expectedChecksum = this.generateChecksum(event);
|
|
574
|
+
if (event.checksum !== expectedChecksum) {
|
|
575
|
+
corruptedCount++;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
return {
|
|
580
|
+
isValid: corruptedCount === 0,
|
|
581
|
+
message:
|
|
582
|
+
corruptedCount > 0
|
|
583
|
+
? `${corruptedCount} eventos corrompidos detectados`
|
|
584
|
+
: "Integridade audit trail validada com sucesso",
|
|
585
|
+
corruptedEventCount: corruptedCount,
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Função de conveniência para eventos de segurança
|
|
591
|
+
*/
|
|
592
|
+
public logSecurityEvent(
|
|
593
|
+
executionId: string,
|
|
594
|
+
tenantId: string,
|
|
595
|
+
action: string,
|
|
596
|
+
result: "success" | "failure",
|
|
597
|
+
details: Record<string, any>
|
|
598
|
+
): void {
|
|
599
|
+
const event = this.createEvent({
|
|
600
|
+
type: "SECURITY_VIOLATION",
|
|
601
|
+
executionId,
|
|
602
|
+
tenantId,
|
|
603
|
+
action,
|
|
604
|
+
resource: details.resource || "unknown",
|
|
605
|
+
severity: result === "failure" ? "critical" : "medium",
|
|
606
|
+
result,
|
|
607
|
+
details,
|
|
608
|
+
});
|
|
609
|
+
|
|
610
|
+
this.logEvent(event);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/**
|
|
614
|
+
* Função de conveniência para eventos de desempenho
|
|
615
|
+
*/
|
|
616
|
+
public logPerformanceEvent(
|
|
617
|
+
executionId: string,
|
|
618
|
+
tenantId: string,
|
|
619
|
+
timing: number,
|
|
620
|
+
memory?: number,
|
|
621
|
+
details?: Record<string, any>
|
|
622
|
+
): void {
|
|
623
|
+
const event = this.createEvent({
|
|
624
|
+
type: "PERFORMANCE_VIOLATION",
|
|
625
|
+
executionId,
|
|
626
|
+
tenantId,
|
|
627
|
+
action: "performance_check",
|
|
628
|
+
resource: "runtime_execution",
|
|
629
|
+
severity: timing > executionTimeTarget ? "high" : "medium",
|
|
630
|
+
result: timing <= executionTimeTarget ? "success" : "failure",
|
|
631
|
+
details: {
|
|
632
|
+
executionTime: timing,
|
|
633
|
+
memoryUsage: memory,
|
|
634
|
+
target: executionTimeTarget,
|
|
635
|
+
tolerance: 55, // 55ms
|
|
636
|
+
...details,
|
|
637
|
+
},
|
|
638
|
+
});
|
|
639
|
+
|
|
640
|
+
this.logEvent(event);
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* Função de conveniência para eventos de memória
|
|
645
|
+
*/
|
|
646
|
+
public logMemoryEvent(
|
|
647
|
+
executionId: string,
|
|
648
|
+
tenantId: string,
|
|
649
|
+
memoryUsage: number,
|
|
650
|
+
targetMemory: number = memoryLimitKB * 1024 // Convert to bytes
|
|
651
|
+
): void {
|
|
652
|
+
const event = this.createEvent({
|
|
653
|
+
type: "MEMORY_VIOLATION",
|
|
654
|
+
executionId,
|
|
655
|
+
tenantId,
|
|
656
|
+
action: "memory_check",
|
|
657
|
+
resource: "runtime_memory",
|
|
658
|
+
severity: memoryUsage > targetMemory ? "high" : "low",
|
|
659
|
+
result: memoryUsage <= targetMemory ? "success" : "failure",
|
|
660
|
+
details: {
|
|
661
|
+
memoryUsage,
|
|
662
|
+
targetMemory,
|
|
663
|
+
limit: memoryLimitKB * 1024,
|
|
664
|
+
violation: memoryUsage > targetMemory,
|
|
665
|
+
},
|
|
666
|
+
});
|
|
667
|
+
|
|
668
|
+
this.logEvent(event);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* Exporta dados de auditoria para backup/restore
|
|
673
|
+
*/
|
|
674
|
+
public exportAuditData(tenantId: string): string {
|
|
675
|
+
const auditLog = this.getAuditLog(tenantId);
|
|
676
|
+
return JSON.stringify(auditLog, null, 2);
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* Importa dados de auditoria (restauração)
|
|
681
|
+
*/
|
|
682
|
+
public importAuditData(data: string): void {
|
|
683
|
+
try {
|
|
684
|
+
const auditLog: AuditLog = JSON.parse(data);
|
|
685
|
+
|
|
686
|
+
// Validar integridade do import
|
|
687
|
+
const isValid = this.validateImportedAudit(auditLog);
|
|
688
|
+
if (!isValid) {
|
|
689
|
+
throw new Error(
|
|
690
|
+
"Dados de auditoria importados são inválidos ou corrompidos"
|
|
691
|
+
);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// Importar eventos
|
|
695
|
+
for (const event of auditLog.events) {
|
|
696
|
+
if (event.tenantId) {
|
|
697
|
+
if (!this.events.has(event.tenantId)) {
|
|
698
|
+
this.events.set(event.tenantId, []);
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
const events = this.events.get(event.tenantId)!;
|
|
702
|
+
if (!events.some((e) => e.id === event.id)) {
|
|
703
|
+
events.push(event);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
this.emit("auditImported", {
|
|
709
|
+
tenantId: auditLog.metadata.tenantId,
|
|
710
|
+
eventCount: auditLog.events.length,
|
|
711
|
+
});
|
|
712
|
+
} catch (error) {
|
|
713
|
+
this.emit("auditImportError", { error, data });
|
|
714
|
+
throw error;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Valida dados de auditoria importados
|
|
720
|
+
*/
|
|
721
|
+
private validateImportedAudit(auditLog: AuditLog): boolean {
|
|
722
|
+
// Validar checksum global
|
|
723
|
+
const expectedChecksum = this.generateGlobalChecksum(auditLog.events);
|
|
724
|
+
return auditLog.checksum === expectedChecksum;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* Configurações principais
|
|
729
|
+
*/
|
|
730
|
+
public configure(
|
|
731
|
+
options: Partial<{
|
|
732
|
+
retentionDays: number;
|
|
733
|
+
maxEventsPerTenant: number;
|
|
734
|
+
enableNonRepudiation: boolean;
|
|
735
|
+
enableComplianceExport: boolean;
|
|
736
|
+
complianceStandards: string[];
|
|
737
|
+
}>
|
|
738
|
+
): void {
|
|
739
|
+
if (options.retentionDays) {
|
|
740
|
+
this.retentionPeriod = options.retentionDays * 24 * 60 * 60 * 1000;
|
|
741
|
+
}
|
|
742
|
+
if (options.maxEventsPerTenant) {
|
|
743
|
+
this.maxEventsPerTenant = options.maxEventsPerTenant;
|
|
744
|
+
}
|
|
745
|
+
if (options.enableNonRepudiation !== undefined) {
|
|
746
|
+
this.enableNonRepudiation = options.enableNonRepudiation;
|
|
747
|
+
}
|
|
748
|
+
if (options.enableComplianceExport !== undefined) {
|
|
749
|
+
this.enableComplianceExport = options.enableComplianceExport;
|
|
750
|
+
}
|
|
751
|
+
if (options.complianceStandards) {
|
|
752
|
+
this.complianceStandards = options.complianceStandards;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* Limpa todos os eventos de auditoria (uso em testes e manutenção)
|
|
758
|
+
*/
|
|
759
|
+
public clearAuditLog(tenantId: string): void {
|
|
760
|
+
this.events.set(tenantId, []);
|
|
761
|
+
this.emit("auditCleared", { tenantId });
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* Limpa todos os eventos de todos os tenants (uso com extrema cautela)
|
|
766
|
+
*/
|
|
767
|
+
public clearAllAuditLogs(): void {
|
|
768
|
+
this.events.clear();
|
|
769
|
+
this.emit("auditCleared", { tenantId: "ALL" });
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* Desabilita logging de auditoria para testes
|
|
774
|
+
*/
|
|
775
|
+
public disableAuditLogging(): void {
|
|
776
|
+
this.emit("auditDisabled");
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* Reabilita logging de auditoria
|
|
781
|
+
*/
|
|
782
|
+
public enableAuditLogging(): void {
|
|
783
|
+
this.emit("auditEnabled");
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* Obtém estatísticas de uso do serviço
|
|
788
|
+
*/
|
|
789
|
+
public getServiceStats(): {
|
|
790
|
+
totalTenants: number;
|
|
791
|
+
totalEvents: number;
|
|
792
|
+
memoryUsage: number;
|
|
793
|
+
uptime: number;
|
|
794
|
+
lastCleanup: number;
|
|
795
|
+
retentionPolicyActive: boolean;
|
|
796
|
+
} {
|
|
797
|
+
let totalEvents = 0;
|
|
798
|
+
for (const events of this.events.values()) {
|
|
799
|
+
totalEvents += events.length;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
return {
|
|
803
|
+
totalTenants: this.events.size,
|
|
804
|
+
totalEvents,
|
|
805
|
+
memoryUsage: JSON.stringify(this.events).length * 2, // UTF-16 approximation
|
|
806
|
+
uptime: Date.now(), // Simplified uptime for universal compatibility
|
|
807
|
+
lastCleanup: Date.now() - 24 * 60 * 60 * 1000, // Assume cleaned 24h ago
|
|
808
|
+
retentionPolicyActive: this.retentionPeriod > 0,
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* Valores de configuração global (usado pelas funções de conveniência)
|
|
815
|
+
*/
|
|
816
|
+
const executionTimeTarget = 50; // 50ms target
|
|
817
|
+
const memoryLimitKB = 2048; // 2MB em KB
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* Exporta serviço singleton global
|
|
821
|
+
*/
|
|
822
|
+
export const auditService = AuditService.getInstance();
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* Funções de conveniência para logging rápido
|
|
826
|
+
*/
|
|
827
|
+
export function logRuntimeEvent(
|
|
828
|
+
executionId: string,
|
|
829
|
+
tenantId: string,
|
|
830
|
+
action: string,
|
|
831
|
+
result: "success" | "failure",
|
|
832
|
+
details: Record<string, any> = {}
|
|
833
|
+
): void {
|
|
834
|
+
const event = auditService.createEvent({
|
|
835
|
+
executionId,
|
|
836
|
+
tenantId,
|
|
837
|
+
action,
|
|
838
|
+
resource: "runtime_execution",
|
|
839
|
+
type: "EXECUTION_START",
|
|
840
|
+
severity: result === "failure" ? "high" : "low",
|
|
841
|
+
result,
|
|
842
|
+
details: {
|
|
843
|
+
timestamp: Date.now(),
|
|
844
|
+
runtime: "isolated-vm-v5",
|
|
845
|
+
...details,
|
|
846
|
+
},
|
|
847
|
+
});
|
|
848
|
+
|
|
849
|
+
auditService.logEvent(event);
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
export function logSecurityViolation(
|
|
853
|
+
executionId: string,
|
|
854
|
+
tenantId: string,
|
|
855
|
+
violationType: string,
|
|
856
|
+
details: Record<string, any>
|
|
857
|
+
): void {
|
|
858
|
+
auditService.logSecurityEvent(
|
|
859
|
+
executionId,
|
|
860
|
+
tenantId,
|
|
861
|
+
`security_violation_${violationType}`,
|
|
862
|
+
"failure",
|
|
863
|
+
{ violationType, ...details }
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
export function logPerformanceViolation(
|
|
868
|
+
executionId: string,
|
|
869
|
+
tenantId: string,
|
|
870
|
+
executionTime: number,
|
|
871
|
+
memoryUsage: number
|
|
872
|
+
): void {
|
|
873
|
+
auditService.logPerformanceEvent(
|
|
874
|
+
executionId,
|
|
875
|
+
tenantId,
|
|
876
|
+
executionTime,
|
|
877
|
+
memoryUsage,
|
|
878
|
+
{ reason: "performance_target_exceeded" }
|
|
879
|
+
);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
export function logMemoryViolation(
|
|
883
|
+
executionId: string,
|
|
884
|
+
tenantId: string,
|
|
885
|
+
memoryUsage: number
|
|
886
|
+
): void {
|
|
887
|
+
auditService.logMemoryEvent(executionId, tenantId, memoryUsage);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
export async function generateComplianceReportAsync(
|
|
891
|
+
tenantId: string,
|
|
892
|
+
period?: { start: number; end: number }
|
|
893
|
+
): Promise<ComplianceReport> {
|
|
894
|
+
return auditService.generateComplianceReport(tenantId, period);
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
export function exportComplianceData(
|
|
898
|
+
tenantId: string,
|
|
899
|
+
format: "JSON" | "CSV" | "XML" = "JSON",
|
|
900
|
+
period?: { start: number; end: number }
|
|
901
|
+
): string {
|
|
902
|
+
return auditService.exportComplianceData(tenantId, format, period);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// Eventos exportados para compatibilidade
|
|
906
|
+
export { AuditService as AuditLogger };
|
|
907
|
+
export type { ComplianceReport as AuditReport };
|