@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.
Files changed (102) hide show
  1. package/CLAUDE.md +42 -58
  2. package/application/commands/README.md +17 -11
  3. package/application/commands/entity-commands.js +18 -60
  4. package/application/commands/integration-commands.js +63 -0
  5. package/core/CLAUDE.md +1 -3
  6. package/core/Worker.js +2 -1
  7. package/core/create-handler.js +0 -3
  8. package/core/index.js +0 -6
  9. package/core/invocation-scope.js +24 -30
  10. package/database/documentdb-encryption-service.js +2 -33
  11. package/database/documentdb-utils.js +4 -1
  12. package/database/encryption/README.md +3 -3
  13. package/database/encryption/ciphertext-format.js +24 -0
  14. package/database/encryption/encryption-schema-registry.js +109 -29
  15. package/database/encryption/field-encryption-service.js +55 -16
  16. package/database/encryption/prisma-encryption-extension.js +6 -9
  17. package/database/prisma.js +10 -1
  18. package/encrypt/Cryptor.js +90 -38
  19. package/errors/fetch-error.js +18 -11
  20. package/errors/index.js +4 -2
  21. package/errors/mapping-already-exists-error.js +14 -0
  22. package/generated/prisma-mongodb/edge.js +6 -2
  23. package/generated/prisma-mongodb/index.js +10 -2
  24. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  25. package/generated/prisma-mongodb/package.json +1 -1
  26. package/generated/prisma-mongodb/schema.prisma +1 -1
  27. package/generated/prisma-mongodb/wasm.js +6 -2
  28. package/generated/prisma-postgresql/edge.js +6 -2
  29. package/generated/prisma-postgresql/index.js +10 -2
  30. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  31. package/generated/prisma-postgresql/package.json +1 -1
  32. package/generated/prisma-postgresql/schema.prisma +1 -1
  33. package/generated/prisma-postgresql/wasm.js +6 -2
  34. package/handlers/WEBHOOKS.md +29 -0
  35. package/handlers/app-definition-loader.js +9 -2
  36. package/handlers/app-handler-helpers.js +12 -1
  37. package/handlers/workers/integration-defined-workers.js +0 -2
  38. package/index.js +2 -18
  39. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -13
  40. package/integrations/integration-base.js +52 -25
  41. package/integrations/integration-router.js +30 -22
  42. package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
  43. package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
  44. package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
  45. package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
  46. package/integrations/repositories/integration-mapping-repository.js +29 -0
  47. package/integrations/repositories/integration-repository-documentdb.js +42 -23
  48. package/integrations/repositories/integration-repository-interface.js +37 -21
  49. package/integrations/repositories/integration-repository-mongo.js +69 -30
  50. package/integrations/repositories/integration-repository-postgres.js +74 -30
  51. package/integrations/repositories/process-repository-mongo.js +1 -1
  52. package/integrations/tests/doubles/test-integration-repository.js +2 -15
  53. package/integrations/use-cases/add-entities-to-integration.js +92 -0
  54. package/integrations/use-cases/create-integration.js +57 -19
  55. package/integrations/use-cases/delete-integration-for-user.js +8 -11
  56. package/integrations/use-cases/get-integration-instance.js +12 -12
  57. package/integrations/use-cases/remove-entities-from-integration.js +70 -0
  58. package/integrations/use-cases/update-integration-messages.js +9 -28
  59. package/integrations/use-cases/update-integration.js +12 -12
  60. package/integrations/utils/assert-entity-ids-input.js +42 -0
  61. package/jest-setup.js +13 -2
  62. package/jest-teardown.js +5 -2
  63. package/jest.config.js +4 -0
  64. package/jest.db.config.js +23 -0
  65. package/logs/serialize.js +0 -15
  66. package/modules/module.js +0 -27
  67. package/modules/requester/requester.js +9 -211
  68. package/modules/use-cases/create-entity-from-credential.js +105 -0
  69. package/modules/use-cases/get-entity-options-by-id.js +7 -5
  70. package/modules/use-cases/get-module.js +29 -8
  71. package/modules/use-cases/process-authorization-callback.js +78 -27
  72. package/modules/use-cases/refresh-entity-options.js +7 -5
  73. package/modules/use-cases/test-module-auth.js +7 -5
  74. package/modules/utils/find-module-definition.js +23 -0
  75. package/modules/utils/map-module-dto.js +5 -3
  76. package/modules/utils/to-credential-id.js +14 -0
  77. package/package.json +10 -7
  78. package/prisma-mongodb/schema.prisma +1 -1
  79. package/prisma-postgresql/schema.prisma +1 -1
  80. package/queues/queuer-util.js +9 -7
  81. package/queues/sqs-message-body.js +17 -0
  82. package/telemetry/otel-telemetry.js +76 -3
  83. package/telemetry/telemetry-config.js +16 -5
  84. package/telemetry/telemetry-runtime.js +14 -1
  85. package/token/repositories/token-repository-documentdb.js +13 -1
  86. package/token/repositories/token-repository-mongo.js +13 -1
  87. package/token/repositories/token-repository-postgres.js +13 -1
  88. package/types/core/index.d.ts +0 -33
  89. package/types/errors/index.d.ts +0 -47
  90. package/types/integrations/index.d.ts +4 -20
  91. package/types/module-plugin/index.d.ts +0 -47
  92. package/user/tests/doubles/test-user-repository.js +1 -1
  93. package/user/use-cases/authenticate-user.js +23 -7
  94. package/user/use-cases/get-user-from-bearer-token.js +7 -2
  95. package/core/invocation-deadline.js +0 -91
  96. package/errors/rate-limit-error.js +0 -46
  97. package/integrations/repositories/message-item-shared.js +0 -4
  98. package/integrations/tests/doubles/prisma-message-row.js +0 -24
  99. package/integrations/use-cases/record-rate-limit-message.js +0 -110
  100. package/modules/requester/rate-limit/index.js +0 -4
  101. package/modules/requester/rate-limit/parsers.js +0 -245
  102. package/modules/requester/rate-limit/policy.js +0 -304
