@friggframework/core 2.0.0--canary.703.6a9383b.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 (214) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/application/commands/integration-commands.js +18 -8
  3. package/application/index.js +6 -2
  4. package/credential/repositories/credential-repository-documentdb.js +34 -0
  5. package/credential/repositories/credential-repository-interface.js +15 -0
  6. package/credential/repositories/credential-repository-mongo.js +23 -0
  7. package/credential/repositories/credential-repository-postgres.js +28 -0
  8. package/credential/use-cases/credential-operations-for-user.js +117 -0
  9. package/credential/use-cases/reauthorize-credential-for-user.js +66 -0
  10. package/database/documentdb-encryption-service.js +9 -22
  11. package/database/documentdb-utils.js +1 -6
  12. package/database/encryption/README.md +78 -14
  13. package/database/encryption/documentdb-encryption-service.md +78 -1
  14. package/database/encryption/encryption-config.js +240 -0
  15. package/database/encryption/encryption-schema-registry.js +41 -12
  16. package/database/encryption/field-encryption-service.js +69 -5
  17. package/database/encryption/integration-mapping-encryption.js +1 -1
  18. package/database/encryption/test-support/fake-ciphertext.js +15 -0
  19. package/database/prisma.js +11 -36
  20. package/database/use-cases/check-encryption-health-use-case.js +43 -52
  21. package/errors/index.js +0 -4
  22. package/generated/prisma-mongodb/edge.js +14 -46
  23. package/generated/prisma-mongodb/index-browser.js +11 -43
  24. package/generated/prisma-mongodb/index.d.ts +748 -2746
  25. package/generated/prisma-mongodb/index.js +14 -46
  26. package/generated/prisma-mongodb/package.json +1 -1
  27. package/generated/prisma-mongodb/schema.prisma +23 -61
  28. package/generated/prisma-mongodb/wasm.js +14 -46
  29. package/generated/prisma-postgresql/edge.js +14 -46
  30. package/generated/prisma-postgresql/index-browser.js +11 -43
  31. package/generated/prisma-postgresql/index.d.ts +736 -2985
  32. package/generated/prisma-postgresql/index.js +14 -46
  33. package/generated/prisma-postgresql/package.json +1 -1
  34. package/generated/prisma-postgresql/schema.prisma +22 -59
  35. package/generated/prisma-postgresql/wasm.js +14 -46
  36. package/handlers/WEBHOOKS.md +0 -29
  37. package/handlers/app-definition-loader.js +19 -8
  38. package/handlers/app-handler-helpers.js +27 -8
  39. package/handlers/backend-utils.js +31 -25
  40. package/handlers/integration-event-dispatcher.js +3 -7
  41. package/handlers/middleware/admin-auth.js +14 -1
  42. package/handlers/routers/auth.js +11 -3
  43. package/handlers/routers/health.js +11 -4
  44. package/handlers/routers/integration-webhook-routers.js +38 -26
  45. package/handlers/workers/integration-defined-workers.js +5 -2
  46. package/index.js +4 -15
  47. package/integrations/index.js +0 -16
  48. package/integrations/integration-base.js +2 -163
  49. package/integrations/integration-router.js +17 -29
  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 +2 -6
  56. package/integrations/repositories/integration-repository-interface.js +0 -3
  57. package/integrations/repositories/integration-repository-mongo.js +5 -20
  58. package/integrations/repositories/integration-repository-postgres.js +1 -5
  59. package/integrations/repositories/process-repository-mongo.js +1 -1
  60. package/integrations/use-cases/create-integration.js +4 -14
  61. package/integrations/use-cases/delete-integration-for-user.js +4 -4
  62. package/integrations/use-cases/get-integration-for-user.js +2 -4
  63. package/integrations/use-cases/get-integration-instance.js +4 -4
  64. package/integrations/use-cases/get-integrations-for-user.js +4 -4
  65. package/integrations/use-cases/get-possible-integrations.js +2 -7
  66. package/integrations/use-cases/integration-operations-for-user.js +225 -0
  67. package/integrations/use-cases/update-integration.js +4 -4
  68. package/integrations/utils/map-integration-dto.js +1 -15
  69. package/management-api/create-management-api-router.js +49 -0
  70. package/management-api/error-response.js +116 -0
  71. package/management-api/management-api-config.js +82 -0
  72. package/management-api/meta-router.js +57 -0
  73. package/management-api/openapi/build-openapi.js +144 -0
  74. package/management-api/openapi/components.js +368 -0
  75. package/management-api/openapi/v1-operations.js +83 -0
  76. package/management-api/openapi/v2-operations.js +252 -0
  77. package/management-api/route-registry.js +294 -0
  78. package/management-api/test-support/http-client.js +39 -0
  79. package/management-api/use-cases/get-management-api-meta.js +57 -0
  80. package/management-api/v1-deprecation.js +120 -0
  81. package/management-api/v2/create-v2-router.js +85 -0
  82. package/management-api/v2/dependencies.js +256 -0
  83. package/management-api/v2/dto.js +123 -0
  84. package/management-api/v2/handlers/authorization.js +93 -0
  85. package/management-api/v2/handlers/credentials.js +29 -0
  86. package/management-api/v2/handlers/entities.js +74 -0
  87. package/management-api/v2/handlers/integrations.js +125 -0
  88. package/management-api/v2/handlers/proxy.js +34 -0
  89. package/management-api/v2/request.js +54 -0
  90. package/management-api/v2/test-support/fake-dependencies.js +103 -0
  91. package/modules/domain/authorization-session.js +144 -0
  92. package/modules/entity-type-registry.js +311 -0
  93. package/modules/index.js +6 -0
  94. package/modules/proxy/proxy-errors.js +20 -0
  95. package/modules/proxy/proxy-path.js +179 -0
  96. package/modules/proxy/proxy-policy.js +248 -0
  97. package/modules/repositories/authorization-session-repository-documentdb.js +112 -0
  98. package/modules/repositories/authorization-session-repository-factory.js +31 -0
  99. package/modules/repositories/authorization-session-repository-interface.js +47 -0
  100. package/modules/repositories/authorization-session-repository-prisma.js +87 -0
  101. package/modules/requester/proxy-request.js +244 -0
  102. package/modules/requester/requester.js +27 -2
  103. package/modules/tests/doubles/in-memory-authorization-session-repository.js +45 -0
  104. package/modules/use-cases/entity-operations-for-user.js +125 -0
  105. package/modules/use-cases/entity-types.js +115 -0
  106. package/modules/use-cases/execute-entity-proxy-request.js +239 -0
  107. package/modules/use-cases/get-authorization-requirements.js +100 -0
  108. package/modules/use-cases/get-entity-module-for-user.js +86 -0
  109. package/modules/use-cases/multi-step-authorization.js +302 -0
  110. package/package.json +5 -7
  111. package/prisma-mongodb/schema.prisma +23 -61
  112. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +28 -0
  113. package/prisma-postgresql/schema.prisma +22 -59
  114. package/queues/queuer-util.js +2 -9
  115. package/types/index.d.ts +1 -0
  116. package/types/modules/index.d.ts +58 -0
  117. package/errors/mapping-already-exists-error.js +0 -14
  118. package/handlers/workers/integration-triggers.js +0 -25
  119. package/infrastructure/scheduler/recurrence.js +0 -204
  120. package/integrations/define/DESIGN.md +0 -108
  121. package/integrations/define/config.js +0 -98
  122. package/integrations/define/define-app.js +0 -52
  123. package/integrations/define/define-extension.js +0 -154
  124. package/integrations/define/define-integration.js +0 -292
  125. package/integrations/define/examples/deal-alerts.js +0 -138
  126. package/integrations/define/extension-binding.js +0 -174
  127. package/integrations/define/index.js +0 -11
  128. package/integrations/define/json-schema-lite.js +0 -68
  129. package/integrations/define/subscriptions.js +0 -93
  130. package/integrations/define/tests/fixtures/hubspot.js +0 -109
  131. package/integrations/define/tests/fixtures/slack.js +0 -26
  132. package/integrations/define/use.js +0 -39
  133. package/integrations/definitions/README.md +0 -278
  134. package/integrations/definitions/canonical.js +0 -11
  135. package/integrations/definitions/capabilities/AUDIT.md +0 -480
  136. package/integrations/definitions/capabilities/acmeerp.capabilities.json +0 -633
  137. package/integrations/definitions/capabilities/asana.capabilities.json +0 -279
  138. package/integrations/definitions/capabilities/calendly.capabilities.json +0 -385
  139. package/integrations/definitions/capabilities/docusign.capabilities.json +0 -314
  140. package/integrations/definitions/capabilities/fathom.capabilities.json +0 -238
  141. package/integrations/definitions/capabilities/github.capabilities.json +0 -585
  142. package/integrations/definitions/capabilities/hubspot.capabilities.json +0 -822
  143. package/integrations/definitions/capabilities/jira.capabilities.json +0 -391
  144. package/integrations/definitions/capabilities/klaviyo.capabilities.json +0 -503
  145. package/integrations/definitions/capabilities/linear.capabilities.json +0 -378
  146. package/integrations/definitions/capabilities/netsuite.capabilities.json +0 -535
  147. package/integrations/definitions/capabilities/notion.capabilities.json +0 -208
  148. package/integrations/definitions/capabilities/phone.capabilities.json +0 -511
  149. package/integrations/definitions/capabilities/pipedrive.capabilities.json +0 -430
  150. package/integrations/definitions/capabilities/quickbooks.capabilities.json +0 -635
  151. package/integrations/definitions/capabilities/salesforce.capabilities.json +0 -568
  152. package/integrations/definitions/capabilities/shopify.capabilities.json +0 -1128
  153. package/integrations/definitions/capabilities/slack.capabilities.json +0 -373
  154. package/integrations/definitions/capabilities/stripe.capabilities.json +0 -630
  155. package/integrations/definitions/capabilities/webflow.capabilities.json +0 -196
  156. package/integrations/definitions/capabilities/zendesk.capabilities.json +0 -422
  157. package/integrations/definitions/compile.js +0 -80
  158. package/integrations/definitions/config-form.js +0 -137
  159. package/integrations/definitions/examples/acme-erp-quickbooks.definition.json +0 -467
  160. package/integrations/definitions/examples/asana-slack.definition.json +0 -219
  161. package/integrations/definitions/examples/calendly-salesforce.definition.json +0 -459
  162. package/integrations/definitions/examples/docusign-salesforce.definition.json +0 -305
  163. package/integrations/definitions/examples/fathom-hubspot-notion.definition.json +0 -575
  164. package/integrations/definitions/examples/github-linear.definition.json +0 -322
  165. package/integrations/definitions/examples/hubspot-slack.definition.json +0 -427
  166. package/integrations/definitions/examples/klaviyo-hubspot.definition.json +0 -336
  167. package/integrations/definitions/examples/phone-hubspot.definition.json +0 -633
  168. package/integrations/definitions/examples/pipedrive-hubspot.definition.json +0 -136
  169. package/integrations/definitions/examples/pipedrive-phone.definition.json +0 -340
  170. package/integrations/definitions/examples/records/phone-hubspot.definition-version.json +0 -652
  171. package/integrations/definitions/examples/records/phone-hubspot.integration.json +0 -86
  172. package/integrations/definitions/examples/records/phone-hubspot.mappings.json +0 -39
  173. package/integrations/definitions/examples/records/phone-hubspot.workflow-run.json +0 -62
  174. package/integrations/definitions/examples/shopify-klaviyo.definition.json +0 -488
  175. package/integrations/definitions/examples/shopify-netsuite.definition.json +0 -622
  176. package/integrations/definitions/examples/stripe-quickbooks.definition.json +0 -476
  177. package/integrations/definitions/examples/webflow-hubspot-slack.definition.json +0 -262
  178. package/integrations/definitions/examples/zendesk-jira.definition.json +0 -604
  179. package/integrations/definitions/expressions.js +0 -229
  180. package/integrations/definitions/index.js +0 -48
  181. package/integrations/definitions/integration-runtime.js +0 -779
  182. package/integrations/definitions/interpreter.js +0 -104
  183. package/integrations/definitions/manifests.js +0 -177
  184. package/integrations/definitions/renderers/common.js +0 -67
  185. package/integrations/definitions/renderers/html.js +0 -129
  186. package/integrations/definitions/renderers/hubspot.js +0 -59
  187. package/integrations/definitions/renderers/preview.js +0 -154
  188. package/integrations/definitions/renderers/slack.js +0 -146
  189. package/integrations/definitions/repositories/definition-version-repository.js +0 -67
  190. package/integrations/definitions/repositories/workflow-run-repository.js +0 -80
  191. package/integrations/definitions/router.js +0 -170
  192. package/integrations/definitions/runtime.js +0 -268
  193. package/integrations/definitions/schema/capability-manifest.v0.1.schema.json +0 -549
  194. package/integrations/definitions/schema/installation.v0.1.schema.json +0 -130
  195. package/integrations/definitions/schema/integration-definition.v0.1.schema.json +0 -909
  196. package/integrations/definitions/schema/records.md +0 -105
  197. package/integrations/definitions/schema-check.js +0 -58
  198. package/integrations/definitions/scripts/check-manifests.js +0 -220
  199. package/integrations/definitions/scripts/validate.js +0 -66
  200. package/integrations/definitions/steps.js +0 -123
  201. package/integrations/definitions/sync-engine.js +0 -297
  202. package/integrations/definitions/tests/helpers-fake-crm.js +0 -49
  203. package/integrations/definitions/transforms.js +0 -91
  204. package/integrations/definitions/use-cases/definition-use-cases.js +0 -245
  205. package/integrations/definitions/validate.js +0 -436
  206. package/integrations/definitions/versioning.js +0 -176
  207. package/integrations/definitions/webhooks.js +0 -119
  208. package/integrations/integration-types.js +0 -73
  209. package/integrations/triggers.js +0 -244
  210. package/integrations/use-cases/run-trigger-tick.js +0 -155
  211. package/integrations/use-cases/run-trigger.js +0 -77
  212. package/prisma-postgresql/migrations/20261018000000_add_data_defined_integrations/migration.sql +0 -66
  213. package/prisma-postgresql/migrations/20261019000000_workflow_run_waits/migration.sql +0 -7
  214. package/prisma-postgresql/migrations/20261019120000_definition_workspace/migration.sql +0 -5
