@friggframework/core 2.0.0--canary.682.451c957.0 → 2.0.0--canary.666.89f6545.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 +41 -3
- package/README.md +0 -105
- package/application/commands/README.md +17 -11
- package/application/commands/entity-commands.js +18 -60
- package/application/commands/integration-commands.js +73 -20
- package/application/commands/user-commands.js +5 -17
- package/application/index.js +2 -6
- package/credential/repositories/credential-repository-documentdb.js +0 -34
- package/credential/repositories/credential-repository-interface.js +0 -15
- package/credential/repositories/credential-repository-mongo.js +0 -23
- package/credential/repositories/credential-repository-postgres.js +0 -28
- package/database/documentdb-encryption-service.js +2 -33
- package/database/documentdb-utils.js +0 -2
- package/database/encryption/README.md +3 -3
- package/database/encryption/ciphertext-format.js +24 -0
- package/database/encryption/encryption-schema-registry.js +109 -42
- package/database/encryption/field-encryption-service.js +13 -16
- package/database/prisma.js +10 -1
- package/errors/index.js +4 -0
- package/errors/mapping-already-exists-error.js +14 -0
- package/generated/prisma-mongodb/edge.js +4 -31
- package/generated/prisma-mongodb/index-browser.js +1 -28
- package/generated/prisma-mongodb/index.d.ts +74 -3463
- package/generated/prisma-mongodb/index.js +4 -31
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +0 -74
- package/generated/prisma-mongodb/wasm.js +4 -31
- package/generated/prisma-postgresql/edge.js +4 -31
- package/generated/prisma-postgresql/index-browser.js +1 -28
- package/generated/prisma-postgresql/index.d.ts +51 -3631
- package/generated/prisma-postgresql/index.js +4 -31
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +0 -70
- package/generated/prisma-postgresql/wasm.js +4 -31
- package/handlers/WEBHOOKS.md +29 -0
- package/handlers/app-definition-loader.js +16 -34
- package/handlers/app-handler-helpers.js +3 -25
- package/handlers/backend-utils.js +25 -31
- package/handlers/middleware/admin-auth.js +1 -14
- package/handlers/routers/auth.js +3 -11
- package/handlers/routers/health.js +4 -11
- package/handlers/workers/integration-defined-workers.js +2 -5
- package/index.js +2 -23
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -13
- package/integrations/index.js +0 -1
- package/integrations/integration-base.js +29 -0
- package/integrations/integration-router.js +87 -129
- package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
- package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
- package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
- package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
- package/integrations/repositories/integration-mapping-repository.js +29 -0
- package/integrations/repositories/integration-repository-documentdb.js +35 -35
- package/integrations/repositories/integration-repository-interface.js +31 -17
- package/integrations/repositories/integration-repository-mongo.js +129 -60
- package/integrations/repositories/integration-repository-postgres.js +134 -62
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/tests/doubles/test-integration-repository.js +1 -12
- package/integrations/use-cases/add-entities-to-integration.js +92 -0
- package/integrations/use-cases/create-integration.js +75 -72
- package/integrations/use-cases/get-integrations-for-user.js +40 -80
- package/integrations/use-cases/index.js +1 -5
- package/integrations/use-cases/remove-entities-from-integration.js +70 -0
- package/integrations/utils/assert-entity-ids-input.js +42 -0
- package/integrations/utils/map-integration-dto.js +15 -47
- package/jest-setup.js +13 -2
- package/jest-teardown.js +5 -2
- package/jest.config.js +4 -0
- package/jest.db.config.js +23 -0
- package/modules/index.js +0 -14
- package/modules/repositories/module-repository-documentdb.js +4 -48
- package/modules/repositories/module-repository-interface.js +2 -19
- package/modules/repositories/module-repository-mongo.js +73 -65
- package/modules/repositories/module-repository-postgres.js +73 -64
- package/modules/requester/requester.js +2 -27
- package/modules/use-cases/create-entity-from-credential.js +28 -36
- package/modules/use-cases/get-entities-for-user.js +5 -16
- package/modules/use-cases/get-entity-options-by-id.js +3 -9
- package/modules/use-cases/get-module.js +24 -19
- package/modules/use-cases/process-authorization-callback.js +18 -52
- package/modules/use-cases/refresh-entity-options.js +3 -9
- package/modules/use-cases/test-module-auth.js +3 -9
- package/modules/utils/map-module-dto.js +6 -10
- package/modules/utils/to-credential-id.js +14 -0
- package/package.json +8 -6
- package/prisma-mongodb/schema.prisma +0 -74
- package/prisma-postgresql/schema.prisma +0 -70
- package/queues/queuer-util.js +6 -5
- package/types/index.d.ts +0 -2
- package/user/repositories/user-repository-documentdb.js +2 -27
- package/user/repositories/user-repository-interface.js +0 -18
- package/user/repositories/user-repository-mongo.js +0 -24
- package/user/repositories/user-repository-postgres.js +0 -18
- package/user/tests/doubles/test-user-repository.js +1 -1
- package/user/use-cases/get-user-from-adopter-jwt.js +125 -86
- package/user/use-cases/get-user-from-bearer-token.js +7 -2
- package/user/use-cases/get-user-from-x-frigg-headers.js +80 -83
- package/user/user.js +0 -27
- package/credential/use-cases/credential-operations-for-user.js +0 -117
- package/credential/use-cases/reauthorize-credential-for-user.js +0 -66
- package/database/organization-where.js +0 -18
- package/database/unique-violation.js +0 -25
- package/integrations/repositories/integration-not-found.js +0 -14
- package/integrations/use-cases/integration-operations-for-user.js +0 -246
- package/integrations/use-cases/resolve-integration-ownership.js +0 -177
- package/management-api/create-management-api-router.js +0 -49
- package/management-api/error-response.js +0 -116
- package/management-api/management-api-config.js +0 -85
- package/management-api/meta-router.js +0 -57
- package/management-api/openapi/build-openapi.js +0 -144
- package/management-api/openapi/components.js +0 -407
- package/management-api/openapi/v1-operations.js +0 -83
- package/management-api/openapi/v2-operations.js +0 -261
- package/management-api/route-registry.js +0 -294
- package/management-api/test-support/http-client.js +0 -39
- package/management-api/use-cases/get-management-api-meta.js +0 -57
- package/management-api/v1-deprecation.js +0 -120
- package/management-api/v2/create-v2-router.js +0 -85
- package/management-api/v2/dependencies.js +0 -279
- package/management-api/v2/dto.js +0 -143
- package/management-api/v2/handlers/authorization.js +0 -94
- package/management-api/v2/handlers/credentials.js +0 -29
- package/management-api/v2/handlers/entities.js +0 -77
- package/management-api/v2/handlers/integrations.js +0 -128
- package/management-api/v2/handlers/proxy.js +0 -34
- package/management-api/v2/request.js +0 -85
- package/management-api/v2/test-support/fake-dependencies.js +0 -103
- package/modules/domain/authorization-session.js +0 -144
- package/modules/entity-scope.js +0 -15
- package/modules/entity-type-registry.js +0 -311
- package/modules/proxy/proxy-errors.js +0 -20
- package/modules/proxy/proxy-path.js +0 -179
- package/modules/proxy/proxy-policy.js +0 -248
- package/modules/repositories/authorization-session-repository-documentdb.js +0 -112
- package/modules/repositories/authorization-session-repository-factory.js +0 -31
- package/modules/repositories/authorization-session-repository-interface.js +0 -47
- package/modules/repositories/authorization-session-repository-prisma.js +0 -87
- package/modules/requester/proxy-request.js +0 -244
- package/modules/scope-config.js +0 -155
- package/modules/scope-policy.js +0 -80
- package/modules/scope-resolution.js +0 -277
- package/modules/scope-visibility.js +0 -165
- package/modules/tests/doubles/in-memory-authorization-session-repository.js +0 -45
- package/modules/tests/doubles/ownership-matching.js +0 -18
- package/modules/use-cases/authorize-entity-for-user.js +0 -59
- package/modules/use-cases/entity-operations-for-user.js +0 -157
- package/modules/use-cases/entity-types.js +0 -139
- package/modules/use-cases/execute-entity-proxy-request.js +0 -254
- package/modules/use-cases/get-authorization-requirements.js +0 -100
- package/modules/use-cases/get-entity-module-for-user.js +0 -106
- package/modules/use-cases/multi-step-authorization.js +0 -326
- package/modules/utils/public-entity.js +0 -59
- package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +0 -28
- package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +0 -26
- package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +0 -25
- package/types/modules/index.d.ts +0 -155
- package/types/user/index.d.ts +0 -117
- package/user/adopter-jwt-config.js +0 -177
- package/user/adopter-jwt-errors.js +0 -59
- package/user/adopter-token-verifier.js +0 -122
- package/user/app-user-helpers.js +0 -97
- package/user/create-user-authentication.js +0 -64
- package/user/membership.js +0 -51
- package/user/repositories/organization-membership-record.js +0 -19
- package/user/repositories/organization-membership-repository-documentdb.js +0 -106
- package/user/repositories/organization-membership-repository-factory.js +0 -42
- package/user/repositories/organization-membership-repository-interface.js +0 -57
- package/user/repositories/organization-membership-repository-mongo.js +0 -13
- package/user/repositories/organization-membership-repository-postgres.js +0 -29
- package/user/repositories/organization-membership-repository-prisma.js +0 -81
- package/user/tests/doubles/adopter-jwt-fixtures.js +0 -220
- package/user/use-cases/ensure-organization-membership.js +0 -92
- package/user/use-cases/find-individual-users-by-organization.js +0 -54
|
@@ -188,29 +188,6 @@ class CredentialRepositoryMongo extends CredentialRepositoryInterface {
|
|
|
188
188
|
};
|
|
189
189
|
}
|
|
190
190
|
|
|
191
|
-
/**
|
|
192
|
-
* All credentials owned by a user, newest first.
|
|
193
|
-
*
|
|
194
|
-
* @param {string} userId - User ID
|
|
195
|
-
* @returns {Promise<Array<Object>>} Credentials with string IDs
|
|
196
|
-
*/
|
|
197
|
-
async findCredentialsByUserId(userId) {
|
|
198
|
-
if (!userId) return [];
|
|
199
|
-
const credentials = await this.prisma.credential.findMany({
|
|
200
|
-
where: { userId: String(userId) },
|
|
201
|
-
orderBy: { createdAt: 'desc' },
|
|
202
|
-
});
|
|
203
|
-
return credentials.map((credential) => ({
|
|
204
|
-
...(credential.data || {}),
|
|
205
|
-
id: credential.id,
|
|
206
|
-
userId: credential.userId,
|
|
207
|
-
externalId: credential.externalId,
|
|
208
|
-
authIsValid: credential.authIsValid,
|
|
209
|
-
createdAt: credential.createdAt,
|
|
210
|
-
updatedAt: credential.updatedAt,
|
|
211
|
-
}));
|
|
212
|
-
}
|
|
213
|
-
|
|
214
191
|
/**
|
|
215
192
|
* Update a credential by ID
|
|
216
193
|
* Replaces: Credential.findByIdAndUpdate(credentialId, { $set: updates })
|
|
@@ -205,34 +205,6 @@ class CredentialRepositoryPostgres extends CredentialRepositoryInterface {
|
|
|
205
205
|
};
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
-
/**
|
|
209
|
-
* All credentials owned by a user, newest first.
|
|
210
|
-
*
|
|
211
|
-
* @param {string} userId - User ID (string from application layer)
|
|
212
|
-
* @returns {Promise<Array<Object>>} Credentials with string IDs
|
|
213
|
-
*/
|
|
214
|
-
async findCredentialsByUserId(userId) {
|
|
215
|
-
let intUserId;
|
|
216
|
-
try {
|
|
217
|
-
intUserId = this._convertId(userId);
|
|
218
|
-
} catch {
|
|
219
|
-
return [];
|
|
220
|
-
}
|
|
221
|
-
const credentials = await this.prisma.credential.findMany({
|
|
222
|
-
where: { userId: intUserId },
|
|
223
|
-
orderBy: { createdAt: 'desc' },
|
|
224
|
-
});
|
|
225
|
-
return credentials.map((credential) => ({
|
|
226
|
-
...(credential.data || {}),
|
|
227
|
-
id: credential.id.toString(),
|
|
228
|
-
userId: credential.userId?.toString(),
|
|
229
|
-
externalId: credential.externalId,
|
|
230
|
-
authIsValid: credential.authIsValid,
|
|
231
|
-
createdAt: credential.createdAt,
|
|
232
|
-
updatedAt: credential.updatedAt,
|
|
233
|
-
}));
|
|
234
|
-
}
|
|
235
|
-
|
|
236
208
|
/**
|
|
237
209
|
* Update a credential by ID
|
|
238
210
|
*
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const { Cryptor } = require('../encrypt/Cryptor');
|
|
2
|
+
const { isEncryptedEnvelope } = require('./encryption/ciphertext-format');
|
|
2
3
|
const {
|
|
3
4
|
getEncryptedFields,
|
|
4
5
|
getFieldsToEncryptOnWrite,
|
|
@@ -295,39 +296,7 @@ class DocumentDBEncryptionService {
|
|
|
295
296
|
* _isEncryptedValue({}) // false
|
|
296
297
|
*/
|
|
297
298
|
_isEncryptedValue(value) {
|
|
298
|
-
|
|
299
|
-
if (typeof value !== 'string') {
|
|
300
|
-
return false;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
// Must have exactly 4 colon-separated parts
|
|
304
|
-
const parts = value.split(':');
|
|
305
|
-
if (parts.length !== 4) {
|
|
306
|
-
return false;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// Enhanced validation: check for base64 pattern
|
|
310
|
-
// This prevents false positives on URLs, connection strings, etc.
|
|
311
|
-
const base64Pattern = /^[A-Za-z0-9+/=]+$/;
|
|
312
|
-
|
|
313
|
-
// All parts should be base64-encoded
|
|
314
|
-
if (!parts.every(part => base64Pattern.test(part))) {
|
|
315
|
-
return false;
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
// Encrypted values should be sufficiently long to be valid
|
|
319
|
-
// Real encrypted values from Cryptor are always >50 chars due to envelope encryption format:
|
|
320
|
-
// - keyId (base64): ~12 chars minimum
|
|
321
|
-
// - iv (base64): ~24 chars for 16-byte IV
|
|
322
|
-
// - ciphertext (base64): varies, minimum ~16 chars for small values
|
|
323
|
-
// - encryptedKey (base64): ~44 chars for 32-byte data key
|
|
324
|
-
// Total minimum: ~96 chars, so 50 is a safe lower bound
|
|
325
|
-
// This prevents false positives on non-encrypted strings that happen to have 4 colons
|
|
326
|
-
if (value.length < 50) {
|
|
327
|
-
return false;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
return true;
|
|
299
|
+
return isEncryptedEnvelope(value);
|
|
331
300
|
}
|
|
332
301
|
}
|
|
333
302
|
|
|
@@ -58,8 +58,6 @@ async function insertOne(client, collection, document) {
|
|
|
58
58
|
|
|
59
59
|
// Provide helpful context for common errors
|
|
60
60
|
if (error.code === 11000) {
|
|
61
|
-
// `code` lets callers recognise a lost race without parsing text
|
|
62
|
-
// (see database/unique-violation.js).
|
|
63
61
|
throw Object.assign(
|
|
64
62
|
new Error(`${errorMsg} - Duplicate key violation`),
|
|
65
63
|
{ code: 11000 }
|
|
@@ -508,9 +508,9 @@ return entities.map((e) => ({
|
|
|
508
508
|
|
|
509
509
|
**Verified:**
|
|
510
510
|
|
|
511
|
-
- ✅ `postgres-relation-decryption.test.js` - Proves the bug exists
|
|
512
|
-
- ✅ `postgres-decryption-fix-verification.test.js` - Verifies separate queries work
|
|
513
|
-
- ✅ `mongo-decryption-fix-verification.test.js` - Verifies fix for MongoDB
|
|
511
|
+
- ✅ `postgres-relation-decryption.db.test.js` - Proves the bug exists
|
|
512
|
+
- ✅ `postgres-decryption-fix-verification.db.test.js` - Verifies separate queries work
|
|
513
|
+
- ✅ `mongo-decryption-fix-verification.db.test.js` - Verifies fix for MongoDB
|
|
514
514
|
|
|
515
515
|
**Implementation Examples:**
|
|
516
516
|
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recognises values produced by Cryptor.encrypt():
|
|
3
|
+
* keyId:iv:ciphertext:encryptedKey
|
|
4
|
+
* keyId and encryptedKey are base64, iv and ciphertext are hex, so all four
|
|
5
|
+
* parts match the base64 alphabet. Real envelopes are well over 50
|
|
6
|
+
* characters (the encrypted data key alone is longer).
|
|
7
|
+
*
|
|
8
|
+
* Shared by the Prisma (FieldEncryptionService) and DocumentDB paths so a
|
|
9
|
+
* plaintext value that happens to contain colons (`a:b:c:d`, a URL with
|
|
10
|
+
* userinfo and a port) is never mistaken for ciphertext: on write it gets
|
|
11
|
+
* encrypted, on read it is returned as plaintext.
|
|
12
|
+
*/
|
|
13
|
+
const BASE64_PART = /^[A-Za-z0-9+/=]+$/;
|
|
14
|
+
const MIN_ENVELOPE_LENGTH = 50;
|
|
15
|
+
|
|
16
|
+
function isEncryptedEnvelope(value) {
|
|
17
|
+
if (typeof value !== 'string' || value.length < MIN_ENVELOPE_LENGTH) {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
const parts = value.split(':');
|
|
21
|
+
return parts.length === 4 && parts.every((part) => BASE64_PART.test(part));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
module.exports = { isEncryptedEnvelope };
|
|
@@ -39,12 +39,6 @@ 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
|
-
},
|
|
48
42
|
};
|
|
49
43
|
|
|
50
44
|
let customSchema = {};
|
|
@@ -152,6 +146,16 @@ function extractCredentialFieldsFromModules(moduleDefinitions) {
|
|
|
152
146
|
}
|
|
153
147
|
|
|
154
148
|
for (const field of credentialFields) {
|
|
149
|
+
// Validate entry by entry: one bad entry must not drop the
|
|
150
|
+
// module's (or any other module's) valid fields.
|
|
151
|
+
if (typeof field !== 'string' || field.trim() === '') {
|
|
152
|
+
logger.warn(
|
|
153
|
+
`Ignoring invalid encryption.credentialFields entry ${JSON.stringify(field)} ` +
|
|
154
|
+
`in module "${moduleDef.moduleName || moduleDef.name || 'unknown'}" ` +
|
|
155
|
+
'(expected a non-empty string)'
|
|
156
|
+
);
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
155
159
|
const prefixedField = field.startsWith('data.') ? field : `data.${field}`;
|
|
156
160
|
fields.push(prefixedField);
|
|
157
161
|
}
|
|
@@ -180,33 +184,46 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
180
184
|
return;
|
|
181
185
|
}
|
|
182
186
|
|
|
183
|
-
|
|
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).
|
|
190
|
-
const { getModulesDefinitionFromIntegrationClasses } = require('../integrations/utils/map-integration-dto');
|
|
187
|
+
const { getModulesDefinitionFromIntegrationClasses } = require('../../integrations/utils/map-integration-dto');
|
|
191
188
|
|
|
192
|
-
|
|
193
|
-
const
|
|
189
|
+
// Integrations without modules contribute no credential fields.
|
|
190
|
+
const integrationsWithModules = integrations.filter(
|
|
191
|
+
(integration) => integration?.Definition?.modules
|
|
192
|
+
);
|
|
193
|
+
const moduleDefinitions = getModulesDefinitionFromIntegrationClasses(
|
|
194
|
+
integrationsWithModules
|
|
195
|
+
);
|
|
196
|
+
|
|
197
|
+
// Fields the core schema already encrypts (e.g. data.api_key) are
|
|
198
|
+
// covered; registering them again would fail validation and drop every
|
|
199
|
+
// other module field with them.
|
|
200
|
+
const coreCredentialFields = CORE_ENCRYPTION_SCHEMA.Credential.fields;
|
|
201
|
+
const credentialFields = extractCredentialFieldsFromModules(
|
|
202
|
+
moduleDefinitions
|
|
203
|
+
).filter((field) => !coreCredentialFields.includes(field));
|
|
194
204
|
|
|
195
205
|
if (credentialFields.length === 0) {
|
|
196
206
|
return;
|
|
197
207
|
}
|
|
198
208
|
|
|
199
|
-
|
|
209
|
+
// Merge with whatever custom schema the app already registered rather
|
|
210
|
+
// than replacing it (registerCustomSchema overwrites).
|
|
211
|
+
const existingCredentialFields = customSchema.Credential?.fields || [];
|
|
212
|
+
const mergedSchema = {
|
|
213
|
+
...customSchema,
|
|
200
214
|
Credential: {
|
|
201
|
-
|
|
202
|
-
|
|
215
|
+
...customSchema.Credential,
|
|
216
|
+
fields: [
|
|
217
|
+
...new Set([...existingCredentialFields, ...credentialFields]),
|
|
218
|
+
],
|
|
219
|
+
},
|
|
203
220
|
};
|
|
204
221
|
|
|
205
222
|
logger.info(
|
|
206
223
|
`Registering module-level encryption for ${credentialFields.length} credential fields`
|
|
207
224
|
);
|
|
208
225
|
|
|
209
|
-
registerCustomSchema(
|
|
226
|
+
registerCustomSchema(mergedSchema);
|
|
210
227
|
}
|
|
211
228
|
|
|
212
229
|
/**
|
|
@@ -218,7 +235,40 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
218
235
|
*
|
|
219
236
|
* Used by both Prisma (MongoDB/PostgreSQL) and DocumentDB encryption services.
|
|
220
237
|
*/
|
|
238
|
+
/**
|
|
239
|
+
* Raised when an app's encryption configuration is invalid. In deployed
|
|
240
|
+
* stages this fails startup instead of silently writing plaintext.
|
|
241
|
+
*/
|
|
242
|
+
class EncryptionSchemaError extends Error {
|
|
243
|
+
constructor(message, { cause } = {}) {
|
|
244
|
+
super(message, { cause });
|
|
245
|
+
this.name = 'EncryptionSchemaError';
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Stages where field-level encryption is bypassed (see prisma.js). */
|
|
250
|
+
function isLocalStage() {
|
|
251
|
+
const stage = process.env.STAGE || process.env.NODE_ENV || 'development';
|
|
252
|
+
return ['dev', 'test', 'local'].includes(stage.toLowerCase());
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* An app definition was found but part of its encryption configuration
|
|
257
|
+
* could not be applied. Deployed stages fail closed; local stages warn and
|
|
258
|
+
* carry on so development isn't blocked.
|
|
259
|
+
*/
|
|
260
|
+
function reportInvalidEncryptionConfig(what, error) {
|
|
261
|
+
const message = `Invalid ${what}: ${error.message}`;
|
|
262
|
+
if (isLocalStage()) {
|
|
263
|
+
logger.warn(`${message} (ignored in local stage)`);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
logger.error(message);
|
|
267
|
+
throw new EncryptionSchemaError(message, { cause: error });
|
|
268
|
+
}
|
|
269
|
+
|
|
221
270
|
function loadCustomEncryptionSchema() {
|
|
271
|
+
let appDefinition;
|
|
222
272
|
try {
|
|
223
273
|
// Lazy require to avoid circular dependency issues
|
|
224
274
|
const path = require('node:path');
|
|
@@ -233,38 +283,54 @@ function loadCustomEncryptionSchema() {
|
|
|
233
283
|
const backendIndexPath = path.join(backendDir, 'index.js');
|
|
234
284
|
|
|
235
285
|
const backendModule = require(backendIndexPath);
|
|
236
|
-
|
|
286
|
+
appDefinition = backendModule?.Definition;
|
|
287
|
+
} catch (error) {
|
|
288
|
+
// No loadable backend (tests, standalone usage): custom schema is
|
|
289
|
+
// optional, so this stays at debug level.
|
|
290
|
+
logger.debug('Could not load custom encryption schema:', error.message);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
237
293
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
294
|
+
if (!appDefinition) {
|
|
295
|
+
return; // No app definition found
|
|
296
|
+
}
|
|
241
297
|
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
298
|
+
// From here an app definition exists, so failures are configuration
|
|
299
|
+
// errors and must be visible.
|
|
300
|
+
|
|
301
|
+
// Load app-level custom schema
|
|
302
|
+
const customSchema = appDefinition.encryption?.schema;
|
|
303
|
+
if (customSchema && Object.keys(customSchema).length > 0) {
|
|
304
|
+
try {
|
|
245
305
|
registerCustomSchema(customSchema);
|
|
306
|
+
} catch (error) {
|
|
307
|
+
reportInvalidEncryptionConfig('app encryption.schema', error);
|
|
246
308
|
}
|
|
309
|
+
}
|
|
247
310
|
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
311
|
+
// Load app-level encryption opt-out — apps can declare fields they
|
|
312
|
+
// don't want encrypted on write (decryption on read still works,
|
|
313
|
+
// so legacy data remains readable).
|
|
314
|
+
const disable = appDefinition.encryption?.disable;
|
|
315
|
+
if (disable && Object.keys(disable).length > 0) {
|
|
316
|
+
try {
|
|
253
317
|
registerEncryptionOptOut(disable);
|
|
318
|
+
} catch (error) {
|
|
319
|
+
reportInvalidEncryptionConfig('app encryption.disable', error);
|
|
254
320
|
}
|
|
321
|
+
}
|
|
255
322
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
323
|
+
// Load module-level encryption schemas from integrations
|
|
324
|
+
const integrations = appDefinition.integrations;
|
|
325
|
+
if (integrations && Array.isArray(integrations)) {
|
|
326
|
+
try {
|
|
259
327
|
loadModuleEncryptionSchemas(integrations);
|
|
328
|
+
} catch (error) {
|
|
329
|
+
reportInvalidEncryptionConfig(
|
|
330
|
+
'module encryption.credentialFields',
|
|
331
|
+
error
|
|
332
|
+
);
|
|
260
333
|
}
|
|
261
|
-
} catch (error) {
|
|
262
|
-
// Silently ignore errors - custom schema is optional
|
|
263
|
-
// This handles cases like:
|
|
264
|
-
// - Backend package.json not found (tests, standalone usage)
|
|
265
|
-
// - No appDefinition defined
|
|
266
|
-
// - No custom encryption schema specified
|
|
267
|
-
logger.debug('Could not load custom encryption schema:', error.message);
|
|
268
334
|
}
|
|
269
335
|
}
|
|
270
336
|
|
|
@@ -399,6 +465,7 @@ function resetCustomSchema() {
|
|
|
399
465
|
}
|
|
400
466
|
|
|
401
467
|
module.exports = {
|
|
468
|
+
EncryptionSchemaError,
|
|
402
469
|
CORE_ENCRYPTION_SCHEMA,
|
|
403
470
|
getEncryptedFields,
|
|
404
471
|
getFieldsToEncryptOnWrite,
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const { isEncryptedEnvelope } = require('./ciphertext-format');
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Field Encryption Service
|
|
3
5
|
*
|
|
@@ -147,12 +149,7 @@ class FieldEncryptionService {
|
|
|
147
149
|
}
|
|
148
150
|
|
|
149
151
|
_isEncrypted(value) {
|
|
150
|
-
|
|
151
|
-
return false;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
const parts = value.split(':');
|
|
155
|
-
return parts.length >= 4;
|
|
152
|
+
return isEncryptedEnvelope(value);
|
|
156
153
|
}
|
|
157
154
|
|
|
158
155
|
_getNestedValue(obj, path) {
|
|
@@ -218,22 +215,22 @@ class FieldEncryptionService {
|
|
|
218
215
|
}
|
|
219
216
|
|
|
220
217
|
/**
|
|
221
|
-
* Serialize a value for encryption
|
|
222
|
-
*
|
|
218
|
+
* Serialize a value for encryption.
|
|
219
|
+
* Every value is JSON-encoded, strings included, so the type survives
|
|
220
|
+
* the round trip: '123456' is stored as "\"123456\"" and reads back as a
|
|
221
|
+
* string, 1234 reads back as a number.
|
|
223
222
|
* @private
|
|
224
223
|
*/
|
|
225
224
|
_serializeForEncryption(value) {
|
|
226
|
-
|
|
227
|
-
// JSON.stringify for objects and arrays
|
|
228
|
-
return JSON.stringify(value);
|
|
229
|
-
}
|
|
230
|
-
// For primitives (string, number, boolean), convert to string
|
|
231
|
-
return String(value);
|
|
225
|
+
return JSON.stringify(value);
|
|
232
226
|
}
|
|
233
227
|
|
|
234
228
|
/**
|
|
235
|
-
* Deserialize a value after decryption
|
|
236
|
-
*
|
|
229
|
+
* Deserialize a value after decryption.
|
|
230
|
+
* Parses the JSON written by _serializeForEncryption. Values encrypted by
|
|
231
|
+
* earlier versions stored strings raw: those that aren't valid JSON come
|
|
232
|
+
* back unchanged; a raw legacy string that is also valid JSON (e.g.
|
|
233
|
+
* '123456') still parses as it always did.
|
|
237
234
|
* @private
|
|
238
235
|
*/
|
|
239
236
|
_deserializeAfterDecryption(value) {
|
package/database/prisma.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
const {
|
|
2
2
|
createEncryptionExtension,
|
|
3
3
|
} = require('./encryption/prisma-encryption-extension');
|
|
4
|
-
const {
|
|
4
|
+
const {
|
|
5
|
+
loadCustomEncryptionSchema,
|
|
6
|
+
EncryptionSchemaError,
|
|
7
|
+
} = require('./encryption/encryption-schema-registry');
|
|
5
8
|
const { logger } = require('./encryption/logger');
|
|
6
9
|
const { Cryptor } = require('../encrypt/Cryptor');
|
|
7
10
|
const config = require('./config');
|
|
@@ -125,6 +128,12 @@ const prismaClientSingleton = () => {
|
|
|
125
128
|
`Field-level encryption enabled using ${encryptionConfig.method.toUpperCase()}`
|
|
126
129
|
);
|
|
127
130
|
} catch (error) {
|
|
131
|
+
// An invalid encryption configuration must fail startup: carrying
|
|
132
|
+
// on without the extension would write encrypted fields in
|
|
133
|
+
// plaintext.
|
|
134
|
+
if (error instanceof EncryptionSchemaError) {
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
128
137
|
logger.error(
|
|
129
138
|
'Failed to initialize encryption extension:',
|
|
130
139
|
error
|
package/errors/index.js
CHANGED
|
@@ -6,6 +6,9 @@ const {
|
|
|
6
6
|
ParameterTypeError,
|
|
7
7
|
} = require('./validation-errors');
|
|
8
8
|
const { ClientSafeError } = require('./client-safe-error');
|
|
9
|
+
const {
|
|
10
|
+
MappingAlreadyExistsError,
|
|
11
|
+
} = require('./mapping-already-exists-error');
|
|
9
12
|
|
|
10
13
|
module.exports = {
|
|
11
14
|
BaseError,
|
|
@@ -14,4 +17,5 @@ module.exports = {
|
|
|
14
17
|
RequiredPropertyError,
|
|
15
18
|
ParameterTypeError,
|
|
16
19
|
ClientSafeError,
|
|
20
|
+
MappingAlreadyExistsError,
|
|
17
21
|
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
const { BaseError } = require('./base-error');
|
|
2
|
+
|
|
3
|
+
class MappingAlreadyExistsError extends BaseError {
|
|
4
|
+
constructor(integrationId, sourceId, ...errorOptions) {
|
|
5
|
+
super(
|
|
6
|
+
`Mapping already exists for integration ${integrationId} and sourceId ${sourceId}`,
|
|
7
|
+
...errorOptions
|
|
8
|
+
);
|
|
9
|
+
this.integrationId = integrationId;
|
|
10
|
+
this.sourceId = sourceId;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
module.exports = { MappingAlreadyExistsError };
|