package/CLAUDE.md CHANGED
@@ -206,11 +206,51 @@ 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
209
210
 
210
211
  **Repositories**:
211
212
  - `integration-repository-factory.js` - Creates database-specific repositories
212
213
  - `integration-repository-mongo.js` - MongoDB implementation
213
214
  - `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.
214
254
  - `integration-mapping-repository-*.js` - Mapping data persistence.
215
255
  `queryMappings(integrationId, { where, orderBy, skip, take, omit })`
216
256
  returns `{ mappings, total }`: one filtered, ordered page of an
@@ -226,7 +266,7 @@ packages/core/
226
266
  mapping keys to leave out of the rows; never write such rows back. Path
227
267
  segments must match `^[A-Za-z_][A-Za-z0-9_]*$`. The PostgreSQL, MongoDB and
228
268
  DocumentDB adapters give the same pages and totals;
229
- `integration-mapping-repository-query-parity.test.js` checks that against
269
+ `integration-mapping-repository-query-parity.db.test.js` checks that against
230
270
  real databases when `QUERY_MAPPINGS_PARITY_MONGO_URL` /
231
271
  `QUERY_MAPPINGS_PARITY_POSTGRES_URL` are set. Two orderings still differ:
232
272
  strings compare by the database collation on PostgreSQL and by code point
@@ -369,16 +409,6 @@ class MyIntegration extends IntegrationBase {
369
409
  - `ApiKeyRequester` - API key authentication
370
410
  - `BasicAuthRequester` - Basic authentication
371
411
 
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
-
382
412
  **Module Factory**:
383
413
  - `ModuleFactory` - Creates and configures API module instances
384
414
  - Handles credential injection
@@ -487,7 +517,7 @@ handlers (`{ req, res, next }`) and `this.on` events do not.
487
517
  `isLastAttempt` is `false` when either count is unknown: a local or non-SQS
488
518
  invocation, or a queue whose redrive policy the stack does not own
489
519
  (`ownership.queue: 'external'`). The value is information only: core still
490
- rethrows retryable errors and discards halt errors (4xx except 408 and 429).
520
+ rethrows retryable errors and discards halt errors (4xx except 408/429).
491
521
 
492
522
  Use it to end a run or count lost work on the final try: when a retryable
493
523
  error (429, 5xx, network) is about to be rethrown and `isLastAttempt` is
@@ -517,7 +547,6 @@ it as `FRIGG_QUEUE_MAX_RECEIVE_COUNT` on the queue worker function.
517
547
  **Error Types**:
518
548
  - `BaseError` - Base error class
519
549
  - `FetchError` - HTTP request failures
520
- - `RateLimitError` - A `FetchError` for a limit the provider or the module's policy says when to retry (`retryAt`)
521
550
  - `HaltError` - Stop processing without retry
522
551
  - `RequiredPropertyError` - Missing required parameters
523
552
  - `ParameterTypeError` - Invalid parameter type
@@ -532,51 +561,6 @@ if (!userId) {
532
561
  }
533
562
  ```
