@friggframework/core 2.0.0--canary.707.df80bfd.0 → 2.0.0--canary.680.d670696.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 (161) hide show
  1. package/CHANGELOG.md +3 -0
  2. package/CLAUDE.md +0 -28
  3. package/README.md +0 -105
  4. package/application/commands/integration-commands.js +2 -2
  5. package/application/commands/scheduler-commands.js +7 -11
  6. package/application/commands/user-commands.js +5 -17
  7. package/core/Worker.js +7 -31
  8. package/core/create-handler.js +0 -9
  9. package/credential/use-cases/credential-operations-for-user.js +25 -110
  10. package/credential/use-cases/reauthorize-credential-for-user.js +8 -15
  11. package/database/config.js +24 -48
  12. package/database/documentdb-encryption-service.js +0 -1
  13. package/database/documentdb-utils.js +1 -6
  14. package/database/encryption/encryption-config.js +44 -13
  15. package/database/encryption/encryption-schema-registry.js +31 -88
  16. package/database/prisma.js +2 -4
  17. package/generated/prisma-mongodb/edge.js +4 -27
  18. package/generated/prisma-mongodb/index-browser.js +1 -24
  19. package/generated/prisma-mongodb/index.d.ts +48 -3228
  20. package/generated/prisma-mongodb/index.js +4 -27
  21. package/generated/prisma-mongodb/package.json +1 -1
  22. package/generated/prisma-mongodb/schema.prisma +0 -65
  23. package/generated/prisma-mongodb/wasm.js +4 -27
  24. package/generated/prisma-postgresql/edge.js +4 -27
  25. package/generated/prisma-postgresql/index-browser.js +1 -24
  26. package/generated/prisma-postgresql/index.d.ts +51 -3503
  27. package/generated/prisma-postgresql/index.js +4 -27
  28. package/generated/prisma-postgresql/package.json +1 -1
  29. package/generated/prisma-postgresql/schema.prisma +0 -61
  30. package/generated/prisma-postgresql/wasm.js +4 -27
  31. package/handlers/app-definition-loader.js +12 -110
  32. package/handlers/routers/auth.js +12 -40
  33. package/handlers/routers/health.js +2 -4
  34. package/handlers/routers/integration-defined-routers.js +92 -144
  35. package/handlers/routers/integration-webhook-routers.js +64 -102
  36. package/index.js +1 -64
  37. package/infrastructure/scheduler/index.js +6 -19
  38. package/infrastructure/scheduler/scheduler-service-factory.js +7 -55
  39. package/integrations/index.js +0 -5
  40. package/integrations/integration-router.js +73 -115
  41. package/integrations/repositories/integration-repository-documentdb.js +3 -35
  42. package/integrations/repositories/integration-repository-interface.js +1 -17
  43. package/integrations/repositories/integration-repository-mongo.js +76 -59
  44. package/integrations/repositories/integration-repository-postgres.js +76 -62
  45. package/integrations/tests/doubles/test-integration-repository.js +1 -12
  46. package/integrations/use-cases/create-integration.js +20 -55
  47. package/integrations/use-cases/get-integrations-for-user.js +40 -80
  48. package/integrations/use-cases/index.js +1 -7
  49. package/integrations/use-cases/integration-operations-for-user.js +24 -55
  50. package/integrations/utils/map-integration-dto.js +1 -44
  51. package/management-api/management-api-config.js +2 -71
  52. package/management-api/meta-router.js +2 -21
  53. package/management-api/openapi/components.js +3 -50
  54. package/management-api/openapi/v2-operations.js +5 -17
  55. package/management-api/route-registry.js +6 -123
  56. package/management-api/v2/dependencies.js +15 -40
  57. package/management-api/v2/dto.js +0 -20
  58. package/management-api/v2/handlers/authorization.js +0 -1
  59. package/management-api/v2/handlers/credentials.js +2 -6
  60. package/management-api/v2/handlers/entities.js +7 -10
  61. package/management-api/v2/handlers/integrations.js +3 -6
  62. package/management-api/v2/request.js +1 -32
  63. package/modules/index.js +0 -8
  64. package/modules/module-factory.js +0 -12
  65. package/modules/module.js +2 -53
  66. package/modules/proxy/proxy-errors.js +1 -12
  67. package/modules/proxy/proxy-path.js +3 -7
  68. package/modules/proxy/proxy-policy.js +5 -34
  69. package/modules/repositories/module-repository-documentdb.js +6 -51
  70. package/modules/repositories/module-repository-interface.js +2 -19
  71. package/modules/repositories/module-repository-mongo.js +74 -67
  72. package/modules/repositories/module-repository-postgres.js +74 -66
  73. package/modules/repositories/module-repository.js +1 -2
  74. package/modules/requester/proxy-request.js +1 -2
  75. package/modules/requester/requester.js +3 -8
  76. package/modules/use-cases/entity-operations-for-user.js +13 -50
  77. package/modules/use-cases/entity-types.js +7 -31
  78. package/modules/use-cases/execute-entity-proxy-request.js +15 -107
  79. package/modules/use-cases/get-authorization-requirements.js +2 -2
  80. package/modules/use-cases/get-entities-for-user.js +13 -26
  81. package/modules/use-cases/get-entity-module-for-user.js +7 -34
  82. package/modules/use-cases/get-entity-options-by-id.js +4 -10
  83. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  84. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  85. package/modules/use-cases/get-module.js +4 -10
  86. package/modules/use-cases/multi-step-authorization.js +13 -40
  87. package/modules/use-cases/process-authorization-callback.js +19 -53
  88. package/modules/use-cases/refresh-entity-options.js +4 -10
  89. package/modules/use-cases/test-module-auth.js +4 -10
  90. package/package.json +5 -6
  91. package/prisma-mongodb/schema.prisma +0 -65
  92. package/prisma-postgresql/schema.prisma +0 -61
  93. package/queues/index.js +0 -25
  94. package/types/index.d.ts +0 -1
  95. package/types/modules/index.d.ts +1 -157
  96. package/user/repositories/user-repository-documentdb.js +2 -27
  97. package/user/repositories/user-repository-interface.js +0 -18
  98. package/user/repositories/user-repository-mongo.js +0 -24
  99. package/user/repositories/user-repository-postgres.js +0 -18
  100. package/user/use-cases/authenticate-user.js +1 -7
  101. package/user/use-cases/get-user-from-adopter-jwt.js +124 -95
  102. package/user/use-cases/get-user-from-x-frigg-headers.js +80 -83
  103. package/user/user.js +1 -64
  104. package/database/organization-where.js +0 -18
  105. package/database/unique-violation.js +0 -25
  106. package/extensions/bootstrap-runner.js +0 -43
  107. package/extensions/extension-loader.js +0 -230
  108. package/extensions/index.js +0 -44
  109. package/extensions/initialize-app.js +0 -123
  110. package/extensions/prisma-composer.js +0 -270
  111. package/extensions/route-mounter.js +0 -103
  112. package/extensions/schema-composer.js +0 -188
  113. package/infrastructure/scheduler/netlify-scheduler-adapter.js +0 -216
  114. package/infrastructure/scheduler/scheduled-job-repository.js +0 -118
  115. package/integrations/repositories/integration-not-found.js +0 -14
  116. package/integrations/schedule-config.js +0 -80
  117. package/integrations/use-cases/dispatch-ongoing-syncs.js +0 -100
  118. package/integrations/use-cases/resolve-integration-ownership.js +0 -177
  119. package/modules/entity-scope.js +0 -15
  120. package/modules/proxy/proxy-bases.js +0 -169
  121. package/modules/repositories/entity-not-found.js +0 -18
  122. package/modules/scope-config.js +0 -192
  123. package/modules/scope-policy.js +0 -112
  124. package/modules/scope-resolution.js +0 -288
  125. package/modules/scope-visibility.js +0 -247
  126. package/modules/tests/doubles/ownership-matching.js +0 -18
  127. package/modules/use-cases/authorize-entity-for-user.js +0 -61
  128. package/modules/use-cases/create-entity-from-credential.js +0 -113
  129. package/modules/use-cases/manage-access.js +0 -21
  130. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +0 -26
  131. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +0 -25
  132. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +0 -28
  133. package/providers/index.js +0 -23
  134. package/providers/resolve-provider.js +0 -93
  135. package/providers/runtime-detection.js +0 -124
  136. package/queues/providers/index.js +0 -11
  137. package/queues/providers/netlify-background-provider.js +0 -150
  138. package/queues/providers/qstash-queue-provider.js +0 -219
  139. package/queues/providers/sqs-queue-provider.js +0 -70
  140. package/queues/queue-client-interface.js +0 -55
  141. package/queues/queue-message-auth.js +0 -193
  142. package/queues/queue-provider-factory.js +0 -101
  143. package/queues/queue-provider.js +0 -65
  144. package/queues/sqs-queue-client.js +0 -81
  145. package/types/user/index.d.ts +0 -134
  146. package/user/adopter-jwt-config.js +0 -177
  147. package/user/adopter-jwt-errors.js +0 -59
  148. package/user/adopter-token-verifier.js +0 -122
  149. package/user/app-user-helpers.js +0 -97
  150. package/user/create-user-authentication.js +0 -64
  151. package/user/membership.js +0 -51
  152. package/user/repositories/organization-membership-record.js +0 -19
  153. package/user/repositories/organization-membership-repository-documentdb.js +0 -106
  154. package/user/repositories/organization-membership-repository-factory.js +0 -42
  155. package/user/repositories/organization-membership-repository-interface.js +0 -57
  156. package/user/repositories/organization-membership-repository-mongo.js +0 -13
  157. package/user/repositories/organization-membership-repository-postgres.js +0 -29
  158. package/user/repositories/organization-membership-repository-prisma.js +0 -81
  159. package/user/tests/doubles/adopter-jwt-fixtures.js +0 -220
  160. package/user/use-cases/ensure-organization-membership.js +0 -92
  161. package/user/use-cases/find-individual-users-by-organization.js +0 -54
