@friggframework/core 2.0.0--canary.686.3e27a92.0 → 2.0.0--canary.663.8de669c.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 (184) hide show
  1. package/CLAUDE.md +0 -28
  2. package/README.md +0 -105
  3. package/application/commands/integration-commands.js +10 -20
  4. package/application/commands/scheduler-commands.js +7 -11
  5. package/application/commands/user-commands.js +5 -17
  6. package/application/index.js +2 -6
  7. package/core/Worker.js +7 -31
  8. package/core/create-handler.js +0 -9
  9. package/credential/repositories/credential-repository-documentdb.js +0 -34
  10. package/credential/repositories/credential-repository-interface.js +0 -15
  11. package/credential/repositories/credential-repository-mongo.js +0 -23
  12. package/credential/repositories/credential-repository-postgres.js +0 -28
  13. package/database/config.js +24 -48
  14. package/database/documentdb-utils.js +1 -6
  15. package/database/encryption/encryption-config.js +31 -10
  16. package/database/encryption/encryption-schema-registry.js +12 -93
  17. package/database/prisma.js +2 -4
  18. package/generated/prisma-mongodb/edge.js +4 -43
  19. package/generated/prisma-mongodb/index-browser.js +1 -40
  20. package/generated/prisma-mongodb/index.d.ts +111 -4739
  21. package/generated/prisma-mongodb/index.js +4 -43
  22. package/generated/prisma-mongodb/package.json +1 -1
  23. package/generated/prisma-mongodb/schema.prisma +0 -92
  24. package/generated/prisma-mongodb/wasm.js +4 -43
  25. package/generated/prisma-postgresql/edge.js +4 -43
  26. package/generated/prisma-postgresql/index-browser.js +1 -40
  27. package/generated/prisma-postgresql/index.d.ts +33 -4966
  28. package/generated/prisma-postgresql/index.js +4 -43
  29. package/generated/prisma-postgresql/package.json +1 -1
  30. package/generated/prisma-postgresql/schema.prisma +0 -87
  31. package/generated/prisma-postgresql/wasm.js +4 -43
  32. package/handlers/app-definition-loader.js +19 -121
  33. package/handlers/app-handler-helpers.js +3 -25
  34. package/handlers/backend-utils.js +25 -31
  35. package/handlers/middleware/admin-auth.js +1 -14
  36. package/handlers/routers/auth.js +10 -46
  37. package/handlers/routers/health.js +4 -13
  38. package/handlers/routers/integration-defined-routers.js +92 -144
  39. package/handlers/routers/integration-webhook-routers.js +64 -102
  40. package/handlers/workers/integration-defined-workers.js +2 -5
  41. package/index.js +1 -65
  42. package/infrastructure/scheduler/index.js +6 -19
  43. package/infrastructure/scheduler/scheduler-service-factory.js +7 -55
  44. package/integrations/index.js +0 -1
  45. package/integrations/integration-router.js +96 -131
  46. package/integrations/repositories/integration-repository-documentdb.js +3 -35
  47. package/integrations/repositories/integration-repository-interface.js +1 -17
  48. package/integrations/repositories/integration-repository-mongo.js +76 -59
  49. package/integrations/repositories/integration-repository-postgres.js +76 -62
  50. package/integrations/tests/doubles/test-integration-repository.js +1 -12
  51. package/integrations/use-cases/create-integration.js +20 -55
  52. package/integrations/use-cases/get-integrations-for-user.js +40 -80
  53. package/integrations/use-cases/index.js +1 -7
  54. package/integrations/utils/map-integration-dto.js +14 -43
  55. package/modules/index.js +0 -14
  56. package/modules/module-factory.js +0 -12
  57. package/modules/module.js +2 -53
  58. package/modules/repositories/module-repository-documentdb.js +6 -51
  59. package/modules/repositories/module-repository-interface.js +2 -19
  60. package/modules/repositories/module-repository-mongo.js +74 -67
  61. package/modules/repositories/module-repository-postgres.js +74 -66
  62. package/modules/repositories/module-repository.js +1 -2
  63. package/modules/requester/requester.js +2 -27
  64. package/modules/use-cases/get-entities-for-user.js +13 -26
  65. package/modules/use-cases/get-entity-options-by-id.js +4 -10
  66. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  67. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  68. package/modules/use-cases/get-module.js +4 -10
  69. package/modules/use-cases/process-authorization-callback.js +19 -53
  70. package/modules/use-cases/refresh-entity-options.js +4 -10
  71. package/modules/use-cases/test-module-auth.js +4 -10
  72. package/package.json +5 -6
  73. package/prisma-mongodb/schema.prisma +0 -92
  74. package/prisma-postgresql/schema.prisma +0 -87
  75. package/queues/index.js +0 -25
  76. package/types/index.d.ts +0 -2
  77. package/user/repositories/user-repository-documentdb.js +2 -27
  78. package/user/repositories/user-repository-interface.js +0 -18
  79. package/user/repositories/user-repository-mongo.js +0 -24
  80. package/user/repositories/user-repository-postgres.js +0 -18
  81. package/user/use-cases/authenticate-user.js +1 -7
  82. package/user/use-cases/get-user-from-adopter-jwt.js +124 -95
  83. package/user/use-cases/get-user-from-x-frigg-headers.js +80 -83
  84. package/user/user.js +1 -64
  85. package/credential/use-cases/credential-operations-for-user.js +0 -202
  86. package/credential/use-cases/reauthorize-credential-for-user.js +0 -73
  87. package/database/organization-where.js +0 -18
  88. package/database/unique-violation.js +0 -25
  89. package/extensions/bootstrap-runner.js +0 -43
  90. package/extensions/extension-loader.js +0 -187
  91. package/extensions/index.js +0 -41
  92. package/extensions/initialize-app.js +0 -123
  93. package/extensions/route-mounter.js +0 -103
  94. package/extensions/schema-composer.js +0 -188
  95. package/infrastructure/scheduler/netlify-scheduler-adapter.js +0 -216
  96. package/infrastructure/scheduler/scheduled-job-repository.js +0 -118
  97. package/integrations/repositories/integration-not-found.js +0 -14
  98. package/integrations/schedule-config.js +0 -80
  99. package/integrations/use-cases/dispatch-ongoing-syncs.js +0 -100
  100. package/integrations/use-cases/integration-operations-for-user.js +0 -256
  101. package/integrations/use-cases/resolve-integration-ownership.js +0 -177
  102. package/management-api/create-management-api-router.js +0 -49
  103. package/management-api/error-response.js +0 -116
  104. package/management-api/management-api-config.js +0 -151
  105. package/management-api/meta-router.js +0 -76
  106. package/management-api/openapi/build-openapi.js +0 -144
  107. package/management-api/openapi/components.js +0 -408
  108. package/management-api/openapi/v1-operations.js +0 -83
  109. package/management-api/openapi/v2-operations.js +0 -264
  110. package/management-api/route-registry.js +0 -411
  111. package/management-api/test-support/http-client.js +0 -39
  112. package/management-api/use-cases/get-management-api-meta.js +0 -57
  113. package/management-api/v1-deprecation.js +0 -120
  114. package/management-api/v2/create-v2-router.js +0 -85
  115. package/management-api/v2/dependencies.js +0 -281
  116. package/management-api/v2/dto.js +0 -143
  117. package/management-api/v2/handlers/authorization.js +0 -94
  118. package/management-api/v2/handlers/credentials.js +0 -33
  119. package/management-api/v2/handlers/entities.js +0 -77
  120. package/management-api/v2/handlers/integrations.js +0 -128
  121. package/management-api/v2/handlers/proxy.js +0 -34
  122. package/management-api/v2/request.js +0 -85
  123. package/management-api/v2/test-support/fake-dependencies.js +0 -103
  124. package/modules/domain/authorization-session.js +0 -144
  125. package/modules/entity-scope.js +0 -15
  126. package/modules/entity-type-registry.js +0 -311
  127. package/modules/proxy/proxy-errors.js +0 -20
  128. package/modules/proxy/proxy-path.js +0 -179
  129. package/modules/proxy/proxy-policy.js +0 -248
  130. package/modules/repositories/authorization-session-repository-documentdb.js +0 -112
  131. package/modules/repositories/authorization-session-repository-factory.js +0 -31
  132. package/modules/repositories/authorization-session-repository-interface.js +0 -47
  133. package/modules/repositories/authorization-session-repository-prisma.js +0 -87
  134. package/modules/repositories/entity-not-found.js +0 -18
  135. package/modules/requester/proxy-request.js +0 -244
  136. package/modules/scope-config.js +0 -192
  137. package/modules/scope-policy.js +0 -112
  138. package/modules/scope-resolution.js +0 -288
  139. package/modules/scope-visibility.js +0 -247
  140. package/modules/tests/doubles/in-memory-authorization-session-repository.js +0 -45
  141. package/modules/tests/doubles/ownership-matching.js +0 -18
  142. package/modules/use-cases/authorize-entity-for-user.js +0 -61
  143. package/modules/use-cases/create-entity-from-credential.js +0 -113
  144. package/modules/use-cases/entity-operations-for-user.js +0 -162
  145. package/modules/use-cases/entity-types.js +0 -139
  146. package/modules/use-cases/execute-entity-proxy-request.js +0 -286
  147. package/modules/use-cases/get-authorization-requirements.js +0 -100
  148. package/modules/use-cases/get-entity-module-for-user.js +0 -113
  149. package/modules/use-cases/manage-access.js +0 -21
  150. package/modules/use-cases/multi-step-authorization.js +0 -329
  151. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +0 -28
  152. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +0 -26
  153. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +0 -25
  154. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +0 -28
  155. package/providers/index.js +0 -23
  156. package/providers/resolve-provider.js +0 -93
  157. package/providers/runtime-detection.js +0 -124
  158. package/queues/providers/index.js +0 -11
  159. package/queues/providers/netlify-background-provider.js +0 -150
  160. package/queues/providers/qstash-queue-provider.js +0 -219
  161. package/queues/providers/sqs-queue-provider.js +0 -70
  162. package/queues/queue-client-interface.js +0 -55
  163. package/queues/queue-message-auth.js +0 -193
  164. package/queues/queue-provider-factory.js +0 -101
  165. package/queues/queue-provider.js +0 -65
  166. package/queues/sqs-queue-client.js +0 -81
  167. package/types/modules/index.d.ts +0 -197
  168. package/types/user/index.d.ts +0 -134
  169. package/user/adopter-jwt-config.js +0 -177
  170. package/user/adopter-jwt-errors.js +0 -59
  171. package/user/adopter-token-verifier.js +0 -122
  172. package/user/app-user-helpers.js +0 -97
  173. package/user/create-user-authentication.js +0 -64
  174. package/user/membership.js +0 -51
  175. package/user/repositories/organization-membership-record.js +0 -19
  176. package/user/repositories/organization-membership-repository-documentdb.js +0 -106
  177. package/user/repositories/organization-membership-repository-factory.js +0 -42
  178. package/user/repositories/organization-membership-repository-interface.js +0 -57
  179. package/user/repositories/organization-membership-repository-mongo.js +0 -13
  180. package/user/repositories/organization-membership-repository-postgres.js +0 -29
  181. package/user/repositories/organization-membership-repository-prisma.js +0 -81
  182. package/user/tests/doubles/adopter-jwt-fixtures.js +0 -220
  183. package/user/use-cases/ensure-organization-membership.js +0 -92
  184. package/user/use-cases/find-individual-users-by-organization.js +0 -54
