@friggframework/core 2.0.0--canary.690.d043f23.0 → 2.0.0--canary.691.2fd013b.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 (193) 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 +0 -2
  15. package/database/encryption/encryption-schema-registry.js +12 -93
  16. package/database/prisma.js +2 -4
  17. package/errors/index.js +4 -0
  18. package/errors/mapping-already-exists-error.js +14 -0
  19. package/generated/prisma-mongodb/edge.js +4 -43
  20. package/generated/prisma-mongodb/index-browser.js +1 -40
  21. package/generated/prisma-mongodb/index.d.ts +111 -4739
  22. package/generated/prisma-mongodb/index.js +4 -43
  23. package/generated/prisma-mongodb/package.json +1 -1
  24. package/generated/prisma-mongodb/schema.prisma +0 -92
  25. package/generated/prisma-mongodb/wasm.js +4 -43
  26. package/generated/prisma-postgresql/edge.js +4 -43
  27. package/generated/prisma-postgresql/index-browser.js +1 -40
  28. package/generated/prisma-postgresql/index.d.ts +33 -4966
  29. package/generated/prisma-postgresql/index.js +4 -43
  30. package/generated/prisma-postgresql/package.json +1 -1
  31. package/generated/prisma-postgresql/schema.prisma +0 -87
  32. package/generated/prisma-postgresql/wasm.js +4 -43
  33. package/handlers/WEBHOOKS.md +29 -0
  34. package/handlers/app-definition-loader.js +19 -118
  35. package/handlers/app-handler-helpers.js +3 -25
  36. package/handlers/backend-utils.js +25 -31
  37. package/handlers/middleware/admin-auth.js +1 -14
  38. package/handlers/routers/auth.js +10 -46
  39. package/handlers/routers/health.js +4 -11
  40. package/handlers/routers/integration-defined-routers.js +92 -144
  41. package/handlers/routers/integration-webhook-routers.js +64 -102
  42. package/handlers/workers/integration-defined-workers.js +2 -5
  43. package/index.js +3 -63
  44. package/infrastructure/scheduler/index.js +6 -19
  45. package/infrastructure/scheduler/scheduler-service-factory.js +7 -55
  46. package/integrations/index.js +0 -1
  47. package/integrations/integration-base.js +29 -0
  48. package/integrations/integration-router.js +96 -131
  49. package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
  50. package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
  51. package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
  52. package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
  53. package/integrations/repositories/integration-mapping-repository.js +29 -0
  54. package/integrations/repositories/integration-repository-documentdb.js +3 -35
  55. package/integrations/repositories/integration-repository-interface.js +1 -17
  56. package/integrations/repositories/integration-repository-mongo.js +77 -60
  57. package/integrations/repositories/integration-repository-postgres.js +76 -62
  58. package/integrations/repositories/process-repository-mongo.js +1 -1
  59. package/integrations/tests/doubles/test-integration-repository.js +1 -12
  60. package/integrations/use-cases/create-integration.js +20 -55
  61. package/integrations/use-cases/get-integrations-for-user.js +40 -80
  62. package/integrations/use-cases/index.js +1 -5
  63. package/integrations/utils/map-integration-dto.js +14 -43
  64. package/modules/index.js +0 -14
  65. package/modules/module-factory.js +0 -12
  66. package/modules/module.js +2 -53
  67. package/modules/repositories/module-repository-documentdb.js +6 -51
  68. package/modules/repositories/module-repository-interface.js +2 -19
  69. package/modules/repositories/module-repository-mongo.js +74 -67
  70. package/modules/repositories/module-repository-postgres.js +74 -66
  71. package/modules/repositories/module-repository.js +1 -2
  72. package/modules/requester/requester.js +2 -27
  73. package/modules/use-cases/get-entities-for-user.js +13 -26
  74. package/modules/use-cases/get-entity-options-by-id.js +4 -10
  75. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  76. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  77. package/modules/use-cases/get-module.js +4 -10
  78. package/modules/use-cases/process-authorization-callback.js +19 -53
  79. package/modules/use-cases/refresh-entity-options.js +4 -10
  80. package/modules/use-cases/test-module-auth.js +4 -10
  81. package/package.json +5 -6
  82. package/prisma-mongodb/schema.prisma +0 -92
  83. package/prisma-postgresql/schema.prisma +0 -87
  84. package/queues/index.js +0 -25
  85. package/types/index.d.ts +0 -2
  86. package/user/repositories/user-repository-documentdb.js +2 -27
  87. package/user/repositories/user-repository-interface.js +0 -18
  88. package/user/repositories/user-repository-mongo.js +0 -24
  89. package/user/repositories/user-repository-postgres.js +0 -18
  90. package/user/tests/doubles/test-user-repository.js +1 -1
  91. package/user/use-cases/authenticate-user.js +1 -7
  92. package/user/use-cases/get-user-from-adopter-jwt.js +124 -95
  93. package/user/use-cases/get-user-from-bearer-token.js +7 -2
  94. package/user/use-cases/get-user-from-x-frigg-headers.js +80 -83
  95. package/user/user.js +1 -64
  96. package/credential/use-cases/credential-operations-for-user.js +0 -202
  97. package/credential/use-cases/reauthorize-credential-for-user.js +0 -73
  98. package/database/organization-where.js +0 -18
  99. package/database/unique-violation.js +0 -25
  100. package/extensions/bootstrap-runner.js +0 -43
  101. package/extensions/extension-loader.js +0 -167
  102. package/extensions/index.js +0 -41
  103. package/extensions/initialize-app.js +0 -123
  104. package/extensions/route-mounter.js +0 -103
  105. package/extensions/schema-composer.js +0 -188
  106. package/infrastructure/scheduler/netlify-scheduler-adapter.js +0 -216
  107. package/infrastructure/scheduler/scheduled-job-repository.js +0 -118
  108. package/integrations/repositories/integration-not-found.js +0 -14
  109. package/integrations/use-cases/integration-operations-for-user.js +0 -256
  110. package/integrations/use-cases/resolve-integration-ownership.js +0 -177
  111. package/management-api/create-management-api-router.js +0 -49
  112. package/management-api/error-response.js +0 -116
  113. package/management-api/management-api-config.js +0 -151
  114. package/management-api/meta-router.js +0 -57
  115. package/management-api/openapi/build-openapi.js +0 -144
  116. package/management-api/openapi/components.js +0 -414
  117. package/management-api/openapi/v1-operations.js +0 -83
  118. package/management-api/openapi/v2-operations.js +0 -264
  119. package/management-api/route-registry.js +0 -294
  120. package/management-api/test-support/http-client.js +0 -39
  121. package/management-api/use-cases/get-management-api-meta.js +0 -57
  122. package/management-api/v1-deprecation.js +0 -120
  123. package/management-api/v2/create-v2-router.js +0 -85
  124. package/management-api/v2/dependencies.js +0 -281
  125. package/management-api/v2/dto.js +0 -143
  126. package/management-api/v2/handlers/authorization.js +0 -94
  127. package/management-api/v2/handlers/credentials.js +0 -33
  128. package/management-api/v2/handlers/entities.js +0 -77
  129. package/management-api/v2/handlers/integrations.js +0 -128
  130. package/management-api/v2/handlers/proxy.js +0 -34
  131. package/management-api/v2/request.js +0 -85
  132. package/management-api/v2/test-support/fake-dependencies.js +0 -103
  133. package/modules/domain/authorization-session.js +0 -144
  134. package/modules/entity-scope.js +0 -15
  135. package/modules/entity-type-registry.js +0 -311
  136. package/modules/proxy/proxy-bases.js +0 -169
  137. package/modules/proxy/proxy-errors.js +0 -31
  138. package/modules/proxy/proxy-path.js +0 -183
  139. package/modules/proxy/proxy-policy.js +0 -265
  140. package/modules/repositories/authorization-session-repository-documentdb.js +0 -112
  141. package/modules/repositories/authorization-session-repository-factory.js +0 -31
  142. package/modules/repositories/authorization-session-repository-interface.js +0 -47
  143. package/modules/repositories/authorization-session-repository-prisma.js +0 -87
  144. package/modules/repositories/entity-not-found.js +0 -18
  145. package/modules/requester/proxy-request.js +0 -245
  146. package/modules/scope-config.js +0 -192
  147. package/modules/scope-policy.js +0 -112
  148. package/modules/scope-resolution.js +0 -288
  149. package/modules/scope-visibility.js +0 -247
  150. package/modules/tests/doubles/in-memory-authorization-session-repository.js +0 -45
  151. package/modules/tests/doubles/ownership-matching.js +0 -18
  152. package/modules/use-cases/authorize-entity-for-user.js +0 -61
  153. package/modules/use-cases/create-entity-from-credential.js +0 -113
  154. package/modules/use-cases/entity-operations-for-user.js +0 -162
  155. package/modules/use-cases/entity-types.js +0 -139
  156. package/modules/use-cases/execute-entity-proxy-request.js +0 -331
  157. package/modules/use-cases/get-authorization-requirements.js +0 -100
  158. package/modules/use-cases/get-entity-module-for-user.js +0 -113
  159. package/modules/use-cases/manage-access.js +0 -21
  160. package/modules/use-cases/multi-step-authorization.js +0 -329
  161. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +0 -28
  162. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +0 -26
  163. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +0 -25
  164. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +0 -28
  165. package/providers/index.js +0 -13
  166. package/providers/resolve-provider.js +0 -93
  167. package/queues/providers/index.js +0 -11
  168. package/queues/providers/netlify-background-provider.js +0 -150
  169. package/queues/providers/qstash-queue-provider.js +0 -199
  170. package/queues/providers/sqs-queue-provider.js +0 -70
  171. package/queues/queue-client-interface.js +0 -55
  172. package/queues/queue-message-auth.js +0 -187
  173. package/queues/queue-provider-factory.js +0 -101
  174. package/queues/queue-provider.js +0 -65
  175. package/queues/sqs-queue-client.js +0 -81
  176. package/types/modules/index.d.ts +0 -214
  177. package/types/user/index.d.ts +0 -134
  178. package/user/adopter-jwt-config.js +0 -177
  179. package/user/adopter-jwt-errors.js +0 -59
  180. package/user/adopter-token-verifier.js +0 -122
  181. package/user/app-user-helpers.js +0 -97
  182. package/user/create-user-authentication.js +0 -64
  183. package/user/membership.js +0 -51
  184. package/user/repositories/organization-membership-record.js +0 -19
  185. package/user/repositories/organization-membership-repository-documentdb.js +0 -106
  186. package/user/repositories/organization-membership-repository-factory.js +0 -42
  187. package/user/repositories/organization-membership-repository-interface.js +0 -57
  188. package/user/repositories/organization-membership-repository-mongo.js +0 -13
  189. package/user/repositories/organization-membership-repository-postgres.js +0 -29
  190. package/user/repositories/organization-membership-repository-prisma.js +0 -81
  191. package/user/tests/doubles/adopter-jwt-fixtures.js +0 -220
  192. package/user/use-cases/ensure-organization-membership.js +0 -92
  193. package/user/use-cases/find-individual-users-by-organization.js +0 -54
