@friggframework/core 2.0.0--canary.663.8de669c.0 → 2.0.0--canary.690.3fe2b27.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 (189) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/CLAUDE.md +28 -0
  3. package/README.md +105 -0
  4. package/application/commands/integration-commands.js +20 -10
  5. package/application/commands/scheduler-commands.js +11 -7
  6. package/application/commands/user-commands.js +17 -5
  7. package/application/index.js +6 -2
  8. package/core/Worker.js +31 -7
  9. package/core/create-handler.js +9 -0
  10. package/credential/repositories/credential-repository-documentdb.js +34 -0
  11. package/credential/repositories/credential-repository-interface.js +15 -0
  12. package/credential/repositories/credential-repository-mongo.js +23 -0
  13. package/credential/repositories/credential-repository-postgres.js +28 -0
  14. package/credential/use-cases/credential-operations-for-user.js +202 -0
  15. package/credential/use-cases/reauthorize-credential-for-user.js +73 -0
  16. package/database/config.js +48 -24
  17. package/database/documentdb-utils.js +6 -1
  18. package/database/encryption/README.md +2 -0
  19. package/database/encryption/encryption-config.js +10 -31
  20. package/database/encryption/encryption-schema-registry.js +121 -24
  21. package/database/encryption/field-encryption-service.js +69 -5
  22. package/database/encryption/test-support/fake-ciphertext.js +15 -0
  23. package/database/organization-where.js +18 -0
  24. package/database/prisma.js +4 -2
  25. package/database/unique-violation.js +25 -0
  26. package/extensions/bootstrap-runner.js +43 -0
  27. package/extensions/extension-loader.js +187 -0
  28. package/extensions/index.js +41 -0
  29. package/extensions/initialize-app.js +123 -0
  30. package/extensions/route-mounter.js +103 -0
  31. package/extensions/schema-composer.js +188 -0
  32. package/generated/prisma-mongodb/edge.js +43 -4
  33. package/generated/prisma-mongodb/index-browser.js +40 -1
  34. package/generated/prisma-mongodb/index.d.ts +4761 -133
  35. package/generated/prisma-mongodb/index.js +43 -4
  36. package/generated/prisma-mongodb/package.json +1 -1
  37. package/generated/prisma-mongodb/schema.prisma +92 -0
  38. package/generated/prisma-mongodb/wasm.js +43 -4
  39. package/generated/prisma-postgresql/edge.js +43 -4
  40. package/generated/prisma-postgresql/index-browser.js +40 -1
  41. package/generated/prisma-postgresql/index.d.ts +4961 -28
  42. package/generated/prisma-postgresql/index.js +43 -4
  43. package/generated/prisma-postgresql/package.json +1 -1
  44. package/generated/prisma-postgresql/schema.prisma +87 -0
  45. package/generated/prisma-postgresql/wasm.js +43 -4
  46. package/handlers/app-definition-loader.js +128 -19
  47. package/handlers/app-handler-helpers.js +25 -3
  48. package/handlers/backend-utils.js +31 -25
  49. package/handlers/middleware/admin-auth.js +14 -1
  50. package/handlers/routers/auth.js +46 -10
  51. package/handlers/routers/health.js +13 -4
  52. package/handlers/routers/integration-defined-routers.js +144 -92
  53. package/handlers/routers/integration-webhook-routers.js +102 -64
  54. package/handlers/workers/integration-defined-workers.js +5 -2
  55. package/index.js +65 -1
  56. package/infrastructure/scheduler/index.js +19 -6
  57. package/infrastructure/scheduler/netlify-scheduler-adapter.js +216 -0
  58. package/infrastructure/scheduler/scheduled-job-repository.js +118 -0
  59. package/infrastructure/scheduler/scheduler-service-factory.js +55 -7
  60. package/integrations/index.js +1 -0
  61. package/integrations/integration-router.js +131 -96
  62. package/integrations/repositories/integration-not-found.js +14 -0
  63. package/integrations/repositories/integration-repository-documentdb.js +35 -3
  64. package/integrations/repositories/integration-repository-interface.js +17 -1
  65. package/integrations/repositories/integration-repository-mongo.js +59 -76
  66. package/integrations/repositories/integration-repository-postgres.js +62 -76
  67. package/integrations/schedule-config.js +80 -0
  68. package/integrations/tests/doubles/test-integration-repository.js +12 -1
  69. package/integrations/use-cases/create-integration.js +55 -20
  70. package/integrations/use-cases/dispatch-ongoing-syncs.js +100 -0
  71. package/integrations/use-cases/get-integrations-for-user.js +80 -40
  72. package/integrations/use-cases/index.js +7 -1
  73. package/integrations/use-cases/integration-operations-for-user.js +256 -0
  74. package/integrations/use-cases/resolve-integration-ownership.js +177 -0
  75. package/integrations/utils/map-integration-dto.js +43 -14
  76. package/management-api/create-management-api-router.js +49 -0
  77. package/management-api/error-response.js +116 -0
  78. package/management-api/management-api-config.js +151 -0
  79. package/management-api/meta-router.js +76 -0
  80. package/management-api/openapi/build-openapi.js +144 -0
  81. package/management-api/openapi/components.js +415 -0
  82. package/management-api/openapi/v1-operations.js +83 -0
  83. package/management-api/openapi/v2-operations.js +264 -0
  84. package/management-api/route-registry.js +411 -0
  85. package/management-api/test-support/http-client.js +39 -0
  86. package/management-api/use-cases/get-management-api-meta.js +57 -0
  87. package/management-api/v1-deprecation.js +120 -0
  88. package/management-api/v2/create-v2-router.js +85 -0
  89. package/management-api/v2/dependencies.js +281 -0
  90. package/management-api/v2/dto.js +143 -0
  91. package/management-api/v2/handlers/authorization.js +94 -0
  92. package/management-api/v2/handlers/credentials.js +33 -0
  93. package/management-api/v2/handlers/entities.js +77 -0
  94. package/management-api/v2/handlers/integrations.js +128 -0
  95. package/management-api/v2/handlers/proxy.js +34 -0
  96. package/management-api/v2/request.js +85 -0
  97. package/management-api/v2/test-support/fake-dependencies.js +103 -0
  98. package/modules/domain/authorization-session.js +144 -0
  99. package/modules/entity-scope.js +15 -0
  100. package/modules/entity-type-registry.js +311 -0
  101. package/modules/index.js +14 -0
  102. package/modules/module-factory.js +12 -0
  103. package/modules/module.js +53 -2
  104. package/modules/proxy/proxy-bases.js +169 -0
  105. package/modules/proxy/proxy-errors.js +31 -0
  106. package/modules/proxy/proxy-path.js +183 -0
  107. package/modules/proxy/proxy-policy.js +277 -0
  108. package/modules/repositories/authorization-session-repository-documentdb.js +112 -0
  109. package/modules/repositories/authorization-session-repository-factory.js +31 -0
  110. package/modules/repositories/authorization-session-repository-interface.js +47 -0
  111. package/modules/repositories/authorization-session-repository-prisma.js +87 -0
  112. package/modules/repositories/entity-not-found.js +18 -0
  113. package/modules/repositories/module-repository-documentdb.js +51 -6
  114. package/modules/repositories/module-repository-interface.js +19 -2
  115. package/modules/repositories/module-repository-mongo.js +67 -74
  116. package/modules/repositories/module-repository-postgres.js +66 -74
  117. package/modules/repositories/module-repository.js +2 -1
  118. package/modules/requester/proxy-request.js +245 -0
  119. package/modules/requester/requester.js +35 -5
  120. package/modules/scope-config.js +192 -0
  121. package/modules/scope-policy.js +112 -0
  122. package/modules/scope-resolution.js +288 -0
  123. package/modules/scope-visibility.js +247 -0
  124. package/modules/tests/doubles/in-memory-authorization-session-repository.js +45 -0
  125. package/modules/tests/doubles/ownership-matching.js +18 -0
  126. package/modules/use-cases/authorize-entity-for-user.js +61 -0
  127. package/modules/use-cases/create-entity-from-credential.js +113 -0
  128. package/modules/use-cases/entity-operations-for-user.js +162 -0
  129. package/modules/use-cases/entity-types.js +139 -0
  130. package/modules/use-cases/execute-entity-proxy-request.js +331 -0
  131. package/modules/use-cases/get-authorization-requirements.js +100 -0
  132. package/modules/use-cases/get-entities-for-user.js +26 -13
  133. package/modules/use-cases/get-entity-module-for-user.js +113 -0
  134. package/modules/use-cases/get-entity-options-by-id.js +10 -4
  135. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  136. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  137. package/modules/use-cases/get-module.js +10 -4
  138. package/modules/use-cases/manage-access.js +21 -0
  139. package/modules/use-cases/multi-step-authorization.js +329 -0
  140. package/modules/use-cases/process-authorization-callback.js +53 -19
  141. package/modules/use-cases/refresh-entity-options.js +10 -4
  142. package/modules/use-cases/test-module-auth.js +10 -4
  143. package/package.json +6 -5
  144. package/prisma-mongodb/schema.prisma +92 -0
  145. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +28 -0
  146. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +26 -0
  147. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +25 -0
  148. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +28 -0
  149. package/prisma-postgresql/schema.prisma +87 -0
  150. package/providers/index.js +23 -0
  151. package/providers/resolve-provider.js +93 -0
  152. package/providers/runtime-detection.js +124 -0
  153. package/queues/index.js +25 -0
  154. package/queues/providers/index.js +11 -0
  155. package/queues/providers/netlify-background-provider.js +150 -0
  156. package/queues/providers/qstash-queue-provider.js +219 -0
  157. package/queues/providers/sqs-queue-provider.js +70 -0
  158. package/queues/queue-client-interface.js +55 -0
  159. package/queues/queue-message-auth.js +193 -0
  160. package/queues/queue-provider-factory.js +101 -0
  161. package/queues/queue-provider.js +65 -0
  162. package/queues/sqs-queue-client.js +81 -0
  163. package/types/index.d.ts +2 -0
  164. package/types/modules/index.d.ts +214 -0
  165. package/types/user/index.d.ts +134 -0
  166. package/user/adopter-jwt-config.js +177 -0
  167. package/user/adopter-jwt-errors.js +59 -0
  168. package/user/adopter-token-verifier.js +122 -0
  169. package/user/app-user-helpers.js +97 -0
  170. package/user/create-user-authentication.js +64 -0
  171. package/user/membership.js +51 -0
  172. package/user/repositories/organization-membership-record.js +19 -0
  173. package/user/repositories/organization-membership-repository-documentdb.js +106 -0
  174. package/user/repositories/organization-membership-repository-factory.js +42 -0
  175. package/user/repositories/organization-membership-repository-interface.js +57 -0
  176. package/user/repositories/organization-membership-repository-mongo.js +13 -0
  177. package/user/repositories/organization-membership-repository-postgres.js +29 -0
  178. package/user/repositories/organization-membership-repository-prisma.js +81 -0
  179. package/user/repositories/user-repository-documentdb.js +27 -2
  180. package/user/repositories/user-repository-interface.js +18 -0
  181. package/user/repositories/user-repository-mongo.js +24 -0
  182. package/user/repositories/user-repository-postgres.js +18 -0
  183. package/user/tests/doubles/adopter-jwt-fixtures.js +220 -0
  184. package/user/use-cases/authenticate-user.js +7 -1
  185. package/user/use-cases/ensure-organization-membership.js +92 -0
  186. package/user/use-cases/find-individual-users-by-organization.js +54 -0
  187. package/user/use-cases/get-user-from-adopter-jwt.js +95 -124
  188. package/user/use-cases/get-user-from-x-frigg-headers.js +83 -80
  189. package/user/user.js +64 -1