534
563
 
535
- **Rate-limit message** (ADR-049): when a wait is longer than the in-process cap
536
- of the caller (`maxInProcessWaitMs`: 10 s HTTP, 60 s queue worker, 5 min outside
537
- an invocation), the Requester tells its delegate
538
- (`RATE_LIMITED`, with the `RateLimitError`) and then throws. A shorter wait
539
- that throws sends no notification. The notification takes the path of
540
- `CREDENTIAL_INVALIDATED`: Requester, `Module`, `IntegrationBase`.
541
-
542
- - The `Module` sends `{ moduleName, reason, retryAt, policy, statusCode, links }`.
543
- `links` is `static rateLimit.userHints[reason].links`, or `[]`. The message,
544
- url, body and headers of the error are never sent: the message reaches end
545
- users.
546
- - `IntegrationBase` writes one `WARN` (`integration.<name>.rate_limited`), and
547
- `RecordRateLimitMessage` appends one item to the stored `warnings`. It
548
- changes no status. A rate limit is not an `ERROR`, and an `ERROR` status
549
- makes the queue worker drop every webhook.
550
- - A report for the same module whose reset time is within 60 s of a stored one
551
- is skipped. The check reads the stored `warnings` with
552
- `findIntegrationMessages`, not `this.messages`, which is per instance and
553
- empty on Postgres. It is a read then a write, so workers that report at the
554
- same instant can still store a few copies.
555
- - Every hop is best effort. A failure is logged, and the caller still gets the
556
- `RateLimitError`.
557
-
558
- ```javascript
559
- {
560
- title: 'Rate limit reached',
561
- message: 'The hubspot API rate limit was reached and resets at 2026-09-28 14:31 UTC.',
562
- timestamp: 1790000000000,
563
- code: 'RATE_LIMITED',
564
- module: 'hubspot',
565
- reason: 'daily',
566
- retryAt: '2026-09-28T14:30:15.000Z',
567
- actions: [
568
- { type: 'RETRY_WHEN_READY' },
569
- { type: 'LINK', label: 'API usage limits', url: 'https://example.com/limits' },
570
- ],
571
- }
572
- ```
573
-
574
- The text is fixed. It holds the module name and the reset time in UTC, rounded
575
- up to the minute, and nothing from the request.
576
-
577
- Integration messages (the item form, `findIntegrationMessages`, the newest 50
578
- per type): see "Integration Messages" in `docs/guides/INTEGRATION-PATTERNS.md`.
579
-
580
564
  ### 9. Logging System (`/logs`)
581
565
 
582
566
  **Purpose**: One redacted JSON record per line to stdout (ADR-048). See `docs/guides/LOGGING.md`.
@@ -67,9 +67,10 @@ 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
- externalUserId
72
- );
70
+ await this.commands.findIntegrationContextByExternalEntityId({
71
+ externalId: externalUserId,
72
+ type: 'my-integration', // integration config.type to match
73
+ });
73
74
 