@@ -1,183 +0,0 @@
1
- const { ProxyRequestError } = require('./proxy-errors');
2
- const { DEFAULT_BASE, ruleBase } = require('./proxy-bases');
3
-
4
- /**
5
- * Path rules for the entity proxy (ADR-052 §4). The caller supplies a path
6
- * relative to the module's base URL and nothing else: the host, scheme and
7
- * port always come from the module.
8
- */
9
-
10
- const invalid = (reason) =>
11
- new ProxyRequestError('INVALID_PROXY_REQUEST', `Invalid proxy path: ${reason}`, {
12
- field: 'path',
13
- });
14
-
15
- // Control characters (C0, DEL, C1), any whitespace, and invisible format
16
- // characters such as zero-width spaces and byte-order marks.
17
- const FORBIDDEN_CHARS = /[\x00-\x20\x7f-\x9f]|\s|\p{Cf}/u;
18
-
19
- /**
20
- * Validates and normalises a caller-supplied path.
21
- *
22
- * - must start with a single `/`; `//` (anywhere), `\`, `?`, `#`, control
23
- * and whitespace characters are rejected;
24
- * - encoded separators (`%2f`, `%5c`) are rejected, then the path is
25
- * percent-decoded exactly once; a `%` left after decoding (double
26
- * encoding) is rejected, as is any decoded control or whitespace
27
- * character other than a space (`%20`);
28
- * - `.` and `..` segments are rejected rather than resolved.
29
- *
30
- * @param {unknown} path
31
- * @returns {string} the decoded path, e.g. `/crm/v3/objects/contacts`
32
- * @throws {ProxyRequestError} INVALID_PROXY_REQUEST
33
- */
34
- function normalizeProxyPath(path) {
35
- if (typeof path !== 'string' || path.length === 0) {
36
- throw invalid('path must be a non-empty string');
37
- }
38
- if (path.length > 2048) throw invalid('path is too long');
39
- if (!path.startsWith('/')) throw invalid('path must start with /');
40
- if (path.startsWith('//') || path.includes('//')) {
41
- throw invalid('empty path segments (//) are not allowed');
42
- }
43
- if (path.includes('\\')) throw invalid('backslashes are not allowed');
44
- if (path.includes('?') || path.includes('#')) {
45
- throw invalid('send the query string in `query`, not in the path');
46
- }
47
- if (FORBIDDEN_CHARS.test(path)) {
48
- throw invalid('control and whitespace characters are not allowed');
49
- }
50
- if (/%(2f|5c)/i.test(path)) {
51
- throw invalid('encoded path separators are not allowed');
52
- }
53
-
54
- let decoded;
55
- try {
56
- decoded = decodeURIComponent(path);
57
- } catch {
58
- throw invalid('malformed percent-encoding');
59
- }
60
- if (
61
- decoded.includes('%') ||
62
- decoded.includes('\\') ||
63
- decoded.includes('?') ||
64
- decoded.includes('#') ||
65
- decoded.includes('//') ||
66
- // An encoded space (%20) is a legitimate path character; every other
67
- // control or whitespace character stays forbidden.
68
- FORBIDDEN_CHARS.test(decoded.replaceAll(' ', ''))
69
- ) {
70
- throw invalid('encoded characters decode to something not allowed');
71
- }
72
-
73
- const segments = decoded.split('/').slice(1);
74
- if (segments.some((segment) => segment === '.' || segment === '..')) {
75
- throw invalid('dot segments (. and ..) are not allowed');
76
- }
77
- return decoded;
78
- }
79
-
80
- /**
81
- * Joins a module base URL and a normalised path, then proves the result
82
- * cannot leave the module's API: https only, same origin as the base URL,
83
- * and under the base URL's path.
84
- *
85
- * @param {string} baseUrl - from the module, never from the request
86
- * @param {string} normalizedPath - from normalizeProxyPath()
87
- * @returns {{ url: string, basePath: string, origin: string }} `url` is not
88
- * percent-encoded; the Requester encodes it once.
89
- * @throws {ProxyRequestError} PROXY_NOT_CONFIGURED or INVALID_PROXY_REQUEST
90
- */
91
- function joinProxyUrl(baseUrl, normalizedPath) {
92
- let base;
93
- try {
94
- base = new URL(baseUrl);
95
- } catch {
96
- throw new ProxyRequestError(
97
- 'PROXY_NOT_CONFIGURED',
98
- 'The module has no valid base URL to proxy to'
99
- );
100
- }
101
- if (base.protocol !== 'https:') {
102
- throw new ProxyRequestError(
103
- 'PROXY_NOT_CONFIGURED',
104
- 'The module base URL must use https to be proxied'
105
- );
106
- }
107
- if (base.username || base.password || base.search || base.hash) {
108
- throw new ProxyRequestError(
109
- 'PROXY_NOT_CONFIGURED',
110
- 'The module base URL must not carry credentials, a query or a fragment'
111
- );
112
- }
113
-
114
- const basePath = base.pathname.replace(/\/+$/, '');
115
- const url = `${base.origin}${basePath}${normalizedPath}`;
116
-
117
- let joined;
118
- try {
119
- joined = new URL(url);
120
- } catch {
121
- throw invalid('the joined URL is not valid');
122
- }
123
- const joinedPath = decodeURIComponent(joined.pathname);
124
- if (
125
- joined.protocol !== 'https:' ||
126
- joined.origin !== base.origin ||
127
- joined.username ||
128
- joined.password ||
129
- !(joinedPath === basePath || joinedPath.startsWith(`${basePath}/`))
130
- ) {
131
- throw invalid('the path leaves the module API');
132
- }
133
- return { url, basePath, origin: base.origin };
134
- }
135
-
136
- /**
137
- * Finds the allow-list rule that permits `method` on `path` of `base`.
138
- *
139
- * Patterns use `:param` for exactly one segment and a trailing `/**` for a
140
- * subtree (the prefix itself included). `method: '*'` matches any method.
141
- *
142
- * @param {Array<{method: string, path: string}>} rules
143
- * @param {string} method - upper case
144
- * @param {string} path - normalised path
145
- * @param {string} [base='default'] - the named base the request targets; a
146
- * rule applies to its own `base` only (no `base` means `default`)
147
- * @returns {{method: string, path: string, base?: string}|null}
148
- */
149
- function matchAllowRule(rules, method, path, base = DEFAULT_BASE) {
150
- const requestSegments = path.split('/').slice(1);
151
- for (const rule of rules || []) {
152
- if (!rule || typeof rule.path !== 'string' || typeof rule.method !== 'string') {
153
- continue;
154
- }
155
- if (ruleBase(rule) !== base) continue;
156
- const ruleMethod = rule.method.toUpperCase();
157
- if (ruleMethod !== '*' && ruleMethod !== method) continue;
158
- if (patternMatches(rule.path, requestSegments)) return rule;
159
- }
160
- return null;
161
- }
162
-
163
- function patternMatches(pattern, requestSegments) {
164
- if (!pattern.startsWith('/')) return false;
165
- let patternSegments = pattern.split('/').slice(1);
166
- let subtree = false;
167
- if (patternSegments[patternSegments.length - 1] === '**') {
168
- subtree = true;
169
- patternSegments = patternSegments.slice(0, -1);
170
- }
171
- if (subtree) {
172
- if (requestSegments.length < patternSegments.length) return false;
173
- } else if (requestSegments.length !== patternSegments.length) {
174
- return false;
175
- }
176
- return patternSegments.every((segment, index) => {
177
- const actual = requestSegments[index];
178
- if (segment.startsWith(':')) return actual !== undefined && actual !== '';
179
- return segment === actual;
180
- });
181
- }
182
-
183
- module.exports = { normalizeProxyPath, joinProxyUrl, matchAllowRule };
@@ -1,265 +0,0 @@
1
- const { ProxyRequestError } = require('./proxy-errors');
2
- const { isValidBaseName } = require('./proxy-bases');
3
-
4
- /**
5
- * What the entity proxy accepts and returns (ADR-052 §5-§7). Pure functions:
6
- * no I/O, so every rule is unit-tested on its own.
7
- */
8
-
9
- const PROXY_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
10
- const METHODS_WITH_BODY = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
11
-
12
- /** Request headers a caller may always send (lower case). */
13
- const ALLOWED_REQUEST_HEADERS = [
14
- 'accept',
15
- 'content-type',
16
- 'accept-language',
17
- 'if-match',
18
- 'if-none-match',
19
- ];
20
-
21
- /** Request headers that are refused outright, even if a module lists them. */
22
- const REJECTED_REQUEST_HEADERS = [
23
- 'authorization',
24
- 'proxy-authorization',
25
- 'cookie',
26
- 'host',
27
- 'forwarded',
28
- 'x-real-ip',
29
- 'x-api-key',
30
- ];
31
- const REJECTED_REQUEST_HEADER_PREFIXES = ['x-forwarded-'];
32
-
33
- /** Response headers never passed back (credentials and hop-by-hop). */
34
- const REMOVED_RESPONSE_HEADERS = [
35
- 'authorization',
36
- 'proxy-authorization',
37
- 'proxy-authenticate',
38
- 'set-cookie',
39
- 'set-cookie2',
40
- 'www-authenticate',
41
- 'x-api-key',
42
- 'connection',
43
- 'keep-alive',
44
- 'te',
45
- 'trailer',
46
- 'transfer-encoding',
47
- 'upgrade',
48
- // The body is re-encoded as JSON, so these no longer describe it.
49
- 'content-length',
50
- 'content-encoding',
51
- ];
52
-
53
- const invalid = (message, details) =>
54
- new ProxyRequestError('INVALID_PROXY_REQUEST', message, details);
55
-
56
- const isPlainObject = (value) =>
57
- value !== null && typeof value === 'object' && !Array.isArray(value);
58
-
59
- /**
60
- * Validates the request body of POST /api/v2/entities/:id/proxy and returns
61
- * it with the method upper-cased and the body serialised.
62
- *
63
- * @param {unknown} request
64
- * @param {{ maxRequestBytes: number }} limits
65
- * @returns {{ method: string, path: string, base?: string, query?: Object, headers: Object, body?: string, requestBytes: number, bodyIsJson: boolean }}
66
- */
67
- function validateProxyRequest(request, { maxRequestBytes }) {
68
- if (!isPlainObject(request)) throw invalid('The proxy request must be a JSON object');
69
- const method = typeof request.method === 'string' ? request.method.toUpperCase() : '';
70
- if (!PROXY_METHODS.includes(method)) {
71
- throw invalid(`method must be one of ${PROXY_METHODS.join(', ')}`, { field: 'method' });
72
- }
73
- if (typeof request.path !== 'string') {
74
- throw invalid('path is required', { field: 'path' });
75
- }
76
-
77
- // `base` is a name, never a URL or host; anything else is refused before
78
- // a module is looked up. Omitted means `default` (the caller applies it).
79
- let base;
80
- if (request.base !== undefined && request.base !== null) {
81
- if (typeof request.base !== 'string' || !isValidBaseName(request.base)) {
82
- throw invalid(
83
- 'base must be the name of one of the module\'s base URLs (lower case letters, digits and -), not a URL or host',
84
- { field: 'base' }
85
- );
86
- }
87
- base = request.base;
88
- }
89
-
90
- let query;
91
- if (request.query !== undefined && request.query !== null) {
92
- if (!isPlainObject(request.query)) throw invalid('query must be an object', { field: 'query' });
93
- query = {};
94
- for (const [key, value] of Object.entries(request.query)) {
95
- const scalar = ['string', 'number', 'boolean'].includes(typeof value);
96
- const list = Array.isArray(value) && value.every((v) => typeof v === 'string');
97
- if (!scalar && !list) {
98
- throw invalid(`query.${key} must be a string, number, boolean or array of strings`, {
99
- field: `query.${key}`,
100
- });
101
- }
102
- // The requester sends one value per key; arrays go comma-separated.
103
- query[key] = list ? value.join(',') : value;
104
- }
105
- }
106
-
107
- const headers = {};
108
- if (request.headers !== undefined && request.headers !== null) {
109
- if (!isPlainObject(request.headers)) throw invalid('headers must be an object', { field: 'headers' });
110
- for (const [name, value] of Object.entries(request.headers)) {
111
- if (typeof value !== 'string') {
112
- throw invalid(`header ${name} must be a string`, { field: `headers.${name}` });
113
- }
114
- headers[name.toLowerCase()] = value;
115
- }
116
- }
117
-
118
- let body;
119
- let bodyIsJson = false;
120
- if (request.body !== undefined && request.body !== null) {
121
- if (!METHODS_WITH_BODY.has(method)) {
122
- throw invalid(`${method} requests cannot have a body`, { field: 'body' });
123
- }
124
- if (typeof request.body === 'string') {
125
- body = request.body;
126
- } else {
127
- body = JSON.stringify(request.body);
128
- bodyIsJson = true;
129
- }
130
- }
131
- const requestBytes = body === undefined ? 0 : Buffer.byteLength(body);
132
- if (requestBytes > maxRequestBytes) {
133
- throw new ProxyRequestError(
134
- 'PAYLOAD_TOO_LARGE',
135
- `The proxied request body is larger than ${maxRequestBytes} bytes`
136
- );
137
- }
138
- return { method, path: request.path, ...(base !== undefined && { base }), query, headers, body, bodyIsJson, requestBytes };
139
- }
140
-
141
- const isWildcardRule = (rule) => rule?.method === '*' || rule?.path === '/**';
142
-
143
- // A rule's `base` is checked against the module's declared bases at load, by
144
- // assertProxyConfig (proxy-bases.js); here only its shape is.
145
- const isValidRule = (rule) =>
146
- isPlainObject(rule) &&
147
- typeof rule.method === 'string' &&
148
- typeof rule.path === 'string' &&
149
- rule.path.startsWith('/') &&
150
- (rule.base === undefined || isValidBaseName(rule.base));
151
-
152
- /**
153
- * The allow-list in force for a module: the app definition's list for it when
154
- * one is given (`managementApi.proxy.modules[name].allow`), otherwise the
155
- * module's own `proxy.allow`. A module cannot grant itself a wildcard; only
156
- * the app definition can. No list means nothing may be proxied.
157
- *
158
- * @returns {{ rules: Array<{method: string, path: string}>, source: 'app'|'module'|'none', ignored: number }}
159
- */
160
- function resolveAllowRules(definition, moduleOverrides = {}) {
161
- const override = moduleOverrides?.[definition.moduleName]?.allow;
162
- if (Array.isArray(override)) {
163
- return { rules: override.filter(isValidRule), source: 'app', ignored: 0 };
164
- }
165
- const declared = Array.isArray(definition.proxy?.allow) ? definition.proxy.allow : [];
166
- const rules = declared.filter((rule) => isValidRule(rule) && !isWildcardRule(rule));
167
- return {
168
- rules,
169
- source: rules.length ? 'module' : 'none',
170
- ignored: declared.length - rules.length,
171
- };
172
- }
173
-
174
- /**
175
- * Keeps only the request headers the caller may set. A header from the
176
- * rejected list (credentials, Host, forwarding headers, or one the module's
177
- * own auth sets) fails the request instead of being dropped quietly.
178
- *
179
- * @param {Object} headers - lower-cased names
180
- * @param {Object} options
181
- * @param {string[]} [options.moduleHeaders] - from the module's `proxy.headers`
182
- * @param {string[]} [options.authHeaderNames] - headers the module's auth sets
183
- */
184
- function filterRequestHeaders(headers, { moduleHeaders = [], authHeaderNames = [] } = {}) {
185
- const rejected = new Set([
186
- ...REJECTED_REQUEST_HEADERS,
187
- ...authHeaderNames.filter(Boolean).map((name) => String(name).toLowerCase()),
188
- ]);
189
- const allowed = new Set([
190
- ...ALLOWED_REQUEST_HEADERS,
191
- ...moduleHeaders.map((name) => String(name).toLowerCase()),
192
- ]);
193
- const kept = {};
194
- for (const [name, value] of Object.entries(headers)) {
195
- if (
196
- rejected.has(name) ||
197
- REJECTED_REQUEST_HEADER_PREFIXES.some((prefix) => name.startsWith(prefix))
198
- ) {
199
- throw invalid(`The ${name} header cannot be sent through the proxy`, {
200
- field: `headers.${name}`,
201
- });
202
- }
203
- if (allowed.has(name)) kept[name] = value;
204
- }
205
- return kept;
206
- }
207
-
208
- /**
209
- * Removes credential and hop-by-hop headers from an upstream response, and
210
- * the Location of a redirect the proxy refused to follow.
211
- */
212
- function filterResponseHeaders(headers, { redirectBlocked = false, authHeaderNames = [] } = {}) {
213
- const removed = new Set([
214
- ...REMOVED_RESPONSE_HEADERS,
215
- ...authHeaderNames.filter(Boolean).map((name) => String(name).toLowerCase()),
216
- ]);
217
- if (redirectBlocked) removed.add('location');
218
- const kept = {};
219
- for (const [name, value] of Object.entries(headers || {})) {
220
- if (!removed.has(name.toLowerCase())) kept[name.toLowerCase()] = value;
221
- }
222
- return kept;
223
- }
224
-
225
- const JSON_TYPE = /^application\/([a-z0-9.+-]*\+)?json\b/i;
226
- const TEXT_TYPE = /^(text\/|application\/(xml|x-www-form-urlencoded|javascript|graphql)\b|[a-z]+\/[a-z0-9.+-]*\+xml\b)/i;
227
-
228
- /**
229
- * Turns the upstream body into the `data` of the proxy response: parsed JSON,
230
- * text, or (only if the module allows binary) base64.
231
- *
232
- * @returns {{ data: unknown, encoding?: 'base64' }}
233
- */
234
- function decodeResponseBody(body, contentType, { binary = false } = {}) {
235
- if (!body || body.length === 0) return { data: null };
236
- if (JSON_TYPE.test(contentType)) {
237
- const text = body.toString('utf8');
238
- try {
239
- return { data: JSON.parse(text) };
240
- } catch {
241
- return { data: text };
242
- }
243
- }
244
- if (!contentType || TEXT_TYPE.test(contentType)) {
245
- return { data: body.toString('utf8') };
246
- }
247
- if (binary) return { data: body.toString('base64'), encoding: 'base64' };
248
- throw new ProxyRequestError(
249
- 'UNSUPPORTED_MEDIA_TYPE',
250
- 'The upstream response is binary and this module does not allow binary proxying',
251
- { contentType: contentType.split(';')[0] }
252
- );
253
- }
254
-
255
- module.exports = {
256
- PROXY_METHODS,
257
- ALLOWED_REQUEST_HEADERS,
258
- REJECTED_REQUEST_HEADERS,
259
- REMOVED_RESPONSE_HEADERS,
260
- validateProxyRequest,
261
- resolveAllowRules,
262
- filterRequestHeaders,
263
- filterResponseHeaders,
264
- decodeResponseBody,
265
- };
@@ -1,112 +0,0 @@
1
- const { prisma } = require('../../database/prisma');
2
- const {
3
- findOne,
4
- insertOne,
5
- updateOne,
6
- deleteMany,
7
- } = require('../../database/documentdb-utils');
8
- const {
9
- DocumentDBEncryptionService,
10
- } = require('../../database/documentdb-encryption-service');
11
- const { AuthorizationSession } = require('../domain/authorization-session');
12
- const {
13
- AuthorizationSessionRepositoryInterface,
14
- } = require('./authorization-session-repository-interface');
15
-
16
- const COLLECTION = 'AuthorizationSession';
17
-
18
- /**
19
- * AuthorizationSession persistence for DocumentDB through raw commands.
20
- * `stepData` is encrypted with DocumentDBEncryptionService, as the Prisma
21
- * extension does not run for raw commands.
22
- */
23
- class AuthorizationSessionRepositoryDocumentDB extends AuthorizationSessionRepositoryInterface {
24
- constructor() {
25
- super();
26
- this.prisma = prisma;
27
- this.encryptionService = new DocumentDBEncryptionService();
28
- }
29
-
30
- async create(session) {
31
- const now = new Date();
32
- const document = await this.encryptionService.encryptFields(COLLECTION, {
33
- sessionId: session.sessionId,
34
- userId: session.userId,
35
- entityType: session.entityType,
36
- credentialId: session.credentialId,
37
- currentStep: session.currentStep,
38
- maxSteps: session.maxSteps,
39
- stepData: session.stepData,
40
- expiresAt: session.expiresAt,
41
- completed: session.completed,
42
- createdAt: now,
43
- updatedAt: now,
44
- });
45
- await insertOne(this.prisma, COLLECTION, document);
46
- return this._toDomain(
47
- await this.encryptionService.decryptFields(COLLECTION, document)
48
- );
49
- }
50
-
51
- async findBySessionId(sessionId) {
52
- if (typeof sessionId !== 'string' || !sessionId) return null;
53
- const document = await findOne(this.prisma, COLLECTION, {
54
- sessionId,
55
- expiresAt: { $gt: new Date() },
56
- });
57
- if (!document) return null;
58
- return this._toDomain(
59
- await this.encryptionService.decryptFields(COLLECTION, document)
60
- );
61
- }
62
-
63
- async update(session) {
64
- const encrypted = await this.encryptionService.encryptFields(COLLECTION, {
65
- stepData: session.stepData,
66
- });
67
- await updateOne(
68
- this.prisma,
69
- COLLECTION,
70
- { sessionId: session.sessionId },
71
- {
72
- $set: {
73
- currentStep: session.currentStep,
74
- stepData: encrypted.stepData,
75
- completed: session.completed,
76
- updatedAt: new Date(),
77
- },
78
- }
79
- );
80
- return session;
81
- }
82
-
83
- async deleteBySessionId(sessionId) {
84
- const result = await deleteMany(this.prisma, COLLECTION, { sessionId });
85
- return result?.n ?? 0;
86
- }
87
-
88
- async deleteExpired(now = new Date()) {
89
- const result = await deleteMany(this.prisma, COLLECTION, {
90
- expiresAt: { $lte: now },
91
- });
92
- return result?.n ?? 0;
93
- }
94
-
95
- _toDomain(document) {
96
- return new AuthorizationSession({
97
- sessionId: document.sessionId,
98
- userId: document.userId,
99
- entityType: document.entityType,
100
- credentialId: document.credentialId ?? null,
101
- currentStep: document.currentStep,
102
- maxSteps: document.maxSteps,
103
- stepData: document.stepData || {},
104
- expiresAt: new Date(document.expiresAt),
105
- completed: Boolean(document.completed),
106
- createdAt: document.createdAt,
107
- updatedAt: document.updatedAt,
108
- });
109
- }
110
- }
111
-
112
- module.exports = { AuthorizationSessionRepositoryDocumentDB };
@@ -1,31 +0,0 @@
1
- const config = require('../../database/config');
2
- const {
3
- AuthorizationSessionRepositoryPrisma,
4
- } = require('./authorization-session-repository-prisma');
5
- const {
6
- AuthorizationSessionRepositoryDocumentDB,
7
- } = require('./authorization-session-repository-documentdb');
8
-
9
- /**
10
- * AuthorizationSession repository for the configured database. PostgreSQL
11
- * and MongoDB share the Prisma adapter; DocumentDB uses raw commands.
12
- */
13
- function createAuthorizationSessionRepository() {
14
- switch (config.DB_TYPE) {
15
- case 'mongodb':
16
- case 'postgresql':
17
- return new AuthorizationSessionRepositoryPrisma();
18
- case 'documentdb':
19
- return new AuthorizationSessionRepositoryDocumentDB();
20
- default:
21
- throw new Error(
22
- `Unsupported database type: ${config.DB_TYPE}. Supported values: 'mongodb', 'documentdb', 'postgresql'`
23
- );
24
- }
25
- }
26
-
27
- module.exports = {
28
- createAuthorizationSessionRepository,
29
- AuthorizationSessionRepositoryPrisma,
30
- AuthorizationSessionRepositoryDocumentDB,
31
- };
@@ -1,47 +0,0 @@
1
- /**
2
- * Port for persisting AuthorizationSession records (Management API v2
3
- * multi-step authorization). Adapters return AuthorizationSession domain
4
- * objects and never expired sessions from lookups.
5
- */
6
- class AuthorizationSessionRepositoryInterface {
7
- /**
8
- * @param {import('../domain/authorization-session').AuthorizationSession} session
9
- * @returns {Promise<import('../domain/authorization-session').AuthorizationSession>}
10
- */
11
- async create(session) {
12
- throw new Error('Method create must be implemented by subclass');
13
- }
14
-
15
- /**
16
- * @param {string} sessionId
17
- * @returns {Promise<import('../domain/authorization-session').AuthorizationSession|null>}
18
- * null when missing or expired.
19
- */
20
- async findBySessionId(sessionId) {
21
- throw new Error('Method findBySessionId must be implemented by subclass');
22
- }
23
-
24
- /**
25
- * Saves currentStep, stepData and completed.
26
- * @param {import('../domain/authorization-session').AuthorizationSession} session
27
- */
28
- async update(session) {
29
- throw new Error('Method update must be implemented by subclass');
30
- }
31
-
32
- /** @param {string} sessionId */
33
- async deleteBySessionId(sessionId) {
34
- throw new Error('Method deleteBySessionId must be implemented by subclass');
35
- }
36
-
37
- /**
38
- * Removes sessions that expired before `now`.
39
- * @param {Date} [now]
40
- * @returns {Promise<number>} how many were removed
41
- */
42
- async deleteExpired(now) {
43
- throw new Error('Method deleteExpired must be implemented by subclass');
44
- }
45
- }
46
-
47
- module.exports = { AuthorizationSessionRepositoryInterface };