@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.
Files changed (77) hide show
  1. package/CLAUDE.md +14 -42
  2. package/application/commands/README.md +11 -17
  3. package/application/commands/entity-commands.js +60 -18
  4. package/application/commands/integration-commands.js +0 -63
  5. package/core/CLAUDE.md +3 -1
  6. package/core/create-handler.js +3 -0
  7. package/core/index.js +6 -0
  8. package/core/invocation-deadline.js +91 -0
  9. package/core/invocation-scope.js +30 -24
  10. package/database/documentdb-encryption-service.js +33 -2
  11. package/database/documentdb-utils.js +1 -4
  12. package/database/encryption/README.md +3 -3
  13. package/database/encryption/encryption-schema-registry.js +29 -109
  14. package/database/encryption/field-encryption-service.js +16 -55
  15. package/database/encryption/prisma-encryption-extension.js +9 -6
  16. package/database/prisma.js +1 -10
  17. package/encrypt/Cryptor.js +38 -90
  18. package/errors/fetch-error.js +11 -18
  19. package/errors/index.js +2 -4
  20. package/errors/rate-limit-error.js +45 -0
  21. package/handlers/WEBHOOKS.md +0 -29
  22. package/handlers/app-definition-loader.js +2 -9
  23. package/handlers/app-handler-helpers.js +1 -12
  24. package/handlers/backend-utils.js +2 -1
  25. package/handlers/workers/integration-defined-workers.js +2 -0
  26. package/index.js +18 -2
  27. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +13 -67
  28. package/integrations/integration-base.js +9 -52
  29. package/integrations/integration-router.js +22 -30
  30. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  31. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  32. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  33. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  34. package/integrations/repositories/integration-mapping-repository.js +0 -29
  35. package/integrations/repositories/integration-repository-documentdb.js +0 -32
  36. package/integrations/repositories/integration-repository-interface.js +0 -30
  37. package/integrations/repositories/integration-repository-mongo.js +1 -53
  38. package/integrations/repositories/integration-repository-postgres.js +0 -58
  39. package/integrations/repositories/process-repository-mongo.js +1 -1
  40. package/integrations/use-cases/create-integration.js +19 -57
  41. package/integrations/use-cases/delete-integration-for-user.js +11 -8
  42. package/integrations/use-cases/get-integration-instance.js +12 -12
  43. package/integrations/use-cases/update-integration.js +12 -12
  44. package/jest-setup.js +2 -13
  45. package/jest-teardown.js +2 -5
  46. package/jest.config.js +0 -4
  47. package/logs/serialize.js +15 -0
  48. package/modules/requester/rate-limit/index.js +4 -0
  49. package/modules/requester/rate-limit/parsers.js +245 -0
  50. package/modules/requester/rate-limit/policy.js +304 -0
  51. package/modules/requester/requester.js +187 -9
  52. package/modules/use-cases/get-entity-options-by-id.js +5 -7
  53. package/modules/use-cases/get-module.js +8 -29
  54. package/modules/use-cases/process-authorization-callback.js +27 -78
  55. package/modules/use-cases/refresh-entity-options.js +5 -7
  56. package/modules/use-cases/test-module-auth.js +5 -7
  57. package/modules/utils/map-module-dto.js +3 -5
  58. package/package.json +7 -10
  59. package/queues/queuer-util.js +5 -6
  60. package/token/repositories/token-repository-documentdb.js +1 -13
  61. package/token/repositories/token-repository-mongo.js +1 -13
  62. package/token/repositories/token-repository-postgres.js +1 -13
  63. package/types/core/index.d.ts +33 -0
  64. package/types/errors/index.d.ts +47 -0
  65. package/types/module-plugin/index.d.ts +43 -0
  66. package/user/tests/doubles/test-user-repository.js +1 -1
  67. package/user/use-cases/authenticate-user.js +7 -23
  68. package/user/use-cases/get-user-from-bearer-token.js +2 -7
  69. package/database/encryption/ciphertext-format.js +0 -24
  70. package/errors/mapping-already-exists-error.js +0 -14
  71. package/integrations/use-cases/add-entities-to-integration.js +0 -92
  72. package/integrations/use-cases/remove-entities-from-integration.js +0 -70
  73. package/integrations/utils/assert-entity-ids-input.js +0 -42
  74. package/jest.db.config.js +0 -23
  75. package/modules/use-cases/create-entity-from-credential.js +0 -105
  76. package/modules/utils/find-module-definition.js +0 -23
  77. package/modules/utils/to-credential-id.js +0 -14