@@ -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)
@@ -4,8 +4,41 @@
4
4
  * Infrastructure layer service that orchestrates field-level encryption/decryption.
5
5
  * Handles nested JSON paths (e.g., 'data.access_token') and bulk operations.
6
6
  */
7
+ const { logger } = require('./logger');
8
+ const { isDeployedRuntime } = require('./encryption-config');
9
+
10
+ /**
11
+ * Thrown when a value that looks like ciphertext cannot be decrypted in a
12
+ * deployed runtime (a wrong, rotated or missing key). Returning the stored
13
+ * ciphertext would hand it to API modules as if it were a token.
14
+ */
15
+ class FieldDecryptionError extends Error {
16
+ constructor(message, options) {
17
+ super(message, options);
18
+ this.name = 'FieldDecryptionError';
19
+ }
20
+ }
21
+
22
+ // Cryptor.encrypt() returns `${keyId}:${iv}:${ciphertext}:${encryptedKey}`:
23
+ // keyId and encryptedKey are base64, iv is 16 bytes of hex, ciphertext is hex.
24
+ // Plaintext with three colons (`https://user:pw@host:443`, `a:b:c:d`) must not
25
+ // be mistaken for it.
26
+ const BASE64_PART = /^[A-Za-z0-9+/]+={0,2}$/;
27
+ const IV_PART = /^[0-9a-f]{32}$/i;
28
+ const CIPHERTEXT_PART = /^(?:[0-9a-f]{2})+$/i;
29
+
7
30
  class FieldEncryptionService {
8
- constructor({ cryptor, schema }) {
31
+ /**
32
+ * @param {Object} params
33
+ * @param {Object} params.cryptor
34
+ * @param {Object} params.schema
35
+ * @param {() => boolean} [params.failClosedOnDecryptError] - whether a
36
+ * ciphertext-shaped value that fails to decrypt throws. Defaults to
37
+ * "running deployed" (encryption-config's isDeployedRuntime), read on
38
+ * each failure. Locally such a value is returned as stored, with a
39
+ * warning.
40
+ */
41
+ constructor({ cryptor, schema, failClosedOnDecryptError }) {
9
42
  if (!cryptor) {
10
43
  throw new Error('Cryptor instance required');
11
44
  }
@@ -15,6 +48,10 @@ class FieldEncryptionService {
15
48
 
16
49
  this.cryptor = cryptor;
17
50
  this.schema = schema;
51
+ this.failClosedOnDecryptError =
52
+ typeof failClosedOnDecryptError === 'function'
53
+ ? failClosedOnDecryptError
54
+ : () => isDeployedRuntime();
18
55
  }
19
56
 
20
57
  /**
@@ -97,12 +134,33 @@ class FieldEncryptionService {
97
134
  const decryptionPromises = fields.map(async (fieldPath) => {
98
135
  const value = this._getNestedValue(decrypted, fieldPath);
99
136
 
100
- if (this._isEncrypted(value)) {
137
+ if (!this._isEncrypted(value)) {
138
+ return null;
139
+ }
140
+ try {
101
141
  const decryptedValue = await this.cryptor.decrypt(value);
102
142
  const deserializedValue = this._deserializeAfterDecryption(decryptedValue);
103
143
  return { fieldPath, decryptedValue: deserializedValue };
144
+ } catch (error) {
145
+ // Deployed: a ciphertext-shaped value under a wrong, rotated or
146
+ // missing key fails the read rather than reaching an API
147
+ // module as a token. Legacy plaintext never gets here: it does
148
+ // not look like ciphertext (_isEncrypted).
149
+ if (this.failClosedOnDecryptError()) {
150
+ throw new FieldDecryptionError(
151
+ `Could not decrypt ${modelName}.${fieldPath}`,
152
+ { cause: error }
153
+ );
154
+ }
155
+ // Local: a value that looks like ciphertext but is not is read
156
+ // as it is stored. One such field must not fail the whole
157
+ // read, findMany included.
158
+ logger.warn(
159
+ `Could not decrypt ${modelName}.${fieldPath}; returning the stored value`,
160
+ { errorName: error?.name }
161
+ );
162
+ return null;
104
163
  }
105
- return null;
106
164
  });
107
165
 
108
166
  const results = await Promise.all(decryptionPromises);
@@ -152,7 +210,13 @@ class FieldEncryptionService {
152
210
  }
153
211
 
154
212
  const parts = value.split(':');
155
- return parts.length >= 4;
213
+ return (
214
+ parts.length === 4 &&
215
+ BASE64_PART.test(parts[0]) &&
216
+ IV_PART.test(parts[1]) &&
217
+ CIPHERTEXT_PART.test(parts[2]) &&
218
+ BASE64_PART.test(parts[3])
219
+ );
156
220
  }
157
221
 
158
222
  _getNestedValue(obj, path) {
@@ -251,4 +315,4 @@ class FieldEncryptionService {
251
315
  }
252
316
  }
253
317
 
254
- module.exports = { FieldEncryptionService };
318
+ module.exports = { FieldEncryptionService, FieldDecryptionError };
@@ -1,4 +1,4 @@
1
- const { getEncryptionConfig } = require('../prisma');
1
+ const { getEncryptionConfig } = require('./encryption-config');
2
2
  const { Cryptor } = require('../../encrypt/Cryptor');
3
3
  const {
4
4
  getFieldsToDecryptOnRead,
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Test double for Cryptor output. Same shape as the real thing
3
+ * (`keyId:iv:ciphertext:encryptedKey`: base64, 16-byte hex, hex, base64) so
4
+ * FieldEncryptionService._isEncrypted accepts it, with the plaintext
5
+ * recoverable for the fake decrypt.
6
+ */
7
+ const fakeCiphertext = (plain) =>
8
+ `a2V5SWQ=:${'0'.repeat(32)}:${Buffer.from(String(plain)).toString(
9
+ 'hex'
10
+ )}:ZW5jS2V5`;
11
+
12
+ const fakePlaintext = (ciphertext) =>
13
+ Buffer.from(String(ciphertext).split(':')[2], 'hex').toString();
14
+
15
+ module.exports = { fakeCiphertext, fakePlaintext };
@@ -4,6 +4,7 @@ const {
4
4
  const { loadCustomEncryptionSchema } = require('./encryption/encryption-schema-registry');
5
5
  const { logger } = require('./encryption/logger');
6
6
  const { Cryptor } = require('../encrypt/Cryptor');
7
+ const { getEncryptionConfig } = require('./encryption/encryption-config');
7
8
  const config = require('./config');
8
9
 
9
10
  /**
@@ -32,33 +33,6 @@ function ensureMongoDbUrl() {
32
33
  );
33
34
  }
34
35
 
35
- function getEncryptionConfig() {
36
- const STAGE = process.env.STAGE || process.env.NODE_ENV || 'development';
37
- const shouldBypassEncryption = ['dev', 'test', 'local'].includes(STAGE);
38
-
39
- if (shouldBypassEncryption) {
40
- return { enabled: false };
41
- }
42
-
43
- const hasKMS =
44
- process.env.KMS_KEY_ARN && process.env.KMS_KEY_ARN.trim() !== '';
45
- const hasAES =
46
- process.env.AES_KEY_ID && process.env.AES_KEY_ID.trim() !== '';
47
-
48
- if (!hasKMS && !hasAES) {
49
- logger.warn(
50
- 'No encryption keys configured (KMS_KEY_ARN or AES_KEY_ID). ' +
51
- 'Field-level encryption disabled. Set STAGE=production and configure keys to enable.'
52
- );
53
- return { enabled: false };
54
- }
55
-
56
- return {
57
- enabled: true,
58
- method: hasKMS ? 'kms' : 'aes',
59
- };
60
- }
61
-
62
36
  const prismaClientSingleton = () => {
63
37
  let PrismaClient;
64
38
 
@@ -103,9 +77,13 @@ const prismaClientSingleton = () => {
103
77
  errorFormat: 'pretty',
104
78
  });
105
79
 
80
+ // Throws when a deployed runtime has no encryption key: the app must not
81
+ // start and write sensitive fields in plaintext.
106
82
  const encryptionConfig = getEncryptionConfig();
107
83
 
108
84
  if (encryptionConfig.enabled) {
85
+ // Fail closed: if the extension cannot be installed, do not hand out
86
+ // a client that would write plaintext.
109
87
  try {
110
88
  // Load custom encryption schema from appDefinition before creating extension
111
89
  loadCustomEncryptionSchema();
@@ -120,17 +98,14 @@ const prismaClientSingleton = () => {
120
98
  enabled: true,
121
99
  })
122
100
  );
123
-
124
- logger.info(
125
- `Field-level encryption enabled using ${encryptionConfig.method.toUpperCase()}`
126
- );
127
101
  } catch (error) {
128
- logger.error(
129
- 'Failed to initialize encryption extension:',
130
- error
131
- );
132
- logger.warn('Continuing without encryption...');
102
+ logger.error('Failed to initialize encryption extension:', error);
103
+ throw error;
133
104
  }
105
+
106
+ logger.info(
107
+ `Field-level encryption enabled using ${encryptionConfig.method.toUpperCase()}`
108
+ );
134
109
  } else {
135
110
  logger.info('Field-level encryption disabled');
136
111
  }