@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
@@ -1,10 +1,38 @@
1
1
  const Boom = require('@hapi/boom');
2
- const { User } = require('../user');
2
+ const {
3
+ findAppUsers,
4
+ createMissingAppUsers,
5
+ buildUser,
6
+ wantsIndividual,
7
+ } = require('../app-user-helpers');
8
+ const { getLogger } = require('../../logs');
9
+
10
+ const log = getLogger('frigg.user.x_frigg_headers');
11
+
12
+ const NOT_A_MEMBER_MESSAGE =
13
+ 'Not a member: the user identified by x-frigg-appUserId is not a member of the ' +
14
+ 'organization identified by x-frigg-appOrgId, and strict membership does not ' +
15
+ 'allow these headers to add them.';
3
16
 
4
17
  /**
5
18
  * Use case for retrieving or creating a user from x-frigg header identifiers.
6
19
  * Supports backend-to-backend API communication using application user IDs.
7
20
  *
21
+ * `x-frigg-appOrgId` names the request's active organization (ADR-056 §3.6).
22
+ * A person the organization does not know yet is added to it as a member; the
23
+ * person is never moved out of another organization, and
24
+ * `IndividualUser.organizationId` is set only on a first link.
25
+ *
26
+ * With `user.strictMembership: true` the headers cannot make anyone a member of
27
+ * an organization that already existed: a person who is not already a member
28
+ * (a brand-new `appUserId` included) is refused with 400. The one thing strict
29
+ * mode still allows is naming an organization this request creates, so a first
30
+ * login can bootstrap its own organization. Apps that run strict add people to
31
+ * existing organizations themselves, through the membership repository.
32
+ *
33
+ * `strictUserValidation` is a deprecated alias for `strictMembership`; its
34
+ * meaning changed (it used to reject a mismatched individual/organization pair).
35
+ *
8
36
  * @class GetUserFromXFriggHeaders
9
37
  */
