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

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 (165) hide show
  1. package/infrastructure/ARCHITECTURE.md +487 -0
  2. package/infrastructure/CLAUDE.md +481 -0
  3. package/infrastructure/HEALTH.md +468 -0
  4. package/infrastructure/README.md +522 -0
  5. package/infrastructure/__tests__/fixtures/mock-aws-resources.js +391 -0
  6. package/infrastructure/__tests__/helpers/test-utils.js +277 -0
  7. package/infrastructure/__tests__/postgres-config.test.js +914 -0
  8. package/infrastructure/__tests__/template-generation.test.js +687 -0
  9. package/infrastructure/create-frigg-infrastructure.js +147 -0
  10. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +630 -0
  11. package/infrastructure/docs/PRE-DEPLOYMENT-HEALTH-CHECK-SPEC.md +1317 -0
  12. package/infrastructure/docs/WEBSOCKET-CONFIGURATION.md +105 -0
  13. package/infrastructure/docs/deployment-instructions.md +268 -0
  14. package/infrastructure/docs/generate-iam-command.md +278 -0
  15. package/infrastructure/docs/iam-policy-templates.md +193 -0
  16. package/infrastructure/domains/database/aurora-builder.js +809 -0
  17. package/infrastructure/domains/database/aurora-builder.test.js +950 -0
  18. package/infrastructure/domains/database/aurora-discovery.js +87 -0
  19. package/infrastructure/domains/database/aurora-discovery.test.js +188 -0
  20. package/infrastructure/domains/database/aurora-resolver.js +210 -0
  21. package/infrastructure/domains/database/aurora-resolver.test.js +347 -0
  22. package/infrastructure/domains/database/migration-builder.js +701 -0
  23. package/infrastructure/domains/database/migration-builder.test.js +321 -0
  24. package/infrastructure/domains/database/migration-resolver.js +163 -0
  25. package/infrastructure/domains/database/migration-resolver.test.js +337 -0
  26. package/infrastructure/domains/health/application/ports/IPropertyReconciler.js +164 -0
  27. package/infrastructure/domains/health/application/ports/IResourceDetector.js +129 -0
  28. package/infrastructure/domains/health/application/ports/IResourceImporter.js +142 -0
  29. package/infrastructure/domains/health/application/ports/IStackRepository.js +131 -0
  30. package/infrastructure/domains/health/application/ports/index.js +26 -0
  31. package/infrastructure/domains/health/application/use-cases/__tests__/execute-resource-import-use-case.test.js +679 -0
  32. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +167 -0
  33. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +1130 -0
  34. package/infrastructure/domains/health/application/use-cases/execute-resource-import-use-case.js +221 -0
  35. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +152 -0
  36. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.test.js +343 -0
  37. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +535 -0
  38. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.test.js +376 -0
  39. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +213 -0
  40. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +441 -0
  41. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +267 -0
  42. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +324 -0
  43. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +386 -0
  44. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +1419 -0
  45. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +391 -0
  46. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +551 -0
  47. package/infrastructure/domains/health/domain/entities/issue.js +299 -0
  48. package/infrastructure/domains/health/domain/entities/issue.test.js +528 -0
  49. package/infrastructure/domains/health/domain/entities/property-mismatch.js +108 -0
  50. package/infrastructure/domains/health/domain/entities/property-mismatch.test.js +275 -0
  51. package/infrastructure/domains/health/domain/entities/resource.js +159 -0
  52. package/infrastructure/domains/health/domain/entities/resource.test.js +432 -0
  53. package/infrastructure/domains/health/domain/entities/stack-health-report.js +306 -0
  54. package/infrastructure/domains/health/domain/entities/stack-health-report.test.js +601 -0
  55. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +380 -0
  56. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +971 -0
  57. package/infrastructure/domains/health/domain/services/__tests__/import-template-generator.test.js +1150 -0
  58. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +672 -0
  59. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +496 -0
  60. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +419 -0
  61. package/infrastructure/domains/health/domain/services/health-score-calculator.js +248 -0
  62. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +504 -0
  63. package/infrastructure/domains/health/domain/services/import-progress-monitor.js +195 -0
  64. package/infrastructure/domains/health/domain/services/import-template-generator.js +435 -0
  65. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +345 -0
  66. package/infrastructure/domains/health/domain/services/mismatch-analyzer.js +234 -0
  67. package/infrastructure/domains/health/domain/services/mismatch-analyzer.test.js +431 -0
  68. package/infrastructure/domains/health/domain/services/property-mutability-config.js +382 -0
  69. package/infrastructure/domains/health/domain/services/template-parser.js +245 -0
  70. package/infrastructure/domains/health/domain/services/update-progress-monitor.js +192 -0
  71. package/infrastructure/domains/health/domain/value-objects/health-score.js +138 -0
  72. package/infrastructure/domains/health/domain/value-objects/health-score.test.js +267 -0
  73. package/infrastructure/domains/health/domain/value-objects/property-mutability.js +161 -0
  74. package/infrastructure/domains/health/domain/value-objects/property-mutability.test.js +198 -0
  75. package/infrastructure/domains/health/domain/value-objects/resource-state.js +167 -0
  76. package/infrastructure/domains/health/domain/value-objects/resource-state.test.js +196 -0
  77. package/infrastructure/domains/health/domain/value-objects/stack-identifier.js +192 -0
  78. package/infrastructure/domains/health/domain/value-objects/stack-identifier.test.js +262 -0
  79. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +312 -0
  80. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +367 -0
  81. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +432 -0
  82. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +784 -0
  83. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +1133 -0
  84. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +565 -0
  85. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +554 -0
  86. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.js +318 -0
  87. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.test.js +398 -0
  88. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +777 -0
  89. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.test.js +580 -0
  90. package/infrastructure/domains/integration/integration-builder.js +404 -0
  91. package/infrastructure/domains/integration/integration-builder.test.js +690 -0
  92. package/infrastructure/domains/integration/integration-resolver.js +170 -0
  93. package/infrastructure/domains/integration/integration-resolver.test.js +369 -0
  94. package/infrastructure/domains/integration/websocket-builder.js +69 -0
  95. package/infrastructure/domains/integration/websocket-builder.test.js +195 -0
  96. package/infrastructure/domains/networking/vpc-builder.js +2051 -0
  97. package/infrastructure/domains/networking/vpc-builder.test.js +1960 -0
  98. package/infrastructure/domains/networking/vpc-discovery.js +177 -0
  99. package/infrastructure/domains/networking/vpc-discovery.test.js +350 -0
  100. package/infrastructure/domains/networking/vpc-resolver.js +505 -0
  101. package/infrastructure/domains/networking/vpc-resolver.test.js +801 -0
  102. package/infrastructure/domains/parameters/ssm-builder.js +79 -0
  103. package/infrastructure/domains/parameters/ssm-builder.test.js +189 -0
  104. package/infrastructure/domains/parameters/ssm-discovery.js +84 -0
  105. package/infrastructure/domains/parameters/ssm-discovery.test.js +210 -0
  106. package/infrastructure/domains/security/iam-generator.js +816 -0
  107. package/infrastructure/domains/security/iam-generator.test.js +204 -0
  108. package/infrastructure/domains/security/kms-builder.js +415 -0
  109. package/infrastructure/domains/security/kms-builder.test.js +392 -0
  110. package/infrastructure/domains/security/kms-discovery.js +80 -0
  111. package/infrastructure/domains/security/kms-discovery.test.js +177 -0
  112. package/infrastructure/domains/security/kms-resolver.js +96 -0
  113. package/infrastructure/domains/security/kms-resolver.test.js +216 -0
  114. package/infrastructure/domains/security/templates/frigg-deployment-iam-stack.yaml +401 -0
  115. package/infrastructure/domains/security/templates/iam-policy-basic.json +218 -0
  116. package/infrastructure/domains/security/templates/iam-policy-full.json +288 -0
  117. package/infrastructure/domains/shared/base-builder.js +112 -0
  118. package/infrastructure/domains/shared/base-resolver.js +186 -0
  119. package/infrastructure/domains/shared/base-resolver.test.js +305 -0
  120. package/infrastructure/domains/shared/builder-orchestrator.js +212 -0
  121. package/infrastructure/domains/shared/builder-orchestrator.test.js +213 -0
  122. package/infrastructure/domains/shared/cloudformation-discovery-v2.js +334 -0
  123. package/infrastructure/domains/shared/cloudformation-discovery.js +672 -0
  124. package/infrastructure/domains/shared/cloudformation-discovery.test.js +985 -0
  125. package/infrastructure/domains/shared/environment-builder.js +119 -0
  126. package/infrastructure/domains/shared/environment-builder.test.js +247 -0
  127. package/infrastructure/domains/shared/providers/aws-provider-adapter.js +579 -0
  128. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +416 -0
  129. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +93 -0
  130. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +136 -0
  131. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +82 -0
  132. package/infrastructure/domains/shared/providers/provider-factory.js +108 -0
  133. package/infrastructure/domains/shared/providers/provider-factory.test.js +170 -0
  134. package/infrastructure/domains/shared/resource-discovery.enhanced.test.js +306 -0
  135. package/infrastructure/domains/shared/resource-discovery.js +233 -0
  136. package/infrastructure/domains/shared/resource-discovery.test.js +588 -0
  137. package/infrastructure/domains/shared/types/app-definition.js +205 -0
  138. package/infrastructure/domains/shared/types/discovery-result.js +106 -0
  139. package/infrastructure/domains/shared/types/discovery-result.test.js +258 -0
  140. package/infrastructure/domains/shared/types/index.js +46 -0
  141. package/infrastructure/domains/shared/types/resource-ownership.js +108 -0
  142. package/infrastructure/domains/shared/types/resource-ownership.test.js +101 -0
  143. package/infrastructure/domains/shared/utilities/base-definition-factory.js +408 -0
  144. package/infrastructure/domains/shared/utilities/base-definition-factory.js.bak +338 -0
  145. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +291 -0
  146. package/infrastructure/domains/shared/utilities/handler-path-resolver.js +134 -0
  147. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +268 -0
  148. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +159 -0
  149. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +444 -0
  150. package/infrastructure/domains/shared/validation/env-validator.js +78 -0
  151. package/infrastructure/domains/shared/validation/env-validator.test.js +173 -0
  152. package/infrastructure/domains/shared/validation/plugin-validator.js +187 -0
  153. package/infrastructure/domains/shared/validation/plugin-validator.test.js +323 -0
  154. package/infrastructure/esbuild.config.js +53 -0
  155. package/infrastructure/index.js +4 -0
  156. package/infrastructure/infrastructure-composer.js +117 -0
  157. package/infrastructure/infrastructure-composer.test.js +1895 -0
  158. package/infrastructure/integration.test.js +383 -0
  159. package/infrastructure/scripts/build-prisma-layer.js +701 -0
  160. package/infrastructure/scripts/build-prisma-layer.test.js +170 -0
  161. package/infrastructure/scripts/build-time-discovery.js +238 -0
  162. package/infrastructure/scripts/build-time-discovery.test.js +379 -0
  163. package/infrastructure/scripts/run-discovery.js +110 -0
  164. package/infrastructure/scripts/verify-prisma-layer.js +72 -0
  165. package/package.json +8 -7
