@friggframework/core 2.0.0--canary.703.12b980b.0 → 2.0.0--canary.707.df80bfd.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 (308) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/CLAUDE.md +28 -0
  3. package/README.md +105 -0
  4. package/application/commands/integration-commands.js +20 -10
  5. package/application/commands/scheduler-commands.js +11 -7
  6. package/application/commands/user-commands.js +17 -5
  7. package/application/index.js +6 -2
  8. package/core/Worker.js +31 -7
  9. package/core/create-handler.js +9 -0
  10. package/credential/repositories/credential-repository-documentdb.js +34 -0
  11. package/credential/repositories/credential-repository-interface.js +15 -0
  12. package/credential/repositories/credential-repository-mongo.js +23 -0
  13. package/credential/repositories/credential-repository-postgres.js +28 -0
  14. package/credential/use-cases/credential-operations-for-user.js +202 -0
  15. package/credential/use-cases/reauthorize-credential-for-user.js +73 -0
  16. package/database/config.js +48 -24
  17. package/database/documentdb-encryption-service.js +9 -22
  18. package/database/documentdb-utils.js +2 -2
  19. package/database/encryption/README.md +78 -14
  20. package/database/encryption/documentdb-encryption-service.md +78 -1
  21. package/database/encryption/encryption-config.js +219 -0
  22. package/database/encryption/encryption-schema-registry.js +121 -24
  23. package/database/encryption/field-encryption-service.js +69 -5
  24. package/database/encryption/integration-mapping-encryption.js +1 -1
  25. package/database/encryption/test-support/fake-ciphertext.js +15 -0
  26. package/database/organization-where.js +18 -0
  27. package/database/prisma.js +15 -38
  28. package/database/unique-violation.js +25 -0
  29. package/database/use-cases/check-encryption-health-use-case.js +43 -52
  30. package/errors/index.js +0 -4
  31. package/extensions/bootstrap-runner.js +43 -0
  32. package/extensions/extension-loader.js +230 -0
  33. package/extensions/index.js +44 -0
  34. package/extensions/initialize-app.js +123 -0
  35. package/extensions/prisma-composer.js +270 -0
  36. package/extensions/route-mounter.js +103 -0
  37. package/extensions/schema-composer.js +188 -0
  38. package/generated/prisma-mongodb/edge.js +33 -42
  39. package/generated/prisma-mongodb/index-browser.js +30 -39
  40. package/generated/prisma-mongodb/index.d.ts +3187 -2005
  41. package/generated/prisma-mongodb/index.js +33 -42
  42. package/generated/prisma-mongodb/package.json +1 -1
  43. package/generated/prisma-mongodb/schema.prisma +86 -59
  44. package/generated/prisma-mongodb/wasm.js +33 -42
  45. package/generated/prisma-postgresql/edge.js +33 -42
  46. package/generated/prisma-postgresql/index-browser.js +30 -39
  47. package/generated/prisma-postgresql/index.d.ts +3380 -2177
  48. package/generated/prisma-postgresql/index.js +33 -42
  49. package/generated/prisma-postgresql/package.json +1 -1
  50. package/generated/prisma-postgresql/schema.prisma +81 -57
  51. package/generated/prisma-postgresql/wasm.js +33 -42
  52. package/handlers/WEBHOOKS.md +0 -29
  53. package/handlers/app-definition-loader.js +128 -19
  54. package/handlers/app-handler-helpers.js +27 -8
  55. package/handlers/backend-utils.js +31 -25
  56. package/handlers/integration-event-dispatcher.js +3 -7
  57. package/handlers/middleware/admin-auth.js +14 -1
  58. package/handlers/routers/auth.js +46 -10
  59. package/handlers/routers/health.js +13 -4
  60. package/handlers/routers/integration-defined-routers.js +144 -92
  61. package/handlers/routers/integration-webhook-routers.js +100 -50
  62. package/handlers/workers/integration-defined-workers.js +5 -2
  63. package/index.js +66 -16
  64. package/infrastructure/scheduler/index.js +19 -6
  65. package/infrastructure/scheduler/netlify-scheduler-adapter.js +216 -0
  66. package/infrastructure/scheduler/scheduled-job-repository.js +118 -0
  67. package/infrastructure/scheduler/scheduler-service-factory.js +55 -7
  68. package/integrations/index.js +1 -14
  69. package/integrations/integration-base.js +2 -163
  70. package/integrations/integration-router.js +132 -102
  71. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  72. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  73. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  74. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  75. package/integrations/repositories/integration-mapping-repository.js +0 -29
  76. package/integrations/repositories/integration-not-found.js +14 -0
  77. package/integrations/repositories/integration-repository-documentdb.js +37 -9
  78. package/integrations/repositories/integration-repository-interface.js +17 -4
  79. package/integrations/repositories/integration-repository-mongo.js +64 -96
  80. package/integrations/repositories/integration-repository-postgres.js +63 -81
  81. package/integrations/repositories/process-repository-mongo.js +1 -1
  82. package/integrations/schedule-config.js +80 -0
  83. package/integrations/tests/doubles/test-integration-repository.js +12 -1
  84. package/integrations/use-cases/create-integration.js +56 -31
  85. package/integrations/use-cases/delete-integration-for-user.js +4 -4
  86. package/integrations/use-cases/dispatch-ongoing-syncs.js +100 -0
  87. package/integrations/use-cases/get-integration-for-user.js +2 -4
  88. package/integrations/use-cases/get-integration-instance.js +4 -4
  89. package/integrations/use-cases/get-integrations-for-user.js +79 -39
  90. package/integrations/use-cases/get-possible-integrations.js +2 -7
  91. package/integrations/use-cases/index.js +7 -1
  92. package/integrations/use-cases/integration-operations-for-user.js +256 -0
  93. package/integrations/use-cases/resolve-integration-ownership.js +177 -0
  94. package/integrations/use-cases/update-integration.js +4 -4
  95. package/integrations/utils/map-integration-dto.js +43 -14
  96. package/management-api/create-management-api-router.js +49 -0
  97. package/management-api/error-response.js +116 -0
  98. package/management-api/management-api-config.js +151 -0
  99. package/management-api/meta-router.js +76 -0
  100. package/management-api/openapi/build-openapi.js +144 -0
  101. package/management-api/openapi/components.js +415 -0
  102. package/management-api/openapi/v1-operations.js +83 -0
  103. package/management-api/openapi/v2-operations.js +264 -0
  104. package/management-api/route-registry.js +411 -0
  105. package/management-api/test-support/http-client.js +39 -0
  106. package/management-api/use-cases/get-management-api-meta.js +57 -0
  107. package/management-api/v1-deprecation.js +120 -0
  108. package/management-api/v2/create-v2-router.js +85 -0
  109. package/management-api/v2/dependencies.js +281 -0
  110. package/management-api/v2/dto.js +143 -0
  111. package/management-api/v2/handlers/authorization.js +94 -0
  112. package/management-api/v2/handlers/credentials.js +33 -0
  113. package/management-api/v2/handlers/entities.js +77 -0
  114. package/management-api/v2/handlers/integrations.js +128 -0
  115. package/management-api/v2/handlers/proxy.js +34 -0
  116. package/management-api/v2/request.js +85 -0
  117. package/management-api/v2/test-support/fake-dependencies.js +103 -0
  118. package/modules/domain/authorization-session.js +144 -0
  119. package/modules/entity-scope.js +15 -0
  120. package/modules/entity-type-registry.js +311 -0
  121. package/modules/index.js +14 -0
  122. package/modules/module-factory.js +12 -0
  123. package/modules/module.js +53 -2
  124. package/modules/proxy/proxy-bases.js +169 -0
  125. package/modules/proxy/proxy-errors.js +31 -0
  126. package/modules/proxy/proxy-path.js +183 -0
  127. package/modules/proxy/proxy-policy.js +277 -0
  128. package/modules/repositories/authorization-session-repository-documentdb.js +112 -0
  129. package/modules/repositories/authorization-session-repository-factory.js +31 -0
  130. package/modules/repositories/authorization-session-repository-interface.js +47 -0
  131. package/modules/repositories/authorization-session-repository-prisma.js +87 -0
  132. package/modules/repositories/entity-not-found.js +18 -0
  133. package/modules/repositories/module-repository-documentdb.js +51 -6
  134. package/modules/repositories/module-repository-interface.js +19 -2
  135. package/modules/repositories/module-repository-mongo.js +67 -74
  136. package/modules/repositories/module-repository-postgres.js +66 -74
  137. package/modules/repositories/module-repository.js +2 -1
  138. package/modules/requester/proxy-request.js +245 -0
  139. package/modules/requester/requester.js +35 -5
  140. package/modules/scope-config.js +192 -0
  141. package/modules/scope-policy.js +112 -0
  142. package/modules/scope-resolution.js +288 -0
  143. package/modules/scope-visibility.js +247 -0
  144. package/modules/tests/doubles/in-memory-authorization-session-repository.js +45 -0
  145. package/modules/tests/doubles/ownership-matching.js +18 -0
  146. package/modules/use-cases/authorize-entity-for-user.js +61 -0
  147. package/modules/use-cases/create-entity-from-credential.js +113 -0
  148. package/modules/use-cases/entity-operations-for-user.js +162 -0
  149. package/modules/use-cases/entity-types.js +139 -0
  150. package/modules/use-cases/execute-entity-proxy-request.js +331 -0
  151. package/modules/use-cases/get-authorization-requirements.js +100 -0
  152. package/modules/use-cases/get-entities-for-user.js +26 -13
  153. package/modules/use-cases/get-entity-module-for-user.js +113 -0
  154. package/modules/use-cases/get-entity-options-by-id.js +10 -4
  155. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  156. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  157. package/modules/use-cases/get-module.js +10 -4
  158. package/modules/use-cases/manage-access.js +21 -0
  159. package/modules/use-cases/multi-step-authorization.js +329 -0
  160. package/modules/use-cases/process-authorization-callback.js +53 -19
  161. package/modules/use-cases/refresh-entity-options.js +10 -4
  162. package/modules/use-cases/test-module-auth.js +10 -4
  163. package/package.json +6 -7
  164. package/prisma-mongodb/schema.prisma +86 -59
  165. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +28 -0
  166. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +26 -0
  167. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +25 -0
  168. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +28 -0
  169. package/prisma-postgresql/schema.prisma +81 -57
  170. package/providers/index.js +23 -0
  171. package/providers/resolve-provider.js +93 -0
  172. package/providers/runtime-detection.js +124 -0
  173. package/queues/index.js +25 -0
  174. package/queues/providers/index.js +11 -0
  175. package/queues/providers/netlify-background-provider.js +150 -0
  176. package/queues/providers/qstash-queue-provider.js +219 -0
  177. package/queues/providers/sqs-queue-provider.js +70 -0
  178. package/queues/queue-client-interface.js +55 -0
  179. package/queues/queue-message-auth.js +193 -0
  180. package/queues/queue-provider-factory.js +101 -0
  181. package/queues/queue-provider.js +65 -0
  182. package/queues/queuer-util.js +2 -9
  183. package/queues/sqs-queue-client.js +81 -0
  184. package/types/index.d.ts +2 -0
  185. package/types/modules/index.d.ts +214 -0
  186. package/types/user/index.d.ts +134 -0
  187. package/user/adopter-jwt-config.js +177 -0
  188. package/user/adopter-jwt-errors.js +59 -0
  189. package/user/adopter-token-verifier.js +122 -0
  190. package/user/app-user-helpers.js +97 -0
  191. package/user/create-user-authentication.js +64 -0
  192. package/user/membership.js +51 -0
  193. package/user/repositories/organization-membership-record.js +19 -0
  194. package/user/repositories/organization-membership-repository-documentdb.js +106 -0
  195. package/user/repositories/organization-membership-repository-factory.js +42 -0
  196. package/user/repositories/organization-membership-repository-interface.js +57 -0
  197. package/user/repositories/organization-membership-repository-mongo.js +13 -0
  198. package/user/repositories/organization-membership-repository-postgres.js +29 -0
  199. package/user/repositories/organization-membership-repository-prisma.js +81 -0
  200. package/user/repositories/user-repository-documentdb.js +27 -2
  201. package/user/repositories/user-repository-interface.js +18 -0
  202. package/user/repositories/user-repository-mongo.js +24 -0
  203. package/user/repositories/user-repository-postgres.js +18 -0
  204. package/user/tests/doubles/adopter-jwt-fixtures.js +220 -0
  205. package/user/use-cases/authenticate-user.js +7 -1
  206. package/user/use-cases/ensure-organization-membership.js +92 -0
  207. package/user/use-cases/find-individual-users-by-organization.js +54 -0
  208. package/user/use-cases/get-user-from-adopter-jwt.js +95 -124
  209. package/user/use-cases/get-user-from-x-frigg-headers.js +83 -80
  210. package/user/user.js +64 -1
  211. package/errors/mapping-already-exists-error.js +0 -14
  212. package/handlers/workers/integration-triggers.js +0 -25
  213. package/infrastructure/scheduler/recurrence.js +0 -204
  214. package/integrations/define/DESIGN.md +0 -122
  215. package/integrations/define/config.js +0 -98
  216. package/integrations/define/define-app.js +0 -66
  217. package/integrations/define/define-extension.js +0 -154
  218. package/integrations/define/define-integration.js +0 -335
  219. package/integrations/define/examples/deal-alerts.js +0 -140
  220. package/integrations/define/extension-binding.js +0 -174
  221. package/integrations/define/index.js +0 -11
  222. package/integrations/define/json-schema-lite.js +0 -68
  223. package/integrations/define/subscriptions.js +0 -186
  224. package/integrations/define/tests/fixtures/hubspot.js +0 -109
  225. package/integrations/define/tests/fixtures/slack.js +0 -26
  226. package/integrations/define/use.js +0 -39
  227. package/integrations/definitions/README.md +0 -278
  228. package/integrations/definitions/canonical.js +0 -11
  229. package/integrations/definitions/capabilities/AUDIT.md +0 -480
  230. package/integrations/definitions/capabilities/acmeerp.capabilities.json +0 -633
  231. package/integrations/definitions/capabilities/asana.capabilities.json +0 -279
  232. package/integrations/definitions/capabilities/calendly.capabilities.json +0 -385
  233. package/integrations/definitions/capabilities/docusign.capabilities.json +0 -314
  234. package/integrations/definitions/capabilities/fathom.capabilities.json +0 -238
  235. package/integrations/definitions/capabilities/github.capabilities.json +0 -585
  236. package/integrations/definitions/capabilities/hubspot.capabilities.json +0 -822
  237. package/integrations/definitions/capabilities/jira.capabilities.json +0 -391
  238. package/integrations/definitions/capabilities/klaviyo.capabilities.json +0 -503
  239. package/integrations/definitions/capabilities/linear.capabilities.json +0 -378
  240. package/integrations/definitions/capabilities/netsuite.capabilities.json +0 -535
  241. package/integrations/definitions/capabilities/notion.capabilities.json +0 -208
  242. package/integrations/definitions/capabilities/phone.capabilities.json +0 -511
  243. package/integrations/definitions/capabilities/pipedrive.capabilities.json +0 -430
  244. package/integrations/definitions/capabilities/quickbooks.capabilities.json +0 -635
  245. package/integrations/definitions/capabilities/salesforce.capabilities.json +0 -568
  246. package/integrations/definitions/capabilities/shopify.capabilities.json +0 -1128
  247. package/integrations/definitions/capabilities/slack.capabilities.json +0 -373
  248. package/integrations/definitions/capabilities/stripe.capabilities.json +0 -630
  249. package/integrations/definitions/capabilities/webflow.capabilities.json +0 -196
  250. package/integrations/definitions/capabilities/zendesk.capabilities.json +0 -422
  251. package/integrations/definitions/compile.js +0 -80
  252. package/integrations/definitions/config-form.js +0 -137
  253. package/integrations/definitions/examples/acme-erp-quickbooks.definition.json +0 -467
  254. package/integrations/definitions/examples/asana-slack.definition.json +0 -219
  255. package/integrations/definitions/examples/calendly-salesforce.definition.json +0 -459
  256. package/integrations/definitions/examples/docusign-salesforce.definition.json +0 -305
  257. package/integrations/definitions/examples/fathom-hubspot-notion.definition.json +0 -575
  258. package/integrations/definitions/examples/github-linear.definition.json +0 -322
  259. package/integrations/definitions/examples/hubspot-slack.definition.json +0 -427
  260. package/integrations/definitions/examples/klaviyo-hubspot.definition.json +0 -336
  261. package/integrations/definitions/examples/phone-hubspot.definition.json +0 -633
  262. package/integrations/definitions/examples/pipedrive-hubspot.definition.json +0 -136
  263. package/integrations/definitions/examples/pipedrive-phone.definition.json +0 -340
  264. package/integrations/definitions/examples/records/phone-hubspot.definition-version.json +0 -652
  265. package/integrations/definitions/examples/records/phone-hubspot.integration.json +0 -86
  266. package/integrations/definitions/examples/records/phone-hubspot.mappings.json +0 -39
  267. package/integrations/definitions/examples/records/phone-hubspot.workflow-run.json +0 -62
  268. package/integrations/definitions/examples/shopify-klaviyo.definition.json +0 -488
  269. package/integrations/definitions/examples/shopify-netsuite.definition.json +0 -622
  270. package/integrations/definitions/examples/stripe-quickbooks.definition.json +0 -476
  271. package/integrations/definitions/examples/webflow-hubspot-slack.definition.json +0 -262
  272. package/integrations/definitions/examples/zendesk-jira.definition.json +0 -604
  273. package/integrations/definitions/expressions.js +0 -229
  274. package/integrations/definitions/index.js +0 -48
  275. package/integrations/definitions/integration-runtime.js +0 -779
  276. package/integrations/definitions/interpreter.js +0 -104
  277. package/integrations/definitions/manifests.js +0 -177
  278. package/integrations/definitions/renderers/common.js +0 -67
  279. package/integrations/definitions/renderers/html.js +0 -129
  280. package/integrations/definitions/renderers/hubspot.js +0 -59
  281. package/integrations/definitions/renderers/preview.js +0 -154
  282. package/integrations/definitions/renderers/slack.js +0 -146
  283. package/integrations/definitions/repositories/definition-version-repository.js +0 -67
  284. package/integrations/definitions/repositories/workflow-run-repository.js +0 -80
  285. package/integrations/definitions/router.js +0 -170
  286. package/integrations/definitions/runtime.js +0 -268
  287. package/integrations/definitions/schema/capability-manifest.v0.1.schema.json +0 -549
  288. package/integrations/definitions/schema/installation.v0.1.schema.json +0 -130
  289. package/integrations/definitions/schema/integration-definition.v0.1.schema.json +0 -909
  290. package/integrations/definitions/schema/records.md +0 -105
  291. package/integrations/definitions/schema-check.js +0 -58
  292. package/integrations/definitions/scripts/check-manifests.js +0 -220
  293. package/integrations/definitions/scripts/validate.js +0 -66
  294. package/integrations/definitions/steps.js +0 -123
  295. package/integrations/definitions/sync-engine.js +0 -297
  296. package/integrations/definitions/tests/helpers-fake-crm.js +0 -49
  297. package/integrations/definitions/transforms.js +0 -91
  298. package/integrations/definitions/use-cases/definition-use-cases.js +0 -245
  299. package/integrations/definitions/validate.js +0 -436
  300. package/integrations/definitions/versioning.js +0 -176
  301. package/integrations/definitions/webhooks.js +0 -119
  302. package/integrations/integration-types.js +0 -73
  303. package/integrations/triggers.js +0 -244
  304. package/integrations/use-cases/run-trigger-tick.js +0 -155
  305. package/integrations/use-cases/run-trigger.js +0 -77
  306. package/prisma-postgresql/migrations/20261018000000_add_data_defined_integrations/migration.sql +0 -66
  307. package/prisma-postgresql/migrations/20261019000000_workflow_run_waits/migration.sql +0 -7
  308. package/prisma-postgresql/migrations/20261019120000_definition_workspace/migration.sql +0 -5
