@friggframework/core 2.0.0--canary.703.12b980b.0 → 2.0.0--canary.707.df80bfd.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.
- package/CHANGELOG.md +11 -0
- package/CLAUDE.md +28 -0
- package/README.md +105 -0
- package/application/commands/integration-commands.js +20 -10
- package/application/commands/scheduler-commands.js +11 -7
- package/application/commands/user-commands.js +17 -5
- package/application/index.js +6 -2
- package/core/Worker.js +31 -7
- package/core/create-handler.js +9 -0
- package/credential/repositories/credential-repository-documentdb.js +34 -0
- package/credential/repositories/credential-repository-interface.js +15 -0
- package/credential/repositories/credential-repository-mongo.js +23 -0
- package/credential/repositories/credential-repository-postgres.js +28 -0
- package/credential/use-cases/credential-operations-for-user.js +202 -0
- package/credential/use-cases/reauthorize-credential-for-user.js +73 -0
- package/database/config.js +48 -24
- package/database/documentdb-encryption-service.js +9 -22
- package/database/documentdb-utils.js +2 -2
- package/database/encryption/README.md +78 -14
- package/database/encryption/documentdb-encryption-service.md +78 -1
- package/database/encryption/encryption-config.js +219 -0
- package/database/encryption/encryption-schema-registry.js +121 -24
- package/database/encryption/field-encryption-service.js +69 -5
- package/database/encryption/integration-mapping-encryption.js +1 -1
- package/database/encryption/test-support/fake-ciphertext.js +15 -0
- package/database/organization-where.js +18 -0
- package/database/prisma.js +15 -38
- package/database/unique-violation.js +25 -0
- package/database/use-cases/check-encryption-health-use-case.js +43 -52
- package/errors/index.js +0 -4
- package/extensions/bootstrap-runner.js +43 -0
- package/extensions/extension-loader.js +230 -0
- package/extensions/index.js +44 -0
- package/extensions/initialize-app.js +123 -0
- package/extensions/prisma-composer.js +270 -0
- package/extensions/route-mounter.js +103 -0
- package/extensions/schema-composer.js +188 -0
- package/generated/prisma-mongodb/edge.js +33 -42
- package/generated/prisma-mongodb/index-browser.js +30 -39
- package/generated/prisma-mongodb/index.d.ts +3187 -2005
- package/generated/prisma-mongodb/index.js +33 -42
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +86 -59
- package/generated/prisma-mongodb/wasm.js +33 -42
- package/generated/prisma-postgresql/edge.js +33 -42
- package/generated/prisma-postgresql/index-browser.js +30 -39
- package/generated/prisma-postgresql/index.d.ts +3380 -2177
- package/generated/prisma-postgresql/index.js +33 -42
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +81 -57
- package/generated/prisma-postgresql/wasm.js +33 -42
- package/handlers/WEBHOOKS.md +0 -29
- package/handlers/app-definition-loader.js +128 -19
- package/handlers/app-handler-helpers.js +27 -8
- package/handlers/backend-utils.js +31 -25
- package/handlers/integration-event-dispatcher.js +3 -7
- package/handlers/middleware/admin-auth.js +14 -1
- package/handlers/routers/auth.js +46 -10
- package/handlers/routers/health.js +13 -4
- package/handlers/routers/integration-defined-routers.js +144 -92
- package/handlers/routers/integration-webhook-routers.js +100 -50
- package/handlers/workers/integration-defined-workers.js +5 -2
- package/index.js +66 -16
- package/infrastructure/scheduler/index.js +19 -6
- package/infrastructure/scheduler/netlify-scheduler-adapter.js +216 -0
- package/infrastructure/scheduler/scheduled-job-repository.js +118 -0
- package/infrastructure/scheduler/scheduler-service-factory.js +55 -7
- package/integrations/index.js +1 -14
- package/integrations/integration-base.js +2 -163
- package/integrations/integration-router.js +132 -102
- package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
- package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
- package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
- package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
- package/integrations/repositories/integration-mapping-repository.js +0 -29
- package/integrations/repositories/integration-not-found.js +14 -0
- package/integrations/repositories/integration-repository-documentdb.js +37 -9
- package/integrations/repositories/integration-repository-interface.js +17 -4
- package/integrations/repositories/integration-repository-mongo.js +64 -96
- package/integrations/repositories/integration-repository-postgres.js +63 -81
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/schedule-config.js +80 -0
- package/integrations/tests/doubles/test-integration-repository.js +12 -1
- package/integrations/use-cases/create-integration.js +56 -31
- package/integrations/use-cases/delete-integration-for-user.js +4 -4
- package/integrations/use-cases/dispatch-ongoing-syncs.js +100 -0
- package/integrations/use-cases/get-integration-for-user.js +2 -4
- package/integrations/use-cases/get-integration-instance.js +4 -4
- package/integrations/use-cases/get-integrations-for-user.js +79 -39
- package/integrations/use-cases/get-possible-integrations.js +2 -7
- package/integrations/use-cases/index.js +7 -1
- package/integrations/use-cases/integration-operations-for-user.js +256 -0
- package/integrations/use-cases/resolve-integration-ownership.js +177 -0
- package/integrations/use-cases/update-integration.js +4 -4
- package/integrations/utils/map-integration-dto.js +43 -14
- package/management-api/create-management-api-router.js +49 -0
- package/management-api/error-response.js +116 -0
- package/management-api/management-api-config.js +151 -0
- package/management-api/meta-router.js +76 -0
- package/management-api/openapi/build-openapi.js +144 -0
- package/management-api/openapi/components.js +415 -0
- package/management-api/openapi/v1-operations.js +83 -0
- package/management-api/openapi/v2-operations.js +264 -0
- package/management-api/route-registry.js +411 -0
- package/management-api/test-support/http-client.js +39 -0
- package/management-api/use-cases/get-management-api-meta.js +57 -0
- package/management-api/v1-deprecation.js +120 -0
- package/management-api/v2/create-v2-router.js +85 -0
- package/management-api/v2/dependencies.js +281 -0
- package/management-api/v2/dto.js +143 -0
- package/management-api/v2/handlers/authorization.js +94 -0
- package/management-api/v2/handlers/credentials.js +33 -0
- package/management-api/v2/handlers/entities.js +77 -0
- package/management-api/v2/handlers/integrations.js +128 -0
- package/management-api/v2/handlers/proxy.js +34 -0
- package/management-api/v2/request.js +85 -0
- package/management-api/v2/test-support/fake-dependencies.js +103 -0
- package/modules/domain/authorization-session.js +144 -0
- package/modules/entity-scope.js +15 -0
- package/modules/entity-type-registry.js +311 -0
- package/modules/index.js +14 -0
- package/modules/module-factory.js +12 -0
- package/modules/module.js +53 -2
- package/modules/proxy/proxy-bases.js +169 -0
- package/modules/proxy/proxy-errors.js +31 -0
- package/modules/proxy/proxy-path.js +183 -0
- package/modules/proxy/proxy-policy.js +277 -0
- package/modules/repositories/authorization-session-repository-documentdb.js +112 -0
- package/modules/repositories/authorization-session-repository-factory.js +31 -0
- package/modules/repositories/authorization-session-repository-interface.js +47 -0
- package/modules/repositories/authorization-session-repository-prisma.js +87 -0
- package/modules/repositories/entity-not-found.js +18 -0
- package/modules/repositories/module-repository-documentdb.js +51 -6
- package/modules/repositories/module-repository-interface.js +19 -2
- package/modules/repositories/module-repository-mongo.js +67 -74
- package/modules/repositories/module-repository-postgres.js +66 -74
- package/modules/repositories/module-repository.js +2 -1
- package/modules/requester/proxy-request.js +245 -0
- package/modules/requester/requester.js +35 -5
- package/modules/scope-config.js +192 -0
- package/modules/scope-policy.js +112 -0
- package/modules/scope-resolution.js +288 -0
- package/modules/scope-visibility.js +247 -0
- package/modules/tests/doubles/in-memory-authorization-session-repository.js +45 -0
- package/modules/tests/doubles/ownership-matching.js +18 -0
- package/modules/use-cases/authorize-entity-for-user.js +61 -0
- package/modules/use-cases/create-entity-from-credential.js +113 -0
- package/modules/use-cases/entity-operations-for-user.js +162 -0
- package/modules/use-cases/entity-types.js +139 -0
- package/modules/use-cases/execute-entity-proxy-request.js +331 -0
- package/modules/use-cases/get-authorization-requirements.js +100 -0
- package/modules/use-cases/get-entities-for-user.js +26 -13
- package/modules/use-cases/get-entity-module-for-user.js +113 -0
- package/modules/use-cases/get-entity-options-by-id.js +10 -4
- package/modules/use-cases/get-entity-options-by-type.js +1 -1
- package/modules/use-cases/get-module-instance-from-type.js +1 -1
- package/modules/use-cases/get-module.js +10 -4
- package/modules/use-cases/manage-access.js +21 -0
- package/modules/use-cases/multi-step-authorization.js +329 -0
- package/modules/use-cases/process-authorization-callback.js +53 -19
- package/modules/use-cases/refresh-entity-options.js +10 -4
- package/modules/use-cases/test-module-auth.js +10 -4
- package/package.json +6 -7
- package/prisma-mongodb/schema.prisma +86 -59
- package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +28 -0
- package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +26 -0
- package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +25 -0
- package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +28 -0
- package/prisma-postgresql/schema.prisma +81 -57
- package/providers/index.js +23 -0
- package/providers/resolve-provider.js +93 -0
- package/providers/runtime-detection.js +124 -0
- package/queues/index.js +25 -0
- package/queues/providers/index.js +11 -0
- package/queues/providers/netlify-background-provider.js +150 -0
- package/queues/providers/qstash-queue-provider.js +219 -0
- package/queues/providers/sqs-queue-provider.js +70 -0
- package/queues/queue-client-interface.js +55 -0
- package/queues/queue-message-auth.js +193 -0
- package/queues/queue-provider-factory.js +101 -0
- package/queues/queue-provider.js +65 -0
- package/queues/queuer-util.js +2 -9
- package/queues/sqs-queue-client.js +81 -0
- package/types/index.d.ts +2 -0
- package/types/modules/index.d.ts +214 -0
- package/types/user/index.d.ts +134 -0
- package/user/adopter-jwt-config.js +177 -0
- package/user/adopter-jwt-errors.js +59 -0
- package/user/adopter-token-verifier.js +122 -0
- package/user/app-user-helpers.js +97 -0
- package/user/create-user-authentication.js +64 -0
- package/user/membership.js +51 -0
- package/user/repositories/organization-membership-record.js +19 -0
- package/user/repositories/organization-membership-repository-documentdb.js +106 -0
- package/user/repositories/organization-membership-repository-factory.js +42 -0
- package/user/repositories/organization-membership-repository-interface.js +57 -0
- package/user/repositories/organization-membership-repository-mongo.js +13 -0
- package/user/repositories/organization-membership-repository-postgres.js +29 -0
- package/user/repositories/organization-membership-repository-prisma.js +81 -0
- package/user/repositories/user-repository-documentdb.js +27 -2
- package/user/repositories/user-repository-interface.js +18 -0
- package/user/repositories/user-repository-mongo.js +24 -0
- package/user/repositories/user-repository-postgres.js +18 -0
- package/user/tests/doubles/adopter-jwt-fixtures.js +220 -0
- package/user/use-cases/authenticate-user.js +7 -1
- package/user/use-cases/ensure-organization-membership.js +92 -0
- package/user/use-cases/find-individual-users-by-organization.js +54 -0
- package/user/use-cases/get-user-from-adopter-jwt.js +95 -124
- package/user/use-cases/get-user-from-x-frigg-headers.js +83 -80
- package/user/user.js +64 -1
- package/errors/mapping-already-exists-error.js +0 -14
- package/handlers/workers/integration-triggers.js +0 -25
- package/infrastructure/scheduler/recurrence.js +0 -204
- package/integrations/define/DESIGN.md +0 -122
- package/integrations/define/config.js +0 -98
- package/integrations/define/define-app.js +0 -66
- package/integrations/define/define-extension.js +0 -154
- package/integrations/define/define-integration.js +0 -335
- package/integrations/define/examples/deal-alerts.js +0 -140
- package/integrations/define/extension-binding.js +0 -174
- package/integrations/define/index.js +0 -11
- package/integrations/define/json-schema-lite.js +0 -68
- package/integrations/define/subscriptions.js +0 -186
- package/integrations/define/tests/fixtures/hubspot.js +0 -109
- package/integrations/define/tests/fixtures/slack.js +0 -26
- package/integrations/define/use.js +0 -39
- package/integrations/definitions/README.md +0 -278
- package/integrations/definitions/canonical.js +0 -11
- package/integrations/definitions/capabilities/AUDIT.md +0 -480
- package/integrations/definitions/capabilities/acmeerp.capabilities.json +0 -633
- package/integrations/definitions/capabilities/asana.capabilities.json +0 -279
- package/integrations/definitions/capabilities/calendly.capabilities.json +0 -385
- package/integrations/definitions/capabilities/docusign.capabilities.json +0 -314
- package/integrations/definitions/capabilities/fathom.capabilities.json +0 -238
- package/integrations/definitions/capabilities/github.capabilities.json +0 -585
- package/integrations/definitions/capabilities/hubspot.capabilities.json +0 -822
- package/integrations/definitions/capabilities/jira.capabilities.json +0 -391
- package/integrations/definitions/capabilities/klaviyo.capabilities.json +0 -503
- package/integrations/definitions/capabilities/linear.capabilities.json +0 -378
- package/integrations/definitions/capabilities/netsuite.capabilities.json +0 -535
- package/integrations/definitions/capabilities/notion.capabilities.json +0 -208
- package/integrations/definitions/capabilities/phone.capabilities.json +0 -511
- package/integrations/definitions/capabilities/pipedrive.capabilities.json +0 -430
- package/integrations/definitions/capabilities/quickbooks.capabilities.json +0 -635
- package/integrations/definitions/capabilities/salesforce.capabilities.json +0 -568
- package/integrations/definitions/capabilities/shopify.capabilities.json +0 -1128
- package/integrations/definitions/capabilities/slack.capabilities.json +0 -373
- package/integrations/definitions/capabilities/stripe.capabilities.json +0 -630
- package/integrations/definitions/capabilities/webflow.capabilities.json +0 -196
- package/integrations/definitions/capabilities/zendesk.capabilities.json +0 -422
- package/integrations/definitions/compile.js +0 -80
- package/integrations/definitions/config-form.js +0 -137
- package/integrations/definitions/examples/acme-erp-quickbooks.definition.json +0 -467
- package/integrations/definitions/examples/asana-slack.definition.json +0 -219
- package/integrations/definitions/examples/calendly-salesforce.definition.json +0 -459
- package/integrations/definitions/examples/docusign-salesforce.definition.json +0 -305
- package/integrations/definitions/examples/fathom-hubspot-notion.definition.json +0 -575
- package/integrations/definitions/examples/github-linear.definition.json +0 -322
- package/integrations/definitions/examples/hubspot-slack.definition.json +0 -427
- package/integrations/definitions/examples/klaviyo-hubspot.definition.json +0 -336
- package/integrations/definitions/examples/phone-hubspot.definition.json +0 -633
- package/integrations/definitions/examples/pipedrive-hubspot.definition.json +0 -136
- package/integrations/definitions/examples/pipedrive-phone.definition.json +0 -340
- package/integrations/definitions/examples/records/phone-hubspot.definition-version.json +0 -652
- package/integrations/definitions/examples/records/phone-hubspot.integration.json +0 -86
- package/integrations/definitions/examples/records/phone-hubspot.mappings.json +0 -39
- package/integrations/definitions/examples/records/phone-hubspot.workflow-run.json +0 -62
- package/integrations/definitions/examples/shopify-klaviyo.definition.json +0 -488
- package/integrations/definitions/examples/shopify-netsuite.definition.json +0 -622
- package/integrations/definitions/examples/stripe-quickbooks.definition.json +0 -476
- package/integrations/definitions/examples/webflow-hubspot-slack.definition.json +0 -262
- package/integrations/definitions/examples/zendesk-jira.definition.json +0 -604
- package/integrations/definitions/expressions.js +0 -229
- package/integrations/definitions/index.js +0 -48
- package/integrations/definitions/integration-runtime.js +0 -779
- package/integrations/definitions/interpreter.js +0 -104
- package/integrations/definitions/manifests.js +0 -177
- package/integrations/definitions/renderers/common.js +0 -67
- package/integrations/definitions/renderers/html.js +0 -129
- package/integrations/definitions/renderers/hubspot.js +0 -59
- package/integrations/definitions/renderers/preview.js +0 -154
- package/integrations/definitions/renderers/slack.js +0 -146
- package/integrations/definitions/repositories/definition-version-repository.js +0 -67
- package/integrations/definitions/repositories/workflow-run-repository.js +0 -80
- package/integrations/definitions/router.js +0 -170
- package/integrations/definitions/runtime.js +0 -268
- package/integrations/definitions/schema/capability-manifest.v0.1.schema.json +0 -549
- package/integrations/definitions/schema/installation.v0.1.schema.json +0 -130
- package/integrations/definitions/schema/integration-definition.v0.1.schema.json +0 -909
- package/integrations/definitions/schema/records.md +0 -105
- package/integrations/definitions/schema-check.js +0 -58
- package/integrations/definitions/scripts/check-manifests.js +0 -220
- package/integrations/definitions/scripts/validate.js +0 -66
- package/integrations/definitions/steps.js +0 -123
- package/integrations/definitions/sync-engine.js +0 -297
- package/integrations/definitions/tests/helpers-fake-crm.js +0 -49
- package/integrations/definitions/transforms.js +0 -91
- package/integrations/definitions/use-cases/definition-use-cases.js +0 -245
- package/integrations/definitions/validate.js +0 -436
- package/integrations/definitions/versioning.js +0 -176
- package/integrations/definitions/webhooks.js +0 -119
- package/integrations/integration-types.js +0 -73
- package/integrations/triggers.js +0 -244
- package/integrations/use-cases/run-trigger-tick.js +0 -155
- package/integrations/use-cases/run-trigger.js +0 -77
- package/prisma-postgresql/migrations/20261018000000_add_data_defined_integrations/migration.sql +0 -66
- package/prisma-postgresql/migrations/20261019000000_workflow_run_waits/migration.sql +0 -7
- 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. **
|
|
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,219 @@
|
|
|
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
|
+
const {
|
|
22
|
+
isDeployedRuntime: isDeployedProviderRuntime,
|
|
23
|
+
} = require('../../providers/runtime-detection');
|
|
24
|
+
|
|
25
|
+
const LOCAL_BYPASS_STAGES = ['dev', 'test', 'local'];
|
|
26
|
+
const OPT_OUT_VAR = 'FRIGG_ENCRYPTION_DISABLED';
|
|
27
|
+
|
|
28
|
+
class EncryptionConfigurationError extends Error {
|
|
29
|
+
constructor(message) {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = 'EncryptionConfigurationError';
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isSet(value) {
|
|
36
|
+
return typeof value === 'string' && value.trim() !== '';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isTrue(value) {
|
|
40
|
+
if (typeof value !== 'string') return false;
|
|
41
|
+
const normalized = value.trim().toLowerCase();
|
|
42
|
+
return normalized === 'true' || normalized === '1';
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* True when the process runs as a deployed function, on AWS Lambda or on the
|
|
47
|
+
* active provider's platform (provider-netlify: FRIGG_PROVIDER=netlify, set by
|
|
48
|
+
* its generated entry points), and not under a local emulator or test runner.
|
|
49
|
+
* One rule for encryption and queue authentication: core/providers/
|
|
50
|
+
* runtime-detection asks the provider's detect(), and fails closed when a
|
|
51
|
+
* named non-AWS provider cannot be loaded.
|
|
52
|
+
*
|
|
53
|
+
* @param {Object} [env=process.env]
|
|
54
|
+
* @returns {boolean}
|
|
55
|
+
*/
|
|
56
|
+
function isDeployedRuntime(env = process.env) {
|
|
57
|
+
return isDeployedProviderRuntime(env);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function missingKeyMessage(stage) {
|
|
61
|
+
return (
|
|
62
|
+
`[Frigg] No field-level encryption key is configured for stage "${stage}". ` +
|
|
63
|
+
'A deployed Frigg app will not write credentials and other sensitive fields in plaintext. ' +
|
|
64
|
+
"Fix: set encryption: { fieldLevelEncryptionMethod: 'kms' } in the app definition and redeploy " +
|
|
65
|
+
'(Frigg creates or discovers a KMS key and sets KMS_KEY_ARN), ' +
|
|
66
|
+
'or provide AES_KEY_ID and AES_KEY (32 characters) in the Lambda environment. ' +
|
|
67
|
+
`To run this stage without encryption on purpose, set ${OPT_OUT_VAR}=true ` +
|
|
68
|
+
"(or encryption: { fieldLevelEncryptionMethod: 'none' } in the app definition)."
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function incompleteAesMessage(stage) {
|
|
73
|
+
return (
|
|
74
|
+
`[Frigg] AES_KEY_ID is set but AES_KEY is not (stage "${stage}"). ` +
|
|
75
|
+
'Provide AES_KEY (32 characters) alongside AES_KEY_ID, ' +
|
|
76
|
+
"or use KMS with encryption: { fieldLevelEncryptionMethod: 'kms' }."
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Resolves the encryption configuration without side effects.
|
|
82
|
+
*
|
|
83
|
+
* @param {Object} [env=process.env]
|
|
84
|
+
* @returns {{
|
|
85
|
+
* enabled: boolean,
|
|
86
|
+
* method: 'kms'|'aes'|undefined,
|
|
87
|
+
* mode: 'kms'|'aes'|'none',
|
|
88
|
+
* runtime: 'deployed'|'local',
|
|
89
|
+
* stage: string,
|
|
90
|
+
* bypassed: boolean,
|
|
91
|
+
* optedOut: boolean,
|
|
92
|
+
* optOutIgnored: boolean,
|
|
93
|
+
* hasKMS: boolean,
|
|
94
|
+
* hasAES: boolean,
|
|
95
|
+
* error: string|null,
|
|
96
|
+
* }} `error` is set when a deployed runtime has no usable key.
|
|
97
|
+
*/
|
|
98
|
+
function resolveEncryptionConfig(env = process.env) {
|
|
99
|
+
const stage = env.STAGE || env.NODE_ENV || 'development';
|
|
100
|
+
const runtime = isDeployedRuntime(env) ? 'deployed' : 'local';
|
|
101
|
+
const hasKMS = isSet(env.KMS_KEY_ARN);
|
|
102
|
+
const hasAES = isSet(env.AES_KEY_ID);
|
|
103
|
+
const optOutRequested = isTrue(env[OPT_OUT_VAR]);
|
|
104
|
+
|
|
105
|
+
const base = {
|
|
106
|
+
enabled: false,
|
|
107
|
+
method: undefined,
|
|
108
|
+
mode: 'none',
|
|
109
|
+
runtime,
|
|
110
|
+
stage,
|
|
111
|
+
bypassed: false,
|
|
112
|
+
optedOut: false,
|
|
113
|
+
optOutIgnored: false,
|
|
114
|
+
hasKMS,
|
|
115
|
+
hasAES,
|
|
116
|
+
error: null,
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
if (runtime === 'local') {
|
|
120
|
+
if (LOCAL_BYPASS_STAGES.includes(String(stage).toLowerCase())) {
|
|
121
|
+
return { ...base, bypassed: true };
|
|
122
|
+
}
|
|
123
|
+
if (hasKMS || hasAES) {
|
|
124
|
+
const method = hasKMS ? 'kms' : 'aes';
|
|
125
|
+
return { ...base, enabled: true, method, mode: method };
|
|
126
|
+
}
|
|
127
|
+
return base;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const hasCompleteAES = hasAES && isSet(env.AES_KEY);
|
|
131
|
+
if (hasKMS || hasCompleteAES) {
|
|
132
|
+
const method = hasKMS ? 'kms' : 'aes';
|
|
133
|
+
return {
|
|
134
|
+
...base,
|
|
135
|
+
enabled: true,
|
|
136
|
+
method,
|
|
137
|
+
mode: method,
|
|
138
|
+
optOutIgnored: optOutRequested,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (optOutRequested) {
|
|
143
|
+
return { ...base, optedOut: true };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
...base,
|
|
148
|
+
error: hasAES ? incompleteAesMessage(stage) : missingKeyMessage(stage),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const warned = new Set();
|
|
153
|
+
|
|
154
|
+
function warnOnce(key, message) {
|
|
155
|
+
if (warned.has(key)) return;
|
|
156
|
+
warned.add(key);
|
|
157
|
+
logger.warn(message);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Resolves the encryption configuration for use: throws when a deployed
|
|
162
|
+
* runtime has no usable key, and warns once per process (once per Lambda
|
|
163
|
+
* cold start) when encryption is explicitly disabled.
|
|
164
|
+
*
|
|
165
|
+
* @param {Object} [env=process.env]
|
|
166
|
+
* @returns {ReturnType<typeof resolveEncryptionConfig>}
|
|
167
|
+
* @throws {EncryptionConfigurationError}
|
|
168
|
+
*/
|
|
169
|
+
function getEncryptionConfig(env = process.env) {
|
|
170
|
+
const config = resolveEncryptionConfig(env);
|
|
171
|
+
|
|
172
|
+
if (config.error) {
|
|
173
|
+
throw new EncryptionConfigurationError(config.error);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (config.optedOut) {
|
|
177
|
+
warnOnce(
|
|
178
|
+
'opted-out',
|
|
179
|
+
`[Frigg] ${OPT_OUT_VAR}=true: field-level encryption is OFF for stage "${config.stage}". ` +
|
|
180
|
+
'Credentials and other sensitive fields are stored in PLAINTEXT. ' +
|
|
181
|
+
`Remove ${OPT_OUT_VAR} and configure a key (fieldLevelEncryptionMethod: 'kms') to encrypt them.`
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (config.optOutIgnored) {
|
|
186
|
+
warnOnce(
|
|
187
|
+
'opt-out-ignored',
|
|
188
|
+
`[Frigg] ${OPT_OUT_VAR}=true is ignored because an encryption key is configured; ` +
|
|
189
|
+
`fields are encrypted with ${config.method.toUpperCase()}. ` +
|
|
190
|
+
'Turning encryption off while a key is present would leave encrypted data unreadable.'
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (config.runtime === 'local' && !config.enabled && !config.bypassed) {
|
|
195
|
+
warnOnce(
|
|
196
|
+
'local-no-keys',
|
|
197
|
+
`No encryption keys configured (KMS_KEY_ARN or AES_KEY_ID) for local stage "${config.stage}". ` +
|
|
198
|
+
'Field-level encryption disabled for this local run. ' +
|
|
199
|
+
'A deployed stage without a key refuses to start.'
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return config;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Test helper: let the once-per-process warnings fire again. */
|
|
207
|
+
function resetEncryptionConfigWarnings() {
|
|
208
|
+
warned.clear();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
module.exports = {
|
|
212
|
+
EncryptionConfigurationError,
|
|
213
|
+
LOCAL_BYPASS_STAGES,
|
|
214
|
+
OPT_OUT_VAR,
|
|
215
|
+
getEncryptionConfig,
|
|
216
|
+
isDeployedRuntime,
|
|
217
|
+
resetEncryptionConfigWarnings,
|
|
218
|
+
resolveEncryptionConfig,
|
|
219
|
+
};
|
|
@@ -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
|
-
|
|
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
|
|
178
|
-
|
|
179
|
-
|
|
191
|
+
const moduleDefinitions = getEntityTypeDefinitions(
|
|
192
|
+
getEntityTypeRegistry({ integrations, entities })
|
|
193
|
+
);
|
|
180
194
|
const credentialFields = extractCredentialFieldsFromModules(moduleDefinitions);
|
|
181
195
|
|
|
182
|
-
|
|
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
|
-
|
|
188
|
-
|
|
189
|
-
}
|
|
212
|
+
...customSchema,
|
|
213
|
+
Credential: { ...customSchema.Credential, fields },
|
|
190
214
|
};
|
|
191
215
|
|
|
192
216
|
logger.info(
|
|
193
|
-
`Registering module-level encryption for ${
|
|
217
|
+
`Registering module-level encryption for ${fields.length} credential fields`
|
|
194
218
|
);
|
|
195
219
|
|
|
196
220
|
registerCustomSchema(moduleSchema);
|
|
@@ -205,22 +229,80 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
205
229
|
*
|
|
206
230
|
* Used by both Prisma (MongoDB/PostgreSQL) and DocumentDB encryption services.
|
|
207
231
|
*/
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
232
|
+
/**
|
|
233
|
+
* Registers encryption schemas declared by app-level extensions
|
|
234
|
+
* (`appDefinition.coreExtensions[].encryption`), e.g. the db-credentials
|
|
235
|
+
* extension's `OAuthAppCredential.clientSecret`.
|
|
236
|
+
*
|
|
237
|
+
* @param {Array<Object>} extensions - Normalized extensions (extension-loader)
|
|
238
|
+
*/
|
|
239
|
+
function loadExtensionEncryptionSchemas(extensions) {
|
|
240
|
+
if (!extensions || !Array.isArray(extensions) || extensions.length === 0) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
for (const ext of extensions) {
|
|
245
|
+
if (!ext.encryption || typeof ext.encryption !== 'object') {
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const schema = {};
|
|
250
|
+
for (const [modelName, config] of Object.entries(ext.encryption)) {
|
|
251
|
+
if (config && Array.isArray(config.fields) && config.fields.length > 0) {
|
|
252
|
+
schema[modelName] = { fields: config.fields };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
213
255
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
256
|
+
if (Object.keys(schema).length > 0) {
|
|
257
|
+
logger.info(
|
|
258
|
+
`Registering encryption schema from extension "${ext.name}" for models: ${Object.keys(schema).join(', ')}`
|
|
259
|
+
);
|
|
260
|
+
// registerCustomSchema replaces the registered schema, so merge:
|
|
261
|
+
// an extension adds its models to the app's encryption.schema
|
|
262
|
+
// rather than dropping it.
|
|
263
|
+
const merged = { ...customSchema };
|
|
264
|
+
for (const [modelName, config] of Object.entries(schema)) {
|
|
265
|
+
const existing = merged[modelName]?.fields || [];
|
|
266
|
+
merged[modelName] = {
|
|
267
|
+
...merged[modelName],
|
|
268
|
+
fields: [...new Set([...existing, ...config.fields])],
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
registerCustomSchema(merged);
|
|
217
272
|
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
218
275
|
|
|
219
|
-
|
|
220
|
-
|
|
276
|
+
function readAppDefinitionForEncryption() {
|
|
277
|
+
// Lazy require to avoid circular dependency issues
|
|
278
|
+
const {
|
|
279
|
+
getPresetAppDefinition,
|
|
280
|
+
} = require('../../handlers/app-definition-loader');
|
|
281
|
+
// A definition preset with setAppDefinition() (provider-netlify's
|
|
282
|
+
// preamble) wins: on Netlify process.cwd() cannot find the backend.
|
|
283
|
+
const preset = getPresetAppDefinition();
|
|
284
|
+
if (preset) {
|
|
285
|
+
return preset;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const path = require('node:path');
|
|
289
|
+
const { findNearestBackendPackageJson } = require('../../utils');
|
|
290
|
+
|
|
291
|
+
const backendPackagePath = findNearestBackendPackageJson();
|
|
292
|
+
if (!backendPackagePath) {
|
|
293
|
+
return null; // No backend found, skip custom schema
|
|
294
|
+
}
|
|
221
295
|
|
|
222
|
-
|
|
223
|
-
|
|
296
|
+
const backendDir = path.dirname(backendPackagePath);
|
|
297
|
+
const backendIndexPath = path.join(backendDir, 'index.js');
|
|
298
|
+
|
|
299
|
+
const backendModule = require(backendIndexPath);
|
|
300
|
+
return backendModule?.Definition || null;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function loadCustomEncryptionSchema() {
|
|
304
|
+
try {
|
|
305
|
+
const appDefinition = readAppDefinitionForEncryption();
|
|
224
306
|
|
|
225
307
|
if (!appDefinition) {
|
|
226
308
|
return; // No app definition found
|
|
@@ -240,12 +322,26 @@ function loadCustomEncryptionSchema() {
|
|
|
240
322
|
registerEncryptionOptOut(disable);
|
|
241
323
|
}
|
|
242
324
|
|
|
325
|
+
// Load app-level extension encryption schemas. Before the module
|
|
326
|
+
// schemas: loadModuleEncryptionSchemas currently throws (see the
|
|
327
|
+
// NOTE inside it) and the throw would skip anything after it.
|
|
328
|
+
const { loadExtensions } = require('../../extensions/extension-loader');
|
|
329
|
+
const extensions = loadExtensions(appDefinition);
|
|
330
|
+
if (extensions.length > 0) {
|
|
331
|
+
loadExtensionEncryptionSchemas(extensions);
|
|
332
|
+
}
|
|
333
|
+
|
|
243
334
|
// Load module-level encryption schemas from integrations
|
|
244
335
|
const integrations = appDefinition.integrations;
|
|
245
|
-
if (
|
|
246
|
-
loadModuleEncryptionSchemas(
|
|
336
|
+
if (Array.isArray(integrations) || appDefinition.entities) {
|
|
337
|
+
loadModuleEncryptionSchemas(
|
|
338
|
+
Array.isArray(integrations) ? integrations : [],
|
|
339
|
+
appDefinition.entities
|
|
340
|
+
);
|
|
247
341
|
}
|
|
248
342
|
} catch (error) {
|
|
343
|
+
// A bad entity registry is a configuration error, not "no custom schema".
|
|
344
|
+
if (error instanceof EntityRegistryError) throw error;
|
|
249
345
|
// Silently ignore errors - custom schema is optional
|
|
250
346
|
// This handles cases like:
|
|
251
347
|
// - Backend package.json not found (tests, standalone usage)
|
|
@@ -396,6 +492,7 @@ module.exports = {
|
|
|
396
492
|
registerEncryptionOptOut,
|
|
397
493
|
loadCustomEncryptionSchema,
|
|
398
494
|
loadModuleEncryptionSchemas,
|
|
495
|
+
loadExtensionEncryptionSchemas,
|
|
399
496
|
extractCredentialFieldsFromModules,
|
|
400
497
|
validateCustomSchema,
|
|
401
498
|
validateOptOut,
|
|
@@ -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
|
-
|
|
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
|
|
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 };
|
|
@@ -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 };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Prisma `where` fragment for an `organizationId` on MongoDB (ADR-056
|
|
3
|
+
* §3.6), shared by the entity and integration adapters.
|
|
4
|
+
*
|
|
5
|
+
* Prisma on MongoDB: `null` matches only an explicit null and `isSet: false`
|
|
6
|
+
* only a missing field. A row written before the column existed is the common
|
|
7
|
+
* "no organization" case, so `null` here means both.
|
|
8
|
+
*/
|
|
9
|
+
function organizationWhere(organizationId) {
|
|
10
|
+
if (organizationId === null) {
|
|
11
|
+
return {
|
|
12
|
+
OR: [{ organizationId: null }, { organizationId: { isSet: false } }],
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
return { organizationId };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
module.exports = { organizationWhere };
|