@friggframework/core 2.0.0--canary.730.f2ba24a.0 → 2.0.0--canary.656.6eb85ab.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 +14 -42
- package/application/commands/README.md +11 -17
- package/application/commands/entity-commands.js +60 -18
- package/application/commands/integration-commands.js +0 -63
- package/core/CLAUDE.md +3 -1
- package/core/create-handler.js +3 -0
- package/core/index.js +6 -0
- package/core/invocation-deadline.js +91 -0
- package/core/invocation-scope.js +30 -24
- package/database/documentdb-encryption-service.js +33 -2
- package/database/documentdb-utils.js +1 -4
- package/database/encryption/README.md +3 -3
- package/database/encryption/encryption-schema-registry.js +29 -109
- package/database/encryption/field-encryption-service.js +16 -55
- package/database/encryption/prisma-encryption-extension.js +9 -6
- package/database/prisma.js +1 -10
- package/encrypt/Cryptor.js +38 -90
- package/errors/fetch-error.js +11 -18
- package/errors/index.js +2 -4
- package/errors/rate-limit-error.js +45 -0
- package/handlers/WEBHOOKS.md +0 -29
- package/handlers/app-definition-loader.js +2 -9
- package/handlers/app-handler-helpers.js +1 -12
- package/handlers/backend-utils.js +2 -1
- package/handlers/workers/integration-defined-workers.js +2 -0
- package/index.js +18 -2
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +13 -67
- package/integrations/integration-base.js +9 -52
- package/integrations/integration-router.js +22 -30
- 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-repository-documentdb.js +0 -32
- package/integrations/repositories/integration-repository-interface.js +0 -30
- package/integrations/repositories/integration-repository-mongo.js +1 -53
- package/integrations/repositories/integration-repository-postgres.js +0 -58
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/use-cases/create-integration.js +19 -57
- package/integrations/use-cases/delete-integration-for-user.js +11 -8
- package/integrations/use-cases/get-integration-instance.js +12 -12
- package/integrations/use-cases/update-integration.js +12 -12
- package/jest-setup.js +2 -13
- package/jest-teardown.js +2 -5
- package/jest.config.js +0 -4
- package/logs/serialize.js +15 -0
- package/modules/requester/rate-limit/index.js +4 -0
- package/modules/requester/rate-limit/parsers.js +245 -0
- package/modules/requester/rate-limit/policy.js +304 -0
- package/modules/requester/requester.js +187 -9
- package/modules/use-cases/get-entity-options-by-id.js +5 -7
- package/modules/use-cases/get-module.js +8 -29
- package/modules/use-cases/process-authorization-callback.js +27 -78
- package/modules/use-cases/refresh-entity-options.js +5 -7
- package/modules/use-cases/test-module-auth.js +5 -7
- package/modules/utils/map-module-dto.js +3 -5
- package/package.json +7 -10
- package/queues/queuer-util.js +5 -6
- package/token/repositories/token-repository-documentdb.js +1 -13
- package/token/repositories/token-repository-mongo.js +1 -13
- package/token/repositories/token-repository-postgres.js +1 -13
- package/types/core/index.d.ts +33 -0
- package/types/errors/index.d.ts +47 -0
- package/types/module-plugin/index.d.ts +43 -0
- package/user/tests/doubles/test-user-repository.js +1 -1
- package/user/use-cases/authenticate-user.js +7 -23
- package/user/use-cases/get-user-from-bearer-token.js +2 -7
- package/database/encryption/ciphertext-format.js +0 -24
- 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/jest.db.config.js +0 -23
- package/modules/use-cases/create-entity-from-credential.js +0 -105
- package/modules/utils/find-module-definition.js +0 -23
- package/modules/utils/to-credential-id.js +0 -14
|
@@ -146,16 +146,6 @@ 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
|
-
}
|
|
159
149
|
const prefixedField = field.startsWith('data.') ? field : `data.${field}`;
|
|
160
150
|
fields.push(prefixedField);
|
|
161
151
|
}
|
|
@@ -184,46 +174,26 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
184
174
|
return;
|
|
185
175
|
}
|
|
186
176
|
|
|
187
|
-
const { getModulesDefinitionFromIntegrationClasses } = require('
|
|
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
|
-
);
|
|
177
|
+
const { getModulesDefinitionFromIntegrationClasses } = require('../integrations/utils/map-integration-dto');
|
|
196
178
|
|
|
197
|
-
|
|
198
|
-
|
|
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));
|
|
179
|
+
const moduleDefinitions = getModulesDefinitionFromIntegrationClasses(integrations);
|
|
180
|
+
const credentialFields = extractCredentialFieldsFromModules(moduleDefinitions);
|
|
204
181
|
|
|
205
182
|
if (credentialFields.length === 0) {
|
|
206
183
|
return;
|
|
207
184
|
}
|
|
208
185
|
|
|
209
|
-
|
|
210
|
-
// than replacing it (registerCustomSchema overwrites).
|
|
211
|
-
const existingCredentialFields = customSchema.Credential?.fields || [];
|
|
212
|
-
const mergedSchema = {
|
|
213
|
-
...customSchema,
|
|
186
|
+
const moduleSchema = {
|
|
214
187
|
Credential: {
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
...new Set([...existingCredentialFields, ...credentialFields]),
|
|
218
|
-
],
|
|
219
|
-
},
|
|
188
|
+
fields: credentialFields
|
|
189
|
+
}
|
|
220
190
|
};
|
|
221
191
|
|
|
222
192
|
logger.info(
|
|
223
193
|
`Registering module-level encryption for ${credentialFields.length} credential fields`
|
|
224
194
|
);
|
|
225
195
|
|
|
226
|
-
registerCustomSchema(
|
|
196
|
+
registerCustomSchema(moduleSchema);
|
|
227
197
|
}
|
|
228
198
|
|
|
229
199
|
/**
|
|
@@ -235,40 +205,7 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
235
205
|
*
|
|
236
206
|
* Used by both Prisma (MongoDB/PostgreSQL) and DocumentDB encryption services.
|
|
237
207
|
*/
|
|
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
|
-
|
|
270
208
|
function loadCustomEncryptionSchema() {
|
|
271
|
-
let appDefinition;
|
|
272
209
|
try {
|
|
273
210
|
// Lazy require to avoid circular dependency issues
|
|
274
211
|
const path = require('node:path');
|
|
@@ -283,54 +220,38 @@ function loadCustomEncryptionSchema() {
|
|
|
283
220
|
const backendIndexPath = path.join(backendDir, 'index.js');
|
|
284
221
|
|
|
285
222
|
const backendModule = require(backendIndexPath);
|
|
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
|
-
}
|
|
223
|
+
const appDefinition = backendModule?.Definition;
|
|
293
224
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
// From here an app definition exists, so failures are configuration
|
|
299
|
-
// errors and must be visible.
|
|
225
|
+
if (!appDefinition) {
|
|
226
|
+
return; // No app definition found
|
|
227
|
+
}
|
|
300
228
|
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
try {
|
|
229
|
+
// Load app-level custom schema
|
|
230
|
+
const customSchema = appDefinition.encryption?.schema;
|
|
231
|
+
if (customSchema && Object.keys(customSchema).length > 0) {
|
|
305
232
|
registerCustomSchema(customSchema);
|
|
306
|
-
} catch (error) {
|
|
307
|
-
reportInvalidEncryptionConfig('app encryption.schema', error);
|
|
308
233
|
}
|
|
309
|
-
}
|
|
310
234
|
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
try {
|
|
235
|
+
// Load app-level encryption opt-out — apps can declare fields they
|
|
236
|
+
// don't want encrypted on write (decryption on read still works,
|
|
237
|
+
// so legacy data remains readable).
|
|
238
|
+
const disable = appDefinition.encryption?.disable;
|
|
239
|
+
if (disable && Object.keys(disable).length > 0) {
|
|
317
240
|
registerEncryptionOptOut(disable);
|
|
318
|
-
} catch (error) {
|
|
319
|
-
reportInvalidEncryptionConfig('app encryption.disable', error);
|
|
320
241
|
}
|
|
321
|
-
}
|
|
322
242
|
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
try {
|
|
243
|
+
// Load module-level encryption schemas from integrations
|
|
244
|
+
const integrations = appDefinition.integrations;
|
|
245
|
+
if (integrations && Array.isArray(integrations)) {
|
|
327
246
|
loadModuleEncryptionSchemas(integrations);
|
|
328
|
-
} catch (error) {
|
|
329
|
-
reportInvalidEncryptionConfig(
|
|
330
|
-
'module encryption.credentialFields',
|
|
331
|
-
error
|
|
332
|
-
);
|
|
333
247
|
}
|
|
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);
|
|
334
255
|
}
|
|
335
256
|
}
|
|
336
257
|
|
|
@@ -465,7 +386,6 @@ function resetCustomSchema() {
|
|
|
465
386
|
}
|
|
466
387
|
|
|
467
388
|
module.exports = {
|
|
468
|
-
EncryptionSchemaError,
|
|
469
389
|
CORE_ENCRYPTION_SCHEMA,
|
|
470
390
|
getEncryptedFields,
|
|
471
391
|
getFieldsToEncryptOnWrite,
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
const { isEncryptedEnvelope } = require('./ciphertext-format');
|
|
2
|
-
|
|
3
1
|
/**
|
|
4
2
|
* Field Encryption Service
|
|
5
3
|
*
|
|
@@ -83,48 +81,6 @@ class FieldEncryptionService {
|
|
|
83
81
|
return encrypted;
|
|
84
82
|
}
|
|
85
83
|
|
|
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
|
-
|
|
128
84
|
async decryptFields(modelName, document) {
|
|
129
85
|
if (!document || typeof document !== 'object') {
|
|
130
86
|
return document;
|
|
@@ -191,7 +147,12 @@ class FieldEncryptionService {
|
|
|
191
147
|
}
|
|
192
148
|
|
|
193
149
|
_isEncrypted(value) {
|
|
194
|
-
|
|
150
|
+
if (typeof value !== 'string') {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const parts = value.split(':');
|
|
155
|
+
return parts.length >= 4;
|
|
195
156
|
}
|
|
196
157
|
|
|
197
158
|
_getNestedValue(obj, path) {
|
|
@@ -257,22 +218,22 @@ class FieldEncryptionService {
|
|
|
257
218
|
}
|
|
258
219
|
|
|
259
220
|
/**
|
|
260
|
-
* Serialize a value for encryption
|
|
261
|
-
*
|
|
262
|
-
* the round trip: '123456' is stored as "\"123456\"" and reads back as a
|
|
263
|
-
* string, 1234 reads back as a number.
|
|
221
|
+
* Serialize a value for encryption
|
|
222
|
+
* Objects/arrays are JSON stringified, primitives are converted to strings
|
|
264
223
|
* @private
|
|
265
224
|
*/
|
|
266
225
|
_serializeForEncryption(value) {
|
|
267
|
-
|
|
226
|
+
if (typeof value === 'object' && value !== null) {
|
|
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);
|
|
268
232
|
}
|
|
269
233
|
|
|
270
234
|
/**
|
|
271
|
-
* Deserialize a value after decryption
|
|
272
|
-
*
|
|
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.
|
|
235
|
+
* Deserialize a value after decryption
|
|
236
|
+
* Attempts to parse as JSON, returns string if parsing fails
|
|
276
237
|
* @private
|
|
277
238
|
*/
|
|
278
239
|
_deserializeAfterDecryption(value) {
|
|
@@ -114,15 +114,18 @@ 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
|
-
);
|
|
121
117
|
if (args.create) {
|
|
122
|
-
args.create =
|
|
118
|
+
args.create = await encryptionService.encryptFields(
|
|
119
|
+
model,
|
|
120
|
+
args.create
|
|
121
|
+
);
|
|
123
122
|
}
|
|
123
|
+
|
|
124
124
|
if (args.update) {
|
|
125
|
-
args.update =
|
|
125
|
+
args.update = await encryptionService.encryptFields(
|
|
126
|
+
model,
|
|
127
|
+
args.update
|
|
128
|
+
);
|
|
126
129
|
}
|
|
127
130
|
|
|
128
131
|
const result = await query(args);
|
package/database/prisma.js
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
const {
|
|
2
2
|
createEncryptionExtension,
|
|
3
3
|
} = require('./encryption/prisma-encryption-extension');
|
|
4
|
-
const {
|
|
5
|
-
loadCustomEncryptionSchema,
|
|
6
|
-
EncryptionSchemaError,
|
|
7
|
-
} = require('./encryption/encryption-schema-registry');
|
|
4
|
+
const { loadCustomEncryptionSchema } = require('./encryption/encryption-schema-registry');
|
|
8
5
|
const { logger } = require('./encryption/logger');
|
|
9
6
|
const { Cryptor } = require('../encrypt/Cryptor');
|
|
10
7
|
const config = require('./config');
|
|
@@ -128,12 +125,6 @@ const prismaClientSingleton = () => {
|
|
|
128
125
|
`Field-level encryption enabled using ${encryptionConfig.method.toUpperCase()}`
|
|
129
126
|
);
|
|
130
127
|
} 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
|
-
}
|
|
137
128
|
logger.error(
|
|
138
129
|
'Failed to initialize encryption extension:',
|
|
139
130
|
error
|
package/encrypt/Cryptor.js
CHANGED
|
@@ -20,86 +20,26 @@ 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
|
-
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;
|
|
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
|
-
}
|
|
23
|
+
class Cryptor {
|
|
24
|
+
constructor({ shouldUseAws }) {
|
|
25
|
+
this.shouldUseAws = shouldUseAws;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async generateDataKey() {
|
|
29
|
+
if (this.shouldUseAws) {
|
|
30
|
+
const kmsClient = new KMSClient({});
|
|
31
|
+
const command = new GenerateDataKeyCommand({
|
|
32
|
+
KeyId: process.env.KMS_KEY_ARN,
|
|
33
|
+
KeySpec: 'AES_256',
|
|
95
34
|
});
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
35
|
+
const dataKey = await kmsClient.send(command);
|
|
36
|
+
|
|
37
|
+
const keyId = Buffer.from(dataKey.KeyId).toString('base64');
|
|
38
|
+
const encryptedKey = Buffer.from(dataKey.CiphertextBlob).toString('base64');
|
|
39
|
+
const plaintext = dataKey.Plaintext;
|
|
40
|
+
return { keyId, encryptedKey, plaintext };
|
|
41
|
+
}
|
|
100
42
|
|
|
101
|
-
const localDataKeys = {
|
|
102
|
-
async generate() {
|
|
103
43
|
const { AES_KEY, AES_KEY_ID } = process.env;
|
|
104
44
|
const randomKey = crypto.randomBytes(32).toString('hex').slice(0, 32);
|
|
105
45
|
|
|
@@ -110,9 +50,9 @@ const localDataKeys = {
|
|
|
110
50
|
),
|
|
111
51
|
plaintext: randomKey,
|
|
112
52
|
};
|
|
113
|
-
}
|
|
53
|
+
}
|
|
114
54
|
|
|
115
|
-
|
|
55
|
+
getKeyFromEnvironment(keyId) {
|
|
116
56
|
const availableKeys = {
|
|
117
57
|
[process.env.AES_KEY_ID]: process.env.AES_KEY,
|
|
118
58
|
[process.env.DEPRECATED_AES_KEY_ID]: process.env.DEPRECATED_AES_KEY,
|
|
@@ -124,20 +64,27 @@ const localDataKeys = {
|
|
|
124
64
|
throw new Error('Encryption key not found');
|
|
125
65
|
}
|
|
126
66
|
|
|
127
|
-
return
|
|
128
|
-
}
|
|
129
|
-
|
|
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);
|
|
130
78
|
|
|
131
|
-
|
|
79
|
+
return dataKey.Plaintext;
|
|
80
|
+
}
|
|
132
81
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
this.shouldUseAws = shouldUseAws;
|
|
136
|
-
this.dataKeys = shouldUseAws ? kmsDataKeys : localDataKeys;
|
|
82
|
+
const key = this.getKeyFromEnvironment(keyId);
|
|
83
|
+
return aes.decrypt(encryptedKey, key);
|
|
137
84
|
}
|
|
138
85
|
|
|
139
86
|
async encrypt(text) {
|
|
140
|
-
const { keyId, encryptedKey, plaintext } = await this.
|
|
87
|
+
const { keyId, encryptedKey, plaintext } = await this.generateDataKey();
|
|
141
88
|
const encryptedText = aes.encrypt(text, plaintext);
|
|
142
89
|
return `${keyId}:${encryptedText}:${encryptedKey}`;
|
|
143
90
|
}
|
|
@@ -146,7 +93,8 @@ class Cryptor {
|
|
|
146
93
|
const split = text.split(':');
|
|
147
94
|
const keyId = Buffer.from(split[0], 'base64').toString();
|
|
148
95
|
const encryptedText = `${split[1]}:${split[2]}`;
|
|
149
|
-
const
|
|
96
|
+
const encryptedKey = Buffer.from(split[3], 'base64');
|
|
97
|
+
const plaintext = await this.decryptDataKey(keyId, encryptedKey);
|
|
150
98
|
return aes.decrypt(encryptedText, plaintext);
|
|
151
99
|
}
|
|
152
100
|
}
|
package/errors/fetch-error.js
CHANGED
|
@@ -12,21 +12,10 @@ 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
|
-
|
|
21
15
|
function causeLabel(cause) {
|
|
22
16
|
if (!cause || typeof cause !== 'object') return '';
|
|
23
17
|
const label = cause.code ?? cause.name;
|
|
24
|
-
|
|
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(': ');
|
|
18
|
+
return label === undefined || label === null ? '' : scrubString(String(label));
|
|
30
19
|
}
|
|
31
20
|
|
|
32
21
|
function buildMessage({ method, url, response, cause }) {
|
|
@@ -66,12 +55,16 @@ class FetchError extends BaseError {
|
|
|
66
55
|
|
|
67
56
|
static async create(options = {}) {
|
|
68
57
|
const { response } = options;
|
|
69
|
-
let responseBody =
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
58
|
+
let { responseBody } = options;
|
|
59
|
+
if (responseBody === undefined || responseBody === null) {
|
|
60
|
+
const canRead =
|
|
61
|
+
response &&
|
|
62
|
+
!response.bodyUsed &&
|
|
63
|
+
typeof response.text === 'function';
|
|
64
|
+
responseBody = (canRead && (await response.text())) || options.body;
|
|
65
|
+
}
|
|
66
|
+
const ErrorClass = typeof this === 'function' ? this : FetchError;
|
|
67
|
+
return new ErrorClass({ ...options, responseBody });
|
|
75
68
|
}
|
|
76
69
|
}
|
|
77
70
|
|
package/errors/index.js
CHANGED
|
@@ -1,21 +1,19 @@
|
|
|
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');
|
|
4
5
|
const {
|
|
5
6
|
RequiredPropertyError,
|
|
6
7
|
ParameterTypeError,
|
|
7
8
|
} = require('./validation-errors');
|
|
8
9
|
const { ClientSafeError } = require('./client-safe-error');
|
|
9
|
-
const {
|
|
10
|
-
MappingAlreadyExistsError,
|
|
11
|
-
} = require('./mapping-already-exists-error');
|
|
12
10
|
|
|
13
11
|
module.exports = {
|
|
14
12
|
BaseError,
|
|
15
13
|
FetchError,
|
|
16
14
|
HaltError,
|
|
15
|
+
RateLimitError,
|
|
17
16
|
RequiredPropertyError,
|
|
18
17
|
ParameterTypeError,
|
|
19
18
|
ClientSafeError,
|
|
20
|
-
MappingAlreadyExistsError,
|
|
21
19
|
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
const { FetchError } = require('./fetch-error');
|
|
2
|
+
|
|
3
|
+
function resolveTiming({ hint, waitMs, now }) {
|
|
4
|
+
if (waitMs !== undefined) {
|
|
5
|
+
return { waitMs, retryAt: new Date(now + waitMs) };
|
|
6
|
+
}
|
|
7
|
+
if (hint?.retryAt) {
|
|
8
|
+
const retryAt = new Date(hint.retryAt);
|
|
9
|
+
if (!Number.isNaN(retryAt.getTime())) {
|
|
10
|
+
return { waitMs: Math.max(0, retryAt.getTime() - now), retryAt };
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
if (hint?.waitMs !== undefined) {
|
|
14
|
+
return {
|
|
15
|
+
waitMs: hint.waitMs,
|
|
16
|
+
retryAt: new Date(now + hint.waitMs),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
return { waitMs: undefined, retryAt: undefined };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
class RateLimitError extends FetchError {
|
|
23
|
+
constructor({
|
|
24
|
+
hint,
|
|
25
|
+
waitMs,
|
|
26
|
+
module,
|
|
27
|
+
scopeKey,
|
|
28
|
+
now = Date.now(),
|
|
29
|
+
...fetchErrorArgs
|
|
30
|
+
} = {}) {
|
|
31
|
+
super(fetchErrorArgs);
|
|
32
|
+
|
|
33
|
+
const timing = resolveTiming({ hint, waitMs, now });
|
|
34
|
+
this.isRateLimited = true;
|
|
35
|
+
this.waitMs = timing.waitMs;
|
|
36
|
+
this.retryAt = timing.retryAt;
|
|
37
|
+
this.reason = hint?.reason ?? 'unknown';
|
|
38
|
+
this.policy = hint?.policy;
|
|
39
|
+
this.source = hint?.source ?? 'unknown';
|
|
40
|
+
this.module = module;
|
|
41
|
+
this.scopeKey = scopeKey;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = { RateLimitError };
|
package/handlers/WEBHOOKS.md
CHANGED
|
@@ -483,35 +483,6 @@ async onWebhook({ data }) {
|
|
|
483
483
|
}
|
|
484
484
|
```
|
|
485
485
|
|
|
486
|
-
`getMapping` followed by `upsertMapping` is not atomic. To claim an event so only one
|
|
487
|
-
concurrent worker proceeds, use the insert-only `createMapping`, which throws
|
|
488
|
-
`MappingAlreadyExistsError` (exported from `@friggframework/core`) when the
|
|
489
|
-
`sourceId` is already taken. `deleteMapping(sourceId)` releases the claim and is a
|
|
490
|
-
no-op when nothing exists.
|
|
491
|
-
|
|
492
|
-
```javascript
|
|
493
|
-
const { MappingAlreadyExistsError } = require('@friggframework/core');
|
|
494
|
-
|
|
495
|
-
async onWebhook({ data }) {
|
|
496
|
-
const claimId = `claim:${data.body.id}`;
|
|
497
|
-
try {
|
|
498
|
-
await this.createMapping(claimId, { claimedAt: new Date() });
|
|
499
|
-
} catch (error) {
|
|
500
|
-
if (error instanceof MappingAlreadyExistsError) {
|
|
501
|
-
return { processed: false, duplicate: true };
|
|
502
|
-
}
|
|
503
|
-
throw error;
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
try {
|
|
507
|
-
await this.processEvent(data.body);
|
|
508
|
-
} catch (error) {
|
|
509
|
-
await this.deleteMapping(claimId);
|
|
510
|
-
throw error;
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
```
|
|
514
|
-
|
|
515
486
|
### 4. Error Handling
|
|
516
487
|
```javascript
|
|
517
488
|
async onWebhook({ data }) {
|