@friggframework/devtools 2.0.0-next.12 → 2.0.0-next.121

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 (265) hide show
  1. package/frigg-cli/README.md +1336 -0
  2. package/frigg-cli/__tests__/unit/commands/build.test.js +279 -0
  3. package/frigg-cli/__tests__/unit/commands/db-setup.test.js +649 -0
  4. package/frigg-cli/__tests__/unit/commands/deploy.test.js +320 -0
  5. package/frigg-cli/__tests__/unit/commands/doctor.test.js +309 -0
  6. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +115 -0
  7. package/frigg-cli/__tests__/unit/commands/init.test.js +688 -0
  8. package/frigg-cli/__tests__/unit/commands/install.test.js +653 -0
  9. package/frigg-cli/__tests__/unit/commands/ui.test.js +346 -0
  10. package/frigg-cli/__tests__/unit/dependencies.test.js +74 -0
  11. package/frigg-cli/__tests__/unit/utils/database-validator.test.js +397 -0
  12. package/frigg-cli/__tests__/unit/utils/error-messages.test.js +345 -0
  13. package/frigg-cli/__tests__/unit/version-detection.test.js +171 -0
  14. package/frigg-cli/__tests__/utils/mock-factory.js +270 -0
  15. package/frigg-cli/__tests__/utils/prisma-mock.js +194 -0
  16. package/frigg-cli/__tests__/utils/test-fixtures.js +463 -0
  17. package/frigg-cli/__tests__/utils/test-setup.js +287 -0
  18. package/frigg-cli/auth-command/CLAUDE.md +293 -0
  19. package/frigg-cli/auth-command/README.md +450 -0
  20. package/frigg-cli/auth-command/api-key-flow.js +153 -0
  21. package/frigg-cli/auth-command/auth-tester.js +344 -0
  22. package/frigg-cli/auth-command/credential-storage.js +182 -0
  23. package/frigg-cli/auth-command/index.js +256 -0
  24. package/frigg-cli/auth-command/json-schema-form.js +67 -0
  25. package/frigg-cli/auth-command/module-loader.js +172 -0
  26. package/frigg-cli/auth-command/oauth-callback-server.js +431 -0
  27. package/frigg-cli/auth-command/oauth-flow.js +195 -0
  28. package/frigg-cli/auth-command/utils/browser.js +30 -0
  29. package/frigg-cli/build-command/index.js +17 -3
  30. package/frigg-cli/db-setup-command/index.js +246 -0
  31. package/frigg-cli/deploy-command/SPEC-DEPLOY-DRY-RUN.md +981 -0
  32. package/frigg-cli/deploy-command/index.js +339 -23
  33. package/frigg-cli/doctor-command/index.js +335 -0
  34. package/frigg-cli/generate-command/__tests__/generate-command.test.js +301 -0
  35. package/frigg-cli/generate-command/azure-generator.js +43 -0
  36. package/frigg-cli/generate-command/gcp-generator.js +47 -0
  37. package/frigg-cli/generate-command/index.js +334 -0
  38. package/frigg-cli/generate-command/terraform-generator.js +555 -0
  39. package/frigg-cli/generate-iam-command.js +120 -0
  40. package/frigg-cli/index.js +193 -1
  41. package/frigg-cli/index.test.js +1 -4
  42. package/frigg-cli/init-command/backend-first-handler.js +599 -0
  43. package/frigg-cli/init-command/deployment-modes.js +7 -0
  44. package/frigg-cli/init-command/index.js +140 -0
  45. package/frigg-cli/init-command/safe-path.js +58 -0
  46. package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
  47. package/frigg-cli/init-command/template-handler.js +143 -0
  48. package/frigg-cli/install-command/app-definition.js +174 -0
  49. package/frigg-cli/install-command/commit-changes.js +40 -8
  50. package/frigg-cli/install-command/environment-variables.js +15 -0
  51. package/frigg-cli/install-command/index.js +96 -24
  52. package/frigg-cli/install-command/install-package.js +77 -4
  53. package/frigg-cli/install-command/integration-file.js +20 -11
  54. package/frigg-cli/install-command/resolve-module.js +69 -0
  55. package/frigg-cli/install-command/template.js +102 -75
  56. package/frigg-cli/install-command/validate-package.js +36 -4
  57. package/frigg-cli/jest.config.js +124 -0
  58. package/frigg-cli/package.json +63 -0
  59. package/frigg-cli/repair-command/index.js +564 -0
  60. package/frigg-cli/ssm-command/index.js +308 -0
  61. package/frigg-cli/ssm-command/index.test.js +318 -0
  62. package/frigg-cli/start-command/index.js +118 -5
  63. package/frigg-cli/start-command/start-command.test.js +297 -0
  64. package/frigg-cli/templates/backend/README.md +267 -0
  65. package/frigg-cli/templates/backend/env.example +20 -0
  66. package/frigg-cli/templates/backend/gitignore +10 -0
  67. package/frigg-cli/templates/backend/index.js +114 -0
  68. package/frigg-cli/templates/backend/infrastructure.js +20 -0
  69. package/frigg-cli/test/init-command.test.js +187 -0
  70. package/frigg-cli/test/npm-registry.test.js +319 -0
  71. package/frigg-cli/ui-command/index.js +154 -0
  72. package/frigg-cli/utils/app-resolver.js +319 -0
  73. package/frigg-cli/utils/backend-path.js +16 -17
  74. package/frigg-cli/utils/database-validator.js +167 -0
  75. package/frigg-cli/utils/error-messages.js +329 -0
  76. package/frigg-cli/utils/npm-registry.js +167 -0
  77. package/frigg-cli/utils/process-manager.js +199 -0
  78. package/frigg-cli/utils/repo-detection.js +405 -0
  79. package/infrastructure/ARCHITECTURE.md +487 -0
  80. package/infrastructure/CLAUDE.md +481 -0
  81. package/infrastructure/HEALTH.md +468 -0
  82. package/infrastructure/README.md +540 -0
  83. package/infrastructure/__tests__/fixtures/mock-aws-resources.js +391 -0
  84. package/infrastructure/__tests__/helpers/test-utils.js +275 -0
  85. package/infrastructure/__tests__/postgres-config.test.js +914 -0
  86. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +148 -0
  87. package/infrastructure/__tests__/scoped-environment.test.js +126 -0
  88. package/infrastructure/__tests__/ssm-preload-node-options.test.js +79 -0
  89. package/infrastructure/__tests__/template-generation.test.js +687 -0
  90. package/infrastructure/create-frigg-infrastructure.js +129 -20
  91. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +650 -0
  92. package/infrastructure/docs/PRE-DEPLOYMENT-HEALTH-CHECK-SPEC.md +1317 -0
  93. package/infrastructure/docs/WEBSOCKET-CONFIGURATION.md +105 -0
  94. package/infrastructure/docs/deployment-instructions.md +268 -0
  95. package/infrastructure/docs/generate-iam-command.md +278 -0
  96. package/infrastructure/docs/iam-policy-templates.md +193 -0
  97. package/infrastructure/domains/admin-scripts/admin-script-builder.js +571 -0
  98. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +1047 -0
  99. package/infrastructure/domains/admin-scripts/index.js +5 -0
  100. package/infrastructure/domains/database/aurora-builder.js +868 -0
  101. package/infrastructure/domains/database/aurora-builder.test.js +982 -0
  102. package/infrastructure/domains/database/aurora-discovery.js +87 -0
  103. package/infrastructure/domains/database/aurora-discovery.test.js +188 -0
  104. package/infrastructure/domains/database/aurora-resolver.js +210 -0
  105. package/infrastructure/domains/database/aurora-resolver.test.js +347 -0
  106. package/infrastructure/domains/database/migration-builder.js +757 -0
  107. package/infrastructure/domains/database/migration-builder.test.js +454 -0
  108. package/infrastructure/domains/database/migration-resolver.js +163 -0
  109. package/infrastructure/domains/database/migration-resolver.test.js +337 -0
  110. package/infrastructure/domains/health/application/ports/IPropertyReconciler.js +164 -0
  111. package/infrastructure/domains/health/application/ports/IResourceDetector.js +129 -0
  112. package/infrastructure/domains/health/application/ports/IResourceImporter.js +142 -0
  113. package/infrastructure/domains/health/application/ports/IStackRepository.js +131 -0
  114. package/infrastructure/domains/health/application/ports/index.js +26 -0
  115. package/infrastructure/domains/health/application/use-cases/__tests__/execute-resource-import-use-case.test.js +679 -0
  116. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +167 -0
  117. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +1130 -0
  118. package/infrastructure/domains/health/application/use-cases/execute-resource-import-use-case.js +221 -0
  119. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +152 -0
  120. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.test.js +343 -0
  121. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +535 -0
  122. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.test.js +376 -0
  123. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +213 -0
  124. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +441 -0
  125. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +267 -0
  126. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +324 -0
  127. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +386 -0
  128. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +1419 -0
  129. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +391 -0
  130. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +551 -0
  131. package/infrastructure/domains/health/domain/entities/issue.js +299 -0
  132. package/infrastructure/domains/health/domain/entities/issue.test.js +528 -0
  133. package/infrastructure/domains/health/domain/entities/property-mismatch.js +108 -0
  134. package/infrastructure/domains/health/domain/entities/property-mismatch.test.js +275 -0
  135. package/infrastructure/domains/health/domain/entities/resource.js +159 -0
  136. package/infrastructure/domains/health/domain/entities/resource.test.js +432 -0
  137. package/infrastructure/domains/health/domain/entities/stack-health-report.js +306 -0
  138. package/infrastructure/domains/health/domain/entities/stack-health-report.test.js +601 -0
  139. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +380 -0
  140. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +971 -0
  141. package/infrastructure/domains/health/domain/services/__tests__/import-template-generator.test.js +1150 -0
  142. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +672 -0
  143. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +496 -0
  144. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +419 -0
  145. package/infrastructure/domains/health/domain/services/health-score-calculator.js +248 -0
  146. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +504 -0
  147. package/infrastructure/domains/health/domain/services/import-progress-monitor.js +195 -0
  148. package/infrastructure/domains/health/domain/services/import-template-generator.js +435 -0
  149. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +345 -0
  150. package/infrastructure/domains/health/domain/services/mismatch-analyzer.js +234 -0
  151. package/infrastructure/domains/health/domain/services/mismatch-analyzer.test.js +431 -0
  152. package/infrastructure/domains/health/domain/services/property-mutability-config.js +382 -0
  153. package/infrastructure/domains/health/domain/services/template-parser.js +245 -0
  154. package/infrastructure/domains/health/domain/services/update-progress-monitor.js +192 -0
  155. package/infrastructure/domains/health/domain/value-objects/health-score.js +138 -0
  156. package/infrastructure/domains/health/domain/value-objects/health-score.test.js +267 -0
  157. package/infrastructure/domains/health/domain/value-objects/property-mutability.js +161 -0
  158. package/infrastructure/domains/health/domain/value-objects/property-mutability.test.js +198 -0
  159. package/infrastructure/domains/health/domain/value-objects/resource-state.js +167 -0
  160. package/infrastructure/domains/health/domain/value-objects/resource-state.test.js +196 -0
  161. package/infrastructure/domains/health/domain/value-objects/stack-identifier.js +192 -0
  162. package/infrastructure/domains/health/domain/value-objects/stack-identifier.test.js +262 -0
  163. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +312 -0
  164. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +367 -0
  165. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +432 -0
  166. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +784 -0
  167. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +1133 -0
  168. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +565 -0
  169. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +554 -0
  170. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.js +318 -0
  171. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.test.js +398 -0
  172. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +777 -0
  173. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.test.js +580 -0
  174. package/infrastructure/domains/integration/integration-builder.js +668 -0
  175. package/infrastructure/domains/integration/integration-builder.test.js +1116 -0
  176. package/infrastructure/domains/integration/integration-resolver.js +170 -0
  177. package/infrastructure/domains/integration/integration-resolver.test.js +369 -0
  178. package/infrastructure/domains/integration/websocket-builder.js +69 -0
  179. package/infrastructure/domains/integration/websocket-builder.test.js +195 -0
  180. package/infrastructure/domains/networking/vpc-builder.js +2101 -0
  181. package/infrastructure/domains/networking/vpc-builder.test.js +2001 -0
  182. package/infrastructure/domains/networking/vpc-discovery.js +184 -0
  183. package/infrastructure/domains/networking/vpc-discovery.test.js +368 -0
  184. package/infrastructure/domains/networking/vpc-resolver.js +514 -0
  185. package/infrastructure/domains/networking/vpc-resolver.test.js +841 -0
  186. package/infrastructure/domains/parameters/offload-utils.js +197 -0
  187. package/infrastructure/domains/parameters/offload-utils.test.js +206 -0
  188. package/infrastructure/domains/parameters/ssm-builder.js +132 -0
  189. package/infrastructure/domains/parameters/ssm-builder.test.js +346 -0
  190. package/infrastructure/domains/parameters/ssm-discovery.js +84 -0
  191. package/infrastructure/domains/parameters/ssm-discovery.test.js +210 -0
  192. package/infrastructure/domains/scheduler/scheduler-builder.js +247 -0
  193. package/infrastructure/domains/scheduler/scheduler-builder.test.js +118 -0
  194. package/infrastructure/domains/security/iam-generator.js +959 -0
  195. package/infrastructure/domains/security/iam-generator.test.js +410 -0
  196. package/infrastructure/domains/security/kms-builder.js +415 -0
  197. package/infrastructure/domains/security/kms-builder.test.js +392 -0
  198. package/infrastructure/domains/security/kms-discovery.js +80 -0
  199. package/infrastructure/domains/security/kms-discovery.test.js +177 -0
  200. package/infrastructure/domains/security/kms-resolver.js +96 -0
  201. package/infrastructure/domains/security/kms-resolver.test.js +216 -0
  202. package/infrastructure/domains/security/templates/frigg-deployment-iam-stack.yaml +419 -0
  203. package/infrastructure/domains/security/templates/iam-policy-basic.json +219 -0
  204. package/infrastructure/domains/security/templates/iam-policy-full.json +294 -0
  205. package/infrastructure/domains/shared/base-builder.js +112 -0
  206. package/infrastructure/domains/shared/base-resolver.js +186 -0
  207. package/infrastructure/domains/shared/base-resolver.test.js +305 -0
  208. package/infrastructure/domains/shared/builder-orchestrator.js +226 -0
  209. package/infrastructure/domains/shared/builder-orchestrator.test.js +258 -0
  210. package/infrastructure/domains/shared/cloudformation-discovery-v2.js +334 -0
  211. package/infrastructure/domains/shared/cloudformation-discovery.js +681 -0
  212. package/infrastructure/domains/shared/cloudformation-discovery.test.js +1320 -0
  213. package/infrastructure/domains/shared/environment-builder.js +222 -0
  214. package/infrastructure/domains/shared/environment-builder.test.js +648 -0
  215. package/infrastructure/domains/shared/function-environments.js +97 -0
  216. package/infrastructure/domains/shared/function-environments.test.js +146 -0
  217. package/infrastructure/domains/shared/providers/aws-provider-adapter.js +579 -0
  218. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +416 -0
  219. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +93 -0
  220. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +136 -0
  221. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +82 -0
  222. package/infrastructure/domains/shared/providers/provider-factory.js +108 -0
  223. package/infrastructure/domains/shared/providers/provider-factory.test.js +170 -0
  224. package/infrastructure/domains/shared/resource-discovery.enhanced.test.js +306 -0
  225. package/infrastructure/domains/shared/resource-discovery.js +256 -0
  226. package/infrastructure/domains/shared/resource-discovery.test.js +757 -0
  227. package/infrastructure/domains/shared/types/app-definition.js +225 -0
  228. package/infrastructure/domains/shared/types/discovery-result.js +106 -0
  229. package/infrastructure/domains/shared/types/discovery-result.test.js +258 -0
  230. package/infrastructure/domains/shared/types/index.js +46 -0
  231. package/infrastructure/domains/shared/types/resource-ownership.js +108 -0
  232. package/infrastructure/domains/shared/types/resource-ownership.test.js +101 -0
  233. package/infrastructure/domains/shared/utilities/base-definition-factory.js +417 -0
  234. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +391 -0
  235. package/infrastructure/domains/shared/utilities/handler-path-resolver.js +134 -0
  236. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +268 -0
  237. package/infrastructure/domains/shared/utilities/logging-config.js +82 -0
  238. package/infrastructure/domains/shared/utilities/logging-config.test.js +52 -0
  239. package/infrastructure/domains/shared/utilities/nested-node-modules.js +53 -0
  240. package/infrastructure/domains/shared/utilities/nested-node-modules.test.js +61 -0
  241. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +159 -0
  242. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +444 -0
  243. package/infrastructure/domains/shared/validation/env-validator.js +78 -0
  244. package/infrastructure/domains/shared/validation/env-validator.test.js +173 -0
  245. package/infrastructure/domains/shared/validation/plugin-validator.js +187 -0
  246. package/infrastructure/domains/shared/validation/plugin-validator.test.js +323 -0
  247. package/infrastructure/esbuild.config.js +53 -0
  248. package/infrastructure/infrastructure-composer.js +168 -0
  249. package/infrastructure/infrastructure-composer.test.js +2086 -0
  250. package/infrastructure/integration.test.js +381 -0
  251. package/infrastructure/scripts/build-prisma-layer.js +701 -0
  252. package/infrastructure/scripts/build-prisma-layer.test.js +170 -0
  253. package/infrastructure/scripts/build-time-discovery.js +238 -0
  254. package/infrastructure/scripts/build-time-discovery.test.js +379 -0
  255. package/infrastructure/scripts/run-discovery.js +110 -0
  256. package/infrastructure/scripts/verify-prisma-layer.js +72 -0
  257. package/management-ui/README.md +203 -0
  258. package/package.json +49 -16
  259. package/test/index.js +2 -4
  260. package/test/mock-api.js +1 -3
  261. package/test/mock-integration.js +4 -14
  262. package/.eslintrc.json +0 -3
  263. package/CHANGELOG.md +0 -132
  264. package/infrastructure/serverless-template.js +0 -279
  265. package/test/auther-definition-tester.js +0 -125