@@ -1,247 +0,0 @@
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
- };
@@ -1,18 +0,0 @@
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 };
@@ -1,61 +0,0 @@
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 };
@@ -1,113 +0,0 @@
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,21 +0,0 @@
1
- const Boom = require('@hapi/boom');
2
- const { ACCESS } = require('../scope-resolution');
3
-
4
- /**
5
- * The one check behind every "may this caller change or delete it" gate
6
- * (ADR-056 §3 permissions): the caller may use it but not manage it, so 403
7
- * `ORG_ADMIN_REQUIRED`. `access` comes from describeRecord (entities,
8
- * integrations) or scopePolicy.accessToOwnedBy (credentials).
9
- *
10
- * @param {string|null} access - ACCESS value
11
- * @param {string} subject - e.g. `entity 5`, for the message
12
- */
13
- function assertCanManage(access, subject) {
14
- if (access !== ACCESS.MANAGE) {
15
- throw Boom.forbidden(`You may use ${subject} but not change or delete it`, {
16
- code: 'ORG_ADMIN_REQUIRED',
17
- });
18
- }
19
- }
20
-
21
- module.exports = { assertCanManage };
@@ -1,26 +0,0 @@
1
- -- CreateTable
2
- -- Organization memberships (ADR-056 §3.6). One row per person per organization.
3
- -- "User"."organizationId" stays as the legacy single-org pointer. It is NOT
4
- -- backfilled into this table: the domain (user/membership.js) reads it as an
5
- -- implicit membership when no row exists (see docs/guides/organization-memberships.md).
6
- CREATE TABLE "OrganizationMembership" (
7
- "id" SERIAL NOT NULL,
8
- "individualUserId" INTEGER NOT NULL,
9
- "organizationUserId" INTEGER NOT NULL,
10
- "orgRole" TEXT NOT NULL DEFAULT 'MEMBER',
11
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
12
-
13
- CONSTRAINT "OrganizationMembership_pkey" PRIMARY KEY ("id")
14
- );
15
-
16
- -- CreateIndex
17
- CREATE INDEX "OrganizationMembership_organizationUserId_idx" ON "OrganizationMembership"("organizationUserId");
18
-
19
- -- CreateIndex
20
- CREATE UNIQUE INDEX "OrganizationMembership_individualUserId_organizationUserId_key" ON "OrganizationMembership"("individualUserId", "organizationUserId");
21
-
22
- -- AddForeignKey
23
- ALTER TABLE "OrganizationMembership" ADD CONSTRAINT "OrganizationMembership_individualUserId_fkey" FOREIGN KEY ("individualUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE NO ACTION;
24
-
25
- -- AddForeignKey
26
- ALTER TABLE "OrganizationMembership" ADD CONSTRAINT "OrganizationMembership_organizationUserId_fkey" FOREIGN KEY ("organizationUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE NO ACTION;
@@ -1,25 +0,0 @@
1
- -- Entity and Integration carry the organization they were created in (ADR-056 §3.6).
2
- -- Nullable, no default and no backfill: a row written before this migration keeps
3
- -- NULL, and the domain (modules/entity-scope.js) reads NULL as "predates scoping"
4
- -- (docs/guides/entity-scopes.md). No scope column: the owner's user type says it.
5
- -- Deliberately no foreign key: a deleted organization must leave its rows
6
- -- invisible, and ON DELETE SET NULL would turn them into unscoped ones.
7
- --
8
- -- Release note: the two CREATE INDEX statements below are plain (not
9
- -- CONCURRENTLY, which Prisma migrations cannot run inside a transaction). Each
10
- -- takes a SHARE lock on its table while it builds, so writes to "Entity" and
11
- -- "Integration" wait for it. Both tables are small in a typical Frigg
12
- -- deployment; on a very large one, create the indexes by hand first with
13
- -- CREATE INDEX CONCURRENTLY IF NOT EXISTS under the same names, then deploy.
14
-
15
- -- AlterTable
16
- ALTER TABLE "Entity" ADD COLUMN "organizationId" INTEGER;
17
-
18
- -- AlterTable
19
- ALTER TABLE "Integration" ADD COLUMN "organizationId" INTEGER;
20
-
21
- -- CreateIndex
22
- CREATE INDEX "Entity_userId_organizationId_idx" ON "Entity"("userId", "organizationId");
23
-
24
- -- CreateIndex
25
- CREATE INDEX "Integration_userId_organizationId_idx" ON "Integration"("userId", "organizationId");
@@ -1,28 +0,0 @@
1
- -- One-time scheduled jobs for the poll-and-dispatch scheduler
2
- -- (NetlifySchedulerAdapter, friggframework/frigg#545): a cron function reads
3
- -- PENDING rows that are due and dispatches them to a queue.
4
- --
5
- -- IF NOT EXISTS on purpose: #545 shipped this model in the Prisma schema with
6
- -- no migration, so an app that ran its canary may already have the table from
7
- -- `prisma db push`. On such a database this migration is a no-op; on a fresh
8
- -- one it is the SQL `prisma migrate diff` generates.
9
-
10
- -- CreateTable
11
- CREATE TABLE IF NOT EXISTS "ScheduledJob" (
12
- "id" SERIAL NOT NULL,
13
- "scheduleName" TEXT NOT NULL,
14
- "scheduledAt" TIMESTAMP(3) NOT NULL,
15
- "queueResourceId" TEXT NOT NULL,
16
- "payload" JSONB,
17
- "state" TEXT NOT NULL DEFAULT 'PENDING',
18
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
19
- "updatedAt" TIMESTAMP(3) NOT NULL,
20
-
21
- CONSTRAINT "ScheduledJob_pkey" PRIMARY KEY ("id")
22
- );
23
-
24
- -- CreateIndex
25
- CREATE UNIQUE INDEX IF NOT EXISTS "ScheduledJob_scheduleName_key" ON "ScheduledJob"("scheduleName");
26
-
27
- -- CreateIndex
28
- CREATE INDEX IF NOT EXISTS "ScheduledJob_state_scheduledAt_idx" ON "ScheduledJob"("state", "scheduledAt");
@@ -1,23 +0,0 @@
1
- const {
2
- resolveProvider,
3
- determineProviderName,
4
- providerPackageName,
5
- KNOWN_PROVIDERS,
6
- } = require('./resolve-provider');
7
- const {
8
- isDeployedRuntime,
9
- isAwsLambdaRuntime,
10
- isLocalRun,
11
- resolveActiveProvider,
12
- } = require('./runtime-detection');
13
-
14
- module.exports = {
15
- resolveProvider,
16
- determineProviderName,
17
- providerPackageName,
18
- KNOWN_PROVIDERS,
19
- isDeployedRuntime,
20
- isAwsLambdaRuntime,
21
- isLocalRun,
22
- resolveActiveProvider,
23
- };
@@ -1,93 +0,0 @@
1
- /**
2
- * Provider Resolver
3
- *
4
- * Resolves a provider name from the appDefinition into the corresponding
5
- * @friggframework/provider-{name} package. This is the bridge between
6
- * `appDefinition.provider` and the provider plugin interface.
7
- *
8
- * Resolution order:
9
- * 1. Explicit `providerName` argument
10
- * 2. `appDefinition.provider`
11
- * 3. `FRIGG_PROVIDER` environment variable
12
- * 4. Default: 'aws'
13
- *
14
- * Package naming convention:
15
- * provider: 'netlify' → require('@friggframework/provider-netlify')
16
- * provider: 'aws' → require('@friggframework/provider-aws')
17
- *
18
- * @example
19
- * const provider = resolveProvider({ provider: 'netlify' });
20
- * // provider.name === 'netlify'
21
- * // provider.deploy(appDefinition, options)
22
- * // provider.createHandler(options)
23
- * // provider.QueueProvider (class)
24
- * // etc.
25
- */
26
-
27
- const KNOWN_PROVIDERS = ['aws', 'netlify'];
28
-
29
- /**
30
- * Determine the provider name from available sources.
31
- *
32
- * @param {Object} [appDefinition] - Frigg app definition
33
- * @param {string} [providerName] - Explicit override
34
- * @returns {string} Provider name (e.g. 'netlify', 'aws')
35
- */
36
- function determineProviderName(appDefinition, providerName) {
37
- if (providerName) {
38
- return providerName;
39
- }
40
- if (appDefinition?.provider) {
41
- return appDefinition.provider;
42
- }
43
- if (process.env.FRIGG_PROVIDER) {
44
- return process.env.FRIGG_PROVIDER;
45
- }
46
- return 'aws';
47
- }
48
-
49
- /**
50
- * Resolve a provider name to a package name.
51
- *
52
- * @param {string} name - Provider name (e.g. 'netlify')
53
- * @returns {string} npm package name (e.g. '@friggframework/provider-netlify')
54
- */
55
- function providerPackageName(name) {
56
- return `@friggframework/provider-${name}`;
57
- }
58
-
59
- /**
60
- * Resolve and load the provider plugin for the given app definition.
61
- *
62
- * @param {Object} [appDefinition] - Frigg app definition (reads .provider)
63
- * @param {Object} [options]
64
- * @param {string} [options.provider] - Explicit provider name override
65
- * @returns {Object} Provider plugin (conforms to the provider plugin interface)
66
- * @throws {Error} If the provider package is not installed
67
- */
68
- function resolveProvider(appDefinition, options = {}) {
69
- const name = determineProviderName(appDefinition, options.provider);
70
- const packageName = providerPackageName(name);
71
-
72
- try {
73
- return require(packageName);
74
- } catch (error) {
75
- if (error.code === 'MODULE_NOT_FOUND') {
76
- const hint = KNOWN_PROVIDERS.includes(name)
77
- ? `Install it with: npm install ${packageName}`
78
- : `Is '${name}' a valid Frigg provider? Known providers: ${KNOWN_PROVIDERS.join(', ')}`;
79
-
80
- throw new Error(
81
- `Provider '${name}' specified in appDefinition but package '${packageName}' is not installed.\n ${hint}`
82
- );
83
- }
84
- throw error;
85
- }
86
- }
87
-
88
- module.exports = {
89
- resolveProvider,
90
- determineProviderName,
91
- providerPackageName,
92
- KNOWN_PROVIDERS,
93
- };