package/CLAUDE.md CHANGED
@@ -206,51 +206,11 @@ packages/core/
206
206
  - `delete-integration-for-user.js` - Remove integration
207
207
  - `get-integration-instance.js` - Load integration with modules
208
208
  - `load-integration-context.js` - Full integration context loading
209
- - `add-entities-to-integration.js` / `remove-entities-from-integration.js` - Attach or detach entities on an existing integration
210
209
 
211
210
  **Repositories**:
212
211
  - `integration-repository-factory.js` - Creates database-specific repositories
213
212
  - `integration-repository-mongo.js` - MongoDB implementation
214
213
  - `integration-repository-postgres.js` - PostgreSQL implementation
215
- - `addEntitiesToIntegration(integrationId, entityIds)` /
216
- `removeEntitiesFromIntegration(integrationId, entityIds)` change the entity
217
- set of an existing integration (all three adapters; `null` for an unknown
218
- integration). Reach them through the `addEntitiesToIntegration` /
219
- `removeEntitiesFromIntegration` commands. The add use case
220
- (`add-entities-to-integration.js`) rejects unknown entities
221
- (`ENTITIES_NOT_FOUND`, 404), entities of another user
222
- (`ENTITY_USER_MISMATCH`, 403) and entities of a module the integration does
223
- not already hold (`ENTITY_MODULE_MISMATCH`, 400). The remove use case
224
- (`remove-entities-from-integration.js`) refuses to leave a module with no
225
- entity (`LAST_ENTITY_OF_MODULE`, 409). Re-adding an attached entity or
226
- removing a detached one changes nothing; a detached entity is not deleted.
227
- `integration-repository-entities-parity.db.test.js` runs every adapter against
228
- real databases when `INTEGRATION_ENTITIES_PARITY_MONGO_URL` /
229
- `INTEGRATION_ENTITIES_PARITY_POSTGRES_URL` are set. The DocumentDB adapter
230
- writes only `Integration.entityIds` (as its `createIntegration` does), not
231
- `Entity.integrationIds`.
232
- **One credential, many accounts**: when one credential covers several
233
- provider accounts, give each account its own entity (externalId = account
234
- id) and attach them all to one integration; webhooks then route with
235
- `findIntegrationByEntityExternalId`. Traps:
236
- (1) `IntegrationBase` keys modules by module name, so `this.<moduleKey>`
237
- holds only one entity's module, and on the queue/webhook path
238
- (`get-integration-instance.js`) `this.entities` holds entity **ids**, not
239
- records. For per-account work (a webhook for one account, teardown of every
240
- account in `onDelete`), load
241
- `this.commands.loadIntegrationContextById(this.id)` and use
242
- `context.modules`: one module per entity, each with its record on
243
- `module.entity` (pick by `module.entity.externalId`).
244
- (2) `findIntegrationByEntityExternalId` counts every entity with that
245
- externalId, attached or not, across users: reuse an existing entity
246
- (`findEntity`) when an account comes back, or delete it when it is revoked,
247
- never create a second one.
248
- (3) `createIntegration` reuses an existing integration of the same user
249
- and type whose entities include all requested ones (an exact match wins),
250
- so a reconnect that sends the original entities finds the integration that
251
- now holds more.
252
- (4) Every module's delegate is the integration: an auth failure on any
253
- account marks the shared credential invalid and the integration ERROR.
254
214
  - `integration-mapping-repository-*.js` - Mapping data persistence.
255
215
  `queryMappings(integrationId, { where, orderBy, skip, take, omit })`
256
216
  returns `{ mappings, total }`: one filtered, ordered page of an
@@ -266,7 +226,7 @@ packages/core/
266
226
  mapping keys to leave out of the rows; never write such rows back. Path
267
227
  segments must match `^[A-Za-z_][A-Za-z0-9_]*$`. The PostgreSQL, MongoDB and