@@ -1,286 +0,0 @@
1
- const Boom = require('@hapi/boom');
2
- const { getLogger } = require('../../logs');
3
- const { getTelemetry } = require('../../telemetry/telemetry-runtime');
4
- const { ProxyRequestError } = require('../proxy/proxy-errors');
5
- const { SCOPES } = require('../scope-resolution');
6
- const { grantsUse } = require('../scope-visibility');
7
- const { normalizeProxyPath, matchAllowRule } = require('../proxy/proxy-path');
8
- const {
9
- validateProxyRequest,
10
- resolveAllowRules,
11
- filterRequestHeaders,
12
- filterResponseHeaders,
13
- decodeResponseBody,
14
- } = require('../proxy/proxy-policy');
15
-
16
- const log = getLogger('frigg.api.proxy');
17
-
18
- /** HTTP status and audit outcome for each proxy error code (ADR-052 §10). */
19
- const ERROR_MAP = {
20
- INVALID_PROXY_REQUEST: { status: 400, outcome: 'denied' },
21
- PROXY_NOT_ALLOWED: { status: 403, outcome: 'denied' },
22
- PAYLOAD_TOO_LARGE: { status: 413, outcome: 'too_large' },
23
- UNSUPPORTED_MEDIA_TYPE: { status: 415, outcome: 'denied' },
24
- PROXY_NOT_CONFIGURED: { status: 501, outcome: 'denied' },
25
- INVALID_CREDENTIALS: { status: 401, outcome: 'upstream_error' },
26
- RATE_LIMITED: { status: 429, outcome: 'upstream_error' },
27
- UPSTREAM_ERROR: { status: 502, outcome: 'upstream_error' },
28
- NETWORK_ERROR: { status: 502, outcome: 'upstream_error' },
29
- RESPONSE_TOO_LARGE: { status: 502, outcome: 'too_large' },
30
- TIMEOUT: { status: 504, outcome: 'timeout' },
31
- };
32
-
33
- function toBoom(error, extra = {}) {
34
- const mapping = ERROR_MAP[error.code] || { status: 502 };
35
- const boom = new Boom.Boom(error.message, {
36
- statusCode: mapping.status,
37
- data: {
38
- code: error.code,
39
- details: error.details,
40
- // Every proxy message is written for the caller (no URLs, no
41
- // credential material), including the 5xx ones.
42
- expose: true,
43
- proxy: true,
44
- ...extra,
45
- },
46
- });
47
- return boom;
48
- }
49
-
50
- const authHeaderNamesOf = (api) =>
51
- [api?.api_key_name, api?.API_KEY_NAME].filter(
52
- (name) => typeof name === 'string' && name
53
- );
54
-
55
- /**
56
- * POST /api/v2/entities/:entityId/proxy (ADR-052): calls the entity's API
57
- * through its module with the stored credential, inside the limits the app
58
- * and the module set.
59
- *
60
- * Order of checks: request shape and size, path rules, entity visibility in
61
- * the active organization (404), `use` access (403), the entity's scope
62
- * against `managementApi.proxy.scopes` (403), the module's allow-list (403,
63
- * deny by default), credential readiness (401), then the call through
64
- * Requester._proxyRequest. Every call,
65
- * allowed or denied, writes one audit record and one usage count. Bodies,
66
- * headers, query values and the raw path are never logged.
67
- */
68
- class ExecuteEntityProxyRequest {
69
- /**
70
- * @param {Object} params
71
- * @param {import('./get-entity-module-for-user').GetEntityModuleForUser} params.getEntityModuleForUser
72
- * @param {ReturnType<import('../../management-api/management-api-config').resolveManagementApiConfig>['proxy']} params.proxyConfig
73
- * @param {Object} [params.telemetry]
74
- * @param {() => number} [params.now]
75
- */
76
- constructor({ getEntityModuleForUser, proxyConfig, telemetry, now }) {
77
- this.getEntityModuleForUser = getEntityModuleForUser;
78
- this.proxyConfig = proxyConfig;
79
- this.telemetry = telemetry;
80
- this.now = now || Date.now;
81
- }
82
-
83
- /**
84
- * @param {string} entityId
85
- * @param {Object} user - authenticated User
86
- * @param {Object} request - { method, path, query?, headers?, body? }
87
- * @returns {Promise<{ status: number, body: { success: boolean, status: number, headers: Object, data: unknown, dataEncoding?: string } }>}
88
- */
89
- async execute(entityId, user, request) {
90
- const started = this.now();
91
- const audit = {
92
- userId: user?.getId?.(),
93
- organizationId: user?.getOrganizationUser?.()?.id,
94
- entityId: String(entityId),
95
- method: typeof request?.method === 'string' ? request.method.toUpperCase() : undefined,
96
- requestBytes: 0,
97
- };
98
-
99
- try {
100
- const validated = validateProxyRequest(request, this.proxyConfig);
101
- audit.method = validated.method;
102
- audit.requestBytes = validated.requestBytes;
103
- const path = normalizeProxyPath(validated.path);
104
-
105
- // Visible in the active organization, or 404 (ADR-056 §3.6): the
106
- // same clauses the v2 lists use, so a missing entity, another
107
- // person's and one paired with another organization look alike.
108
- const { entity, definition, module } =
109
- await this.getEntityModuleForUser.execute(entityId, user);
110
- audit.module = definition.moduleName;
111
- this.assertProxyable(entityId, entity, definition, user);
112
-
113
- const credentialRef = entity.credential;
114
- const credentialId =
115
- credentialRef && typeof credentialRef === 'object'
116
- ? credentialRef.id ?? credentialRef._id
117
- : credentialRef;
118
- if (credentialId !== undefined && credentialId !== null) {
119
- audit.credentialId = String(credentialId);
120
- }
121
-
122
- const { rules } = resolveAllowRules(definition, this.proxyConfig.modules);
123
- const rule = matchAllowRule(rules, validated.method, path);
124
- if (!rule) {
125
- throw new ProxyRequestError(
126
- 'PROXY_NOT_ALLOWED',
127
- `Module ${definition.moduleName} does not allow ${validated.method} on this path`,
128
- { module: definition.moduleName, method: validated.method }
129
- );
130
- }
131
- audit.pattern = rule.path;
132
-
133
- const credential = entity.credential;
134
- if (!credential || (typeof credential === 'object' && credential.authIsValid === false)) {
135
- throw new ProxyRequestError(
136
- 'INVALID_CREDENTIALS',
137
- 'The entity has no usable credential; re-authorize it'
138
- );
139
- }
140
-
141
- const authHeaderNames = authHeaderNamesOf(module.api);
142
- const headers = filterRequestHeaders(validated.headers, {
143
- moduleHeaders: Array.isArray(definition.proxy?.headers) ? definition.proxy.headers : [],
144
- authHeaderNames,
145
- });
146
- if (validated.body !== undefined && !headers['content-type']) {
147
- headers['content-type'] = validated.bodyIsJson ? 'application/json' : 'text/plain';
148
- }
149
-
150
- const upstream = await module.api._proxyRequest({
151
- method: validated.method,
152
- path,
153
- query: validated.query,
154
- headers,
155
- body: validated.body,
156
- baseUrl: this.resolveBaseUrl(definition, module.api),
157
- timeoutMs: this.proxyConfig.timeoutMs,
158
- maxResponseBytes: this.proxyConfig.maxResponseBytes,
159
- isAllowedRedirect: (nextPath, nextMethod) =>
160
- Boolean(matchAllowRule(rules, nextMethod, nextPath)),
161
- });
162
- audit.upstreamStatus = upstream.status;
163
- audit.responseBytes = upstream.body?.length ?? 0;
164
-
165
- if (upstream.status === 429) {
166
- throw Object.assign(
167
- new ProxyRequestError('RATE_LIMITED', 'The upstream API is rate limiting this account', {
168
- upstreamStatus: 429,
169
- }),
170
- { retryAfter: upstream.headers['retry-after'] }
171
- );
172
- }
173
- if (upstream.status >= 500) {
174
- throw new ProxyRequestError('UPSTREAM_ERROR', 'The upstream API returned an error', {
175
- upstreamStatus: upstream.status,
176
- });
177
- }
178
-
179
- const decoded = decodeResponseBody(upstream.body, upstream.contentType, {
180
- binary: definition.proxy?.binary === true,
181
- });
182
- const result = {
183
- status: upstream.status,
184
- body: {
185
- success: upstream.status < 400,
186
- status: upstream.status,
187
- headers: filterResponseHeaders(upstream.headers, {
188
- redirectBlocked: upstream.redirectBlocked,
189
- authHeaderNames,
190
- }),
191
- data: decoded.data,
192
- ...(decoded.encoding && { dataEncoding: decoded.encoding }),
193
- },
194
- };
195
- this.record(audit, upstream.status < 400 ? 'ok' : 'upstream_error', started);
196
- return result;
197
- } catch (error) {
198
- if (error instanceof ProxyRequestError) {
199
- const { outcome = 'upstream_error' } = ERROR_MAP[error.code] || {};
200
- this.record(audit, outcome, started, error.code);
201
- throw toBoom(error, error.retryAfter ? { retryAfter: error.retryAfter } : {});
202
- }
203
- const notFound = error?.isBoom && error.output.statusCode === 404;
204
- this.record(
205
- audit,
206
- notFound ? 'denied' : 'error',
207
- started,
208
- error?.data?.code || (error?.isBoom ? undefined : 'INTERNAL_ERROR')
209
- );
210
- throw error;
211
- }
212
- }
213
-
214
- /**
215
- * ADR-056 §3.5: the caller needs `use` access to the entity in the active
216
- * organization, and the entity's scope must be one the app lets the proxy
217
- * accept. `access` and `scope` come from the description the v2 lists
218
- * return (GetEntityModuleForUser.describe), never from a second rule.
219
- *
220
- * Both refusals are 403 PROXY_NOT_ALLOWED: the caller can already see the
221
- * entity, so saying it exists leaks nothing. `details.reason` tells them
222
- * apart ('access' or 'scope').
223
- */
224
- assertProxyable(entityId, entity, definition, user) {
225
- const tenancy = this.getEntityModuleForUser.describe(entity, user);
226
- if (!tenancy) {
227
- // Not visible after all: the same 404 as a missing entity.
228
- throw Boom.notFound(`Entity ${entityId} not found`, {
229
- code: 'ENTITY_NOT_FOUND',
230
- });
231
- }
232
- if (!grantsUse(tenancy.access)) {
233
- throw new ProxyRequestError(
234
- 'PROXY_NOT_ALLOWED',
235
- 'Proxying through an entity needs use access to it; you can only view this one',
236
- { module: definition.moduleName, reason: 'access' }
237
- );
238
- }
239
- // Narrowest by default (§3.5): with no setting only individual
240
- // entities are proxied, because proxying through a shared credential
241
- // lets any member act on the organization's account.
242
- const acceptedScopes = this.proxyConfig.scopes ?? [SCOPES.INDIVIDUAL];
243
- if (!acceptedScopes.includes(tenancy.scope)) {
244
- throw new ProxyRequestError(
245
- 'PROXY_NOT_ALLOWED',
246
- `The entity proxy does not accept ${tenancy.scope} entities in this app`,
247
- { module: definition.moduleName, reason: 'scope', scope: tenancy.scope }
248
- );
249
- }
250
- }
251
-
252
- /** A module may pin its proxy base URL (string, or a function of the api). */
253
- resolveBaseUrl(definition, api) {
254
- const declared = definition.proxy?.baseUrl;
255
- if (typeof declared === 'function') return declared(api);
256
- if (typeof declared === 'string') return declared;
257
- return undefined;
258
- }
259
-
260
- /** One audit record (ADR-048) and one usage count (ADR-011) per call. */
261
- record(audit, outcome, started, reason) {
262
- const fields = {
263
- eventName: 'frigg.api.proxy.request',
264
- ...audit,
265
- outcome,
266
- durationMs: this.now() - started,
267
- ...(reason && { reason }),
268
- };
269
- if (outcome === 'ok' || outcome === 'upstream_error') {
270
- log.info('Entity proxy request', fields);
271
- } else {
272
- log.warn('Entity proxy request refused', fields);
273
- }
274
- try {
275
- (this.telemetry || getTelemetry()).count('frigg.api.proxy.requests', 1, {
276
- module: audit.module || 'unknown',
277
- method: audit.method || 'unknown',
278
- outcome,
279
- });
280
- } catch {
281
- // Telemetry must never break a request.
282
- }
283
- }
284
- }
285
-
286
- module.exports = { ExecuteEntityProxyRequest, ERROR_MAP };
@@ -1,100 +0,0 @@
1
- const Boom = require('@hapi/boom');
2
- const { findDefinition, getAuthStepCount } = require('./entity-types');
3
-
4
- const defaultCreateModule = (params) => {
5
- const { Module } = require('../module');
6
- return Module.create(params);
7
- };
8
-
9
- /**
10
- * Normalises what a module returns for a step into the v2 requirements
11
- * shape: `{ type, data }`. Modules either return `{ type, data }` already
12
- * (multi-step, JSON-schema forms) or a flat object such as the OAuth2
13
- * requester's `{ type: 'oauth2', url }`.
14
- */
15
- function normalizeRequirements(raw) {
16
- if (!raw || typeof raw !== 'object') return { type: 'custom', data: {} };
17
- if (raw.data && typeof raw.data === 'object') {
18
- return { ...raw, type: raw.type || 'custom' };
19
- }
20
- const { type, ...data } = raw;
21
- return { type: type || 'custom', data };
22
- }
23
-
24
- /**
25
- * Single-step requirements, from wherever the module declares them: a
26
- * requiredAuthMethods.getAuthorizationRequirements(api) (the form-based
27
- * API-key convention `frigg auth` uses), or the Api's own
28
- * getAuthorizationRequirements() (OAuth2Requester builds the authorize URL).
29
- */
30
- async function singleStepRequirements(definition, module) {
31
- const declared = definition.requiredAuthMethods?.getAuthorizationRequirements;
32
- if (typeof declared === 'function') return declared(module.api);
33
- if (typeof module.api?.getAuthorizationRequirements === 'function') {
34
- return module.api.getAuthorizationRequirements();
35
- }
36
- throw Boom.notImplemented(
37
- `Module ${definition.moduleName} declares no authorization requirements (add requiredAuthMethods.getAuthorizationRequirements)`,
38
- { code: 'REQUIREMENTS_NOT_DECLARED', expose: true }
39
- );
40
- }
41
-
42
- /**
43
- * What the caller must submit for one authorization step of an entity type
44
- * (Management API v2). Single-step modules use their Api's
45
- * getAuthorizationRequirements(); multi-step modules declare
46
- * getAuthStepCount() and getAuthRequirementsForStep(step) on their
47
- * definition (docs/MULTI_STEP_AUTH_MIGRATION_GUIDE.md).
48
- */
49
- class GetAuthorizationRequirements {
50
- /**
51
- * @param {Object} params
52
- * @param {Array<Object>} params.moduleDefinitions
53
- * @param {Function} [params.createModule]
54
- */
55
- constructor({ moduleDefinitions, createModule }) {
56
- this.moduleDefinitions = moduleDefinitions || [];
57
- this.createModule = createModule || defaultCreateModule;
58
- }
59
-
60
- /**
61
- * @param {Object} params
62
- * @param {string} params.entityType
63
- * @param {number} [params.step=1]
64
- * @param {string} [params.userId]
65
- * @param {string} [params.state] - OAuth state forwarded to the Api.
66
- * @returns {Promise<{type: string, data: Object, step: number, totalSteps: number, isMultiStep: boolean}>}
67
- */
68
- async execute({ entityType, step = 1, userId = null, state } = {}) {
69
- const definition = findDefinition(this.moduleDefinitions, entityType);
70
- const totalSteps = getAuthStepCount(definition);
71
-
72
- if (!Number.isInteger(step) || step < 1 || step > totalSteps) {
73
- throw Boom.badRequest(
74
- `step must be between 1 and ${totalSteps} for ${entityType}`,
75
- { code: 'INVALID_STEP' }
76
- );
77
- }
78
-
79
- let raw;
80
- if (typeof definition.getAuthRequirementsForStep === 'function') {
81
- raw = await definition.getAuthRequirementsForStep(step);
82
- } else {
83
- const module = await this.createModule({
84
- userId,
85
- definition,
86
- ...(state ? { state } : {}),
87
- });
88
- raw = await singleStepRequirements(definition, module);
89
- }
90
-
91
- return {
92
- ...normalizeRequirements(raw),
93
- step,
94
- totalSteps,
95
- isMultiStep: totalSteps > 1,
96
- };
97
- }
98
- }
99
-
100
- module.exports = { GetAuthorizationRequirements, normalizeRequirements };
@@ -1,113 +0,0 @@
1
- const Boom = require('@hapi/boom');
2
- const { describeRecord } = require('../scope-visibility');
3
- const { DEFAULT_SCOPE_POLICY } = require('../scope-policy');
4
- const { isEntityNotFound } = require('../repositories/entity-not-found');
5
-
6
- /**
7
- * True when `user` may act on records owned by `ownerId`. Uses the User
8
- * domain object's rule (individual or organisation user model) when present.
9
- * This is the owner-only rule: it ignores the organization a record belongs
10
- * to, so it no longer decides access to an entity or an integration
11
- * (modules/scope-visibility.js does). Credentials still use it.
12
- * @param {Object} user - authenticated User (or a plain { getId } double)
13
- * @param {string|number} ownerId
14
- */
15
- function userOwns(user, ownerId) {
16
- if (ownerId === undefined || ownerId === null || !user) return false;
17
- if (typeof user.ownsUserId === 'function') return user.ownsUserId(ownerId);
18
- return String(user.getId()) === String(ownerId);
19
- }
20
-
21
- const defaultCreateModule = (params) => {
22
- const { Module } = require('../module');
23
- return Module.create(params);
24
- };
25
-
26
- /**
27
- * Loads an entity the caller owns and builds its Module (API client
28
- * hydrated from the persisted entity and credential). Management API v2.
29
- *
30
- * A missing entity and one owned by someone else are the same 404, so ids
31
- * cannot be probed (ADR-052 §3).
32
- */
33
- class GetEntityModuleForUser {
34
- /**
35
- * @param {Object} params
36
- * @param {import('../repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
37
- * @param {Array<Object>} params.moduleDefinitions
38
- * @param {Function} [params.createModule] - builds a Module; injectable for tests.
39
- * @param {Object} [params.scopePolicy] - from createScopePolicy; with none the
40
- * app configures nothing (ADR-056 §3.1).
41
- */
42
- constructor({ moduleRepository, moduleDefinitions, createModule, scopePolicy }) {
43
- this.scopePolicy = scopePolicy || DEFAULT_SCOPE_POLICY;
44
- this.moduleRepository = moduleRepository;
45
- this.moduleDefinitions = moduleDefinitions || [];
46
- this.createModule = createModule || defaultCreateModule;
47
- }
48
-
49
- /**
50
- * @param {string} entityId
51
- * @param {Object} user - authenticated User
52
- * @returns {Promise<{ entity: Object, definition: Object, module: Object }>}
53
- */
54
- async execute(entityId, user) {
55
- const entity = await this.loadOwnedEntity(entityId, user);
56
- const definition = this.moduleDefinitions.find(
57
- (def) => def.moduleName === entity.moduleName
58
- );
59
- if (!definition) {
60
- throw Boom.notFound(
61
- `Entity type ${entity.moduleName} is not configured in this app`,
62
- { code: 'ENTITY_TYPE_NOT_FOUND' }
63
- );
64
- }
65
- const module = await this.createModule({
66
- userId: entity.userId,
67
- entity,
68
- definition,
69
- });
70
- return { entity, definition, module };
71
- }
72
-
73
- /**
74
- * The entity record, or a 404 when it is missing or the caller may not use
75
- * it: not theirs, or paired with another organization (ADR-056 §3.6). A
76
- * `global` entity is never the tenant's to load.
77
- */
78
- async loadOwnedEntity(entityId, user) {
79
- let entity = null;
80
- try {
81
- entity = await this.moduleRepository.findEntityById(entityId);
82
- } catch (error) {
83
- // Every adapter throws for a missing row, and a malformed id (e.g.
84
- // not an integer on Postgres) is "not found" too. Both must be the
85
- // 404 another tenant's entity gets, or the status says which ids
86
- // exist. Anything else is a real failure.
87
- if (
88
- isEntityNotFound(error) ||
89
- /Invalid ID|ObjectId|Malformed/i.test(error?.message || '')
90
- ) {
91
- entity = null;
92
- } else {
93
- throw error;
94
- }
95
- }
96
- if (!entity || !this.describe(entity, user)) {
97
- throw Boom.notFound(`Entity ${entityId} not found`, {
98
- code: 'ENTITY_NOT_FOUND',
99
- });
100
- }
101
- return entity;
102
- }
103
-
104
- /**
105
- * `{ scope, owner, organizationId, access }` of an entity to this caller,
106
- * or null when they may not see it (§3.4).
107
- */
108
- describe(entity, user) {
109
- return describeRecord(entity, this.scopePolicy.accessContext(user), 'entity');
110
- }
111
- }
112
-
113
- module.exports = { GetEntityModuleForUser, userOwns };
@@ -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 };