@friggframework/core 2.0.0--canary.703.6a9383b.0 → 2.0.0--canary.680.daae24e.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 (214) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/application/commands/integration-commands.js +18 -8
  3. package/application/index.js +6 -2
  4. package/credential/repositories/credential-repository-documentdb.js +34 -0
  5. package/credential/repositories/credential-repository-interface.js +15 -0
  6. package/credential/repositories/credential-repository-mongo.js +23 -0
  7. package/credential/repositories/credential-repository-postgres.js +28 -0
  8. package/credential/use-cases/credential-operations-for-user.js +117 -0
  9. package/credential/use-cases/reauthorize-credential-for-user.js +66 -0
  10. package/database/documentdb-encryption-service.js +9 -22
  11. package/database/documentdb-utils.js +1 -6
  12. package/database/encryption/README.md +78 -14
  13. package/database/encryption/documentdb-encryption-service.md +78 -1
  14. package/database/encryption/encryption-config.js +240 -0
  15. package/database/encryption/encryption-schema-registry.js +41 -12
  16. package/database/encryption/field-encryption-service.js +69 -5
  17. package/database/encryption/integration-mapping-encryption.js +1 -1
  18. package/database/encryption/test-support/fake-ciphertext.js +15 -0
  19. package/database/prisma.js +11 -36
  20. package/database/use-cases/check-encryption-health-use-case.js +43 -52
  21. package/errors/index.js +0 -4
  22. package/generated/prisma-mongodb/edge.js +14 -46
  23. package/generated/prisma-mongodb/index-browser.js +11 -43
  24. package/generated/prisma-mongodb/index.d.ts +748 -2746
  25. package/generated/prisma-mongodb/index.js +14 -46
  26. package/generated/prisma-mongodb/package.json +1 -1
  27. package/generated/prisma-mongodb/schema.prisma +23 -61
  28. package/generated/prisma-mongodb/wasm.js +14 -46
  29. package/generated/prisma-postgresql/edge.js +14 -46
  30. package/generated/prisma-postgresql/index-browser.js +11 -43
  31. package/generated/prisma-postgresql/index.d.ts +736 -2985
  32. package/generated/prisma-postgresql/index.js +14 -46
  33. package/generated/prisma-postgresql/package.json +1 -1
  34. package/generated/prisma-postgresql/schema.prisma +22 -59
  35. package/generated/prisma-postgresql/wasm.js +14 -46
  36. package/handlers/WEBHOOKS.md +0 -29
  37. package/handlers/app-definition-loader.js +19 -8
  38. package/handlers/app-handler-helpers.js +27 -8
  39. package/handlers/backend-utils.js +31 -25
  40. package/handlers/integration-event-dispatcher.js +3 -7
  41. package/handlers/middleware/admin-auth.js +14 -1
  42. package/handlers/routers/auth.js +11 -3
  43. package/handlers/routers/health.js +11 -4
  44. package/handlers/routers/integration-webhook-routers.js +38 -26
  45. package/handlers/workers/integration-defined-workers.js +5 -2
  46. package/index.js +4 -15
  47. package/integrations/index.js +0 -16
  48. package/integrations/integration-base.js +2 -163
  49. package/integrations/integration-router.js +17 -29
  50. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  51. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  52. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  53. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  54. package/integrations/repositories/integration-mapping-repository.js +0 -29
  55. package/integrations/repositories/integration-repository-documentdb.js +2 -6
  56. package/integrations/repositories/integration-repository-interface.js +0 -3
  57. package/integrations/repositories/integration-repository-mongo.js +5 -20
  58. package/integrations/repositories/integration-repository-postgres.js +1 -5
  59. package/integrations/repositories/process-repository-mongo.js +1 -1
  60. package/integrations/use-cases/create-integration.js +4 -14
  61. package/integrations/use-cases/delete-integration-for-user.js +4 -4
  62. package/integrations/use-cases/get-integration-for-user.js +2 -4
  63. package/integrations/use-cases/get-integration-instance.js +4 -4
  64. package/integrations/use-cases/get-integrations-for-user.js +4 -4
  65. package/integrations/use-cases/get-possible-integrations.js +2 -7
  66. package/integrations/use-cases/integration-operations-for-user.js +225 -0
  67. package/integrations/use-cases/update-integration.js +4 -4
  68. package/integrations/utils/map-integration-dto.js +1 -15
  69. package/management-api/create-management-api-router.js +49 -0
  70. package/management-api/error-response.js +116 -0
  71. package/management-api/management-api-config.js +82 -0
  72. package/management-api/meta-router.js +57 -0
  73. package/management-api/openapi/build-openapi.js +144 -0
  74. package/management-api/openapi/components.js +368 -0
  75. package/management-api/openapi/v1-operations.js +83 -0
  76. package/management-api/openapi/v2-operations.js +252 -0
  77. package/management-api/route-registry.js +294 -0
  78. package/management-api/test-support/http-client.js +39 -0
  79. package/management-api/use-cases/get-management-api-meta.js +57 -0
  80. package/management-api/v1-deprecation.js +120 -0
  81. package/management-api/v2/create-v2-router.js +85 -0
  82. package/management-api/v2/dependencies.js +256 -0
  83. package/management-api/v2/dto.js +123 -0
  84. package/management-api/v2/handlers/authorization.js +93 -0
  85. package/management-api/v2/handlers/credentials.js +29 -0
  86. package/management-api/v2/handlers/entities.js +74 -0
  87. package/management-api/v2/handlers/integrations.js +125 -0
  88. package/management-api/v2/handlers/proxy.js +34 -0
  89. package/management-api/v2/request.js +54 -0
  90. package/management-api/v2/test-support/fake-dependencies.js +103 -0
  91. package/modules/domain/authorization-session.js +144 -0
  92. package/modules/entity-type-registry.js +311 -0
  93. package/modules/index.js +6 -0
  94. package/modules/proxy/proxy-errors.js +20 -0
  95. package/modules/proxy/proxy-path.js +179 -0
  96. package/modules/proxy/proxy-policy.js +248 -0
  97. package/modules/repositories/authorization-session-repository-documentdb.js +112 -0
  98. package/modules/repositories/authorization-session-repository-factory.js +31 -0
  99. package/modules/repositories/authorization-session-repository-interface.js +47 -0
  100. package/modules/repositories/authorization-session-repository-prisma.js +87 -0
  101. package/modules/requester/proxy-request.js +244 -0
  102. package/modules/requester/requester.js +27 -2
  103. package/modules/tests/doubles/in-memory-authorization-session-repository.js +45 -0
  104. package/modules/use-cases/entity-operations-for-user.js +125 -0
  105. package/modules/use-cases/entity-types.js +115 -0
  106. package/modules/use-cases/execute-entity-proxy-request.js +239 -0
  107. package/modules/use-cases/get-authorization-requirements.js +100 -0
  108. package/modules/use-cases/get-entity-module-for-user.js +86 -0
  109. package/modules/use-cases/multi-step-authorization.js +302 -0
  110. package/package.json +5 -7
  111. package/prisma-mongodb/schema.prisma +23 -61
  112. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +28 -0
  113. package/prisma-postgresql/schema.prisma +22 -59
  114. package/queues/queuer-util.js +2 -9
  115. package/types/index.d.ts +1 -0
  116. package/types/modules/index.d.ts +58 -0
  117. package/errors/mapping-already-exists-error.js +0 -14
  118. package/handlers/workers/integration-triggers.js +0 -25
  119. package/infrastructure/scheduler/recurrence.js +0 -204
  120. package/integrations/define/DESIGN.md +0 -108
  121. package/integrations/define/config.js +0 -98
  122. package/integrations/define/define-app.js +0 -52
  123. package/integrations/define/define-extension.js +0 -154
  124. package/integrations/define/define-integration.js +0 -292
  125. package/integrations/define/examples/deal-alerts.js +0 -138
  126. package/integrations/define/extension-binding.js +0 -174
  127. package/integrations/define/index.js +0 -11
  128. package/integrations/define/json-schema-lite.js +0 -68
  129. package/integrations/define/subscriptions.js +0 -93
  130. package/integrations/define/tests/fixtures/hubspot.js +0 -109
  131. package/integrations/define/tests/fixtures/slack.js +0 -26
  132. package/integrations/define/use.js +0 -39
  133. package/integrations/definitions/README.md +0 -278
  134. package/integrations/definitions/canonical.js +0 -11
  135. package/integrations/definitions/capabilities/AUDIT.md +0 -480
  136. package/integrations/definitions/capabilities/acmeerp.capabilities.json +0 -633
  137. package/integrations/definitions/capabilities/asana.capabilities.json +0 -279
  138. package/integrations/definitions/capabilities/calendly.capabilities.json +0 -385
  139. package/integrations/definitions/capabilities/docusign.capabilities.json +0 -314
  140. package/integrations/definitions/capabilities/fathom.capabilities.json +0 -238
  141. package/integrations/definitions/capabilities/github.capabilities.json +0 -585
  142. package/integrations/definitions/capabilities/hubspot.capabilities.json +0 -822
  143. package/integrations/definitions/capabilities/jira.capabilities.json +0 -391
  144. package/integrations/definitions/capabilities/klaviyo.capabilities.json +0 -503
  145. package/integrations/definitions/capabilities/linear.capabilities.json +0 -378
  146. package/integrations/definitions/capabilities/netsuite.capabilities.json +0 -535
  147. package/integrations/definitions/capabilities/notion.capabilities.json +0 -208
  148. package/integrations/definitions/capabilities/phone.capabilities.json +0 -511
  149. package/integrations/definitions/capabilities/pipedrive.capabilities.json +0 -430
  150. package/integrations/definitions/capabilities/quickbooks.capabilities.json +0 -635
  151. package/integrations/definitions/capabilities/salesforce.capabilities.json +0 -568
  152. package/integrations/definitions/capabilities/shopify.capabilities.json +0 -1128
  153. package/integrations/definitions/capabilities/slack.capabilities.json +0 -373
  154. package/integrations/definitions/capabilities/stripe.capabilities.json +0 -630
  155. package/integrations/definitions/capabilities/webflow.capabilities.json +0 -196
  156. package/integrations/definitions/capabilities/zendesk.capabilities.json +0 -422
  157. package/integrations/definitions/compile.js +0 -80
  158. package/integrations/definitions/config-form.js +0 -137
  159. package/integrations/definitions/examples/acme-erp-quickbooks.definition.json +0 -467
  160. package/integrations/definitions/examples/asana-slack.definition.json +0 -219
  161. package/integrations/definitions/examples/calendly-salesforce.definition.json +0 -459
  162. package/integrations/definitions/examples/docusign-salesforce.definition.json +0 -305
  163. package/integrations/definitions/examples/fathom-hubspot-notion.definition.json +0 -575
  164. package/integrations/definitions/examples/github-linear.definition.json +0 -322
  165. package/integrations/definitions/examples/hubspot-slack.definition.json +0 -427
  166. package/integrations/definitions/examples/klaviyo-hubspot.definition.json +0 -336
  167. package/integrations/definitions/examples/phone-hubspot.definition.json +0 -633
  168. package/integrations/definitions/examples/pipedrive-hubspot.definition.json +0 -136
  169. package/integrations/definitions/examples/pipedrive-phone.definition.json +0 -340
  170. package/integrations/definitions/examples/records/phone-hubspot.definition-version.json +0 -652
  171. package/integrations/definitions/examples/records/phone-hubspot.integration.json +0 -86
  172. package/integrations/definitions/examples/records/phone-hubspot.mappings.json +0 -39
  173. package/integrations/definitions/examples/records/phone-hubspot.workflow-run.json +0 -62
  174. package/integrations/definitions/examples/shopify-klaviyo.definition.json +0 -488
  175. package/integrations/definitions/examples/shopify-netsuite.definition.json +0 -622
  176. package/integrations/definitions/examples/stripe-quickbooks.definition.json +0 -476
  177. package/integrations/definitions/examples/webflow-hubspot-slack.definition.json +0 -262
  178. package/integrations/definitions/examples/zendesk-jira.definition.json +0 -604
  179. package/integrations/definitions/expressions.js +0 -229
  180. package/integrations/definitions/index.js +0 -48
  181. package/integrations/definitions/integration-runtime.js +0 -779
  182. package/integrations/definitions/interpreter.js +0 -104
  183. package/integrations/definitions/manifests.js +0 -177
  184. package/integrations/definitions/renderers/common.js +0 -67
  185. package/integrations/definitions/renderers/html.js +0 -129
  186. package/integrations/definitions/renderers/hubspot.js +0 -59
  187. package/integrations/definitions/renderers/preview.js +0 -154
  188. package/integrations/definitions/renderers/slack.js +0 -146
  189. package/integrations/definitions/repositories/definition-version-repository.js +0 -67
  190. package/integrations/definitions/repositories/workflow-run-repository.js +0 -80
  191. package/integrations/definitions/router.js +0 -170
  192. package/integrations/definitions/runtime.js +0 -268
  193. package/integrations/definitions/schema/capability-manifest.v0.1.schema.json +0 -549
  194. package/integrations/definitions/schema/installation.v0.1.schema.json +0 -130
  195. package/integrations/definitions/schema/integration-definition.v0.1.schema.json +0 -909
  196. package/integrations/definitions/schema/records.md +0 -105
  197. package/integrations/definitions/schema-check.js +0 -58
  198. package/integrations/definitions/scripts/check-manifests.js +0 -220
  199. package/integrations/definitions/scripts/validate.js +0 -66
  200. package/integrations/definitions/steps.js +0 -123
  201. package/integrations/definitions/sync-engine.js +0 -297
  202. package/integrations/definitions/tests/helpers-fake-crm.js +0 -49
  203. package/integrations/definitions/transforms.js +0 -91
  204. package/integrations/definitions/use-cases/definition-use-cases.js +0 -245
  205. package/integrations/definitions/validate.js +0 -436
  206. package/integrations/definitions/versioning.js +0 -176
  207. package/integrations/definitions/webhooks.js +0 -119
  208. package/integrations/integration-types.js +0 -73
  209. package/integrations/triggers.js +0 -244
  210. package/integrations/use-cases/run-trigger-tick.js +0 -155
  211. package/integrations/use-cases/run-trigger.js +0 -77
  212. package/prisma-postgresql/migrations/20261018000000_add_data_defined_integrations/migration.sql +0 -66
  213. package/prisma-postgresql/migrations/20261019000000_workflow_run_waits/migration.sql +0 -7
  214. package/prisma-postgresql/migrations/20261019120000_definition_workspace/migration.sql +0 -5