74
75
  if (result.error) {
75
76
  return { error: result.error };
@@ -231,9 +232,10 @@ Manage integration records and load full integration contexts.
231
232
  ```javascript
232
233
  // Find integration context by external entity ID
233
234
  // Returns { context, error } where context includes record + hydrated modules
234
- const result = await commands.findIntegrationContextByExternalEntityId(
235
- 'external-user-or-workspace-id'
236
- );
235
+ const result = await commands.findIntegrationContextByExternalEntityId({
236
+ externalId: 'external-user-or-workspace-id',
237
+ type: 'my-integration', // integration config.type to match
238
+ });
237
239
 
238
240
  if (!result.error) {
239
241
  integration.setIntegrationRecord(result.context);
@@ -299,7 +301,10 @@ try {
299
301
  For integration context operations, errors are returned in the result:
300
302
 
301
303
  ```javascript
302
- const result = await commands.findIntegrationContextByExternalEntityId(userId);
304
+ const result = await commands.findIntegrationContextByExternalEntityId({
305
+ externalId: userId,
306
+ type: 'my-integration',
307
+ });
303
308
 
304
309
  if (result.error) {
305
310
  return { error: result.error };
@@ -349,9 +354,10 @@ const result =
349
354
  const { createFriggCommands } = require('@friggframework/core');
350
355
 
351
356
  this.commands = createFriggCommands({ integrationClass: MyIntegration });
352
- const result = await this.commands.findIntegrationContextByExternalEntityId(
353
- userId
354
- );
357
+ const result = await this.commands.findIntegrationContextByExternalEntityId({
358
+ externalId: userId,
359
+ type: 'my-integration',
360
+ });
355
361
  ```
356
362
 
357
363
  ## Best Practices
@@ -433,7 +439,7 @@ if (!user) {
433
439
  | | `findEntitiesByIds(ids)` | Find multiple by IDs |
434
440
  | | `updateEntity(id, updates)` | Update entity properties |
435
441
  | | `deleteEntity(id)` | Delete entity |
436
- | **Integration** | `findIntegrationContextByExternalEntityId(externalId)` | Load integration + modules by external ID |
442
+ | **Integration** | `findIntegrationContextByExternalEntityId({ externalId, type })` | Load integration + modules by external ID |
437
443
  | | `loadIntegrationContextById(integrationId)` | Load integration + modules by ID |
438
444
 
439
445
  ## Support
@@ -1,12 +1,24 @@
1
1
  const {
2
2
  createModuleRepository,
3
3
  } = require('../../modules/repositories/module-repository-factory');
4
+ const { toCredentialId } = require('../../modules/utils/to-credential-id');
4
5
 
5
6
  const ERROR_CODE_MAP = {
6
7
  ENTITY_NOT_FOUND: 404,
7
8
  INVALID_ENTITY_DATA: 400,
8
9
  };
9
10
 
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
+
10
22
  function mapErrorToResponse(error) {
11
23
  const status = ERROR_CODE_MAP[error?.code] || 500;
12
24
  return {
@@ -66,16 +78,7 @@ function createEntityCommands() {
66
78
 
67
79
  const entity = await moduleRepo.createEntity(entityData);
68
80
 
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
- };
81
+ return toEntityDto(entity);
79
82
  } catch (error) {
80
83
  return mapErrorToResponse(error);
81
84
  }
@@ -109,16 +112,7 @@ function createEntityCommands() {
109
112
  return null;
110
113
  }
111
114
 
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
- };
115
+ return toEntityDto(entity);
122
116
  } catch (error) {
123
117
  return mapErrorToResponse(error);
124
118
  }
@@ -139,16 +133,7 @@ function createEntityCommands() {
139
133
 
140
134
  const entities = await moduleRepo.findEntitiesByUserId(userId);
141
135
 
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
- }));
136
+ return entities.map((entity) => toEntityDto(entity));
152
137
  } catch (error) {
153
138
  if (error.code) {
154
139
  return mapErrorToResponse(error);
@@ -180,16 +165,7 @@ function createEntityCommands() {
180
165
  moduleName
181
166
  );
182
167
 
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
- }));
168
+ return entities.map((entity) => toEntityDto(entity));
193
169
  } catch (error) {
194
170
  if (error.code) {
195
171
  return mapErrorToResponse(error);
@@ -213,16 +189,7 @@ function createEntityCommands() {
213
189
 
214
190
  const entity = await moduleRepo.findEntityById(entityId);
215
191
 
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
- };
192
+ return toEntityDto(entity);
226
193
  } catch (error) {
227
194
  return mapErrorToResponse(error);
228
195
  }
@@ -250,16 +217,7 @@ function createEntityCommands() {
250
217
  throw error;
251
218
  }
252
219
 
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
- };
220
+ return toEntityDto(entity);
263
221
  } catch (error) {
264
222
  return mapErrorToResponse(error);
265
223
  }
@@ -29,6 +29,12 @@ 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');
32
38
  const {
33
39
  getModulesDefinitionFromIntegrationClasses,
34
40
  } = require('../../integrations/utils/map-integration-dto');
@@ -40,6 +46,11 @@ const ERROR_CODE_MAP = {
40
46
  EXTERNAL_ID_REQUIRED: 400,
41
47
  TYPE_REQUIRED: 400,
42
48
  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,
43
54
  };
44
55
 
45
56
  function mapErrorToResponse(error) {
@@ -163,6 +174,17 @@ function createIntegrationCommands({ integrationClass } = {}) {
163
174
  integrationRepository,
164
175
  });
165
176
 
177
+ const addEntitiesToIntegrationUseCase = new AddEntitiesToIntegration({
178
+ integrationRepository,
179
+ moduleRepository,
180
+ });
181
+
182
+ const removeEntitiesFromIntegrationUseCase =
183
+ new RemoveEntitiesFromIntegration({
184
+ integrationRepository,
185
+ moduleRepository,
186
+ });
187
+
166
188
  return {
167
189
  findIntegrationById,
168
190
  listIntegrations,
@@ -307,6 +329,47 @@ function createIntegrationCommands({ integrationClass } = {}) {
307
329
  }
308
330
  },
309
331
 
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
+
310
373
  /**
311
374
  * Delete an integration by ID
312
375
  * @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 + invocation deadline (remainingInvocationMs()) + in-process wait budget (createHandler `maxInProcessWaitMs`: 10 s HTTP, 60 s queue worker)
133
+ runInvocationScope({ requestId, handlerName, method, route, invocation }, …); // Logger scope for the invocation
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,8 +226,6 @@ 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)
231
229
 
232
230
  ### Logging Strategy
233
231
  ```javascript
package/core/Worker.js CHANGED
@@ -3,6 +3,7 @@ const _ = require('lodash');
3
3
  const { RequiredPropertyError } = require('../errors');
4
4
  const { get } = require('../assertions');
5
5
  const { readQueueDelivery } = require('../queues/queue-delivery');
6
+ const { toSqsMessageBody } = require('../queues/sqs-message-body');
6
7
  const { runMessageScope } = require('./invocation-scope');
7
8
  const { getLogger } = require('../logs');
8
9
 
@@ -84,7 +85,7 @@ class Worker {
84
85
  const messageParams = _.omit(params, 'QueueUrl');
85
86
  const args = {
86
87
  DelaySeconds: delay,
87
- MessageBody: JSON.stringify(messageParams),
88
+ MessageBody: toSqsMessageBody(messageParams),
88
89
  QueueUrl: queueURL,
89
90
  };
90
91
  return this.sendAsyncSQSMessage(args);
@@ -12,7 +12,6 @@ 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');
16
15
  const { secretsToEnv } = require('./secrets-to-env');
17
16
  const { parametersToEnv } = require('./parameters-to-env');
18
17
  const {
@@ -32,7 +31,6 @@ const createHandler = (optionByName = {}) => {
32
31
  telemetry,
33
32
  flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
34
33
  usageRollup,
35
- maxInProcessWaitMs = MAX_IN_PROCESS_WAIT_MS.http,
36
34
  } = optionByName;
37
35
 
38
36
  if (!method) {
@@ -146,7 +144,6 @@ const createHandler = (optionByName = {}) => {
146
144
  shouldUseDatabase,
147
145
  flushTimeoutMs,
148
146
  context,
149
- maxInProcessWaitMs,
150
147
  }
151
148
  );
152
149
  };
package/core/index.js CHANGED
@@ -3,10 +3,6 @@ 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');
10
6
 
11
7
  module.exports = {
12
8
  Delegate,
@@ -14,6 +10,4 @@ module.exports = {
14
10
  loadInstalledModules,
15
11
  createHandler,
16
12
  runInvocationScope,
17
- runWithInvocationDeadline,
18
- remainingInvocationMs,
19
13
  };
@@ -1,11 +1,6 @@
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');
9
4
 
10
5
  // Bounds the tail latency telemetry adds to every warm invocation. Kept low so
11
6
  // an unreachable OTLP endpoint (e.g. a VPC Lambda with no NAT/egress) costs at
@@ -116,6 +111,15 @@ function withDeadline(ms, fn) {
116
111
  });
117
112
  }
118
113
 
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
+
119
123
  async function flushInvocation({
120
124
  telemetry,
121
125
  usageRollup,
@@ -163,32 +167,22 @@ async function runInvocationScope(fields, fn, opts = {}) {
163
167
  shouldUseDatabase = true,
164
168
  flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
165
169
  context,
166
- maxInProcessWaitMs,
167
170
  } = opts;
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
- );
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
+ });
192
186
  }
193
187
 
194
188
  function toCount(value) {
@@ -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
- // 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;
299
+ return isEncryptedEnvelope(value);
331
300
  }
332
301
  }
333
302
 
@@ -58,7 +58,10 @@ async function insertOne(client, collection, document) {
58
58
 
59
59
  // Provide helpful context for common errors
60
60
  if (error.code === 11000) {
61
- throw new Error(`${errorMsg} - Duplicate key violation`);
61
+ throw Object.assign(
62
+ new Error(`${errorMsg} - Duplicate key violation`),
63
+ { code: 11000 }
64
+ );
62
65
  }
63
66
  throw new Error(errorMsg);
64
67
  }
@@ -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