@@ -0,0 +1,672 @@
1
+ /**
2
+ * CloudFormation-based Resource Discovery
3
+ *
4
+ * Domain Service - Hexagonal Architecture
5
+ *
6
+ * Discovers resources from existing CloudFormation stacks as the primary
7
+ * source of truth before falling back to direct AWS API discovery.
8
+ *
9
+ * Benefits:
10
+ * - Faster discovery (1 CF call vs multiple AWS API calls)
11
+ * - More accurate (stack is source of truth)
12
+ * - Eliminates tagging dependencies
13
+ * - Idempotent (discover mode reuses stack resources)
14
+ */
15
+
16
+ class CloudFormationDiscovery {
17
+ constructor(provider, config = {}) {
18
+ this.provider = provider;
19
+ this.serviceName = config.serviceName;
20
+ this.stage = config.stage;
21
+ }
22
+
23
+ /**
24
+ * Discover resources from an existing CloudFormation stack
25
+ *
26
+ * @param {string} stackName - Name of the CloudFormation stack
27
+ * @returns {Promise<Object|null>} Discovered resources or null if stack doesn't exist
28
+ */
29
+ async discoverFromStack(stackName) {
30
+ try {
31
+ // Store stack name for use in helper methods
32
+ this.currentStackName = stackName;
33
+
34
+ // Try to get the stack
35
+ const stack = await this.provider.describeStack(stackName);
36
+
37
+ // Get stack resources
38
+ const resources = await this.provider.listStackResources(stackName);
39
+
40
+ // Extract discovered resources from outputs and resources
41
+ const discovered = {
42
+ // Metadata to indicate resources came from CloudFormation stack
43
+ fromCloudFormationStack: true,
44
+ stackName: stackName,
45
+ existingLogicalIds: []
46
+ };
47
+
48
+ // Extract from outputs
49
+ if (stack.Outputs && stack.Outputs.length > 0) {
50
+ this._extractFromOutputs(stack.Outputs, discovered);
51
+ }
52
+
53
+ // Extract from resources (now async to query AWS for details)
54
+ // Always call this even if resources is empty, as it may query AWS for resources
55
+ await this._extractFromResources(resources || [], discovered);
56
+
57
+ // Clean up metadata if no resources were discovered
58
+ if (discovered.existingLogicalIds.length === 0) {
59
+ delete discovered.existingLogicalIds;
60
+ }
61
+
62
+ return discovered;
63
+ } catch (error) {
64
+ // Stack doesn't exist - return null to trigger fallback discovery
65
+ if (error.message && error.message.includes('does not exist')) {
66
+ return null;
67
+ }
68
+
69
+ // Other errors - log and return null
70
+ console.warn(`⚠️ CloudFormation discovery failed: ${error.message}`);
71
+ return null;
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Extract discovered resources from CloudFormation stack outputs
77
+ *
78
+ * @private
79
+ * @param {Array} outputs - CloudFormation stack outputs
80
+ * @param {Object} discovered - Object to populate with discovered resources
81
+ */
82
+ _extractFromOutputs(outputs, discovered) {
83
+ const outputMap = outputs.reduce((acc, output) => {
84
+ acc[output.OutputKey] = output.OutputValue;
85
+ return acc;
86
+ }, {});
87
+
88
+ // VPC outputs
89
+ if (outputMap.VpcId) {
90
+ discovered.defaultVpcId = outputMap.VpcId; // VpcBuilder expects 'defaultVpcId'
91
+ }
92
+
93
+ if (outputMap.PrivateSubnetIds) {
94
+ // Handle comma-separated subnet IDs
95
+ discovered.privateSubnetIds = outputMap.PrivateSubnetIds.split(',').map(id => id.trim());
96
+ }
97
+
98
+ if (outputMap.PublicSubnetId) {
99
+ discovered.publicSubnetId = outputMap.PublicSubnetId;
100
+ }
101
+
102
+ if (outputMap.SecurityGroupId) {
103
+ discovered.securityGroupId = outputMap.SecurityGroupId;
104
+ }
105
+
106
+ // KMS outputs
107
+ if (outputMap.KMS_KEY_ARN) {
108
+ discovered.defaultKmsKeyId = outputMap.KMS_KEY_ARN;
109
+ }
110
+
111
+ // Database outputs (if exposed)
112
+ if (outputMap.DatabaseEndpoint) {
113
+ discovered.databaseEndpoint = outputMap.DatabaseEndpoint;
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Extract external resource references from stack resource properties
119
+ *
120
+ * When VPC/subnets/NAT are external, they're referenced in routing resources' properties.
121
+ * We query EC2 to get the actual VPC ID, NAT Gateway ID, and subnet IDs from the route table.
122
+ *
123
+ * @private
124
+ * @param {Array} resources - CloudFormation stack resources
125
+ * @param {Object} discovered - Object to populate with discovered resources
126
+ */
127
+ async _extractExternalReferencesFromStackResources(resources, discovered) {
128
+ if (!this.provider || !this.provider.getEC2Client) {
129
+ console.log(' ℹ Skipping external reference extraction (EC2 client not available)');
130
+ return;
131
+ }
132
+
133
+ try {
134
+ // If we found a route table in the stack, query EC2 for its details
135
+ // This gives us VPC ID, NAT Gateway ID, and subnet IDs
136
+ if (discovered.routeTableId) {
137
+ try {
138
+ console.log(` ℹ Querying route table ${discovered.routeTableId} for external references...`);
139
+ const { DescribeRouteTablesCommand } = require('@aws-sdk/client-ec2');
140
+ const ec2 = this.provider.getEC2Client();
141
+ const rtResponse = await ec2.send(new DescribeRouteTablesCommand({
142
+ RouteTableIds: [discovered.routeTableId]
143
+ }));
144
+
145
+ if (rtResponse.RouteTables && rtResponse.RouteTables.length > 0) {
146
+ const routeTable = rtResponse.RouteTables[0];
147
+
148
+ // Extract VPC ID
149
+ if (routeTable.VpcId && !discovered.defaultVpcId) {
150
+ discovered.defaultVpcId = routeTable.VpcId;
151
+ console.log(` ✓ Extracted VPC ID from route table: ${routeTable.VpcId}`);
152
+ }
153
+
154
+ // Extract NAT Gateway ID from routes
155
+ const natRoute = routeTable.Routes?.find(r => r.NatGatewayId);
156
+ if (natRoute && natRoute.NatGatewayId && !discovered.natGatewayId) {
157
+ discovered.natGatewayId = natRoute.NatGatewayId;
158
+ discovered.existingNatGatewayId = natRoute.NatGatewayId;
159
+ console.log(` ✓ Extracted NAT Gateway ID from routes: ${natRoute.NatGatewayId}`);
160
+ }
161
+
162
+ // Extract subnet IDs from route table associations
163
+ const associations = routeTable.Associations || [];
164
+ const subnetAssociations = associations.filter(a => a.SubnetId);
165
+
166
+
167
+ if (subnetAssociations.length >= 1 && !discovered.privateSubnetId1) {
168
+ discovered.privateSubnetId1 = subnetAssociations[0].SubnetId;
169
+ console.log(` ✓ Extracted private subnet 1 from associations: ${subnetAssociations[0].SubnetId}`);
170
+ }
171
+ if (subnetAssociations.length >= 2 && !discovered.privateSubnetId2) {
172
+ discovered.privateSubnetId2 = subnetAssociations[1].SubnetId;
173
+ console.log(` ✓ Extracted private subnet 2 from associations: ${subnetAssociations[1].SubnetId}`);
174
+ }
175
+
176
+ // Query for default security group in the VPC (matches canary behavior)
177
+ if (routeTable.VpcId && !discovered.defaultSecurityGroupId) {
178
+ try {
179
+ const { DescribeSecurityGroupsCommand } = require('@aws-sdk/client-ec2');
180
+ const sgResponse = await ec2.send(new DescribeSecurityGroupsCommand({
181
+ Filters: [
182
+ { Name: 'vpc-id', Values: [routeTable.VpcId] },
183
+ { Name: 'group-name', Values: ['default'] }
184
+ ]
185
+ }));
186
+
187
+ if (sgResponse.SecurityGroups && sgResponse.SecurityGroups.length > 0) {
188
+ discovered.defaultSecurityGroupId = sgResponse.SecurityGroups[0].GroupId;
189
+ console.log(` ✓ Extracted default security group: ${discovered.defaultSecurityGroupId}`);
190
+ }
191
+ } catch (error) {
192
+ console.warn(` ⚠️ Could not query default security group: ${error.message}`);
193
+ }
194
+ }
195
+ }
196
+ } catch (error) {
197
+ console.warn(` ⚠️ Could not query route table for external references: ${error.message}`);
198
+ }
199
+ }
200
+ } catch (error) {
201
+ console.warn(` ⚠️ Error extracting external references: ${error.message}`);
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Extract discovered resources from CloudFormation stack resources
207
+ *
208
+ * @private
209
+ * @param {Array} resources - CloudFormation stack resources
210
+ * @param {Object} discovered - Object to populate with discovered resources
211
+ */
212
+ async _extractFromResources(resources, discovered) {
213
+
214
+ // Initialize existingLogicalIds array if not present
215
+ if (!discovered.existingLogicalIds) {
216
+ discovered.existingLogicalIds = [];
217
+ }
218
+
219
+ for (const resource of resources) {
220
+ const { LogicalResourceId, PhysicalResourceId, ResourceType } = resource;
221
+
222
+ // Track Frigg-managed resources by logical ID
223
+ // Include VPC endpoints with legacy naming (VPCEndpointS3, VPCEndpointDynamoDB, etc.)
224
+ if (LogicalResourceId.startsWith('Frigg') ||
225
+ LogicalResourceId.includes('Migration') ||
226
+ LogicalResourceId.startsWith('VPCEndpoint')) {
227
+ discovered.existingLogicalIds.push(LogicalResourceId);
228
+ }
229
+
230
+
231
+ // Security Group - use to get VPC ID
232
+ if (LogicalResourceId === 'FriggLambdaSecurityGroup' && ResourceType === 'AWS::EC2::SecurityGroup') {
233
+ discovered.securityGroupId = PhysicalResourceId;
234
+ console.log(` ✓ Found security group in stack: ${PhysicalResourceId}`);
235
+
236
+ // Query security group to get VPC ID (required because SG resource doesn't include VPC ID)
237
+ if (this.provider && this.provider.getEC2Client && !discovered.defaultVpcId) {
238
+ try {
239
+ console.log(` Querying EC2 to get VPC ID from security group...`);
240
+ const { DescribeSecurityGroupsCommand } = require('@aws-sdk/client-ec2');
241
+ const ec2Client = this.provider.getEC2Client();
242
+ const sgDetails = await ec2Client.send(
243
+ new DescribeSecurityGroupsCommand({
244
+ GroupIds: [PhysicalResourceId]
245
+ })
246
+ );
247
+
248
+ if (sgDetails.SecurityGroups && sgDetails.SecurityGroups.length > 0) {
249
+ const vpcId = sgDetails.SecurityGroups[0].VpcId;
250
+ discovered.defaultVpcId = vpcId;
251
+ console.log(` ✓ Extracted VPC ID from security group: ${vpcId}`);
252
+
253
+ // Now query for the default security group in this VPC
254
+ if (!discovered.defaultSecurityGroupId) {
255
+ try {
256
+ console.log(` Querying for default security group in VPC...`);
257
+ const defaultSgResponse = await ec2Client.send(
258
+ new DescribeSecurityGroupsCommand({
259
+ Filters: [
260
+ { Name: 'vpc-id', Values: [vpcId] },
261
+ { Name: 'group-name', Values: ['default'] }
262
+ ]
263
+ })
264
+ );
265
+
266
+ if (defaultSgResponse.SecurityGroups && defaultSgResponse.SecurityGroups.length > 0) {
267
+ discovered.defaultSecurityGroupId = defaultSgResponse.SecurityGroups[0].GroupId;
268
+ console.log(` ✓ Discovered default security group: ${discovered.defaultSecurityGroupId}`);
269
+ }
270
+ } catch (error) {
271
+ console.warn(` ⚠️ Could not query default security group: ${error.message}`);
272
+ }
273
+ }
274
+ } else {
275
+ console.warn(` ⚠️ Security group query returned no results`);
276
+ }
277
+ } catch (error) {
278
+ console.warn(` ⚠️ Could not get VPC from security group: ${error.message}`);
279
+ }
280
+ }
281
+ }
282
+
283
+ // Aurora cluster - query AWS to get endpoint details
284
+ if (LogicalResourceId === 'FriggAuroraCluster' && ResourceType === 'AWS::RDS::DBCluster') {
285
+ discovered.auroraClusterId = PhysicalResourceId;
286
+ console.log(` ✓ Found Aurora cluster in stack: ${PhysicalResourceId}`);
287
+
288
+ // Query RDS to get cluster endpoint
289
+ if (this.provider && !discovered.auroraClusterEndpoint) {
290
+ try {
291
+ console.log(` Querying RDS to get Aurora endpoint...`);
292
+ const { DescribeDBClustersCommand } = require('@aws-sdk/client-rds');
293
+ const { RDSClient } = require('@aws-sdk/client-rds');
294
+
295
+ const rdsClient = new RDSClient({ region: this.provider.region });
296
+ const clusterDetails = await rdsClient.send(
297
+ new DescribeDBClustersCommand({
298
+ DBClusterIdentifier: PhysicalResourceId
299
+ })
300
+ );
301
+
302
+ if (clusterDetails.DBClusters && clusterDetails.DBClusters.length > 0) {
303
+ const cluster = clusterDetails.DBClusters[0];
304
+ discovered.auroraClusterEndpoint = cluster.Endpoint;
305
+ discovered.auroraClusterPort = cluster.Port;
306
+ discovered.auroraClusterIdentifier = cluster.DBClusterIdentifier;
307
+ console.log(` ✓ Extracted Aurora endpoint: ${cluster.Endpoint}:${cluster.Port}`);
308
+ } else {
309
+ console.warn(` ⚠️ RDS cluster query returned no results`);
310
+ }
311
+ } catch (error) {
312
+ console.warn(` ⚠️ Could not get endpoint from Aurora cluster: ${error.message}`);
313
+ }
314
+ }
315
+ }
316
+
317
+ // Migration status bucket
318
+ if (LogicalResourceId === 'FriggMigrationStatusBucket' && ResourceType === 'AWS::S3::Bucket') {
319
+ discovered.migrationStatusBucket = PhysicalResourceId;
320
+ }
321
+
322
+ // Migration queue
323
+ if (LogicalResourceId === 'DbMigrationQueue' && ResourceType === 'AWS::SQS::Queue') {
324
+ discovered.migrationQueueUrl = PhysicalResourceId;
325
+ }
326
+
327
+ // NAT Gateway
328
+ if (LogicalResourceId === 'FriggNatGateway' && ResourceType === 'AWS::EC2::NatGateway') {
329
+ discovered.natGatewayId = PhysicalResourceId;
330
+ }
331
+
332
+ // Route Table (Lambda route table for external VPC pattern)
333
+ if (LogicalResourceId === 'FriggLambdaRouteTable' && ResourceType === 'AWS::EC2::RouteTable') {
334
+ discovered.routeTableId = PhysicalResourceId;
335
+ discovered.privateRouteTableId = PhysicalResourceId;
336
+ console.log(` ✓ Found route table in stack: ${PhysicalResourceId}`);
337
+ }
338
+
339
+ // NAT Route (proves NAT configuration exists) - support both naming patterns
340
+ if ((LogicalResourceId === 'FriggNATRoute' || LogicalResourceId === 'FriggPrivateRoute') &&
341
+ ResourceType === 'AWS::EC2::Route') {
342
+ discovered.natRoute = PhysicalResourceId;
343
+ console.log(` ✓ Found NAT route in stack: ${LogicalResourceId}`);
344
+ }
345
+
346
+ // Route Table Associations (links subnets to route table)
347
+ if (LogicalResourceId.includes('RouteAssociation') &&
348
+ ResourceType === 'AWS::EC2::SubnetRouteTableAssociation') {
349
+ if (!discovered.routeTableAssociations) {
350
+ discovered.routeTableAssociations = [];
351
+ }
352
+ discovered.routeTableAssociations.push(PhysicalResourceId);
353
+ console.log(` ✓ Found route table association: ${LogicalResourceId}`);
354
+
355
+ // Store association ID to query later for subnet extraction (after loop)
356
+ if (this.provider && this.provider.getEC2Client &&
357
+ (LogicalResourceId === 'FriggSubnet1RouteAssociation' || LogicalResourceId === 'FriggPrivateSubnet1RouteTableAssociation')) {
358
+ discovered._subnet1AssociationId = PhysicalResourceId;
359
+ }
360
+ if (this.provider && this.provider.getEC2Client &&
361
+ (LogicalResourceId === 'FriggSubnet2RouteAssociation' || LogicalResourceId === 'FriggPrivateSubnet2RouteTableAssociation')) {
362
+ discovered._subnet2AssociationId = PhysicalResourceId;
363
+ }
364
+ }
365
+
366
+ // VPC - direct extraction (primary method)
367
+ if (LogicalResourceId === 'FriggVPC' && ResourceType === 'AWS::EC2::VPC') {
368
+ discovered.defaultVpcId = PhysicalResourceId;
369
+ console.log(` ✓ Found VPC in stack: ${PhysicalResourceId}`);
370
+ }
371
+
372
+ // KMS Key (alternative to output)
373
+ if (LogicalResourceId === 'FriggKMSKey' && ResourceType === 'AWS::KMS::Key') {
374
+ // Note: For KMS, we prefer the ARN from outputs, but this is a fallback
375
+ if (!discovered.defaultKmsKeyId) {
376
+ discovered.defaultKmsKeyId = PhysicalResourceId;
377
+ }
378
+ }
379
+
380
+ // KMS Key Alias - query to get the actual key ARN
381
+ if (LogicalResourceId === 'FriggKMSKeyAlias' && ResourceType === 'AWS::KMS::Alias') {
382
+ discovered.kmsKeyAlias = PhysicalResourceId;
383
+ console.log(` ✓ Found KMS key alias in stack: ${PhysicalResourceId}`);
384
+
385
+ // Query KMS to get the key ARN that this alias points to
386
+ // Always query even if key is already set, to ensure consistency
387
+ if (this.provider && this.provider.describeKmsKey) {
388
+ try {
389
+ console.log(` Querying KMS to get key ARN from alias...`);
390
+ const keyMetadata = await this.provider.describeKmsKey(PhysicalResourceId);
391
+
392
+ if (keyMetadata) {
393
+ discovered.defaultKmsKeyId = keyMetadata.Arn;
394
+ console.log(` ✓ Extracted KMS key ARN from alias: ${discovered.defaultKmsKeyId}`);
395
+ } else {
396
+ console.warn(` ⚠️ KMS key query returned no metadata`);
397
+ }
398
+ } catch (error) {
399
+ console.warn(` ⚠️ Could not get key ARN from alias: ${error.message}`);
400
+ }
401
+ }
402
+ }
403
+
404
+ // Subnets
405
+ if (LogicalResourceId === 'FriggPrivateSubnet1' && ResourceType === 'AWS::EC2::Subnet') {
406
+ discovered.privateSubnetId1 = PhysicalResourceId;
407
+ }
408
+ if (LogicalResourceId === 'FriggPrivateSubnet2' && ResourceType === 'AWS::EC2::Subnet') {
409
+ discovered.privateSubnetId2 = PhysicalResourceId;
410
+ }
411
+ if (LogicalResourceId === 'FriggPublicSubnet' && ResourceType === 'AWS::EC2::Subnet') {
412
+ discovered.publicSubnetId1 = PhysicalResourceId;
413
+ }
414
+ if (LogicalResourceId === 'FriggPublicSubnet2' && ResourceType === 'AWS::EC2::Subnet') {
415
+ discovered.publicSubnetId2 = PhysicalResourceId;
416
+ }
417
+
418
+ // Route Tables
419
+ if (LogicalResourceId === 'FriggLambdaRouteTable' && ResourceType === 'AWS::EC2::RouteTable') {
420
+ discovered.routeTableId = PhysicalResourceId;
421
+ }
422
+
423
+ // VPC Endpoint Security Group
424
+ if (LogicalResourceId === 'FriggVPCEndpointSecurityGroup' && ResourceType === 'AWS::EC2::SecurityGroup') {
425
+ discovered.vpcEndpointSecurityGroupId = PhysicalResourceId;
426
+ console.log(` ✓ Found VPC endpoint security group in stack: ${PhysicalResourceId}`);
427
+ }
428
+
429
+ // Lambda Security Group (if created in stack)
430
+ if (LogicalResourceId === 'FriggLambdaSecurityGroup' && ResourceType === 'AWS::EC2::SecurityGroup') {
431
+ discovered.lambdaSecurityGroupId = PhysicalResourceId;
432
+ // DO NOT overwrite defaultSecurityGroupId - that should only be the VPC's default SG
433
+ console.log(` ✓ Found Lambda security group in stack: ${PhysicalResourceId}`);
434
+ }
435
+
436
+ // VPC Endpoints - support both old and new naming conventions
437
+ // Initialize vpcEndpoints object for structured access
438
+ if (!discovered.vpcEndpoints) {
439
+ discovered.vpcEndpoints = {};
440
+ }
441
+
442
+ // S3 Endpoint (both naming patterns)
443
+ if ((LogicalResourceId === 'FriggS3VPCEndpoint' || LogicalResourceId === 'VPCEndpointS3') &&
444
+ ResourceType === 'AWS::EC2::VPCEndpoint') {
445
+ discovered.s3VpcEndpointId = PhysicalResourceId;
446
+ discovered.vpcEndpoints.s3 = PhysicalResourceId;
447
+ console.log(` ✓ Found S3 VPC endpoint in stack: ${PhysicalResourceId}`);
448
+ }
449
+
450
+ // DynamoDB Endpoint (both naming patterns)
451
+ if ((LogicalResourceId === 'FriggDynamoDBVPCEndpoint' || LogicalResourceId === 'VPCEndpointDynamoDB') &&
452
+ ResourceType === 'AWS::EC2::VPCEndpoint') {
453
+ discovered.dynamodbVpcEndpointId = PhysicalResourceId; // Note: all lowercase for consistency
454
+ discovered.vpcEndpoints.dynamodb = PhysicalResourceId;
455
+ console.log(` ✓ Found DynamoDB VPC endpoint in stack: ${PhysicalResourceId}`);
456
+ }
457
+
458
+ // KMS Endpoint (both naming patterns)
459
+ if ((LogicalResourceId === 'FriggKMSVPCEndpoint' || LogicalResourceId === 'VPCEndpointKMS') &&
460
+ ResourceType === 'AWS::EC2::VPCEndpoint') {
461
+ discovered.kmsVpcEndpointId = PhysicalResourceId;
462
+ discovered.vpcEndpoints.kms = PhysicalResourceId;
463
+ console.log(` ✓ Found KMS VPC endpoint in stack: ${PhysicalResourceId}`);
464
+ }
465
+
466
+ // Secrets Manager Endpoint
467
+ if (LogicalResourceId === 'FriggSecretsManagerVPCEndpoint' && ResourceType === 'AWS::EC2::VPCEndpoint') {
468
+ discovered.secretsManagerVpcEndpointId = PhysicalResourceId;
469
+ discovered.vpcEndpoints.secretsManager = PhysicalResourceId;
470
+ }
471
+
472
+ // SQS Endpoint
473
+ if (LogicalResourceId === 'FriggSQSVPCEndpoint' && ResourceType === 'AWS::EC2::VPCEndpoint') {
474
+ discovered.sqsVpcEndpointId = PhysicalResourceId;
475
+ discovered.vpcEndpoints.sqs = PhysicalResourceId;
476
+ }
477
+ }
478
+
479
+ // Extract VPC ID and other external references from routing resource properties
480
+ // This handles the pattern where VPC is external but routing is in the stack
481
+ await this._extractExternalReferencesFromStackResources(resources, discovered);
482
+
483
+ // If we have a VPC ID but no subnet IDs, query EC2 for Frigg-managed subnets
484
+ if (discovered.defaultVpcId && this.provider &&
485
+ !discovered.privateSubnetId1 && !discovered.publicSubnetId1) {
486
+ try {
487
+ console.log(' Querying EC2 for Frigg-managed subnets...');
488
+ const { DescribeSubnetsCommand } = require('@aws-sdk/client-ec2');
489
+ const subnetResponse = await this.provider.getEC2Client().send(
490
+ new DescribeSubnetsCommand({
491
+ Filters: [
492
+ { Name: 'vpc-id', Values: [discovered.defaultVpcId] },
493
+ { Name: 'tag:ManagedBy', Values: ['Frigg'] },
494
+ ],
495
+ })
496
+ );
497
+
498
+ if (subnetResponse.Subnets && subnetResponse.Subnets.length > 0) {
499
+ // Extract subnet IDs by logical ID from tags
500
+ const subnets = subnetResponse.Subnets.map(subnet => ({
501
+ subnetId: subnet.SubnetId,
502
+ logicalId: subnet.Tags?.find(t => t.Key === 'aws:cloudformation:logical-id')?.Value,
503
+ isPublic: subnet.MapPublicIpOnLaunch,
504
+ }));
505
+
506
+ // Find private subnets
507
+ const privateSubnets = subnets.filter(s => !s.isPublic).sort((a, b) =>
508
+ a.logicalId?.localeCompare(b.logicalId) || 0
509
+ );
510
+ if (privateSubnets.length >= 1) {
511
+ discovered.privateSubnetId1 = privateSubnets[0].subnetId;
512
+ }
513
+ if (privateSubnets.length >= 2) {
514
+ discovered.privateSubnetId2 = privateSubnets[1].subnetId;
515
+ }
516
+
517
+ // Find public subnets
518
+ const publicSubnets = subnets.filter(s => s.isPublic).sort((a, b) =>
519
+ a.logicalId?.localeCompare(b.logicalId) || 0
520
+ );
521
+ if (publicSubnets.length >= 1) {
522
+ discovered.publicSubnetId1 = publicSubnets[0].subnetId;
523
+ }
524
+ if (publicSubnets.length >= 2) {
525
+ discovered.publicSubnetId2 = publicSubnets[1].subnetId;
526
+ }
527
+
528
+ console.log(` ✓ Found ${subnets.length} Frigg-managed subnets via EC2 query`);
529
+ }
530
+ } catch (error) {
531
+ console.warn(` ⚠️ Could not query EC2 for subnets: ${error.message}`);
532
+ }
533
+ }
534
+
535
+ // If we have VPC and route table but no subnets, query VPC for all subnets and filter by route table
536
+ // This approach queries by VPC ID (vpc-id filter) and route table ID (RouteTableIds parameter)
537
+ // Handles edge case where route table Associations array is empty in DescribeRouteTables response
538
+ if (discovered.defaultVpcId && !discovered.privateSubnetId1 &&
539
+ discovered.routeTableId && this.provider && this.provider.getEC2Client) {
540
+ try {
541
+ console.log(` Querying ALL subnets in VPC ${discovered.defaultVpcId}...`);
542
+ const { DescribeSubnetsCommand } = require('@aws-sdk/client-ec2');
543
+ const ec2 = this.provider.getEC2Client();
544
+
545
+ const subnetsResponse = await ec2.send(new DescribeSubnetsCommand({
546
+ Filters: [{ Name: 'vpc-id', Values: [discovered.defaultVpcId] }]
547
+ }));
548
+
549
+ console.log(` Found ${subnetsResponse.Subnets?.length || 0} total subnets in VPC`);
550
+
551
+ if (subnetsResponse.Subnets && subnetsResponse.Subnets.length > 0) {
552
+ // Get route table to find associated subnets
553
+ const { DescribeRouteTablesCommand } = require('@aws-sdk/client-ec2');
554
+ const rtResponse = await ec2.send(new DescribeRouteTablesCommand({
555
+ RouteTableIds: [discovered.routeTableId]
556
+ }));
557
+
558
+ if (rtResponse.RouteTables && rtResponse.RouteTables[0]) {
559
+ const associations = rtResponse.RouteTables[0].Associations || [];
560
+ const associatedSubnetIds = associations
561
+ .filter(a => a.SubnetId)
562
+ .map(a => a.SubnetId);
563
+
564
+ console.log(` Route table has ${associatedSubnetIds.length} associated subnets: ${associatedSubnetIds.join(', ')}`);
565
+
566
+ // Use the associated subnets if available
567
+ if (associatedSubnetIds.length >= 2) {
568
+ discovered.privateSubnetId1 = associatedSubnetIds[0];
569
+ discovered.privateSubnetId2 = associatedSubnetIds[1];
570
+ console.log(` ✓ Extracted subnets from route table associations: ${discovered.privateSubnetId1}, ${discovered.privateSubnetId2}`);
571
+ } else if (associatedSubnetIds.length === 1) {
572
+ // Only 1 associated subnet, use another subnet from VPC as backup
573
+ discovered.privateSubnetId1 = associatedSubnetIds[0];
574
+ discovered.privateSubnetId2 = subnetsResponse.Subnets.find(s => s.SubnetId !== associatedSubnetIds[0])?.SubnetId;
575
+ console.log(` ✓ Extracted subnets (1 from route table, 1 fallback): ${discovered.privateSubnetId1}, ${discovered.privateSubnetId2}`);
576
+ } else if (subnetsResponse.Subnets.length >= 2) {
577
+ // Edge case: route table Associations array is empty even when queried by ID
578
+ // This can happen when associations exist in CloudFormation but AWS API doesn't return them
579
+ // Fallback: Use first 2 subnets from VPC (all subnets in same VPC should work)
580
+ discovered.privateSubnetId1 = subnetsResponse.Subnets[0].SubnetId;
581
+ discovered.privateSubnetId2 = subnetsResponse.Subnets[1].SubnetId;
582
+ console.log(` ✓ Using first 2 subnets from VPC (route table Associations empty): ${discovered.privateSubnetId1}, ${discovered.privateSubnetId2}`);
583
+ }
584
+ }
585
+ }
586
+ } catch (error) {
587
+ console.warn(` ⚠️ Could not query subnets from VPC: ${error.message}`);
588
+ }
589
+ }
590
+
591
+ // FALLBACK: Extract subnet IDs from route table associations (if VPC query didn't work)
592
+ if (!discovered.privateSubnetId1 && discovered._subnet1AssociationId && this.provider && this.provider.getEC2Client) {
593
+ try {
594
+ console.log(` Querying EC2 for subnet from association ${discovered._subnet1AssociationId}...`);
595
+ const { DescribeRouteTablesCommand } = require('@aws-sdk/client-ec2');
596
+ const ec2 = this.provider.getEC2Client();
597
+
598
+ // Query route table by association ID to get subnet
599
+ const rtResponse = await ec2.send(new DescribeRouteTablesCommand({
600
+ Filters: [
601
+ { Name: 'association.route-table-association-id', Values: [discovered._subnet1AssociationId] }
602
+ ]
603
+ }));
604
+
605
+ if (rtResponse.RouteTables && rtResponse.RouteTables[0]) {
606
+ const assoc = rtResponse.RouteTables[0].Associations.find(a =>
607
+ a.RouteTableAssociationId === discovered._subnet1AssociationId
608
+ );
609
+ if (assoc && assoc.SubnetId) {
610
+ discovered.privateSubnetId1 = assoc.SubnetId;
611
+ console.log(` ✓ Extracted private subnet 1 from association query: ${assoc.SubnetId}`);
612
+ }
613
+ }
614
+ } catch (error) {
615
+ console.warn(` ⚠️ Could not query subnet from association: ${error.message}`);
616
+ }
617
+ }
618
+
619
+ if (!discovered.privateSubnetId2 && discovered._subnet2AssociationId && this.provider && this.provider.getEC2Client) {
620
+ try {
621
+ const { DescribeRouteTablesCommand } = require('@aws-sdk/client-ec2');
622
+ const ec2 = this.provider.getEC2Client();
623
+
624
+ const rtResponse = await ec2.send(new DescribeRouteTablesCommand({
625
+ Filters: [
626
+ { Name: 'association.route-table-association-id', Values: [discovered._subnet2AssociationId] }
627
+ ]
628
+ }));
629
+
630
+ if (rtResponse.RouteTables && rtResponse.RouteTables[0]) {
631
+ const assoc = rtResponse.RouteTables[0].Associations.find(a =>
632
+ a.RouteTableAssociationId === discovered._subnet2AssociationId
633
+ );
634
+ if (assoc && assoc.SubnetId) {
635
+ discovered.privateSubnetId2 = assoc.SubnetId;
636
+ console.log(` ✓ Extracted private subnet 2 from association query: ${assoc.SubnetId}`);
637
+ }
638
+ }
639
+ } catch (error) {
640
+ console.warn(` ⚠️ Could not query subnet from association: ${error.message}`);
641
+ }
642
+ }
643
+
644
+ // Clean up temporary association IDs
645
+ delete discovered._subnet1AssociationId;
646
+ delete discovered._subnet2AssociationId;
647
+
648
+ // Check for KMS key alias via AWS API if not found in stack resources
649
+ // This handles cases where the alias was created outside CloudFormation
650
+ if (!discovered.defaultKmsKeyId && !discovered.kmsKeyAlias &&
651
+ this.provider && this.provider.describeKmsKey && this.serviceName && this.stage) {
652
+ try {
653
+ const aliasName = `alias/${this.serviceName}-${this.stage}-frigg-kms`;
654
+ console.log(` Querying KMS for alias: ${aliasName}...`);
655
+
656
+ const keyMetadata = await this.provider.describeKmsKey(aliasName);
657
+
658
+ if (keyMetadata) {
659
+ discovered.defaultKmsKeyId = keyMetadata.Arn;
660
+ discovered.kmsKeyAlias = aliasName;
661
+ console.log(` ✓ Found KMS key via alias query: ${discovered.defaultKmsKeyId}`);
662
+ }
663
+ } catch (error) {
664
+ // Alias not found - this is expected if no KMS key exists yet
665
+ console.log(` ℹ No KMS key alias found via AWS API`);
666
+ }
667
+ }
668
+ }
669
+ }
670
+
671
+ module.exports = { CloudFormationDiscovery };
672
+