@friggframework/core 2.0.0--canary.680.daae24e.0 → 2.0.0--canary.686.e94de4d.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 (156) hide show
  1. package/CHANGELOG.md +0 -11
  2. package/CLAUDE.md +28 -0
  3. package/README.md +105 -0
  4. package/application/commands/integration-commands.js +2 -2
  5. package/application/commands/scheduler-commands.js +11 -7
  6. package/application/commands/user-commands.js +17 -5
  7. package/core/Worker.js +31 -7
  8. package/core/create-handler.js +9 -0
  9. package/credential/use-cases/credential-operations-for-user.js +110 -25
  10. package/credential/use-cases/reauthorize-credential-for-user.js +15 -8
  11. package/database/config.js +48 -24
  12. package/database/documentdb-utils.js +6 -1
  13. package/database/encryption/README.md +0 -2
  14. package/database/encryption/encryption-config.js +10 -31
  15. package/database/encryption/encryption-schema-registry.js +99 -47
  16. package/database/encryption/field-encryption-service.js +5 -69
  17. package/database/organization-where.js +18 -0
  18. package/database/prisma.js +4 -2
  19. package/database/unique-violation.js +25 -0
  20. package/extensions/bootstrap-runner.js +43 -0
  21. package/extensions/extension-loader.js +187 -0
  22. package/extensions/index.js +41 -0
  23. package/extensions/initialize-app.js +123 -0
  24. package/extensions/route-mounter.js +103 -0
  25. package/extensions/schema-composer.js +188 -0
  26. package/generated/prisma-mongodb/edge.js +27 -4
  27. package/generated/prisma-mongodb/index-browser.js +24 -1
  28. package/generated/prisma-mongodb/index.d.ts +3227 -47
  29. package/generated/prisma-mongodb/index.js +27 -4
  30. package/generated/prisma-mongodb/package.json +1 -1
  31. package/generated/prisma-mongodb/schema.prisma +65 -0
  32. package/generated/prisma-mongodb/wasm.js +27 -4
  33. package/generated/prisma-postgresql/edge.js +27 -4
  34. package/generated/prisma-postgresql/index-browser.js +24 -1
  35. package/generated/prisma-postgresql/index.d.ts +3519 -67
  36. package/generated/prisma-postgresql/index.js +27 -4
  37. package/generated/prisma-postgresql/package.json +1 -1
  38. package/generated/prisma-postgresql/schema.prisma +61 -0
  39. package/generated/prisma-postgresql/wasm.js +27 -4
  40. package/handlers/app-definition-loader.js +103 -12
  41. package/handlers/routers/auth.js +40 -12
  42. package/handlers/routers/health.js +4 -2
  43. package/handlers/routers/integration-defined-routers.js +144 -92
  44. package/handlers/routers/integration-webhook-routers.js +102 -64
  45. package/index.js +63 -1
  46. package/infrastructure/scheduler/index.js +19 -6
  47. package/infrastructure/scheduler/netlify-scheduler-adapter.js +216 -0
  48. package/infrastructure/scheduler/scheduled-job-repository.js +118 -0
  49. package/infrastructure/scheduler/scheduler-service-factory.js +55 -7
  50. package/integrations/index.js +5 -0
  51. package/integrations/integration-router.js +115 -73
  52. package/integrations/repositories/integration-not-found.js +14 -0
  53. package/integrations/repositories/integration-repository-documentdb.js +35 -3
  54. package/integrations/repositories/integration-repository-interface.js +17 -1
  55. package/integrations/repositories/integration-repository-mongo.js +59 -76
  56. package/integrations/repositories/integration-repository-postgres.js +62 -76
  57. package/integrations/schedule-config.js +80 -0
  58. package/integrations/tests/doubles/test-integration-repository.js +12 -1
  59. package/integrations/use-cases/create-integration.js +55 -20
  60. package/integrations/use-cases/dispatch-ongoing-syncs.js +100 -0
  61. package/integrations/use-cases/get-integrations-for-user.js +80 -40
  62. package/integrations/use-cases/index.js +7 -1
  63. package/integrations/use-cases/integration-operations-for-user.js +55 -24
  64. package/integrations/use-cases/resolve-integration-ownership.js +177 -0
  65. package/integrations/utils/map-integration-dto.js +44 -1
  66. package/management-api/management-api-config.js +71 -2
  67. package/management-api/meta-router.js +21 -2
  68. package/management-api/openapi/components.js +40 -0
  69. package/management-api/openapi/v2-operations.js +16 -4
  70. package/management-api/route-registry.js +123 -6
  71. package/management-api/v2/dependencies.js +40 -15
  72. package/management-api/v2/dto.js +20 -0
  73. package/management-api/v2/handlers/authorization.js +1 -0
  74. package/management-api/v2/handlers/credentials.js +6 -2
  75. package/management-api/v2/handlers/entities.js +10 -7
  76. package/management-api/v2/handlers/integrations.js +6 -3
  77. package/management-api/v2/request.js +32 -1
  78. package/modules/entity-scope.js +15 -0
  79. package/modules/index.js +8 -0
  80. package/modules/module-factory.js +12 -0
  81. package/modules/module.js +53 -2
  82. package/modules/repositories/entity-not-found.js +18 -0
  83. package/modules/repositories/module-repository-documentdb.js +51 -6
  84. package/modules/repositories/module-repository-interface.js +19 -2
  85. package/modules/repositories/module-repository-mongo.js +67 -74
  86. package/modules/repositories/module-repository-postgres.js +66 -74
  87. package/modules/repositories/module-repository.js +2 -1
  88. package/modules/scope-config.js +192 -0
  89. package/modules/scope-policy.js +112 -0
  90. package/modules/scope-resolution.js +288 -0
  91. package/modules/scope-visibility.js +247 -0
  92. package/modules/tests/doubles/ownership-matching.js +18 -0
  93. package/modules/use-cases/authorize-entity-for-user.js +61 -0
  94. package/modules/use-cases/create-entity-from-credential.js +113 -0
  95. package/modules/use-cases/entity-operations-for-user.js +50 -13
  96. package/modules/use-cases/entity-types.js +31 -7
  97. package/modules/use-cases/execute-entity-proxy-request.js +50 -3
  98. package/modules/use-cases/get-authorization-requirements.js +2 -2
  99. package/modules/use-cases/get-entities-for-user.js +26 -13
  100. package/modules/use-cases/get-entity-module-for-user.js +34 -7
  101. package/modules/use-cases/get-entity-options-by-id.js +10 -4
  102. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  103. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  104. package/modules/use-cases/get-module.js +10 -4
  105. package/modules/use-cases/manage-access.js +21 -0
  106. package/modules/use-cases/multi-step-authorization.js +40 -13
  107. package/modules/use-cases/process-authorization-callback.js +53 -19
  108. package/modules/use-cases/refresh-entity-options.js +10 -4
  109. package/modules/use-cases/test-module-auth.js +10 -4
  110. package/package.json +6 -5
  111. package/prisma-mongodb/schema.prisma +65 -0
  112. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +26 -0
  113. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +25 -0
  114. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +28 -0
  115. package/prisma-postgresql/schema.prisma +61 -0
  116. package/providers/index.js +23 -0
  117. package/providers/resolve-provider.js +93 -0
  118. package/providers/runtime-detection.js +124 -0
  119. package/queues/index.js +25 -0
  120. package/queues/providers/index.js +11 -0
  121. package/queues/providers/netlify-background-provider.js +150 -0
  122. package/queues/providers/qstash-queue-provider.js +219 -0
  123. package/queues/providers/sqs-queue-provider.js +70 -0
  124. package/queues/queue-client-interface.js +55 -0
  125. package/queues/queue-message-auth.js +193 -0
  126. package/queues/queue-provider-factory.js +101 -0
  127. package/queues/queue-provider.js +65 -0
  128. package/queues/sqs-queue-client.js +81 -0
  129. package/types/index.d.ts +1 -0
  130. package/types/modules/index.d.ts +139 -0
  131. package/types/user/index.d.ts +134 -0
  132. package/user/adopter-jwt-config.js +177 -0
  133. package/user/adopter-jwt-errors.js +59 -0
  134. package/user/adopter-token-verifier.js +122 -0
  135. package/user/app-user-helpers.js +97 -0
  136. package/user/create-user-authentication.js +64 -0
  137. package/user/membership.js +51 -0
  138. package/user/repositories/organization-membership-record.js +19 -0
  139. package/user/repositories/organization-membership-repository-documentdb.js +106 -0
  140. package/user/repositories/organization-membership-repository-factory.js +42 -0
  141. package/user/repositories/organization-membership-repository-interface.js +57 -0
  142. package/user/repositories/organization-membership-repository-mongo.js +13 -0
  143. package/user/repositories/organization-membership-repository-postgres.js +29 -0
  144. package/user/repositories/organization-membership-repository-prisma.js +81 -0
  145. package/user/repositories/user-repository-documentdb.js +27 -2
  146. package/user/repositories/user-repository-interface.js +18 -0
  147. package/user/repositories/user-repository-mongo.js +24 -0
  148. package/user/repositories/user-repository-postgres.js +18 -0
  149. package/user/tests/doubles/adopter-jwt-fixtures.js +220 -0
  150. package/user/use-cases/authenticate-user.js +7 -1
  151. package/user/use-cases/ensure-organization-membership.js +92 -0
  152. package/user/use-cases/find-individual-users-by-organization.js +54 -0
  153. package/user/use-cases/get-user-from-adopter-jwt.js +95 -124
  154. package/user/use-cases/get-user-from-x-frigg-headers.js +83 -80
  155. package/user/user.js +64 -1
  156. package/database/encryption/test-support/fake-ciphertext.js +0 -15
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Which stored rows a caller may see and use (ADR-056 §3.4, §3.6).
3
+ *
4
+ * No I/O. One clause list (`ctx.clauses`) is what a repository is asked for and
5
+ * what `describeRecord` checks every returned row against, so a list and an
6
+ * access check cannot drift apart. The clauses are built once per request, when
7
+ * the access context is.
8
+ */
9
+
10
+ const { isPresent, idString, sameId } = require('../user/membership');
11
+ const { AUTH_SOURCES } = require('../user/user');
12
+ const { SCOPES, ACCESS, DEFAULT_ORG_ADMIN_ROLES } = require('./scope-resolution');
13
+
14
+ /**
15
+ * One owner/organization pair a repository ORs into a single query.
16
+ * `userId` is the owner's user id, and for an organization-owned row that is
17
+ * the ORGANIZATION user's id, not a person's. `organizationId: null` means "has
18
+ * no organization" (unset or null); otherwise the id of the organization.
19
+ *
20
+ * @typedef {Object} OwnershipClause
21
+ * @property {string} userId
22
+ * @property {(string|null)} organizationId
23
+ */
24
+
25
+ /**
26
+ * Whether the caller's own rows with no organization belong to the context this
27
+ * request acts in: always when it acts in no organization (today's behaviour),
28
+ * always for an entity under `individualAcross: 'all'`, and otherwise only in
29
+ * the person's legacy organization.
30
+ */
31
+ function unscopedRowsBelongHere(base, kind) {
32
+ return (
33
+ !base.activeOrgId ||
34
+ (kind === 'entity' && base.individualAcross === 'all') ||
35
+ sameId(base.legacyOrgId, base.activeOrgId)
36
+ );
37
+ }
38
+
39
+ /**
40
+ * What a caller may see, as owner/organization pairs:
41
+ *
42
+ * - the active organization's own rows (owner = the organization), whether
43
+ * they carry its id or, written before scoping, none;
44
+ * - the caller's rows in the active organization;
45
+ * - the caller's rows with no organization, when `unscopedRowsBelongHere`.
46
+ *
47
+ * `kind` is 'entity' or 'integration'; only entities may be
48
+ * organization-independent under 'all' (an integration always belongs to the
49
+ * organization it was created in).
50
+ *
51
+ * @returns {OwnershipClause[]}
52
+ */
53
+ function buildClauses(base, kind) {
54
+ const clauses = [];
55
+ if (base.activeOrgId) {
56
+ clauses.push({ userId: base.activeOrgId, organizationId: base.activeOrgId });
57
+ clauses.push({ userId: base.activeOrgId, organizationId: null });
58
+ }
59
+ if (base.callerId) {
60
+ if (base.activeOrgId) {
61
+ clauses.push({ userId: base.callerId, organizationId: base.activeOrgId });
62
+ }
63
+ if (unscopedRowsBelongHere(base, kind)) {
64
+ clauses.push({ userId: base.callerId, organizationId: null });
65
+ }
66
+ }
67
+ return clauses;
68
+ }
69
+
70
+ /**
71
+ * Whether the caller may manage organization-level things (create, change,
72
+ * delete), ADR-056 §3.6:
73
+ *
74
+ * - A shared-secret caller is the app's own backend and may.
75
+ * - A Frigg bearer token (`/user/login`) predates organization roles and
76
+ * carries none. It keeps its pre-roles behaviour and may, unless the app
77
+ * sets `user.orgAdminGateBearerTokens: true`; then it is judged like any
78
+ * other caller below.
79
+ * - Otherwise the role is the one the token carries; when it carries none,
80
+ * the role stored on the caller's membership of the active organization;
81
+ * when there is none, `MEMBER`. A missing role never means admin. An
82
+ * unknown source (a `User` built outside AuthenticateUser) is judged this
83
+ * way too.
84
+ *
85
+ * @param {{authSource: (string|null), orgRole: (string|null), membershipRole: (string|null)}} who
86
+ * @param {string[]} adminRoles - `user.orgAdminRoles`, compared case-insensitively
87
+ * @param {{gateBearerTokens?: boolean}} [options]
88
+ */
89
+ function canManageOrganization(
90
+ { authSource, orgRole, membershipRole },
91
+ adminRoles = DEFAULT_ORG_ADMIN_ROLES,
92
+ { gateBearerTokens = false } = {}
93
+ ) {
94
+ if (authSource === AUTH_SOURCES.SHARED_SECRET) return true;
95
+ if (authSource === AUTH_SOURCES.BEARER_TOKEN && !gateBearerTokens) return true;
96
+ let role = 'MEMBER';
97
+ if (isPresent(orgRole)) role = orgRole;
98
+ else if (isPresent(membershipRole)) role = membershipRole;
99
+ role = String(role).toUpperCase();
100
+ return adminRoles.some((admin) => String(admin).toUpperCase() === role);
101
+ }
102
+
103
+ /**
104
+ * Who the caller is, for ownership and visibility: their individual user, the
105
+ * organization this request acts in, the legacy `organizationId` pointer,
106
+ * whether they may manage organization-level things, and the clauses that
107
+ * follow from them (computed once).
108
+ *
109
+ * @param {Object} user - the authenticated `User` (or a `{ getId }` double)
110
+ * @param {{individualAcross?: string, orgAdminRoles?: string[], gateBearerTokens?: boolean}} [options]
111
+ */
112
+ function accessContext(
113
+ user,
114
+ {
115
+ individualAcross = 'organization',
116
+ orgAdminRoles = DEFAULT_ORG_ADMIN_ROLES,
117
+ gateBearerTokens = false,
118
+ } = {}
119
+ ) {
120
+ const hasUserModel = typeof user?.getIndividualUser === 'function';
121
+ const individual = hasUserModel ? user.getIndividualUser() : null;
122
+ const base = {
123
+ callerId: hasUserModel ? idString(individual?.id) : idString(user?.getId?.()),
124
+ activeOrgId:
125
+ typeof user?.getActiveOrganizationId === 'function'
126
+ ? idString(user.getActiveOrganizationId())
127
+ : null,
128
+ legacyOrgId: idString(individual?.organizationId),
129
+ individualAcross,
130
+ };
131
+ const who = {
132
+ authSource:
133
+ typeof user?.getAuthSource === 'function' ? user.getAuthSource() : null,
134
+ orgRole: typeof user?.getOrgRole === 'function' ? user.getOrgRole() : null,
135
+ membershipRole:
136
+ typeof user?.getMembershipRole === 'function'
137
+ ? user.getMembershipRole()
138
+ : null,
139
+ };
140
+ return {
141
+ ...base,
142
+ canManageOrg: canManageOrganization(who, orgAdminRoles, {
143
+ gateBearerTokens,
144
+ }),
145
+ clauses: {
146
+ entity: buildClauses(base, 'entity'),
147
+ integration: buildClauses(base, 'integration'),
148
+ },
149
+ };
150
+ }
151
+
152
+ /** The clauses for `kind` ('entity' | 'integration'): what to ask the repository. */
153
+ const visibilityClauses = (ctx, kind) => ctx.clauses[kind];
154
+
155
+ const matchesClause = (record, clause) =>
156
+ sameId(record.userId, clause.userId) &&
157
+ (clause.organizationId === null
158
+ ? !isPresent(record.organizationId)
159
+ : sameId(record.organizationId, clause.organizationId));
160
+
161
+ /** The scope a stored row has for this caller, from its owner. */
162
+ function scopeOf(record, ctx) {
163
+ if (!isPresent(record?.userId)) return SCOPES.GLOBAL;
164
+ if (sameId(record.userId, ctx.activeOrgId)) return SCOPES.ORGANIZATION;
165
+ if (sameId(record.userId, ctx.callerId)) return SCOPES.INDIVIDUAL;
166
+ return null;
167
+ }
168
+
169
+ /** manage for the person's own; for the organization's, only an admin; use otherwise. */
170
+ const accessFor = (scope, ctx) => {
171
+ if (scope === SCOPES.INDIVIDUAL) return ACCESS.MANAGE;
172
+ if (scope === SCOPES.ORGANIZATION) {
173
+ return ctx.canManageOrg ? ACCESS.MANAGE : ACCESS.USE;
174
+ }
175
+ return ACCESS.USE;
176
+ };
177
+
178
+ /**
179
+ * Whether an access level lets the caller use a record: bind it, proxy through
180
+ * it (§3.4). `manage` includes `use`; `view` (metadata only) does not, and
181
+ * neither does anything unrecognised.
182
+ */
183
+ const grantsUse = (access) => access === ACCESS.USE || access === ACCESS.MANAGE;
184
+
185
+ /**
186
+ * What the caller may do with a record owned by `ownerId` that carries no
187
+ * organization of its own (a credential): manage the person's own, manage the
188
+ * active organization's only as an admin, nothing otherwise. Null when the
189
+ * record is not theirs.
190
+ */
191
+ function accessToOwner(ownerId, ctx) {
192
+ const scope = scopeOf({ userId: ownerId }, ctx);
193
+ if (scope !== SCOPES.INDIVIDUAL && scope !== SCOPES.ORGANIZATION) return null;
194
+ return accessFor(scope, ctx);
195
+ }
196
+
197
+ /**
198
+ * What a row is to this caller, or null when they may not see it.
199
+ * `{ scope, owner: {type, id}, organizationId, access }` (§3.4). A `global`
200
+ * row is never described: it is not the tenant's to see.
201
+ */
202
+ function describeRecord(record, ctx, kind) {
203
+ if (!record) return null;
204
+ const scope = scopeOf(record, ctx);
205
+ if (scope === null || scope === SCOPES.GLOBAL) return null;
206
+ if (!ctx.clauses[kind].some((clause) => matchesClause(record, clause))) {
207
+ return null;
208
+ }
209
+ return {
210
+ scope,
211
+ owner: { type: scope, id: idString(record.userId) },
212
+ organizationId:
213
+ scope === SCOPES.ORGANIZATION
214
+ ? idString(record.userId)
215
+ : idString(record.organizationId),
216
+ access: accessFor(scope, ctx),
217
+ };
218
+ }
219
+
220
+ /** `?owner=` values and the scope each one means. */
221
+ const LIST_OWNERS = Object.freeze({
222
+ me: SCOPES.INDIVIDUAL,
223
+ org: SCOPES.ORGANIZATION,
224
+ });
225
+
226
+ /** Whether a described row passes `?scope=` and `?owner=`. */
227
+ function matchesListFilters(description, { scope, owner } = {}) {
228
+ if (scope !== undefined && description.scope !== scope) return false;
229
+ if (owner !== undefined && description.owner.type !== LIST_OWNERS[owner]) {
230
+ return false;
231
+ }
232
+ return true;
233
+ }
234
+
235
+ module.exports = {
236
+ canManageOrganization,
237
+ accessToOwner,
238
+ accessContext,
239
+ unscopedRowsBelongHere,
240
+ visibilityClauses,
241
+ matchesClause,
242
+ scopeOf,
243
+ describeRecord,
244
+ grantsUse,
245
+ LIST_OWNERS,
246
+ matchesListFilters,
247
+ };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Test double helper: answers an owner/organization clause the way a database
3
+ * does, so in-memory repositories run the clauses a use case hands them.
4
+ * `clause.organizationId === null` matches a row with no organization (unset
5
+ * or null).
6
+ */
7
+ const same = (a, b) =>
8
+ a !== undefined && a !== null && b !== undefined && b !== null && String(a) === String(b);
9
+
10
+ const matchesClause = (row, clause) =>
11
+ same(row.userId, clause.userId) &&
12
+ (clause.organizationId === null
13
+ ? row.organizationId === null || row.organizationId === undefined
14
+ : same(row.organizationId, clause.organizationId));
15
+
16
+ const matchesAnyClause = (row, clauses) => clauses.some((clause) => matchesClause(row, clause));
17
+
18
+ module.exports = { same, matchesClause, matchesAnyClause };
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Authorizes an entity for a caller: decides who will own it and in which
3
+ * organization (ADR-056 §3.2, §3.6), then runs the module's authorization.
4
+ * Shared by the v1 `POST /api/authorize` and the v2 authorize flow, so the
5
+ * owner is decided in one place and never by `user.primary`.
6
+ */
7
+ class AuthorizeEntityForUser {
8
+ /**
9
+ * @param {Object} params
10
+ * @param {Object} params.scopePolicy - from createScopePolicy
11
+ * @param {import('./process-authorization-callback').ProcessAuthorizationCallback} params.processAuthorizationCallback
12
+ */
13
+ constructor({ scopePolicy, processAuthorizationCallback }) {
14
+ this.scopePolicy = scopePolicy;
15
+ this.processAuthorizationCallback = processAuthorizationCallback;
16
+ }
17
+
18
+ /**
19
+ * The scope, owner and organization a new entity of `entityType` gets for
20
+ * this caller. Throws a 400/403 when the request cannot have one.
21
+ *
22
+ * @param {{user: Object, entityType: string, scope?: string, fixedScope?: string}} params
23
+ * `fixedScope`: a re-authorization keeps the scope its connection has
24
+ */
25
+ resolveOwnership({ user, entityType, scope, fixedScope }) {
26
+ if (fixedScope) return this.scopePolicy.ownershipForScope({ scope: fixedScope, user });
27
+ return this.scopePolicy.resolveOwnership({
28
+ entityType,
29
+ requestScope: scope,
30
+ user,
31
+ });
32
+ }
33
+
34
+ /**
35
+ * @param {Object} params
36
+ * @param {Object} params.user - authenticated User
37
+ * @param {string} params.entityType
38
+ * @param {Object} params.data - what the module's authorization needs
39
+ * @param {string} [params.scope] - the scope the request asks for
40
+ * @param {Object} [params.ownership] - from `resolveOwnership`, when the
41
+ * caller needed it earlier (a multi-step flow does)
42
+ * @returns {Promise<{result: Object, ownership: Object}>} the callback's
43
+ * `{ credential_id, entity_id, type }` and the ownership it ran with
44
+ */
45
+ async execute({ user, entityType, data, scope, ownership }) {
46
+ const resolved = ownership ?? this.resolveOwnership({ user, entityType, scope });
47
+ const result = await this.processAuthorizationCallback.execute(
48
+ resolved.ownerId,
49
+ entityType,
50
+ data,
51
+ {
52
+ scope: resolved.scope,
53
+ organizationId: resolved.organizationId,
54
+ legacyOrgId: resolved.legacyOrgId,
55
+ }
56
+ );
57
+ return { result, ownership: resolved };
58
+ }
59
+ }
60
+
61
+ module.exports = { AuthorizeEntityForUser };
@@ -0,0 +1,113 @@
1
+ const Boom = require('@hapi/boom');
2
+ const { Module } = require('../module');
3
+
4
+ const sameId = (a, b) =>
5
+ a !== undefined && a !== null && b !== undefined && b !== null &&
6
+ String(a) === String(b);
7
+
8
+ /**
9
+ * Creates (or finds) the entity for a credential the caller already holds:
10
+ * the v1 `POST /api/entity`. The owner and organization follow the scope of
11
+ * `entityType`, exactly as an authorization does (ADR-056 §3.2, §3.6), so the
12
+ * owner is decided by `AuthorizeEntityForUser.resolveOwnership` and never by
13
+ * `user.getId()`. Whatever that resolution refuses (a missing identity, and
14
+ * an organization-level connection by a non-admin) is refused here too.
15
+ *
16
+ * The credential must belong to that owner: an organization entity is built
17
+ * on the organization's credential, an individual one on the person's own.
18
+ */
19
+ class CreateEntityFromCredential {
20
+ /**
21
+ * @param {Object} params
22
+ * @param {import('./authorize-entity-for-user').AuthorizeEntityForUser} params.authorizeEntityForUser
23
+ * @param {import('./process-authorization-callback').ProcessAuthorizationCallback} params.processAuthorizationCallback
24
+ * @param {Object} params.credentialRepository
25
+ * @param {Array<Object>} params.moduleDefinitions
26
+ * @param {Function} [params.createModule] - builds a Module; injectable for tests
27
+ */
28
+ constructor({
29
+ authorizeEntityForUser,
30
+ processAuthorizationCallback,
31
+ credentialRepository,
32
+ moduleDefinitions,
33
+ createModule,
34
+ }) {
35
+ this.authorizeEntityForUser = authorizeEntityForUser;
36
+ this.processAuthorizationCallback = processAuthorizationCallback;
37
+ this.credentialRepository = credentialRepository;
38
+ this.moduleDefinitions = moduleDefinitions || [];
39
+ this.createModule = createModule || ((params) => Module.create(params));
40
+ }
41
+
42
+ /**
43
+ * @param {Object} params
44
+ * @param {Object} params.user - authenticated User
45
+ * @param {string} params.entityType
46
+ * @param {string} params.credentialId
47
+ * @returns {Promise<Object>} the persisted entity
48
+ */
49
+ async execute({ user, entityType, credentialId }) {
50
+ const definition = this.moduleDefinitions.find(
51
+ (def) =>
52
+ def.moduleName === entityType ||
53
+ (typeof def.getName === 'function' && def.getName() === entityType)
54
+ );
55
+ if (!definition) {
56
+ throw Boom.badRequest(`Unknown entity type ${entityType}`, {
57
+ code: 'ENTITY_TYPE_NOT_FOUND',
58
+ });
59
+ }
60
+
61
+ const ownership = this.authorizeEntityForUser.resolveOwnership({
62
+ user,
63
+ entityType,
64
+ });
65
+
66
+ const credential =
67
+ await this.credentialRepository.findCredentialById(credentialId);
68
+ // A missing credential and someone else's are the same answer, so ids
69
+ // cannot be probed.
70
+ if (!credential || !sameId(credential.userId, ownership.ownerId)) {
71
+ throw Boom.badRequest('Invalid credential ID', {
72
+ code: 'INVALID_CREDENTIAL',
73
+ });
74
+ }
75
+
76
+ // Built for the owner, with the credential loaded (the repository
77
+ // returns its tokens flat; a Module reads them from `data`), so the
78
+ // API can call the provider and a token refresh during
79
+ // getEntityDetails updates the owner's credential.
80
+ const { id, userId, externalId, authIsValid, ...data } = credential;
81
+ const module = await this.createModule({
82
+ userId: ownership.ownerId,
83
+ definition,
84
+ entity: {
85
+ credential: { id, userId, externalId, authIsValid, data },
86
+ },
87
+ });
88
+ const entityDetails =
89
+ await definition.requiredAuthMethods.getEntityDetails(
90
+ module.api,
91
+ null,
92
+ null,
93
+ ownership.ownerId
94
+ );
95
+ Object.assign(
96
+ entityDetails.details,
97
+ module.apiParamsFromEntity(module.api)
98
+ );
99
+
100
+ return this.processAuthorizationCallback.findOrCreateEntity(
101
+ entityDetails,
102
+ definition.moduleName,
103
+ credential.id,
104
+ {
105
+ scope: ownership.scope,
106
+ organizationId: ownership.organizationId,
107
+ legacyOrgId: ownership.legacyOrgId,
108
+ }
109
+ );
110
+ }
111
+ }
112
+
113
+ module.exports = { CreateEntityFromCredential };
@@ -1,4 +1,11 @@
1
1
  const Boom = require('@hapi/boom');