package/CHANGELOG.md CHANGED
@@ -1,3 +1,14 @@
1
+ # Unreleased
2
+
3
+ #### Behaviour change: module credential fields are now encrypted
4
+
5
+ - `credentialFields` declared in an API module's `encryption` config (for example `Definition.encryption.credentialFields`) were never registered for encryption: `loadModuleEncryptionSchemas` required a path that does not exist and the error was swallowed. They are now registered, for modules bound by integrations and for modules registered in `appDefinition.entities` (ADR-059).
6
+ - Existing rows are not rewritten. A credential saved before this release stays plaintext until it is next written, and is read as stored.
7
+ - Reads now tolerate plaintext: a value is only treated as ciphertext when it has the exact `keyId:iv:ciphertext:encryptedKey` shape (previously any string with three or more colons, such as `https://user:pw@host:443`), and a value with that shape that fails to decrypt throws `FieldDecryptionError` in a deployed runtime (any stage, AWS Lambda or Netlify) and is returned as stored with a warning on a local run.
8
+ - An app's own `encryption.schema` is no longer replaced when module fields are added to it.
9
+
10
+ ---
11
+
1
12
  # v1.2.2 (Fri Aug 09 2024)
2
13
 
3
14
  #### 🐛 Bug Fix
@@ -30,8 +30,9 @@ const {
30
30
  PatchIntegrationConfig,
31
31
  } = require('../../integrations/use-cases/patch-integration-config');
