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.
Files changed (236) hide show
  1. package/README.md +297 -0
  2. package/dist/agents/agentRegistry.d.ts +68 -0
  3. package/dist/agents/agentRegistry.d.ts.map +1 -0
  4. package/dist/agents/agentRegistry.js +222 -0
  5. package/dist/agents/agentRegistry.js.map +1 -0
  6. package/dist/agents/formatter-agent.d.ts +10 -0
  7. package/dist/agents/formatter-agent.d.ts.map +1 -0
  8. package/dist/agents/formatter-agent.js +49 -0
  9. package/dist/agents/formatter-agent.js.map +1 -0
  10. package/dist/agents/genkit-agent.d.ts +12 -0
  11. package/dist/agents/genkit-agent.d.ts.map +1 -0
  12. package/dist/agents/genkit-agent.js +119 -0
  13. package/dist/agents/genkit-agent.js.map +1 -0
  14. package/dist/agents/i18n-messages.d.ts +17 -0
  15. package/dist/agents/i18n-messages.d.ts.map +1 -0
  16. package/dist/agents/i18n-messages.js +92 -0
  17. package/dist/agents/i18n-messages.js.map +1 -0
  18. package/dist/agents/index.d.ts +10 -0
  19. package/dist/agents/index.d.ts.map +1 -0
  20. package/dist/agents/index.js +26 -0
  21. package/dist/agents/index.js.map +1 -0
  22. package/dist/agents/pipeline.d.ts +15 -0
  23. package/dist/agents/pipeline.d.ts.map +1 -0
  24. package/dist/agents/pipeline.js +45 -0
  25. package/dist/agents/pipeline.js.map +1 -0
  26. package/dist/agents/schema-factory.d.ts +40 -0
  27. package/dist/agents/schema-factory.d.ts.map +1 -0
  28. package/dist/agents/schema-factory.js +121 -0
  29. package/dist/agents/schema-factory.js.map +1 -0
  30. package/dist/agents/translation-validators.d.ts +26 -0
  31. package/dist/agents/translation-validators.d.ts.map +1 -0
  32. package/dist/agents/translation-validators.js +77 -0
  33. package/dist/agents/translation-validators.js.map +1 -0
  34. package/dist/agents/translator-agents.d.ts +184 -0
  35. package/dist/agents/translator-agents.d.ts.map +1 -0
  36. package/dist/agents/translator-agents.js +613 -0
  37. package/dist/agents/translator-agents.js.map +1 -0
  38. package/dist/agents/types/translation.types.d.ts +100 -0
  39. package/dist/agents/types/translation.types.d.ts.map +1 -0
  40. package/dist/agents/types/translation.types.js +3 -0
  41. package/dist/agents/types/translation.types.js.map +1 -0
  42. package/dist/agents/validator-agent.d.ts +42 -0
  43. package/dist/agents/validator-agent.d.ts.map +1 -0
  44. package/dist/agents/validator-agent.js +122 -0
  45. package/dist/agents/validator-agent.js.map +1 -0
  46. package/dist/audit/auditTrail.d.ts +55 -0
  47. package/dist/audit/auditTrail.d.ts.map +1 -0
  48. package/dist/audit/auditTrail.js +93 -0
  49. package/dist/audit/auditTrail.js.map +1 -0
  50. package/dist/compliance/gdprEngine.d.ts +44 -0
  51. package/dist/compliance/gdprEngine.d.ts.map +1 -0
  52. package/dist/compliance/gdprEngine.js +178 -0
  53. package/dist/compliance/gdprEngine.js.map +1 -0
  54. package/dist/compliance/lgpdEngine.d.ts +51 -0
  55. package/dist/compliance/lgpdEngine.d.ts.map +1 -0
  56. package/dist/compliance/lgpdEngine.js +221 -0
  57. package/dist/compliance/lgpdEngine.js.map +1 -0
  58. package/dist/config.d.ts +78 -0
  59. package/dist/config.d.ts.map +1 -0
  60. package/dist/config.js +77 -0
  61. package/dist/config.js.map +1 -0
  62. package/dist/errors.d.ts +17 -0
  63. package/dist/errors.d.ts.map +1 -0
  64. package/dist/errors.js +40 -0
  65. package/dist/errors.js.map +1 -0
  66. package/dist/firebase/tenantManager.d.ts +84 -0
  67. package/dist/firebase/tenantManager.d.ts.map +1 -0
  68. package/dist/firebase/tenantManager.js +378 -0
  69. package/dist/firebase/tenantManager.js.map +1 -0
  70. package/dist/index.d.ts +36 -0
  71. package/dist/index.d.ts.map +1 -0
  72. package/dist/index.js +118 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/integration/secure-yaml-runtime.d.ts +68 -0
  75. package/dist/integration/secure-yaml-runtime.d.ts.map +1 -0
  76. package/dist/integration/secure-yaml-runtime.js +245 -0
  77. package/dist/integration/secure-yaml-runtime.js.map +1 -0
  78. package/dist/parser/secure-yaml-parser.d.ts +62 -0
  79. package/dist/parser/secure-yaml-parser.d.ts.map +1 -0
  80. package/dist/parser/secure-yaml-parser.js +234 -0
  81. package/dist/parser/secure-yaml-parser.js.map +1 -0
  82. package/dist/performance/autoscaling.d.ts +100 -0
  83. package/dist/performance/autoscaling.d.ts.map +1 -0
  84. package/dist/performance/autoscaling.js +339 -0
  85. package/dist/performance/autoscaling.js.map +1 -0
  86. package/dist/performance/benchmark.d.ts +104 -0
  87. package/dist/performance/benchmark.d.ts.map +1 -0
  88. package/dist/performance/benchmark.js +514 -0
  89. package/dist/performance/benchmark.js.map +1 -0
  90. package/dist/performance/index.d.ts +14 -0
  91. package/dist/performance/index.d.ts.map +1 -0
  92. package/dist/performance/index.js +35 -0
  93. package/dist/performance/index.js.map +1 -0
  94. package/dist/performance/monitor.d.ts +126 -0
  95. package/dist/performance/monitor.d.ts.map +1 -0
  96. package/dist/performance/monitor.js +324 -0
  97. package/dist/performance/monitor.js.map +1 -0
  98. package/dist/performance/streaming.d.ts +82 -0
  99. package/dist/performance/streaming.d.ts.map +1 -0
  100. package/dist/performance/streaming.js +287 -0
  101. package/dist/performance/streaming.js.map +1 -0
  102. package/dist/runtime/audit.d.ts +240 -0
  103. package/dist/runtime/audit.d.ts.map +1 -0
  104. package/dist/runtime/audit.js +641 -0
  105. package/dist/runtime/audit.js.map +1 -0
  106. package/dist/runtime/declarativeAgentRuntime.d.ts +123 -0
  107. package/dist/runtime/declarativeAgentRuntime.d.ts.map +1 -0
  108. package/dist/runtime/declarativeAgentRuntime.js +576 -0
  109. package/dist/runtime/declarativeAgentRuntime.js.map +1 -0
  110. package/dist/runtime/isolatedRuntime.d.ts +119 -0
  111. package/dist/runtime/isolatedRuntime.d.ts.map +1 -0
  112. package/dist/runtime/isolatedRuntime.js +425 -0
  113. package/dist/runtime/isolatedRuntime.js.map +1 -0
  114. package/dist/runtime/schemaCompiler.d.ts +35 -0
  115. package/dist/runtime/schemaCompiler.d.ts.map +1 -0
  116. package/dist/runtime/schemaCompiler.js +151 -0
  117. package/dist/runtime/schemaCompiler.js.map +1 -0
  118. package/dist/runtime/simpleRuntime.d.ts +57 -0
  119. package/dist/runtime/simpleRuntime.d.ts.map +1 -0
  120. package/dist/runtime/simpleRuntime.js +187 -0
  121. package/dist/runtime/simpleRuntime.js.map +1 -0
  122. package/dist/security/dashboard.d.ts +89 -0
  123. package/dist/security/dashboard.d.ts.map +1 -0
  124. package/dist/security/dashboard.js +300 -0
  125. package/dist/security/dashboard.js.map +1 -0
  126. package/dist/security/hardening.d.ts +130 -0
  127. package/dist/security/hardening.d.ts.map +1 -0
  128. package/dist/security/hardening.js +414 -0
  129. package/dist/security/hardening.js.map +1 -0
  130. package/dist/security/index.d.ts +128 -0
  131. package/dist/security/index.d.ts.map +1 -0
  132. package/dist/security/index.js +353 -0
  133. package/dist/security/index.js.map +1 -0
  134. package/dist/security/monitor.d.ts +88 -0
  135. package/dist/security/monitor.d.ts.map +1 -0
  136. package/dist/security/monitor.js +356 -0
  137. package/dist/security/monitor.js.map +1 -0
  138. package/dist/security/scanner.d.ts +104 -0
  139. package/dist/security/scanner.d.ts.map +1 -0
  140. package/dist/security/scanner.js +298 -0
  141. package/dist/security/scanner.js.map +1 -0
  142. package/dist/security/score.d.ts +150 -0
  143. package/dist/security/score.d.ts.map +1 -0
  144. package/dist/security/score.js +983 -0
  145. package/dist/security/score.js.map +1 -0
  146. package/dist/security/test-security.d.ts +22 -0
  147. package/dist/security/test-security.d.ts.map +1 -0
  148. package/dist/security/test-security.js +154 -0
  149. package/dist/security/test-security.js.map +1 -0
  150. package/dist/security/threatDetector.d.ts +39 -0
  151. package/dist/security/threatDetector.d.ts.map +1 -0
  152. package/dist/security/threatDetector.js +354 -0
  153. package/dist/security/threatDetector.js.map +1 -0
  154. package/dist/security/validation.d.ts +69 -0
  155. package/dist/security/validation.d.ts.map +1 -0
  156. package/dist/security/validation.js +286 -0
  157. package/dist/security/validation.js.map +1 -0
  158. package/dist/server/api/clientsRoute.d.ts +9 -0
  159. package/dist/server/api/clientsRoute.d.ts.map +1 -0
  160. package/dist/server/api/clientsRoute.js +71 -0
  161. package/dist/server/api/clientsRoute.js.map +1 -0
  162. package/dist/server/api/endpointsRoute.d.ts +8 -0
  163. package/dist/server/api/endpointsRoute.d.ts.map +1 -0
  164. package/dist/server/api/endpointsRoute.js +76 -0
  165. package/dist/server/api/endpointsRoute.js.map +1 -0
  166. package/dist/server/api/graphql.d.ts +9 -0
  167. package/dist/server/api/graphql.d.ts.map +1 -0
  168. package/dist/server/api/graphql.js +180 -0
  169. package/dist/server/api/graphql.js.map +1 -0
  170. package/dist/server/errors.d.ts +19 -0
  171. package/dist/server/errors.d.ts.map +1 -0
  172. package/dist/server/errors.js +42 -0
  173. package/dist/server/errors.js.map +1 -0
  174. package/dist/server/index.d.ts +7 -0
  175. package/dist/server/index.d.ts.map +1 -0
  176. package/dist/server/index.js +24 -0
  177. package/dist/server/index.js.map +1 -0
  178. package/dist/server/kvStore.d.ts +27 -0
  179. package/dist/server/kvStore.d.ts.map +1 -0
  180. package/dist/server/kvStore.js +128 -0
  181. package/dist/server/kvStore.js.map +1 -0
  182. package/dist/server/runtimeSecurity.d.ts +28 -0
  183. package/dist/server/runtimeSecurity.d.ts.map +1 -0
  184. package/dist/server/runtimeSecurity.js +85 -0
  185. package/dist/server/runtimeSecurity.js.map +1 -0
  186. package/dist/server/types.d.ts +53 -0
  187. package/dist/server/types.d.ts.map +1 -0
  188. package/dist/server/types.js +8 -0
  189. package/dist/server/types.js.map +1 -0
  190. package/dist/types/executionContext.d.ts +16 -0
  191. package/dist/types/executionContext.d.ts.map +1 -0
  192. package/dist/types/executionContext.js +3 -0
  193. package/dist/types/executionContext.js.map +1 -0
  194. package/package.json +77 -0
  195. package/src/agents/agentRegistry.ts +272 -0
  196. package/src/agents/image-agent.yaml +86 -0
  197. package/src/agents/joker-agent.yaml +47 -0
  198. package/src/agents/translator-agent.yaml +80 -0
  199. package/src/audit/auditTrail.ts +134 -0
  200. package/src/compliance/gdprEngine.ts +209 -0
  201. package/src/compliance/lgpdEngine.ts +268 -0
  202. package/src/config.ts +179 -0
  203. package/src/errors.ts +35 -0
  204. package/src/firebase/tenantManager.ts +443 -0
  205. package/src/index.ts +125 -0
  206. package/src/integration/secure-yaml-runtime.ts +341 -0
  207. package/src/parser/secure-yaml-parser.ts +273 -0
  208. package/src/performance/autoscaling.ts +495 -0
  209. package/src/performance/benchmark.ts +644 -0
  210. package/src/performance/index.ts +34 -0
  211. package/src/performance/monitor.ts +469 -0
  212. package/src/performance/streaming.ts +317 -0
  213. package/src/runtime/audit.ts +907 -0
  214. package/src/runtime/declarativeAgentRuntime.ts +836 -0
  215. package/src/runtime/isolatedRuntime.ts +572 -0
  216. package/src/runtime/schemaCompiler.ts +228 -0
  217. package/src/runtime/simpleRuntime.ts +201 -0
  218. package/src/security/dashboard.ts +462 -0
  219. package/src/security/hardening.ts +560 -0
  220. package/src/security/index.ts +439 -0
  221. package/src/security/monitor.ts +490 -0
  222. package/src/security/scanner.ts +368 -0
  223. package/src/security/score.ts +1138 -0
  224. package/src/security/threatDetector.ts +481 -0
  225. package/src/security/validation.ts +365 -0
  226. package/src/server/api/clientsRoute.ts +92 -0
  227. package/src/server/api/endpointsRoute.ts +97 -0
  228. package/src/server/api/graphql.ts +249 -0
  229. package/src/server/errors.ts +38 -0
  230. package/src/server/index.ts +6 -0
  231. package/src/server/kvStore.ts +152 -0
  232. package/src/server/runtimeSecurity.ts +102 -0
  233. package/src/server/types.ts +60 -0
  234. package/src/types/executionContext.ts +16 -0
  235. package/tools/seed.ts +365 -0
  236. package/tools/test-endpoints.ts +174 -0