@@ -0,0 +1,202 @@
1
+ const Boom = require('@hapi/boom');
2
+ const {
3
+ createScopePolicy,
4
+ describeRecord,
5
+ visibilityClauses,
6
+ matchesListFilters,
7
+ SCOPES,
8
+ } = require('../../modules/entity-scope');
9
+ const { assertCanManage } = require('../../modules/use-cases/manage-access');
10
+
11
+ /**
12
+ * Management API v2 credential operations (ADR-056 §3.4, §3.6). A credential
13
+ * has no module name and no organization of its own:
14
+ *
15
+ * - its `type` and `entityIds` come from the entities that use it that the
16
+ * caller may see, so the same person's account connected in two
17
+ * organizations (one credential, two entities) lists in each organization
18
+ * with that organization's entity only;
19
+ * - who it belongs to is its OWNER (`credential.userId`), never the entities:
20
+ * a credential an individual entity and an organization entity both point at
21
+ * (possible only through legacy data) is described by whoever owns the
22
+ * credential, so the answer cannot change with the order the entities load;
23
+ * - a credential whose entities are all out of sight (another organization's)
24
+ * is a 404, and one with no entities at all (its entity was deleted) is
25
+ * visible to its owner only, as it was before scoping.
26
+ */
27
+
28
+ const credentialIdOf = (entity) => {
29
+ const ref = entity.credential ?? entity.credentialId;
30
+ if (ref === undefined || ref === null) return null;
31
+ if (typeof ref === 'object') {
32
+ const id = ref.id ?? ref._id;
33
+ return id === undefined || id === null ? null : String(id);
34
+ }
35
+ return String(ref);
36
+ };
37
+
38
+ /** Adds `type` and `entityIds` from the user's entities to each credential. */
39
+ function withEntityUsage(credentials, entities) {
40
+ const usage = new Map();
41
+ for (const entity of entities || []) {
42
+ const credentialId = credentialIdOf(entity);
43
+ if (!credentialId) continue;
44
+ const entry = usage.get(credentialId) || { type: null, entityIds: [] };
45
+ entry.type = entry.type || entity.moduleName || null;
46
+ entry.entityIds.push(String(entity.id));
47
+ usage.set(credentialId, entry);
48
+ }
49
+ return credentials.map((credential) => {
50
+ const entry = usage.get(String(credential.id)) || {
51
+ type: null,
52
+ entityIds: [],
53
+ };
54
+ return { ...credential, type: entry.type, entityIds: entry.entityIds };
55
+ });
56
+ }
57
+
58
+ /**
59
+ * `{scope, owner, organizationId, access}` of a credential for this caller, or
60
+ * null when its owner is neither the caller nor the active organization. Built
61
+ * by `describeRecord` over the row a connection by this owner has: the
62
+ * organization of a visible entity, else the one a new entity would get.
63
+ */
64
+ function credentialTenancy(credential, visibleEntities, ctx) {
65
+ const entityOrg = visibleEntities.find(
66
+ (entity) => entity.organizationId !== undefined && entity.organizationId !== null
67
+ )?.organizationId;
68
+ const organizationId =
69
+ entityOrg ?? (ctx.individualAcross === 'all' ? null : ctx.activeOrgId);
70
+ return describeRecord({ userId: credential.userId, organizationId }, ctx, 'entity');
71
+ }
72
+
73
+ /** The entities of `entities` the caller may see, each with its `tenancy`. */
74
+ function visibleOf(entities, ctx) {
75
+ const visible = [];
76
+ for (const entity of entities || []) {
77
+ const tenancy = describeRecord(entity, ctx, 'entity');
78
+ if (tenancy) visible.push({ ...entity, tenancy });
79
+ }
80
+ return visible;
81
+ }
82
+
83
+ /**
84
+ * The caller's credentials with their type, the entities of them they may see
85
+ * and `tenancy`. Credentials with no entity at all are listed too, for the
86
+ * person and the active organization that own them.
87
+ */
88
+ class ListCredentialsForUser {
89
+ constructor({ credentialRepository, moduleRepository, scopePolicy }) {
90
+ this.credentialRepository = credentialRepository;
91
+ this.moduleRepository = moduleRepository;
92
+ this.scopePolicy = scopePolicy || createScopePolicy();
93
+ }
94
+
95
+ /** @param {{scope?: string, owner?: string}} [filters] */
96
+ async execute(user, filters = {}) {
97
+ const ctx = this.scopePolicy.accessContext(user);
98
+ const owners = [...new Set([ctx.callerId, ctx.activeOrgId].filter(Boolean))];
99
+ const [found, perOwner, owned] = await Promise.all([
100
+ this.moduleRepository.findEntitiesByOwnership(visibilityClauses(ctx, 'entity')),
101
+ Promise.all(owners.map((id) => this.credentialRepository.findCredentialsByUserId(id))),
102
+ // Every entity of those owners, in any organization: only to tell a credential
103
+ // with no entity at all from one used elsewhere.
104
+ Promise.all(owners.map((id) => this.moduleRepository.findEntitiesByUserId(id))),
105
+ ]);
106
+ const visible = visibleOf(found, ctx);
107
+ const usedAnywhere = new Set(owned.flat().map(credentialIdOf).filter(Boolean));
108
+ const listed = [];
109
+ for (const credential of perOwner.flat().filter(Boolean)) {
110
+ const id = String(credential.id);
111
+ const referencing = visible.filter((entity) => credentialIdOf(entity) === id);
112
+ if (referencing.length === 0 && usedAnywhere.has(id)) continue;
113
+ const tenancy = credentialTenancy(credential, referencing, ctx);
114
+ if (!tenancy || !matchesListFilters(tenancy, filters)) continue;
115
+ listed.push({ ...withEntityUsage([credential], referencing)[0], tenancy });
116
+ }
117
+ return listed;
118
+ }
119
+ }
120
+
121
+ /** One credential the caller may see: see the header. 404 otherwise. */
122
+ class GetCredentialForUserV2 {
123
+ constructor({ credentialRepository, moduleRepository, scopePolicy }) {
124
+ this.credentialRepository = credentialRepository;
125
+ this.moduleRepository = moduleRepository;
126
+ this.scopePolicy = scopePolicy || createScopePolicy();
127
+ }
128
+
129
+ async execute(credentialId, user) {
130
+ const notFound = () =>
131
+ Boom.notFound(`Credential ${credentialId} not found`, {
132
+ code: 'CREDENTIAL_NOT_FOUND',
133
+ });
134
+ let credential = null;
135
+ try {
136
+ credential = await this.credentialRepository.findCredentialById(
137
+ credentialId
138
+ );
139
+ } catch (error) {
140
+ if (!/Invalid ID|ObjectId|Malformed/i.test(error?.message || '')) {
141
+ throw error;
142
+ }
143
+ }
144
+ if (!credential) throw notFound();
145
+ const ctx = this.scopePolicy.accessContext(user);
146
+
147
+ const referencing =
148
+ (await this.moduleRepository.findEntities({ credentialId: credential.id })) || [];
149
+ const visible = visibleOf(referencing, ctx);
150
+ if (referencing.length > 0 && visible.length === 0) throw notFound();
151
+ const tenancy = credentialTenancy(credential, visible, ctx);
152
+ if (!tenancy) throw notFound();
153
+ return { ...withEntityUsage([credential], visible)[0], tenancy };
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Deletes a credential the caller may manage. The entities that used it stay,
159
+ * with their credential unset, so they show as needing re-authorization rather
160
+ * than disappearing from integrations.
161
+ *
162
+ * Refuses with 409 `CREDENTIAL_SHARED` while an entity the caller cannot see
163
+ * still uses it: one credential row serves the same provider account in every
164
+ * organization, and deleting it from one would break the other. The message
165
+ * says nothing about the other connections (not even how many): remove the
166
+ * entities that use it, and it goes with the last one.
167
+ */
168
+ class DeleteCredentialForUser {
169
+ constructor({ credentialRepository, moduleRepository, getCredentialForUser }) {
170
+ this.credentialRepository = credentialRepository;
171
+ this.moduleRepository = moduleRepository;
172
+ this.getCredentialForUser = getCredentialForUser;
173
+ }
174
+
175
+ async execute(credentialId, user) {
176
+ const credential = await this.getCredentialForUser.execute(
177
+ credentialId,
178
+ user
179
+ );
180
+ assertCanManage(credential.tenancy.access, `credential ${credential.id}`);
181
+ const usedBy =
182
+ (await this.moduleRepository.findEntities({ credentialId: credential.id })) || [];
183
+ if (usedBy.length > credential.entityIds.length) {
184
+ throw Boom.conflict(
185
+ `Credential ${credential.id} is still in use by other connections and cannot be deleted from here`,
186
+ { code: 'CREDENTIAL_SHARED' }
187
+ );
188
+ }
189
+ for (const entityId of credential.entityIds) {
190
+ await this.moduleRepository.unsetCredential(entityId);
191
+ }
192
+ await this.credentialRepository.deleteCredentialById(credential.id);
193
+ return { id: String(credential.id), entityIds: credential.entityIds };
194
+ }
195
+ }
196
+
197
+ module.exports = {
198
+ ListCredentialsForUser,
199
+ GetCredentialForUserV2,
200
+ DeleteCredentialForUser,
201
+ withEntityUsage,
202
+ };
@@ -0,0 +1,73 @@
1
+ const Boom = require('@hapi/boom');
2
+ const { assertCanManage } = require('../../modules/use-cases/manage-access');
3
+
4
+ /**
5
+ * Re-authorization of a credential the caller owns (Management API v2). It
6
+ * runs the same flow as /api/v2/authorize for the credential's entity type,
7
+ * with the session bound to the credential so it cannot be reused for
8
+ * anything else.
9
+ */
10
+ async function credentialEntityType(getCredentialForUser, credentialId, user) {
11
+ const credential = await getCredentialForUser.execute(credentialId, user);
12
+ if (!credential.type) {
13
+ throw Boom.conflict(
14
+ `Credential ${credentialId} is not used by any entity, so its type is unknown; authorize a new connection instead`,
15
+ { code: 'CREDENTIAL_TYPE_UNKNOWN' }
16
+ );
17
+ }
18
+ return {
19
+ entityType: credential.type,
20
+ credentialId: String(credential.id),
21
+ // A re-authorization keeps the scope the connection already has.
22
+ fixedScope: credential.tenancy?.scope,
23
+ access: credential.tenancy?.access,
24
+ };
25
+ }
26
+
27
+ /** GET /api/v2/credentials/:credentialId/reauthorize */
28
+ class GetCredentialReauthorization {
29
+ constructor({ getCredentialForUser, getAuthorizationStep }) {
30
+ this.getCredentialForUser = getCredentialForUser;
31
+ this.getAuthorizationStep = getAuthorizationStep;
32
+ }
33
+
34
+ async execute(credentialId, user, { step = 1, sessionId, state } = {}) {
35
+ const { entityType, credentialId: boundCredentialId } =
36
+ await credentialEntityType(this.getCredentialForUser, credentialId, user);
37
+ return this.getAuthorizationStep.execute({
38
+ user,
39
+ entityType,
40
+ credentialId: boundCredentialId,
41
+ step,
42
+ sessionId,
43
+ state,
44
+ });
45
+ }
46
+ }
47
+
48
+ /** POST /api/v2/credentials/:credentialId/reauthorize */
49
+ class ReauthorizeCredentialForUser {
50
+ constructor({ getCredentialForUser, submitAuthorizationStep }) {
51
+ this.getCredentialForUser = getCredentialForUser;
52
+ this.submitAuthorizationStep = submitAuthorizationStep;
53
+ }
54
+
55
+ async execute(credentialId, user, { data, step = 1, sessionId } = {}) {
56
+ const { access, ...binding } = await credentialEntityType(
57
+ this.getCredentialForUser,
58
+ credentialId,
59
+ user
60
+ );
61
+ // A credential an organization owns: the organization's admins only.
62
+ assertCanManage(access, `credential ${credentialId}`);
63
+ return this.submitAuthorizationStep.execute({
64
+ user,
65
+ ...binding,
66
+ data,
67
+ step,
68
+ sessionId,
69
+ });
70
+ }
71
+ }
72
+
73
+ module.exports = { GetCredentialReauthorization, ReauthorizeCredentialForUser };
@@ -3,6 +3,39 @@
3
3
  * Manages configuration for Prisma ORM operations
4
4
  */
5
5
 
6
+ /**
7
+ * Maps an app definition's `database` block to a Prisma database type.
8
+ *
9
+ * @param {Object|undefined} database - `Definition.database`
10
+ * @param {string} where - where the definition lives, for the error message
11
+ * @returns {'mongodb'|'postgresql'|'documentdb'}
12
+ */
13
+ function databaseTypeFromConfig(database, where) {
14
+ if (!database) {
15
+ throw new Error(
16
+ '[Frigg] App definition missing database configuration. ' +
17
+ `Add database: { postgres: { enable: true } } (or mongoDB/documentDB) to ${where}`
18
+ );
19
+ }
20
+
21
+ // Determine database type from enabled database
22
+ // Priority order: postgres > mongoDB > documentDB
23
+ if (database.postgres?.enable === true) {
24
+ return 'postgresql';
25
+ }
26
+ if (database.mongoDB?.enable === true) {
27
+ return 'mongodb';
28
+ }
29
+ if (database.documentDB?.enable === true) {
30
+ return 'documentdb';
31
+ }
32
+
33
+ throw new Error(
34
+ '[Frigg] No database enabled in app definition. ' +
35
+ 'Set one of: database.postgres.enable, database.mongoDB.enable, or database.documentDB.enable to true'
36
+ );
37
+ }
38
+
6
39
  /**
7
40
  * Determines database type from environment or app definition
8
41
  *
@@ -21,6 +54,20 @@ function getDatabaseType() {
21
54
 
22
55
  // Fallback: Load app definition
23
56
  try {
57
+ // A definition preset with setAppDefinition() (provider-netlify's
58
+ // function preamble) wins: on Netlify process.cwd() is the function
59
+ // root at runtime, so discovery cannot find the backend.
60
+ const {
61
+ getPresetAppDefinition,
62
+ } = require('../handlers/app-definition-loader');
63
+ const preset = getPresetAppDefinition();
64
+ if (preset) {
65
+ return databaseTypeFromConfig(
66
+ preset.database,
67
+ 'your backend/index.js'
68
+ );
69
+ }
70
+
24
71
  const path = require('node:path');
25
72
  const fs = require('node:fs');
26
73
  const { findNearestBackendPackageJson } = require('../utils');
@@ -76,30 +123,7 @@ function getDatabaseType() {
76
123
  }
77
124
 
78
125
  database = backendModule?.Definition?.database;
79
-
80
- if (!database) {
81
- throw new Error(
82
- '[Frigg] App definition missing database configuration. ' +
83
- `Add database: { postgres: { enable: true } } (or mongoDB/documentDB) to ${backendIndexPath}`
84
- );
85
- }
86
-
87
- // Determine database type from enabled database
88
- // Priority order: postgres > mongoDB > documentDB
89
- if (database.postgres?.enable === true) {
90
- return 'postgresql';
91
- }
92
- if (database.mongoDB?.enable === true) {
93
- return 'mongodb';
94
- }
95
- if (database.documentDB?.enable === true) {
96
- return 'documentdb';
97
- }
98
-
99
- throw new Error(
100
- '[Frigg] No database enabled in app definition. ' +
101
- 'Set one of: database.postgres.enable, database.mongoDB.enable, or database.documentDB.enable to true'
102
- );
126
+ return databaseTypeFromConfig(database, backendIndexPath);
103
127
  } catch (error) {
104
128
  // Re-throw with context if it's our error
105
129
  if (error.message.includes('[Frigg]')) {
@@ -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,6 +58,8 @@ async function insertOne(client, collection, document) {
60
58
 
61
59
  // Provide helpful context for common errors
62
60
  if (error.code === 11000) {
61
+ // `code` lets callers recognise a lost race without parsing text
62
+ // (see database/unique-violation.js).
63
63
  throw Object.assign(
64
64
  new Error(`${errorMsg} - Duplicate key violation`),
65
65
  { code: 11000 }
@@ -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"**