@friggframework/devtools 2.0.0-next.41 → 2.0.0-next.42

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 (32) hide show
  1. package/frigg-cli/__tests__/unit/commands/build.test.js +173 -405
  2. package/frigg-cli/__tests__/unit/commands/db-setup.test.js +548 -0
  3. package/frigg-cli/__tests__/unit/commands/install.test.js +359 -377
  4. package/frigg-cli/__tests__/unit/commands/ui.test.js +266 -512
  5. package/frigg-cli/__tests__/unit/utils/database-validator.test.js +366 -0
  6. package/frigg-cli/__tests__/unit/utils/error-messages.test.js +304 -0
  7. package/frigg-cli/__tests__/unit/utils/prisma-runner.test.js +486 -0
  8. package/frigg-cli/__tests__/utils/prisma-mock.js +194 -0
  9. package/frigg-cli/__tests__/utils/test-setup.js +22 -21
  10. package/frigg-cli/db-setup-command/index.js +186 -0
  11. package/frigg-cli/generate-command/__tests__/generate-command.test.js +151 -162
  12. package/frigg-cli/generate-iam-command.js +7 -4
  13. package/frigg-cli/index.js +9 -1
  14. package/frigg-cli/install-command/index.js +1 -1
  15. package/frigg-cli/jest.config.js +124 -0
  16. package/frigg-cli/package.json +4 -1
  17. package/frigg-cli/start-command/index.js +95 -2
  18. package/frigg-cli/start-command/start-command.test.js +161 -19
  19. package/frigg-cli/utils/database-validator.js +158 -0
  20. package/frigg-cli/utils/error-messages.js +257 -0
  21. package/frigg-cli/utils/prisma-runner.js +280 -0
  22. package/infrastructure/CLAUDE.md +481 -0
  23. package/infrastructure/IAM-POLICY-TEMPLATES.md +30 -12
  24. package/infrastructure/create-frigg-infrastructure.js +0 -2
  25. package/infrastructure/iam-generator.js +18 -38
  26. package/infrastructure/iam-generator.test.js +40 -8
  27. package/package.json +6 -6
  28. package/test/index.js +2 -4
  29. package/test/mock-integration.js +4 -14
  30. package/frigg-cli/__tests__/jest.config.js +0 -102
  31. package/frigg-cli/__tests__/utils/command-tester.js +0 -170
  32. package/test/auther-definition-tester.js +0 -125