@@ -0,0 +1,331 @@
1
+ const Boom = require('@hapi/boom');
2
+ const { getLogger } = require('../../logs');
3
+ const { getTelemetry } = require('../../telemetry/telemetry-runtime');
4
+ const { ProxyRequestError, ProxyConfigError } = 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 { DEFAULT_BASE, resolveModuleBases } = require('../proxy/proxy-bases');
9
+ const {
10
+ validateProxyRequest,
11
+ resolveAllowRules,
12
+ filterRequestHeaders,
13
+ filterResponseHeaders,
14
+ decodeResponseBody,
15
+ } = require('../proxy/proxy-policy');
16
+
17
+ const log = getLogger('frigg.api.proxy');
18
+
19
+ /** HTTP status and audit outcome for each proxy error code (ADR-052 §10). */
20
+ const ERROR_MAP = {
21
+ INVALID_PROXY_REQUEST: { status: 400, outcome: 'denied' },
22
+ PROXY_UNKNOWN_BASE: { status: 400, outcome: 'denied' },
23
+ PROXY_NOT_ALLOWED: { status: 403, outcome: 'denied' },
24
+ PAYLOAD_TOO_LARGE: { status: 413, outcome: 'too_large' },
25
+ UNSUPPORTED_MEDIA_TYPE: { status: 415, outcome: 'denied' },
26
+ PROXY_NOT_CONFIGURED: { status: 501, outcome: 'denied' },
27
+ INVALID_CREDENTIALS: { status: 401, outcome: 'upstream_error' },
28
+ RATE_LIMITED: { status: 429, outcome: 'upstream_error' },
29
+ UPSTREAM_ERROR: { status: 502, outcome: 'upstream_error' },
30
+ NETWORK_ERROR: { status: 502, outcome: 'upstream_error' },
31
+ RESPONSE_TOO_LARGE: { status: 502, outcome: 'too_large' },
32
+ TIMEOUT: { status: 504, outcome: 'timeout' },
33
+ };
34
+
35
+ function toBoom(error, extra = {}) {
36
+ const mapping = ERROR_MAP[error.code] || { status: 502 };
37
+ const boom = new Boom.Boom(error.message, {
38
+ statusCode: mapping.status,
39
+ data: {
40
+ code: error.code,
41
+ details: error.details,
42
+ // Every proxy message is written for the caller (no URLs, no
43
+ // credential material), including the 5xx ones.
44
+ expose: true,
45
+ proxy: true,
46
+ ...extra,
47
+ },
48
+ });
49
+ return boom;
50
+ }
51
+
52
+ const authHeaderNamesOf = (api) =>
53
+ [api?.api_key_name, api?.API_KEY_NAME].filter(
54
+ (name) => typeof name === 'string' && name
55
+ );
56
+
57
+ /**
58
+ * POST /api/v2/entities/:entityId/proxy (ADR-052): calls the entity's API
59
+ * through its module with the stored credential, inside the limits the app
60
+ * and the module set.
61
+ *
62
+ * Order of checks: request shape and size, path rules, entity visibility in
63
+ * the active organization (404), `use` access (403), the entity's scope
64
+ * against `managementApi.proxy.scopes` (403), the module's allow-list (403,
65
+ * deny by default), credential readiness (401), then the call through
66
+ * Requester._proxyRequest. Every call,
67
+ * allowed or denied, writes one audit record and one usage count. Bodies,
68
+ * headers, query values and the raw path are never logged.
69
+ */
70
+ class ExecuteEntityProxyRequest {
71
+ /**
72
+ * @param {Object} params
73
+ * @param {import('./get-entity-module-for-user').GetEntityModuleForUser} params.getEntityModuleForUser
74
+ * @param {ReturnType<import('../../management-api/management-api-config').resolveManagementApiConfig>['proxy']} params.proxyConfig
75
+ * @param {Object} [params.telemetry]
76
+ * @param {() => number} [params.now]
77
+ */
78
+ constructor({ getEntityModuleForUser, proxyConfig, telemetry, now }) {
79
+ this.getEntityModuleForUser = getEntityModuleForUser;
80
+ this.proxyConfig = proxyConfig;
81
+ this.telemetry = telemetry;
82
+ this.now = now || Date.now;
83
+ }
84
+
85
+ /**
86
+ * @param {string} entityId
87
+ * @param {Object} user - authenticated User
88
+ * @param {Object} request - { method, path, query?, headers?, body? }
89
+ * @returns {Promise<{ status: number, body: { success: boolean, status: number, headers: Object, data: unknown, dataEncoding?: string } }>}
90
+ */
91
+ async execute(entityId, user, request) {
92
+ const started = this.now();
93
+ const audit = {
94
+ userId: user?.getId?.(),
95
+ organizationId: user?.getOrganizationUser?.()?.id,
96
+ entityId: String(entityId),
97
+ method: typeof request?.method === 'string' ? request.method.toUpperCase() : undefined,
98
+ requestBytes: 0,
99
+ };
100
+
101
+ try {
102
+ const validated = validateProxyRequest(request, this.proxyConfig);
103
+ audit.method = validated.method;
104
+ audit.requestBytes = validated.requestBytes;
105
+ const path = normalizeProxyPath(validated.path);
106
+
107
+ // Visible in the active organization, or 404 (ADR-056 §3.6): the
108
+ // same clauses the v2 lists use, so a missing entity, another
109
+ // person's and one paired with another organization look alike.
110
+ const { entity, definition, module } =
111
+ await this.getEntityModuleForUser.execute(entityId, user);
112
+ audit.module = definition.moduleName;
113
+ this.assertProxyable(entityId, entity, definition, user);
114
+
115
+ // The base is a name the module declared; the host comes from the
116
+ // module's declaration, never from the request.
117
+ const base = validated.base ?? DEFAULT_BASE;
118
+ audit.base = base;
119
+ const bases = this.basesOf(definition);
120
+ if (!bases.names.includes(base)) {
121
+ throw new ProxyRequestError(
122
+ 'PROXY_UNKNOWN_BASE',
123
+ `Module ${definition.moduleName} has no base named ${base}; use one of: ${bases.names.join(', ')}`,
124
+ { module: definition.moduleName, base, bases: bases.names }
125
+ );
126
+ }
127
+
128
+ const credentialRef = entity.credential;
129
+ const credentialId =
130
+ credentialRef && typeof credentialRef === 'object'
131
+ ? credentialRef.id ?? credentialRef._id
132
+ : credentialRef;
133
+ if (credentialId !== undefined && credentialId !== null) {
134
+ audit.credentialId = String(credentialId);
135
+ }
136
+
137
+ const { rules } = resolveAllowRules(definition, this.proxyConfig.modules);
138
+ const rule = matchAllowRule(rules, validated.method, path, base);
139
+ if (!rule) {
140
+ throw new ProxyRequestError(
141
+ 'PROXY_NOT_ALLOWED',
142
+ `Module ${definition.moduleName} does not allow ${validated.method} on this path` +
143
+ // Single-base modules keep the message they always had.
144
+ (bases.names.length > 1 ? ` of base ${base}` : ''),
145
+ { module: definition.moduleName, method: validated.method, base }
146
+ );
147
+ }
148
+ audit.pattern = rule.path;
149
+
150
+ const credential = entity.credential;
151
+ if (!credential || (typeof credential === 'object' && credential.authIsValid === false)) {
152
+ throw new ProxyRequestError(
153
+ 'INVALID_CREDENTIALS',
154
+ 'The entity has no usable credential; re-authorize it'
155
+ );
156
+ }
157
+
158
+ const authHeaderNames = authHeaderNamesOf(module.api);
159
+ const headers = filterRequestHeaders(validated.headers, {
160
+ moduleHeaders: Array.isArray(definition.proxy?.headers) ? definition.proxy.headers : [],
161
+ authHeaderNames,
162
+ });
163
+ if (validated.body !== undefined && !headers['content-type']) {
164
+ headers['content-type'] = validated.bodyIsJson ? 'application/json' : 'text/plain';
165
+ }
166
+
167
+ const upstream = await module.api._proxyRequest({
168
+ method: validated.method,
169
+ path,
170
+ query: validated.query,
171
+ headers,
172
+ body: validated.body,
173
+ baseUrl: this.resolveBaseUrl(bases, module.api, base),
174
+ timeoutMs: this.proxyConfig.timeoutMs,
175
+ maxResponseBytes: this.proxyConfig.maxResponseBytes,
176
+ isAllowedRedirect: (nextPath, nextMethod) =>
177
+ Boolean(matchAllowRule(rules, nextMethod, nextPath, base)),
178
+ });
179
+ audit.upstreamStatus = upstream.status;
180
+ audit.responseBytes = upstream.body?.length ?? 0;
181
+
182
+ if (upstream.status === 429) {
183
+ throw Object.assign(
184
+ new ProxyRequestError('RATE_LIMITED', 'The upstream API is rate limiting this account', {
185
+ upstreamStatus: 429,
186
+ }),
187
+ { retryAfter: upstream.headers['retry-after'] }
188
+ );
189
+ }
190
+ if (upstream.status >= 500) {
191
+ throw new ProxyRequestError('UPSTREAM_ERROR', 'The upstream API returned an error', {
192
+ upstreamStatus: upstream.status,
193
+ });
194
+ }
195
+
196
+ const decoded = decodeResponseBody(upstream.body, upstream.contentType, {
197
+ binary: definition.proxy?.binary === true,
198
+ });
199
+ const result = {
200
+ status: upstream.status,
201
+ body: {
202
+ success: upstream.status < 400,
203
+ status: upstream.status,
204
+ headers: filterResponseHeaders(upstream.headers, {
205
+ redirectBlocked: upstream.redirectBlocked,
206
+ authHeaderNames,
207
+ }),
208
+ data: decoded.data,
209
+ ...(decoded.encoding && { dataEncoding: decoded.encoding }),
210
+ },
211
+ };
212
+ this.record(audit, upstream.status < 400 ? 'ok' : 'upstream_error', started);
213
+ return result;
214
+ } catch (error) {
215
+ if (error instanceof ProxyRequestError) {
216
+ const { outcome = 'upstream_error' } = ERROR_MAP[error.code] || {};
217
+ this.record(audit, outcome, started, error.code);
218
+ throw toBoom(error, error.retryAfter ? { retryAfter: error.retryAfter } : {});
219
+ }
220
+ const notFound = error?.isBoom && error.output.statusCode === 404;
221
+ this.record(
222
+ audit,
223
+ notFound ? 'denied' : 'error',
224
+ started,
225
+ error?.data?.code || (error?.isBoom ? undefined : 'INTERNAL_ERROR')
226
+ );
227
+ throw error;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * ADR-056 §3.5: the caller needs `use` access to the entity in the active
233
+ * organization, and the entity's scope must be one the app lets the proxy
234
+ * accept. `access` and `scope` come from the description the v2 lists
235
+ * return (GetEntityModuleForUser.describe), never from a second rule.
236
+ *
237
+ * Both refusals are 403 PROXY_NOT_ALLOWED: the caller can already see the
238
+ * entity, so saying it exists leaks nothing. `details.reason` tells them
239
+ * apart ('access' or 'scope').
240
+ */
241
+ assertProxyable(entityId, entity, definition, user) {
242
+ const tenancy = this.getEntityModuleForUser.describe(entity, user);
243
+ if (!tenancy) {
244
+ // Not visible after all: the same 404 as a missing entity.
245
+ throw Boom.notFound(`Entity ${entityId} not found`, {
246
+ code: 'ENTITY_NOT_FOUND',
247
+ });
248
+ }
249
+ if (!grantsUse(tenancy.access)) {
250
+ throw new ProxyRequestError(
251
+ 'PROXY_NOT_ALLOWED',
252
+ 'Proxying through an entity needs use access to it; you can only view this one',
253
+ { module: definition.moduleName, reason: 'access' }
254
+ );
255
+ }
256
+ // Narrowest by default (§3.5): with no setting only individual
257
+ // entities are proxied, because proxying through a shared credential
258
+ // lets any member act on the organization's account.
259
+ const acceptedScopes = this.proxyConfig.scopes ?? [SCOPES.INDIVIDUAL];
260
+ if (!acceptedScopes.includes(tenancy.scope)) {
261
+ throw new ProxyRequestError(
262
+ 'PROXY_NOT_ALLOWED',
263
+ `The entity proxy does not accept ${tenancy.scope} entities in this app`,
264
+ { module: definition.moduleName, reason: 'scope', scope: tenancy.scope }
265
+ );
266
+ }
267
+ }
268
+
269
+ /**
270
+ * The module's bases. Load already validated the definition
271
+ * (assertProxyConfig), so this only fails for a definition that skipped
272
+ * load; that is a configuration fault (501), never an unmapped 500.
273
+ */
274
+ basesOf(definition) {
275
+ try {
276
+ return resolveModuleBases(definition);
277
+ } catch (error) {
278
+ if (!(error instanceof ProxyConfigError)) throw error;
279
+ throw new ProxyRequestError(
280
+ 'PROXY_NOT_CONFIGURED',
281
+ `Module ${definition.moduleName} has invalid proxy settings`
282
+ );
283
+ }
284
+ }
285
+
286
+ /**
287
+ * The URL of the named base. A base the module declared never falls back
288
+ * to the requester's own host (that would send the module's token to a
289
+ * host the module did not name); only a module that declares nothing at
290
+ * all uses the requester's base URL, signalled by undefined.
291
+ */
292
+ resolveBaseUrl(bases, api, name) {
293
+ const declared = bases.values.get(name);
294
+ if (!bases.declared) return undefined;
295
+ const url = typeof declared === 'function' ? declared(api) : declared;
296
+ if (typeof url !== 'string' || url === '') {
297
+ throw new ProxyRequestError(
298
+ 'PROXY_NOT_CONFIGURED',
299
+ `The module declares no usable URL for base ${name}`
300
+ );
301
+ }
302
+ return url;
303
+ }
304
+
305
+ /** One audit record (ADR-048) and one usage count (ADR-011) per call. */
306
+ record(audit, outcome, started, reason) {
307
+ const fields = {
308
+ eventName: 'frigg.api.proxy.request',
309
+ ...audit,
310
+ outcome,
311
+ durationMs: this.now() - started,
312
+ ...(reason && { reason }),
313
+ };
314
+ if (outcome === 'ok' || outcome === 'upstream_error') {
315
+ log.info('Entity proxy request', fields);
316
+ } else {
317
+ log.warn('Entity proxy request refused', fields);
318
+ }
319
+ try {
320
+ (this.telemetry || getTelemetry()).count('frigg.api.proxy.requests', 1, {
321
+ module: audit.module || 'unknown',
322
+ method: audit.method || 'unknown',
323
+ outcome,
324
+ });
325
+ } catch {
326
+ // Telemetry must never break a request.
327
+ }
328
+ }
329
+ }
330
+
331
+ module.exports = { ExecuteEntityProxyRequest, ERROR_MAP };
@@ -0,0 +1,100 @@
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,8 +1,11 @@
1
1
  const { Module } = require('../module');
2
2
  const { mapModuleClassToModuleDTO } = require('../utils/map-module-dto');
3
+ const { describeRecord, visibilityClauses } = require('../scope-visibility');
4
+ const { DEFAULT_SCOPE_POLICY } = require('../scope-policy');
3
5
 
4
6
  class GetEntitiesForUser {
5
- constructor({ moduleRepository, moduleDefinitions }) {
7
+ constructor({ moduleRepository, moduleDefinitions, scopePolicy }) {
8
+ this.scopePolicy = scopePolicy || DEFAULT_SCOPE_POLICY;
6
9
  this.moduleRepository = moduleRepository;
7
10
 
8
11
  this.definitionMap = new Map();
@@ -11,21 +14,31 @@ class GetEntitiesForUser {
11
14
  }
12
15
  }
13
16
 
14
- async execute(userId) {
15
- const entities = await this.moduleRepository.findEntitiesByUserId(
16
- userId
17
+ /**
18
+ * The entities a `User` may see in the active organization (ADR-056 §3.6).
19
+ * @param {Object} user - authenticated User
20
+ */
21
+ async execute(user) {
22
+ const ctx = this.scopePolicy.accessContext(user);
23
+ const found = await this.moduleRepository.findEntitiesByOwnership(
24
+ visibilityClauses(ctx, 'entity')
25
+ );
26
+ const entities = (found || []).filter((entity) =>
27
+ describeRecord(entity, ctx, 'entity')
17
28
  );
18
29
 
19
- return entities.map((entity) => {
20
- const definition = this.definitionMap.get(entity.moduleName);
30
+ return Promise.all(
31
+ entities.map(async (entity) => {
32
+ const definition = this.definitionMap.get(entity.moduleName);
21
33
 
22
- const moduleInstance = new Module({
23
- userId,
24
- definition: definition,
25
- entity: entity,
26
- });
27
- return mapModuleClassToModuleDTO(moduleInstance);
28
- });
34
+ const moduleInstance = await Module.create({
35
+ userId: entity.userId,
36
+ definition: definition,
37
+ entity: entity,
38
+ });
39
+ return mapModuleClassToModuleDTO(moduleInstance);
40
+ })
41
+ );
29
42
  }
30
43
  }
31
44
 
@@ -0,0 +1,113 @@
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,4 +1,5 @@
1
1
  const { Module } = require('../module');
2
+ const { DEFAULT_SCOPE_POLICY } = require('../scope-policy');
2
3
 
3
4
  class GetEntityOptionsById {
4
5
  /**
@@ -6,9 +7,11 @@ class GetEntityOptionsById {
6
7
  * @param {import('../repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
7
8
  * @param {} params.moduleDefinitions
8
9
  */
9
- constructor({ moduleRepository, moduleDefinitions }) {
10
+ constructor({ moduleRepository, moduleDefinitions, scopePolicy }) {
10
11
  this.moduleRepository = moduleRepository;
11
12
  this.moduleDefinitions = moduleDefinitions;
13
+ // Who may load an entity follows its scope (ADR-056 §3.6).
14
+ this.scopePolicy = scopePolicy || DEFAULT_SCOPE_POLICY;
12
15
  }
13
16
 
14
17
  /**
@@ -35,7 +38,7 @@ class GetEntityOptionsById {
35
38
 
36
39
  // Validate entity ownership
37
40
  const isOwned = typeof userIdOrUser === 'object' && userIdOrUser?.ownsUserId
38
- ? userIdOrUser.ownsUserId(entity.userId)
41
+ ? this.scopePolicy.canUseEntity(userIdOrUser, entity)
39
42
  : entity.userId?.toString() === userId?.toString();
40
43
 
41
44
  if (!isOwned) {
@@ -57,8 +60,11 @@ class GetEntityOptionsById {
57
60
  );
58
61
  }
59
62
 
60
- const module = new Module({
61
- userId,
63
+ // Built for the entity's OWNER, not the caller: a caller may use an
64
+ // organization's entity, and a token refresh during this call must
65
+ // update the owner's credential, not create one under the caller.
66
+ const module = await Module.create({
67
+ userId: entity.userId ?? userId,
62
68
  entity,
63
69
  definition: moduleDefinition,
64
70
  });
@@ -21,7 +21,7 @@ class GetEntityOptionsByType {
21
21
  if (!moduleDefinition) {
22
22
  throw new Error(`Module definition not found for type: ${type}`);
23
23
  }
24
- const moduleInstance = new Module({
24
+ const moduleInstance = await Module.create({
25
25
  userId,
26
26
  definition: moduleDefinition,
27
27
  });
@@ -23,7 +23,7 @@ class GetModuleInstanceFromType {
23
23
  if (!moduleDefinition) {
24
24
  throw new Error(`Module definition not found for type: ${type}`);
25
25
  }
26
- return new Module({
26
+ return Module.create({
27
27
  userId,
28
28
  definition: moduleDefinition,
29
29
  state: options.state,