@friggframework/core 2.0.0--canary.704.79d9a63.0 → 2.0.0--canary.686.e94de4d.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/CLAUDE.md +28 -40
- package/README.md +105 -0
- package/application/commands/entity-commands.js +60 -18
- package/application/commands/integration-commands.js +20 -73
- 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 -0
- package/database/encryption/README.md +76 -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 +93 -12
- package/database/encryption/integration-mapping-encryption.js +1 -1
- 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 +187 -0
- package/extensions/index.js +41 -0
- package/extensions/initialize-app.js +123 -0
- package/extensions/route-mounter.js +103 -0
- package/extensions/schema-composer.js +188 -0
- package/generated/prisma-mongodb/edge.js +43 -4
- package/generated/prisma-mongodb/index-browser.js +40 -1
- package/generated/prisma-mongodb/index.d.ts +4761 -133
- package/generated/prisma-mongodb/index.js +43 -4
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +92 -0
- package/generated/prisma-mongodb/wasm.js +43 -4
- package/generated/prisma-postgresql/edge.js +43 -4
- package/generated/prisma-postgresql/index-browser.js +40 -1
- package/generated/prisma-postgresql/index.d.ts +4961 -28
- package/generated/prisma-postgresql/index.js +43 -4
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +87 -0
- package/generated/prisma-postgresql/wasm.js +43 -4
- package/handlers/WEBHOOKS.md +0 -29
- package/handlers/app-definition-loader.js +121 -19
- package/handlers/app-handler-helpers.js +25 -3
- package/handlers/backend-utils.js +31 -25
- 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 +102 -64
- package/handlers/workers/integration-defined-workers.js +5 -2
- package/index.js +65 -3
- 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 -0
- package/integrations/integration-base.js +0 -29
- package/integrations/integration-router.js +131 -96
- 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 +35 -35
- package/integrations/repositories/integration-repository-interface.js +17 -31
- package/integrations/repositories/integration-repository-mongo.js +60 -129
- package/integrations/repositories/integration-repository-postgres.js +62 -134
- 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 +72 -75
- package/integrations/use-cases/dispatch-ongoing-syncs.js +100 -0
- package/integrations/use-cases/get-integrations-for-user.js +80 -40
- 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/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 +408 -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-errors.js +20 -0
- package/modules/proxy/proxy-path.js +179 -0
- package/modules/proxy/proxy-policy.js +248 -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 +244 -0
- package/modules/requester/requester.js +27 -2
- 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 +286 -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/modules/utils/map-module-dto.js +3 -5
- package/package.json +6 -5
- package/prisma-mongodb/schema.prisma +92 -0
- 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 +87 -0
- 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/sqs-queue-client.js +81 -0
- package/types/index.d.ts +2 -0
- package/types/modules/index.d.ts +197 -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/tests/doubles/test-user-repository.js +1 -1
- 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-bearer-token.js +2 -7
- 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/integrations/use-cases/add-entities-to-integration.js +0 -92
- package/integrations/use-cases/remove-entities-from-integration.js +0 -70
- package/integrations/utils/assert-entity-ids-input.js +0 -42
- package/modules/utils/to-credential-id.js +0 -14
|
@@ -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
|
-
- ✅ **
|
|
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
|
-
|
|
110
|
+
### When Encryption Runs
|
|
111
111
|
|
|
112
|
-
|
|
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
|
-
|
|
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
115
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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
|
|
130
|
+
|
|
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
|
|
140
|
+
|
|
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
|
+
};
|
|
119
147
|
```
|
|
120
148
|
|
|
121
|
-
|
|
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
|
|
|
@@ -553,8 +581,8 @@ class MyRepositoryDocumentDB {
|
|
|
553
581
|
|
|
554
582
|
#### Configuration
|
|
555
583
|
|
|
556
|
-
Uses the same
|
|
557
|
-
- `STAGE`:
|
|
584
|
+
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`.
|
|
585
|
+
- `STAGE`: Skips encryption for dev/test/local on local runs only
|
|
558
586
|
- `KMS_KEY_ARN`: AWS KMS encryption (production)
|
|
559
587
|
- `AES_KEY_ID` + `AES_KEY`: AES encryption (fallback)
|
|
560
588
|
|
|
@@ -615,10 +643,27 @@ curl http://localhost:3000/health/test-encryption
|
|
|
615
643
|
"encryptionWorks": true
|
|
616
644
|
}
|
|
617
645
|
|
|
618
|
-
# Response
|
|
646
|
+
# Response on a local run with STAGE=dev:
|
|
619
647
|
{
|
|
620
648
|
"status": "disabled",
|
|
621
|
-
"
|
|
649
|
+
"bypassed": true,
|
|
650
|
+
"runtime": "local",
|
|
651
|
+
"testResult": "Encryption bypassed for this stage"
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
# Response in a deployed stage with no key (the app itself refuses to start):
|
|
655
|
+
{
|
|
656
|
+
"status": "unhealthy",
|
|
657
|
+
"mode": "none",
|
|
658
|
+
"runtime": "deployed",
|
|
659
|
+
"testResult": "[Frigg] No field-level encryption key is configured for stage \"dev\". ..."
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
# Response in a deployed stage with FRIGG_ENCRYPTION_DISABLED=true and no key:
|
|
663
|
+
{
|
|
664
|
+
"status": "disabled",
|
|
665
|
+
"optedOut": true,
|
|
666
|
+
"testResult": "Encryption explicitly disabled (FRIGG_ENCRYPTION_DISABLED=true); sensitive fields are stored in plaintext"
|
|
622
667
|
}
|
|
623
668
|
```
|
|
624
669
|
|
|
@@ -732,9 +777,10 @@ FRIGG_LOG_LEVEL=INFO
|
|
|
732
777
|
**Check environment variables:**
|
|
733
778
|
|
|
734
779
|
```bash
|
|
735
|
-
echo $STAGE # Should be 'production' (not dev/test/local)
|
|
736
780
|
echo $KMS_KEY_ARN # Should be set (for KMS)
|
|
737
|
-
echo $AES_KEY_ID
|
|
781
|
+
echo $AES_KEY_ID $AES_KEY # Both should be set (for AES)
|
|
782
|
+
echo $STAGE # Local runs only: dev/test/local skip encryption
|
|
783
|
+
echo $FRIGG_ENCRYPTION_DISABLED # Should be unset
|
|
738
784
|
```
|
|
739
785
|
|
|
740
786
|
**Check console logs:**
|
|
@@ -749,6 +795,22 @@ or
|
|
|
749
795
|
[Frigg] Field-level encryption disabled
|
|
750
796
|
```
|
|
751
797
|
|
|
798
|
+
### Deployed Stage Refuses to Start
|
|
799
|
+
|
|
800
|
+
**Error: "EncryptionConfigurationError: [Frigg] No field-level encryption key is configured for stage ..."**
|
|
801
|
+
|
|
802
|
+
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:
|
|
803
|
+
|
|
804
|
+
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.
|
|
805
|
+
2. Provide `AES_KEY_ID` and `AES_KEY` (32 characters) through the app definition's `environment` and the deploy environment.
|
|
806
|
+
3. To keep the stage in plaintext on purpose, set `encryption: { fieldLevelEncryptionMethod: 'none' }` (or `FRIGG_ENCRYPTION_DISABLED=true`).
|
|
807
|
+
|
|
808
|
+
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.
|
|
809
|
+
|
|
810
|
+
**Error: "[Frigg] AES_KEY_ID is set but AES_KEY is not"**
|
|
811
|
+
|
|
812
|
+
Provide `AES_KEY` alongside `AES_KEY_ID`, or switch to KMS.
|
|
813
|
+
|
|
752
814
|
### AWS KMS Errors
|
|
753
815
|
|
|
754
816
|
**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. **
|
|
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
|
+
};
|
|
@@ -39,6 +39,12 @@ const CORE_ENCRYPTION_SCHEMA = {
|
|
|
39
39
|
Token: {
|
|
40
40
|
fields: ['token'],
|
|
41
41
|
},
|
|
42
|
+
|
|
43
|
+
// Multi-step authorization (Management API v2): earlier steps can collect
|
|
44
|
+
// emails, usernames or one-time codes.
|
|
45
|
+
AuthorizationSession: {
|
|
46
|
+
fields: ['stepData'],
|
|
47
|
+
},
|
|
42
48
|
};
|
|
43
49
|
|
|
44
50
|
let customSchema = {};
|
|
@@ -174,6 +180,13 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
174
180
|
return;
|
|
175
181
|
}
|
|
176
182
|
|
|
183
|
+
// NOTE: this path does not exist ('../integrations' resolves to
|
|
184
|
+
// database/integrations), so today this function throws MODULE_NOT_FOUND,
|
|
185
|
+
// loadCustomEncryptionSchema swallows it, and module credentialFields are
|
|
186
|
+
// effectively NOT registered. Fixing it changes which fields are encrypted
|
|
187
|
+
// and needs a decrypt that tolerates plaintext, so it ships separately:
|
|
188
|
+
// branch claude/internal-mcp-03b-module-credential-encryption. Left as is
|
|
189
|
+
// here on purpose (ADR-059 must not change what gets encrypted).
|
|
177
190
|
const { getModulesDefinitionFromIntegrationClasses } = require('../integrations/utils/map-integration-dto');
|
|
178
191
|
|
|
179
192
|
const moduleDefinitions = getModulesDefinitionFromIntegrationClasses(integrations);
|
|
@@ -205,22 +218,80 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
205
218
|
*
|
|
206
219
|
* Used by both Prisma (MongoDB/PostgreSQL) and DocumentDB encryption services.
|
|
207
220
|
*/
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
221
|
+
/**
|
|
222
|
+
* Registers encryption schemas declared by app-level extensions
|
|
223
|
+
* (`appDefinition.coreExtensions[].encryption`), e.g. the db-credentials
|
|
224
|
+
* extension's `OAuthAppCredential.clientSecret`.
|
|
225
|
+
*
|
|
226
|
+
* @param {Array<Object>} extensions - Normalized extensions (extension-loader)
|
|
227
|
+
*/
|
|
228
|
+
function loadExtensionEncryptionSchemas(extensions) {
|
|
229
|
+
if (!extensions || !Array.isArray(extensions) || extensions.length === 0) {
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
for (const ext of extensions) {
|
|
234
|
+
if (!ext.encryption || typeof ext.encryption !== 'object') {
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const schema = {};
|
|
239
|
+
for (const [modelName, config] of Object.entries(ext.encryption)) {
|
|
240
|
+
if (config && Array.isArray(config.fields) && config.fields.length > 0) {
|
|
241
|
+
schema[modelName] = { fields: config.fields };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
213
244
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
245
|
+
if (Object.keys(schema).length > 0) {
|
|
246
|
+
logger.info(
|
|
247
|
+
`Registering encryption schema from extension "${ext.name}" for models: ${Object.keys(schema).join(', ')}`
|
|
248
|
+
);
|
|
249
|
+
// registerCustomSchema replaces the registered schema, so merge:
|
|
250
|
+
// an extension adds its models to the app's encryption.schema
|
|
251
|
+
// rather than dropping it.
|
|
252
|
+
const merged = { ...customSchema };
|
|
253
|
+
for (const [modelName, config] of Object.entries(schema)) {
|
|
254
|
+
const existing = merged[modelName]?.fields || [];
|
|
255
|
+
merged[modelName] = {
|
|
256
|
+
...merged[modelName],
|
|
257
|
+
fields: [...new Set([...existing, ...config.fields])],
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
registerCustomSchema(merged);
|
|
217
261
|
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
218
264
|
|
|
219
|
-
|
|
220
|
-
|
|
265
|
+
function readAppDefinitionForEncryption() {
|
|
266
|
+
// Lazy require to avoid circular dependency issues
|
|
267
|
+
const {
|
|
268
|
+
getPresetAppDefinition,
|
|
269
|
+
} = require('../../handlers/app-definition-loader');
|
|
270
|
+
// A definition preset with setAppDefinition() (provider-netlify's
|
|
271
|
+
// preamble) wins: on Netlify process.cwd() cannot find the backend.
|
|
272
|
+
const preset = getPresetAppDefinition();
|
|
273
|
+
if (preset) {
|
|
274
|
+
return preset;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const path = require('node:path');
|
|
278
|
+
const { findNearestBackendPackageJson } = require('../../utils');
|
|
279
|
+
|
|
280
|
+
const backendPackagePath = findNearestBackendPackageJson();
|
|
281
|
+
if (!backendPackagePath) {
|
|
282
|
+
return null; // No backend found, skip custom schema
|
|
283
|
+
}
|
|
221
284
|
|
|
222
|
-
|
|
223
|
-
|
|
285
|
+
const backendDir = path.dirname(backendPackagePath);
|
|
286
|
+
const backendIndexPath = path.join(backendDir, 'index.js');
|
|
287
|
+
|
|
288
|
+
const backendModule = require(backendIndexPath);
|
|
289
|
+
return backendModule?.Definition || null;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function loadCustomEncryptionSchema() {
|
|
293
|
+
try {
|
|
294
|
+
const appDefinition = readAppDefinitionForEncryption();
|
|
224
295
|
|
|
225
296
|
if (!appDefinition) {
|
|
226
297
|
return; // No app definition found
|
|
@@ -240,6 +311,15 @@ function loadCustomEncryptionSchema() {
|
|
|
240
311
|
registerEncryptionOptOut(disable);
|
|
241
312
|
}
|
|
242
313
|
|
|
314
|
+
// Load app-level extension encryption schemas. Before the module
|
|
315
|
+
// schemas: loadModuleEncryptionSchemas currently throws (see the
|
|
316
|
+
// NOTE inside it) and the throw would skip anything after it.
|
|
317
|
+
const { loadExtensions } = require('../../extensions/extension-loader');
|
|
318
|
+
const extensions = loadExtensions(appDefinition);
|
|
319
|
+
if (extensions.length > 0) {
|
|
320
|
+
loadExtensionEncryptionSchemas(extensions);
|
|
321
|
+
}
|
|
322
|
+
|
|
243
323
|
// Load module-level encryption schemas from integrations
|
|
244
324
|
const integrations = appDefinition.integrations;
|
|
245
325
|
if (integrations && Array.isArray(integrations)) {
|
|
@@ -396,6 +476,7 @@ module.exports = {
|
|
|
396
476
|
registerEncryptionOptOut,
|
|
397
477
|
loadCustomEncryptionSchema,
|
|
398
478
|
loadModuleEncryptionSchemas,
|
|
479
|
+
loadExtensionEncryptionSchemas,
|
|
399
480
|
extractCredentialFieldsFromModules,
|
|
400
481
|
validateCustomSchema,
|
|
401
482
|
validateOptOut,
|
|
@@ -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 };
|