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