@friggframework/devtools 2.0.0-next.60 → 2.0.0-next.62

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 (305) hide show
  1. package/package.json +14 -7
  2. package/.eslintrc.json +0 -3
  3. package/CHANGELOG.md +0 -132
  4. package/infrastructure/ARCHITECTURE.md +0 -487
  5. package/infrastructure/CLAUDE.md +0 -481
  6. package/infrastructure/HEALTH.md +0 -468
  7. package/infrastructure/README.md +0 -522
  8. package/infrastructure/__tests__/fixtures/mock-aws-resources.js +0 -391
  9. package/infrastructure/__tests__/helpers/test-utils.js +0 -277
  10. package/infrastructure/__tests__/postgres-config.test.js +0 -914
  11. package/infrastructure/__tests__/template-generation.test.js +0 -687
  12. package/infrastructure/create-frigg-infrastructure.js +0 -147
  13. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +0 -630
  14. package/infrastructure/docs/PRE-DEPLOYMENT-HEALTH-CHECK-SPEC.md +0 -1317
  15. package/infrastructure/docs/WEBSOCKET-CONFIGURATION.md +0 -105
  16. package/infrastructure/docs/deployment-instructions.md +0 -268
  17. package/infrastructure/docs/generate-iam-command.md +0 -278
  18. package/infrastructure/docs/iam-policy-templates.md +0 -193
  19. package/infrastructure/domains/database/aurora-builder.js +0 -809
  20. package/infrastructure/domains/database/aurora-builder.test.js +0 -950
  21. package/infrastructure/domains/database/aurora-discovery.js +0 -87
  22. package/infrastructure/domains/database/aurora-discovery.test.js +0 -188
  23. package/infrastructure/domains/database/aurora-resolver.js +0 -210
  24. package/infrastructure/domains/database/aurora-resolver.test.js +0 -347
  25. package/infrastructure/domains/database/migration-builder.js +0 -701
  26. package/infrastructure/domains/database/migration-builder.test.js +0 -321
  27. package/infrastructure/domains/database/migration-resolver.js +0 -163
  28. package/infrastructure/domains/database/migration-resolver.test.js +0 -337
  29. package/infrastructure/domains/health/application/ports/IPropertyReconciler.js +0 -164
  30. package/infrastructure/domains/health/application/ports/IResourceDetector.js +0 -129
  31. package/infrastructure/domains/health/application/ports/IResourceImporter.js +0 -142
  32. package/infrastructure/domains/health/application/ports/IStackRepository.js +0 -131
  33. package/infrastructure/domains/health/application/ports/index.js +0 -26
  34. package/infrastructure/domains/health/application/use-cases/__tests__/execute-resource-import-use-case.test.js +0 -679
  35. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +0 -167
  36. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +0 -1130
  37. package/infrastructure/domains/health/application/use-cases/execute-resource-import-use-case.js +0 -221
  38. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +0 -152
  39. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.test.js +0 -343
  40. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +0 -535
  41. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.test.js +0 -376
  42. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +0 -213
  43. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +0 -441
  44. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +0 -267
  45. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +0 -324
  46. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +0 -386
  47. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +0 -1419
  48. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +0 -391
  49. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +0 -551
  50. package/infrastructure/domains/health/domain/entities/issue.js +0 -299
  51. package/infrastructure/domains/health/domain/entities/issue.test.js +0 -528
  52. package/infrastructure/domains/health/domain/entities/property-mismatch.js +0 -108
  53. package/infrastructure/domains/health/domain/entities/property-mismatch.test.js +0 -275
  54. package/infrastructure/domains/health/domain/entities/resource.js +0 -159
  55. package/infrastructure/domains/health/domain/entities/resource.test.js +0 -432
  56. package/infrastructure/domains/health/domain/entities/stack-health-report.js +0 -306
  57. package/infrastructure/domains/health/domain/entities/stack-health-report.test.js +0 -601
  58. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +0 -380
  59. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +0 -971
  60. package/infrastructure/domains/health/domain/services/__tests__/import-template-generator.test.js +0 -1150
  61. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +0 -672
  62. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +0 -496
  63. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +0 -419
  64. package/infrastructure/domains/health/domain/services/health-score-calculator.js +0 -248
  65. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +0 -504
  66. package/infrastructure/domains/health/domain/services/import-progress-monitor.js +0 -195
  67. package/infrastructure/domains/health/domain/services/import-template-generator.js +0 -435
  68. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +0 -345
  69. package/infrastructure/domains/health/domain/services/mismatch-analyzer.js +0 -234
  70. package/infrastructure/domains/health/domain/services/mismatch-analyzer.test.js +0 -431
  71. package/infrastructure/domains/health/domain/services/property-mutability-config.js +0 -382
  72. package/infrastructure/domains/health/domain/services/template-parser.js +0 -245
  73. package/infrastructure/domains/health/domain/services/update-progress-monitor.js +0 -192
  74. package/infrastructure/domains/health/domain/value-objects/health-score.js +0 -138
  75. package/infrastructure/domains/health/domain/value-objects/health-score.test.js +0 -267
  76. package/infrastructure/domains/health/domain/value-objects/property-mutability.js +0 -161
  77. package/infrastructure/domains/health/domain/value-objects/property-mutability.test.js +0 -198
  78. package/infrastructure/domains/health/domain/value-objects/resource-state.js +0 -167
  79. package/infrastructure/domains/health/domain/value-objects/resource-state.test.js +0 -196
  80. package/infrastructure/domains/health/domain/value-objects/stack-identifier.js +0 -192
  81. package/infrastructure/domains/health/domain/value-objects/stack-identifier.test.js +0 -262
  82. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +0 -312
  83. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +0 -367
  84. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +0 -432
  85. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +0 -784
  86. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +0 -1133
  87. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +0 -565
  88. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +0 -554
  89. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.js +0 -318
  90. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.test.js +0 -398
  91. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +0 -777
  92. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.test.js +0 -580
  93. package/infrastructure/domains/integration/integration-builder.js +0 -404
  94. package/infrastructure/domains/integration/integration-builder.test.js +0 -690
  95. package/infrastructure/domains/integration/integration-resolver.js +0 -170
  96. package/infrastructure/domains/integration/integration-resolver.test.js +0 -369
  97. package/infrastructure/domains/integration/websocket-builder.js +0 -69
  98. package/infrastructure/domains/integration/websocket-builder.test.js +0 -195
  99. package/infrastructure/domains/networking/vpc-builder.js +0 -2051
  100. package/infrastructure/domains/networking/vpc-builder.test.js +0 -1960
  101. package/infrastructure/domains/networking/vpc-discovery.js +0 -177
  102. package/infrastructure/domains/networking/vpc-discovery.test.js +0 -350
  103. package/infrastructure/domains/networking/vpc-resolver.js +0 -505
  104. package/infrastructure/domains/networking/vpc-resolver.test.js +0 -801
  105. package/infrastructure/domains/parameters/ssm-builder.js +0 -79
  106. package/infrastructure/domains/parameters/ssm-builder.test.js +0 -189
  107. package/infrastructure/domains/parameters/ssm-discovery.js +0 -84
  108. package/infrastructure/domains/parameters/ssm-discovery.test.js +0 -210
  109. package/infrastructure/domains/security/iam-generator.js +0 -816
  110. package/infrastructure/domains/security/iam-generator.test.js +0 -204
  111. package/infrastructure/domains/security/kms-builder.js +0 -415
  112. package/infrastructure/domains/security/kms-builder.test.js +0 -392
  113. package/infrastructure/domains/security/kms-discovery.js +0 -80
  114. package/infrastructure/domains/security/kms-discovery.test.js +0 -177
  115. package/infrastructure/domains/security/kms-resolver.js +0 -96
  116. package/infrastructure/domains/security/kms-resolver.test.js +0 -216
  117. package/infrastructure/domains/security/templates/frigg-deployment-iam-stack.yaml +0 -401
  118. package/infrastructure/domains/security/templates/iam-policy-basic.json +0 -218
  119. package/infrastructure/domains/security/templates/iam-policy-full.json +0 -288
  120. package/infrastructure/domains/shared/base-builder.js +0 -112
  121. package/infrastructure/domains/shared/base-resolver.js +0 -186
  122. package/infrastructure/domains/shared/base-resolver.test.js +0 -305
  123. package/infrastructure/domains/shared/builder-orchestrator.js +0 -212
  124. package/infrastructure/domains/shared/builder-orchestrator.test.js +0 -213
  125. package/infrastructure/domains/shared/cloudformation-discovery-v2.js +0 -334
  126. package/infrastructure/domains/shared/cloudformation-discovery.js +0 -672
  127. package/infrastructure/domains/shared/cloudformation-discovery.test.js +0 -985
  128. package/infrastructure/domains/shared/environment-builder.js +0 -119
  129. package/infrastructure/domains/shared/environment-builder.test.js +0 -247
  130. package/infrastructure/domains/shared/providers/aws-provider-adapter.js +0 -579
  131. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +0 -416
  132. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +0 -93
  133. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +0 -136
  134. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +0 -82
  135. package/infrastructure/domains/shared/providers/provider-factory.js +0 -108
  136. package/infrastructure/domains/shared/providers/provider-factory.test.js +0 -170
  137. package/infrastructure/domains/shared/resource-discovery.enhanced.test.js +0 -306
  138. package/infrastructure/domains/shared/resource-discovery.js +0 -233
  139. package/infrastructure/domains/shared/resource-discovery.test.js +0 -588
  140. package/infrastructure/domains/shared/types/app-definition.js +0 -205
  141. package/infrastructure/domains/shared/types/discovery-result.js +0 -106
  142. package/infrastructure/domains/shared/types/discovery-result.test.js +0 -258
  143. package/infrastructure/domains/shared/types/index.js +0 -46
  144. package/infrastructure/domains/shared/types/resource-ownership.js +0 -108
  145. package/infrastructure/domains/shared/types/resource-ownership.test.js +0 -101
  146. package/infrastructure/domains/shared/utilities/base-definition-factory.js +0 -394
  147. package/infrastructure/domains/shared/utilities/base-definition-factory.js.bak +0 -338
  148. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +0 -291
  149. package/infrastructure/domains/shared/utilities/handler-path-resolver.js +0 -134
  150. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +0 -268
  151. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +0 -159
  152. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +0 -444
  153. package/infrastructure/domains/shared/validation/env-validator.js +0 -78
  154. package/infrastructure/domains/shared/validation/env-validator.test.js +0 -173
  155. package/infrastructure/domains/shared/validation/plugin-validator.js +0 -187
  156. package/infrastructure/domains/shared/validation/plugin-validator.test.js +0 -323
  157. package/infrastructure/esbuild.config.js +0 -53
  158. package/infrastructure/index.js +0 -4
  159. package/infrastructure/infrastructure-composer.js +0 -117
  160. package/infrastructure/infrastructure-composer.test.js +0 -1895
  161. package/infrastructure/integration.test.js +0 -383
  162. package/infrastructure/scripts/build-prisma-layer.js +0 -701
  163. package/infrastructure/scripts/build-prisma-layer.test.js +0 -170
  164. package/infrastructure/scripts/build-time-discovery.js +0 -238
  165. package/infrastructure/scripts/build-time-discovery.test.js +0 -379
  166. package/infrastructure/scripts/run-discovery.js +0 -110
  167. package/infrastructure/scripts/verify-prisma-layer.js +0 -72
  168. package/layers/prisma/.build-complete +0 -3
  169. package/layers/prisma/nodejs/package.json +0 -8
  170. package/management-ui/.eslintrc.js +0 -22
  171. package/management-ui/components.json +0 -21
  172. package/management-ui/docs/phase2-integration-guide.md +0 -320
  173. package/management-ui/index.html +0 -13
  174. package/management-ui/package.json +0 -76
  175. package/management-ui/packages/devtools/frigg-cli/ui-command/index.js +0 -302
  176. package/management-ui/postcss.config.js +0 -6
  177. package/management-ui/server/api/backend.js +0 -256
  178. package/management-ui/server/api/cli.js +0 -315
  179. package/management-ui/server/api/codegen.js +0 -663
  180. package/management-ui/server/api/connections.js +0 -857
  181. package/management-ui/server/api/discovery.js +0 -185
  182. package/management-ui/server/api/environment/index.js +0 -1
  183. package/management-ui/server/api/environment/router.js +0 -378
  184. package/management-ui/server/api/environment.js +0 -328
  185. package/management-ui/server/api/integrations.js +0 -876
  186. package/management-ui/server/api/logs.js +0 -248
  187. package/management-ui/server/api/monitoring.js +0 -282
  188. package/management-ui/server/api/open-ide.js +0 -31
  189. package/management-ui/server/api/project.js +0 -1029
  190. package/management-ui/server/api/users/sessions.js +0 -371
  191. package/management-ui/server/api/users/simulation.js +0 -254
  192. package/management-ui/server/api/users.js +0 -362
  193. package/management-ui/server/api-contract.md +0 -275
  194. package/management-ui/server/index.js +0 -873
  195. package/management-ui/server/middleware/errorHandler.js +0 -93
  196. package/management-ui/server/middleware/security.js +0 -32
  197. package/management-ui/server/processManager.js +0 -296
  198. package/management-ui/server/server.js +0 -346
  199. package/management-ui/server/services/aws-monitor.js +0 -413
  200. package/management-ui/server/services/npm-registry.js +0 -347
  201. package/management-ui/server/services/template-engine.js +0 -538
  202. package/management-ui/server/utils/cliIntegration.js +0 -220
  203. package/management-ui/server/utils/environment/auditLogger.js +0 -471
  204. package/management-ui/server/utils/environment/awsParameterStore.js +0 -275
  205. package/management-ui/server/utils/environment/encryption.js +0 -278
  206. package/management-ui/server/utils/environment/envFileManager.js +0 -286
  207. package/management-ui/server/utils/import-commonjs.js +0 -28
  208. package/management-ui/server/utils/response.js +0 -83
  209. package/management-ui/server/websocket/handler.js +0 -325
  210. package/management-ui/src/App.jsx +0 -25
  211. package/management-ui/src/assets/FriggLogo.svg +0 -1
  212. package/management-ui/src/components/AppRouter.jsx +0 -65
  213. package/management-ui/src/components/Button.jsx +0 -70
  214. package/management-ui/src/components/Card.jsx +0 -97
  215. package/management-ui/src/components/EnvironmentCompare.jsx +0 -400
  216. package/management-ui/src/components/EnvironmentEditor.jsx +0 -372
  217. package/management-ui/src/components/EnvironmentImportExport.jsx +0 -469
  218. package/management-ui/src/components/EnvironmentSchema.jsx +0 -491
  219. package/management-ui/src/components/EnvironmentSecurity.jsx +0 -463
  220. package/management-ui/src/components/ErrorBoundary.jsx +0 -73
  221. package/management-ui/src/components/IntegrationCard.jsx +0 -481
  222. package/management-ui/src/components/IntegrationCardEnhanced.jsx +0 -770
  223. package/management-ui/src/components/IntegrationExplorer.jsx +0 -379
  224. package/management-ui/src/components/IntegrationStatus.jsx +0 -336
  225. package/management-ui/src/components/Layout.jsx +0 -716
  226. package/management-ui/src/components/LoadingSpinner.jsx +0 -113
  227. package/management-ui/src/components/RepositoryPicker.jsx +0 -248
  228. package/management-ui/src/components/SessionMonitor.jsx +0 -350
  229. package/management-ui/src/components/StatusBadge.jsx +0 -208
  230. package/management-ui/src/components/UserContextSwitcher.jsx +0 -212
  231. package/management-ui/src/components/UserSimulation.jsx +0 -327
  232. package/management-ui/src/components/Welcome.jsx +0 -434
  233. package/management-ui/src/components/codegen/APIEndpointGenerator.jsx +0 -637
  234. package/management-ui/src/components/codegen/APIModuleSelector.jsx +0 -227
  235. package/management-ui/src/components/codegen/CodeGenerationWizard.jsx +0 -247
  236. package/management-ui/src/components/codegen/CodePreviewEditor.jsx +0 -316
  237. package/management-ui/src/components/codegen/DynamicModuleForm.jsx +0 -271
  238. package/management-ui/src/components/codegen/FormBuilder.jsx +0 -737
  239. package/management-ui/src/components/codegen/IntegrationGenerator.jsx +0 -855
  240. package/management-ui/src/components/codegen/ProjectScaffoldWizard.jsx +0 -797
  241. package/management-ui/src/components/codegen/SchemaBuilder.jsx +0 -303
  242. package/management-ui/src/components/codegen/TemplateSelector.jsx +0 -586
  243. package/management-ui/src/components/codegen/index.js +0 -10
  244. package/management-ui/src/components/connections/ConnectionConfigForm.jsx +0 -362
  245. package/management-ui/src/components/connections/ConnectionHealthMonitor.jsx +0 -182
  246. package/management-ui/src/components/connections/ConnectionTester.jsx +0 -200
  247. package/management-ui/src/components/connections/EntityRelationshipMapper.jsx +0 -292
  248. package/management-ui/src/components/connections/OAuthFlow.jsx +0 -204
  249. package/management-ui/src/components/connections/index.js +0 -5
  250. package/management-ui/src/components/index.js +0 -21
  251. package/management-ui/src/components/monitoring/APIGatewayMetrics.jsx +0 -222
  252. package/management-ui/src/components/monitoring/LambdaMetrics.jsx +0 -169
  253. package/management-ui/src/components/monitoring/MetricsChart.jsx +0 -197
  254. package/management-ui/src/components/monitoring/MonitoringDashboard.jsx +0 -393
  255. package/management-ui/src/components/monitoring/SQSMetrics.jsx +0 -246
  256. package/management-ui/src/components/monitoring/index.js +0 -6
  257. package/management-ui/src/components/monitoring/monitoring.css +0 -218
  258. package/management-ui/src/components/theme-provider.jsx +0 -52
  259. package/management-ui/src/components/theme-toggle.jsx +0 -39
  260. package/management-ui/src/components/ui/badge.tsx +0 -36
  261. package/management-ui/src/components/ui/button.test.jsx +0 -56
  262. package/management-ui/src/components/ui/button.tsx +0 -57
  263. package/management-ui/src/components/ui/card.tsx +0 -76
  264. package/management-ui/src/components/ui/dropdown-menu.tsx +0 -199
  265. package/management-ui/src/components/ui/select.tsx +0 -157
  266. package/management-ui/src/components/ui/skeleton.jsx +0 -15
  267. package/management-ui/src/hooks/useFrigg.jsx +0 -387
  268. package/management-ui/src/hooks/useSocket.jsx +0 -58
  269. package/management-ui/src/index.css +0 -193
  270. package/management-ui/src/lib/utils.ts +0 -6
  271. package/management-ui/src/main.jsx +0 -10
  272. package/management-ui/src/pages/CodeGeneration.jsx +0 -14
  273. package/management-ui/src/pages/Connections.jsx +0 -252
  274. package/management-ui/src/pages/ConnectionsEnhanced.jsx +0 -633
  275. package/management-ui/src/pages/Dashboard.jsx +0 -311
  276. package/management-ui/src/pages/Environment.jsx +0 -314
  277. package/management-ui/src/pages/IntegrationConfigure.jsx +0 -669
  278. package/management-ui/src/pages/IntegrationDiscovery.jsx +0 -567
  279. package/management-ui/src/pages/IntegrationTest.jsx +0 -742
  280. package/management-ui/src/pages/Integrations.jsx +0 -253
  281. package/management-ui/src/pages/Monitoring.jsx +0 -17
  282. package/management-ui/src/pages/Simulation.jsx +0 -155
  283. package/management-ui/src/pages/Users.jsx +0 -492
  284. package/management-ui/src/services/api.js +0 -41
  285. package/management-ui/src/services/apiModuleService.js +0 -193
  286. package/management-ui/src/services/websocket-handlers.js +0 -120
  287. package/management-ui/src/test/api/project.test.js +0 -273
  288. package/management-ui/src/test/components/Welcome.test.jsx +0 -378
  289. package/management-ui/src/test/mocks/server.js +0 -178
  290. package/management-ui/src/test/setup.js +0 -61
  291. package/management-ui/src/test/utils/test-utils.jsx +0 -134
  292. package/management-ui/src/utils/repository.js +0 -98
  293. package/management-ui/src/utils/repository.test.js +0 -118
  294. package/management-ui/src/workflows/phase2-integration-workflows.js +0 -884
  295. package/management-ui/tailwind.config.js +0 -63
  296. package/management-ui/tsconfig.json +0 -37
  297. package/management-ui/tsconfig.node.json +0 -10
  298. package/management-ui/vite.config.js +0 -26
  299. package/management-ui/vitest.config.js +0 -38
  300. package/test/auther-definition-method-tester.js +0 -45
  301. package/test/index.js +0 -9
  302. package/test/integration-validator.js +0 -2
  303. package/test/mock-api-readme.md +0 -102
  304. package/test/mock-api.js +0 -284
  305. package/test/mock-integration.js +0 -78
