@friggframework/core 2.0.0--canary.704.79d9a63.0 → 2.0.0--canary.680.daae24e.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/CLAUDE.md +0 -40
  3. package/application/commands/entity-commands.js +60 -18
  4. package/application/commands/integration-commands.js +18 -71
  5. package/application/index.js +6 -2
  6. package/credential/repositories/credential-repository-documentdb.js +34 -0
  7. package/credential/repositories/credential-repository-interface.js +15 -0
  8. package/credential/repositories/credential-repository-mongo.js +23 -0
  9. package/credential/repositories/credential-repository-postgres.js +28 -0
  10. package/credential/use-cases/credential-operations-for-user.js +117 -0
  11. package/credential/use-cases/reauthorize-credential-for-user.js +66 -0
  12. package/database/documentdb-encryption-service.js +9 -22
  13. package/database/documentdb-utils.js +1 -4
  14. package/database/encryption/README.md +78 -14
  15. package/database/encryption/documentdb-encryption-service.md +78 -1
  16. package/database/encryption/encryption-config.js +240 -0
  17. package/database/encryption/encryption-schema-registry.js +41 -12
  18. package/database/encryption/field-encryption-service.js +69 -5
  19. package/database/encryption/integration-mapping-encryption.js +1 -1
  20. package/database/encryption/test-support/fake-ciphertext.js +15 -0
  21. package/database/prisma.js +11 -36
  22. package/database/use-cases/check-encryption-health-use-case.js +43 -52
  23. package/errors/index.js +0 -4
  24. package/generated/prisma-mongodb/edge.js +20 -4
  25. package/generated/prisma-mongodb/index-browser.js +17 -1
  26. package/generated/prisma-mongodb/index.d.ts +1543 -95
  27. package/generated/prisma-mongodb/index.js +20 -4
  28. package/generated/prisma-mongodb/package.json +1 -1
  29. package/generated/prisma-mongodb/schema.prisma +27 -0
  30. package/generated/prisma-mongodb/wasm.js +20 -4
  31. package/generated/prisma-postgresql/edge.js +20 -4
  32. package/generated/prisma-postgresql/index-browser.js +17 -1
  33. package/generated/prisma-postgresql/index.d.ts +1570 -89
  34. package/generated/prisma-postgresql/index.js +20 -4
  35. package/generated/prisma-postgresql/package.json +1 -1
  36. package/generated/prisma-postgresql/schema.prisma +26 -0
  37. package/generated/prisma-postgresql/wasm.js +20 -4
  38. package/handlers/WEBHOOKS.md +0 -29
  39. package/handlers/app-definition-loader.js +19 -8
  40. package/handlers/app-handler-helpers.js +25 -3
  41. package/handlers/backend-utils.js +31 -25
  42. package/handlers/middleware/admin-auth.js +14 -1
  43. package/handlers/routers/auth.js +11 -3
  44. package/handlers/routers/health.js +11 -4
  45. package/handlers/workers/integration-defined-workers.js +5 -2
  46. package/index.js +4 -4
  47. package/integrations/index.js +0 -4
  48. package/integrations/integration-base.js +0 -29
  49. package/integrations/integration-router.js +16 -23
  50. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  51. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  52. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  53. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  54. package/integrations/repositories/integration-mapping-repository.js +0 -29
  55. package/integrations/repositories/integration-repository-documentdb.js +0 -32
  56. package/integrations/repositories/integration-repository-interface.js +0 -30
  57. package/integrations/repositories/integration-repository-mongo.js +1 -53
  58. package/integrations/repositories/integration-repository-postgres.js +0 -58
  59. package/integrations/repositories/process-repository-mongo.js +1 -1
  60. package/integrations/use-cases/create-integration.js +19 -57
  61. package/integrations/use-cases/integration-operations-for-user.js +225 -0
  62. package/integrations/utils/map-integration-dto.js +1 -15
  63. package/management-api/create-management-api-router.js +49 -0
  64. package/management-api/error-response.js +116 -0
  65. package/management-api/management-api-config.js +82 -0
  66. package/management-api/meta-router.js +57 -0
  67. package/management-api/openapi/build-openapi.js +144 -0
  68. package/management-api/openapi/components.js +368 -0
  69. package/management-api/openapi/v1-operations.js +83 -0
  70. package/management-api/openapi/v2-operations.js +252 -0
  71. package/management-api/route-registry.js +294 -0
  72. package/management-api/test-support/http-client.js +39 -0
  73. package/management-api/use-cases/get-management-api-meta.js +57 -0
  74. package/management-api/v1-deprecation.js +120 -0
  75. package/management-api/v2/create-v2-router.js +85 -0
  76. package/management-api/v2/dependencies.js +256 -0
  77. package/management-api/v2/dto.js +123 -0
  78. package/management-api/v2/handlers/authorization.js +93 -0
  79. package/management-api/v2/handlers/credentials.js +29 -0
  80. package/management-api/v2/handlers/entities.js +74 -0
  81. package/management-api/v2/handlers/integrations.js +125 -0
  82. package/management-api/v2/handlers/proxy.js +34 -0
  83. package/management-api/v2/request.js +54 -0
  84. package/management-api/v2/test-support/fake-dependencies.js +103 -0
  85. package/modules/domain/authorization-session.js +144 -0
  86. package/modules/entity-type-registry.js +311 -0
  87. package/modules/index.js +6 -0
  88. package/modules/proxy/proxy-errors.js +20 -0
  89. package/modules/proxy/proxy-path.js +179 -0
  90. package/modules/proxy/proxy-policy.js +248 -0
  91. package/modules/repositories/authorization-session-repository-documentdb.js +112 -0
  92. package/modules/repositories/authorization-session-repository-factory.js +31 -0
  93. package/modules/repositories/authorization-session-repository-interface.js +47 -0
  94. package/modules/repositories/authorization-session-repository-prisma.js +87 -0
  95. package/modules/requester/proxy-request.js +244 -0
  96. package/modules/requester/requester.js +27 -2
  97. package/modules/tests/doubles/in-memory-authorization-session-repository.js +45 -0
  98. package/modules/use-cases/entity-operations-for-user.js +125 -0
  99. package/modules/use-cases/entity-types.js +115 -0
  100. package/modules/use-cases/execute-entity-proxy-request.js +239 -0
  101. package/modules/use-cases/get-authorization-requirements.js +100 -0
  102. package/modules/use-cases/get-entity-module-for-user.js +86 -0
  103. package/modules/use-cases/multi-step-authorization.js +302 -0
  104. package/modules/utils/map-module-dto.js +3 -5
  105. package/package.json +5 -5
  106. package/prisma-mongodb/schema.prisma +27 -0
  107. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +28 -0
  108. package/prisma-postgresql/schema.prisma +26 -0
  109. package/types/index.d.ts +1 -0
  110. package/types/modules/index.d.ts +58 -0
  111. package/user/tests/doubles/test-user-repository.js +1 -1
  112. package/user/use-cases/get-user-from-bearer-token.js +2 -7
  113. package/errors/mapping-already-exists-error.js +0 -14
  114. package/integrations/use-cases/add-entities-to-integration.js +0 -92
  115. package/integrations/use-cases/remove-entities-from-integration.js +0 -70
  116. package/integrations/utils/assert-entity-ids-input.js +0 -42
  117. package/modules/utils/to-credential-id.js +0 -14
