@getstrata/bootstrap 2.2.60 → 3.0.4

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 (90) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/bootstrap/app.d.ts +18 -7
  3. package/dist/bootstrap/buildModuleRoutes.d.ts +3 -5
  4. package/dist/bootstrap/buildWebModuleRoutes.d.ts +2 -3
  5. package/dist/bootstrap/cache/modelCacheTags.d.ts +3 -2
  6. package/dist/bootstrap/cachedJson.d.ts +7 -2
  7. package/dist/bootstrap/config.d.ts +1 -1
  8. package/dist/bootstrap/context.d.ts +25 -7
  9. package/dist/bootstrap/contracts.d.ts +1 -0
  10. package/dist/bootstrap/createWebRoutes.d.ts +2 -1
  11. package/dist/bootstrap/databaseReadiness.d.ts +3 -0
  12. package/dist/bootstrap/dependencies.d.ts +3 -2
  13. package/dist/bootstrap/discoverJobs.d.ts +3 -2
  14. package/dist/bootstrap/discoverListeners.d.ts +10 -7
  15. package/dist/bootstrap/discoverModels.d.ts +3 -2
  16. package/dist/bootstrap/discoverModules.d.ts +7 -6
  17. package/dist/bootstrap/health.d.ts +3 -2
  18. package/dist/bootstrap/http/securedRouteModelBinding.d.ts +1 -1
  19. package/dist/bootstrap/httpKernel.d.ts +43 -22
  20. package/dist/bootstrap/httpPersistence.d.ts +4 -0
  21. package/dist/bootstrap/inProcessCron.d.ts +5 -5
  22. package/dist/bootstrap/listeners/invalidateCacheOnModelWrite.d.ts +13 -12
  23. package/dist/bootstrap/metricsRoutes.d.ts +6 -1
  24. package/dist/bootstrap/moduleRouteMiddleware.d.ts +4 -4
  25. package/dist/bootstrap/modules.d.ts +1 -1
  26. package/dist/bootstrap/ownedHttpRoute.d.ts +23 -0
  27. package/dist/bootstrap/persistenceContracts.d.ts +70 -0
  28. package/dist/bootstrap/persistenceInvocation.d.ts +4 -0
  29. package/dist/bootstrap/providers/auth.d.ts +21 -0
  30. package/dist/bootstrap/providers/cache.d.ts +9 -3
  31. package/dist/bootstrap/providers/cacheProvider.d.ts +3 -0
  32. package/dist/bootstrap/providers/config.d.ts +6 -3
  33. package/dist/bootstrap/providers/events.d.ts +5 -2
  34. package/dist/bootstrap/providers/index.d.ts +3 -2
  35. package/dist/bootstrap/providers/listeners.d.ts +3 -3
  36. package/dist/bootstrap/providers/mail.d.ts +15 -0
  37. package/dist/bootstrap/providers/queue.d.ts +3 -2
  38. package/dist/bootstrap/providers/storage.d.ts +11 -2
  39. package/dist/bootstrap/providers/tracing.d.ts +4 -2
  40. package/dist/bootstrap/providers/view.d.ts +8 -5
  41. package/dist/bootstrap/public-api.d.ts +10 -7
  42. package/dist/bootstrap/queue/defaultJobs.d.ts +4 -2
  43. package/dist/bootstrap/rateLimit.d.ts +13 -3
  44. package/dist/bootstrap/routeCompiler.d.ts +20 -0
  45. package/dist/bootstrap/routeMetadata.d.ts +3 -3
  46. package/dist/bootstrap/routePlan.d.ts +11 -0
  47. package/dist/bootstrap/schedule.d.ts +11 -2
  48. package/dist/bootstrap/secretsGuard.d.ts +2 -3
  49. package/dist/bootstrap/web/routing.d.ts +6 -3
  50. package/dist/bootstrap/web/server.d.ts +14 -4
  51. package/dist/bootstrap/web/session.d.ts +23 -16
  52. package/dist/entries/buildModuleRoutes.js +602 -384
  53. package/dist/entries/buildWebModuleRoutes.js +596 -347
  54. package/dist/entries/cache/modelCacheTags.js +8 -186
  55. package/dist/entries/cachedJson.js +22 -0
  56. package/dist/entries/config.js +1 -3
  57. package/dist/entries/context.js +665 -700
  58. package/dist/entries/createSpaRoutes.js +194 -5
  59. package/dist/entries/createWebRoutes.js +618 -367
  60. package/dist/entries/databaseReadiness.js +267 -0
  61. package/dist/entries/dependencies.js +666 -701
  62. package/dist/entries/discoverJobs.js +18 -16
  63. package/dist/entries/discoverListeners.js +27 -38
  64. package/dist/entries/discoverModels.js +4 -3
  65. package/dist/entries/discoverModules.js +29 -67
  66. package/dist/entries/health.js +14 -34
  67. package/dist/entries/httpKernel.js +405 -89
  68. package/dist/entries/listeners/invalidateCacheOnModelWrite.js +43 -289
  69. package/dist/entries/metricsRoutes.js +9 -5
  70. package/dist/entries/persistenceContracts.js +1 -0
  71. package/dist/entries/persistenceInvocation.js +17 -0
  72. package/dist/entries/providers/auth.js +114 -0
  73. package/dist/entries/providers/cache.js +35 -0
  74. package/dist/entries/providers/events.js +55 -0
  75. package/dist/entries/providers/view.js +34 -44
  76. package/dist/entries/providers.js +392 -561
  77. package/dist/entries/queue/defaultJobs.js +9 -6
  78. package/dist/entries/routePlan.js +200 -0
  79. package/dist/entries/schedule.js +37 -37
  80. package/dist/entries/secretsGuard.js +10 -13
  81. package/dist/entries/web/routing.js +412 -96
  82. package/dist/entries/web/server.js +461 -29
  83. package/dist/entries/web/session.js +61 -73
  84. package/dist/index.js +1520 -1085
  85. package/dist/internal/ownedHttpRoute.js +66 -0
  86. package/package.json +52 -15
  87. package/dist/bootstrap/applicationRegistry.d.ts +0 -1
  88. package/dist/bootstrap/routeRegistry.d.ts +0 -10
  89. package/dist/entries/applicationRegistry.js +0 -24
  90. package/dist/entries/routeRegistry.js +0 -29
@@ -1,24 +1,36 @@
1
1
  // @bun
2
+ // ../../src/bootstrap/buildModuleRoutes.ts
3
+ import { withMiddleware as withMiddleware2 } from "@getstrata/core/http/routeMiddleware";
4
+ import { identityModes as identityModes2, scimMiddleware as scimMiddleware2 } from "#strata-http-route";
5
+
2
6
  // ../../src/bootstrap/cachedJson.ts
3
- import { conditionalJsonResponse } from "@getstrata/core/http/conditionalResponse";
4
- function createCachedJson(dependencies) {
7
+ import { CORE_JSON_RESPONSE_POLICY_TOKEN } from "@getstrata/core/contracts/serviceTokens";
8
+ import {
9
+ conditionalJsonResponse,
10
+ snapshotJsonResponsePolicy
11
+ } from "@getstrata/core/http/conditionalResponse";
12
+ function createCachedJson(cache, policy) {
13
+ const responsePolicy = snapshotJsonResponsePolicy(policy);
5
14
  return async (cacheKey, loader, tags = [], request) => {
6
- const data = tags.length > 0 ? await dependencies.cache.tags(...tags).remember(cacheKey, loader) : await dependencies.cache.remember(cacheKey, loader);
7
- return conditionalJsonResponse(request, data);
15
+ const data = tags.length > 0 ? await cache.tags(...tags).remember(cacheKey, loader) : await cache.remember(cacheKey, loader);
16
+ return conditionalJsonResponse(request, data, responsePolicy);
8
17
  };
9
18
  }
19
+ function createApplicationCachedJson(dependencies) {
20
+ const policy = dependencies.container.has(CORE_JSON_RESPONSE_POLICY_TOKEN) ? dependencies.container.resolve(CORE_JSON_RESPONSE_POLICY_TOKEN) : { etagEnabled: true };
21
+ return createCachedJson(dependencies.cache, policy);
22
+ }
10
23
 
11
24
  // ../../src/bootstrap/httpKernel.ts
25
+ import { establishedAuthReader as establishedAuthReader2 } from "@getstrata/core/auth/authReader";
26
+ import { hasVerifiedEmail } from "@getstrata/core/auth/emailVerification";
12
27
  import {
13
- hasVerifiedEmail,
14
- isEmailVerificationRequired
15
- } from "@getstrata/core/auth/emailVerification";
16
- import { createMembershipMiddleware } from "@getstrata/core/auth/membershipMiddleware";
17
- import { resolveAbilityChecker } from "@getstrata/core/contracts/serviceTokens";
18
- import { createAuthMiddleware } from "@getstrata/core/http/authMiddleware";
28
+ CORE_TRACING_RUNTIME_TOKEN,
29
+ resolveAbilityChecker
30
+ } from "@getstrata/core/contracts/serviceTokens";
19
31
  import { createAuthorizeMiddleware } from "@getstrata/core/http/authorizeMiddleware";