2
+ const {
3
+ describeRecord,
4
+ visibilityClauses,
5
+ matchesListFilters,
6
+ } = require('../scope-visibility');
7
+ const { DEFAULT_SCOPE_POLICY } = require('../scope-policy');
8
+ const { assertCanManage } = require('./manage-access');
2
9
 
3
10
  /**
4
11
  * Management API v2 entity operations. Each one starts from
@@ -6,29 +13,55 @@ const Boom = require('@hapi/boom');
6
13
  * (missing or foreign entity = 404).
7
14
  */
8
15
 
9
- /** The caller's connected entities. */
16
+ /**
17
+ * The entities the caller may see in the active organization (ADR-056 §3.4,
18
+ * §3.6): the organization's own, and the caller's individual ones by the
19
+ * visibility rule. Each carries `tenancy` ({scope, owner, organizationId,
20
+ * access}); the stored entity is otherwise untouched.
21
+ */
10
22
  class ListEntitiesForUser {
11
- constructor({ moduleRepository }) {
23
+ constructor({ moduleRepository, scopePolicy }) {
12
24
  this.moduleRepository = moduleRepository;
25
+ this.scopePolicy = scopePolicy || DEFAULT_SCOPE_POLICY;
13
26
  }
14
27
 
15
- /** @param {Object} user - authenticated User */
16
- async execute(user) {
17
- const entities = await this.moduleRepository.findEntitiesByUserId(
18
- user.getId()
28
+ /**
29
+ * @param {Object} user - authenticated User
30
+ * @param {{scope?: string, owner?: string}} [filters] - `?scope=` and `?owner=`
31
+ */
32
+ async execute(user, filters = {}) {
33
+ const ctx = this.scopePolicy.accessContext(user);
34
+ const entities = await this.moduleRepository.findEntitiesByOwnership(
35
+ visibilityClauses(ctx, 'entity')
19
36
  );
20
- return Array.isArray(entities) ? entities : [];
37
+ const listed = [];
38
+ for (const entity of Array.isArray(entities) ? entities : []) {
39
+ // The query is the filter; this is the same rule applied again,
40
+ // so a repository that returns too much cannot widen the list.
41
+ const tenancy = describeRecord(entity, ctx, 'entity');
42
+ if (tenancy && matchesListFilters(tenancy, filters)) {
43
+ listed.push({ ...entity, tenancy });
44
+ }
45
+ }
46
+ return listed;
21
47
  }
22
48
  }
23
49
 
24
- /** One entity the caller owns. */
50
+ /** One entity the caller may use, with its `tenancy`. */
25
51
  class GetEntityForUser {
26
52
  constructor({ getEntityModuleForUser }) {
27
53
  this.getEntityModuleForUser = getEntityModuleForUser;
28
54
  }
29
55
 
30
56
  async execute(entityId, user) {
31
- return this.getEntityModuleForUser.loadOwnedEntity(entityId, user);
57
+ const entity = await this.getEntityModuleForUser.loadOwnedEntity(
58
+ entityId,
59
+ user
60
+ );
61
+ return {
62
+ ...entity,
63
+ tenancy: this.getEntityModuleForUser.describe(entity, user),
64
+ };
32
65
  }
33
66
  }
34
67
 
@@ -79,10 +112,10 @@ class RefreshEntityOptionsForUser {
79
112
  }
80
113
 
81
114
  /**
82
- * Deletes an entity the caller owns. Refuses with 409 while integrations
83
- * still use it, so an integration never points at a missing entity. The
84
- * credential is left alone (others may share it); delete it through
85
- * /api/v2/credentials.
115
+ * Deletes an entity the caller may manage (the owner; for an organization
116
+ * entity, an organization admin). Refuses with 409 while integrations still
117
+ * use it, so an integration never points at a missing entity. The credential
118
+ * is left alone (others may share it); delete it through /api/v2/credentials.
86
119
  */
87
120
  class DeleteEntityForUser {
88
121
  constructor({ getEntityModuleForUser, moduleRepository, integrationRepository }) {
@@ -96,6 +129,10 @@ class DeleteEntityForUser {
96
129
  entityId,
97
130
  user
98
131
  );
132
+ assertCanManage(
133
+ this.getEntityModuleForUser.describe(entity, user)?.access,
134
+ `entity ${entity.id}`
135
+ );
99
136
  const integrations =
100
137
  (await this.integrationRepository.findIntegrationsByEntityId(
101
138
  entity.id
@@ -59,10 +59,31 @@ function findDefinition(moduleDefinitions, entityType) {
59
59
  return definition;
60
60
  }
61
61
 
62
- const describeEntry = (name, entry) => ({
62
+ /**
63
+ * With a scope policy the entry also says which scope a new connection gets
64
+ * and which a request may choose (ADR-056 §3.1), so a UI can offer the choice.
65
+ * `global` is never offered: a tenant request cannot create one.
66
+ */
67
+ const scopeOf = (scopePolicy, name, user) => {
68
+ if (!scopePolicy) return {};
69
+ const { scope, source, allow } = scopePolicy.resolveScope({
70
+ entityType: name,
71
+ user,
72
+ });
73
+ return {
74
+ scope: {
75
+ default: scope,
76
+ allow: allow.filter((value) => value !== 'global'),
77
+ source,
78
+ },
79
+ };
80
+ };
81
+
82
+ const describeEntry = (name, entry, scopePolicy, user) => ({
63
83
  // The registry key is the name the API uses, whatever the definition spells.
64
84
  ...describeEntityType(entry.definition, name),
65
85
  usedBy: usedByOf(entry),
86
+ ...scopeOf(scopePolicy, name, user),
66
87
  });
67
88
 
68
89
  function requireRegistry(entityTypeRegistry) {
@@ -78,31 +99,34 @@ function requireRegistry(entityTypeRegistry) {
78
99
  * bind each type; it is empty for a registry-only type.
79
100
  */
80
101
  class ListEntityTypes {
81
- constructor({ entityTypeRegistry }) {
102
+ constructor({ entityTypeRegistry, scopePolicy }) {
82
103
  this.registry = requireRegistry(entityTypeRegistry);
104
+ this.scopePolicy = scopePolicy;
83
105
  }
84
106
 
85
- async execute() {
107
+ /** @param {{user?: Object}} [params] - the caller, for the level-6 scope default */
108
+ async execute({ user } = {}) {
86
109
  return [...this.registry]
87
- .map(([name, entry]) => describeEntry(name, entry))
110
+ .map(([name, entry]) => describeEntry(name, entry, this.scopePolicy, user))
88
111
  .sort((a, b) => a.name.localeCompare(b.name));
89
112
  }
90
113
  }
91
114
 
92
115
  /** Describes one entity type, looked up by its registry key; 404 when absent. */
93
116
  class GetEntityType {
94
- constructor({ entityTypeRegistry }) {
117
+ constructor({ entityTypeRegistry, scopePolicy }) {
95
118
  this.registry = requireRegistry(entityTypeRegistry);
119
+ this.scopePolicy = scopePolicy;
96
120
  }
97
121
 
98
- async execute(entityType) {
122
+ async execute(entityType, { user } = {}) {
99
123
  const entry = this.registry.get(entityType);
100
124
  if (!entry) {
101
125
  throw Boom.notFound(`Entity type '${entityType}' not found`, {
102
126
  code: 'ENTITY_TYPE_NOT_FOUND',
103
127
  });
104
128
  }
105
- return describeEntry(entityType, entry);
129
+ return describeEntry(entityType, entry, this.scopePolicy, user);
106
130
  }
107
131
  }
108
132