@@ -4,6 +4,7 @@ const {
4
4
  getFieldsToEncryptOnWrite,
5
5
  loadCustomEncryptionSchema,
6
6
  } = require('./encryption/encryption-schema-registry');
7
+ const { getEncryptionConfig } = require('./encryption/encryption-config');
7
8
 
8
9
  /**
9
10
  * Encryption service specifically for DocumentDB repositories
@@ -41,43 +42,29 @@ class DocumentDBEncryptionService {
41
42
  }
42
43
 
43
44
  /**
44
- * Initialize Cryptor with environment-based configuration.
45
- * Matches the logic from @friggframework/core/database/prisma.js
45
+ * Initialize Cryptor with environment-based configuration, using the
46
+ * same rule as the Prisma client (see encryption/encryption-config.js).
46
47
  *
47
- * Encryption is bypassed in dev/test/local stages.
48
- * Production uses AWS KMS (if available) or AES encryption.
48
+ * Local runs skip encryption on the dev, test and local stages. A
49
+ * deployed runtime with no key throws instead of writing plaintext.
49
50
  *
50
51
  * @private
52
+ * @throws {EncryptionConfigurationError} deployed with no usable key
51
53
  */
52
54
  _initializeCryptor() {
53
55
  // Load custom encryption schema from app definition BEFORE checking configuration
54
56
  // This ensures custom fields (like User.username) are registered before any encryption operations
55
57
  loadCustomEncryptionSchema();
56
58
 
57
- // Match logic from packages/core/database/prisma.js
58
- const stage = process.env.STAGE || process.env.NODE_ENV || 'development';
59
- const bypassEncryption = ['dev', 'test', 'local'].includes(stage.toLowerCase());
59
+ const config = getEncryptionConfig();
60
60
 
61
- if (bypassEncryption) {
61
+ if (!config.enabled) {
62
62
  this.cryptor = null;
63
63
  this.enabled = false;
64
64
  return;
65
65
  }
66
66
 
67
- // Determine encryption method (ensure boolean values)
68
- const hasKMS = !!(process.env.KMS_KEY_ARN && process.env.KMS_KEY_ARN.trim() !== '');
69
- const hasAES = !!(process.env.AES_KEY_ID && process.env.AES_KEY_ID.trim() !== '');
70
-
71
- if (!hasKMS && !hasAES) {
72
- console.warn('[DocumentDBEncryptionService] No encryption keys configured. Encryption disabled.');
73
- this.cryptor = null;
74
- this.enabled = false;
75
- return;
76
- }
77
-
78
- // KMS takes precedence over AES
79
- const shouldUseAws = hasKMS;
80
- this.cryptor = new Cryptor({ shouldUseAws });
67
+ this.cryptor = new Cryptor({ shouldUseAws: config.method === 'kms' });
81
68
  this.enabled = true;
82
69
  }
83
70
 
@@ -58,10 +58,7 @@ async function insertOne(client, collection, document) {
58
58
 
59
59
  // Provide helpful context for common errors
60
60
  if (error.code === 11000) {
61
- throw Object.assign(
62
- new Error(`${errorMsg} - Duplicate key violation`),
63
- { code: 11000 }
64
- );
61
+ throw new Error(`${errorMsg} - Duplicate key violation`);
65
62
  }
66
63
  throw new Error(errorMsg);
67
64
  }
@@ -13,7 +13,7 @@ This module provides **transparent field-level encryption** for sensitive data i
13
13
  - ✅ **Hexagonal architecture**: Clean separation of concerns
14
14
  - ✅ **AWS KMS support**: Enterprise-grade encryption with AWS Key Management Service
15
15
  - ✅ **Local AES fallback**: Development mode using local encryption keys
16
- - ✅ **Environment-based**: Automatic bypass in dev/test/local environments
16
+ - ✅ **Fails closed**: A deployed stage with no key refuses to start; only local runs (`frigg start`, tests) skip encryption
17
17
  - ✅ **Envelope encryption**: Secure key management pattern
18
18
 
19
19
  ## Architecture
@@ -107,18 +107,46 @@ AES_KEY=your-32-character-secret-key-here
107
107
  STAGE=production # or development, staging, etc.
108
108
  ```
109
109
 
110
- **⚠️ Important**: Encryption is automatically **disabled** when `STAGE` is set to `dev`, `test`, or `local`, regardless of key configuration.
110
+ ### When Encryption Runs
111
111
 
112
- ### Bypass Encryption
112
+ The rule lives in `encryption-config.js` and is shared by the Prisma client, the DocumentDB encryption service, the integration-mapping helpers and the `/health/detailed` check. It depends on **where the code runs**, not on the stage name.
113
113
 
114
- To explicitly disable encryption:
114
+ A process is **deployed** when it runs in AWS Lambda (`AWS_LAMBDA_FUNCTION_NAME` or `LAMBDA_TASK_ROOT` is set, or `AWS_EXECUTION_ENV` starts with `AWS_Lambda_`) or on another provider's platform (`FRIGG_PROVIDER` names a provider other than `aws`; provider-netlify's generated functions set `FRIGG_PROVIDER=netlify`), and is **not** a local run (`IS_OFFLINE=true` from serverless-offline / `frigg start`, `IS_LOCAL=true` from `serverless invoke local`, `NETLIFY_DEV=true` from `netlify dev`, or `JEST_WORKER_ID` from Jest). Everything else is **local**. Netlify's `SITE_ID`, `CONTEXT` and `NETLIFY` are build-time variables, so they are not used.
115
+
116
+ | Runtime | Key configured | `FRIGG_ENCRYPTION_DISABLED=true` | Result |
117
+ | --- | --- | --- | --- |
118
+ | Deployed, any stage (including `dev`) | `KMS_KEY_ARN` | any | Encrypt with KMS |
119
+ | Deployed, any stage | `AES_KEY_ID` + `AES_KEY` | any | Encrypt with AES |
120
+ | Deployed, any stage | `AES_KEY_ID` without `AES_KEY` | no | **Refuses to start** (`EncryptionConfigurationError`) |
121
+ | Deployed, any stage | none | no | **Refuses to start** (`EncryptionConfigurationError`) |
122
+ | Deployed, any stage | none | yes | Plaintext, with a warning on every cold start |
123
+ | Local, `STAGE` (or `NODE_ENV`) is `dev`, `test` or `local` | any | any | Skipped |
124
+ | Local, any other stage | `KMS_KEY_ARN` or `AES_KEY_ID` | any | Encrypt |
125
+ | Local, any other stage | none | any | Plaintext, with a warning |
126
+
127
+ KMS wins when both keys are set. A configured key always wins over `FRIGG_ENCRYPTION_DISABLED`: switching encryption off while a key exists would leave already-encrypted data unreadable, so the opt-out is ignored (with a warning).
128
+
129
+ "Refuses to start" means the Prisma client is never created: the first database access on a cold start throws
115
130
 
116
- ```bash
117
- # Disable encryption (development only)
118
- STAGE=development # or dev, test, local
119
131
  ```
132
+ EncryptionConfigurationError: [Frigg] No field-level encryption key is configured for stage "dev". A deployed Frigg app will not write credentials and other sensitive fields in plaintext. Fix: ...
133
+ ```
134
+
135
+ and `/health/detailed` reports `checks.encryption.status: "unhealthy"` with the same message. If a key is configured but the encryption extension fails to initialise, the client also refuses to start rather than continuing without encryption.
136
+
137
+ To encrypt a local run, use a stage other than `dev`, `test` or `local` and configure a key.
138
+
139
+ ### Running a Deployed Stage Without Encryption
120
140
 
121
- Or simply don't configure any encryption keys. In Production field level encryption **must** be enabled.
141
+ Only do this on purpose, for a stage that never holds real credentials. Either set it in the app definition:
142
+
143
+ ```javascript
144
+ const appDefinition = {
145
+ encryption: { fieldLevelEncryptionMethod: 'none' },
146
+ };
147
+ ```
148
+
149
+ which the infrastructure builders turn into `FRIGG_ENCRYPTION_DISABLED=true` on every function, or set `FRIGG_ENCRYPTION_DISABLED=true` in the Lambda environment yourself. Every cold start logs a warning that sensitive fields are stored in plaintext. There is no default that does this.
122
150
 
123
151
  ## Encrypted Fields
124
152
 
@@ -428,6 +456,8 @@ Format: "keyId:encryptedText:encryptedKey"
428
456
  Example: "base64KeyId:iv:ciphertext:base64EncryptedDataKey"
429
457
  ```
430
458
 
459
+ **Recognising ciphertext on read.** A value is decrypted only when it has exactly four colon-separated parts: base64 `keyId`, 32-hex-character `iv`, hex ciphertext, base64 `encryptedKey`. Plaintext that merely contains colons (`https://user:pw@host:443`) is left alone. A value with that shape that still fails to decrypt (a wrong, rotated or missing key) fails the read with `FieldDecryptionError` in a deployed runtime (see [When Encryption Runs](#when-encryption-runs)), so ciphertext never reaches an API module as if it were a token. Locally it is returned as stored and logged as a warning, so one bad field does not fail a whole read. A field that becomes encrypted later (for example a module's `credentialFields`) stays plaintext in existing rows until they are next written.
460
+
431
461
  **Why Envelope Encryption?**
432
462
 
433
463
  - Reduces KMS API calls (one DEK per field, cached)
@@ -553,8 +583,8 @@ class MyRepositoryDocumentDB {
553
583
 
554
584
  #### Configuration
555
585
 
556
- Uses the same environment variables and Cryptor as the Prisma Extension:
557
- - `STAGE`: Bypasses encryption for dev/test/local
586
+ Uses the same rule (`encryption-config.js`, see [When Encryption Runs](#when-encryption-runs)) and Cryptor as the Prisma Extension. Constructing the service in a deployed runtime with no key throws `EncryptionConfigurationError`.
587
+ - `STAGE`: Skips encryption for dev/test/local on local runs only
558
588
  - `KMS_KEY_ARN`: AWS KMS encryption (production)
559
589
  - `AES_KEY_ID` + `AES_KEY`: AES encryption (fallback)
560
590
 
@@ -615,10 +645,27 @@ curl http://localhost:3000/health/test-encryption
615
645
  "encryptionWorks": true
616
646
  }
617
647
 
618
- # Response when encryption disabled:
648
+ # Response on a local run with STAGE=dev:
619
649
  {
620
650
  "status": "disabled",
621
- "reason": "Encryption bypassed for stage: development"
651
+ "bypassed": true,
652
+ "runtime": "local",
653
+ "testResult": "Encryption bypassed for this stage"
654
+ }
655
+
656
+ # Response in a deployed stage with no key (the app itself refuses to start):
657
+ {
658
+ "status": "unhealthy",
659
+ "mode": "none",
660
+ "runtime": "deployed",
661
+ "testResult": "[Frigg] No field-level encryption key is configured for stage \"dev\". ..."
662
+ }
663
+
664
+ # Response in a deployed stage with FRIGG_ENCRYPTION_DISABLED=true and no key:
665
+ {
666
+ "status": "disabled",
667
+ "optedOut": true,
668
+ "testResult": "Encryption explicitly disabled (FRIGG_ENCRYPTION_DISABLED=true); sensitive fields are stored in plaintext"
622
669
  }
623
670
  ```
624
671
 
@@ -732,9 +779,10 @@ FRIGG_LOG_LEVEL=INFO
732
779
  **Check environment variables:**
733
780
 
734
781
  ```bash
735
- echo $STAGE # Should be 'production' (not dev/test/local)
736
782
  echo $KMS_KEY_ARN # Should be set (for KMS)
737
- echo $AES_KEY_ID # Should be set (for AES)
783
+ echo $AES_KEY_ID $AES_KEY # Both should be set (for AES)
784
+ echo $STAGE # Local runs only: dev/test/local skip encryption
785
+ echo $FRIGG_ENCRYPTION_DISABLED # Should be unset
738
786
  ```
739
787
 
740
788
  **Check console logs:**
@@ -749,6 +797,22 @@ or
749
797
  [Frigg] Field-level encryption disabled
750
798
  ```
751
799
 
800
+ ### Deployed Stage Refuses to Start
801
+
802
+ **Error: "EncryptionConfigurationError: [Frigg] No field-level encryption key is configured for stage ..."**
803
+
804
+ The function runs in AWS and has neither `KMS_KEY_ARN` nor `AES_KEY_ID` + `AES_KEY`. Earlier versions skipped encryption on stages named `dev`, `test` or `local` and wrote plaintext when no key was set; deployed stages now refuse instead. Fix one of:
805
+
806
+ 1. Set `encryption: { fieldLevelEncryptionMethod: 'kms' }` in the app definition and redeploy. Frigg creates or discovers a KMS key and sets `KMS_KEY_ARN` on every function, whatever the stage name.
807
+ 2. Provide `AES_KEY_ID` and `AES_KEY` (32 characters) through the app definition's `environment` and the deploy environment.
808
+ 3. To keep the stage in plaintext on purpose, set `encryption: { fieldLevelEncryptionMethod: 'none' }` (or `FRIGG_ENCRYPTION_DISABLED=true`).
809
+
810
+ Data written in plaintext before the key existed stays readable: reads leave values that are not in the encrypted `keyId:iv:cipher:encKey` format untouched, and the next write of each record encrypts it. Records that are never rewritten stay in plaintext until you re-save them.
811
+
812
+ **Error: "[Frigg] AES_KEY_ID is set but AES_KEY is not"**
813
+
814
+ Provide `AES_KEY` alongside `AES_KEY_ID`, or switch to KMS.
815
+
752
816
  ### AWS KMS Errors
753
817
 
754
818
  **Error: "User is not authorized to perform: kms:GenerateDataKey"**
@@ -225,7 +225,84 @@ Database (ENCRYPTED STORAGE) ✅ SECURE
225
225
  1. **Consistency**: Same encryption format and Cryptor as Prisma Extension
226
226
  2. **Reusability**: Single service used by all DocumentDB repositories
227
227
  3. **Schema-Driven**: Uses `encryption-schema-registry.js` (same as Prisma)
228
- 4. **Environment-Aware**: Respects STAGE-based bypass (dev/test/local)
228
+ 4. **Fails Closed**: Same rule as the Prisma client; a deployed runtime with no key throws, only local runs skip encryption
229
+ 5. **Error-Tolerant**: Graceful handling of decryption failures
230
+ 6. **Testable**: Can be unit tested independently of repositories
231
+
232
+ ---
233
+
234
+ ## Technical Specification
235
+
236
+ ### Class Design
237
+
238
+ ```javascript
239
+ /**
240
+ * Encryption service specifically for DocumentDB repositories
241
+ * that use $runCommandRaw and bypass Prisma Extensions.
242
+ *
243
+ * Provides document-level encryption/decryption,
244
+ * handling nested fields according to the encryption schema registry.
245
+ */
246
+ class DocumentDBEncryptionService {
247
+ constructor()
248
+ _initializeCryptor()
249
+ async encryptFields(modelName, document)
250
+ async decryptFields(modelName, document)
251
+ async _encryptFieldPath(document, fieldPath, modelName)
252
+ async _decryptFieldPath(document, fieldPath, modelName)
253
+ _isEncryptedValue(value)
254
+ }
255
+ ```
256
+
257
+ ### Method Specifications
258
+
259
+ #### `constructor()`
260
+
261
+ **Purpose**: Initialize the service and configure Cryptor
262
+
263
+ **Behavior**:
264
+
265
+ - Calls `_initializeCryptor()` immediately
266
+ - Sets up `this.cryptor` and `this.enabled` properties
267
+
268
+ **No parameters**
269
+
270
+ ---
271
+
272
+ #### `_initializeCryptor()`
273
+
274
+ **Purpose**: Initialize Cryptor with environment-based configuration
275
+
276
+ **Logic**:
277
+
278
+ ```javascript
279
+ 1. loadCustomEncryptionSchema()
280
+ 2. config = getEncryptionConfig() // encryption/encryption-config.js, shared with the Prisma client
281
+ - throws EncryptionConfigurationError in a deployed runtime with no key
282
+ 3. If !config.enabled (local dev/test/local stage, local run without keys,
283
+ or FRIGG_ENCRYPTION_DISABLED=true opt-out):
284
+ - Set this.cryptor = null
285
+ - Set this.enabled = false
286
+ - Return
287
+ 4. Create Cryptor({ shouldUseAws: config.method === 'kms' })
288
+ 5. Set this.enabled = true
289
+ ```
290
+
291
+ **Environment Variables Used** (see "When Encryption Runs" in README.md):
292
+
293
+ - `AWS_LAMBDA_FUNCTION_NAME` / `LAMBDA_TASK_ROOT` / `AWS_EXECUTION_ENV=AWS_Lambda_*`, or a non-`aws` `FRIGG_PROVIDER`, minus `IS_OFFLINE` / `IS_LOCAL` / `NETLIFY_DEV` / `JEST_WORKER_ID`: deployed or local run
294
+ - `STAGE` or `NODE_ENV`: dev/test/local skip encryption on local runs only
295
+ - `KMS_KEY_ARN`: AWS KMS key ARN (enables KMS encryption)
296
+ - `AES_KEY_ID`: AES key identifier (enables AES encryption)
297
+ - `AES_KEY`: AES encryption key (required with AES_KEY_ID in a deployed runtime)
298
+ - `FRIGG_ENCRYPTION_DISABLED`: explicit plaintext opt-out for a deployed stage with no key
299
+
300
+ ### Design Principles
301
+
302
+ 1. **Consistency**: Same encryption format and Cryptor as Prisma Extension
303
+ 2. **Reusability**: Single service used by all DocumentDB repositories
304
+ 3. **Schema-Driven**: Uses `encryption-schema-registry.js` (same as Prisma)
305
+ 4. **Fails Closed**: Same rule as the Prisma client; a deployed runtime with no key throws, only local runs skip encryption
229
306
  5. **Error-Tolerant**: Graceful handling of decryption failures
230
307
  6. **Testable**: Can be unit tested independently of repositories
231
308
 
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Field-level encryption configuration: decides whether sensitive fields are
3
+ * encrypted, and with which key, from the process environment.
4
+ *
5
+ * The rule fails closed:
6
+ *
7
+ * - **Deployed** (running in AWS Lambda, and not under
8
+ * serverless-offline, `serverless invoke local` or Jest): the stage name is
9
+ * ignored. A configured key (KMS_KEY_ARN, or AES_KEY_ID with AES_KEY) turns
10
+ * encryption on. With no key, the configuration is an error and the Prisma
11
+ * client refuses to start, unless FRIGG_ENCRYPTION_DISABLED=true opts out
12
+ * explicitly.
13
+ * - **Local** (`frigg start`, tests, scripts on a laptop): the stages dev,
14
+ * test and local skip encryption. Any other stage encrypts when a key is
15
+ * configured and stays plaintext, with a warning, when none is.
16
+ *
17
+ * Every module that encrypts or reports on encryption reads this one rule.
18
+ */
19
+
20
+ const { logger } = require('./logger');
21
+
22
+ const LOCAL_BYPASS_STAGES = ['dev', 'test', 'local'];
23
+ const OPT_OUT_VAR = 'FRIGG_ENCRYPTION_DISABLED';
24
+
25
+ class EncryptionConfigurationError extends Error {
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = 'EncryptionConfigurationError';
29
+ }
30
+ }
31
+
32
+ function isSet(value) {
33
+ return typeof value === 'string' && value.trim() !== '';
34
+ }
35
+
36
+ function isTrue(value) {
37
+ if (typeof value !== 'string') return false;
38
+ const normalized = value.trim().toLowerCase();
39
+ return normalized === 'true' || normalized === '1';
40
+ }
41
+
42
+ /**
43
+ * True when the process runs as a deployed function, on AWS Lambda or on
44
+ * another provider's platform.
45
+ *
46
+ * - AWS Lambda sets AWS_LAMBDA_FUNCTION_NAME, LAMBDA_TASK_ROOT and
47
+ * AWS_EXECUTION_ENV (AWS_Lambda_<runtime>). Other AWS hosts (CloudShell,
48
+ * CodeBuild, ECS) set AWS_EXECUTION_ENV to other values and count as local:
49
+ * CLI commands run from CI must not trip the deployed-stage check.
50
+ * - Other providers: FRIGG_PROVIDER names a non-AWS provider. Frigg's
51
+ * generated function entry points for that provider set it (provider-netlify
52
+ * sets 'netlify'), so it is present in every deployed function. Netlify
53
+ * exposes SITE_ID, CONTEXT and NETLIFY at build time only, so they cannot
54
+ * tell a running function from a laptop.
55
+ *
56
+ * A local run is never deployed: serverless-offline and `serverless invoke
57
+ * local` (which set the Lambda variables themselves) mark IS_OFFLINE /
58
+ * IS_LOCAL, `netlify dev` marks NETLIFY_DEV, and Jest marks JEST_WORKER_ID.
59
+ *
60
+ * @param {Object} [env=process.env]
61
+ * @returns {boolean}
62
+ */
63
+ function isDeployedRuntime(env = process.env) {
64
+ const localRun =
65
+ isTrue(env.IS_OFFLINE) ||
66
+ isTrue(env.IS_LOCAL) ||
67
+ isTrue(env.NETLIFY_DEV) ||
68
+ isSet(env.JEST_WORKER_ID);
69
+ if (localRun) return false;
70
+
71
+ const onAwsRuntime =
72
+ isSet(env.AWS_LAMBDA_FUNCTION_NAME) ||
73
+ isSet(env.LAMBDA_TASK_ROOT) ||
74
+ String(env.AWS_EXECUTION_ENV ?? '').startsWith('AWS_Lambda_');
75
+ if (onAwsRuntime) return true;
76
+
77
+ const provider = String(env.FRIGG_PROVIDER ?? '').trim().toLowerCase();
78
+ return provider !== '' && provider !== 'aws';
79
+ }
80
+
81
+ function missingKeyMessage(stage) {
82
+ return (
83
+ `[Frigg] No field-level encryption key is configured for stage "${stage}". ` +
84
+ 'A deployed Frigg app will not write credentials and other sensitive fields in plaintext. ' +
85
+ "Fix: set encryption: { fieldLevelEncryptionMethod: 'kms' } in the app definition and redeploy " +
86
+ '(Frigg creates or discovers a KMS key and sets KMS_KEY_ARN), ' +
87
+ 'or provide AES_KEY_ID and AES_KEY (32 characters) in the Lambda environment. ' +
88
+ `To run this stage without encryption on purpose, set ${OPT_OUT_VAR}=true ` +
89
+ "(or encryption: { fieldLevelEncryptionMethod: 'none' } in the app definition)."
90
+ );
91
+ }
92
+
93
+ function incompleteAesMessage(stage) {
94
+ return (
95
+ `[Frigg] AES_KEY_ID is set but AES_KEY is not (stage "${stage}"). ` +
96
+ 'Provide AES_KEY (32 characters) alongside AES_KEY_ID, ' +
97
+ "or use KMS with encryption: { fieldLevelEncryptionMethod: 'kms' }."
98
+ );
99
+ }
100
+
101
+ /**
102
+ * Resolves the encryption configuration without side effects.
103
+ *
104
+ * @param {Object} [env=process.env]
105
+ * @returns {{
106
+ * enabled: boolean,
107
+ * method: 'kms'|'aes'|undefined,
108
+ * mode: 'kms'|'aes'|'none',
109
+ * runtime: 'deployed'|'local',
110
+ * stage: string,
111
+ * bypassed: boolean,
112
+ * optedOut: boolean,
113
+ * optOutIgnored: boolean,
114
+ * hasKMS: boolean,
115
+ * hasAES: boolean,
116
+ * error: string|null,
117
+ * }} `error` is set when a deployed runtime has no usable key.
118
+ */
119
+ function resolveEncryptionConfig(env = process.env) {
120
+ const stage = env.STAGE || env.NODE_ENV || 'development';
121
+ const runtime = isDeployedRuntime(env) ? 'deployed' : 'local';
122
+ const hasKMS = isSet(env.KMS_KEY_ARN);
123
+ const hasAES = isSet(env.AES_KEY_ID);
124
+ const optOutRequested = isTrue(env[OPT_OUT_VAR]);
125
+
126
+ const base = {
127
+ enabled: false,
128
+ method: undefined,
129
+ mode: 'none',
130
+ runtime,
131
+ stage,
132
+ bypassed: false,
133
+ optedOut: false,
134
+ optOutIgnored: false,
135
+ hasKMS,
136
+ hasAES,
137
+ error: null,
138
+ };
139
+
140
+ if (runtime === 'local') {
141
+ if (LOCAL_BYPASS_STAGES.includes(String(stage).toLowerCase())) {
142
+ return { ...base, bypassed: true };
143
+ }
144
+ if (hasKMS || hasAES) {
145
+ const method = hasKMS ? 'kms' : 'aes';
146
+ return { ...base, enabled: true, method, mode: method };
147
+ }
148
+ return base;
149
+ }
150
+
151
+ const hasCompleteAES = hasAES && isSet(env.AES_KEY);
152
+ if (hasKMS || hasCompleteAES) {
153
+ const method = hasKMS ? 'kms' : 'aes';
154
+ return {
155
+ ...base,
156
+ enabled: true,
157
+ method,
158
+ mode: method,
159
+ optOutIgnored: optOutRequested,
160
+ };
161
+ }
162
+
163
+ if (optOutRequested) {
164
+ return { ...base, optedOut: true };
165
+ }
166
+
167
+ return {
168
+ ...base,
169
+ error: hasAES ? incompleteAesMessage(stage) : missingKeyMessage(stage),
170
+ };
171
+ }
172
+
173
+ const warned = new Set();
174
+
175
+ function warnOnce(key, message) {
176
+ if (warned.has(key)) return;
177
+ warned.add(key);
178
+ logger.warn(message);
179
+ }
180
+
181
+ /**
182
+ * Resolves the encryption configuration for use: throws when a deployed
183
+ * runtime has no usable key, and warns once per process (once per Lambda
184
+ * cold start) when encryption is explicitly disabled.
185
+ *
186
+ * @param {Object} [env=process.env]
187
+ * @returns {ReturnType<typeof resolveEncryptionConfig>}
188
+ * @throws {EncryptionConfigurationError}
189
+ */
190
+ function getEncryptionConfig(env = process.env) {
191
+ const config = resolveEncryptionConfig(env);
192
+
193
+ if (config.error) {
194
+ throw new EncryptionConfigurationError(config.error);
195
+ }
196
+
197
+ if (config.optedOut) {
198
+ warnOnce(
199
+ 'opted-out',
200
+ `[Frigg] ${OPT_OUT_VAR}=true: field-level encryption is OFF for stage "${config.stage}". ` +
201
+ 'Credentials and other sensitive fields are stored in PLAINTEXT. ' +
202
+ `Remove ${OPT_OUT_VAR} and configure a key (fieldLevelEncryptionMethod: 'kms') to encrypt them.`
203
+ );
204
+ }
205
+
206
+ if (config.optOutIgnored) {
207
+ warnOnce(
208
+ 'opt-out-ignored',
209
+ `[Frigg] ${OPT_OUT_VAR}=true is ignored because an encryption key is configured; ` +
210
+ `fields are encrypted with ${config.method.toUpperCase()}. ` +
211
+ 'Turning encryption off while a key is present would leave encrypted data unreadable.'
212
+ );
213
+ }
214
+
215
+ if (config.runtime === 'local' && !config.enabled && !config.bypassed) {
216
+ warnOnce(
217
+ 'local-no-keys',
218
+ `No encryption keys configured (KMS_KEY_ARN or AES_KEY_ID) for local stage "${config.stage}". ` +
219
+ 'Field-level encryption disabled for this local run. ' +
220
+ 'A deployed stage without a key refuses to start.'
221
+ );
222
+ }
223
+
224
+ return config;
225
+ }
226
+
227
+ /** Test helper: let the once-per-process warnings fire again. */
228
+ function resetEncryptionConfigWarnings() {
229
+ warned.clear();
230
+ }
231
+
232
+ module.exports = {
233
+ EncryptionConfigurationError,
234
+ LOCAL_BYPASS_STAGES,
235
+ OPT_OUT_VAR,
236
+ getEncryptionConfig,
237
+ isDeployedRuntime,
238
+ resetEncryptionConfigWarnings,
239
+ resolveEncryptionConfig,
240
+ };
@@ -10,6 +10,11 @@
10
10
 
11
11
  const { logger } = require('./logger');
12
12
  const { registerDeniedKeys } = require('../../logs/denied-keys');
13
+ const {
14
+ getEntityTypeRegistry,
15
+ getEntityTypeDefinitions,
16
+ EntityRegistryError,
17
+ } = require('../../modules/entity-type-registry');
13
18
 
14
19
  /**
15
20
  * Core encryption schema (immutable - cannot be overridden by custom schemas)
@@ -39,6 +44,12 @@ const CORE_ENCRYPTION_SCHEMA = {
39
44
  Token: {
40
45
  fields: ['token'],
41
46
  },
47
+
48
+ // Multi-step authorization (Management API v2): earlier steps can collect
49
+ // emails, usernames or one-time codes.
50
+ AuthorizationSession: {
51
+ fields: ['stepData'],
52
+ },
42
53
  };
43
54
 
44
55
  let customSchema = {};
@@ -160,8 +171,9 @@ function extractCredentialFieldsFromModules(moduleDefinitions) {
160
171
  * Each module can declare credentialFields to encrypt in its encryption config.
161
172
  *
162
173
  * @param {Array} integrations - Array of integration classes with modules
174
+ * @param {object} [entities] - `appDefinition.entities` (ADR-059 registry)
163
175
  */
164
- function loadModuleEncryptionSchemas(integrations) {
176
+ function loadModuleEncryptionSchemas(integrations, entities) {
165
177
  if (!integrations) {
166
178
  throw new Error('integrations parameter is required');
167
179
  }
@@ -170,27 +182,39 @@ function loadModuleEncryptionSchemas(integrations) {
170
182
  throw new Error('integrations must be an array');
171
183
  }
172
184
 
173
- if (integrations.length === 0) {
185
+ // `entities` is the app definition's registry (ADR-059): a module an app
186
+ // registers without any integration still carries credentials to encrypt.
187
+ if (integrations.length === 0 && !entities) {
174
188
  return;
175
189
  }
176
190
 
177
- const { getModulesDefinitionFromIntegrationClasses } = require('../integrations/utils/map-integration-dto');
178
-
179
- const moduleDefinitions = getModulesDefinitionFromIntegrationClasses(integrations);
191
+ const moduleDefinitions = getEntityTypeDefinitions(
192
+ getEntityTypeRegistry({ integrations, entities })
193
+ );
180
194
  const credentialFields = extractCredentialFieldsFromModules(moduleDefinitions);
181
195
 
182
- if (credentialFields.length === 0) {
196
+ // Core fields are encrypted already and a custom schema may not repeat
197
+ // them. Everything the app registered itself stays: module fields are added
198
+ // to the custom schema, never substituted for it (other models included).
199
+ const coreFields = new Set(CORE_ENCRYPTION_SCHEMA.Credential?.fields || []);
200
+ const fields = [
201
+ ...new Set([
202
+ ...(customSchema.Credential?.fields || []),
203
+ ...credentialFields.filter((field) => !coreFields.has(field)),
204
+ ]),
205
+ ];
206
+
207
+ if (fields.length === 0) {
183
208
  return;
184
209
  }
185
210
 
186
211
  const moduleSchema = {
187
- Credential: {
188
- fields: credentialFields
189
- }
212
+ ...customSchema,
213
+ Credential: { ...customSchema.Credential, fields },
190
214
  };
191
215
 
192
216
  logger.info(
193
- `Registering module-level encryption for ${credentialFields.length} credential fields`
217
+ `Registering module-level encryption for ${fields.length} credential fields`
194
218
  );
195
219
 
196
220
  registerCustomSchema(moduleSchema);
@@ -242,10 +266,15 @@ function loadCustomEncryptionSchema() {
242
266
 
243
267
  // Load module-level encryption schemas from integrations
244
268
  const integrations = appDefinition.integrations;
245
- if (integrations && Array.isArray(integrations)) {
246
- loadModuleEncryptionSchemas(integrations);
269
+ if (Array.isArray(integrations) || appDefinition.entities) {
270
+ loadModuleEncryptionSchemas(
271
+ Array.isArray(integrations) ? integrations : [],
272
+ appDefinition.entities
273
+ );
247
274
  }
248
275
  } catch (error) {
276
+ // A bad entity registry is a configuration error, not "no custom schema".
277
+ if (error instanceof EntityRegistryError) throw error;
249
278
  // Silently ignore errors - custom schema is optional
250
279
  // This handles cases like:
251
280
  // - Backend package.json not found (tests, standalone usage)