@@ -0,0 +1,481 @@
1
+ # CLAUDE.md - Frigg Infrastructure as Code
2
+
3
+ This file provides guidance to Claude Code when working with the Frigg Framework's infrastructure system in `packages/devtools/infrastructure/`.
4
+
5
+ ## Critical Context (Read First)
6
+
7
+ - **Package Purpose**: Infrastructure-as-code templates and AWS resource discovery for Frigg serverless applications
8
+ - **Core Architecture**: AWS-native infrastructure with CloudFormation, serverless framework integration, automatic resource discovery
9
+ - **Key Components**: Serverless template generator, AWS resource discovery, IAM policy generator, deployment automation
10
+ - **Security Model**: VPC deployment, KMS encryption, IAM least-privilege, SSM Parameter Store integration
11
+ - **Deployment Phases**: Phase 1-2 (basic), Phase 3 (enhanced monitoring, CDN, CI/CD pipelines)
12
+ - **DO NOT**: Hardcode AWS resource IDs, bypass security configurations, create infrastructure outside CloudFormation
13
+
14
+ ## Infrastructure System Architecture
15
+
16
+ ### Core Infrastructure Generator (`serverless-template.js:1-50940`)
17
+
18
+ **Purpose**: Generates complete serverless.yml configurations with AWS resource discovery integration
19
+
20
+ **Key Responsibilities**:
21
+ - **Template Generation**: Creates serverless framework configuration from app definition
22
+ - **Resource Discovery Integration**: Automatically discovers and configures AWS resources
23
+ - **Environment Variable Management**: Handles reserved AWS variables and user-defined variables
24
+ - **Module Discovery**: Finds and integrates Node.js modules and dependencies
25
+ - **VPC Configuration**: Configures Lambda functions for private subnet deployment
26
+ - **KMS Integration**: Sets up field-level encryption with customer-managed keys
27
+
28
+ **App Definition Structure**:
29
+ ```javascript
30
+ const AppDefinition = {
31
+ name: 'my-frigg-app',
32
+ provider: 'aws',
33
+
34
+ // VPC Configuration
35
+ vpc: {
36
+ enable: true, // Enable VPC deployment
37
+ createNew: false, // Use existing VPC (default)
38
+ securityGroupIds: [...], // Optional custom security groups
39
+ subnetIds: [...], // Optional custom subnets
40
+ enableVPCEndpoints: true // Create VPC endpoints for AWS services
41
+ },
42
+
43
+ // Encryption Configuration
44
+ encryption: {
45
+ useDefaultKMSForFieldLevelEncryption: true
46
+ },
47
+
48
+ // SSM Parameter Store
49
+ ssm: {
50
+ enable: true
51
+ },
52
+
53
+ // Environment Variables (serverless-template.js:24-79)
54
+ environment: {
55
+ MY_VAR: true, // Creates ${env:MY_VAR, ''} reference
56
+ AWS_REGION: true // Skipped - reserved AWS variable
57
+ },
58
+
59
+ // WebSocket Support (Phase 3)
60
+ websockets: {
61
+ enable: true
62
+ },
63
+
64
+ // Integration Definitions
65
+ integrations: [
66
+ { Definition: { name: 'hubspot' } },
67
+ { Definition: { name: 'salesforce' } }
68
+ ]
69
+ };
70
+ ```
71
+
72
+ ### AWS Resource Discovery (`aws-discovery.js:27-550`)
73
+
74
+ **Purpose**: Automatically discovers existing AWS resources for serverless deployment
75
+
76
+ **Discovery Capabilities**:
77
+ - **VPC Discovery**: Find default VPC and associated resources
78
+ - **Subnet Discovery**: Identify private subnets for Lambda deployment
79
+ - **Security Group Discovery**: Locate default security groups
80
+ - **KMS Key Discovery**: Find customer-managed KMS keys for encryption
81
+ - **Route Table Discovery**: Map route tables for VPC endpoints
82
+ - **Account Information**: Get AWS account ID and region details
83
+
84
+ **Core Discovery Methods**:
85
+ ```javascript
86
+ const discovery = new AWSDiscovery('us-east-1');
87
+
88
+ // VPC and Networking
89
+ const vpcId = await discovery.findDefaultVpc();
90
+ const subnets = await discovery.findPrivateSubnets(vpcId);
91
+ const securityGroups = await discovery.findDefaultSecurityGroup(vpcId);
92
+ const routeTables = await discovery.findRouteTables(vpcId);
93
+
94
+ // Encryption
95
+ const kmsKey = await discovery.findDefaultKMSKey();
96
+
97
+ // Account Information
98
+ const accountId = await discovery.getAccountId();
99
+ ```
100
+
101
+ **Resource Discovery Triggers** (`serverless-template.js:10-17`):
102
+ ```javascript
103
+ const shouldRunDiscovery = (AppDefinition) => {
104
+ return (
105
+ AppDefinition.vpc?.enable === true || // VPC deployment
106
+ AppDefinition.encryption?.useDefaultKMSForFieldLevelEncryption === true || // KMS encryption
107
+ AppDefinition.ssm?.enable === true // SSM parameters
108
+ );
109
+ };
110
+ ```
111
+
112
+ ### IAM Policy Generator (`iam-generator.js:12-885`)
113
+
114
+ **Purpose**: Generate least-privilege IAM policies based on app definition features
115
+
116
+ **Policy Generation Modes**:
117
+ - **Auto Mode**: Detects features from app definition and generates appropriate policies
118
+ - **Basic Mode**: Minimal permissions for simple deployments
119
+ - **Full Mode**: Complete permissions for all features
120
+
121
+ **Feature-Based Policy Generation**:
122
+ ```javascript
123
+ const features = {
124
+ vpc: appDefinition.vpc?.enable === true, // EC2 VPC permissions
125
+ kms: appDefinition.encryption?.useDefaultKMSForFieldLevelEncryption === true, // KMS permissions
126
+ ssm: appDefinition.ssm?.enable === true, // SSM Parameter Store permissions
127
+ websockets: appDefinition.websockets?.enable === true // API Gateway WebSocket permissions
128
+ };
129
+ ```
130
+
131
+ **Generated IAM Resources**:
132
+ - **Deployment User**: IAM user for CI/CD deployments
133
+ - **Lambda Execution Roles**: Roles for Lambda function execution
134
+ - **CloudFormation Roles**: Roles for infrastructure stack management
135
+ - **Service-Specific Policies**: Tailored policies for each AWS service used
136
+
137
+ ### Build-Time Discovery (`build-time-discovery.js:1-300`)
138
+
139
+ **Purpose**: Integration between AWS discovery and serverless deployment process
140
+
141
+ **Integration Points**:
142
+ - **Pre-Build Hook**: Runs discovery before serverless deployment
143
+ - **Environment Injection**: Sets discovered resources as environment variables
144
+ - **Template Variables**: Replaces placeholders in serverless templates
145
+ - **Error Handling**: Graceful fallbacks when discovery fails
146
+
147
+ **Environment Variable Injection**:
148
+ ```bash
149
+ # Automatically set by build-time discovery
150
+ AWS_DISCOVERY_VPC_ID=vpc-12345678
151
+ AWS_DISCOVERY_SECURITY_GROUP_ID=sg-12345678
152
+ AWS_DISCOVERY_SUBNET_ID_1=subnet-12345678
153
+ AWS_DISCOVERY_SUBNET_ID_2=subnet-87654321
154
+ AWS_DISCOVERY_ROUTE_TABLE_ID=rtb-12345678
155
+ AWS_DISCOVERY_KMS_KEY_ID=arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012
156
+ ```
157
+
158
+ ## Phase 3 Infrastructure Components
159
+
160
+ ### Enhanced Monitoring (`cloudformation/monitoring-infrastructure.yaml`)
161
+
162
+ **Advanced CloudWatch Configuration**:
163
+ - **Custom Dashboards**: Multi-service monitoring dashboards
164
+ - **Composite Alarms**: System health monitoring with multiple metrics
165
+ - **Code Generation Monitoring**: AI/ML service performance tracking
166
+ - **UI Distribution Monitoring**: CDN and S3 performance metrics
167
+ - **Cross-Stack Dependencies**: Monitoring across infrastructure stacks
168
+
169
+ ### CDN Infrastructure (`cloudformation/cdn-infrastructure.yaml`)
170
+
171
+ **CloudFront Distribution System**:
172
+ - **S3 Origin**: Multi-framework UI package storage
173
+ - **Custom Domains**: Route 53 integration for branded URLs
174
+ - **Lambda@Edge**: Package deployment automation
175
+ - **API Gateway Integration**: RESTful package management API
176
+ - **Cache Optimization**: Intelligent caching for UI assets
177
+
178
+ ### Code Generation Infrastructure (`cloudformation/codegen-infrastructure.yaml`)
179
+
180
+ **AI/ML-Powered Code Generation Platform**:
181
+ - **SQS Queue System**: Asynchronous generation request processing
182
+ - **Lambda Functions**: AI/ML integration for code generation
183
+ - **DynamoDB Tracking**: Generation request and status tracking
184
+ - **S3 Template Storage**: Version-controlled template repository
185
+ - **ElastiCache**: Template and generated code caching
186
+
187
+ ### Advanced Alerting (`cloudformation/alerting-infrastructure.yaml`)
188
+
189
+ **Multi-Channel Alerting System**:
190
+ - **SNS Topics**: Severity-based alert routing (critical, warning, info)
191
+ - **Lambda Processing**: Alert enrichment and routing logic
192
+ - **PagerDuty Integration**: On-call escalation for critical issues
193
+ - **Slack Integration**: Team collaboration and alert management
194
+ - **Composite Health Checks**: System-wide health monitoring
195
+
196
+ ### CI/CD Pipeline (`cloudformation/deployment-pipeline.yaml`)
197
+
198
+ **Automated Deployment Pipeline**:
199
+ - **CodePipeline**: Multi-stage deployment workflow
200
+ - **CodeBuild Projects**: Separate build processes for backend and UI
201
+ - **GitHub Integration**: Source code management and webhooks
202
+ - **Multi-Environment**: Development, staging, production environments
203
+ - **Approval Gates**: Manual approval for production deployments
204
+
205
+ ## Infrastructure Configuration Patterns
206
+
207
+ ### VPC-Enabled Deployment
208
+ ```javascript
209
+ const vpcConfig = {
210
+ vpc: {
211
+ enable: true,
212
+ createNew: false, // Use existing default VPC
213
+ enableVPCEndpoints: true // Create endpoints for AWS services
214
+ }
215
+ };
216
+
217
+ // Results in Lambda functions deployed in private subnets
218
+ // with VPC endpoints for S3, DynamoDB, SQS, SNS, etc.
219
+ ```
220
+
221
+ ### KMS Encryption Setup
222
+ ```javascript
223
+ const encryptionConfig = {
224
+ encryption: {
225
+ useDefaultKMSForFieldLevelEncryption: true
226
+ }
227
+ };
228
+
229
+ // Automatically discovers customer-managed KMS key
230
+ // Sets up Lambda environment variables for encryption
231
+ // Configures IAM permissions for KMS operations
232
+ ```
233
+
234
+ ### SSM Parameter Store Integration
235
+ ```javascript
236
+ const ssmConfig = {
237
+ ssm: {
238
+ enable: true
239
+ }
240
+ };
241
+
242
+ // Creates SSM parameters for configuration management
243
+ // Sets up IAM permissions for parameter access
244
+ // Enables secure configuration without hardcoding
245
+ ```
246
+
247
+ ### WebSocket Configuration (Phase 3)
248
+ ```javascript
249
+ const websocketConfig = {
250
+ websockets: {
251
+ enable: true
252
+ }
253
+ };
254
+
255
+ // Creates API Gateway WebSocket API
256
+ // Sets up connection management Lambda functions
257
+ // Configures route handlers for WebSocket messages
258
+ ```
259
+
260
+ ## Security Architecture
261
+
262
+ ### IAM Permission Structure
263
+
264
+ **Lambda Execution Permissions**:
265
+ - **VPC Access**: ENI creation/deletion for VPC deployment
266
+ - **Encryption**: KMS key usage for field-level encryption
267
+ - **Storage**: S3 bucket operations for file handling
268
+ - **Queues**: SQS send/receive for background job processing
269
+ - **Parameters**: SSM parameter read access for configuration
270
+ - **Logging**: CloudWatch Logs creation and writing
271
+
272
+ **Deployment Permissions**:
273
+ - **CloudFormation**: Stack create/update/delete operations
274
+ - **IAM**: Role and policy management (limited scope)
275
+ - **Lambda**: Function management and configuration
276
+ - **API Gateway**: API creation and configuration
277
+ - **Resource Discovery**: Read-only access for resource discovery
278
+
279
+ ### Network Security Model
280
+
281
+ **Private Subnet Deployment**:
282
+ ```javascript
283
+ // Lambda functions deployed in private subnets
284
+ // No direct internet access - uses NAT Gateway or VPC endpoints
285
+ {
286
+ vpc: { enable: true },
287
+ // Automatically configures:
288
+ // - Private subnet placement
289
+ // - Security group associations
290
+ // - VPC endpoints for AWS services
291
+ }
292
+ ```
293
+
294
+ **VPC Endpoint Strategy**:
295
+ - **S3 Gateway Endpoint**: Cost-effective S3 access
296
+ - **Interface Endpoints**: SQS, SNS, DynamoDB, KMS, SSM
297
+ - **DNS Resolution**: Private DNS for AWS services
298
+ - **Security Groups**: Restricted access to required ports/protocols
299
+
300
+ ### Encryption Implementation
301
+
302
+ **Field-Level Encryption**:
303
+ ```javascript
304
+ // Automatic KMS integration
305
+ {
306
+ encryption: { useDefaultKMSForFieldLevelEncryption: true },
307
+ // Results in:
308
+ // - KMS key discovery and configuration
309
+ // - Lambda environment variables for encryption
310
+ // - IAM permissions for KMS operations
311
+ // - Automatic encrypt/decrypt in data layer
312
+ }
313
+ ```
314
+
315
+ **Data at Rest**:
316
+ - **S3 Buckets**: SSE-S3 or SSE-KMS encryption
317
+ - **DynamoDB**: Encryption at rest with KMS
318
+ - **SQS Queues**: Server-side encryption
319
+ - **Lambda Environment**: Encrypted environment variables
320
+
321
+ ## Deployment Automation
322
+
323
+ ### Infrastructure Deployment Process
324
+
325
+ **Discovery and Template Generation**:
326
+ ```bash
327
+ # 1. AWS resource discovery
328
+ node aws-discovery.js --region us-east-1
329
+
330
+ # 2. Serverless template generation
331
+ node serverless-template.js --app-definition ./app-definition.js
332
+
333
+ # 3. IAM policy generation
334
+ node iam-generator.js --mode auto --app-definition ./app-definition.js
335
+
336
+ # 4. CloudFormation deployment
337
+ serverless deploy --stage production
338
+ ```
339
+
340
+ **Environment Variable Management**:
341
+ ```javascript
342
+ // Reserved AWS variables automatically skipped
343
+ const reservedVars = [
344
+ '_HANDLER', '_X_AMZN_TRACE_ID', 'AWS_DEFAULT_REGION',
345
+ 'AWS_EXECUTION_ENV', 'AWS_REGION', 'AWS_LAMBDA_FUNCTION_NAME',
346
+ 'AWS_LAMBDA_FUNCTION_MEMORY_SIZE', 'AWS_LAMBDA_FUNCTION_VERSION',
347
+ 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN'
348
+ ];
349
+
350
+ // User variables converted to serverless references
351
+ { MY_VAR: true } → { MY_VAR: "${env:MY_VAR, ''}" }
352
+ ```
353
+
354
+ ### Testing Strategy
355
+
356
+ **Infrastructure Validation Tests** (`integration.test.js:1-450`):
357
+ - **Template Generation**: Validate generated serverless.yml syntax
358
+ - **Resource Discovery**: Test AWS API integration with mock data
359
+ - **IAM Policy**: Validate policy syntax and permissions
360
+ - **Cross-Stack Dependencies**: Test Phase 3 stack interactions
361
+ - **CloudFormation Limits**: Validate template size and resource counts
362
+
363
+ **Mock Data Patterns**:
364
+ ```javascript
365
+ const mockAWSResources = {
366
+ defaultVpcId: 'vpc-12345678',
367
+ defaultSecurityGroupId: 'sg-12345678',
368
+ privateSubnetId1: 'subnet-private-1',
369
+ privateSubnetId2: 'subnet-private-2',
370
+ defaultKmsKeyId: 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012',
371
+ routeTableId: 'rtb-12345678'
372
+ };
373
+ ```
374
+
375
+ ## Performance Optimization
376
+
377
+ ### Lambda Cold Start Optimization
378
+ - **Provisioned Concurrency**: Configure for critical functions
379
+ - **VPC Optimization**: Use VPC endpoints to reduce ENI creation time
380
+ - **Layer Strategy**: Share common dependencies via Lambda layers
381
+ - **Function Sizing**: Right-size memory allocation for performance/cost
382
+
383
+ ### Cost Optimization Strategies
384
+ - **VPC Endpoints**: Reduce NAT Gateway data transfer costs
385
+ - **S3 Intelligent Tiering**: Automatic storage class optimization
386
+ - **CloudWatch Log Retention**: Configure appropriate retention periods
387
+ - **Reserved Capacity**: Use reserved concurrency for predictable workloads
388
+
389
+ ### Infrastructure Scaling
390
+ - **Auto Scaling**: Configure Lambda concurrency limits
391
+ - **DynamoDB**: On-demand billing for variable workloads
392
+ - **SQS**: Use appropriate queue types (standard vs FIFO)
393
+ - **CloudFront**: Global edge locations for UI distribution
394
+
395
+ ## Anti-Patterns to Avoid
396
+
397
+ ❌ **Don't hardcode AWS resource IDs** - use discovery system for dynamic configuration
398
+ ❌ **Don't bypass VPC security** - always deploy Lambda functions in private subnets when VPC enabled
399
+ ❌ **Don't create infrastructure manually** - use CloudFormation templates for consistency
400
+ ❌ **Don't ignore IAM least privilege** - use generated policies based on actual feature usage
401
+ ❌ **Don't skip resource discovery** - discovery ensures compatibility with existing infrastructure
402
+ ❌ **Don't expose secrets in templates** - use SSM Parameter Store or Secrets Manager
403
+ ❌ **Don't ignore CloudFormation limits** - validate template size and resource counts
404
+
405
+ ## Troubleshooting Common Issues
406
+
407
+ ### AWS Discovery Failures
408
+ ```bash
409
+ # Check AWS credentials and region
410
+ aws sts get-caller-identity
411
+ echo $AWS_REGION
412
+
413
+ # Test specific discovery functions
414
+ node -e "
415
+ const { AWSDiscovery } = require('./aws-discovery');
416
+ const discovery = new AWSDiscovery('us-east-1');
417
+ discovery.findDefaultVpc().then(console.log).catch(console.error);
418
+ "
419
+ ```
420
+
421
+ ### Serverless Deployment Issues
422
+ ```bash
423
+ # Enable debug logging for serverless
424
+ SLS_DEBUG=true serverless deploy
425
+
426
+ # Validate generated template
427
+ serverless print > template.yml
428
+
429
+ # Check CloudFormation template syntax
430
+ aws cloudformation validate-template --template-body file://template.yml
431
+ ```
432
+
433
+ ### VPC Configuration Problems
434
+ - **ENI Limits**: Check elastic network interface limits in target subnets
435
+ - **Security Groups**: Ensure security groups allow required traffic
436
+ - **Route Tables**: Verify routing for VPC endpoints and NAT Gateway
437
+ - **DNS Resolution**: Check VPC DNS settings for private DNS names
438
+
439
+ ### KMS Encryption Issues
440
+ - **Key Permissions**: Ensure IAM roles have KMS usage permissions
441
+ - **Key Policy**: Check KMS key policy allows Lambda function usage
442
+ - **Region Consistency**: Ensure KMS key is in same region as Lambda
443
+ - **Alias Usage**: Use key ARN rather than alias for reliability
444
+
445
+ ## Environment Variables Reference
446
+
447
+ ### AWS Discovery Variables
448
+ ```bash
449
+ # Set by discovery process
450
+ AWS_DISCOVERY_VPC_ID=vpc-12345678
451
+ AWS_DISCOVERY_SECURITY_GROUP_ID=sg-12345678
452
+ AWS_DISCOVERY_SUBNET_ID_1=subnet-12345678
453
+ AWS_DISCOVERY_SUBNET_ID_2=subnet-87654321
454
+ AWS_DISCOVERY_ROUTE_TABLE_ID=rtb-12345678
455
+ AWS_DISCOVERY_KMS_KEY_ID=arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012
456
+ ```
457
+
458
+ ### Serverless Framework Variables
459
+ ```bash
460
+ # Set by serverless during deployment
461
+ AWS_REGION=us-east-1
462
+ STAGE=production
463
+ SERVICE_NAME=my-frigg-app
464
+ ```
465
+
466
+ ### Development/Testing Variables
467
+ ```bash
468
+ # Skip discovery in test environments
469
+ SKIP_AWS_DISCOVERY=true
470
+
471
+ # Use mock data for testing
472
+ USE_MOCK_AWS_DATA=true
473
+ ```
474
+
475
+ ## Related Documentation
476
+
477
+ - **Phase 3 Deployment**: See `DEPLOYMENT-INSTRUCTIONS.md` for Phase 3 features
478
+ - **AWS Discovery**: See `AWS-DISCOVERY-TROUBLESHOOTING.md` for troubleshooting
479
+ - **IAM Policies**: See `IAM-POLICY-TEMPLATES.md` for policy examples
480
+ - **Testing Strategy**: See `README-TESTING.md` for testing approach
481
+ - **WebSocket Config**: See `WEBSOCKET-CONFIGURATION.md` for WebSocket setup
@@ -83,27 +83,45 @@ aws cloudformation update-stack \
83
83
  For custom policy generation based on your app definition:
84
84
 
85
85
  ```javascript
86
- const { generateIAMPolicy, generateIAMCloudFormation } = require('./iam-generator');
86
+ const { generateIAMPolicy, generateIAMCloudFormation, getFeatureSummary } = require('./iam-generator');
87
87
 
88
88
  // Generate basic JSON policy
89
89
  const basicPolicy = generateIAMPolicy('basic');
90
90
 
91
- // Generate full JSON policy
91
+ // Generate full JSON policy
92
92
  const fullPolicy = generateIAMPolicy('full');
93
93
 
94
- // Generate CloudFormation template with auto-detection
95
- const autoTemplate = generateIAMCloudFormation(appDefinition, { mode: 'auto' });
96
-
97
- // Generate CloudFormation template with specific mode
98
- const basicTemplate = generateIAMCloudFormation(appDefinition, { mode: 'basic' });
99
- const fullTemplate = generateIAMCloudFormation(appDefinition, { mode: 'full' });
94
+ // Generate CloudFormation template with auto-detected features
95
+ const summary = getFeatureSummary(appDefinition);
96
+ const template = generateIAMCloudFormation({
97
+ appName: summary.appName,
98
+ features: summary.features,
99
+ userPrefix: 'frigg-deployment-user',
100
+ stackName: 'frigg-deployment-iam'
101
+ });
102
+
103
+ // Or manually specify features
104
+ const customTemplate = generateIAMCloudFormation({
105
+ appName: 'my-app',
106
+ features: {
107
+ vpc: true,
108
+ kms: true,
109
+ ssm: true,
110
+ websockets: false
111
+ },
112
+ userPrefix: 'my-deployment-user',
113
+ stackName: 'my-deployment-stack'
114
+ });
100
115
  ```