32
32
  const {
33
- getModulesDefinitionFromIntegrationClasses,
34
- } = require('../../integrations/utils/map-integration-dto');
33
+ getEntityTypeRegistry,
34
+ getEntityTypeDefinitions,
35
+ } = require('../../modules/entity-type-registry');
35
36
 
36
37
  const ERROR_CODE_MAP = {
37
38
  ENTITY_NOT_FOUND: 401,
@@ -51,7 +52,16 @@ function mapErrorToResponse(error) {
51
52
  };
52
53
  }
53
54
 
54
- function createIntegrationCommands({ integrationClass } = {}) {
55
+ /**
56
+ * @param {Object} [params]
57
+ * @param {Function} [params.integrationClass]
58
+ * @param {Array<object>} [params.moduleDefinitions] - the app's offered module
59
+ * definitions (`loadAppDefinition().moduleDefinitions`). Integration code
60
+ * calls this from a constructor with no app definition in hand, so when it
61
+ * is omitted the commands hydrate with this integration's own modules only
62
+ * (a registry built from `{ integrations: [integrationClass] }`).
63
+ */
64
+ function createIntegrationCommands({ integrationClass, moduleDefinitions } = {}) {
55
65
  // Always use Frigg's default repositories and use cases
56
66
  const integrationRepository = createIntegrationRepository();
57
67
 
@@ -108,13 +118,13 @@ function createIntegrationCommands({ integrationClass } = {}) {
108
118
 
109
119
  const moduleRepository = createModuleRepository();
110
120
 
111
- const moduleDefinitions = getModulesDefinitionFromIntegrationClasses([
112
- integrationClass,
113
- ]);
114
-
115
121
  const moduleFactory = new ModuleFactory({
116
122
  moduleRepository,
117
- moduleDefinitions,
123
+ moduleDefinitions:
124
+ moduleDefinitions ??
125
+ getEntityTypeDefinitions(
126
+ getEntityTypeRegistry({ integrations: [integrationClass] })
127
+ ),
118
128
  });
119
129
 
120
130
  const loadIntegrationContextUseCase = new LoadIntegrationContextUseCase({
@@ -17,6 +17,7 @@ const { createUsageCommands } = require('./commands/usage-commands');
17
17
  *
18
18
  * @param {Object} params
19
19
  * @param {Object} params.integrationClass - Integration class (required)
20
+ * @param {Array<object>} [params.moduleDefinitions] - the app's offered module definitions; defaults to the integration's own modules
20
21
  * @returns {Object} Unified commands object with all CRUD operations
21
22
  *
22
23
  * @example
@@ -24,9 +25,12 @@ const { createUsageCommands } = require('./commands/usage-commands');
24
25
  * const user = await commands.createUser({ username: 'user@example.com' });
25
26
  * const credential = await commands.createCredential({ userId: user.id, ... });
26
27
  */
27
- function createFriggCommands({ integrationClass }) {
28
+ function createFriggCommands({ integrationClass, moduleDefinitions }) {
28
29
  // All commands use Frigg's default repositories and use cases
29
- const integrationCommands = createIntegrationCommands({ integrationClass });
30
+ const integrationCommands = createIntegrationCommands({
31
+ integrationClass,
32
+ moduleDefinitions,
33
+ });
30
34
 
31
35
  const userCommands = createUserCommands();
32
36
 
@@ -186,6 +186,40 @@ class CredentialRepositoryDocumentDB extends CredentialRepositoryInterface {
186
186
  return this._mapCredential(decryptedCredential);
187
187
  }
188
188
 
189
+ /**
190
+ * All credentials owned by a user, newest first.
191
+ *
192
+ * @param {string} userId - User ID
193
+ * @returns {Promise<Array<Object>>} Credentials with string IDs
194
+ */
195
+ async findCredentialsByUserId(userId) {
196
+ const userObjectId = toObjectId(userId);
197
+ if (!userObjectId) return [];
198
+ const docs = await findManyDrained(
199
+ this.prisma,
200
+ 'Credential',
201
+ { userId: userObjectId },
202
+ { sort: { createdAt: -1 } }
203
+ );
204
+ const credentials = [];
205
+ for (const doc of docs) {
206
+ const decrypted = await this.encryptionService.decryptFields(
207
+ 'Credential',
208
+ doc
209
+ );
210
+ credentials.push({
211
+ ...this._mapCredential(decrypted),
212
+ id: fromObjectId(doc._id),
213
+ userId: fromObjectId(doc.userId) ?? doc.userId,
214
+ externalId: doc.externalId ?? null,
215
+ authIsValid: doc.authIsValid ?? null,
216
+ createdAt: doc.createdAt ?? null,
217
+ updatedAt: doc.updatedAt ?? null,
218
+ });
219
+ }
220
+ return credentials;
221
+ }
222
+
189
223
  async updateCredential(credentialId, updates) {
190
224
  const objectId = toObjectId(credentialId);
191
225
  if (!objectId) return null;
@@ -80,6 +80,21 @@ class CredentialRepositoryInterface {
80
80
  );
81
81
  }
82
82
 
83
+ /**
84
+ * All credentials owned by a user, newest first.
85
+ *
86
+ * @param {string|number} userId - User ID (string from application layer)
87
+ * @returns {Promise<Array<Object>>} Credentials with string IDs, `createdAt`
88
+ * and `updatedAt`, and the (decrypted) data fields spread in, as
89
+ * findCredentialById returns them. Empty when the user has none.
90
+ * @abstract
91
+ */
92
+ async findCredentialsByUserId(userId) {
93
+ throw new Error(
94
+ 'Method findCredentialsByUserId must be implemented by subclass'
95
+ );
96
+ }
97
+
83
98
  /**
84
99
  * Update a credential by ID
85
100
  *
@@ -188,6 +188,29 @@ class CredentialRepositoryMongo extends CredentialRepositoryInterface {
188
188
  };
189
189
  }
190
190
 
191
+ /**
192
+ * All credentials owned by a user, newest first.
193
+ *
194
+ * @param {string} userId - User ID
195
+ * @returns {Promise<Array<Object>>} Credentials with string IDs
196
+ */
197
+ async findCredentialsByUserId(userId) {
198
+ if (!userId) return [];
199
+ const credentials = await this.prisma.credential.findMany({
200
+ where: { userId: String(userId) },
201
+ orderBy: { createdAt: 'desc' },
202
+ });
203
+ return credentials.map((credential) => ({
204
+ ...(credential.data || {}),
205
+ id: credential.id,
206
+ userId: credential.userId,
207
+ externalId: credential.externalId,
208
+ authIsValid: credential.authIsValid,
209
+ createdAt: credential.createdAt,
210
+ updatedAt: credential.updatedAt,
211
+ }));
212
+ }
213
+
191
214
  /**
192
215
  * Update a credential by ID
193
216
  * Replaces: Credential.findByIdAndUpdate(credentialId, { $set: updates })
@@ -205,6 +205,34 @@ class CredentialRepositoryPostgres extends CredentialRepositoryInterface {
205
205
  };
206
206
  }
207
207
 
208
+ /**
209
+ * All credentials owned by a user, newest first.
210
+ *
211
+ * @param {string} userId - User ID (string from application layer)
212
+ * @returns {Promise<Array<Object>>} Credentials with string IDs
213
+ */
214
+ async findCredentialsByUserId(userId) {
215
+ let intUserId;
216
+ try {
217
+ intUserId = this._convertId(userId);
218
+ } catch {
219
+ return [];
220
+ }
221
+ const credentials = await this.prisma.credential.findMany({
222
+ where: { userId: intUserId },
223
+ orderBy: { createdAt: 'desc' },
224
+ });
225
+ return credentials.map((credential) => ({
226
+ ...(credential.data || {}),
227
+ id: credential.id.toString(),
228
+ userId: credential.userId?.toString(),
229
+ externalId: credential.externalId,
230
+ authIsValid: credential.authIsValid,
231
+ createdAt: credential.createdAt,
232
+ updatedAt: credential.updatedAt,
233
+ }));
234
+ }
235
+
208
236
  /**
209
237
  * Update a credential by ID
210
238
  *
@@ -0,0 +1,117 @@
1
+ const Boom = require('@hapi/boom');
2
+ const { userOwns } = require('../../modules/use-cases/get-entity-module-for-user');
3
+
4
+ /**
5
+ * Management API v2 credential operations. A credential has no module name
6
+ * of its own; its `type` and the entities that use it come from the
7
+ * caller's entities. A missing or foreign credential is a 404.
8
+ */
9
+
10
+ const credentialIdOf = (entity) => {
11
+ const ref = entity.credential ?? entity.credentialId;
12
+ if (ref === undefined || ref === null) return null;
13
+ if (typeof ref === 'object') {
14
+ const id = ref.id ?? ref._id;
15
+ return id === undefined || id === null ? null : String(id);
16
+ }
17
+ return String(ref);
18
+ };
19
+
20
+ /** Adds `type` and `entityIds` from the user's entities to each credential. */
21
+ function withEntityUsage(credentials, entities) {
22
+ const usage = new Map();
23
+ for (const entity of entities || []) {
24
+ const credentialId = credentialIdOf(entity);
25
+ if (!credentialId) continue;
26
+ const entry = usage.get(credentialId) || { type: null, entityIds: [] };
27
+ entry.type = entry.type || entity.moduleName || null;
28
+ entry.entityIds.push(String(entity.id));
29
+ usage.set(credentialId, entry);
30
+ }
31
+ return credentials.map((credential) => {
32
+ const entry = usage.get(String(credential.id)) || {
33
+ type: null,
34
+ entityIds: [],
35
+ };
36
+ return { ...credential, type: entry.type, entityIds: entry.entityIds };
37
+ });
38
+ }
39
+
40
+ /** The caller's credentials with their type and entity usage. */
41
+ class ListCredentialsForUser {
42
+ constructor({ credentialRepository, moduleRepository }) {
43
+ this.credentialRepository = credentialRepository;
44
+ this.moduleRepository = moduleRepository;
45
+ }
46
+
47
+ async execute(user) {
48
+ const userId = user.getId();
49
+ const [credentials, entities] = await Promise.all([
50
+ this.credentialRepository.findCredentialsByUserId(userId),
51
+ this.moduleRepository.findEntitiesByUserId(userId),
52
+ ]);
53
+ return withEntityUsage(credentials || [], entities);
54
+ }
55
+ }
56
+
57
+ /** One credential the caller owns, with its type and entity usage. */
58
+ class GetCredentialForUserV2 {
59
+ constructor({ credentialRepository, moduleRepository }) {
60
+ this.credentialRepository = credentialRepository;
61
+ this.moduleRepository = moduleRepository;
62
+ }
63
+
64
+ async execute(credentialId, user) {
65
+ let credential = null;
66
+ try {
67
+ credential = await this.credentialRepository.findCredentialById(
68
+ credentialId
69
+ );
70
+ } catch (error) {
71
+ if (!/Invalid ID|ObjectId|Malformed/i.test(error?.message || '')) {
72
+ throw error;
73
+ }
74
+ }
75
+ if (!credential || !userOwns(user, credential.userId)) {
76
+ throw Boom.notFound(`Credential ${credentialId} not found`, {
77
+ code: 'CREDENTIAL_NOT_FOUND',
78
+ });
79
+ }
80
+ const entities = await this.moduleRepository.findEntitiesByUserId(
81
+ credential.userId
82
+ );
83
+ return withEntityUsage([credential], entities)[0];
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Deletes a credential the caller owns. The entities that used it stay, with
89
+ * their credential unset, so they show as needing re-authorization rather
90
+ * than disappearing from integrations.
91
+ */
92
+ class DeleteCredentialForUser {
93
+ constructor({ credentialRepository, moduleRepository, getCredentialForUser }) {
94
+ this.credentialRepository = credentialRepository;
95
+ this.moduleRepository = moduleRepository;
96
+ this.getCredentialForUser = getCredentialForUser;
97
+ }
98
+
99
+ async execute(credentialId, user) {
100
+ const credential = await this.getCredentialForUser.execute(
101
+ credentialId,
102
+ user
103
+ );
104
+ for (const entityId of credential.entityIds) {
105
+ await this.moduleRepository.unsetCredential(entityId);
106
+ }
107
+ await this.credentialRepository.deleteCredentialById(credential.id);
108
+ return { id: String(credential.id), entityIds: credential.entityIds };
109
+ }
110
+ }
111
+
112
+ module.exports = {
113
+ ListCredentialsForUser,
114
+ GetCredentialForUserV2,
115
+ DeleteCredentialForUser,
116
+ withEntityUsage,
117
+ };
@@ -0,0 +1,66 @@
1
+ const Boom = require('@hapi/boom');
2
+
3
+ /**
4
+ * Re-authorization of a credential the caller owns (Management API v2). It
5
+ * runs the same flow as /api/v2/authorize for the credential's entity type,
6
+ * with the session bound to the credential so it cannot be reused for
7
+ * anything else.
8
+ */
9
+ async function credentialEntityType(getCredentialForUser, credentialId, user) {
10
+ const credential = await getCredentialForUser.execute(credentialId, user);
11
+ if (!credential.type) {
12
+ throw Boom.conflict(
13
+ `Credential ${credentialId} is not used by any entity, so its type is unknown; authorize a new connection instead`,
14
+ { code: 'CREDENTIAL_TYPE_UNKNOWN' }
15
+ );
16
+ }
17
+ return { entityType: credential.type, credentialId: String(credential.id) };
18
+ }
19
+
20
+ /** GET /api/v2/credentials/:credentialId/reauthorize */
21
+ class GetCredentialReauthorization {
22
+ constructor({ getCredentialForUser, getAuthorizationStep }) {
23
+ this.getCredentialForUser = getCredentialForUser;
24
+ this.getAuthorizationStep = getAuthorizationStep;
25
+ }
26
+
27
+ async execute(credentialId, user, { step = 1, sessionId, state } = {}) {
28
+ const binding = await credentialEntityType(
29
+ this.getCredentialForUser,
30
+ credentialId,
31
+ user
32
+ );
33
+ return this.getAuthorizationStep.execute({
34
+ user,
35
+ ...binding,
36
+ step,
37
+ sessionId,
38
+ state,
39
+ });
40
+ }
41
+ }
42
+
43
+ /** POST /api/v2/credentials/:credentialId/reauthorize */
44
+ class ReauthorizeCredentialForUser {
45
+ constructor({ getCredentialForUser, submitAuthorizationStep }) {
46
+ this.getCredentialForUser = getCredentialForUser;
47
+ this.submitAuthorizationStep = submitAuthorizationStep;
48
+ }
49
+
50
+ async execute(credentialId, user, { data, step = 1, sessionId } = {}) {
51
+ const binding = await credentialEntityType(
52
+ this.getCredentialForUser,
53
+ credentialId,
54
+ user
55
+ );
56
+ return this.submitAuthorizationStep.execute({
57
+ user,
58
+ ...binding,
59
+ data,
60
+ step,
61
+ sessionId,
62
+ });
63
+ }
64
+ }
65
+
66
+ module.exports = { GetCredentialReauthorization, ReauthorizeCredentialForUser };
@@ -4,6 +4,7 @@ const {
4
4
  getFieldsToEncryptOnWrite,
5
5
  loadCustomEncryptionSchema,
6
6
  } = require('./encryption/encryption-schema-registry');
7
+ const { getEncryptionConfig } = require('./encryption/encryption-config');
7
8
 
8
9
  /**
9
10
  * Encryption service specifically for DocumentDB repositories
@@ -41,43 +42,29 @@ class DocumentDBEncryptionService {
41
42
  }
42
43
 
43
44
  /**
44
- * Initialize Cryptor with environment-based configuration.
45
- * Matches the logic from @friggframework/core/database/prisma.js
45
+ * Initialize Cryptor with environment-based configuration, using the
46
+ * same rule as the Prisma client (see encryption/encryption-config.js).
46
47
  *
47
- * Encryption is bypassed in dev/test/local stages.
48
- * Production uses AWS KMS (if available) or AES encryption.
48
+ * Local runs skip encryption on the dev, test and local stages. A
49
+ * deployed runtime with no key throws instead of writing plaintext.
49
50
  *
50
51
  * @private
52
+ * @throws {EncryptionConfigurationError} deployed with no usable key
51
53
  */
52
54
  _initializeCryptor() {
53
55
  // Load custom encryption schema from app definition BEFORE checking configuration
54
56
  // This ensures custom fields (like User.username) are registered before any encryption operations
55
57
  loadCustomEncryptionSchema();
56
58
 
57
- // Match logic from packages/core/database/prisma.js
58
- const stage = process.env.STAGE || process.env.NODE_ENV || 'development';
59
- const bypassEncryption = ['dev', 'test', 'local'].includes(stage.toLowerCase());
59
+ const config = getEncryptionConfig();
60
60
 
61
- if (bypassEncryption) {
61
+ if (!config.enabled) {
62
62
  this.cryptor = null;
63
63
  this.enabled = false;
64
64
  return;
65
65
  }
66
66
 
67
- // Determine encryption method (ensure boolean values)
68
- const hasKMS = !!(process.env.KMS_KEY_ARN && process.env.KMS_KEY_ARN.trim() !== '');
69
- const hasAES = !!(process.env.AES_KEY_ID && process.env.AES_KEY_ID.trim() !== '');
70
-
71
- if (!hasKMS && !hasAES) {
72
- console.warn('[DocumentDBEncryptionService] No encryption keys configured. Encryption disabled.');
73
- this.cryptor = null;
74
- this.enabled = false;
75
- return;
76
- }
77
-
78
- // KMS takes precedence over AES
79
- const shouldUseAws = hasKMS;
80
- this.cryptor = new Cryptor({ shouldUseAws });
67
+ this.cryptor = new Cryptor({ shouldUseAws: config.method === 'kms' });
81
68
  this.enabled = true;
82
69
  }
83
70
 
@@ -25,8 +25,6 @@ async function findMany(client, collection, filter = {}, options = {}) {
25
25
  if (options.projection) command.projection = options.projection;
26
26
  if (options.sort) command.sort = options.sort;
27
27
  if (options.limit) command.limit = options.limit;
28
- // The first batch holds 101 documents unless asked for more; a page wants all of its rows.
29
- if (options.batchSize) command.batchSize = options.batchSize;
30
28
  const result = await client.$runCommandRaw(command);
31
29
  return result?.cursor?.firstBatch || [];
32
30
  }
@@ -60,10 +58,7 @@ async function insertOne(client, collection, document) {
60
58
 
61
59
  // Provide helpful context for common errors
62
60
  if (error.code === 11000) {
63
- throw Object.assign(
64
- new Error(`${errorMsg} - Duplicate key violation`),
65
- { code: 11000 }
66
- );
61
+ throw new Error(`${errorMsg} - Duplicate key violation`);
67
62
  }
68
63
  throw new Error(errorMsg);
69
64
  }
@@ -13,7 +13,7 @@ This module provides **transparent field-level encryption** for sensitive data i
13
13
  - ✅ **Hexagonal architecture**: Clean separation of concerns
14
14
  - ✅ **AWS KMS support**: Enterprise-grade encryption with AWS Key Management Service
15
15
  - ✅ **Local AES fallback**: Development mode using local encryption keys
16
- - ✅ **Environment-based**: Automatic bypass in dev/test/local environments
16
+ - ✅ **Fails closed**: A deployed stage with no key refuses to start; only local runs (`frigg start`, tests) skip encryption
17
17
  - ✅ **Envelope encryption**: Secure key management pattern
18
18
 
19
19
  ## Architecture
@@ -107,18 +107,46 @@ AES_KEY=your-32-character-secret-key-here
107
107
  STAGE=production # or development, staging, etc.
108
108
  ```
109
109
 
110
- **⚠️ Important**: Encryption is automatically **disabled** when `STAGE` is set to `dev`, `test`, or `local`, regardless of key configuration.
110
+ ### When Encryption Runs
111
111
 
112
- ### Bypass Encryption
112
+ The rule lives in `encryption-config.js` and is shared by the Prisma client, the DocumentDB encryption service, the integration-mapping helpers and the `/health/detailed` check. It depends on **where the code runs**, not on the stage name.
113
113
 
114
- To explicitly disable encryption:
114
+ A process is **deployed** when it runs in AWS Lambda (`AWS_LAMBDA_FUNCTION_NAME` or `LAMBDA_TASK_ROOT` is set, or `AWS_EXECUTION_ENV` starts with `AWS_Lambda_`) or on another provider's platform (`FRIGG_PROVIDER` names a provider other than `aws`; provider-netlify's generated functions set `FRIGG_PROVIDER=netlify`), and is **not** a local run (`IS_OFFLINE=true` from serverless-offline / `frigg start`, `IS_LOCAL=true` from `serverless invoke local`, `NETLIFY_DEV=true` from `netlify dev`, or `JEST_WORKER_ID` from Jest). Everything else is **local**. Netlify's `SITE_ID`, `CONTEXT` and `NETLIFY` are build-time variables, so they are not used.
115
+
116
+ | Runtime | Key configured | `FRIGG_ENCRYPTION_DISABLED=true` | Result |
117
+ | --- | --- | --- | --- |
118
+ | Deployed, any stage (including `dev`) | `KMS_KEY_ARN` | any | Encrypt with KMS |
119
+ | Deployed, any stage | `AES_KEY_ID` + `AES_KEY` | any | Encrypt with AES |
120
+ | Deployed, any stage | `AES_KEY_ID` without `AES_KEY` | no | **Refuses to start** (`EncryptionConfigurationError`) |
121
+ | Deployed, any stage | none | no | **Refuses to start** (`EncryptionConfigurationError`) |
122
+ | Deployed, any stage | none | yes | Plaintext, with a warning on every cold start |
123
+ | Local, `STAGE` (or `NODE_ENV`) is `dev`, `test` or `local` | any | any | Skipped |
124
+ | Local, any other stage | `KMS_KEY_ARN` or `AES_KEY_ID` | any | Encrypt |
125
+ | Local, any other stage | none | any | Plaintext, with a warning |
126
+
127
+ KMS wins when both keys are set. A configured key always wins over `FRIGG_ENCRYPTION_DISABLED`: switching encryption off while a key exists would leave already-encrypted data unreadable, so the opt-out is ignored (with a warning).
128
+
129
+ "Refuses to start" means the Prisma client is never created: the first database access on a cold start throws
115
130
 
116
- ```bash
117
- # Disable encryption (development only)
118
- STAGE=development # or dev, test, local
119
131
  ```
132
+ EncryptionConfigurationError: [Frigg] No field-level encryption key is configured for stage "dev". A deployed Frigg app will not write credentials and other sensitive fields in plaintext. Fix: ...
133
+ ```
134
+
135
+ and `/health/detailed` reports `checks.encryption.status: "unhealthy"` with the same message. If a key is configured but the encryption extension fails to initialise, the client also refuses to start rather than continuing without encryption.
136
+
137
+ To encrypt a local run, use a stage other than `dev`, `test` or `local` and configure a key.
138
+
139
+ ### Running a Deployed Stage Without Encryption
120
140
 
121
- Or simply don't configure any encryption keys. In Production field level encryption **must** be enabled.
141
+ Only do this on purpose, for a stage that never holds real credentials. Either set it in the app definition:
142
+
143
+ ```javascript
144
+ const appDefinition = {
145
+ encryption: { fieldLevelEncryptionMethod: 'none' },
146
+ };
147
+ ```
148
+
149
+ which the infrastructure builders turn into `FRIGG_ENCRYPTION_DISABLED=true` on every function, or set `FRIGG_ENCRYPTION_DISABLED=true` in the Lambda environment yourself. Every cold start logs a warning that sensitive fields are stored in plaintext. There is no default that does this.
122
150
 
123
151
  ## Encrypted Fields
124
152
 
@@ -428,6 +456,8 @@ Format: "keyId:encryptedText:encryptedKey"
428
456
  Example: "base64KeyId:iv:ciphertext:base64EncryptedDataKey"
429
457
  ```
430
458
 
459
+ **Recognising ciphertext on read.** A value is decrypted only when it has exactly four colon-separated parts: base64 `keyId`, 32-hex-character `iv`, hex ciphertext, base64 `encryptedKey`. Plaintext that merely contains colons (`https://user:pw@host:443`) is left alone. A value with that shape that still fails to decrypt (a wrong, rotated or missing key) fails the read with `FieldDecryptionError` in a deployed runtime (see [When Encryption Runs](#when-encryption-runs)), so ciphertext never reaches an API module as if it were a token. Locally it is returned as stored and logged as a warning, so one bad field does not fail a whole read. A field that becomes encrypted later (for example a module's `credentialFields`) stays plaintext in existing rows until they are next written.
460
+
431
461
  **Why Envelope Encryption?**
432
462
 
433
463
  - Reduces KMS API calls (one DEK per field, cached)
@@ -553,8 +583,8 @@ class MyRepositoryDocumentDB {
553
583
 
554
584
  #### Configuration
555
585
 
556
- Uses the same environment variables and Cryptor as the Prisma Extension:
557
- - `STAGE`: Bypasses encryption for dev/test/local
586
+ Uses the same rule (`encryption-config.js`, see [When Encryption Runs](#when-encryption-runs)) and Cryptor as the Prisma Extension. Constructing the service in a deployed runtime with no key throws `EncryptionConfigurationError`.
587
+ - `STAGE`: Skips encryption for dev/test/local on local runs only
558
588
  - `KMS_KEY_ARN`: AWS KMS encryption (production)
559
589
  - `AES_KEY_ID` + `AES_KEY`: AES encryption (fallback)
560
590
 
@@ -615,10 +645,27 @@ curl http://localhost:3000/health/test-encryption
615
645
  "encryptionWorks": true
616
646
  }
617
647
 
618
- # Response when encryption disabled:
648
+ # Response on a local run with STAGE=dev:
619
649
  {
620
650
  "status": "disabled",
621
- "reason": "Encryption bypassed for stage: development"
651
+ "bypassed": true,
652
+ "runtime": "local",
653
+ "testResult": "Encryption bypassed for this stage"
654
+ }
655
+
656
+ # Response in a deployed stage with no key (the app itself refuses to start):
657
+ {
658
+ "status": "unhealthy",
659
+ "mode": "none",
660
+ "runtime": "deployed",
661
+ "testResult": "[Frigg] No field-level encryption key is configured for stage \"dev\". ..."
662
+ }
663
+
664
+ # Response in a deployed stage with FRIGG_ENCRYPTION_DISABLED=true and no key:
665
+ {
666
+ "status": "disabled",
667
+ "optedOut": true,
668
+ "testResult": "Encryption explicitly disabled (FRIGG_ENCRYPTION_DISABLED=true); sensitive fields are stored in plaintext"
622
669
  }
623
670
  ```
624
671
 
@@ -732,9 +779,10 @@ FRIGG_LOG_LEVEL=INFO
732
779
  **Check environment variables:**
733
780
 
734
781
  ```bash
735
- echo $STAGE # Should be 'production' (not dev/test/local)
736
782
  echo $KMS_KEY_ARN # Should be set (for KMS)
737
- echo $AES_KEY_ID # Should be set (for AES)
783
+ echo $AES_KEY_ID $AES_KEY # Both should be set (for AES)
784
+ echo $STAGE # Local runs only: dev/test/local skip encryption
785
+ echo $FRIGG_ENCRYPTION_DISABLED # Should be unset
738
786
  ```
739
787
 
740
788
  **Check console logs:**
@@ -749,6 +797,22 @@ or
749
797
  [Frigg] Field-level encryption disabled
750
798
  ```
751
799
 
800
+ ### Deployed Stage Refuses to Start
801
+
802
+ **Error: "EncryptionConfigurationError: [Frigg] No field-level encryption key is configured for stage ..."**
803
+
804
+ The function runs in AWS and has neither `KMS_KEY_ARN` nor `AES_KEY_ID` + `AES_KEY`. Earlier versions skipped encryption on stages named `dev`, `test` or `local` and wrote plaintext when no key was set; deployed stages now refuse instead. Fix one of:
805
+
806
+ 1. Set `encryption: { fieldLevelEncryptionMethod: 'kms' }` in the app definition and redeploy. Frigg creates or discovers a KMS key and sets `KMS_KEY_ARN` on every function, whatever the stage name.
807
+ 2. Provide `AES_KEY_ID` and `AES_KEY` (32 characters) through the app definition's `environment` and the deploy environment.
808
+ 3. To keep the stage in plaintext on purpose, set `encryption: { fieldLevelEncryptionMethod: 'none' }` (or `FRIGG_ENCRYPTION_DISABLED=true`).
809
+
810
+ Data written in plaintext before the key existed stays readable: reads leave values that are not in the encrypted `keyId:iv:cipher:encKey` format untouched, and the next write of each record encrypts it. Records that are never rewritten stay in plaintext until you re-save them.
811
+
812
+ **Error: "[Frigg] AES_KEY_ID is set but AES_KEY is not"**
813
+
814
+ Provide `AES_KEY` alongside `AES_KEY_ID`, or switch to KMS.
815
+
752
816
  ### AWS KMS Errors
753
817
 
754
818
  **Error: "User is not authorized to perform: kms:GenerateDataKey"**