20
32
  import { createBodySizeLimitMiddleware } from "@getstrata/core/http/bodySizeLimitMiddleware";
21
- import { createCorsMiddleware } from "@getstrata/core/http/corsMiddleware";
33
+ import { createCorsMiddleware, resolveCorsConfig } from "@getstrata/core/http/corsMiddleware";
22
34
  import { createCsrfMiddleware } from "@getstrata/core/http/csrfMiddleware";
23
35
  import { createFlashMiddleware } from "@getstrata/core/http/flashMiddleware";
24
36
  import { createLoginThrottleMiddleware } from "@getstrata/core/http/loginThrottleMiddleware";
@@ -31,21 +43,21 @@ import { createRequireGlobalAdminMiddleware } from "@getstrata/core/http/require
31
43
  import { createRequirePasswordConfirmMiddleware } from "@getstrata/core/http/requirePasswordConfirmMiddleware";
32
44
  import { createRequireVerifiedMiddleware } from "@getstrata/core/http/requireVerifiedMiddleware";
33
45
  import { createRequireWebAuthMiddleware } from "@getstrata/core/http/requireWebAuthMiddleware";
34
- import {
35
- createJsonErrorMiddleware,
36
- createWebErrorMiddleware,
37
- withErrorHandling,
38
- withJsonErrorHandling
39
- } from "@getstrata/core/http/response";
46
+ import { createJsonErrorMiddleware, createWebErrorMiddleware } from "@getstrata/core/http/response";
40
47
  import { withMiddleware } from "@getstrata/core/http/routeMiddleware";
41
48
  import { createSecurityHeadersMiddleware } from "@getstrata/core/http/securityHeadersMiddleware";
42
49
  import { createValidateSignatureMiddleware } from "@getstrata/core/http/signedUrl";
43
50
  import { createThrottleMiddleware } from "@getstrata/core/http/throttleMiddleware";
44
51
  import { createRequestLoggingMiddleware } from "@getstrata/core/logging/requestLoggingMiddleware";
45
- import { isViewsEnabled } from "@getstrata/core/runtime/frontendMode";
46
- import { isPublicReadsEnabled } from "@getstrata/core/security/publicReads";
47
- import { createTenantMiddleware } from "@getstrata/core/tenant/tenantMiddleware";
48
52
  import { createTracingMiddleware } from "@getstrata/core/tracing/tracingMiddleware";
53
+ import { CORE_WEB_ERROR_VIEW_TOKEN } from "@getstrata/core/view/tokens";
54
+ import {
55
+ assertHttpHandler,
56
+ identityModes,
57
+ ownedHttpRoute,
58
+ ownedPublicHttpRoute,
59
+ scimMiddleware
60
+ } from "#strata-http-route";
49
61
 
50
62
  // ../../src/bootstrap/config.ts
51
63
  import {
@@ -60,8 +72,7 @@ import {
60
72
  CORE_PUBLIC_TENANCY_TOKEN,
61
73
  CORE_QUEUE_TOKEN,
62
74
  CORE_TENANT_RESOLVER_TOKEN,
63
- CORE_THROTTLE_QUOTA_POLICY_TOKEN,
64
- CORE_TOKEN_SERVICE_TOKEN
75
+ CORE_THROTTLE_QUOTA_POLICY_TOKEN
65
76
  } from "@getstrata/core/contracts/serviceTokens";
66
77
  var APP_PORT_CONFIG_KEY = "app.port";
67
78
  var CACHE_TTL_MS_CONFIG_KEY = "cache.ttlMs";
@@ -78,6 +89,189 @@ var DEFAULT_CACHE_DRIVER = "array";
78
89
  var DEFAULT_API_TOKEN = "";
79
90
  var DEFAULT_QUEUE_DRIVER = "sync";
80
91
 
92
+ // ../../src/bootstrap/httpPersistence.ts
93
+ import { establishedAuthReader, runWithEstablishedAuth } from "@getstrata/core/auth/authReader";
94
+ import { validatedAuthOutcome } from "@getstrata/core/auth/guard";
95
+ import { runWithMembershipSnapshot } from "@getstrata/core/auth/membershipContext";
96
+ import { InternalServerError, InvalidCredentialsError } from "@getstrata/core/errors/http";
97
+ import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
98
+ import { errorResponse } from "@getstrata/core/http/response";
99
+ import { webErrorResponse } from "@getstrata/core/http/webErrorResponse";
100
+ import { createPublicTenantSelector } from "@getstrata/core/tenant/publicTenantHost";
101
+ import { runWithTenant } from "@getstrata/core/tenant/tenantContext";
102
+ import { DEFAULT_TENANT, resolveTenantForRequest } from "@getstrata/core/tenant/tenantMiddleware";
103
+ import { businessPorts } from "#strata-http-route";
104
+ import { HTTP_PERSISTENCE_OPTIONS } from "#strata-http-route";
105
+ function snapshotAuth(input) {
106
+ const auth = validatedAuthOutcome(input);
107
+ if (auth.status === "error")
108
+ throw Object.assign(new InternalServerError, { cause: auth.error });
109
+ if (auth.status === "invalid")
110
+ throw new InvalidCredentialsError;
111
+ const user = auth.user;
112
+ const name = user?.name;
113
+ const email = user?.email;
114
+ return Object.freeze({
115
+ credentialSource: auth.credentialSource,
116
+ user: user ? Object.freeze({
117
+ id: user.id,
118
+ ...typeof name === "string" ? { name } : {},
119
+ ...typeof email === "string" ? { email } : {},
120
+ ...user.role !== undefined ? { role: user.role } : {},
121
+ ...user.isActive !== undefined ? { isActive: user.isActive } : {},
122
+ ...user.authVersion !== undefined ? { authVersion: user.authVersion } : {},
123
+ ...user.tokenId !== undefined ? { tokenId: user.tokenId } : {},
124
+ ...user.abilities ? { abilities: Object.freeze([...user.abilities]) } : {},
125
+ ...user.emailVerifiedAt !== undefined ? {
126
+ emailVerifiedAt: user.emailVerifiedAt instanceof Date ? user.emailVerifiedAt.toISOString() : user.emailVerifiedAt
127
+ } : {}
128
+ }) : null
129
+ });
130
+ }
131
+ function snapshotTenant(tenant) {
132
+ const snapshot = structuredClone(tenant);
133
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot) || !Number.isSafeInteger(snapshot.id) || snapshot.id < 1 || typeof snapshot.slug !== "string")
134
+ throw new TypeError("HTTP metadata must establish a valid tenant identity.");
135
+ return Object.freeze(snapshot);
136
+ }
137
+ function createHttpPersistence(invoke, options) {
138
+ const invalidSessionCookie = options.invalidSessionCookie ? Object.freeze({ ...options.invalidSessionCookie }) : undefined;
139
+ const selectPublic = options.publicTenancy ? createPublicTenantSelector(options.publicTenancy) : undefined;
140
+ return async (request, handler, identity, scim = false) => {
141
+ const externalId = currentRequestMeta().requestId;
142
+ const metadata = { routeTemplate: currentRequestMeta().routeTemplate ?? "", phase: "metadata" };
143
+ const established = await invoke({
144
+ kind: "request",
145
+ externalId,
146
+ signal: request.signal,
147
+ metadata,
148
+ actor: { kind: "system", policy: "http.identity-metadata" }
149
+ }, async (ports) => {
150
+ if (scim) {
151
+ if (!options.scim)
152
+ throw new Error("Explicit SCIM metadata authentication is required.");
153
+ const tenant = await options.scim(request, ports.database);
154
+ if (tenant instanceof Response)
155
+ return tenant;
156
+ return Object.freeze({
157
+ auth: Object.freeze({ user: null, credentialSource: "bearer" }),
158
+ memberships: Object.freeze([]),
159
+ tenant: snapshotTenant(tenant)
160
+ });
161
+ }
162
+ const lookup = options.metadata(ports);
163
+ const outcome = validatedAuthOutcome(await lookup.authenticate(request));
164
+ if (outcome.status === "invalid" && outcome.credentialSource === "session" && invalidSessionCookie && request.headers.get("cookie")?.split(";").some((part) => part.trim().startsWith(`${invalidSessionCookie.name}=`))) {
165
+ const error = new InvalidCredentialsError;
166
+ const response = await webErrorResponse(error, request) ?? errorResponse(error);
167
+ response.headers.append("Set-Cookie", invalidSessionCookie.expiredHeader);
168
+ return response;
169
+ }
170
+ const auth = snapshotAuth(outcome);
171
+ const memberships = auth.user ? await lookup.memberships(auth.user) : [];
172
+ const resolveTenant = async (id) => {
173
+ const result = await lookup.tenant(id);
174
+ if (result === null)
175
+ return null;
176
+ const snapshot = snapshotTenant(result);
177
+ if (snapshot.id !== id)
178
+ throw new Error("Tenant resolver returned a different tenant identity.");
179
+ return snapshot;
180
+ };
181
+ const tenant = options.tenancy === "none" ? snapshotTenant(DEFAULT_TENANT) : await resolveTenantForRequest(request, {
182
+ auth,
183
+ config: {
184
+ enabled: true,
185
+ production: options.production,
186
+ allowDevHeaders: options.allowTenantDevHeaders
187
+ },
188
+ resolveTenant,
189
+ userTenantId: lookup.userTenantId
190
+ }, resolveTenant, selectPublic);
191
+ return Object.freeze({
192
+ auth,
193
+ tenant,
194
+ memberships: Object.freeze(memberships.map((row) => Object.freeze({ ...row })))
195
+ });
196
+ });
197
+ if (established instanceof Response)
198
+ return established;
199
+ const claims = {};
200
+ if (established.auth.user) {
201
+ for (const [key, value] of Object.entries(established.auth.user))
202
+ if (value !== undefined) {
203
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || Array.isArray(value))
204
+ claims[key] = value;
205
+ }
206
+ }
207
+ return invoke({
208
+ kind: "request",
209
+ externalId,
210
+ signal: request.signal,
211
+ metadata: {
212
+ ...metadata,
213
+ phase: identity ? "identity-operation" : "business",
214
+ credentialSource: established.auth.credentialSource
215
+ },
216
+ ...scim ? { actor: { kind: "system", policy: "http.scim" } } : identity ? { actor: { kind: "system", policy: "http.identity-operation" } } : established.auth.user ? { actor: { kind: "principal", claims } } : {},
217
+ tenant: { id: established.tenant.id, slug: established.tenant.slug }
218
+ }, (ports) => {
219
+ const policy = Object.freeze({
220
+ run: (selected, mode, work) => {
221
+ const allowed = mode.kind === "tenant" ? identity === undefined : identity?.includes(mode.kind) === true;
222
+ if (!allowed)
223
+ throw new Error("Database policy is not allowed by this route declaration.");
224
+ return ports.policy.run(selected, mode, work);
225
+ }
226
+ });
227
+ const work = (database) => runWithEstablishedAuth(request, established.auth, () => runWithMembershipSnapshot(established.memberships, () => {
228
+ const execute = () => handler(request, businessPorts({
229
+ database,
230
+ auth: establishedAuthReader,
231
+ established,
232
+ policy
233
+ }));
234
+ return runWithTenant(established.tenant, execute);
235
+ }));
236
+ return !identity && options.tenancy === "rls" ? ports.policy.run(ports.database, { kind: "tenant", tenantId: established.tenant.id }, work) : work(ports.database);
237
+ });
238
+ };
239
+ }
240
+
241
+ // ../../src/bootstrap/moduleRouteMiddleware.ts
242
+ function enterModuleRoutes(routes, enter) {
243
+ const wrapped = {};
244
+ for (const [path, value] of Object.entries(routes)) {
245
+ if (value instanceof Response) {
246
+ const methods = {};
247
+ for (const method of ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]) {
248
+ methods[method] = enter(() => value.clone());
249
+ }
250
+ wrapped[path] = methods;
251
+ continue;
252
+ }
253
+ if (typeof value === "function") {
254
+ wrapped[path] = enter(value);
255
+ continue;
256
+ }
257
+ if (value && typeof value === "object" && !Array.isArray(value)) {
258
+ const entries = Object.entries(value);
259
+ if (entries.some(([, handler]) => typeof handler === "function" || handler instanceof Response)) {
260
+ wrapped[path] = Object.fromEntries(entries.map(([method, handler]) => {
261
+ const callback = handler instanceof Response ? () => handler.clone() : handler;
262
+ return [
263
+ method,
264
+ typeof callback === "function" ? enter(callback) : callback
265
+ ];
266
+ }));
267
+ continue;
268
+ }
269
+ }
270
+ wrapped[path] = value;
271
+ }
272
+ return wrapped;
273
+ }
274
+
81
275
  // ../../src/bootstrap/rateLimit.ts