101
116
 
102
- ### Generator Modes
117
+ ### Feature Detection
118
+
119
+ Use `getFeatureSummary(appDefinition)` to automatically detect features from your app definition:
103
120
 
104
- - **`basic`** - Core permissions only, ignores app definition features
105
- - **`full`** - All features enabled, ignores app definition features
106
- - **`auto`** - Analyzes app definition and enables features as needed (default)
121
+ ```javascript
122
+ const summary = getFeatureSummary(appDefinition);
123
+ // Returns: { appName, features: { core, vpc, kms, ssm, websockets }, integrationCount }
124
+ ```
107
125
 
108
126
  ## Security Best Practices
109
127
 
@@ -1,7 +1,6 @@
1
1
  const path = require('path');
2
2
  const fs = require('fs-extra');
3
3
  const { composeServerlessDefinition } = require('./serverless-template');
4
-
5
4
  const { findNearestBackendPackageJson } = require('@friggframework/core');
6
5
 
7
6
  async function createFriggInfrastructure() {
@@ -25,7 +24,6 @@ async function createFriggInfrastructure() {
25
24
  // ));
26
25
  const definition = await composeServerlessDefinition(
27
26
  appDefinition,
28
- backend.IntegrationFactory
29
27
  );
30
28
 
31
29
  return {
@@ -1,52 +1,31 @@
1
1
  const path = require('path');
2
2
 
3
3
  /**
4
- * Generate IAM CloudFormation template based on AppDefinition
5
- * @param {Object} appDefinition - Application definition object
4
+ * Generate IAM CloudFormation template
6
5
  * @param {Object} options - Generation options
7
- * @param {string} [options.deploymentUserName='frigg-deployment-user'] - IAM user name
6
+ * @param {string} [options.appName='Frigg'] - Application name
7
+ * @param {Object} [options.features={}] - Enabled features { vpc, kms, ssm, websockets }
8
+ * @param {string} [options.userPrefix='frigg-deployment-user'] - IAM user name prefix
8
9
  * @param {string} [options.stackName='frigg-deployment-iam'] - CloudFormation stack name
9
- * @param {string} [options.mode='auto'] - Policy mode: 'basic', 'full', or 'auto' (auto-detect from appDefinition)
10
10
  * @returns {string} CloudFormation YAML template
11
11
  */
12
- function generateIAMCloudFormation(appDefinition, options = {}) {
13
- const { deploymentUserName = 'frigg-deployment-user', mode = 'auto' } =
14
- options;
15
-
16
- // Determine which features are enabled based on mode
17
- let features;
18
- if (mode === 'basic') {
19
- features = {
20
- vpc: false,
21
- kms: false,
22
- ssm: false,
23
- websockets: appDefinition.websockets?.enable === true,
24
- };
25
- } else if (mode === 'full') {
26
- features = {
27
- vpc: true,
28
- kms: true,
29
- ssm: true,
30
- websockets: appDefinition.websockets?.enable === true,
31
- };
32
- } else {
33
- // mode === 'auto'
34
- features = {
35
- vpc: appDefinition.vpc?.enable === true,
36
- kms:
37
- appDefinition.encryption
38
- ?.fieldLevelEncryptionMethod === 'kms',
39
- ssm: appDefinition.ssm?.enable === true,
40
- websockets: appDefinition.websockets?.enable === true,
41
- };
42
- }
12
+ function generateIAMCloudFormation(options = {}) {
13
+ const {
14
+ appName = 'Frigg',
15
+ features = {},
16
+ userPrefix = 'frigg-deployment-user',
17
+ stackName = 'frigg-deployment-iam'
18
+ } = options;
19
+
20
+ const deploymentUserName = userPrefix;
21
+
22
+ // Features are already analyzed by caller (use getFeatureSummary to extract features from appDefinition)
23
+ // Expected features: { vpc, kms, ssm, websockets }
43
24
 
44
25
  // Build the CloudFormation template
45
26
  const template = {
46
27
  AWSTemplateFormatVersion: '2010-09-09',
47
- Description: `IAM roles and policies for ${
48
- appDefinition.name || 'Frigg'
49
- } application deployment pipeline`,
28
+ Description: `IAM roles and policies for ${appName} application deployment pipeline`,
50
29
 
51
30
  Parameters: {
52
31
  DeploymentUserName: {
@@ -829,6 +808,7 @@ function generateIAMPolicy(mode = 'basic') {
829
808
 
830
809
  module.exports = {
831
810
  generateIAMCloudFormation,
811
+ generateCloudFormationTemplate: generateIAMCloudFormation, // Alias for generate-command/index.js compatibility
832
812
  getFeatureSummary,
833
813
  generateBasicIAMPolicy,
834
814
  generateFullIAMPolicy,