@@ -0,0 +1,868 @@
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
+ // Pool + timeout query params appended to DATABASE_URL for Lambda-to-Aurora
25
+ // connections. Chosen to make worker Lambdas fail loud and fast on any DB
26
+ // contention rather than silently hanging for Lambda's 900s timeout.
27
+ //
28
+ // connection_limit=2 — two pg connections per Lambda container. One is too
29
+ // tight: several core use cases (get-process.executeMany,
30
+ // field-encryption-service batches) issue in-handler
31
+ // Promise.all against Prisma, and would serialize
32
+ // behind a single slot. Two removes that cliff while
33
+ // still being safe against max_connections (at 4 ACU
34
+ // Aurora pg 15 allows ~400 connections; 200 concurrent
35
+ // Lambdas × 2 = 400, leaves cluster room for maint).
36
+ // pool_timeout=20 — wait up to 20s for a pool slot, then throw P2024.
37
+ // Still fail-fast relative to 900s Lambda cap; gives
38
+ // in-handler fan-outs headroom.
39
+ // connect_timeout=10 — bound TCP/TLS handshake.
40
+ // socket_timeout=60 — kill dead client sockets (server never responds).
41
+ // options=-c statement_timeout=30000 -c lock_timeout=10000
42
+ // — Postgres-side hard caps. A query stuck >30s aborts
43
+ // with SQLSTATE 57014; a lock wait >10s aborts with
44
+ // SQLSTATE 55P03. URL encoding per libpq URI rules
45
+ // (space→%20, `=`→%3D inside the options value).
46
+ const LAMBDA_DATABASE_URL_QUERY_PARAMS = [
47
+ 'connection_limit=2',
48
+ 'pool_timeout=20',
49
+ 'connect_timeout=10',
50
+ 'socket_timeout=60',
51
+ 'options=-c%20statement_timeout%3D30000%20-c%20lock_timeout%3D10000',
52
+ ].join('&');
53
+
54
+ class AuroraBuilder extends InfrastructureBuilder {
55
+ constructor() {
56
+ super();
57
+ this.name = 'AuroraBuilder';
58
+ }
59
+
60
+ shouldExecute(appDefinition) {
61
+ // Skip Aurora in local mode (when FRIGG_SKIP_AWS_DISCOVERY is set)
62
+ // Aurora is an AWS-specific service that should only be created in production
63
+ if (process.env.FRIGG_SKIP_AWS_DISCOVERY === 'true') {
64
+ return false;
65
+ }
66
+
67
+ const postgres = appDefinition.database?.postgres;
68
+
69
+ // management='external': the app brings its own PostgreSQL (any
70
+ // provider) and connects through DATABASE_URL. Frigg creates and
71
+ // discovers no database resources and needs no VPC for it. This
72
+ // check precedes managementMode, which otherwise always manages
73
+ // Aurora. Migrations still run (MigrationBuilder) against DATABASE_URL.
74
+ if (postgres?.management === 'external') {
75
+ return false;
76
+ }
77
+
78
+ return postgres?.enable === true;
79
+ }
80
+
81
+ getDependencies() {
82
+ return ['VpcBuilder']; // Aurora requires VPC to be configured first
83
+ }
84
+
85
+ validate(appDefinition) {
86
+ const result = new ValidationResult();
87
+
88
+ if (!appDefinition.database?.postgres) {
89
+ result.addError('PostgreSQL database configuration is missing');
90
+ return result;
91
+ }
92
+
93
+ const dbConfig = appDefinition.database.postgres;
94
+
95
+ // Validate management mode
96
+ const validModes = ['discover', 'managed', 'use-existing', 'external'];
97
+ const management = dbConfig.management || 'discover';
98
+ if (!validModes.includes(management)) {
99
+ result.addError(`Invalid database.postgres.management: "${management}"`);
100
+ }
101
+
102
+ // Validate use-existing requirements
103
+ if (management === 'use-existing' && !dbConfig.endpoint) {
104
+ result.addError('database.postgres.endpoint is required when management="use-existing"');
105
+ }
106
+
107
+ // Validate capacity settings
108
+ if (dbConfig.minCapacity !== undefined && (dbConfig.minCapacity < 0.5 || dbConfig.minCapacity > 128)) {
109
+ result.addError('database.postgres.minCapacity must be between 0.5 and 128');
110
+ }
111
+ if (dbConfig.maxCapacity !== undefined && (dbConfig.maxCapacity < 0.5 || dbConfig.maxCapacity > 128)) {
112
+ result.addError('database.postgres.maxCapacity must be between 0.5 and 128');
113
+ }
114
+
115
+ // Warn about public accessibility in production
116
+ if (dbConfig.publiclyAccessible === true) {
117
+ result.addWarning('database.postgres.publiclyAccessible=true is not recommended for production');
118
+ }
119
+
120
+ return result;
121
+ }
122
+
123
+ /**
124
+ * Build Aurora infrastructure using ownership-based architecture
125
+ */
126
+ async build(appDefinition, discoveredResources) {
127
+ console.log(`\n[${this.name}] Configuring Aurora PostgreSQL...`);
128
+
129
+ // Backwards compatibility: Translate old schema to new ownership schema
130
+ appDefinition = this.translateLegacyConfig(appDefinition, discoveredResources);
131
+
132
+ // Initialize result
133
+ const result = {
134
+ resources: {},
135
+ iamStatements: [],
136
+ environment: {},
137
+ };
138
+
139
+ // Special case: use-existing with endpoint (bypass resolver)
140
+ if (appDefinition.database?.postgres?._useExistingEndpoint) {
141
+ console.log(' Using provided database endpoint (use-existing mode)');
142
+ await this.useExistingAurora(appDefinition, discoveredResources, result);
143
+ console.log(`\n[${this.name}] ✅ Aurora PostgreSQL configuration completed`);
144
+ return result;
145
+ }
146
+
147
+ // Get structured discovery result
148
+ const discovery = discoveredResources._structured || this.convertFlatDiscoveryToStructured(discoveredResources, appDefinition);
149
+
150
+ // Use AuroraResourceResolver to make ownership decisions
151
+ const resolver = new AuroraResourceResolver();
152
+ const decisions = resolver.resolveAll(appDefinition, discovery);
153
+
154
+ console.log('\n 📋 Resource Ownership Decisions:');
155
+ console.log(` Cluster: ${decisions.cluster.ownership} - ${decisions.cluster.reason}`);
156
+ console.log(` Instance: ${decisions.instance.ownership} - ${decisions.instance.reason}`);
157
+ console.log(` Subnet Group: ${decisions.subnetGroup.ownership} - ${decisions.subnetGroup.reason}`);
158
+ console.log(` Secret: ${decisions.secret.ownership} - ${decisions.secret.reason}`);
159
+
160
+ // Build resources based on ownership decisions
161
+ await this.buildFromDecisions(decisions, appDefinition, discoveredResources, result);
162
+
163
+ console.log(`\n[${this.name}] ✅ Aurora PostgreSQL configuration completed`);
164
+ return result;
165
+ }
166
+
167
+ /**
168
+ * Convert flat discovery to structured discovery
169
+ * Provides backwards compatibility for tests
170
+ */
171
+ convertFlatDiscoveryToStructured(flatDiscovery, appDefinition = {}) {
172
+ const discovery = createEmptyDiscoveryResult();
173
+
174
+ if (!flatDiscovery) {
175
+ return discovery;
176
+ }
177
+
178
+ // Check if resources are from CloudFormation stack
179
+ const isManagedIsolated = appDefinition.managementMode === 'managed' &&
180
+ (appDefinition.vpcIsolation === 'isolated' || !appDefinition.vpcIsolation);
181
+ const hasExistingStackResources = isManagedIsolated && flatDiscovery.auroraClusterId &&
182
+ typeof flatDiscovery.auroraClusterId === 'string';
183
+
184
+ if (flatDiscovery.fromCloudFormationStack || hasExistingStackResources) {
185
+ discovery.fromCloudFormation = true;
186
+ discovery.stackName = flatDiscovery.stackName || 'assumed-stack';
187
+
188
+ // Add stack-managed resources
189
+ let existingLogicalIds = flatDiscovery.existingLogicalIds || [];
190
+
191
+ // Infer logical IDs from physical IDs if needed
192
+ if (hasExistingStackResources && existingLogicalIds.length === 0) {
193
+ if (flatDiscovery.auroraClusterId) existingLogicalIds.push('FriggAuroraCluster');
194
+ if (flatDiscovery.auroraInstanceId) existingLogicalIds.push('FriggAuroraInstance');
195
+ if (flatDiscovery.dbSubnetGroupName) existingLogicalIds.push('FriggDBSubnetGroup');
196
+ if (flatDiscovery.dbSecretArn) existingLogicalIds.push('FriggDBSecret');
197
+ }
198
+
199
+ existingLogicalIds.forEach(logicalId => {
200
+ let resourceType = '';
201
+ let physicalId = '';
202
+
203
+ if (logicalId === 'FriggAuroraCluster') {
204
+ resourceType = 'AWS::RDS::DBCluster';
205
+ physicalId = flatDiscovery.auroraClusterId;
206
+ } else if (logicalId === 'FriggAuroraInstance') {
207
+ resourceType = 'AWS::RDS::DBInstance';
208
+ physicalId = flatDiscovery.auroraInstanceId;
209
+ } else if (logicalId === 'FriggDBSubnetGroup') {
210
+ resourceType = 'AWS::RDS::DBSubnetGroup';
211
+ physicalId = flatDiscovery.dbSubnetGroupName;
212
+ } else if (logicalId === 'FriggDBSecret') {
213
+ resourceType = 'AWS::SecretsManager::Secret';
214
+ physicalId = flatDiscovery.dbSecretArn;
215
+ }
216
+
217
+ if (physicalId && typeof physicalId === 'string') {
218
+ discovery.stackManaged.push({
219
+ logicalId,
220
+ physicalId,
221
+ resourceType
222
+ });
223
+ }
224
+ });
225
+ } else {
226
+ // Resources discovered from AWS API (external)
227
+ // Handle both cluster ID and endpoint
228
+ if (flatDiscovery.auroraClusterId && typeof flatDiscovery.auroraClusterId === 'string') {
229
+ discovery.external.push({
230
+ physicalId: flatDiscovery.auroraClusterId,
231
+ resourceType: 'AWS::RDS::DBCluster',
232
+ source: 'aws-discovery'
233
+ });
234
+ } else if (flatDiscovery.auroraClusterEndpoint && typeof flatDiscovery.auroraClusterEndpoint === 'string') {
235
+ // Endpoint provided (discover mode) - treat as external
236
+ discovery.external.push({
237
+ physicalId: flatDiscovery.auroraClusterEndpoint,
238
+ resourceType: 'AWS::RDS::DBCluster',
239
+ source: 'aws-discovery',
240
+ properties: { Endpoint: flatDiscovery.auroraClusterEndpoint }
241
+ });
242
+ }
243
+
244
+ if (flatDiscovery.auroraInstanceId && typeof flatDiscovery.auroraInstanceId === 'string') {
245
+ discovery.external.push({
246
+ physicalId: flatDiscovery.auroraInstanceId,
247
+ resourceType: 'AWS::RDS::DBInstance',
248
+ source: 'aws-discovery'
249
+ });
250
+ }
251
+ }
252
+
253
+ return discovery;
254
+ }
255
+
256
+ /**
257
+ * Translate legacy configuration to ownership-based configuration
258
+ * Provides backwards compatibility
259
+ */
260
+ translateLegacyConfig(appDefinition, discoveredResources) {
261
+ // If already using ownership schema, return as-is
262
+ if (appDefinition.database?.postgres?.ownership) {
263
+ return appDefinition;
264
+ }
265
+
266
+ const translated = JSON.parse(JSON.stringify(appDefinition));
267
+
268
+ // Initialize ownership sections
269
+ if (!translated.database) translated.database = {};
270
+ if (!translated.database.postgres) translated.database.postgres = {};
271
+ if (!translated.database.postgres.ownership) {
272
+ translated.database.postgres.ownership = {};
273
+ }
274
+ if (!translated.database.postgres.external) {
275
+ translated.database.postgres.external = {};
276
+ }
277
+ if (!translated.database.postgres.config) {
278
+ translated.database.postgres.config = {};
279
+ }
280
+
281
+ // Handle top-level managementMode
282
+ const globalMode = appDefinition.managementMode || 'discover';
283
+ const vpcIsolation = appDefinition.vpcIsolation || 'shared';
284
+
285
+ if (globalMode === 'managed') {
286
+ if (appDefinition.database?.postgres?.management) {
287
+ console.log(` ⚠️ managementMode='managed' ignoring: database.postgres.management`);
288
+ }
289
+
290
+ if (vpcIsolation === 'isolated') {
291
+ const hasStackAurora = discoveredResources?.auroraClusterId &&
292
+ typeof discoveredResources.auroraClusterId === 'string';
293
+
294
+ if (hasStackAurora) {
295
+ translated.database.postgres.ownership.cluster = 'auto';
296
+ translated.database.postgres.ownership.instance = 'auto';
297
+ translated.database.postgres.ownership.subnetGroup = 'auto';
298
+ translated.database.postgres.ownership.secret = 'auto';
299
+ console.log(` managementMode='managed' + vpcIsolation='isolated' → stack has Aurora, reusing`);
300
+ } else {
301
+ translated.database.postgres.ownership.cluster = 'stack';
302
+ translated.database.postgres.ownership.instance = 'stack';
303
+ translated.database.postgres.ownership.subnetGroup = 'stack';
304
+ translated.database.postgres.ownership.secret = 'stack';
305
+ console.log(` managementMode='managed' + vpcIsolation='isolated' → no stack Aurora, creating new`);
306
+ }
307
+ } else {
308
+ translated.database.postgres.ownership.cluster = 'auto';
309
+ translated.database.postgres.ownership.instance = 'auto';
310
+ translated.database.postgres.ownership.subnetGroup = 'auto';
311
+ translated.database.postgres.ownership.secret = 'auto';
312
+ console.log(` managementMode='managed' + vpcIsolation='shared' → discovering Aurora`);
313
+ }
314
+ } else if (globalMode === 'existing') {
315
+ translated.database.postgres.ownership.cluster = 'external';
316
+ translated.database.postgres.ownership.instance = 'external';
317
+ }
318
+
319
+ // Handle legacy database.postgres.management
320
+ // BUT: if managementMode (top-level) is set, it takes precedence
321
+ const dbManagement = appDefinition.database?.postgres?.management;
322
+ if (dbManagement && globalMode !== 'managed' && globalMode !== 'existing') {
323
+ if (dbManagement === 'managed') {
324
+ translated.database.postgres.ownership.cluster = 'stack';
325
+ translated.database.postgres.ownership.instance = 'stack';
326
+ translated.database.postgres.ownership.subnetGroup = 'stack';
327
+ translated.database.postgres.ownership.secret = 'stack';
328
+ } else if (dbManagement === 'use-existing') {
329
+ // For use-existing with endpoint, we bypass resolver entirely
330
+ // Mark this with a special flag
331
+ translated.database.postgres._useExistingEndpoint = true;
332
+ if (appDefinition.database.postgres.endpoint) {
333
+ translated.database.postgres.external.endpoint = appDefinition.database.postgres.endpoint;
334
+ }
335
+ } else if (dbManagement === 'discover') {
336
+ translated.database.postgres.ownership.cluster = 'auto';
337
+ translated.database.postgres.ownership.instance = 'auto';
338
+ }
339
+ }
340
+
341
+ // Preserve other database config
342
+ if (appDefinition.database?.postgres?.minCapacity) {
343
+ translated.database.postgres.config.minCapacity = appDefinition.database.postgres.minCapacity;
344
+ }
345
+ if (appDefinition.database?.postgres?.maxCapacity) {
346
+ translated.database.postgres.config.maxCapacity = appDefinition.database.postgres.maxCapacity;
347
+ }
348
+ if (appDefinition.database?.postgres?.publiclyAccessible !== undefined) {
349
+ translated.database.postgres.config.publiclyAccessible = appDefinition.database.postgres.publiclyAccessible;
350
+ }
351
+
352
+ return translated;
353
+ }
354
+
355
+ /**
356
+ * Build all Aurora resources based on ownership decisions
357
+ */
358
+ async buildFromDecisions(decisions, appDefinition, discoveredResources, result) {
359
+ // Determine build strategy from ownership decisions
360
+
361
+ if (decisions.cluster.ownership === ResourceOwnership.EXTERNAL) {
362
+ // External cluster discovered - reference it without creating infrastructure
363
+ console.log(' → Discovering and referencing external Aurora cluster');
364
+ await this.discoverAurora(appDefinition, discoveredResources, result);
365
+ } else if (decisions.cluster.ownership === ResourceOwnership.STACK && decisions.cluster.physicalId) {
366
+ // Cluster exists in stack - add definitions (CloudFormation idempotency)
367
+ console.log(' → Adding Aurora definitions to template (existing in stack)');
368
+ await this.createNewAurora(appDefinition, discoveredResources, result);
369
+ } else if (decisions.cluster.ownership === ResourceOwnership.STACK && !decisions.cluster.physicalId) {
370
+ // Create new cluster (stack, no existing)
371
+ console.log(' → Creating new Aurora cluster in stack');
372
+ await this.createNewAurora(appDefinition, discoveredResources, result);
373
+ } else {
374
+ // Fallback: discover mode
375
+ console.log(' → Discovering Aurora resources');
376
+ await this.discoverAurora(appDefinition, discoveredResources, result);
377
+ }
378
+ }
379
+
380
+ /**
381
+ * Create new Aurora cluster
382
+ */
383
+ async createNewAurora(appDefinition, discoveredResources, result) {
384
+ console.log(' Creating new Aurora Serverless v2 cluster...');
385
+
386
+ const dbConfig = appDefinition.database.postgres;
387
+ const publiclyAccessible = dbConfig.publiclyAccessible === true;
388
+
389
+ // Get subnet IDs for DB Subnet Group
390
+ const subnetIds = publiclyAccessible
391
+ ? [discoveredResources.publicSubnetId1, discoveredResources.publicSubnetId2]
392
+ : [discoveredResources.privateSubnetId1, discoveredResources.privateSubnetId2];
393
+
394
+ if (!subnetIds[0] || !subnetIds[1]) {
395
+ throw new Error(
396
+ `Aurora requires 2 ${publiclyAccessible ? 'public' : 'private'} subnets in different AZs. ` +
397
+ 'Ensure VPC is configured correctly.'
398
+ );
399
+ }
400
+
401
+ // Database Subnet Group
402
+ result.resources.FriggDBSubnetGroup = {
403
+ Type: 'AWS::RDS::DBSubnetGroup',
404
+ Properties: {
405
+ DBSubnetGroupName: '${self:service}-${self:provider.stage}-db-subnet-group',
406
+ DBSubnetGroupDescription: 'Subnet group for Frigg Aurora cluster',
407
+ SubnetIds: subnetIds,
408
+ Tags: [
409
+ { Key: 'Name', Value: '${self:service}-${self:provider.stage}-db-subnet' },
410
+ { Key: 'ManagedBy', Value: 'Frigg' },
411
+ ],
412
+ },
413
+ };
414
+
415
+ // Database Credentials Secret
416
+ result.resources.FriggDBSecret = {
417
+ Type: 'AWS::SecretsManager::Secret',
418
+ Properties: {
419
+ Name: '${self:service}-${self:provider.stage}-db-credentials',
420
+ Description: 'Aurora database credentials',
421
+ GenerateSecretString: {
422
+ SecretStringTemplate: JSON.stringify({ username: dbConfig.username || 'postgres' }),
423
+ GenerateStringKey: 'password',
424
+ PasswordLength: 32,
425
+ // Exclude URL-special characters for Prisma connection string compatibility
426
+ // Prisma docs: https://www.prisma.io/docs/reference/database-reference/connection-urls#special-characters
427
+ // Exclude: " @ : / ? # [ ] % \ (all have special meaning in URLs or need escaping)
428
+ ExcludeCharacters: '"@:/?#[]%\\\\',
429
+ },
430
+ Tags: [
431
+ { Key: 'Name', Value: '${self:service}-${self:provider.stage}-db-secret' },
432
+ { Key: 'ManagedBy', Value: 'Frigg' },
433
+ ],
434
+ },
435
+ };
436
+
437
+ // Aurora Cluster
438
+ result.resources.FriggAuroraCluster = {
439
+ Type: 'AWS::RDS::DBCluster',
440
+ DeletionPolicy: 'Snapshot',
441
+ Properties: {
442
+ Engine: 'aurora-postgresql',
443
+ EngineMode: 'provisioned',
444
+ EngineVersion: dbConfig.engineVersion || '15.13', // Configurable, defaults to 15.13 (latest as of Oct 2025)
445
+ Port: 5432, // Explicitly set PostgreSQL port (AWS may not auto-detect)
446
+ DatabaseName: dbConfig.database || 'frigg',
447
+ MasterUsername: {
448
+ 'Fn::Sub': '{{resolve:secretsmanager:${FriggDBSecret}:SecretString:username}}',
449
+ },
450
+ MasterUserPassword: {
451
+ 'Fn::Sub': '{{resolve:secretsmanager:${FriggDBSecret}:SecretString:password}}',
452
+ },
453
+ DBSubnetGroupName: { Ref: 'FriggDBSubnetGroup' },
454
+ VpcSecurityGroupIds: discoveredResources.vpcSecurityGroupIds || [
455
+ { Ref: 'FriggLambdaSecurityGroup' },
456
+ ],
457
+ // Note: PubliclyAccessible is NOT supported on Aurora clusters
458
+ // It should only be set on DB instances (see FriggAuroraInstance below)
459
+ // MaxCapacity default bumped 1 → 4 ACU: at 0.5–1 ACU Aurora is
460
+ // CPU-starved under 20-way concurrent writes from a Lambda
461
+ // fan-out sync, which starves worker queries and compounds
462
+ // the tail-latency problem. 4 ACU is still cheap (scales to
463
+ // min when idle) and gives the DB enough headroom to
464
+ // absorb bursty sync traffic. Apps can still override both
465
+ // via app definition dbConfig.
466
+ ServerlessV2ScalingConfiguration: {
467
+ MinCapacity: dbConfig.minCapacity || 0.5,
468
+ MaxCapacity: dbConfig.maxCapacity || 4,
469
+ },
470
+ EnableHttpEndpoint: false,
471
+ BackupRetentionPeriod: 7,
472
+ PreferredBackupWindow: '03:00-04:00',
473
+ PreferredMaintenanceWindow: 'sun:04:00-sun:05:00',
474
+ Tags: [
475
+ { Key: 'Name', Value: '${self:service}-${self:provider.stage}-aurora' },
476
+ { Key: 'ManagedBy', Value: 'Frigg' },
477
+ ],
478
+ },
479
+ };
480
+
481
+ // Aurora Instance
482
+ result.resources.FriggAuroraInstance = {
483
+ Type: 'AWS::RDS::DBInstance',
484
+ Properties: {
485
+ Engine: 'aurora-postgresql',
486
+ DBInstanceClass: 'db.serverless',
487
+ DBClusterIdentifier: { Ref: 'FriggAuroraCluster' },
488
+ PubliclyAccessible: publiclyAccessible,
489
+ Tags: [
490
+ { Key: 'Name', Value: '${self:service}-${self:provider.stage}-aurora-instance' },
491
+ { Key: 'ManagedBy', Value: 'Frigg' },
492
+ ],
493
+ },
494
+ };
495
+
496
+ // Environment variables
497
+ result.environment.DATABASE_URL = this.buildDatabaseUrl(
498
+ { 'Fn::GetAtt': ['FriggAuroraCluster', 'Endpoint.Address'] },
499
+ { 'Fn::GetAtt': ['FriggAuroraCluster', 'Endpoint.Port'] },
500
+ dbConfig.database || 'frigg',
501
+ { Ref: 'FriggDBSecret' }
502
+ );
503
+
504
+ // IAM permissions for Secrets Manager
505
+ result.iamStatements.push({
506
+ Effect: 'Allow',
507
+ Action: ['secretsmanager:GetSecretValue'],
508
+ Resource: { Ref: 'FriggDBSecret' },
509
+ });
510
+
511
+ // Add self-referencing security group ingress rule to allow Lambda to connect to Aurora
512
+ // Since both Lambda and Aurora share the same security group, we need to allow the SG to accept traffic from itself
513
+ result.resources.FriggAuroraIngressRule = {
514
+ Type: 'AWS::EC2::SecurityGroupIngress',
515
+ Properties: {
516
+ GroupId: { Ref: 'FriggLambdaSecurityGroup' },
517
+ IpProtocol: 'tcp',
518
+ FromPort: 5432,
519
+ ToPort: 5432,
520
+ SourceSecurityGroupId: { Ref: 'FriggLambdaSecurityGroup' },
521
+ Description: 'Allow Lambda functions to connect to Aurora PostgreSQL (self-referencing rule)',
522
+ },
523
+ };
524
+
525
+ console.log(' ✅ Aurora Serverless v2 cluster resources created');
526
+ }
527
+
528
+ /**
529
+ * Use existing Aurora cluster
530
+ */
531
+ async useExistingAurora(appDefinition, discoveredResources, result) {
532
+ console.log(' Using existing Aurora cluster...');
533
+
534
+ const dbConfig = appDefinition.database.postgres;
535
+
536
+ if (!dbConfig.endpoint) {
537
+ throw new Error('database.postgres.endpoint is required when management="use-existing"');
538
+ }
539
+
540
+ // Set environment variables for existing cluster
541
+ result.environment.DATABASE_HOST = dbConfig.endpoint;
542
+ result.environment.DATABASE_PORT = String(dbConfig.port || 5432);
543
+ result.environment.DATABASE_NAME = dbConfig.database || 'frigg';
544
+ result.environment.DATABASE_USER = dbConfig.username || 'postgres';
545
+ // Consumers that build DATABASE_URL from components at runtime MUST
546
+ // append `?${DATABASE_URL_PARAMS}` to get the same hang-prevention
547
+ // timeouts as the managed path.
548
+ result.environment.DATABASE_URL_PARAMS = LAMBDA_DATABASE_URL_QUERY_PARAMS;
549
+
550
+ console.log(` ✅ Using existing cluster: ${dbConfig.endpoint}`);
551
+ }
552
+
553
+ /**
554
+ * Discover existing Aurora cluster
555
+ */
556
+ async discoverAurora(appDefinition, discoveredResources, result) {
557
+ console.log(' Discovering Aurora cluster...');
558
+
559
+ if (!discoveredResources.auroraClusterEndpoint) {
560
+ throw new Error(
561
+ 'No Aurora cluster found in discovery mode. Set management to "managed" or provide endpoint with "use-existing".'
562
+ );
563
+ }
564
+
565
+ console.log(` ✅ Using discovered Aurora cluster: ${discoveredResources.auroraClusterEndpoint}`);
566
+
567
+ const dbConfig = appDefinition.database.postgres;
568
+
569
+ // Use discovered cluster details
570
+ result.environment.DATABASE_HOST = discoveredResources.auroraClusterEndpoint;
571
+ result.environment.DATABASE_PORT = String(discoveredResources.auroraPort || 5432);
572
+
573
+ // Check if we should auto-create credentials
574
+ if (dbConfig.autoCreateCredentials && !discoveredResources.databaseSecretArn) {
575
+ console.log(' Creating Secrets Manager secret and rotating Aurora password...');
576
+
577
+ // Create Secrets Manager secret with auto-generated password
578
+ result.resources.FriggDBSecret = {
579
+ Type: 'AWS::SecretsManager::Secret',
580
+ Properties: {
581
+ Name: '${self:service}-${self:provider.stage}-db-credentials',
582
+ Description: 'Aurora database credentials (auto-created for discovered cluster)',
583
+ GenerateSecretString: {
584
+ SecretStringTemplate: JSON.stringify({ username: dbConfig.username || 'postgres' }),
585
+ GenerateStringKey: 'password',
586
+ PasswordLength: 32,
587
+ // Exclude URL-special characters for Prisma connection string compatibility
588
+ // Prisma docs: https://www.prisma.io/docs/reference/database-reference/connection-urls#special-characters
589
+ // Exclude: " @ : / ? # [ ] % \ (all have special meaning in URLs or need escaping)
590
+ ExcludeCharacters: '"@:/?#[]%\\\\',
591
+ },
592
+ Tags: [
593
+ { Key: 'Name', Value: '${self:service}-${self:provider.stage}-db-secret' },
594
+ { Key: 'ManagedBy', Value: 'Frigg' },
595
+ { Key: 'Purpose', Value: 'DiscoveredClusterCredentials' },
596
+ ],
597
+ },
598
+ };
599
+
600
+ // Get the cluster identifier from the endpoint
601
+ // Format: cluster-name.cluster-xyz.region.rds.amazonaws.com
602
+ const clusterIdentifier = discoveredResources.auroraClusterEndpoint.split('.')[0];
603
+
604
+ // Create custom resource to rotate the Aurora master password
605
+ // This uses a Lambda-backed CloudFormation custom resource
606
+ result.resources.FriggAuroraPasswordRotator = {
607
+ Type: 'Custom::AuroraPasswordRotator',
608
+ Properties: {
609
+ ServiceToken: { 'Fn::GetAtt': ['PasswordRotatorLambda', 'Arn'] },
610
+ ClusterIdentifier: clusterIdentifier,
611
+ SecretArn: { Ref: 'FriggDBSecret' },
612
+ Region: '${self:provider.region}',
613
+ },
614
+ DependsOn: ['FriggDBSecret', 'PasswordRotatorLambda'],
615
+ };
616
+
617
+ // Lambda function to rotate the password
618
+ result.resources.PasswordRotatorLambda = {
619
+ Type: 'AWS::Lambda::Function',
620
+ Properties: {
621
+ FunctionName: '${self:service}-${self:provider.stage}-password-rotator',
622
+ Runtime: 'nodejs22.x',
623
+ Handler: 'index.handler',
624
+ Role: { 'Fn::GetAtt': ['PasswordRotatorRole', 'Arn'] },
625
+ Timeout: 60,
626
+ Code: {
627
+ ZipFile: `
628
+ const { RDSClient, ModifyDBClusterCommand } = require('@aws-sdk/client-rds');
629
+ const { SecretsManagerClient, GetSecretValueCommand } = require('@aws-sdk/client-secrets-manager');
630
+
631
+ exports.handler = async (event, context) => {
632
+ console.log('Event:', JSON.stringify(event, null, 2));
633
+
634
+ const { RequestType, ResourceProperties } = event;
635
+ const { ClusterIdentifier, SecretArn, Region } = ResourceProperties;
636
+
637
+ const sendResponse = async (status, data = {}) => {
638
+ const responseBody = JSON.stringify({
639
+ Status: status,
640
+ Reason: data.Reason || 'See CloudWatch logs',
641
+ PhysicalResourceId: context.logStreamName,
642
+ StackId: event.StackId,
643
+ RequestId: event.RequestId,
644
+ LogicalResourceId: event.LogicalResourceId,
645
+ Data: data,
646
+ });
647
+
648
+ await fetch(event.ResponseURL, {
649
+ method: 'PUT',
650
+ body: responseBody,
651
+ headers: { 'Content-Type': '' },
652
+ });
653
+ };
654
+
655
+ try {
656
+ if (RequestType === 'Delete') {
657
+ await sendResponse('SUCCESS', { Message: 'Delete not required' });
658
+ return;
659
+ }
660
+
661
+ // Get the new password from Secrets Manager
662
+ const smClient = new SecretsManagerClient({ region: Region });
663
+ const secretResponse = await smClient.send(
664
+ new GetSecretValueCommand({ SecretId: SecretArn })
665
+ );
666
+ const secret = JSON.parse(secretResponse.SecretString);
667
+ const newPassword = secret.password;
668
+
669
+ // Rotate the Aurora cluster master password
670
+ const rdsClient = new RDSClient({ region: Region });
671
+ await rdsClient.send(
672
+ new ModifyDBClusterCommand({
673
+ DBClusterIdentifier: ClusterIdentifier,
674
+ MasterUserPassword: newPassword,
675
+ ApplyImmediately: true,
676
+ })
677
+ );
678
+
679
+ console.log('Successfully rotated password for cluster: ' + ClusterIdentifier);
680
+ await sendResponse('SUCCESS', {
681
+ Message: 'Password rotated successfully',
682
+ ClusterIdentifier,
683
+ });
684
+ } catch (error) {
685
+ console.error('Error rotating password:', error);
686
+ await sendResponse('FAILED', { Reason: error.message });
687
+ }
688
+ };
689
+ `,
690
+ },
691
+ },
692
+ };
693
+
694
+ // IAM role for the password rotator Lambda
695
+ result.resources.PasswordRotatorRole = {
696
+ Type: 'AWS::IAM::Role',
697
+ Properties: {
698
+ AssumeRolePolicyDocument: {
699
+ Version: '2012-10-17',
700
+ Statement: [
701
+ {
702
+ Effect: 'Allow',
703
+ Principal: { Service: 'lambda.amazonaws.com' },
704
+ Action: 'sts:AssumeRole',
705
+ },
706
+ ],
707
+ },
708
+ ManagedPolicyArns: [
709
+ 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole',
710
+ ],
711
+ Policies: [
712
+ {
713
+ PolicyName: 'PasswordRotatorPolicy',
714
+ PolicyDocument: {
715
+ Version: '2012-10-17',
716
+ Statement: [
717
+ {
718
+ Effect: 'Allow',
719
+ Action: [
720
+ 'rds:ModifyDBCluster',
721
+ 'rds:DescribeDBClusters',
722
+ ],
723
+ Resource: '*',
724
+ },
725
+ {
726
+ Effect: 'Allow',
727
+ Action: ['secretsmanager:GetSecretValue'],
728
+ Resource: { Ref: 'FriggDBSecret' },
729
+ },
730
+ ],
731
+ },
732
+ },
733
+ ],
734
+ },
735
+ };
736
+
737
+ // Use the secret for DATABASE_URL
738
+ result.environment.DATABASE_SECRET_ARN = { Ref: 'FriggDBSecret' };
739
+ result.environment.DATABASE_URL = this.buildDatabaseUrl(
740
+ discoveredResources.auroraClusterEndpoint,
741
+ discoveredResources.auroraPort || 5432,
742
+ dbConfig.database || 'frigg',
743
+ { Ref: 'FriggDBSecret' }
744
+ );
745
+
746
+ // Grant Lambda functions permission to read the secret
747
+ result.iamStatements.push({
748
+ Effect: 'Allow',
749
+ Action: ['secretsmanager:GetSecretValue'],
750
+ Resource: { Ref: 'FriggDBSecret' },
751
+ });
752
+
753
+ console.log(' ✅ Credentials auto-creation configured');
754
+ } else if (discoveredResources.databaseSecretArn) {
755
+ // Use existing discovered secret
756
+ result.environment.DATABASE_SECRET_ARN = discoveredResources.databaseSecretArn;
757
+ result.environment.DATABASE_URL = this.buildDatabaseUrl(
758
+ discoveredResources.auroraClusterEndpoint,
759
+ discoveredResources.auroraPort || 5432,
760
+ dbConfig.database || 'frigg',
761
+ discoveredResources.databaseSecretArn
762
+ );
763
+
764
+ result.iamStatements.push({
765
+ Effect: 'Allow',
766
+ Action: ['secretsmanager:GetSecretValue'],
767
+ Resource: discoveredResources.databaseSecretArn,
768
+ });
769
+
770
+ console.log(' ✅ Using discovered Secrets Manager credentials');
771
+ } else {
772
+ // No secret and no auto-create - set individual DB connection components
773
+ // The application will construct DATABASE_URL at runtime from these components + DATABASE_USER + DATABASE_PASSWORD
774
+ const dbName = dbConfig.database || 'frigg';
775
+
776
+ result.environment.DATABASE_HOST = discoveredResources.auroraClusterEndpoint;
777
+ result.environment.DATABASE_PORT = String(discoveredResources.auroraPort || 5432);
778
+ result.environment.DATABASE_NAME = dbName;
779
+ // Consumers that build DATABASE_URL from components at runtime MUST
780
+ // append `?${DATABASE_URL_PARAMS}` to get the same hang-prevention
781
+ // timeouts as the managed path.
782
+ result.environment.DATABASE_URL_PARAMS = LAMBDA_DATABASE_URL_QUERY_PARAMS;
783
+
784
+ // Note: DATABASE_URL is NOT set here to avoid Serverless variable resolution errors
785
+ // The application (Frigg Core) should construct it at runtime from:
786
+ // DATABASE_HOST, DATABASE_PORT, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, DATABASE_URL_PARAMS
787
+
788
+ console.log(' ℹ️ No Secrets Manager secret found - set DATABASE_USER and DATABASE_PASSWORD in Lambda environment');
789
+ console.log(' ℹ️ Application will construct DATABASE_URL at runtime from DATABASE_HOST, DATABASE_PORT, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD');
790
+ console.log(' ℹ️ Append `?${DATABASE_URL_PARAMS}` to the constructed URL for pool/timeout safety.');
791
+ console.log(' ℹ️ Or enable autoCreateCredentials=true to automatically create and rotate credentials');
792
+ }
793
+
794
+ // Add security group ingress rule to allow Lambda to connect to Aurora
795
+ if (discoveredResources.auroraSecurityGroupId) {
796
+ result.resources.FriggAuroraIngressRule = {
797
+ Type: 'AWS::EC2::SecurityGroupIngress',
798
+ Properties: {
799
+ GroupId: discoveredResources.auroraSecurityGroupId,
800
+ IpProtocol: 'tcp',
801
+ FromPort: discoveredResources.auroraPort || 5432,
802
+ ToPort: discoveredResources.auroraPort || 5432,
803
+ SourceSecurityGroupId: { Ref: 'FriggLambdaSecurityGroup' },
804
+ Description: 'Allow Lambda functions to connect to Aurora PostgreSQL',
805
+ },
806
+ };
807
+ console.log(` ✅ Added security group ingress rule for Lambda → Aurora connectivity`);
808
+ }
809
+
810
+ console.log(` ✅ Discovered cluster configuration complete`);
811
+ }
812
+
813
+ /**
814
+ * Build DATABASE_URL connection string
815
+ * @param {string|object} host - Database host (string or CloudFormation intrinsic function)
816
+ * @param {string|number|object} port - Database port (string/number or CloudFormation intrinsic function)
817
+ * @param {string} database - Database name
818
+ * @param {string|object} secretRef - Secret ARN (string) or CloudFormation Ref object
819
+ */
820
+ buildDatabaseUrl(host, port, database, secretRef) {
821
+ // Handle secretRef as either a string ARN or CloudFormation Ref object
822
+ const resolveSecretRef = (secretRefValue) => {
823
+ if (typeof secretRefValue === 'object' && secretRefValue.Ref) {
824
+ // CloudFormation Ref - use nested Fn::Sub to resolve it
825
+ return {
826
+ 'Fn::Sub': [
827
+ '{{resolve:secretsmanager:${SecretArn}:SecretString:username}}',
828
+ { SecretArn: secretRefValue },
829
+ ],
830
+ };
831
+ }
832
+ // String ARN - use directly
833
+ return `{{resolve:secretsmanager:${secretRefValue}:SecretString:username}}`;
834
+ };
835
+
836
+ const resolveSecretPassword = (secretRefValue) => {
837
+ if (typeof secretRefValue === 'object' && secretRefValue.Ref) {
838
+ // CloudFormation Ref - use nested Fn::Sub to resolve it
839
+ return {
840
+ 'Fn::Sub': [
841
+ '{{resolve:secretsmanager:${SecretArn}:SecretString:password}}',
842
+ { SecretArn: secretRefValue },
843
+ ],
844
+ };
845
+ }
846
+ // String ARN - use directly
847
+ return `{{resolve:secretsmanager:${secretRefValue}:SecretString:password}}`;
848
+ };
849
+
850
+ // Query params are defined at module scope (LAMBDA_DATABASE_URL_QUERY_PARAMS)
851
+ // so runtime-URL-construction paths can emit the same timeouts as an env var.
852
+ return {
853
+ 'Fn::Sub': [
854
+ `postgresql://\${Username}:\${Password}@\${Host}:\${Port}/\${Database}?${LAMBDA_DATABASE_URL_QUERY_PARAMS}`,
855
+ {
856
+ Username: resolveSecretRef(secretRef),
857
+ Password: resolveSecretPassword(secretRef),
858
+ Host: host,
859
+ Port: port,
860
+ Database: database,
861
+ },
862
+ ],
863
+ };
864
+ }
865
+ }
866
+
867
+ module.exports = { AuroraBuilder };
868
+