@@ -1,809 +0,0 @@
1
- /**
2
- * Aurora PostgreSQL Builder
3
- *
4
- * Domain Layer - Hexagonal Architecture
5
- *
6
- * Responsible for:
7
- * - Aurora Serverless v2 cluster creation or discovery
8
- * - Database subnet groups
9
- * - Database security groups
10
- * - Secrets Manager integration for credentials
11
- * - Database connection environment variables
12
- *
13
- * Uses ownership-based architecture:
14
- * - STACK: Resources in our CloudFormation template (definitions + Refs)
15
- * - EXTERNAL: Resources outside our stack (reference by physical ID)
16
- * - AUTO: System decides based on discovery
17
- */
18
-
19
- const { InfrastructureBuilder, ValidationResult } = require('../shared/base-builder');
20
- const AuroraResourceResolver = require('./aurora-resolver');
21
- const { createEmptyDiscoveryResult } = require('../shared/types/discovery-result');
22
- const { ResourceOwnership } = require('../shared/types/resource-ownership');
23
-
24
- class AuroraBuilder extends InfrastructureBuilder {
25
- constructor() {
26
- super();
27
- this.name = 'AuroraBuilder';
28
- }
29
-
30
- shouldExecute(appDefinition) {
31
- // Skip Aurora in local mode (when FRIGG_SKIP_AWS_DISCOVERY is set)
32
- // Aurora is an AWS-specific service that should only be created in production
33
- if (process.env.FRIGG_SKIP_AWS_DISCOVERY === 'true') {
34
- return false;
35
- }
36
-
37
- return appDefinition.database?.postgres?.enable === true;
38
- }
39
-
40
- getDependencies() {
41
- return ['VpcBuilder']; // Aurora requires VPC to be configured first
42
- }
43
-
44
- validate(appDefinition) {
45
- const result = new ValidationResult();
46
-
47
- if (!appDefinition.database?.postgres) {
48
- result.addError('PostgreSQL database configuration is missing');
49
- return result;
50
- }
51
-
52
- const dbConfig = appDefinition.database.postgres;
53
-
54
- // Validate management mode
55
- const validModes = ['discover', 'managed', 'use-existing'];
56
- const management = dbConfig.management || 'discover';
57
- if (!validModes.includes(management)) {
58
- result.addError(`Invalid database.postgres.management: "${management}"`);
59
- }
60
-
61
- // Validate use-existing requirements
62
- if (management === 'use-existing' && !dbConfig.endpoint) {
63
- result.addError('database.postgres.endpoint is required when management="use-existing"');
64
- }
65
-
66
- // Validate capacity settings
67
- if (dbConfig.minCapacity !== undefined && (dbConfig.minCapacity < 0.5 || dbConfig.minCapacity > 128)) {
68
- result.addError('database.postgres.minCapacity must be between 0.5 and 128');
69
- }
70
- if (dbConfig.maxCapacity !== undefined && (dbConfig.maxCapacity < 0.5 || dbConfig.maxCapacity > 128)) {
71
- result.addError('database.postgres.maxCapacity must be between 0.5 and 128');
72
- }
73
-
74
- // Warn about public accessibility in production
75
- if (dbConfig.publiclyAccessible === true) {
76
- result.addWarning('database.postgres.publiclyAccessible=true is not recommended for production');
77
- }
78
-
79
- return result;
80
- }
81
-
82
- /**
83
- * Build Aurora infrastructure using ownership-based architecture
84
- */
85
- async build(appDefinition, discoveredResources) {
86
- console.log(`\n[${this.name}] Configuring Aurora PostgreSQL...`);
87
-
88
- // Backwards compatibility: Translate old schema to new ownership schema
89
- appDefinition = this.translateLegacyConfig(appDefinition, discoveredResources);
90
-
91
- // Initialize result
92
- const result = {
93
- resources: {},
94
- iamStatements: [],
95
- environment: {},
96
- };
97
-
98
- // Special case: use-existing with endpoint (bypass resolver)
99
- if (appDefinition.database?.postgres?._useExistingEndpoint) {
100
- console.log(' Using provided database endpoint (use-existing mode)');
101
- await this.useExistingAurora(appDefinition, discoveredResources, result);
102
- console.log(`\n[${this.name}] ✅ Aurora PostgreSQL configuration completed`);
103
- return result;
104
- }
105
-
106
- // Get structured discovery result
107
- const discovery = discoveredResources._structured || this.convertFlatDiscoveryToStructured(discoveredResources, appDefinition);
108
-
109
- // Use AuroraResourceResolver to make ownership decisions
110
- const resolver = new AuroraResourceResolver();
111
- const decisions = resolver.resolveAll(appDefinition, discovery);
112
-
113
- console.log('\n 📋 Resource Ownership Decisions:');
114
- console.log(` Cluster: ${decisions.cluster.ownership} - ${decisions.cluster.reason}`);
115
- console.log(` Instance: ${decisions.instance.ownership} - ${decisions.instance.reason}`);
116
- console.log(` Subnet Group: ${decisions.subnetGroup.ownership} - ${decisions.subnetGroup.reason}`);
117
- console.log(` Secret: ${decisions.secret.ownership} - ${decisions.secret.reason}`);
118
-
119
- // Build resources based on ownership decisions
120
- await this.buildFromDecisions(decisions, appDefinition, discoveredResources, result);
121
-
122
- console.log(`\n[${this.name}] ✅ Aurora PostgreSQL configuration completed`);
123
- return result;
124
- }
125
-
126
- /**
127
- * Convert flat discovery to structured discovery
128
- * Provides backwards compatibility for tests
129
- */
130
- convertFlatDiscoveryToStructured(flatDiscovery, appDefinition = {}) {
131
- const discovery = createEmptyDiscoveryResult();
132
-
133
- if (!flatDiscovery) {
134
- return discovery;
135
- }
136
-
137
- // Check if resources are from CloudFormation stack
138
- const isManagedIsolated = appDefinition.managementMode === 'managed' &&
139
- (appDefinition.vpcIsolation === 'isolated' || !appDefinition.vpcIsolation);
140
- const hasExistingStackResources = isManagedIsolated && flatDiscovery.auroraClusterId &&
141
- typeof flatDiscovery.auroraClusterId === 'string';
142
-
143
- if (flatDiscovery.fromCloudFormationStack || hasExistingStackResources) {
144
- discovery.fromCloudFormation = true;
145
- discovery.stackName = flatDiscovery.stackName || 'assumed-stack';
146
-
147
- // Add stack-managed resources
148
- let existingLogicalIds = flatDiscovery.existingLogicalIds || [];
149
-
150
- // Infer logical IDs from physical IDs if needed
151
- if (hasExistingStackResources && existingLogicalIds.length === 0) {
152
- if (flatDiscovery.auroraClusterId) existingLogicalIds.push('FriggAuroraCluster');
153
- if (flatDiscovery.auroraInstanceId) existingLogicalIds.push('FriggAuroraInstance');
154
- if (flatDiscovery.dbSubnetGroupName) existingLogicalIds.push('FriggDBSubnetGroup');
155
- if (flatDiscovery.dbSecretArn) existingLogicalIds.push('FriggDBSecret');
156
- }
157
-
158
- existingLogicalIds.forEach(logicalId => {
159
- let resourceType = '';
160
- let physicalId = '';
161
-
162
- if (logicalId === 'FriggAuroraCluster') {
163
- resourceType = 'AWS::RDS::DBCluster';
164
- physicalId = flatDiscovery.auroraClusterId;
165
- } else if (logicalId === 'FriggAuroraInstance') {
166
- resourceType = 'AWS::RDS::DBInstance';
167
- physicalId = flatDiscovery.auroraInstanceId;
168
- } else if (logicalId === 'FriggDBSubnetGroup') {
169
- resourceType = 'AWS::RDS::DBSubnetGroup';
170
- physicalId = flatDiscovery.dbSubnetGroupName;
171
- } else if (logicalId === 'FriggDBSecret') {
172
- resourceType = 'AWS::SecretsManager::Secret';
173
- physicalId = flatDiscovery.dbSecretArn;
174
- }
175
-
176
- if (physicalId && typeof physicalId === 'string') {
177
- discovery.stackManaged.push({
178
- logicalId,
179
- physicalId,
180
- resourceType
181
- });
182
- }
183
- });
184
- } else {
185
- // Resources discovered from AWS API (external)
186
- // Handle both cluster ID and endpoint
187
- if (flatDiscovery.auroraClusterId && typeof flatDiscovery.auroraClusterId === 'string') {
188
- discovery.external.push({
189
- physicalId: flatDiscovery.auroraClusterId,
190
- resourceType: 'AWS::RDS::DBCluster',
191
- source: 'aws-discovery'
192
- });
193
- } else if (flatDiscovery.auroraClusterEndpoint && typeof flatDiscovery.auroraClusterEndpoint === 'string') {
194
- // Endpoint provided (discover mode) - treat as external
195
- discovery.external.push({
196
- physicalId: flatDiscovery.auroraClusterEndpoint,
197
- resourceType: 'AWS::RDS::DBCluster',
198
- source: 'aws-discovery',
199
- properties: { Endpoint: flatDiscovery.auroraClusterEndpoint }
200
- });
201
- }
202
-
203
- if (flatDiscovery.auroraInstanceId && typeof flatDiscovery.auroraInstanceId === 'string') {
204
- discovery.external.push({
205
- physicalId: flatDiscovery.auroraInstanceId,
206
- resourceType: 'AWS::RDS::DBInstance',
207
- source: 'aws-discovery'
208
- });
209
- }
210
- }
211
-
212
- return discovery;
213
- }
214
-
215
- /**
216
- * Translate legacy configuration to ownership-based configuration
217
- * Provides backwards compatibility
218
- */
219
- translateLegacyConfig(appDefinition, discoveredResources) {
220
- // If already using ownership schema, return as-is
221
- if (appDefinition.database?.postgres?.ownership) {
222
- return appDefinition;
223
- }
224
-
225
- const translated = JSON.parse(JSON.stringify(appDefinition));
226
-
227
- // Initialize ownership sections
228
- if (!translated.database) translated.database = {};
229
- if (!translated.database.postgres) translated.database.postgres = {};
230
- if (!translated.database.postgres.ownership) {
231
- translated.database.postgres.ownership = {};
232
- }
233
- if (!translated.database.postgres.external) {
234
- translated.database.postgres.external = {};
235
- }
236
- if (!translated.database.postgres.config) {
237
- translated.database.postgres.config = {};
238
- }
239
-
240
- // Handle top-level managementMode
241
- const globalMode = appDefinition.managementMode || 'discover';
242
- const vpcIsolation = appDefinition.vpcIsolation || 'shared';
243
-
244
- if (globalMode === 'managed') {
245
- if (appDefinition.database?.postgres?.management) {
246
- console.log(` ⚠️ managementMode='managed' ignoring: database.postgres.management`);
247
- }
248
-
249
- if (vpcIsolation === 'isolated') {
250
- const hasStackAurora = discoveredResources?.auroraClusterId &&
251
- typeof discoveredResources.auroraClusterId === 'string';
252
-
253
- if (hasStackAurora) {
254
- translated.database.postgres.ownership.cluster = 'auto';
255
- translated.database.postgres.ownership.instance = 'auto';
256
- translated.database.postgres.ownership.subnetGroup = 'auto';
257
- translated.database.postgres.ownership.secret = 'auto';
258
- console.log(` managementMode='managed' + vpcIsolation='isolated' → stack has Aurora, reusing`);
259
- } else {
260
- translated.database.postgres.ownership.cluster = 'stack';
261
- translated.database.postgres.ownership.instance = 'stack';
262
- translated.database.postgres.ownership.subnetGroup = 'stack';
263
- translated.database.postgres.ownership.secret = 'stack';
264
- console.log(` managementMode='managed' + vpcIsolation='isolated' → no stack Aurora, creating new`);
265
- }
266
- } else {
267
- translated.database.postgres.ownership.cluster = 'auto';
268
- translated.database.postgres.ownership.instance = 'auto';
269
- translated.database.postgres.ownership.subnetGroup = 'auto';
270
- translated.database.postgres.ownership.secret = 'auto';
271
- console.log(` managementMode='managed' + vpcIsolation='shared' → discovering Aurora`);
272
- }
273
- } else if (globalMode === 'existing') {
274
- translated.database.postgres.ownership.cluster = 'external';
275
- translated.database.postgres.ownership.instance = 'external';
276
- }
277
-
278
- // Handle legacy database.postgres.management
279
- // BUT: if managementMode (top-level) is set, it takes precedence
280
- const dbManagement = appDefinition.database?.postgres?.management;
281
- if (dbManagement && globalMode !== 'managed' && globalMode !== 'existing') {
282
- if (dbManagement === 'managed') {
283
- translated.database.postgres.ownership.cluster = 'stack';
284
- translated.database.postgres.ownership.instance = 'stack';
285
- translated.database.postgres.ownership.subnetGroup = 'stack';
286
- translated.database.postgres.ownership.secret = 'stack';
287
- } else if (dbManagement === 'use-existing') {
288
- // For use-existing with endpoint, we bypass resolver entirely
289
- // Mark this with a special flag
290
- translated.database.postgres._useExistingEndpoint = true;
291
- if (appDefinition.database.postgres.endpoint) {
292
- translated.database.postgres.external.endpoint = appDefinition.database.postgres.endpoint;
293
- }
294
- } else if (dbManagement === 'discover') {
295
- translated.database.postgres.ownership.cluster = 'auto';
296
- translated.database.postgres.ownership.instance = 'auto';
297
- }
298
- }
299
-
300
- // Preserve other database config
301
- if (appDefinition.database?.postgres?.minCapacity) {
302
- translated.database.postgres.config.minCapacity = appDefinition.database.postgres.minCapacity;
303
- }
304
- if (appDefinition.database?.postgres?.maxCapacity) {
305
- translated.database.postgres.config.maxCapacity = appDefinition.database.postgres.maxCapacity;
306
- }
307
- if (appDefinition.database?.postgres?.publiclyAccessible !== undefined) {
308
- translated.database.postgres.config.publiclyAccessible = appDefinition.database.postgres.publiclyAccessible;
309
- }
310
-
311
- return translated;
312
- }
313
-
314
- /**
315
- * Build all Aurora resources based on ownership decisions
316
- */
317
- async buildFromDecisions(decisions, appDefinition, discoveredResources, result) {
318
- // Determine build strategy from ownership decisions
319
-
320
- if (decisions.cluster.ownership === ResourceOwnership.EXTERNAL) {
321
- // External cluster discovered - reference it without creating infrastructure
322
- console.log(' → Discovering and referencing external Aurora cluster');
323
- await this.discoverAurora(appDefinition, discoveredResources, result);
324
- } else if (decisions.cluster.ownership === ResourceOwnership.STACK && decisions.cluster.physicalId) {
325
- // Cluster exists in stack - add definitions (CloudFormation idempotency)
326
- console.log(' → Adding Aurora definitions to template (existing in stack)');
327
- await this.createNewAurora(appDefinition, discoveredResources, result);
328
- } else if (decisions.cluster.ownership === ResourceOwnership.STACK && !decisions.cluster.physicalId) {
329
- // Create new cluster (stack, no existing)
330
- console.log(' → Creating new Aurora cluster in stack');
331
- await this.createNewAurora(appDefinition, discoveredResources, result);
332
- } else {
333
- // Fallback: discover mode
334
- console.log(' → Discovering Aurora resources');
335
- await this.discoverAurora(appDefinition, discoveredResources, result);
336
- }
337
- }
338
-
339
- /**
340
- * Create new Aurora cluster
341
- */
342
- async createNewAurora(appDefinition, discoveredResources, result) {
343
- console.log(' Creating new Aurora Serverless v2 cluster...');
344
-
345
- const dbConfig = appDefinition.database.postgres;
346
- const publiclyAccessible = dbConfig.publiclyAccessible === true;
347
-
348
- // Get subnet IDs for DB Subnet Group
349
- const subnetIds = publiclyAccessible
350
- ? [discoveredResources.publicSubnetId1, discoveredResources.publicSubnetId2]
351
- : [discoveredResources.privateSubnetId1, discoveredResources.privateSubnetId2];
352
-
353
- if (!subnetIds[0] || !subnetIds[1]) {
354
- throw new Error(
355
- `Aurora requires 2 ${publiclyAccessible ? 'public' : 'private'} subnets in different AZs. ` +
356
- 'Ensure VPC is configured correctly.'
357
- );
358
- }
359
-
360
- // Database Subnet Group
361
- result.resources.FriggDBSubnetGroup = {
362
- Type: 'AWS::RDS::DBSubnetGroup',
363
- Properties: {
364
- DBSubnetGroupName: '${self:service}-${self:provider.stage}-db-subnet-group',
365
- DBSubnetGroupDescription: 'Subnet group for Frigg Aurora cluster',
366
- SubnetIds: subnetIds,
367
- Tags: [
368
- { Key: 'Name', Value: '${self:service}-${self:provider.stage}-db-subnet' },
369
- { Key: 'ManagedBy', Value: 'Frigg' },
370
- ],
371
- },
372
- };
373
-
374
- // Database Credentials Secret
375
- result.resources.FriggDBSecret = {
376
- Type: 'AWS::SecretsManager::Secret',
377
- Properties: {
378
- Name: '${self:service}-${self:provider.stage}-db-credentials',
379
- Description: 'Aurora database credentials',
380
- GenerateSecretString: {
381
- SecretStringTemplate: JSON.stringify({ username: dbConfig.username || 'postgres' }),
382
- GenerateStringKey: 'password',
383
- PasswordLength: 32,
384
- // Exclude URL-special characters for Prisma connection string compatibility
385
- // Prisma docs: https://www.prisma.io/docs/reference/database-reference/connection-urls#special-characters
386
- // Exclude: " @ : / ? # [ ] % \ (all have special meaning in URLs or need escaping)
387
- ExcludeCharacters: '"@:/?#[]%\\\\',
388
- },
389
- Tags: [
390
- { Key: 'Name', Value: '${self:service}-${self:provider.stage}-db-secret' },
391
- { Key: 'ManagedBy', Value: 'Frigg' },
392
- ],
393
- },
394
- };
395
-
396
- // Aurora Cluster
397
- result.resources.FriggAuroraCluster = {
398
- Type: 'AWS::RDS::DBCluster',
399
- DeletionPolicy: 'Snapshot',
400
- Properties: {
401
- Engine: 'aurora-postgresql',
402
- EngineMode: 'provisioned',
403
- EngineVersion: dbConfig.engineVersion || '15.13', // Configurable, defaults to 15.13 (latest as of Oct 2025)
404
- Port: 5432, // Explicitly set PostgreSQL port (AWS may not auto-detect)
405
- DatabaseName: dbConfig.database || 'frigg',
406
- MasterUsername: {
407
- 'Fn::Sub': '{{resolve:secretsmanager:${FriggDBSecret}:SecretString:username}}',
408
- },
409
- MasterUserPassword: {
410
- 'Fn::Sub': '{{resolve:secretsmanager:${FriggDBSecret}:SecretString:password}}',
411
- },
412
- DBSubnetGroupName: { Ref: 'FriggDBSubnetGroup' },
413
- VpcSecurityGroupIds: discoveredResources.vpcSecurityGroupIds || [
414
- { Ref: 'FriggLambdaSecurityGroup' },
415
- ],
416
- // Note: PubliclyAccessible is NOT supported on Aurora clusters
417
- // It should only be set on DB instances (see FriggAuroraInstance below)
418
- ServerlessV2ScalingConfiguration: {
419
- MinCapacity: dbConfig.minCapacity || 0.5,
420
- MaxCapacity: dbConfig.maxCapacity || 1,
421
- },
422
- EnableHttpEndpoint: false,
423
- BackupRetentionPeriod: 7,
424
- PreferredBackupWindow: '03:00-04:00',
425
- PreferredMaintenanceWindow: 'sun:04:00-sun:05:00',
426
- Tags: [
427
- { Key: 'Name', Value: '${self:service}-${self:provider.stage}-aurora' },
428
- { Key: 'ManagedBy', Value: 'Frigg' },
429
- ],
430
- },
431
- };
432
-
433
- // Aurora Instance
434
- result.resources.FriggAuroraInstance = {
435
- Type: 'AWS::RDS::DBInstance',
436
- Properties: {
437
- Engine: 'aurora-postgresql',
438
- DBInstanceClass: 'db.serverless',
439
- DBClusterIdentifier: { Ref: 'FriggAuroraCluster' },
440
- PubliclyAccessible: publiclyAccessible,
441
- Tags: [
442
- { Key: 'Name', Value: '${self:service}-${self:provider.stage}-aurora-instance' },
443
- { Key: 'ManagedBy', Value: 'Frigg' },
444
- ],
445
- },
446
- };
447
-
448
- // Environment variables
449
- result.environment.DATABASE_URL = this.buildDatabaseUrl(
450
- { 'Fn::GetAtt': ['FriggAuroraCluster', 'Endpoint.Address'] },
451
- { 'Fn::GetAtt': ['FriggAuroraCluster', 'Endpoint.Port'] },
452
- dbConfig.database || 'frigg',
453
- { Ref: 'FriggDBSecret' }
454
- );
455
-
456
- // IAM permissions for Secrets Manager
457
- result.iamStatements.push({
458
- Effect: 'Allow',
459
- Action: ['secretsmanager:GetSecretValue'],
460
- Resource: { Ref: 'FriggDBSecret' },
461
- });
462
-
463
- // Add self-referencing security group ingress rule to allow Lambda to connect to Aurora
464
- // Since both Lambda and Aurora share the same security group, we need to allow the SG to accept traffic from itself
465
- result.resources.FriggAuroraIngressRule = {
466
- Type: 'AWS::EC2::SecurityGroupIngress',
467
- Properties: {
468
- GroupId: { Ref: 'FriggLambdaSecurityGroup' },
469
- IpProtocol: 'tcp',
470
- FromPort: 5432,
471
- ToPort: 5432,
472
- SourceSecurityGroupId: { Ref: 'FriggLambdaSecurityGroup' },
473
- Description: 'Allow Lambda functions to connect to Aurora PostgreSQL (self-referencing rule)',
474
- },
475
- };
476
-
477
- console.log(' ✅ Aurora Serverless v2 cluster resources created');
478
- }
479
-
480
- /**
481
- * Use existing Aurora cluster
482
- */
483
- async useExistingAurora(appDefinition, discoveredResources, result) {
484
- console.log(' Using existing Aurora cluster...');
485
-
486
- const dbConfig = appDefinition.database.postgres;
487
-
488
- if (!dbConfig.endpoint) {
489
- throw new Error('database.postgres.endpoint is required when management="use-existing"');
490
- }
491
-
492
- // Set environment variables for existing cluster
493
- result.environment.DATABASE_HOST = dbConfig.endpoint;
494
- result.environment.DATABASE_PORT = String(dbConfig.port || 5432);
495
- result.environment.DATABASE_NAME = dbConfig.database || 'frigg';
496
- result.environment.DATABASE_USER = dbConfig.username || 'postgres';
497
-
498
- console.log(` ✅ Using existing cluster: ${dbConfig.endpoint}`);
499
- }
500
-
501
- /**
502
- * Discover existing Aurora cluster
503
- */
504
- async discoverAurora(appDefinition, discoveredResources, result) {
505
- console.log(' Discovering Aurora cluster...');
506
-
507
- if (!discoveredResources.auroraClusterEndpoint) {
508
- throw new Error(
509
- 'No Aurora cluster found in discovery mode. Set management to "managed" or provide endpoint with "use-existing".'
510
- );
511
- }
512
-
513
- console.log(` ✅ Using discovered Aurora cluster: ${discoveredResources.auroraClusterEndpoint}`);
514
-
515
- const dbConfig = appDefinition.database.postgres;
516
-
517
- // Use discovered cluster details
518
- result.environment.DATABASE_HOST = discoveredResources.auroraClusterEndpoint;
519
- result.environment.DATABASE_PORT = String(discoveredResources.auroraPort || 5432);
520
-
521
- // Check if we should auto-create credentials
522
- if (dbConfig.autoCreateCredentials && !discoveredResources.databaseSecretArn) {
523
- console.log(' Creating Secrets Manager secret and rotating Aurora password...');
524
-
525
- // Create Secrets Manager secret with auto-generated password
526
- result.resources.FriggDBSecret = {
527
- Type: 'AWS::SecretsManager::Secret',
528
- Properties: {
529
- Name: '${self:service}-${self:provider.stage}-db-credentials',
530
- Description: 'Aurora database credentials (auto-created for discovered cluster)',
531
- GenerateSecretString: {
532
- SecretStringTemplate: JSON.stringify({ username: dbConfig.username || 'postgres' }),
533
- GenerateStringKey: 'password',
534
- PasswordLength: 32,
535
- // Exclude URL-special characters for Prisma connection string compatibility
536
- // Prisma docs: https://www.prisma.io/docs/reference/database-reference/connection-urls#special-characters
537
- // Exclude: " @ : / ? # [ ] % \ (all have special meaning in URLs or need escaping)
538
- ExcludeCharacters: '"@:/?#[]%\\\\',
539
- },
540
- Tags: [
541
- { Key: 'Name', Value: '${self:service}-${self:provider.stage}-db-secret' },
542
- { Key: 'ManagedBy', Value: 'Frigg' },
543
- { Key: 'Purpose', Value: 'DiscoveredClusterCredentials' },
544
- ],
545
- },
546
- };
547
-
548
- // Get the cluster identifier from the endpoint
549
- // Format: cluster-name.cluster-xyz.region.rds.amazonaws.com
550
- const clusterIdentifier = discoveredResources.auroraClusterEndpoint.split('.')[0];
551
-
552
- // Create custom resource to rotate the Aurora master password
553
- // This uses a Lambda-backed CloudFormation custom resource
554
- result.resources.FriggAuroraPasswordRotator = {
555
- Type: 'Custom::AuroraPasswordRotator',
556
- Properties: {
557
- ServiceToken: { 'Fn::GetAtt': ['PasswordRotatorLambda', 'Arn'] },
558
- ClusterIdentifier: clusterIdentifier,
559
- SecretArn: { Ref: 'FriggDBSecret' },
560
- Region: '${self:provider.region}',
561
- },
562
- DependsOn: ['FriggDBSecret', 'PasswordRotatorLambda'],
563
- };
564
-
565
- // Lambda function to rotate the password
566
- result.resources.PasswordRotatorLambda = {
567
- Type: 'AWS::Lambda::Function',
568
- Properties: {
569
- FunctionName: '${self:service}-${self:provider.stage}-password-rotator',
570
- Runtime: 'nodejs22.x',
571
- Handler: 'index.handler',
572
- Role: { 'Fn::GetAtt': ['PasswordRotatorRole', 'Arn'] },
573
- Timeout: 60,
574
- Code: {
575
- ZipFile: `
576
- const { RDSClient, ModifyDBClusterCommand } = require('@aws-sdk/client-rds');
577
- const { SecretsManagerClient, GetSecretValueCommand } = require('@aws-sdk/client-secrets-manager');
578
-
579
- exports.handler = async (event, context) => {
580
- console.log('Event:', JSON.stringify(event, null, 2));
581
-
582
- const { RequestType, ResourceProperties } = event;
583
- const { ClusterIdentifier, SecretArn, Region } = ResourceProperties;
584
-
585
- const sendResponse = async (status, data = {}) => {
586
- const responseBody = JSON.stringify({
587
- Status: status,
588
- Reason: data.Reason || 'See CloudWatch logs',
589
- PhysicalResourceId: context.logStreamName,
590
- StackId: event.StackId,
591
- RequestId: event.RequestId,
592
- LogicalResourceId: event.LogicalResourceId,
593
- Data: data,
594
- });
595
-
596
- await fetch(event.ResponseURL, {
597
- method: 'PUT',
598
- body: responseBody,
599
- headers: { 'Content-Type': '' },
600
- });
601
- };
602
-
603
- try {
604
- if (RequestType === 'Delete') {
605
- await sendResponse('SUCCESS', { Message: 'Delete not required' });
606
- return;
607
- }
608
-
609
- // Get the new password from Secrets Manager
610
- const smClient = new SecretsManagerClient({ region: Region });
611
- const secretResponse = await smClient.send(
612
- new GetSecretValueCommand({ SecretId: SecretArn })
613
- );
614
- const secret = JSON.parse(secretResponse.SecretString);
615
- const newPassword = secret.password;
616
-
617
- // Rotate the Aurora cluster master password
618
- const rdsClient = new RDSClient({ region: Region });
619
- await rdsClient.send(
620
- new ModifyDBClusterCommand({
621
- DBClusterIdentifier: ClusterIdentifier,
622
- MasterUserPassword: newPassword,
623
- ApplyImmediately: true,
624
- })
625
- );
626
-
627
- console.log('Successfully rotated password for cluster: ' + ClusterIdentifier);
628
- await sendResponse('SUCCESS', {
629
- Message: 'Password rotated successfully',
630
- ClusterIdentifier,
631
- });
632
- } catch (error) {
633
- console.error('Error rotating password:', error);
634
- await sendResponse('FAILED', { Reason: error.message });
635
- }
636
- };
637
- `,
638
- },
639
- },
640
- };
641
-
642
- // IAM role for the password rotator Lambda
643
- result.resources.PasswordRotatorRole = {
644
- Type: 'AWS::IAM::Role',
645
- Properties: {
646
- AssumeRolePolicyDocument: {
647
- Version: '2012-10-17',
648
- Statement: [
649
- {
650
- Effect: 'Allow',
651
- Principal: { Service: 'lambda.amazonaws.com' },
652
- Action: 'sts:AssumeRole',
653
- },
654
- ],
655
- },
656
- ManagedPolicyArns: [
657
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole',
658
- ],
659
- Policies: [
660
- {
661
- PolicyName: 'PasswordRotatorPolicy',
662
- PolicyDocument: {
663
- Version: '2012-10-17',
664
- Statement: [
665
- {
666
- Effect: 'Allow',
667
- Action: [
668
- 'rds:ModifyDBCluster',
669
- 'rds:DescribeDBClusters',
670
- ],
671
- Resource: '*',
672
- },
673
- {
674
- Effect: 'Allow',
675
- Action: ['secretsmanager:GetSecretValue'],
676
- Resource: { Ref: 'FriggDBSecret' },
677
- },
678
- ],
679
- },
680
- },
681
- ],
682
- },
683
- };
684
-
685
- // Use the secret for DATABASE_URL
686
- result.environment.DATABASE_SECRET_ARN = { Ref: 'FriggDBSecret' };
687
- result.environment.DATABASE_URL = this.buildDatabaseUrl(
688
- discoveredResources.auroraClusterEndpoint,
689
- discoveredResources.auroraPort || 5432,
690
- dbConfig.database || 'frigg',
691
- { Ref: 'FriggDBSecret' }
692
- );
693
-
694
- // Grant Lambda functions permission to read the secret
695
- result.iamStatements.push({
696
- Effect: 'Allow',
697
- Action: ['secretsmanager:GetSecretValue'],
698
- Resource: { Ref: 'FriggDBSecret' },
699
- });
700
-
701
- console.log(' ✅ Credentials auto-creation configured');
702
- } else if (discoveredResources.databaseSecretArn) {
703
- // Use existing discovered secret
704
- result.environment.DATABASE_SECRET_ARN = discoveredResources.databaseSecretArn;
705
- result.environment.DATABASE_URL = this.buildDatabaseUrl(
706
- discoveredResources.auroraClusterEndpoint,
707
- discoveredResources.auroraPort || 5432,
708
- dbConfig.database || 'frigg',
709
- discoveredResources.databaseSecretArn
710
- );
711
-
712
- result.iamStatements.push({
713
- Effect: 'Allow',
714
- Action: ['secretsmanager:GetSecretValue'],
715
- Resource: discoveredResources.databaseSecretArn,
716
- });
717
-
718
- console.log(' ✅ Using discovered Secrets Manager credentials');
719
- } else {
720
- // No secret and no auto-create - set individual DB connection components
721
- // The application will construct DATABASE_URL at runtime from these components + DATABASE_USER + DATABASE_PASSWORD
722
- const dbName = dbConfig.database || 'frigg';
723
-
724
- result.environment.DATABASE_HOST = discoveredResources.auroraClusterEndpoint;
725
- result.environment.DATABASE_PORT = String(discoveredResources.auroraPort || 5432);
726
- result.environment.DATABASE_NAME = dbName;
727
-
728
- // Note: DATABASE_URL is NOT set here to avoid Serverless variable resolution errors
729
- // The application (Frigg Core) should construct it at runtime from:
730
- // DATABASE_HOST, DATABASE_PORT, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD
731
-
732
- console.log(' ℹ️ No Secrets Manager secret found - set DATABASE_USER and DATABASE_PASSWORD in Lambda environment');
733
- console.log(' ℹ️ Application will construct DATABASE_URL at runtime from DATABASE_HOST, DATABASE_PORT, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD');
734
- console.log(' ℹ️ Or enable autoCreateCredentials=true to automatically create and rotate credentials');
735
- }
736
-
737
- // Add security group ingress rule to allow Lambda to connect to Aurora
738
- if (discoveredResources.auroraSecurityGroupId) {
739
- result.resources.FriggAuroraIngressRule = {
740
- Type: 'AWS::EC2::SecurityGroupIngress',
741
- Properties: {
742
- GroupId: discoveredResources.auroraSecurityGroupId,
743
- IpProtocol: 'tcp',
744
- FromPort: discoveredResources.auroraPort || 5432,
745
- ToPort: discoveredResources.auroraPort || 5432,
746
- SourceSecurityGroupId: { Ref: 'FriggLambdaSecurityGroup' },
747
- Description: 'Allow Lambda functions to connect to Aurora PostgreSQL',
748
- },
749
- };
750
- console.log(` ✅ Added security group ingress rule for Lambda → Aurora connectivity`);
751
- }
752
-
753
- console.log(` ✅ Discovered cluster configuration complete`);
754
- }
755
-
756
- /**
757
- * Build DATABASE_URL connection string
758
- * @param {string|object} host - Database host (string or CloudFormation intrinsic function)
759
- * @param {string|number|object} port - Database port (string/number or CloudFormation intrinsic function)
760
- * @param {string} database - Database name
761
- * @param {string|object} secretRef - Secret ARN (string) or CloudFormation Ref object
762
- */
763
- buildDatabaseUrl(host, port, database, secretRef) {
764
- // Handle secretRef as either a string ARN or CloudFormation Ref object
765
- const resolveSecretRef = (secretRefValue) => {
766
- if (typeof secretRefValue === 'object' && secretRefValue.Ref) {
767
- // CloudFormation Ref - use nested Fn::Sub to resolve it
768
- return {
769
- 'Fn::Sub': [
770
- '{{resolve:secretsmanager:${SecretArn}:SecretString:username}}',
771
- { SecretArn: secretRefValue },
772
- ],
773
- };
774
- }
775
- // String ARN - use directly
776
- return `{{resolve:secretsmanager:${secretRefValue}:SecretString:username}}`;
777
- };
778
-
779
- const resolveSecretPassword = (secretRefValue) => {
780
- if (typeof secretRefValue === 'object' && secretRefValue.Ref) {
781
- // CloudFormation Ref - use nested Fn::Sub to resolve it
782
- return {
783
- 'Fn::Sub': [
784
- '{{resolve:secretsmanager:${SecretArn}:SecretString:password}}',
785
- { SecretArn: secretRefValue },
786
- ],
787
- };
788
- }
789
- // String ARN - use directly
790
- return `{{resolve:secretsmanager:${secretRefValue}:SecretString:password}}`;
791
- };
792
-
793
- return {
794
- 'Fn::Sub': [
795
- `postgresql://\${Username}:\${Password}@\${Host}:\${Port}/\${Database}`,
796
- {
797
- Username: resolveSecretRef(secretRef),
798
- Password: resolveSecretPassword(secretRef),
799
- Host: host,
800
- Port: port,
801
- Database: database,
802
- },
803
- ],
804
- };
805
- }
806
- }
807
-
808
- module.exports = { AuroraBuilder };
809
-