268
228
  DocumentDB adapters give the same pages and totals;
269
- `integration-mapping-repository-query-parity.db.test.js` checks that against
229
+ `integration-mapping-repository-query-parity.test.js` checks that against
270
230
  real databases when `QUERY_MAPPINGS_PARITY_MONGO_URL` /
271
231
  `QUERY_MAPPINGS_PARITY_POSTGRES_URL` are set. Two orderings still differ:
272
232
  strings compare by the database collation on PostgreSQL and by code point
@@ -409,6 +369,16 @@ class MyIntegration extends IntegrationBase {
409
369
  - `ApiKeyRequester` - API key authentication
410
370
  - `BasicAuthRequester` - Basic authentication
411
371
 
372
+ **Rate limits** (ADR-049): an API module declares `static rateLimit` on its
373
+ `Requester` subclass. A hinted wait (from `classify()`, the header parsers or
374
+ the static policy) sleeps within a budget that the caller owns (10 s in an HTTP
375
+ handler, 60 s in a queue worker, 300 s outside an invocation, at most 10
376
+ hinted retries), or throws `RateLimitError`
377
+ (`isRateLimited`, `retryAt`) when it does not fit. A 429 with no hint keeps the
378
+ fixed `backOff` ladder. A non-429 limit that `classify` names without a time
379
+ throws `RateLimitError` at once, with `retryAt` unknown. See
380
+ [Rate Limits](../../docs/reference/api-module-definition-and-functions.md#rate-limits-static-ratelimit).
381
+
412
382
  **Module Factory**:
413
383
  - `ModuleFactory` - Creates and configures API module instances
414
384
  - Handles credential injection
@@ -517,7 +487,8 @@ handlers (`{ req, res, next }`) and `this.on` events do not.
517
487
  `isLastAttempt` is `false` when either count is unknown: a local or non-SQS
518
488
  invocation, or a queue whose redrive policy the stack does not own
519
489
  (`ownership.queue: 'external'`). The value is information only: core still
520
- rethrows retryable errors and discards halt errors (4xx except 408/429).
490
+ rethrows retryable errors and discards halt errors (4xx except 408, 429 and
491
+ errors with `isRateLimited`).
521
492
 
522
493
  Use it to end a run or count lost work on the final try: when a retryable
523
494
  error (429, 5xx, network) is about to be rethrown and `isLastAttempt` is
@@ -547,6 +518,7 @@ it as `FRIGG_QUEUE_MAX_RECEIVE_COUNT` on the queue worker function.
547
518
  **Error Types**:
548
519
  - `BaseError` - Base error class
549
520
  - `FetchError` - HTTP request failures
521
+ - `RateLimitError` - A `FetchError` for a limit the provider or the module's policy says when to retry (`retryAt`)
550
522
  - `HaltError` - Stop processing without retry
551
523
  - `RequiredPropertyError` - Missing required parameters
552
524
  - `ParameterTypeError` - Invalid parameter type
@@ -67,10 +67,9 @@ class MyIntegration extends IntegrationBase {
67
67
  async hydrateFromExternalUser(externalUserId) {
68
68
  // Find integration context by external entity ID
69
69
  const result =
70
- await this.commands.findIntegrationContextByExternalEntityId({
71
- externalId: externalUserId,
72
- type: 'my-integration', // integration config.type to match
73
- });
70
+ await this.commands.findIntegrationContextByExternalEntityId(
71
+ externalUserId
72
+ );
74
73
 
75
74
  if (result.error) {
76
75
  return { error: result.error };
@@ -232,10 +231,9 @@ Manage integration records and load full integration contexts.
232
231
  ```javascript
233
232
  // Find integration context by external entity ID
234
233
  // Returns { context, error } where context includes record + hydrated modules
235
- const result = await commands.findIntegrationContextByExternalEntityId({
236
- externalId: 'external-user-or-workspace-id',
237
- type: 'my-integration', // integration config.type to match
238
- });
234
+ const result = await commands.findIntegrationContextByExternalEntityId(
235
+ 'external-user-or-workspace-id'
236
+ );
239
237
 
240
238
  if (!result.error) {
241
239
  integration.setIntegrationRecord(result.context);
@@ -301,10 +299,7 @@ try {
301
299
  For integration context operations, errors are returned in the result:
302
300
 
303
301
  ```javascript
304
- const result = await commands.findIntegrationContextByExternalEntityId({
305
- externalId: userId,
306
- type: 'my-integration',
307
- });
302
+ const result = await commands.findIntegrationContextByExternalEntityId(userId);
308
303
 
309
304
  if (result.error) {
310
305
  return { error: result.error };
@@ -354,10 +349,9 @@ const result =
354
349
  const { createFriggCommands } = require('@friggframework/core');
355
350
 
356
351
  this.commands = createFriggCommands({ integrationClass: MyIntegration });
357
- const result = await this.commands.findIntegrationContextByExternalEntityId({
358
- externalId: userId,
359
- type: 'my-integration',
360
- });
352
+ const result = await this.commands.findIntegrationContextByExternalEntityId(
353
+ userId
354
+ );
361
355
  ```
362
356
 
363
357
  ## Best Practices
@@ -439,7 +433,7 @@ if (!user) {
439
433
  | | `findEntitiesByIds(ids)` | Find multiple by IDs |
440
434
  | | `updateEntity(id, updates)` | Update entity properties |
441
435
  | | `deleteEntity(id)` | Delete entity |
442
- | **Integration** | `findIntegrationContextByExternalEntityId({ externalId, type })` | Load integration + modules by external ID |
436
+ | **Integration** | `findIntegrationContextByExternalEntityId(externalId)` | Load integration + modules by external ID |
443
437
  | | `loadIntegrationContextById(integrationId)` | Load integration + modules by ID |
444
438
 
445
439
  ## Support
@@ -1,24 +1,12 @@
1
1
  const {
2
2
  createModuleRepository,
3
3
  } = require('../../modules/repositories/module-repository-factory');
4
- const { toCredentialId } = require('../../modules/utils/to-credential-id');
5
4
 
6
5
  const ERROR_CODE_MAP = {
7
6
  ENTITY_NOT_FOUND: 404,
8
7
  INVALID_ENTITY_DATA: 400,
9
8
  };
10
9
 
11
- function toEntityDto(entity) {
12
- return {
13
- id: entity.id,
14
- userId: entity.userId,
15
- externalId: entity.externalId,
16
- name: entity.name,
17
- moduleName: entity.moduleName,
18
- credentialId: toCredentialId(entity.credential),
19
- };
20
- }
21
-
22
10
  function mapErrorToResponse(error) {
23
11
  const status = ERROR_CODE_MAP[error?.code] || 500;
24
12
  return {
@@ -78,7 +66,16 @@ function createEntityCommands() {
78
66
 
79
67
  const entity = await moduleRepo.createEntity(entityData);
80
68
 
81
- return toEntityDto(entity);
69
+ return {
70
+ id: entity.id,
71
+ userId: entity.userId,
72
+ externalId: entity.externalId,
73
+ name: entity.name,
74
+ moduleName: entity.moduleName,
75
+ credentialId: entity.credential?._id
76
+ ? entity.credential._id.toString()
77
+ : entity.credential,
78
+ };
82
79
  } catch (error) {
83
80
  return mapErrorToResponse(error);
84
81
  }
@@ -112,7 +109,16 @@ function createEntityCommands() {
112
109
  return null;
113
110
  }
114
111
 
115
- return toEntityDto(entity);
112
+ return {
113
+ id: entity.id,
114
+ userId: entity.userId,
115
+ externalId: entity.externalId,
116
+ name: entity.name,
117
+ moduleName: entity.moduleName,
118
+ credentialId: entity.credential?._id
119
+ ? entity.credential._id.toString()
120
+ : entity.credential,
121
+ };
116
122
  } catch (error) {
117
123
  return mapErrorToResponse(error);
118
124
  }
@@ -133,7 +139,16 @@ function createEntityCommands() {
133
139
 
134
140
  const entities = await moduleRepo.findEntitiesByUserId(userId);
135
141
 
136
- return entities.map((entity) => toEntityDto(entity));
142
+ return entities.map((entity) => ({
143
+ id: entity.id,
144
+ userId: entity.userId,
145
+ externalId: entity.externalId,
146
+ name: entity.name,
147
+ moduleName: entity.moduleName,
148
+ credentialId: entity.credential?._id
149
+ ? entity.credential._id.toString()
150
+ : entity.credential,
151
+ }));
137
152
  } catch (error) {
138
153
  if (error.code) {
139
154
  return mapErrorToResponse(error);
@@ -165,7 +180,16 @@ function createEntityCommands() {
165
180
  moduleName
166
181
  );
167
182
 
168
- return entities.map((entity) => toEntityDto(entity));
183
+ return entities.map((entity) => ({
184
+ id: entity.id,
185
+ userId: entity.userId,
186
+ externalId: entity.externalId,
187
+ name: entity.name,
188
+ moduleName: entity.moduleName,
189
+ credentialId: entity.credential?._id
190
+ ? entity.credential._id.toString()
191
+ : entity.credential,
192
+ }));
169
193
  } catch (error) {
170
194
  if (error.code) {
171
195
  return mapErrorToResponse(error);
@@ -189,7 +213,16 @@ function createEntityCommands() {
189
213
 
190
214
  const entity = await moduleRepo.findEntityById(entityId);
191
215
 
192
- return toEntityDto(entity);
216
+ return {
217
+ id: entity.id,
218
+ userId: entity.userId,
219
+ externalId: entity.externalId,
220
+ name: entity.name,
221
+ moduleName: entity.moduleName,
222
+ credentialId: entity.credential?._id
223
+ ? entity.credential._id.toString()
224
+ : entity.credential,
225
+ };
193
226
  } catch (error) {
194
227
  return mapErrorToResponse(error);
195
228
  }
@@ -217,7 +250,16 @@ function createEntityCommands() {
217
250
  throw error;
218
251
  }
219
252
 
220
- return toEntityDto(entity);
253
+ return {
254
+ id: entity.id,
255
+ userId: entity.userId,
256
+ externalId: entity.externalId,
257
+ name: entity.name,
258
+ moduleName: entity.moduleName,
259
+ credentialId: entity.credential?._id
260
+ ? entity.credential._id.toString()
261
+ : entity.credential,
262
+ };
221
263
  } catch (error) {
222
264
  return mapErrorToResponse(error);
223
265
  }
@@ -29,12 +29,6 @@ const {
29
29
  const {
30
30
  PatchIntegrationConfig,
31
31
  } = require('../../integrations/use-cases/patch-integration-config');
32
- const {
33
- AddEntitiesToIntegration,
34
- } = require('../../integrations/use-cases/add-entities-to-integration');
35
- const {
36
- RemoveEntitiesFromIntegration,
37
- } = require('../../integrations/use-cases/remove-entities-from-integration');
38
32
  const {
39
33
  getModulesDefinitionFromIntegrationClasses,
40
34
  } = require('../../integrations/utils/map-integration-dto');
@@ -46,11 +40,6 @@ const ERROR_CODE_MAP = {
46
40
  EXTERNAL_ID_REQUIRED: 400,
47
41
  TYPE_REQUIRED: 400,
48
42
  INTEGRATION_RECORD_NOT_FOUND: 404,
49
- INVALID_INTEGRATION_DATA: 400,
50
- ENTITIES_NOT_FOUND: 404,
51
- ENTITY_USER_MISMATCH: 403,
52
- ENTITY_MODULE_MISMATCH: 400,
53
- LAST_ENTITY_OF_MODULE: 409,
54
43
  };
55
44
 
56
45
  function mapErrorToResponse(error) {
@@ -174,17 +163,6 @@ function createIntegrationCommands({ integrationClass } = {}) {
174
163
  integrationRepository,
175
164
  });
176
165
 
177
- const addEntitiesToIntegrationUseCase = new AddEntitiesToIntegration({
178
- integrationRepository,
179
- moduleRepository,
180
- });
181
-
182
- const removeEntitiesFromIntegrationUseCase =
183
- new RemoveEntitiesFromIntegration({
184
- integrationRepository,
185
- moduleRepository,
186
- });
187
-
188
166
  return {
189
167
  findIntegrationById,
190
168
  listIntegrations,
@@ -329,47 +307,6 @@ function createIntegrationCommands({ integrationClass } = {}) {
329
307
  }
330
308
  },
331
309
 
332
- /**
333
- * Attach entities to an existing integration. Every entity must
334
- * exist, belong to the integration's user, and be of a module the
335
- * integration already holds; entities that are already attached are
336
- * left as they are.
337
- * @param {Object} params
338
- * @param {string} params.integrationId - Integration ID
339
- * @param {Array<string>} params.entityIds - Entity IDs to attach
340
- * @returns {Promise<Object>} Updated integration
341
- */
342
- async addEntitiesToIntegration({ integrationId, entityIds }) {
343
- try {
344
- return await addEntitiesToIntegrationUseCase.execute(
345
- integrationId,
346
- entityIds
347
- );
348
- } catch (error) {
349
- return mapErrorToResponse(error);
350
- }
351
- },
352
-
353
- /**
354
- * Detach entities from an integration. Entities that are not
355
- * attached are ignored; detached entities are not deleted. Each
356
- * module must keep at least one entity.
357
- * @param {Object} params
358
- * @param {string} params.integrationId - Integration ID
359
- * @param {Array<string>} params.entityIds - Entity IDs to detach
360
- * @returns {Promise<Object>} Updated integration
361
- */
362
- async removeEntitiesFromIntegration({ integrationId, entityIds }) {
363
- try {
364
- return await removeEntitiesFromIntegrationUseCase.execute(
365
- integrationId,
366
- entityIds
367
- );
368
- } catch (error) {
369
- return mapErrorToResponse(error);
370
- }
371
- },
372
-
373
310
  /**
374
311
  * Delete an integration by ID
375
312
  * @param {string} integrationId - Integration ID to delete
package/core/CLAUDE.md CHANGED
@@ -130,7 +130,7 @@ class MyIntegration extends Delegate {
130
130
  ### Lambda Handler Lifecycle
131
131
  1. **Pre-Execution Setup**:
132
132
  ```javascript
133
- runInvocationScope({ requestId, handlerName, method, route, invocation }, …); // Logger scope for the invocation
133
+ runInvocationScope({ requestId, handlerName, method, route, invocation }, …); // Logger scope + invocation deadline (remainingInvocationMs()) + in-process wait budget (createHandler `maxInProcessWaitMs`: 10 s HTTP, 60 s queue worker)
134
134
  log.info('Handler invoked', { eventName: 'frigg.handler.invoked' });
135
135
  await secretsToEnv(); // Secrets Manager injection
136
136
  await parametersToEnv(); // SSM Parameter Store fetch (only when SSM_PARAMETER_PREFIX + FRIGG_SSM_OFFLOADED_KEYS are set)
@@ -226,6 +226,8 @@ const handler = createHandler({
226
226
  - Logs error but returns success
227
227
  - Prevents infinite retries for known issues
228
228
  - Used for graceful degradation scenarios
229
+ - The queue worker sets it on a 4xx except 408, 429 and errors with
230
+ `isRateLimited` (a provider limit signalled with 403 clears with time)
229
231
 
230
232
  ### Logging Strategy
231
233
  ```javascript
@@ -12,6 +12,7 @@ const {
12
12
  runInvocationScope,
13
13
  DEFAULT_FLUSH_TIMEOUT_MS,
14
14
  } = require('./invocation-scope');
15
+ const { MAX_IN_PROCESS_WAIT_MS } = require('./invocation-deadline');
15
16
  const { secretsToEnv } = require('./secrets-to-env');
16
17
  const { parametersToEnv } = require('./parameters-to-env');
17
18
  const {
@@ -31,6 +32,7 @@ const createHandler = (optionByName = {}) => {
31
32
  telemetry,
32
33
  flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
33
34
  usageRollup,
35
+ maxInProcessWaitMs = MAX_IN_PROCESS_WAIT_MS.http,
34
36
  } = optionByName;
35
37
 
36
38
  if (!method) {
@@ -144,6 +146,7 @@ const createHandler = (optionByName = {}) => {
144
146
  shouldUseDatabase,
145
147
  flushTimeoutMs,
146
148
  context,
149
+ maxInProcessWaitMs,
147
150
  }
148
151
  );
149
152
  };
package/core/index.js CHANGED
@@ -3,6 +3,10 @@ const { Worker } = require('./Worker');
3
3
  const { loadInstalledModules } = require('./load-installed-modules');
4
4
  const { createHandler } = require('./create-handler');
5
5
  const { runInvocationScope } = require('./invocation-scope');
6
+ const {
7
+ runWithInvocationDeadline,
8
+ remainingInvocationMs,
9
+ } = require('./invocation-deadline');
6
10
 
7
11
  module.exports = {
8
12
  Delegate,
@@ -10,4 +14,6 @@ module.exports = {
10
14
  loadInstalledModules,
11
15
  createHandler,
12
16
  runInvocationScope,
17
+ runWithInvocationDeadline,
18
+ remainingInvocationMs,
13
19
  };
@@ -0,0 +1,91 @@
1
+ const { AsyncLocalStorage } = require('node:async_hooks');
2
+
3
+ const STORE_KEY = Symbol.for('@friggframework/core.invocation-deadline');
4
+
5
+ function storage() {
6
+ if (!globalThis[STORE_KEY]) {
7
+ globalThis[STORE_KEY] = new AsyncLocalStorage();
8
+ }
9
+ return globalThis[STORE_KEY];
10
+ }
11
+
12
+ const MAX_IN_PROCESS_WAIT_MS = Object.freeze({
13
+ outsideInvocation: 300_000,
14
+ http: 10_000,
15
+ queueWorker: 60_000,
16
+ });
17
+
18
+ const validDeadline = (value) =>
19
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;
20
+
21
+ const validWait = (value) =>
22
+ typeof value === 'number' && Number.isFinite(value) && value >= 0
23
+ ? value
24
+ : undefined;
25
+
26
+ const lower = (outer, next) =>
27
+ outer === undefined
28
+ ? next
29
+ : next === undefined
30
+ ? outer
31
+ : Math.min(outer, next);
32
+
33
+ function runWithInvocationDeadline(
34
+ { deadlineAt, maxInProcessWaitMs } = {},
35
+ fn
36
+ ) {
37
+ const outer = storage().getStore();
38
+ const effectiveDeadline = lower(
39
+ outer?.deadlineAt,
40
+ validDeadline(deadlineAt)
41
+ );
42
+ const effectiveWait = lower(
43
+ outer?.maxInProcessWaitMs,
44
+ validWait(maxInProcessWaitMs)
45
+ );
46
+ if (effectiveDeadline === undefined && effectiveWait === undefined) {
47
+ return fn();
48
+ }
49
+ return storage().run(
50
+ Object.freeze({
51
+ deadlineAt: effectiveDeadline ?? Infinity,
52
+ maxInProcessWaitMs: effectiveWait,
53
+ }),
54
+ fn
55
+ );
56
+ }
57
+
58
+ function remainingTimeMs(context) {
59
+ try {
60
+ const remaining = context?.getRemainingTimeInMillis?.();
61
+ return typeof remaining === 'number' ? remaining : Infinity;
62
+ } catch (_) {
63
+ return Infinity;
64
+ }
65
+ }
66
+
67
+ function deadlineFromContext(context) {
68
+ const remaining = remainingTimeMs(context);
69
+ return Number.isFinite(remaining) ? Date.now() + remaining : undefined;
70
+ }
71
+
72
+ function remainingInvocationMs(now = Date.now()) {
73
+ const store = storage().getStore();
74
+ return store ? Math.max(0, store.deadlineAt - now) : Infinity;
75
+ }
76
+
77
+ function invocationMaxInProcessWaitMs() {
78
+ return (
79
+ storage().getStore()?.maxInProcessWaitMs ??
80
+ MAX_IN_PROCESS_WAIT_MS.outsideInvocation
81
+ );
82
+ }
83
+
84
+ module.exports = {
85
+ MAX_IN_PROCESS_WAIT_MS,
86
+ deadlineFromContext,
87
+ invocationMaxInProcessWaitMs,
88
+ remainingInvocationMs,
89
+ remainingTimeMs,
90
+ runWithInvocationDeadline,
91
+ };
@@ -1,6 +1,11 @@
1
1
  const { runInContext, LOGGER_SCOPE_KEY } = require('../logs/context');
2
2
  const { summarizeMessageBody } = require('../logs/summarize-event');
3
3
  const { flushSinks, hasFlushableSinks } = require('../logs/logger-runtime');
4
+ const {
5
+ deadlineFromContext,
6
+ remainingTimeMs,
7
+ runWithInvocationDeadline,
8
+ } = require('./invocation-deadline');
4
9
 
5
10
  // Bounds the tail latency telemetry adds to every warm invocation. Kept low so
6
11
  // an unreachable OTLP endpoint (e.g. a VPC Lambda with no NAT/egress) costs at
@@ -111,15 +116,6 @@ function withDeadline(ms, fn) {
111
116
  });
112
117
  }
113
118
 
114
- function remainingTimeMs(context) {
115
- try {
116
- const remaining = context?.getRemainingTimeInMillis?.();
117
- return typeof remaining === 'number' ? remaining : Infinity;
118
- } catch (_) {
119
- return Infinity;
120
- }
121
- }
122
-
123
119
  async function flushInvocation({
124
120
  telemetry,
125
121
  usageRollup,
@@ -167,22 +163,32 @@ async function runInvocationScope(fields, fn, opts = {}) {
167
163
  shouldUseDatabase = true,
168
164
  flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
169
165
  context,
166
+ maxInProcessWaitMs,
170
167
  } = opts;
171
- return runInContext({ [LOGGER_SCOPE_KEY]: { ...(fields || {}) } }, async () => {
172
- try {
173
- return await fn();
174
- } finally {
175
- // Every step is guarded, so a flush never changes the result.
176
- await flushInvocation({
177
- telemetry,
178
- usageRollup,
179
- eventSummary,
180
- shouldUseDatabase,
181
- flushTimeoutMs,
182
- context,
183
- });
184
- }
185
- });
168
+ const deadline = {
169
+ deadlineAt: deadlineFromContext(context),
170
+ maxInProcessWaitMs,
171
+ };
172
+ return runWithInvocationDeadline(deadline, () =>
173
+ runInContext(
174
+ { [LOGGER_SCOPE_KEY]: { ...(fields || {}) } },
175
+ async () => {
176
+ try {
177
+ return await fn();
178
+ } finally {
179
+ // Every step is guarded, so a flush never changes the result.
180
+ await flushInvocation({
181
+ telemetry,
182
+ usageRollup,
183
+ eventSummary,
184
+ shouldUseDatabase,
185
+ flushTimeoutMs,
186
+ context,
187
+ });
188
+ }
189
+ }
190
+ )
191
+ );
186
192
  }
187
193
 
188
194
  function toCount(value) {
@@ -1,5 +1,4 @@
1
1
  const { Cryptor } = require('../encrypt/Cryptor');
2
- const { isEncryptedEnvelope } = require('./encryption/ciphertext-format');
3
2
  const {
4
3
  getEncryptedFields,
5
4
  getFieldsToEncryptOnWrite,
@@ -296,7 +295,39 @@ class DocumentDBEncryptionService {
296
295
  * _isEncryptedValue({}) // false
297
296
  */
298
297
  _isEncryptedValue(value) {
299
- return isEncryptedEnvelope(value);
298
+ // Must be string
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;
300
331
  }
301
332
  }
302
333
 
@@ -58,10 +58,7 @@ async function insertOne(client, collection, document) {
58
58
 
59
59
  // Provide helpful context for common errors
60
60
  if (error.code === 11000) {
61
- throw Object.assign(
62
- new Error(`${errorMsg} - Duplicate key violation`),
63
- { code: 11000 }
64
- );
61
+ throw new Error(`${errorMsg} - Duplicate key violation`);
65
62
  }
66
63
  throw new Error(errorMsg);
67
64
  }
@@ -508,9 +508,9 @@ return entities.map((e) => ({
508
508
 
509
509
  **Verified:**
510
510
 
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
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
514
514
 
515
515
  **Implementation Examples:**
516
516