package/src/config.ts ADDED
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Beddel Runtime Configuration - Isolated VM v5
3
+ * Ultra-secure runtime environment with zero-trust architecture
4
+ */
5
+ export type AllowedYamlPrimitive =
6
+ | "null"
7
+ | "boolean"
8
+ | "integer"
9
+ | "float"
10
+ | "string";
11
+
12
+ export interface YAMLParserConfig {
13
+ schema?: "FAILSAFE_SCHEMA";
14
+ allowedTypes?: AllowedYamlPrimitive[];
15
+ performanceTarget?: number;
16
+ maxDepth?: number;
17
+ maxKeys?: number;
18
+ maxStringLength?: number;
19
+ maxValueSize?: number;
20
+ lazyLoading?: boolean;
21
+ enableCaching?: boolean;
22
+ validateUTF8?: boolean;
23
+ strictMode?: boolean;
24
+ filename?: string;
25
+ }
26
+
27
+ export interface RuntimeConfig {
28
+ // Memory limits for isolated execution
29
+ memoryLimit: number; // Memory limit in MB per execution
30
+ timeout: number; // Execution timeout in milliseconds
31
+ securityScore: number; // Minimum security score (9.5/10)
32
+ executionTimeTarget: number; // Target execution time in milliseconds
33
+
34
+ // Pool configuration
35
+ maxPoolSize: number; // Maximum number of isolates in pool
36
+ minPoolSize: number; // Minimum number of isolates in pool
37
+ poolIdleTimeout: number; // Pool cleanup timeout in ms
38
+
39
+ // Security profiles
40
+ defaultSecurityProfile: string; // Default security profile name
41
+ allowRestrictedAccess: boolean; // Allow restricted access to external resources
42
+
43
+ // Audit logging
44
+ auditEnabled: boolean; // Enable audit logging
45
+ auditLevel: "none" | "basic" | "full"; // Audit detail level
46
+ auditHashAlgorithm: "sha256" | "sha512"; // Hash algorithm for audit trail
47
+
48
+ // Performance monitoring
49
+ metricsEnabled: boolean; // Enable performance metrics
50
+ metricsInterval: number; // Metrics collection interval in ms
51
+ maxExecutionHistory: number; // Maximum number of executions to track
52
+
53
+ // Multi-tenant configuration
54
+ tenantIsolation: boolean; // Enable tenant isolation
55
+ maxConcurrentExecutions: number; // Maximum concurrent executions
56
+
57
+ // Firebase multi-tenant configuration (2025)
58
+ multiTenant: boolean; // Firebase multi-tenant mode
59
+ dataRetention: string; // LGPD/GDPR data retention policy
60
+ auditHash: string; // Hash algorithm for audit trail
61
+ }
62
+
63
+ export const runtimeConfig: RuntimeConfig = {
64
+ // Core runtime settings
65
+ memoryLimit: 2, // 2MB por execução
66
+ timeout: 5000, // 5 segundos máximo
67
+ securityScore: 9.5, // Target mínimo 9.5/10
68
+ executionTimeTarget: 50, // 50ms target
69
+
70
+ // Pool management
71
+ maxPoolSize: 100, // Máximo de 100 isolates
72
+ minPoolSize: 5, // Mínimo de 5 isolates
73
+ poolIdleTimeout: 300000, // 5 minutos idle timeout
74
+
75
+ // Security configuration
76
+ defaultSecurityProfile: "ultra-secure",
77
+ allowRestrictedAccess: false, // Sem acesso externo por padrão
78
+
79
+ // Audit configuration
80
+ auditEnabled: true,
81
+ auditLevel: "full",
82
+ auditHashAlgorithm: "sha256",
83
+
84
+ // Performance monitoring
85
+ metricsEnabled: true,
86
+ metricsInterval: 1000, // Coleta a cada segundo
87
+ maxExecutionHistory: 10000, // Histórico de 10k execuções
88
+
89
+ // Multi-tenant settings
90
+ tenantIsolation: true,
91
+ maxConcurrentExecutions: 1000, // Suporte a 1000 execuções simultâneas
92
+
93
+ // Firebase multi-tenant configuration (2025)
94
+ multiTenant: true, // Isolamento total de tenants
95
+ dataRetention: "LGPD", // LGPD compliance automatic
96
+ auditHash: "SHA-256", // Hash criptográfico de operações
97
+ };
98
+
99
+ /**
100
+ * Security profiles for different execution contexts
101
+ */
102
+ export interface SecurityProfile {
103
+ name: string;
104
+ memoryLimit: number;
105
+ timeout: number;
106
+ allowExternalAccess: boolean;
107
+ allowedModules: string[];
108
+ restrictedFunctions: string[];
109
+ securityLevel: "low" | "medium" | "high" | "ultra";
110
+ }
111
+
112
+ export const securityProfiles: Record<string, SecurityProfile> = {
113
+ "ultra-secure": {
114
+ name: "ultra-secure",
115
+ memoryLimit: 2, // 2MB
116
+ timeout: 5000, // 5s
117
+ allowExternalAccess: false,
118
+ allowedModules: [],
119
+ restrictedFunctions: ["require", "eval", "Function", "process"],
120
+ securityLevel: "ultra",
121
+ },
122
+ "high-security": {
123
+ name: "high-security",
124
+ memoryLimit: 4, // 4MB
125
+ timeout: 10000, // 10s
126
+ allowExternalAccess: false,
127
+ allowedModules: ["lodash", "moment"],
128
+ restrictedFunctions: ["eval", "Function"],
129
+ securityLevel: "high",
130
+ },
131
+ "tenant-isolated": {
132
+ name: "tenant-isolated",
133
+ memoryLimit: 8, // 8MB
134
+ timeout: 15000, // 15s
135
+ allowExternalAccess: true,
136
+ allowedModules: ["lodash", "moment", "uuid"],
137
+ restrictedFunctions: ["eval"],
138
+ securityLevel: "medium",
139
+ },
140
+ };
141
+
142
+ /**
143
+ * Performance targets for monitoring
144
+ */
145
+ export interface PerformanceTarget {
146
+ metric: string;
147
+ target: number;
148
+ unit: string;
149
+ threshold: number; // Alert threshold
150
+ }
151
+
152
+ export const performanceTargets: PerformanceTarget[] = [
153
+ { metric: "executionTime", target: 50, unit: "ms", threshold: 75 },
154
+ { metric: "memoryUsage", target: 2, unit: "MB", threshold: 3 },
155
+ { metric: "successRate", target: 99.9, unit: "%", threshold: 99.5 },
156
+ { metric: "isolateCreationTime", target: 100, unit: "ms", threshold: 200 },
157
+ { metric: "poolUtilization", target: 70, unit: "%", threshold: 90 },
158
+ ];
159
+
160
+ /**
161
+ * Audit trail configuration
162
+ */
163
+ export interface AuditConfig {
164
+ enabled: boolean;
165
+ hashAlgorithm: string;
166
+ includeContext: boolean;
167
+ includeResult: boolean;
168
+ maxTrailSize: number;
169
+ retentionPeriod: number; // in days
170
+ }
171
+
172
+ export const auditConfig: AuditConfig = {
173
+ enabled: true,
174
+ hashAlgorithm: "sha256",
175
+ includeContext: true,
176
+ includeResult: true,
177
+ maxTrailSize: 1024 * 1024 * 100, // 100MB
178
+ retentionPeriod: 90, // 90 dias
179
+ };
package/src/errors.ts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Tipos de erro específicos para o parser YAML seguro
3
+ */
4
+
5
+ export class YAMLBaseError extends Error {
6
+ constructor(message: string, public code?: string) {
7
+ super(message);
8
+ this.name = 'YAMLBaseError';
9
+ Object.setPrototypeOf(this, YAMLBaseError.prototype);
10
+ }
11
+ }
12
+
13
+ export class YAMLParseError extends YAMLBaseError {
14
+ constructor(message: string, code?: string) {
15
+ super(message, code);
16
+ this.name = 'YAMLParseError';
17
+ Object.setPrototypeOf(this, YAMLParseError.prototype);
18
+ }
19
+ }
20
+
21
+ export class YAMLSecurityError extends YAMLBaseError {
22
+ constructor(message: string, code?: string) {
23
+ super(message, code);
24
+ this.name = 'YAMLSecurityError';
25
+ Object.setPrototypeOf(this, YAMLSecurityError.prototype);
26
+ }
27
+ }
28
+
29
+ export class YAMLPerformanceError extends YAMLBaseError {
30
+ constructor(message: string, code?: string) {
31
+ super(message, code);
32
+ this.name = 'YAMLPerformanceError';
33
+ Object.setPrototypeOf(this, YAMLPerformanceError.prototype);
34
+ }
35
+ }
@@ -0,0 +1,443 @@
1
+ /**
2
+ * Multi-Tenant Firebase Manager v2025
3
+ * Isolamento completo de tenants com LGPD/GDPR compliance automático
4
+ */
5
+
6
+ import * as admin from "firebase-admin";
7
+ import { runtimeConfig } from "../config";
8
+ import { AuditTrail } from "../audit/auditTrail";
9
+ import { GDPRCompliance } from "../compliance/gdprEngine";
10
+ import { LGPDCompliance } from "../compliance/lgpdEngine";
11
+
12
+ export interface TenantConfig {
13
+ tenantId: string;
14
+ projectId: string;
15
+ databaseURL: string;
16
+ storageBucket: string;
17
+ securityProfile: "ultra-secure" | "tenant-isolated";
18
+ dataRetentionDays: number;
19
+ lgpdEnabled: boolean;
20
+ gdprEnabled: boolean;
21
+ }
22
+
23
+ export interface TenantIsolationResult {
24
+ success: boolean;
25
+ tenantId: string;
26
+ securityScore: number;
27
+ auditHash: string;
28
+ executionTime: number;
29
+ complianceStatus: {
30
+ lgpd: boolean;
31
+ gdpr: boolean;
32
+ };
33
+ }
34
+
35
+ export class MultiTenantFirebaseManager {
36
+ private static instance: MultiTenantFirebaseManager;
37
+ private tenants: Map<string, admin.app.App>;
38
+ private auditTrail: AuditTrail;
39
+ private gdprCompliance: GDPRCompliance;
40
+ private lgpdCompliance: LGPDCompliance;
41
+
42
+ private constructor() {
43
+ this.tenants = new Map();
44
+ this.auditTrail = new AuditTrail();
45
+ this.gdprCompliance = new GDPRCompliance();
46
+ this.lgpdCompliance = new LGPDCompliance();
47
+ }
48
+
49
+ public static getInstance(): MultiTenantFirebaseManager {
50
+ if (!this.instance) {
51
+ this.instance = new MultiTenantFirebaseManager();
52
+ }
53
+ return this.instance;
54
+ }
55
+
56
+ /**
57
+ * Initialize tenant with complete isolation
58
+ */
59
+ public async initializeTenant(
60
+ config: TenantConfig
61
+ ): Promise<TenantIsolationResult> {
62
+ const startTime = Date.now();
63
+
64
+ try {
65
+ // Validate tenant configuration
66
+ this.validateTenantConfig(config);
67
+
68
+ // Check if tenant already exists
69
+ if (this.tenants.has(config.tenantId)) {
70
+ throw new Error(`Tenant ${config.tenantId} already initialized`);
71
+ }
72
+
73
+ // Initialize Firebase app for this tenant
74
+ const app = admin.initializeApp(
75
+ {
76
+ credential: admin.credential.applicationDefault(),
77
+ projectId: config.projectId,
78
+ databaseURL: config.databaseURL,
79
+ storageBucket: config.storageBucket,
80
+ },
81
+ `tenant-${config.tenantId}`
82
+ );
83
+
84
+ // Configure security rules
85
+ await this.configureSecurityRules(app, config);
86
+
87
+ // Store tenant app
88
+ this.tenants.set(config.tenantId, app);
89
+
90
+ // Generate audit trail
91
+ const operationId = `init-${config.tenantId}-${Date.now()}`;
92
+ const auditHash = await this.auditTrail.logOperation({
93
+ operationId,
94
+ tenantId: config.tenantId,
95
+ operation: "tenant_init",
96
+ data: this.sanitizeForAudit(config),
97
+ timestamp: new Date(),
98
+ });
99
+
100
+ // Verify compliance
101
+ const complianceStatus = await this.verifyCompliance(config);
102
+
103
+ const executionTime = Date.now() - startTime;
104
+
105
+ // Calculate security score
106
+ const securityScore = this.calculateSecurityScore(config);
107
+
108
+ return {
109
+ success: true,
110
+ tenantId: config.tenantId,
111
+ securityScore,
112
+ auditHash,
113
+ executionTime,
114
+ complianceStatus,
115
+ };
116
+ } catch (error) {
117
+ const executionTime = Date.now() - startTime;
118
+
119
+ await this.auditTrail.logOperation({
120
+ operationId: `error-${config.tenantId}-${Date.now()}`,
121
+ tenantId: config.tenantId,
122
+ operation: "tenant_init_error",
123
+ data: {
124
+ error: error instanceof Error ? error.message : String(error),
125
+ config: this.sanitizeForAudit(config),
126
+ },
127
+ timestamp: new Date(),
128
+ success: false,
129
+ });
130
+
131
+ throw error;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Get isolated tenant app with security profile
137
+ */
138
+ public getTenantApp(tenantId: string): admin.app.App {
139
+ if (!this.tenants.has(tenantId)) {
140
+ throw new Error(`Tenant ${tenantId} not found or not initialized`);
141
+ }
142
+
143
+ return this.tenants.get(tenantId)!;
144
+ }
145
+
146
+ /**
147
+ * Execute operation in tenant context
148
+ */
149
+ public async executeInTenant<T>(
150
+ tenantId: string,
151
+ operation: string,
152
+ data: any,
153
+ callback: () => Promise<T>
154
+ ): Promise<T> {
155
+ const startTime = Date.now();
156
+
157
+ try {
158
+ const app = this.getTenantApp(tenantId);
159
+
160
+ // Generate audit trail
161
+ const operationId = `${operation}-${tenantId}-${Date.now()}`;
162
+ const auditHash = await this.auditTrail.logOperation({
163
+ operationId,
164
+ tenantId,
165
+ operation,
166
+ data: this.sanitizeForAudit(data),
167
+ timestamp: new Date(),
168
+ });
169
+
170
+ // Execute operation
171
+ const result = await callback();
172
+
173
+ // Record successful operation
174
+ const executionTime = Date.now() - startTime;
175
+ await this.auditTrail.logOperation({
176
+ operationId: `${operationId}-complete`,
177
+ tenantId,
178
+ operation: `${operation}_complete`,
179
+ data: { result: this.sanitizeForAudit(result), executionTime },
180
+ timestamp: new Date(),
181
+ success: true,
182
+ });
183
+
184
+ return result;
185
+ } catch (error) {
186
+ const executionTime = Date.now() - startTime;
187
+
188
+ await this.auditTrail.logOperation({
189
+ operationId: `${operation}-${tenantId}-${Date.now()}-error`,
190
+ tenantId,
191
+ operation: `${operation}_error`,
192
+ data: {
193
+ error: error instanceof Error ? error.message : String(error),
194
+ executionTime,
195
+ },
196
+ timestamp: new Date(),
197
+ success: false,
198
+ });
199
+
200
+ throw error;
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Configure security rules for tenant
206
+ */
207
+ private async configureSecurityRules(
208
+ app: admin.app.App,
209
+ config: TenantConfig
210
+ ): Promise<void> {
211
+ // Configure Firestore security rules based on profile
212
+ const db = app.firestore();
213
+
214
+ // Tenant-isolated rules
215
+ const rules = this.generateSecurityRules(config);
216
+
217
+ // Apply security configuration
218
+ // Note: In production, this would be set via Firebase console or API
219
+ await this.auditTrail.logOperation({
220
+ operationId: `security-${config.tenantId}-${Date.now()}`,
221
+ tenantId: config.tenantId,
222
+ operation: "security_config",
223
+ data: { securityLevel: config.securityProfile },
224
+ timestamp: new Date(),
225
+ });
226
+ }
227
+
228
+ /**
229
+ * Generate security rules based on profile
230
+ */
231
+ private generateSecurityRules(config: TenantConfig): string {
232
+ switch (config.securityProfile) {
233
+ case "ultra-secure":
234
+ return `
235
+ rules_version = '2';
236
+ service cloud.firestore {
237
+ match /databases/{database}/documents {
238
+ match /{document=**} {
239
+ allow read, write: if false;
240
+ }
241
+ }
242
+ }
243
+ `;
244
+ case "tenant-isolated":
245
+ return `
246
+ rules_version = '2';
247
+ service cloud.firestore {
248
+ match /databases/{database}/documents {
249
+ match /tenants/${config.tenantId}/{document=**} {
250
+ allow read, write: if request.auth.uid != null;
251
+ }
252
+ match /{document=**} {
253
+ allow read, write: if false;
254
+ }
255
+ }
256
+ }
257
+ `;
258
+ default:
259
+ throw new Error(`Unknown security profile: ${config.securityProfile}`);
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Verify LGPD/GDPR compliance for tenant
265
+ */
266
+ private async verifyCompliance(config: TenantConfig): Promise<{
267
+ lgpd: boolean;
268
+ gdpr: boolean;
269
+ }> {
270
+ let lgpd = false;
271
+ let gdpr = false;
272
+
273
+ if (config.lgpdEnabled) {
274
+ lgpd = await this.lgpdCompliance.verifyCompliance({
275
+ tenantId: config.tenantId,
276
+ dataConsent: true,
277
+ dataAnonymization: true,
278
+ dataRetentionDays: config.dataRetentionDays,
279
+ brazilianDataResidency: true,
280
+ rightToDelete: true,
281
+ dataOwnerRights: true,
282
+ automaticDeletion: true,
283
+ });
284
+ }
285
+
286
+ if (config.gdprEnabled) {
287
+ gdpr = await this.gdprCompliance.verifyCompliance({
288
+ tenantId: config.tenantId,
289
+ dataAnonymization: true,
290
+ consentManagement: true,
291
+ rightToBeForgotten: true,
292
+ dataPortability: true,
293
+ dataRetentionDays: config.dataRetentionDays,
294
+ });
295
+ }
296
+
297
+ return { lgpd, gdpr };
298
+ }
299
+
300
+ /**
301
+ * Calculate security score based on configuration
302
+ */
303
+ private calculateSecurityScore(config: TenantConfig): number {
304
+ let score = 5.0; // Base score
305
+
306
+ // Multi-tenant isolation
307
+ if (this.tenants.has(config.tenantId)) {
308
+ score += 1.0;
309
+ }
310
+
311
+ // Security profile
312
+ switch (config.securityProfile) {
313
+ case "ultra-secure":
314
+ score += 2.0;
315
+ break;
316
+ case "tenant-isolated":
317
+ score += 1.5;
318
+ break;
319
+ }
320
+
321
+ // Compliance features
322
+ if (config.lgpdEnabled) {
323
+ score += 0.5;
324
+ }
325
+ if (config.gdprEnabled) {
326
+ score += 0.5;
327
+ }
328
+
329
+ // Audit trail
330
+ if (runtimeConfig.auditEnabled) {
331
+ score += 1.0;
332
+ }
333
+
334
+ // Memory limit enforcement (1MB para multi-tenant)
335
+ const memoryLimit = runtimeConfig.memoryLimit;
336
+ if (memoryLimit <= 1) {
337
+ score += 0.5;
338
+ }
339
+
340
+ return Math.min(score, 10.0); // Máximo 10.0
341
+ }
342
+
343
+ /**
344
+ * Validate tenant configuration
345
+ */
346
+ private validateTenantConfig(config: TenantConfig): void {
347
+ if (!config.tenantId || config.tenantId.length < 3) {
348
+ throw new Error("Invalid tenant ID - must be at least 3 characters");
349
+ }
350
+
351
+ if (!config.projectId) {
352
+ throw new Error("Project ID is required");
353
+ }
354
+
355
+ if (!config.securityProfile) {
356
+ config.securityProfile = "tenant-isolated";
357
+ }
358
+
359
+ if (!config.dataRetentionDays) {
360
+ config.dataRetentionDays = 365; // 1 ano padrão LGPD
361
+ }
362
+
363
+ if (config.dataRetentionDays < 90) {
364
+ throw new Error("Data retention minimum 90 days for LGPD compliance");
365
+ }
366
+ }
367
+
368
+ /**
369
+ * Sanitize data for audit trail
370
+ */
371
+ private sanitizeForAudit(data: any): any {
372
+ return JSON.parse(
373
+ JSON.stringify(data, (key, value) => {
374
+ // Remove sensitive information
375
+ if (
376
+ key.includes("password") ||
377
+ key.includes("secret") ||
378
+ key.includes("key")
379
+ ) {
380
+ return "[REDACTED]";
381
+ }
382
+ return value;
383
+ })
384
+ );
385
+ }
386
+
387
+ /**
388
+ * Get all active tenants
389
+ */
390
+ public getActiveTenants(): string[] {
391
+ return Array.from(this.tenants.keys());
392
+ }
393
+
394
+ /**
395
+ * Get statistics for all tenants
396
+ */
397
+ public async getTenantStats(): Promise<Map<string, TenantIsolationResult>> {
398
+ const stats = new Map<string, TenantIsolationResult>();
399
+
400
+ for (const tenantId of this.tenants.keys()) {
401
+ // Simulate getting stats (in real implementation, would query actual metrics)
402
+ const mockStats: TenantIsolationResult = {
403
+ success: true,
404
+ tenantId,
405
+ securityScore: 9.5, // Target 9.5/10
406
+ auditHash: "SHA256-" + Math.random().toString(36),
407
+ executionTime: 95, // Target <100ms
408
+ complianceStatus: {
409
+ lgpd: true,
410
+ gdpr: true,
411
+ },
412
+ };
413
+
414
+ stats.set(tenantId, mockStats);
415
+ }
416
+
417
+ return stats;
418
+ }
419
+
420
+ /**
421
+ * Safely remove tenant
422
+ */
423
+ public async removeTenant(tenantId: string): Promise<void> {
424
+ if (!this.tenants.has(tenantId)) {
425
+ throw new Error(`Tenant ${tenantId} not found`);
426
+ }
427
+
428
+ const app = this.tenants.get(tenantId)!;
429
+
430
+ // Log removal
431
+ await this.auditTrail.logOperation({
432
+ operationId: `remove-${tenantId}-${Date.now()}`,
433
+ tenantId,
434
+ operation: "tenant_removal",
435
+ data: { reason: "admin_removal" },
436
+ timestamp: new Date(),
437
+ });
438
+
439
+ // Delete tenant app
440
+ await app.delete();
441
+ this.tenants.delete(tenantId);
442
+ }
443
+ }