82
276
  var LOCAL_LOGIN_RATE_LIMIT = {
83
277
  maxAttempts: 100,
@@ -87,9 +281,6 @@ var PRODUCTION_LOGIN_RATE_LIMIT = {
87
281
  maxAttempts: 5,
88
282
  decaySeconds: 900
89
283
  };
90
- function isLocalAppEnv() {
91
- return (process.env.APP_ENV ?? "local") === "local";
92
- }
93
284
  function parsePositiveInt(value, fallback) {
94
285
  const parsed = Number(value);
95
286
  if (!Number.isFinite(parsed) || parsed <= 0) {
@@ -109,18 +300,18 @@ function parseWindowSeconds(secondsValue, msValue, fallback) {
109
300
  }
110
301
  return fallback;
111
302
  }
112
- function resolveLoginRateLimit() {
113
- const defaults = isLocalAppEnv() ? LOCAL_LOGIN_RATE_LIMIT : PRODUCTION_LOGIN_RATE_LIMIT;
303
+ function resolveLoginRateLimit(env = {}) {
304
+ const defaults = env.APP_ENV === "local" ? LOCAL_LOGIN_RATE_LIMIT : PRODUCTION_LOGIN_RATE_LIMIT;
114
305
  return {
115
- maxAttempts: parsePositiveInt(process.env.LOGIN_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
116
- decaySeconds: parseWindowSeconds(process.env.LOGIN_RATE_LIMIT_WINDOW_SECONDS, process.env.LOGIN_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
306
+ maxAttempts: parsePositiveInt(env.LOGIN_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
307
+ decaySeconds: parseWindowSeconds(env.LOGIN_RATE_LIMIT_WINDOW_SECONDS, env.LOGIN_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
117
308
  };
118
309
  }
119
- function resolveRegisterRateLimit() {
120
- const defaults = isLocalAppEnv() ? { maxAttempts: 100, decaySeconds: 60 } : { maxAttempts: 10, decaySeconds: 60 };
310
+ function resolveRegisterRateLimit(env = {}) {
311
+ const defaults = env.APP_ENV === "local" ? { maxAttempts: 100, decaySeconds: 60 } : { maxAttempts: 10, decaySeconds: 60 };
121
312
  return {
122
- maxAttempts: parsePositiveInt(process.env.REGISTER_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
123
- decaySeconds: parseWindowSeconds(process.env.REGISTER_RATE_LIMIT_WINDOW_SECONDS, process.env.REGISTER_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
313
+ maxAttempts: parsePositiveInt(env.REGISTER_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
314
+ decaySeconds: parseWindowSeconds(env.REGISTER_RATE_LIMIT_WINDOW_SECONDS, env.REGISTER_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
124
315
  };
125
316
  }
126
317
 
@@ -129,15 +320,78 @@ class HttpKernel {
129
320
  dependencies;
130
321
  ownedThrottles = new Set;
131
322
  disposed = false;
323
+ emailVerificationRequired;
324
+ viewsEnabled;
325
+ publicReadsEnabled;
326
+ etagEnabled;
327
+ httpOptions;
328
+ responsePolicy;
132
329
  configuredCsrfMiddleware;
330
+ responses;
331
+ persistence;
133
332
  constructor(dependencies) {
134
333
  this.dependencies = dependencies;
334
+ const http = dependencies.container.has(HTTP_PERSISTENCE_OPTIONS) ? dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS) : undefined;
335
+ this.httpOptions = http;
336
+ const config = dependencies.container.has(CORE_CONFIG_TOKEN) ? dependencies.container.resolve(CORE_CONFIG_TOKEN) : undefined;
337
+ const features = http?.features ?? config?.get("http.features");
338
+ this.emailVerificationRequired = features?.emailVerificationRequired ?? false;
339
+ this.viewsEnabled = features?.viewsEnabled ?? false;
340
+ this.publicReadsEnabled = features?.publicReadsEnabled ?? false;
341
+ this.etagEnabled = features?.etagEnabled ?? true;
342
+ const policy = http?.responsePolicy ?? config?.get("http.responsePolicy");
343
+ if (policy?.cors)
344
+ resolveCorsConfig(policy.cors);
345
+ this.responsePolicy = Object.freeze({
346
+ cors: policy?.cors ? {
347
+ allowedOrigins: [...policy.cors.allowedOrigins ?? []],
348
+ additionalAllowedHeaders: [...policy.cors.additionalAllowedHeaders ?? []]
349
+ } : undefined,
350
+ securityHeaders: policy?.securityHeaders ?? {
351
+ production: http?.production ?? true,
352
+ frontendMode: this.viewsEnabled ? "server-htmx" : "api"
353
+ },
354
+ maxBodyBytes: policy?.maxBodyBytes ?? 1048576,
355
+ rateLimitPerMinute: policy?.rateLimitPerMinute ?? 120,
356
+ namespace: policy?.namespace ?? "strata",
357
+ trustForwardedFor: policy?.trustForwardedFor ?? false,
358
+ loginRateLimit: Object.freeze({ ...policy?.loginRateLimit ?? resolveLoginRateLimit() }),
359
+ registerRateLimit: Object.freeze({
360
+ ...policy?.registerRateLimit ?? resolveRegisterRateLimit()
361
+ })
362
+ });
135
363
  const targetOrigin = dependencies.container.has(CORE_CONFIG_TOKEN) ? dependencies.container.resolve(CORE_CONFIG_TOKEN).get(CSRF_TARGET_ORIGIN_CONFIG_KEY) : undefined;
136
- this.configuredCsrfMiddleware = createCsrfMiddleware({ targetOrigin });
364
+ this.configuredCsrfMiddleware = createCsrfMiddleware({ targetOrigin, ...http?.csrf });
365
+ this.responses = Object.freeze({
366
+ json: Object.freeze(this.responseMiddleware("json")),
367
+ web: Object.freeze(this.responseMiddleware("web"))
368
+ });
369
+ this.persistence = dependencies.container.has(HTTP_PERSISTENCE_OPTIONS) ? createHttpPersistence(dependencies.invoke, dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS)) : undefined;
137
370
  if (dependencies.container.has(CORE_HTTP_CLEANUP_TOKEN)) {
138
371
  dependencies.container.resolve(CORE_HTTP_CLEANUP_TOKEN)(() => this.dispose());
139
372
  }
140
373
  }
374
+ requireFlashOptions() {
375
+ const options = this.httpOptions?.flash;
376
+ if (!options)
377
+ throw new TypeError("Explicit flash configuration is required for web routes.");
378
+ return options;
379
+ }
380
+ requireIntendedOptions() {
381
+ const options = this.httpOptions?.intendedUrl;
382
+ if (!options)
383
+ throw new TypeError("Explicit intended URL cookie configuration is required for web authentication.");
384
+ return options;
385
+ }
386
+ routeModelBindingPorts(auth) {
387
+ const gate = this.dependencies.container.resolve(CORE_POLICY_GATE_TOKEN);
388
+ const authorize = gate.authorize;
389
+ return Object.freeze({
390
+ auth,
391
+ authorize: (...args) => authorize.call(gate, ...args),
392
+ etagEnabled: this.etagEnabled
393
+ });
394
+ }
141
395
  dispose() {
142
396
  this.disposed = true;
143
397
  const owned = [...this.ownedThrottles];
@@ -165,39 +419,73 @@ class HttpKernel {
165
419
  return throttle;
166
420
  }
167
421
  globalMiddleware(errorFormat = "json") {
168
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
169
- return [
170
- ...this.responseMiddleware(errorFormat),
171
- createAuthMiddleware(auth),
172
- createMembershipMiddleware(),
173
- createTenantMiddleware({
174
- publicTenancy: this.dependencies.container.has(CORE_PUBLIC_TENANCY_TOKEN) ? this.dependencies.container.resolve(CORE_PUBLIC_TENANCY_TOKEN) : undefined,
175
- resolveTenant: this.dependencies.container.has(CORE_TENANT_RESOLVER_TOKEN) ? this.dependencies.container.resolve(CORE_TENANT_RESOLVER_TOKEN) : undefined
176
- })
177
- ];
422
+ return [...this.responses[errorFormat]];
423
+ }
424
+ run(request, handler, format = "json", identity, scim) {
425
+ assertHttpHandler(handler);
426
+ const execute = this.persistence;
427
+ if (!execute)
428
+ throw new Error("Explicit HTTP persistence composition is required.");
429
+ const outer = withMiddleware(...this.responses[format])((req) => withMiddleware(...scim ?? [])((req) => execute(req, handler, identity, scim !== undefined))(req));
430
+ return Promise.resolve(outer(request));
431
+ }
432
+ composed(handler, format, identity = identityModes(handler), scim = scimMiddleware(handler)) {
433
+ assertHttpHandler(handler);
434
+ if (identity !== undefined && scim !== undefined)
435
+ throw new TypeError("SCIM and identity operation declarations cannot be combined.");
436
+ return ownedHttpRoute(handler, (request, work) => this.run(request, work, format, identity, scim), identity, scim);
437
+ }
438
+ wrapIdentity(handler, modes = ["identifier"]) {
439
+ assertHttpHandler(handler);
440
+ if (scimMiddleware(handler) !== undefined)
441
+ throw new TypeError("SCIM and identity operation declarations cannot be combined.");
442
+ if (!Array.isArray(modes) || modes.some((mode) => mode !== "identifier" && mode !== "bypass"))
443
+ throw new TypeError("Invalid identity route policy modes.");
444
+ return this.composed(handler, "web", Object.freeze([...modes]));
445
+ }
446
+ wrapPasswordConfirm(handler) {
447
+ assertHttpHandler(handler);
448
+ const options = this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).passwordConfirmation;
449
+ if (!options)
450
+ throw new Error("Explicit password confirmation configuration is required.");
451
+ return this.composed(withMiddleware(createRequirePasswordConfirmMiddleware(options))(handler), "json", identityModes(handler), scimMiddleware(handler));
452
+ }
453
+ wrapRouteMap(routes, middleware) {
454
+ return enterModuleRoutes(routes, (callback) => this.composed(withMiddleware(...middleware)(callback), "json", identityModes(callback), scimMiddleware(callback)));
455
+ }
456
+ wrapScim(handler, before = []) {
457
+ assertHttpHandler(handler);
458
+ if (identityModes(handler) !== undefined)
459
+ throw new TypeError("SCIM and identity operation declarations cannot be combined.");
460
+ return this.composed(handler, "json", undefined, Object.freeze([...before]));
178
461
  }
179
462
  responseMiddleware(errorFormat) {
180
463
  return [
181
- createCorsMiddleware(),
182
- createSecurityHeadersMiddleware(),
183
- createBodySizeLimitMiddleware(),
184
- createTracingMiddleware(),
464
+ createCorsMiddleware(this.responsePolicy.cors),
465
+ createSecurityHeadersMiddleware(this.responsePolicy.securityHeaders),
466
+ createBodySizeLimitMiddleware(this.responsePolicy.maxBodyBytes),
467
+ ...this.dependencies.container.has(CORE_TRACING_RUNTIME_TOKEN) ? [createTracingMiddleware(this.dependencies.container.resolve(CORE_TRACING_RUNTIME_TOKEN))] : [],
185
468
  createMetricsMiddleware(),
186
- createRequestLoggingMiddleware(),
469
+ createRequestLoggingMiddleware(this.responsePolicy.trustForwardedFor),
187
470
  requestIdMiddleware,
188
- errorFormat === "json" ? createJsonErrorMiddleware() : createWebErrorMiddleware()
471
+ errorFormat === "json" ? createJsonErrorMiddleware() : createWebErrorMiddleware({
472
+ enabled: this.viewsEnabled,
473
+ production: this.dependencies.container.has(HTTP_PERSISTENCE_OPTIONS) ? this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).production ?? true : true,
474
+ render: this.dependencies.container.has(CORE_WEB_ERROR_VIEW_TOKEN) ? this.dependencies.container.resolve(CORE_WEB_ERROR_VIEW_TOKEN) : undefined
475
+ })
189
476
  ];
190
477
  }
191
478
  wrapPublicDocument(handler) {
192
- return withMiddleware(...this.responseMiddleware("web"))(handler);
479
+ assertHttpHandler(handler);
480
+ return ownedPublicHttpRoute(handler, (request, work) => Promise.resolve(withMiddleware(...this.responses.web)(work)(request)));
193
481
  }
194
482
  group(name) {
195
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
483
+ const auth = establishedAuthReader2;
196
484
  switch (name) {
197
485
  case "authenticated":
198
486
  return [createRequireAuthMiddleware(auth)];
199
487
  case "web":
200
- return isViewsEnabled() ? [createFlashMiddleware(), this.configuredCsrfMiddleware] : [];
488
+ return this.viewsEnabled ? [createFlashMiddleware(this.requireFlashOptions()), this.configuredCsrfMiddleware] : [];
201
489
  case "api": {
202
490
  const csrf = this.configuredCsrfMiddleware;
203
491
  if (!this.dependencies.container.has(CORE_CONFIG_TOKEN)) {
@@ -207,9 +495,11 @@ class HttpKernel {
207
495
  const config = this.dependencies.container.resolve(CORE_CONFIG_TOKEN);
208
496
  const redisUrl = config.get(REDIS_URL_CONFIG_KEY)?.trim() ?? "";
209
497
  if (!redisUrl) {
210
- const maxAttempts = Number(process.env.RATE_LIMIT_PER_MINUTE ?? "120");
498
+ const maxAttempts = this.responsePolicy.rateLimitPerMinute ?? 120;
211
499
  return [
212
500
  this.ownThrottle(createMemoryThrottleMiddleware({
501
+ namespace: this.responsePolicy.namespace,
502
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
213
503
  maxAttempts: Number.isFinite(maxAttempts) ? maxAttempts : 120,
214
504
  decaySeconds: 60,
215
505
  quotaPolicy
@@ -217,9 +507,11 @@ class HttpKernel {
217
507
  csrf
218
508
  ];
219
509
  }
220
- const maxAttempts = Number(process.env.RATE_LIMIT_PER_MINUTE ?? "120");
510
+ const maxAttempts = this.responsePolicy.rateLimitPerMinute ?? 120;
221
511
  return [
222
512
  this.ownThrottle(createThrottleMiddleware({
513
+ namespace: this.responsePolicy.namespace,
514
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
223
515
  redisUrl,
224
516
  maxAttempts: Number.isFinite(maxAttempts) ? maxAttempts : 120,
225
517
  decaySeconds: 60,
@@ -233,469 +525,395 @@ class HttpKernel {
233
525
  }
234
526
  }
235
527
  wrap(groups, handler) {
528
+ assertHttpHandler(handler);
236
529
  const names = Array.isArray(groups) ? groups : [groups];
237
530
  const middleware = names.flatMap((name) => this.group(name));
238
531
  const wrapped = middleware.length === 0 ? handler : withMiddleware(...middleware)(handler);
239
532
  if (names.includes("api")) {
240
- return withJsonErrorHandling(wrapped);
533
+ return this.composed(wrapped, "json", identityModes(handler), scimMiddleware(handler));
241
534
  }
242
- return wrapped;
535
+ return this.composed(wrapped, "web", identityModes(handler), scimMiddleware(handler));
243
536
  }
244
537
  wrapApi(handler) {
538
+ assertHttpHandler(handler);
245
539
  return this.wrap(["api", "authenticated"], handler);
246
540
  }
247
541
  wrapWeb(handler) {
248
- return withErrorHandling(this.wrap("web", handler));
542
+ assertHttpHandler(handler);
543
+ return this.wrap("web", handler);
249
544
  }
250
545
  wrapWebGuest(handler, home = "/") {
251
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
252
- return this.wrapWeb(async (request) => {
546
+ assertHttpHandler(handler);
547
+ const auth = establishedAuthReader2;
548
+ const guest = this.wrapWeb(async (request, ports) => {
253
549
  const user = await auth.resolve(request);
254
550
  if (user) {
255
- if (isEmailVerificationRequired() && !hasVerifiedEmail(user)) {
551
+ if (this.emailVerificationRequired && !hasVerifiedEmail(user)) {
256
552
  return Response.redirect("/email/verify", 302);
257
553
  }
258
554
  const location = typeof home === "function" ? await home(user) : home;
259
555
  return Response.redirect(location, 302);
260
556
  }
261
- return handler(request);
557
+ return handler(request, ports);
262
558
  });
559
+ return this.composed(guest, "web", identityModes(handler), scimMiddleware(handler));
263
560
  }
264
561
  wrapWebPublicRead(handler, options = {}) {
265
- if (options.allowAnonymous ?? isPublicReadsEnabled()) {
562
+ assertHttpHandler(handler);
563
+ if (options.allowAnonymous ?? this.publicReadsEnabled) {
266
564
  return this.wrapWeb(handler);
267
565
  }
268
566
  return this.wrapWebAuthenticated(handler);
269
567
  }
270
568
  wrapWebAuthenticated(handler) {
569
+ assertHttpHandler(handler);
271
570
  return this.wrapWebAuth(handler, { verified: true });
272
571
  }
273
572
  wrapWebAuthenticatedAllowUnverified(handler) {
573
+ assertHttpHandler(handler);
274
574
  return this.wrapWebAuth(handler, { verified: false });
275
575
  }
276
576
  wrapWebVerified(handler) {
577
+ assertHttpHandler(handler);
277
578
  return this.wrapWebAuth(handler, { verified: true });
278
579
  }
279
580
  wrapWebPasswordConfirm(handler) {
280
- return this.wrapWebAuth(withMiddleware(createRequirePasswordConfirmMiddleware())(handler), {
581
+ assertHttpHandler(handler);
582
+ const options = this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).passwordConfirmation;
583
+ if (!options)
584
+ throw new Error("Explicit password confirmation configuration is required.");
585
+ return this.wrapWebAuth(this.composed(withMiddleware(createRequirePasswordConfirmMiddleware(options))(handler), "web", identityModes(handler), scimMiddleware(handler)), {
281
586
  verified: true
282
587
  });
283
588
  }
284
589
  wrapWebAbility(ability, handler) {
285
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
590
+ assertHttpHandler(handler);
591
+ const auth = establishedAuthReader2;
286
592
  const abilityChecker = resolveAbilityChecker(this.dependencies.container);
287
- const requireAbility = createRequireAbilityMiddleware(abilityChecker);
593
+ const requireAbility = createRequireAbilityMiddleware(abilityChecker, this.viewsEnabled);
288
594
  const middleware = [
289
- createRequireWebAuthMiddleware(auth),
595
+ createRequireWebAuthMiddleware(auth, this.requireIntendedOptions()),
290
596
  ...this.verifiedMiddleware(),
291
597
  requireAbility(ability)
292
598
  ];
293
- return this.wrapWeb(withMiddleware(...middleware)(handler));
599
+ return this.wrapWeb(this.composed(withMiddleware(...middleware)(handler), "web", identityModes(handler), scimMiddleware(handler)));
294
600
  }
295
601
  wrapWebGlobalAdmin(handler) {
296
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
602
+ assertHttpHandler(handler);
603
+ const auth = establishedAuthReader2;
297
604
  const middleware = [
298
- createRequireWebAuthMiddleware(auth),
605
+ createRequireWebAuthMiddleware(auth, this.requireIntendedOptions()),
299
606
  ...this.verifiedMiddleware(),
300
607
  createRequireGlobalAdminMiddleware()
301
608
  ];
302
- return this.wrapWeb(withMiddleware(...middleware)(handler));
609
+ return this.wrapWeb(this.composed(withMiddleware(...middleware)(handler), "web", identityModes(handler), scimMiddleware(handler)));
303
610
  }
304
611
  wrapAuthenticated(handler) {
612
+ assertHttpHandler(handler);
305
613
  return this.wrap("authenticated", handler);
306
614
  }
307
615
  wrapVerified(handler) {
616
+ assertHttpHandler(handler);
308
617
  const middleware = [...this.group("authenticated"), ...this.verifiedMiddleware()];
309
- return withMiddleware(...middleware)(handler);
618
+ return this.composed(withMiddleware(...middleware)(handler), "json", identityModes(handler), scimMiddleware(handler));
310
619
  }
311
620
  wrapPublicRead(handler, options = {}) {
312
- if (options.allowAnonymous ?? isPublicReadsEnabled()) {
313
- return handler;
621
+ assertHttpHandler(handler);
622
+ if (options.allowAnonymous ?? this.publicReadsEnabled) {
623
+ return this.composed(handler, "json");
314
624
  }
315
625
  return this.wrapAuthenticated(handler);
316
626
  }
317
627
  wrapGlobalAdmin(handler) {
628
+ assertHttpHandler(handler);
318
629
  const middleware = [...this.group("authenticated"), createRequireGlobalAdminMiddleware()];
319
- return withMiddleware(...middleware)(handler);
630
+ return this.composed(withMiddleware(...middleware)(handler), "json", identityModes(handler), scimMiddleware(handler));
320
631
  }
321
632
  wrapAbility(ability, handler) {
633
+ assertHttpHandler(handler);
322
634
  const abilityChecker = resolveAbilityChecker(this.dependencies.container);
323
- const requireAbility = createRequireAbilityMiddleware(abilityChecker);
635
+ const requireAbility = createRequireAbilityMiddleware(abilityChecker, this.viewsEnabled);
324
636
  const middleware = [...this.group("authenticated"), requireAbility(ability)];
325
- return withMiddleware(...middleware)(handler);
637
+ return this.composed(withMiddleware(...middleware)(handler), "json", identityModes(handler), scimMiddleware(handler));
326
638
  }
327
639
  wrapPolicy(resource, action, handler) {
328
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
640
+ assertHttpHandler(handler);
641
+ const auth = establishedAuthReader2;
329
642
  const gate = this.dependencies.container.resolve(CORE_POLICY_GATE_TOKEN);
330
- return withMiddleware(createAuthorizeMiddleware(gate, auth, resource, action))(handler);
643
+ return this.composed(withMiddleware(createAuthorizeMiddleware(gate, auth, resource, action))(handler), "json", identityModes(handler), scimMiddleware(handler));
331
644
  }
332
645
  wrapLogin(handler) {
333
- return this.wrapThrottle("login", resolveLoginRateLimit(), handler);
646
+ assertHttpHandler(handler);
647
+ return this.wrapThrottle("login", this.responsePolicy.loginRateLimit ?? resolveLoginRateLimit(), handler);
334
648
  }
335
649
  wrapSigned(handler) {
336
- return withMiddleware(createValidateSignatureMiddleware())(handler);
650
+ assertHttpHandler(handler);
651
+ const secret = this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).signatureSecret;
652
+ if (!secret)
653
+ throw new Error("Explicit signed URL configuration is required.");
654
+ return this.composed(withMiddleware(createValidateSignatureMiddleware({ secret }))(handler), "json", identityModes(handler), scimMiddleware(handler));
337
655
  }
338
656
  wrapRegister(handler) {
339
- return this.wrapThrottle("register", resolveRegisterRateLimit(), handler);
657
+ assertHttpHandler(handler);
658
+ return this.wrapThrottle("register", this.responsePolicy.registerRateLimit ?? resolveRegisterRateLimit(), handler);
340
659
  }
341
660
  wrapWebAuth(handler, options) {
342
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
661
+ assertHttpHandler(handler);
662
+ const auth = establishedAuthReader2;
343
663
  const middleware = [
344
- createRequireWebAuthMiddleware(auth),
664
+ createRequireWebAuthMiddleware(auth, this.requireIntendedOptions()),
345
665
  ...options.verified ? this.verifiedMiddleware() : []
346
666
  ];
347
- return this.wrapWeb(withMiddleware(...middleware)(handler));
667
+ return this.wrapWeb(this.composed(withMiddleware(...middleware)(handler), "web", identityModes(handler), scimMiddleware(handler)));
348
668
  }
349
669
  verifiedMiddleware() {
350
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
351
- return [createRequireVerifiedMiddleware(auth)];
670
+ const auth = establishedAuthReader2;
671
+ return [
672
+ createRequireVerifiedMiddleware(auth, this.emailVerificationRequired, this.requireIntendedOptions())
673
+ ];
352
674
  }
353
675
  wrapThrottle(scope, rateLimit, handler) {
676
+ assertHttpHandler(handler);
354
677
  const memoryKeyPrefix = scope === "login" ? "login-throttle:" : "register-throttle:";
355
678
  const redisUrl = this.dependencies.container.has(CORE_CONFIG_TOKEN) ? this.dependencies.container.resolve(CORE_CONFIG_TOKEN).get(REDIS_URL_CONFIG_KEY)?.trim() ?? "" : "";
356
679
  if (scope === "login") {
357
- return withMiddleware(this.ownThrottle(createLoginThrottleMiddleware({
680
+ return this.composed(withMiddleware(this.ownThrottle(createLoginThrottleMiddleware({
681
+ namespace: this.responsePolicy.namespace,
682
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
358
683
  ...redisUrl ? { redisUrl } : {},
359
684
  maxAttempts: rateLimit.maxAttempts,
360
685
  decaySeconds: rateLimit.decaySeconds
361
- })))(handler);
686
+ })))(handler), "json", identityModes(handler), scimMiddleware(handler));
362
687
  }
363
688
  if (redisUrl) {
364
- return withMiddleware(this.ownThrottle(createThrottleMiddleware({
689
+ return this.composed(withMiddleware(this.ownThrottle(createThrottleMiddleware({
690
+ namespace: this.responsePolicy.namespace,
691
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
365
692
  redisUrl,
366
693
  maxAttempts: rateLimit.maxAttempts,
367
694
  decaySeconds: rateLimit.decaySeconds,
368
695
  keyPrefix: memoryKeyPrefix
369
- })))(handler);
696
+ })))(handler), "json", identityModes(handler), scimMiddleware(handler));
370
697
  }
371
- return withMiddleware(this.ownThrottle(createMemoryThrottleMiddleware({
698
+ return this.composed(withMiddleware(this.ownThrottle(createMemoryThrottleMiddleware({
699
+ namespace: this.responsePolicy.namespace,
700
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
372
701
  maxAttempts: rateLimit.maxAttempts,
373
702
  decaySeconds: rateLimit.decaySeconds,
374
703
  keyPrefix: memoryKeyPrefix
375
- })))(handler);
704
+ })))(handler), "json", identityModes(handler), scimMiddleware(handler));
376
705
  }
377
706
  }
378
707
  function createHttpKernel(dependencies) {
379
708
  return new HttpKernel(dependencies);
380
709
  }
381
710
 
382
- // ../../src/bootstrap/moduleRouteMiddleware.ts
383
- import { applyMiddlewareToRoutes } from "@getstrata/core/http/middleware";
384
- function wrapCallback(path, callback, middleware) {
385
- return applyMiddlewareToRoutes({ [path]: callback }, middleware)[path];
386
- }
387
- function applyModuleRouteMiddleware(routes, middleware) {
388
- const wrapped = {};
389
- for (const [path, value] of Object.entries(routes)) {
390
- if (value instanceof Response) {
391
- const methods = {};
392
- for (const method of ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]) {
393
- methods[method] = wrapCallback(path, () => value.clone(), middleware);
394
- }
395
- wrapped[path] = methods;
396
- continue;
397
- }
398
- if (typeof value === "function") {
399
- wrapped[path] = wrapCallback(path, value, middleware);
400
- continue;
401
- }
402
- if (value && typeof value === "object" && !Array.isArray(value)) {
403
- const entries = Object.entries(value);
404
- if (entries.some(([, handler]) => typeof handler === "function" || handler instanceof Response)) {
405
- wrapped[path] = Object.fromEntries(entries.map(([method, handler]) => {
406
- const callback = handler instanceof Response ? () => handler.clone() : handler;
407
- return [
408
- method,
409
- typeof callback === "function" ? wrapCallback(path, callback, middleware) : callback
410
- ];
411
- }));
412
- continue;
413
- }
414
- }
415
- wrapped[path] = value;
416
- }
417
- return wrapped;
711
+ // ../../src/bootstrap/routeCompiler.ts
712
+ var ROUTE_METHODS = ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"];
713
+ var OPENAPI_METHODS = new Set([...ROUTE_METHODS, "TRACE"]);
714
+ var inventoryKey = Symbol.for("@getstrata/owned-route-inventory");
715
+ function readRouteInventory(routes) {
716
+ return Object.getOwnPropertyDescriptor(routes, inventoryKey)?.value;
418
717
  }
419
-
420
- // ../../src/bootstrap/discoverModules.ts
421
- import { readdir as readdir2 } from "fs/promises";
422
- import { join as join2, resolve } from "path";
423
-
424
- // ../../src/bootstrap/infrastructureDiscovery.ts
425
- import { readdir } from "fs/promises";
426
- import { join, relative } from "path";
427
- import { pathToFileURL } from "url";
428
- async function infrastructureFiles(directory, exclude = []) {
429
- const excluded = new Set([
430
- "index.ts",
431
- "index.js",
432
- "index.mts",
433
- "index.mjs",
434
- "register.ts",
435
- "register.js",
436
- "register.mts",
437
- "register.mjs",
438
- ...exclude
439
- ]);
440
- const files = [];
441
- async function visit(path) {
442
- const entries = await readdir(path, { withFileTypes: true });
443
- entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
444
- for (const entry of entries) {
445
- const file = join(path, entry.name);
446
- const key = relative(directory, file).replaceAll("\\", "/");
447
- if (excluded.has(entry.name) || excluded.has(key))
448
- continue;
449
- if (entry.isDirectory())
450
- await visit(file);
451
- else if (entry.isFile() && /\.(ts|js|mts|mjs)$/.test(entry.name) && !/\.(d|test|spec)\.[cm]?[jt]s$/.test(entry.name))
452
- files.push(file);
718
+ function immutableCopy(value, ancestors = new Set) {
719
+ if (value === null || typeof value !== "object") {
720
+ if (typeof value === "function" || typeof value === "symbol" || typeof value === "bigint" || typeof value === "number" && !Number.isFinite(value)) {
721
+ throw new Error("Route metadata must contain only JSON values");
453
722
  }
723
+ return value;
454
724
  }
455
- try {
456
- await visit(directory);
457
- } catch (error) {
458
- if (error.code !== "ENOENT")
459
- throw error;
460
- if (error.path !== directory)
461
- throw error;
462
- }
463
- return files;
464
- }
465
- async function importInfrastructure(file) {
466
- try {
467
- return await import(pathToFileURL(file).href);
468
- } catch (error) {
469
- throw new Error(`Cannot load infrastructure module ${file}`, { cause: error });
725
+ if (ancestors.has(value))
726
+ throw new Error("Route metadata must not contain cycles");
727
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
728
+ throw new Error("Route metadata must contain only JSON objects");
470
729
  }
730
+ ancestors.add(value);
731
+ const copy = Array.isArray(value) ? value.map((entry) => immutableCopy(entry, ancestors)) : Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, immutableCopy(entry, ancestors)]));
732
+ ancestors.delete(value);
733
+ return Object.freeze(copy);
471
734
  }
472
-
473
- // ../../src/bootstrap/discoverModules.ts
474
- var KEY = Symbol.for("@getstrata/discoverModulesState");
475
- function state() {
476
- const globals = globalThis;
477
- globals[KEY] ??= { appModules: [] };
478
- return globals[KEY];
479
- }
480
- function configureModulesDirectory(modulesDir) {
481
- const current = state();
482
- const directory = resolve(modulesDir);
483
- if (current.configuredModulesDir !== directory || current.configuredManifest) {
484
- current.appModules.length = 0;
485
- current.modulesReady = undefined;
486
- current.source = undefined;
487
- }
488
- current.configuredManifest = undefined;
489
- current.configuredModulesDir = directory;
735
+ function normalizeRoutePath(path, prefix = "") {
736
+ const normalizedPrefix = prefix.replace(/\/+$/, "");
737
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
738
+ const result = `${normalizedPrefix ? normalizedPrefix.startsWith("/") ? normalizedPrefix : `/${normalizedPrefix}` : ""}${normalizedPath}`;
739
+ if (!path || /[?#\s]/.test(result) || result.includes("//") || result.split("/").some((part) => part === "." || part === "..")) {
740
+ throw new Error(`Invalid route path: ${path}`);
741
+ }
742
+ return result;
490
743
  }
491
- function configureModulesManifest(manifest) {
492
- const current = state();
493
- if (current.configuredManifest !== manifest) {
494
- current.appModules.length = 0;
495
- current.modulesReady = undefined;
496
- current.source = undefined;
497
- }
498
- current.configuredManifest = manifest;
499
- }
500
- function validateModule(value, location) {
501
- if (!value || typeof value !== "object" || Array.isArray(value))
502
- throw new TypeError(`Invalid application module at ${location}.`);
503
- const module = value;
504
- if (typeof module.name !== "string" || !module.name.trim())
505
- throw new TypeError(`Invalid module name at ${location}.`);
506
- if (module.order !== undefined && (typeof module.order !== "number" || !Number.isFinite(module.order)))
507
- throw new TypeError(`Invalid module order at ${location}.`);
508
- for (const hook of ["routes", "webRoutes"])
509
- if (module[hook] !== undefined && typeof module[hook] !== "function")
510
- throw new TypeError(`Invalid ${hook} at ${location}.`);
511
- if (module.providers !== undefined) {
512
- if (!Array.isArray(module.providers))
513
- throw new TypeError(`Invalid providers at ${location}.`);
514
- for (const provider of module.providers) {
515
- if (!provider || typeof provider.name !== "string" || !provider.name.trim() || provider.register !== undefined && typeof provider.register !== "function" || provider.boot !== undefined && typeof provider.boot !== "function")
516
- throw new TypeError(`Invalid provider at ${location}.`);
744
+ function routeMethods(handler) {
745
+ if (handler === false)
746
+ return { methods: [], handler };
747
+ if (handler instanceof Response)
748
+ return {
749
+ methods: [...ROUTE_METHODS],
750
+ handler: Object.freeze(Object.fromEntries(ROUTE_METHODS.map((method) => [method, handler])))
751
+ };
752
+ if (typeof handler === "function")
753
+ return { methods: ["*"], handler };
754
+ if (handler && typeof handler === "object" && !Array.isArray(handler)) {
755
+ const entries = Object.entries(handler);
756
+ if (entries.some(([method, value]) => OPENAPI_METHODS.has(method.toUpperCase()) || typeof value === "function" || value instanceof Response)) {
757
+ const methods = {};
758
+ for (const [rawMethod, value] of entries) {
759
+ const method = rawMethod.toUpperCase();
760
+ if (!ROUTE_METHODS.includes(method)) {
761
+ throw new Error(`Unsupported route method: ${rawMethod}`);
762
+ }
763
+ if (Object.hasOwn(methods, method))
764
+ throw new Error(`Duplicate route method: ${method}`);
765
+ if (typeof value !== "function" && !(value instanceof Response)) {
766
+ throw new Error(`Invalid route handler: ${method}`);
767
+ }
768
+ methods[method] = value;
769
+ }
770
+ return { methods: Object.keys(methods), handler: Object.freeze(methods) };
517
771
  }
518
- }
519
- }
520
- async function load(options) {
521
- const manifest = options.manifest ?? (options.modulesDir === undefined ? state().configuredManifest : undefined);
522
- const entries = [];
523
- if (manifest)
524
- for (const [index, value] of manifest.entries())
525
- entries.push({ value, location: `module manifest[${index}]` });
526
- else {
527
- const directory = options.modulesDir ?? state().configuredModulesDir;
528
- if (!directory)
529
- throw new Error("configureModulesDirectory() or configureModulesManifest() must be called before discovering modules.");
530
- let folders;
531
- try {
532
- folders = await readdir2(directory, { withFileTypes: true });
533
- } catch (error) {
534
- if (error.code === "ENOENT")
535
- return [];
536
- throw error;
772
+ if (Object.prototype.toString.call(handler) === "[object HTMLBundle]") {
773
+ return { methods: ["GET", "HEAD"], handler };
774
+ }
775
+ if (handler instanceof Blob && "exists" in handler && typeof handler.exists === "function") {
776
+ return { methods: ["*"], handler };
537
777
  }
538
- const excluded = new Set(options.exclude ?? []);
539
- for (const folder of folders.filter((entry) => entry.isDirectory() && !excluded.has(entry.name)).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
540
- const path = join2(directory, folder.name);
541
- const files = await readdir2(path);
542
- const candidates = files.filter((file) => /^index\.(ts|js|mts|mjs)$/.test(file));
543
- if (candidates.length !== 1)
544
- throw new Error(`Expected one module entrypoint at ${path}; found ${candidates.length}.`);
545
- const file = join2(path, candidates[0]);
546
- const exports = await importInfrastructure(file);
547
- entries.push({ value: exports.default, location: file });
778
+ if (Object.getPrototypeOf(handler) === Object.prototype && "dir" in handler && typeof handler.dir === "string" && handler.dir.length > 0 && entries.every(([key, value]) => key === "dir" || key === "statCache" && typeof value === "boolean")) {
779
+ return { methods: ["*"], handler: Object.freeze({ ...handler }) };
548
780
  }
781
+ throw new Error("Invalid route method map or native route declaration");
549
782
  }
550
- const names = new Map;
551
- const modules = [];
552
- for (const { value, location } of entries) {
553
- validateModule(value, location);
554
- const previous = names.get(value.name);
555
- if (previous)
556
- throw new Error(`Duplicate module "${value.name}" at ${location}; first declared at ${previous}.`);
557
- names.set(value.name, location);
558
- modules.push(value);
559
- }
560
- return modules.sort((left, right) => (left.order ?? 100) - (right.order ?? 100));
561
- }
562
- function ensureModulesLoaded(options = {}) {
563
- const current = state();
564
- const key = options.manifest ?? (options.modulesDir === undefined ? current.configuredManifest : undefined) ?? JSON.stringify([
565
- options.modulesDir ? resolve(options.modulesDir) : current.configuredModulesDir,
566
- [...options.exclude ?? []].sort()
567
- ]);
568
- if (current.modulesReady && current.source === key)
569
- return current.modulesReady;
570
- current.appModules.length = 0;
571
- current.source = key;
572
- const pending = load(options).then((modules) => {
573
- if (current.modulesReady !== pending)
574
- return modules;
575
- current.appModules.splice(0, current.appModules.length, ...modules);
576
- return current.appModules;
577
- }).catch((error) => {
578
- if (current.modulesReady === pending)
579
- current.modulesReady = undefined;
580
- throw error;
581
- });
582
- current.modulesReady = pending;
583
- return pending;
584
- }
585
- function discoverModules() {
586
- return state().appModules;
783
+ throw new Error("Invalid route handler");
587
784
  }
588
- function resetDiscoverModulesForTests() {
589
- const current = state();
590
- current.configuredModulesDir = undefined;
591
- current.configuredManifest = undefined;
592
- current.appModules.length = 0;
593
- current.modulesReady = undefined;
594
- current.source = undefined;
595
- }
596
- // ../../src/bootstrap/prefixRouteMap.ts
597
- function prefixRouteMap(prefix, routes) {
598
- const normalizedPrefix = prefix.replace(/\/$/, "");
599
- const prefixed = {};
600
- for (const [path, handler] of Object.entries(routes)) {
601
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
602
- prefixed[`${normalizedPrefix}${normalizedPath}`] = handler;
603
- }
604
- return prefixed;
605
- }
606
-
607
- // ../../src/bootstrap/routeRegistry.ts
608
- class RouteRegistry {
609
- routes = [];
610
- register(route) {
611
- this.routes.push(route);
785
+ function compileRoutePlan(sources, prefix = "") {
786
+ const routes = Object.create(null);
787
+ const owners = new Map;
788
+ const inventory = [];
789
+ const canonicalPaths = new Map;
790
+ const implicitHeads = new Map;
791
+ for (const source of sources) {
792
+ for (const path of Object.keys(source.metadata ?? {})) {
793
+ if (!Object.hasOwn(source.routes, path)) {
794
+ throw new Error(`OpenAPI metadata has no API route: ${source.name} ${path}`);
795
+ }
796
+ }
797
+ for (const [rawPath, rawHandler] of Object.entries(source.routes)) {
798
+ const path = normalizeRoutePath(rawPath, prefix);
799
+ const { methods, handler } = routeMethods(rawHandler);
800
+ if (handler && typeof handler === "object" && "dir" in handler && !path.endsWith("/*")) {
801
+ throw new Error(`Directory route must end in /*: ${path}`);
802
+ }
803
+ const collisionPath = path.replace(/:[^/]+/g, ":parameter");
804
+ const canonicalPath = canonicalPaths.get(collisionPath);
805
+ if (canonicalPath && canonicalPath !== path) {
806
+ throw new Error(`Ambiguous route parameter names: ${canonicalPath} and ${path}`);
807
+ }
808
+ canonicalPaths.set(collisionPath, path);
809
+ const previous = owners.get(collisionPath) ?? new Map;
810
+ for (const method of methods) {
811
+ if (previous.has(method) || previous.has("*") || method === "*" && previous.size) {
812
+ throw new Error(`Duplicate route: ${method} ${path} (${[...previous.values()][0]} and ${source.name})`);
813
+ }
814
+ }
815
+ const metadata = source.metadata?.[rawPath];
816
+ for (const method of Object.keys(metadata ?? {})) {
817
+ if (!OPENAPI_METHODS.has(method) || !methods.includes("*") && !methods.includes(method) && !(method === "HEAD" && methods.includes("GET"))) {
818
+ throw new Error(`OpenAPI metadata has no API handler: ${method} ${rawPath}`);
819
+ }
820
+ }
821
+ const inherited = readRouteInventory(source.routes)?.filter((entry) => entry.path === rawPath);
822
+ if (inherited) {
823
+ inventory.push(...inherited.filter((entry) => entry.method !== "HEAD" || !methods.includes("GET") || methods.includes("HEAD")).map((entry) => ({ ...entry, path })));
824
+ } else {
825
+ for (const method of methods) {
826
+ const openApi = metadata?.[method];
827
+ inventory.push({
828
+ method,
829
+ path,
830
+ middleware: source.middleware ?? [],
831
+ ...openApi ? { openApi } : {}
832
+ });
833
+ }
834
+ if (methods.includes("*")) {
835
+ for (const [method, openApi] of Object.entries(metadata ?? {})) {
836
+ inventory.push({
837
+ method,
838
+ path,
839
+ middleware: source.middleware ?? [],
840
+ ...openApi ? { openApi } : {}
841
+ });
842
+ }
843
+ }
844
+ }
845
+ if (methods.includes("GET") && !methods.includes("HEAD")) {
846
+ const openApi = metadata?.HEAD ?? inherited?.find((entry) => entry.method === "HEAD")?.openApi;
847
+ implicitHeads.set(path, {
848
+ method: "HEAD",
849
+ path,
850
+ middleware: inherited?.find((entry) => entry.method === "GET")?.middleware ?? source.middleware ?? [],
851
+ ...openApi ? { openApi } : {}
852
+ });
853
+ }
854
+ for (const method of methods)
855
+ previous.set(method, source.name);
856
+ owners.set(collisionPath, previous);
857
+ if (Object.hasOwn(routes, path)) {
858
+ if (routes[path] === false || handler === false || Object.prototype.toString.call(routes[path]) === "[object HTMLBundle]" || Object.prototype.toString.call(handler) === "[object HTMLBundle]") {
859
+ throw new Error(`Cannot merge native bundle route: ${path}`);
860
+ }
861
+ routes[path] = Object.freeze({ ...routes[path], ...handler });
862
+ } else {
863
+ routes[path] = handler;
864
+ }
865
+ }
612
866
  }
613
- clear() {
614
- this.routes.length = 0;
867
+ for (const [path, head] of implicitHeads) {
868
+ if (!inventory.some((entry) => entry.path === path && entry.method === "HEAD"))
869
+ inventory.push(head);
615
870
  }
616
- list() {
617
- return [...this.routes].sort((left, right) => left.path.localeCompare(right.path));
871
+ const snapshot = immutableCopy(inventory.sort((left, right) => left.path.localeCompare(right.path)));
872
+ return Object.freeze({ routes: attachRouteInventory(routes, snapshot), inventory: snapshot });
873
+ }
874
+ function attachRouteInventory(routes, inventory) {
875
+ for (const value of Object.values(routes)) {
876
+ if (value && typeof value === "object" && !(value instanceof Response) && Object.keys(value).some((method) => ROUTE_METHODS.includes(method))) {
877
+ Object.freeze(value);
878
+ }
618
879
  }
880
+ Object.defineProperty(routes, inventoryKey, { value: inventory, enumerable: false });
881
+ return Object.freeze(routes);
619
882
  }
620
- var ROUTE_REGISTRY_KEY = Symbol.for("@getstrata/routeRegistry");
621
- function readSharedRouteRegistry() {
622
- const globalRegistry = globalThis[ROUTE_REGISTRY_KEY];
623
- if (globalRegistry) {
624
- return globalRegistry;
625
- }
626
- const registry = new RouteRegistry;
627
- globalThis[ROUTE_REGISTRY_KEY] = registry;
628
- return registry;
883
+ function getRouteInventory(routes) {
884
+ const inventory = readRouteInventory(routes);
885
+ if (!inventory)
886
+ throw new Error("Route map has not been compiled");
887
+ return inventory;
629
888
  }
630
- var routeRegistry = readSharedRouteRegistry();
631
889
 
632
890
  // ../../src/bootstrap/routeMetadata.ts
633
- function registerOpenApiRoute(method, path, middleware, openApi) {
634
- routeRegistry.register({ method, path, middleware, ...openApi ? { openApi } : {} });
635
- }
636
- function registerOpenApiRouteMap(routes, middleware, metadata = {}) {
637
- const registered = {};
638
- for (const [path, handler] of Object.entries(routes)) {
639
- if (handler && typeof handler === "object" && !Array.isArray(handler)) {
640
- const methodMap = handler;
641
- registered[path] = methodMap;
642
- for (const method of Object.keys(methodMap)) {
643
- registerOpenApiRoute(method.toUpperCase(), path, middleware, metadata[path]?.[method.toUpperCase()]);
644
- }
645
- continue;
646
- }
647
- registered[path] = handler;
648
- registerOpenApiRoute("GET", path, middleware, metadata[path]?.GET);
649
- }
650
- return registered;
891
+ function publishRoutePlan(plan, routes = plan.routes) {
892
+ return attachRouteInventory(routes, plan.inventory);
651
893
  }
652
894
 
653
895
  // ../../src/bootstrap/buildModuleRoutes.ts
654
- function prefixApiModuleRoutes(prefix, routes, metadata) {
655
- const entries = Object.fromEntries(Object.entries(routes).map(([path, handler]) => [path, { handler, openApi: metadata[path] }]));
656
- const prefixedRoutes = {};
657
- const prefixedMetadata = {};
658
- for (const [path, entry] of Object.entries(prefixRouteMap(prefix, entries))) {
659
- prefixedRoutes[path] = entry.handler;
660
- if (entry.openApi)
661
- prefixedMetadata[path] = entry.openApi;
662
- }
663
- return { routes: prefixedRoutes, metadata: prefixedMetadata };
664
- }
665
- function buildModuleRoutes(dependencies, options = {}) {
666
- const { apiPrefix = "", modules = discoverModules(), clearRegistry = true } = options;
667
- if (clearRegistry) {
668
- routeRegistry.clear();
669
- }
896
+ function buildModuleRoutes(dependencies, options) {
897
+ const { apiPrefix = "", modules } = options;
670
898
  const kernel = createHttpKernel(dependencies);
671
- const middleware = [...kernel.globalMiddleware(), ...kernel.group("api")];
672
- const cachedJson = createCachedJson(dependencies);
673
- const moduleRoutes = {};
674
- const metadata = {};
899
+ const middleware = kernel.group("api");
900
+ const cachedJson = createApplicationCachedJson(dependencies);
901
+ const sources = [];
675
902
  for (const module of modules) {
676
- if (!module.routes) {
903
+ if (!module.routes && !module.openApi) {
677
904
  continue;
678
905
  }
679
- const routes = module.routes({ dependencies, cachedJson, kernel });
680
- for (const [path, operations] of Object.entries(module.openApi ?? {})) {
681
- if (!(path in routes))
682
- throw new Error(`OpenAPI metadata has no API route: ${module.name} ${path}`);
683
- const methods = typeof routes[path] === "function" ? ["GET"] : Object.keys(routes[path]).map((method) => method.toUpperCase());
684
- for (const method of Object.keys(operations))
685
- if (!methods.includes(method))
686
- throw new Error(`OpenAPI metadata has no API handler: ${method} ${path}`);
687
- }
688
- for (const path of Object.keys(routes)) {
689
- delete metadata[path];
690
- if (module.openApi?.[path])
691
- metadata[path] = module.openApi[path];
692
- }
693
- Object.assign(moduleRoutes, routes);
906
+ sources.push({
907
+ name: module.name,
908
+ routes: module.routes?.({ dependencies, cachedJson, kernel }) ?? {},
909
+ metadata: module.openApi,
910
+ middleware: ["global", "api"]
911
+ });
694
912
  }
695
- const prefixed = prefixApiModuleRoutes(apiPrefix, moduleRoutes, metadata);
696
- return applyModuleRouteMiddleware(registerOpenApiRouteMap(prefixed.routes, ["global", "api"], prefixed.metadata), middleware);
913
+ const plan = compileRoutePlan(sources, apiPrefix);
914
+ const routes = enterModuleRoutes(plan.routes, (callback) => kernel.composed(withMiddleware2(...middleware)(callback), "json", identityModes2(callback), scimMiddleware2(callback)));
915
+ return publishRoutePlan(plan, routes);
697
916
  }
698
917
  export {
699
- buildModuleRoutes,
700
- registerOpenApiRouteMap
918
+ buildModuleRoutes
701
919
  };