10
38
  class GetUserFromXFriggHeaders {
@@ -12,11 +40,22 @@ class GetUserFromXFriggHeaders {
12
40
  * Creates a new GetUserFromXFriggHeaders instance.
13
41
  * @param {Object} params - Configuration parameters.
14
42
  * @param {import('../repositories/user-repository-interface').UserRepositoryInterface} params.userRepository - Repository for user data operations.
43
+ * @param {import('./ensure-organization-membership').EnsureOrganizationMembership} params.ensureOrganizationMembership
15
44
  * @param {Object} params.userConfig - The user config in the app definition.
16
45
  */
17
- constructor({ userRepository, userConfig }) {
46
+ constructor({ userRepository, ensureOrganizationMembership, userConfig }) {
18
47
  this.userRepository = userRepository;
48
+ this.ensureOrganizationMembership = ensureOrganizationMembership;
19
49
  this.userConfig = userConfig;
50
+
51
+ const { strictMembership, strictUserValidation } = userConfig ?? {};
52
+ if (strictUserValidation !== undefined && strictMembership === undefined) {
53
+ log.warn(
54
+ 'user.strictUserValidation is deprecated and now means strictMembership; rename it',
55
+ { eventName: `${log.name}.strict_user_validation_deprecated` }
56
+ );
57
+ }
58
+ this.strict = Boolean(strictMembership ?? strictUserValidation);
20
59
  }
21
60
 
22
61
  /**
@@ -25,7 +64,7 @@ class GetUserFromXFriggHeaders {
25
64
  * @param {string} [appUserId] - The app user ID from x-frigg-appUserId header.
26
65
  * @param {string} [appOrgId] - The app organization ID from x-frigg-appOrgId header.
27
66
  * @returns {Promise<import('../user').User>} The authenticated user object.
28
- * @throws {Boom} 400 Bad Request if neither ID is provided or if both IDs are provided but belong to different users.
67
+ * @throws {Boom} 400 Bad Request if neither ID is provided or, in strict mode, if the person is not already a member of the existing organization named.
29
68
  */
30
69
  async execute(appUserId, appOrgId) {
31
70
  // At least one header must be provided
@@ -36,96 +75,60 @@ class GetUserFromXFriggHeaders {
36
75
  }
37
76
 
38
77
  // Find users by both IDs if both are provided
39
- let individualUserData = null;
40
- let organizationUserData = null;
41
-
42
- if (appUserId && this.userConfig.individualUserRequired !== false) {
43
- individualUserData =
44
- await this.userRepository.findIndividualUserByAppUserId(
45
- appUserId
46
- );
47
- }
78
+ let { individual: individualUserData, organization: organizationUserData } =
79
+ await findAppUsers(this.userRepository, this.userConfig, {
80
+ appUserId,
81
+ appOrgId,
82
+ });
48
83
 
49
- if (appOrgId && this.userConfig.organizationUserRequired) {
50
- organizationUserData =
51
- await this.userRepository.findOrganizationUserByAppOrgId(
52
- appOrgId
53
- );
54
- }
84
+ // Strict mode refuses to make anyone a member of an organization that
85
+ // existed before this request. Only an organization created below is
86
+ // exempt, since it has no members to disagree with.
87
+ const refuseNewMembers = this.strict && Boolean(organizationUserData);
55
88
 
56
- // VALIDATION/AUTO-LINKING: If both IDs provided and both users exist, handle mismatch
89
+ // A person who does not exist yet cannot already be a member, so refuse
90
+ // now, before anything is persisted: refusing after creating them would
91
+ // leave an orphan individual behind on every refused request.
57
92
  if (
93
+ refuseNewMembers &&
58
94
  appUserId &&
59
- appOrgId &&
60
- individualUserData &&
61
- organizationUserData
95
+ wantsIndividual(this.userConfig) &&
96
+ !individualUserData
62
97
  ) {
63
- // Check if individual user is linked to the org user
64
- const individualOrgId =
65
- individualUserData.organizationUser?.toString();
66
- const expectedOrgId = organizationUserData.id?.toString();
67
-
68
- if (individualOrgId !== expectedOrgId) {
69
- // Default behavior: Auto-link disconnected users
70
- // Opt-in strict mode: Throw error on mismatch
71
- if (this.userConfig.strictUserValidation) {
72
- throw Boom.badRequest(
73
- 'User ID mismatch: x-frigg-appUserId and x-frigg-appOrgId refer to different users. ' +
74
- 'Provide only one identifier or ensure they belong to the same user.'
75
- );
76
- }
77
-
78
- // Auto-link the users
79
- individualUserData = await this.userRepository.linkIndividualToOrganization(
80
- individualUserData.id,
81
- organizationUserData.id
82
- );
83
- }
98
+ throw Boom.badRequest(NOT_A_MEMBER_MESSAGE);
84
99
  }
85
100
 
86
101
  // Auto-create users independently if they don't exist and are required
87
- if (
88
- !individualUserData &&
89
- appUserId &&
90
- this.userConfig.individualUserRequired !== false
91
- ) {
92
- individualUserData =
93
- await this.userRepository.createIndividualUser({
94
- appUserId,
95
- username: `app-user-${appUserId}`,
96
- email: `${appUserId}@app.local`,
97
- });
98
- }
99
-
100
- if (
101
- !organizationUserData &&
102
- appOrgId &&
103
- this.userConfig.organizationUserRequired
104
- ) {
105
- organizationUserData =
106
- await this.userRepository.createOrganizationUser({
107
- appOrgId,
108
- });
109
-
110
- // Link individual user to newly created org user if individual exists
111
- if (individualUserData && organizationUserData) {
112
- individualUserData = await this.userRepository.linkIndividualToOrganization(
113
- individualUserData.id,
114
- organizationUserData.id
115
- );
102
+ const created = await createMissingAppUsers(
103
+ this.userRepository,
104
+ this.userConfig,
105
+ {
106
+ appUserId,
107
+ appOrgId,
108
+ individual: individualUserData,
109
+ organization: organizationUserData,
116
110
  }
111
+ );
112
+ individualUserData = created.individual;
113
+ organizationUserData = created.organization;
114
+
115
+ // The organization named by the header is the active one: join it
116
+ // rather than re-linking the person's single organizationId.
117
+ const ensured = await this.ensureOrganizationMembership.execute({
118
+ individual: individualUserData,
119
+ organization: organizationUserData,
120
+ requireExisting: refuseNewMembers,
121
+ });
122
+ if (refuseNewMembers && individualUserData && !ensured.membership) {
123
+ throw Boom.badRequest(NOT_A_MEMBER_MESSAGE);
117
124
  }
125
+ individualUserData = ensured.individual;
118
126
 
119
- const user = new User(
127
+ return buildUser(
128
+ this.userConfig,
120
129
  individualUserData,
121
- organizationUserData,
122
- this.userConfig.usePassword,
123
- this.userConfig.primary,
124
- this.userConfig.individualUserRequired,
125
- this.userConfig.organizationUserRequired
130
+ organizationUserData
126
131
  );
127
-
128
- return user;
129
132
  }
130
133
  }
131
134
 
package/user/user.js CHANGED
@@ -1,5 +1,20 @@
1
1
  const bcrypt = require('bcryptjs');
2
2
 
3
+ /**
4
+ * How the request that produced a `User` proved who it is. Set by
5
+ * AuthenticateUser, never inferred from a missing value. Organization roles
6
+ * (ADR-056 §3, §3.6) depend on it: a shared-secret caller is the app's own
7
+ * backend and is trusted to manage; a Frigg bearer token keeps its pre-roles
8
+ * behaviour unless the app opts in (`user.orgAdminGateBearerTokens`); an
9
+ * adopter token has the role it carries, else the stored membership role,
10
+ * else `MEMBER`.
11
+ */
12
+ const AUTH_SOURCES = Object.freeze({
13
+ SHARED_SECRET: 'shared-secret',
14
+ ADOPTER_JWT: 'adopter-jwt',
15
+ BEARER_TOKEN: 'bearer-token',
16
+ });
17
+
3
18
  /**
4
19
  * Represents a user in the system. The User class is a domain entity,
5
20
  * @class User
@@ -18,6 +33,14 @@ class User {
18
33
  this.individualUser = individualUser;
19
34
  this.organizationUser = organizationUser;
20
35
  this.usePassword = usePassword;
36
+ // Organization role from an adopter token claim (ADR-056 §2), per
37
+ // request. When present it wins over the stored membership role.
38
+ this.orgRole = null;
39
+ // The role stored on the person's membership of the active organization
40
+ // (OrganizationMembership.orgRole); used when the token carries none.
41
+ this.membershipRole = null;
42
+ // How this request authenticated (one of AUTH_SOURCES); null until AuthenticateUser says.
43
+ this.authSource = null;
21
44
 
22
45
  this.config = {
23
46
  primary,
@@ -26,6 +49,17 @@ class User {
26
49
  };
27
50
  }
28
51
 
52
+ /**
53
+ * The organization this request acts in (ADR-056 §3.6): the one the token or
54
+ * `x-frigg-appOrgId` named, not the person's legacy `organizationId`
55
+ * pointer. Null when the request has no organization.
56
+ * @returns {string|null}
57
+ */
58
+ getActiveOrganizationId() {
59
+ const id = this.organizationUser?.id;
60
+ return id === undefined || id === null || id === '' ? null : String(id);
61
+ }
62
+
29
63
  getPrimaryUser() {
30
64
  if (this.config.primary === 'organization') {
31
65
  return this.organizationUser;
@@ -33,6 +67,11 @@ class User {
33
67
  return this.individualUser;
34
68
  }
35
69
 
70
+ /**
71
+ * The id of the primary user. With `primary: 'organization'` this is the
72
+ * active organization (the one the request named), never the organization
73
+ * the person was first linked to.
74
+ */
36
75
  getId() {
37
76
  return this.getPrimaryUser()?.id;
38
77
  }
@@ -65,6 +104,30 @@ class User {
65
104
  return this.config.individualUserRequired;
66
105
  }
67
106
 
107
+ getAuthSource() {
108
+ return this.authSource;
109
+ }
110
+
111
+ setAuthSource(authSource) {
112
+ this.authSource = authSource ?? null;
113
+ }
114
+
115
+ getOrgRole() {
116
+ return this.orgRole;
117
+ }
118
+
119
+ setOrgRole(orgRole) {
120
+ this.orgRole = orgRole ?? null;
121
+ }
122
+
123
+ getMembershipRole() {
124
+ return this.membershipRole;
125
+ }
126
+
127
+ setMembershipRole(membershipRole) {
128
+ this.membershipRole = membershipRole ?? null;
129
+ }
130
+
68
131
  getIndividualUser() {
69
132
  return this.individualUser;
70
133
  }
@@ -122,4 +185,4 @@ class User {
122
185
  }
123
186
  }
124
187
 
125
- module.exports = { User };
188
+ module.exports = { User, AUTH_SOURCES };
@@ -1,14 +0,0 @@
1
- const { BaseError } = require('./base-error');
2
-
3
- class MappingAlreadyExistsError extends BaseError {
4
- constructor(integrationId, sourceId, ...errorOptions) {
5
- super(
6
- `Mapping already exists for integration ${integrationId} and sourceId ${sourceId}`,
7
- ...errorOptions
8
- );
9
- this.integrationId = integrationId;
10
- this.sourceId = sourceId;
11
- }
12
- }
13
-
14
- module.exports = { MappingAlreadyExistsError };
@@ -1,25 +0,0 @@
1
- /**
2
- * The `{integration}Triggers` functions (ADR-055 §2-3): one per integration that declares triggers. Devtools gives
3
- * each one schedule per distinct tick (`{ tick: '5m', time }`) and one per `at` trigger (`{ at, time }`); this only
4
- * hands the event to the tick use case.
5
- */
6
- const { createHandler } = require('@friggframework/core');
7
- const { loadAppDefinition } = require('../app-definition-loader');
8
- const { hasTriggers } = require('../../integrations/triggers');
9
- const { runTriggerTick } = require('../../integrations/use-cases/run-trigger-tick');
10
-
11
- const handlers = {};
12
- const { integrations: integrationClasses } = loadAppDefinition();
13
-
14
- for (const IntegrationClass of integrationClasses) {
15
- if (!hasTriggers(IntegrationClass)) continue;
16
- handlers[IntegrationClass.Definition.name] = {
17
- tick: createHandler({
18
- eventName: `Trigger tick for ${IntegrationClass.Definition.name}`,
19
- isUserFacingResponse: false,
20
- method: async (event, context) => runTriggerTick(IntegrationClass, event || {}, context),
21
- }),
22
- };
23
- }
24
-
25
- module.exports = { handlers };
@@ -1,204 +0,0 @@
1
- /**
2
- * Recurrence: how often something repeats, in a form no host owns.
3
- *
4
- * { every: '15m' } every 15 minutes ('30s' is refused: ticks are whole minutes)
5
- * { cron: '0 9 * * 1-5', timezone: 'America/New_York' } standard five-field cron (minute hour dom month dow)
6
- *
7
- * Recurring triggers (ADR-055, integrations/triggers.js) use it for the timing an installation may choose and for
8
- * the floor a developer sets on that choice. Nothing here creates a host schedule: the tick asks `lastFiringIn`
9
- * whether a cron fired since the previous tick, so a per-installation calendar needs no schedule of its own.
10
- *
11
- * Pure; no I/O.
12
- */
13
-
14
- const EVERY = /^(\d+)\s*(m|h|d)$/;
15
- const UNIT_MINUTES = { m: 1, h: 60, d: 1440 };
16
-
17
- /** '15m' -> 15, '2h' -> 120, '1d' -> 1440. Anything else -> null. */
18
- function parseEvery(every) {
19
- const m = EVERY.exec(String(every ?? '').trim());
20
- if (!m) return null;
21
- const n = Number(m[1]) * UNIT_MINUTES[m[2]];
22
- return n > 0 ? n : null;
23
- }
24
-
25
- const MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
26
- const DAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
27
- const FIELDS = [
28
- { name: 'minute', min: 0, max: 59 },
29
- { name: 'hour', min: 0, max: 23 },
30
- { name: 'day of month', min: 1, max: 31 },
31
- { name: 'month', min: 1, max: 12, names: MONTHS, base: 1 },
32
- { name: 'day of week', min: 0, max: 7, names: DAYS, base: 0 }, // 0 and 7 are both Sunday
33
- ];
34
-
35
- function atom(token, field) {
36
- const t = token.toUpperCase();
37
- if (field.names) {
38
- const i = field.names.indexOf(t);
39
- if (i >= 0) return i + field.base;
40
- }
41
- if (!/^\d+$/.test(t)) return null;
42
- const n = Number(t);
43
- return n >= field.min && n <= field.max ? n : null;
44
- }
45
-
46
- /** One cron field -> the sorted set of values it matches, or an error string. */
47
- function parseField(text, field) {
48
- const out = new Set();
49
- for (const part of text.split(',')) {
50
- const [range, stepText] = part.split('/');
51
- if (part.split('/').length > 2) return `${field.name}: "${part}" has more than one step`;
52
- const step = stepText === undefined ? 1 : Number(stepText);
53
- if (!Number.isInteger(step) || step < 1) return `${field.name}: step "${stepText}" is not a positive whole number`;
54
- let lo, hi;
55
- if (range === '*') { lo = field.min; hi = field.name === 'day of week' ? 6 : field.max; }
56
- else if (range.includes('-')) {
57
- const [a, b] = range.split('-');
58
- lo = atom(a, field); hi = atom(b, field);
59
- if (lo === null || hi === null) return `${field.name}: "${range}" is out of range`;
60
- if (lo > hi) return `${field.name}: "${range}" runs backwards`;
61
- } else {
62
- lo = atom(range, field);
63
- if (lo === null) return `${field.name}: "${range}" is out of range`;
64
- hi = stepText === undefined ? lo : (field.name === 'day of week' ? 6 : field.max);
65
- }
66
- for (let v = lo; v <= hi; v += step) out.add(field.name === 'day of week' && v === 7 ? 0 : v);
67
- }
68
- return [...out].sort((a, b) => a - b);
69
- }
70
-
71
- /**
72
- * Parse a five-field cron. Returns { fields: [Set x5], restricted: { dom, dow } } or { error }.
73
- * `restricted` records whether day-of-month / day-of-week were given (not `*`), which decides how they combine.
74
- */
75
- function parseCron(cron) {
76
- const parts = String(cron ?? '').trim().split(/\s+/);
77
- if (parts.length !== 5 || parts[0] === '') return { error: 'A cron expression has five fields: minute hour day-of-month month day-of-week' };
78
- const fields = [];
79
- for (let i = 0; i < 5; i += 1) {
80
- const v = parseField(parts[i], FIELDS[i]);
81
- if (typeof v === 'string') return { error: v };
82
- fields.push(new Set(v));
83
- }
84
- return { fields, parts, restricted: { dom: parts[2] !== '*', dow: parts[4] !== '*' } };
85
- }
86
-
87
- /** Does a parsed cron fire at this (UTC-free, wall-clock) minute? Standard cron: dom and dow OR when both are set. */
88
- function matches(parsed, d) {
89
- const [mi, h, dom, mon, dow] = parsed.fields;
90
- if (!mi.has(d.getUTCMinutes()) || !h.has(d.getUTCHours()) || !mon.has(d.getUTCMonth() + 1)) return false;
91
- const domHit = dom.has(d.getUTCDate()), dowHit = dow.has(d.getUTCDay());
92
- if (parsed.restricted.dom && parsed.restricted.dow) return domHit || dowHit;
93
- return domHit && dowHit;
94
- }
95
-
96
- /**
97
- * The shortest gap, in minutes, between two firings. For `every` it is the interval; for cron it is measured over
98
- * fifteen months of wall-clock minutes (long enough to see every month and weekday combination), so a floor such as
99
- * "no more often than every 15 minutes" is checked against what the expression really does, not its spelling.
100
- * Returns Infinity for an expression that fires at most once in that window, null when invalid.
101
- */
102
- function minGapMinutes(recurrence) {
103
- if (recurrence?.every !== undefined) return parseEvery(recurrence.every);
104
- const parsed = parseCron(recurrence?.cron);
105
- return parsed.error ? null : scan(parsed).best;
106
- }
107
-
108
- /** Walk fifteen months of firings: how many there are and the shortest gap between two. */
109
- function scan(parsed) {
110
- const [mi, h] = parsed.fields;
111
- const minutes = [...mi], hours = [...h];
112
- let prev = null, best = Infinity, count = 0;
113
- const start = Date.UTC(2027, 0, 1);
114
- for (let day = 0; day < 457 && best > 1; day += 1) { // fifteen months: every month and weekday pairing
115
- const midnight = start + day * 86400000;
116
- if (!matches(parsed, new Date(midnight + hours[0] * 3600000 + minutes[0] * 60000))) continue;
117
- for (const hr of hours) {
118
- for (const mn of minutes) {
119
- const t = day * 1440 + hr * 60 + mn;
120
- if (prev !== null && t - prev < best) best = t - prev;
121
- prev = t;
122
- count += 1;
123
- }
124
- }
125
- }
126
- return { best, count };
127
- }
128
-
129
- /** Is `tz` an IANA time zone this runtime knows? */
130
- function isTimeZone(tz) {
131
- try { new Intl.DateTimeFormat('en-US', { timeZone: tz }); return true; } catch { return false; }
132
- }
133
-
134
- /**
135
- * Validate a recurrence. `min` is an optional floor ('15m'): the expression must never fire more often.
136
- * @returns {string[]} problems, empty when valid
137
- */
138
- function validateRecurrence(recurrence, { min } = {}) {
139
- const problems = [];
140
- if (!recurrence || typeof recurrence !== 'object') return ['Give a schedule as { every } or { cron, timezone? }'];
141
- const hasEvery = recurrence.every !== undefined, hasCron = recurrence.cron !== undefined;
142
- if (hasEvery === hasCron) return ['Give exactly one of every or cron'];
143
- if (hasEvery && parseEvery(recurrence.every) === null) problems.push(`every "${recurrence.every}" is not a whole number of minutes, hours or days (15m, 2h, 1d)`);
144
- if (hasCron) {
145
- const parsed = parseCron(recurrence.cron);
146
- if (parsed.error) problems.push(parsed.error);
147
- // EventBridge (and Quartz) cannot express "this day of month OR this weekday"; refuse it everywhere, so a
148
- // schedule that validates here runs on every host.
149
- else if (parsed.restricted.dom && parsed.restricted.dow) problems.push('Restrict day of month or day of week, not both');
150
- else if (scan(parsed).count === 0) problems.push(`"${recurrence.cron}" never fires`);
151
- }
152
- if (recurrence.timezone !== undefined && (hasEvery || !isTimeZone(recurrence.timezone))) {
153
- problems.push(hasEvery ? 'timezone applies to cron schedules only' : `Unknown time zone "${recurrence.timezone}"`);
154
- }
155
- if (!problems.length && min !== undefined) {
156
- const floor = parseEvery(min);
157
- const gap = minGapMinutes(recurrence);
158
- if (floor === null) problems.push(`minimum interval "${min}" is not a duration (15m, 2h, 1d)`);
159
- else if (gap !== null && gap < floor) problems.push(`Runs every ${gap} minute${gap === 1 ? '' : 's'} at its most frequent; the minimum is ${min}`);
160
- }
161
- return problems;
162
- }
163
-
164
- /** The comparable identity of a recurrence (what decides whether a stored schedule must be updated). */
165
- function recurrenceKey(r) {
166
- if (!r) return '';
167
- return r.every !== undefined ? `every:${parseEvery(r.every)}` : `cron:${String(r.cron).trim().split(/\s+/).join(' ')}@${r.timezone || 'UTC'}`;
168
- }
169
-
170
- const wallClockFormats = new Map();
171
- /**
172
- * The wall-clock time of an instant in a time zone, as a Date whose UTC fields hold that wall clock (what `matches`
173
- * reads). Seconds are dropped.
174
- */
175
- function wallClock(ms, timezone = 'UTC') {
176
- if (timezone === 'UTC') return new Date(Math.floor(ms / 60000) * 60000);
177
- let format = wallClockFormats.get(timezone);
178
- if (!format) {
179
- format = new Intl.DateTimeFormat('en-US', { timeZone: timezone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' });
180
- wallClockFormats.set(timezone, format);
181
- }
182
- const p = Object.fromEntries(format.formatToParts(new Date(ms)).map((x) => [x.type, x.value]));
183
- return new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day), Number(p.hour) % 24, Number(p.minute)));
184
- }
185
-
186
- /**
187
- * The latest whole minute in (fromMs, toMs] at which a cron recurrence fires in its time zone, as epoch ms, or null.
188
- *
189
- * This is how one shared tick serves a calendar each installation chose: the tick asks whether the cron fired since
190
- * the previous tick. It is stateless, so a tick that runs twice for the same slot gives the same answer (and the same
191
- * `scheduledFor`, which is what a run dedupes on). Real instants are walked, so a wall-clock time a DST change skips
192
- * does not fire that day, and one it repeats fires twice.
193
- */
194
- function lastFiringIn(recurrence, fromMs, toMs) {
195
- const parsed = parseCron(recurrence?.cron);
196
- if (parsed.error) return null;
197
- const tz = recurrence.timezone || 'UTC';
198
- for (let t = Math.floor(toMs / 60000) * 60000; t > fromMs; t -= 60000) {
199
- if (matches(parsed, wallClock(t, tz))) return t;
200
- }
201
- return null;
202
- }
203
-
204
- module.exports = { parseEvery, parseCron, minGapMinutes, validateRecurrence, recurrenceKey, isTimeZone, matches, wallClock, lastFiringIn };