@friggframework/core 2.0.0--canary.658.e11f3b0.0 → 2.0.0--canary.737.83b4e17.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 +42 -58
- package/application/commands/README.md +17 -11
- package/application/commands/entity-commands.js +18 -60
- package/application/commands/integration-commands.js +63 -0
- package/core/CLAUDE.md +1 -3
- package/core/Worker.js +2 -1
- package/core/create-handler.js +0 -3
- package/core/index.js +0 -6
- package/core/invocation-scope.js +24 -30
- package/database/documentdb-encryption-service.js +2 -33
- package/database/documentdb-utils.js +4 -1
- package/database/encryption/README.md +3 -3
- package/database/encryption/ciphertext-format.js +24 -0
- package/database/encryption/encryption-schema-registry.js +109 -29
- package/database/encryption/field-encryption-service.js +55 -16
- package/database/encryption/prisma-encryption-extension.js +6 -9
- package/database/prisma.js +10 -1
- package/encrypt/Cryptor.js +90 -38
- package/errors/fetch-error.js +18 -11
- package/errors/index.js +4 -2
- package/errors/mapping-already-exists-error.js +14 -0
- package/generated/prisma-mongodb/edge.js +6 -2
- package/generated/prisma-mongodb/index.js +10 -2
- package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +1 -1
- package/generated/prisma-mongodb/wasm.js +6 -2
- package/generated/prisma-postgresql/edge.js +6 -2
- package/generated/prisma-postgresql/index.js +10 -2
- package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +1 -1
- package/generated/prisma-postgresql/wasm.js +6 -2
- package/handlers/WEBHOOKS.md +29 -0
- package/handlers/app-definition-loader.js +9 -2
- package/handlers/app-handler-helpers.js +12 -1
- package/handlers/workers/integration-defined-workers.js +0 -2
- package/index.js +2 -18
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -13
- package/integrations/integration-base.js +52 -25
- package/integrations/integration-router.js +30 -22
- 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 +42 -23
- package/integrations/repositories/integration-repository-interface.js +37 -21
- package/integrations/repositories/integration-repository-mongo.js +69 -30
- package/integrations/repositories/integration-repository-postgres.js +74 -30
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/tests/doubles/test-integration-repository.js +2 -15
- package/integrations/use-cases/add-entities-to-integration.js +92 -0
- package/integrations/use-cases/create-integration.js +57 -19
- package/integrations/use-cases/delete-integration-for-user.js +8 -11
- package/integrations/use-cases/get-integration-instance.js +12 -12
- package/integrations/use-cases/remove-entities-from-integration.js +70 -0
- package/integrations/use-cases/update-integration-messages.js +9 -28
- package/integrations/use-cases/update-integration.js +12 -12
- package/integrations/utils/assert-entity-ids-input.js +42 -0
- 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/logs/serialize.js +0 -15
- package/modules/module.js +0 -27
- package/modules/requester/requester.js +9 -211
- package/modules/use-cases/create-entity-from-credential.js +105 -0
- package/modules/use-cases/get-entity-options-by-id.js +7 -5
- package/modules/use-cases/get-module.js +29 -8
- package/modules/use-cases/process-authorization-callback.js +78 -27
- package/modules/use-cases/refresh-entity-options.js +7 -5
- package/modules/use-cases/test-module-auth.js +7 -5
- package/modules/utils/find-module-definition.js +23 -0
- package/modules/utils/map-module-dto.js +5 -3
- package/modules/utils/to-credential-id.js +14 -0
- package/package.json +10 -7
- package/prisma-mongodb/schema.prisma +1 -1
- package/prisma-postgresql/schema.prisma +1 -1
- package/queues/queuer-util.js +9 -7
- package/queues/sqs-message-body.js +17 -0
- package/telemetry/otel-telemetry.js +76 -3
- package/telemetry/telemetry-config.js +16 -5
- package/telemetry/telemetry-runtime.js +14 -1
- package/token/repositories/token-repository-documentdb.js +13 -1
- package/token/repositories/token-repository-mongo.js +13 -1
- package/token/repositories/token-repository-postgres.js +13 -1
- package/types/core/index.d.ts +0 -33
- package/types/errors/index.d.ts +0 -47
- package/types/integrations/index.d.ts +4 -20
- package/types/module-plugin/index.d.ts +0 -47
- package/user/tests/doubles/test-user-repository.js +1 -1
- package/user/use-cases/authenticate-user.js +23 -7
- package/user/use-cases/get-user-from-bearer-token.js +7 -2
- package/core/invocation-deadline.js +0 -91
- package/errors/rate-limit-error.js +0 -46
- package/integrations/repositories/message-item-shared.js +0 -4
- package/integrations/tests/doubles/prisma-message-row.js +0 -24
- package/integrations/use-cases/record-rate-limit-message.js +0 -110
- package/modules/requester/rate-limit/index.js +0 -4
- package/modules/requester/rate-limit/parsers.js +0 -245
- package/modules/requester/rate-limit/policy.js +0 -304
|
@@ -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 };
|
|
@@ -146,6 +146,16 @@ function extractCredentialFieldsFromModules(moduleDefinitions) {
|
|
|
146
146
|
}
|
|
147
147
|
|
|
148
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
|
+
}
|
|
149
159
|
const prefixedField = field.startsWith('data.') ? field : `data.${field}`;
|
|
150
160
|
fields.push(prefixedField);
|
|
151
161
|
}
|
|
@@ -174,26 +184,46 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
174
184
|
return;
|
|
175
185
|
}
|
|
176
186
|
|
|
177
|
-
const { getModulesDefinitionFromIntegrationClasses } = require('
|
|
187
|
+
const { getModulesDefinitionFromIntegrationClasses } = require('../../integrations/utils/map-integration-dto');
|
|
188
|
+
|
|
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
|
+
);
|
|
178
196
|
|
|
179
|
-
|
|
180
|
-
|
|
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));
|
|
181
204
|
|
|
182
205
|
if (credentialFields.length === 0) {
|
|
183
206
|
return;
|
|
184
207
|
}
|
|
185
208
|
|
|
186
|
-
|
|
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,
|
|
187
214
|
Credential: {
|
|
188
|
-
|
|
189
|
-
|
|
215
|
+
...customSchema.Credential,
|
|
216
|
+
fields: [
|
|
217
|
+
...new Set([...existingCredentialFields, ...credentialFields]),
|
|
218
|
+
],
|
|
219
|
+
},
|
|
190
220
|
};
|
|
191
221
|
|
|
192
222
|
logger.info(
|
|
193
223
|
`Registering module-level encryption for ${credentialFields.length} credential fields`
|
|
194
224
|
);
|
|
195
225
|
|
|
196
|
-
registerCustomSchema(
|
|
226
|
+
registerCustomSchema(mergedSchema);
|
|
197
227
|
}
|
|
198
228
|
|
|
199
229
|
/**
|
|
@@ -205,7 +235,40 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
205
235
|
*
|
|
206
236
|
* Used by both Prisma (MongoDB/PostgreSQL) and DocumentDB encryption services.
|
|
207
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
|
+
|
|
208
270
|
function loadCustomEncryptionSchema() {
|
|
271
|
+
let appDefinition;
|
|
209
272
|
try {
|
|
210
273
|
// Lazy require to avoid circular dependency issues
|
|
211
274
|
const path = require('node:path');
|
|
@@ -220,38 +283,54 @@ function loadCustomEncryptionSchema() {
|
|
|
220
283
|
const backendIndexPath = path.join(backendDir, 'index.js');
|
|
221
284
|
|
|
222
285
|
const backendModule = require(backendIndexPath);
|
|
223
|
-
|
|
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
|
+
}
|
|
224
293
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
294
|
+
if (!appDefinition) {
|
|
295
|
+
return; // No app definition found
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// From here an app definition exists, so failures are configuration
|
|
299
|
+
// errors and must be visible.
|
|
228
300
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
301
|
+
// Load app-level custom schema
|
|
302
|
+
const customSchema = appDefinition.encryption?.schema;
|
|
303
|
+
if (customSchema && Object.keys(customSchema).length > 0) {
|
|
304
|
+
try {
|
|
232
305
|
registerCustomSchema(customSchema);
|
|
306
|
+
} catch (error) {
|
|
307
|
+
reportInvalidEncryptionConfig('app encryption.schema', error);
|
|
233
308
|
}
|
|
309
|
+
}
|
|
234
310
|
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
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 {
|
|
240
317
|
registerEncryptionOptOut(disable);
|
|
318
|
+
} catch (error) {
|
|
319
|
+
reportInvalidEncryptionConfig('app encryption.disable', error);
|
|
241
320
|
}
|
|
321
|
+
}
|
|
242
322
|
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
323
|
+
// Load module-level encryption schemas from integrations
|
|
324
|
+
const integrations = appDefinition.integrations;
|
|
325
|
+
if (integrations && Array.isArray(integrations)) {
|
|
326
|
+
try {
|
|
246
327
|
loadModuleEncryptionSchemas(integrations);
|
|
328
|
+
} catch (error) {
|
|
329
|
+
reportInvalidEncryptionConfig(
|
|
330
|
+
'module encryption.credentialFields',
|
|
331
|
+
error
|
|
332
|
+
);
|
|
247
333
|
}
|
|
248
|
-
} catch (error) {
|
|
249
|
-
// Silently ignore errors - custom schema is optional
|
|
250
|
-
// This handles cases like:
|
|
251
|
-
// - Backend package.json not found (tests, standalone usage)
|
|
252
|
-
// - No appDefinition defined
|
|
253
|
-
// - No custom encryption schema specified
|
|
254
|
-
logger.debug('Could not load custom encryption schema:', error.message);
|
|
255
334
|
}
|
|
256
335
|
}
|
|
257
336
|
|
|
@@ -386,6 +465,7 @@ function resetCustomSchema() {
|
|
|
386
465
|
}
|
|
387
466
|
|
|
388
467
|
module.exports = {
|
|
468
|
+
EncryptionSchemaError,
|
|
389
469
|
CORE_ENCRYPTION_SCHEMA,
|
|
390
470
|
getEncryptedFields,
|
|
391
471
|
getFieldsToEncryptOnWrite,
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const { isEncryptedEnvelope } = require('./ciphertext-format');
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Field Encryption Service
|
|
3
5
|
*
|
|
@@ -81,6 +83,48 @@ class FieldEncryptionService {
|
|
|
81
83
|
return encrypted;
|
|
82
84
|
}
|
|
83
85
|
|
|
86
|
+
async encryptUpsert(modelName, { create, update }) {
|
|
87
|
+
const fields = this._getWriteFields(modelName);
|
|
88
|
+
if (fields.length === 0) {
|
|
89
|
+
return { create, update };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const encryptedCreate = await this.encryptFields(modelName, create);
|
|
93
|
+
const pathsOverlap = fields.some((outer) =>
|
|
94
|
+
fields.some((inner) => inner.startsWith(`${outer}.`))
|
|
95
|
+
);
|
|
96
|
+
if (!create || !update || pathsOverlap) {
|
|
97
|
+
return {
|
|
98
|
+
create: encryptedCreate,
|
|
99
|
+
update: await this.encryptFields(modelName, update),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const reusing = this._deepClone(update);
|
|
104
|
+
for (const fieldPath of fields) {
|
|
105
|
+
const value = this._getNestedValue(update, fieldPath);
|
|
106
|
+
const createCiphertext = this._getNestedValue(
|
|
107
|
+
encryptedCreate,
|
|
108
|
+
fieldPath
|
|
109
|
+
);
|
|
110
|
+
if (
|
|
111
|
+
this._shouldEncrypt(value) &&
|
|
112
|
+
this._isEncrypted(createCiphertext) &&
|
|
113
|
+
this._serializeForEncryption(value) ===
|
|
114
|
+
this._serializeForEncryption(
|
|
115
|
+
this._getNestedValue(create, fieldPath)
|
|
116
|
+
)
|
|
117
|
+
) {
|
|
118
|
+
this._setNestedValue(reusing, fieldPath, createCiphertext);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return {
|
|
123
|
+
create: encryptedCreate,
|
|
124
|
+
update: await this.encryptFields(modelName, reusing),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
84
128
|
async decryptFields(modelName, document) {
|
|
85
129
|
if (!document || typeof document !== 'object') {
|
|
86
130
|
return document;
|
|
@@ -147,12 +191,7 @@ class FieldEncryptionService {
|
|
|
147
191
|
}
|
|
148
192
|
|
|
149
193
|
_isEncrypted(value) {
|
|
150
|
-
|
|
151
|
-
return false;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
const parts = value.split(':');
|
|
155
|
-
return parts.length >= 4;
|
|
194
|
+
return isEncryptedEnvelope(value);
|
|
156
195
|
}
|
|
157
196
|
|
|
158
197
|
_getNestedValue(obj, path) {
|
|
@@ -218,22 +257,22 @@ class FieldEncryptionService {
|
|
|
218
257
|
}
|
|
219
258
|
|
|
220
259
|
/**
|
|
221
|
-
* Serialize a value for encryption
|
|
222
|
-
*
|
|
260
|
+
* Serialize a value for encryption.
|
|
261
|
+
* Every value is JSON-encoded, strings included, so the type survives
|
|
262
|
+
* the round trip: '123456' is stored as "\"123456\"" and reads back as a
|
|
263
|
+
* string, 1234 reads back as a number.
|
|
223
264
|
* @private
|
|
224
265
|
*/
|
|
225
266
|
_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);
|
|
267
|
+
return JSON.stringify(value);
|
|
232
268
|
}
|
|
233
269
|
|
|
234
270
|
/**
|
|
235
|
-
* Deserialize a value after decryption
|
|
236
|
-
*
|
|
271
|
+
* Deserialize a value after decryption.
|
|
272
|
+
* Parses the JSON written by _serializeForEncryption. Values encrypted by
|
|
273
|
+
* earlier versions stored strings raw: those that aren't valid JSON come
|
|
274
|
+
* back unchanged; a raw legacy string that is also valid JSON (e.g.
|
|
275
|
+
* '123456') still parses as it always did.
|
|
237
276
|
* @private
|
|
238
277
|
*/
|
|
239
278
|
_deserializeAfterDecryption(value) {
|
|
@@ -114,18 +114,15 @@ function createEncryptionExtension({ cryptor, enabled = true }) {
|
|
|
114
114
|
},
|
|
115
115
|
|
|
116
116
|
async upsert({ model, args, query }) {
|
|
117
|
+
const encrypted = await encryptionService.encryptUpsert(
|
|
118
|
+
model,
|
|
119
|
+
args
|
|
120
|
+
);
|
|
117
121
|
if (args.create) {
|
|
118
|
-
args.create =
|
|
119
|
-
model,
|
|
120
|
-
args.create
|
|
121
|
-
);
|
|
122
|
+
args.create = encrypted.create;
|
|
122
123
|
}
|
|
123
|
-
|
|
124
124
|
if (args.update) {
|
|
125
|
-
args.update =
|
|
126
|
-
model,
|
|
127
|
-
args.update
|
|
128
|
-
);
|
|
125
|
+
args.update = encrypted.update;
|
|
129
126
|
}
|
|
130
127
|
|
|
131
128
|
const result = await query(args);
|
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/encrypt/Cryptor.js
CHANGED
|
@@ -20,26 +20,86 @@ const crypto = require('crypto');
|
|
|
20
20
|
const { KMSClient, GenerateDataKeyCommand, DecryptCommand } = require('@aws-sdk/client-kms');
|
|
21
21
|
const aes = require('./aes');
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
23
|
+
const DATA_KEY_TTL_MS = 60 * 60 * 1000;
|
|
24
|
+
const DATA_KEY_CACHE_MAX_ENTRIES = 10000;
|
|
25
|
+
|
|
26
|
+
function createKmsDataKeys() {
|
|
27
|
+
let client = null;
|
|
28
|
+
const cache = new Map();
|
|
29
|
+
|
|
30
|
+
const getClient = () => {
|
|
31
|
+
client = client || new KMSClient({});
|
|
32
|
+
return client;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const remember = (encryptedKeyB64, promise) => {
|
|
36
|
+
cache.delete(encryptedKeyB64);
|
|
37
|
+
if (cache.size >= DATA_KEY_CACHE_MAX_ENTRIES) {
|
|
38
|
+
cache.delete(cache.keys().next().value);
|
|
39
|
+
}
|
|
40
|
+
cache.set(encryptedKeyB64, {
|
|
41
|
+
promise,
|
|
42
|
+
expiresAt: Date.now() + DATA_KEY_TTL_MS,
|
|
43
|
+
});
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const lookup = (encryptedKeyB64) => {
|
|
47
|
+
const entry = cache.get(encryptedKeyB64);
|
|
48
|
+
if (!entry) {
|
|
49
|
+
return undefined;
|
|
41
50
|
}
|
|
51
|
+
cache.delete(encryptedKeyB64);
|
|
52
|
+
if (entry.expiresAt <= Date.now()) {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
cache.set(encryptedKeyB64, entry);
|
|
56
|
+
return entry.promise;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
async generate() {
|
|
61
|
+
const dataKey = await getClient().send(
|
|
62
|
+
new GenerateDataKeyCommand({
|
|
63
|
+
KeyId: process.env.KMS_KEY_ARN,
|
|
64
|
+
KeySpec: 'AES_256',
|
|
65
|
+
})
|
|
66
|
+
);
|
|
67
|
+
const encryptedKey = Buffer.from(dataKey.CiphertextBlob).toString('base64');
|
|
68
|
+
remember(encryptedKey, Promise.resolve(dataKey.Plaintext));
|
|
69
|
+
return {
|
|
70
|
+
keyId: Buffer.from(dataKey.KeyId).toString('base64'),
|
|
71
|
+
encryptedKey,
|
|
72
|
+
plaintext: dataKey.Plaintext,
|
|
73
|
+
};
|
|
74
|
+
},
|
|
75
|
+
|
|
76
|
+
async decrypt(keyId, encryptedKeyB64) {
|
|
77
|
+
const cached = lookup(encryptedKeyB64);
|
|
78
|
+
if (cached) {
|
|
79
|
+
return cached;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const pending = getClient()
|
|
83
|
+
.send(
|
|
84
|
+
new DecryptCommand({
|
|
85
|
+
KeyId: keyId,
|
|
86
|
+
CiphertextBlob: Buffer.from(encryptedKeyB64, 'base64'),
|
|
87
|
+
})
|
|
88
|
+
)
|
|
89
|
+
.then((dataKey) => dataKey.Plaintext);
|
|
90
|
+
remember(encryptedKeyB64, pending);
|
|
91
|
+
pending.catch(() => {
|
|
92
|
+
if (cache.get(encryptedKeyB64)?.promise === pending) {
|
|
93
|
+
cache.delete(encryptedKeyB64);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
return pending;
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
42
100
|
|
|
101
|
+
const localDataKeys = {
|
|
102
|
+
async generate() {
|
|
43
103
|
const { AES_KEY, AES_KEY_ID } = process.env;
|
|
44
104
|
const randomKey = crypto.randomBytes(32).toString('hex').slice(0, 32);
|
|
45
105
|
|
|
@@ -50,9 +110,9 @@ class Cryptor {
|
|
|
50
110
|
),
|
|
51
111
|
plaintext: randomKey,
|
|
52
112
|
};
|
|
53
|
-
}
|
|
113
|
+
},
|
|
54
114
|
|
|
55
|
-
|
|
115
|
+
async decrypt(keyId, encryptedKeyB64) {
|
|
56
116
|
const availableKeys = {
|
|
57
117
|
[process.env.AES_KEY_ID]: process.env.AES_KEY,
|
|
58
118
|
[process.env.DEPRECATED_AES_KEY_ID]: process.env.DEPRECATED_AES_KEY,
|
|
@@ -64,27 +124,20 @@ class Cryptor {
|
|
|
64
124
|
throw new Error('Encryption key not found');
|
|
65
125
|
}
|
|
66
126
|
|
|
67
|
-
return key;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
async decryptDataKey(keyId, encryptedKey) {
|
|
71
|
-
if (this.shouldUseAws) {
|
|
72
|
-
const kmsClient = new KMSClient({});
|
|
73
|
-
const command = new DecryptCommand({
|
|
74
|
-
KeyId: keyId,
|
|
75
|
-
CiphertextBlob: encryptedKey,
|
|
76
|
-
});
|
|
77
|
-
const dataKey = await kmsClient.send(command);
|
|
127
|
+
return aes.decrypt(Buffer.from(encryptedKeyB64, 'base64'), key);
|
|
128
|
+
},
|
|
129
|
+
};
|
|
78
130
|
|
|
79
|
-
|
|
80
|
-
}
|
|
131
|
+
const kmsDataKeys = createKmsDataKeys();
|
|
81
132
|
|
|
82
|
-
|
|
83
|
-
|
|
133
|
+
class Cryptor {
|
|
134
|
+
constructor({ shouldUseAws }) {
|
|
135
|
+
this.shouldUseAws = shouldUseAws;
|
|
136
|
+
this.dataKeys = shouldUseAws ? kmsDataKeys : localDataKeys;
|
|
84
137
|
}
|
|
85
138
|
|
|
86
139
|
async encrypt(text) {
|
|
87
|
-
const { keyId, encryptedKey, plaintext } = await this.
|
|
140
|
+
const { keyId, encryptedKey, plaintext } = await this.dataKeys.generate();
|
|
88
141
|
const encryptedText = aes.encrypt(text, plaintext);
|
|
89
142
|
return `${keyId}:${encryptedText}:${encryptedKey}`;
|
|
90
143
|
}
|
|
@@ -93,8 +146,7 @@ class Cryptor {
|
|
|
93
146
|
const split = text.split(':');
|
|
94
147
|
const keyId = Buffer.from(split[0], 'base64').toString();
|
|
95
148
|
const encryptedText = `${split[1]}:${split[2]}`;
|
|
96
|
-
const
|
|
97
|
-
const plaintext = await this.decryptDataKey(keyId, encryptedKey);
|
|
149
|
+
const plaintext = await this.dataKeys.decrypt(keyId, split[3]);
|
|
98
150
|
return aes.decrypt(encryptedText, plaintext);
|
|
99
151
|
}
|
|
100
152
|
}
|
package/errors/fetch-error.js
CHANGED
|
@@ -12,10 +12,21 @@ function resourceUrl(resource) {
|
|
|
12
12
|
return redactUrl(resource);
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
// node-fetch messages can contain part of the response body.
|
|
16
|
+
// Use a fixed phrase instead of the original message.
|
|
17
|
+
const NODE_FETCH_TYPE_PHRASES = {
|
|
18
|
+
'invalid-json': 'invalid json response body',
|
|
19
|
+
};
|
|
20
|
+
|
|
15
21
|
function causeLabel(cause) {
|
|
16
22
|
if (!cause || typeof cause !== 'object') return '';
|
|
17
23
|
const label = cause.code ?? cause.name;
|
|
18
|
-
|
|
24
|
+
const scrubbedLabel =
|
|
25
|
+
label === undefined || label === null ? '' : scrubString(String(label));
|
|
26
|
+
const phrase = Object.hasOwn(NODE_FETCH_TYPE_PHRASES, cause.type)
|
|
27
|
+
? NODE_FETCH_TYPE_PHRASES[cause.type]
|
|
28
|
+
: '';
|
|
29
|
+
return [scrubbedLabel, phrase].filter(Boolean).join(': ');
|
|
19
30
|
}
|
|
20
31
|
|
|
21
32
|
function buildMessage({ method, url, response, cause }) {
|
|
@@ -55,16 +66,12 @@ class FetchError extends BaseError {
|
|
|
55
66
|
|
|
56
67
|
static async create(options = {}) {
|
|
57
68
|
const { response } = options;
|
|
58
|
-
let
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
responseBody = (canRead && (await response.text())) || options.body;
|
|
65
|
-
}
|
|
66
|
-
const ErrorClass = typeof this === 'function' ? this : FetchError;
|
|
67
|
-
return new ErrorClass({ ...options, responseBody });
|
|
69
|
+
let responseBody =
|
|
70
|
+
response && !response.bodyUsed && typeof response.text === 'function'
|
|
71
|
+
? await response.text()
|
|
72
|
+
: null;
|
|
73
|
+
if (!responseBody) responseBody = options.responseBody ?? options.body;
|
|
74
|
+
return new FetchError({ ...options, responseBody });
|
|
68
75
|
}
|
|
69
76
|
}
|
|
70
77
|
|
package/errors/index.js
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
const { BaseError } = require('./base-error');
|
|
2
2
|
const { FetchError } = require('./fetch-error');
|
|
3
3
|
const { HaltError } = require('./halt-error');
|
|
4
|
-
const { RateLimitError } = require('./rate-limit-error');
|
|
5
4
|
const {
|
|
6
5
|
RequiredPropertyError,
|
|
7
6
|
ParameterTypeError,
|
|
8
7
|
} = require('./validation-errors');
|
|
9
8
|
const { ClientSafeError } = require('./client-safe-error');
|
|
9
|
+
const {
|
|
10
|
+
MappingAlreadyExistsError,
|
|
11
|
+
} = require('./mapping-already-exists-error');
|
|
10
12
|
|
|
11
13
|
module.exports = {
|
|
12
14
|
BaseError,
|
|
13
15
|
FetchError,
|
|
14
16
|
HaltError,
|
|
15
|
-
RateLimitError,
|
|
16
17
|
RequiredPropertyError,
|
|
17
18
|
ParameterTypeError,
|
|
18
19
|
ClientSafeError,
|
|
20
|
+
MappingAlreadyExistsError,
|
|
19
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 };
|