@getstrata/bootstrap 2.2.60 → 3.0.5

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 +35 -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,15 +1,14 @@
1
1
  // @bun
2
2
  // ../../src/bootstrap/httpKernel.ts
3
+ import { establishedAuthReader as establishedAuthReader2 } from "@getstrata/core/auth/authReader";
4
+ import { hasVerifiedEmail } from "@getstrata/core/auth/emailVerification";
3
5
  import {
4
- hasVerifiedEmail,
5
- isEmailVerificationRequired
6
- } from "@getstrata/core/auth/emailVerification";
7
- import { createMembershipMiddleware } from "@getstrata/core/auth/membershipMiddleware";
8
- import { resolveAbilityChecker } from "@getstrata/core/contracts/serviceTokens";
9
- import { createAuthMiddleware } from "@getstrata/core/http/authMiddleware";
6
+ CORE_TRACING_RUNTIME_TOKEN,
7
+ resolveAbilityChecker
8
+ } from "@getstrata/core/contracts/serviceTokens";
10
9
  import { createAuthorizeMiddleware } from "@getstrata/core/http/authorizeMiddleware";
11
10
  import { createBodySizeLimitMiddleware } from "@getstrata/core/http/bodySizeLimitMiddleware";
12
- import { createCorsMiddleware } from "@getstrata/core/http/corsMiddleware";
11
+ import { createCorsMiddleware, resolveCorsConfig } from "@getstrata/core/http/corsMiddleware";
13
12
  import { createCsrfMiddleware } from "@getstrata/core/http/csrfMiddleware";
14
13
  import { createFlashMiddleware } from "@getstrata/core/http/flashMiddleware";
15
14
  import { createLoginThrottleMiddleware } from "@getstrata/core/http/loginThrottleMiddleware";
@@ -22,21 +21,21 @@ import { createRequireGlobalAdminMiddleware } from "@getstrata/core/http/require
22
21
  import { createRequirePasswordConfirmMiddleware } from "@getstrata/core/http/requirePasswordConfirmMiddleware";
23
22
  import { createRequireVerifiedMiddleware } from "@getstrata/core/http/requireVerifiedMiddleware";
24
23
  import { createRequireWebAuthMiddleware } from "@getstrata/core/http/requireWebAuthMiddleware";
25
- import {
26
- createJsonErrorMiddleware,
27
- createWebErrorMiddleware,
28
- withErrorHandling,
29
- withJsonErrorHandling
30
- } from "@getstrata/core/http/response";
24
+ import { createJsonErrorMiddleware, createWebErrorMiddleware } from "@getstrata/core/http/response";
31
25
  import { withMiddleware } from "@getstrata/core/http/routeMiddleware";
32
26
  import { createSecurityHeadersMiddleware } from "@getstrata/core/http/securityHeadersMiddleware";
33
27
  import { createValidateSignatureMiddleware } from "@getstrata/core/http/signedUrl";
34
28
  import { createThrottleMiddleware } from "@getstrata/core/http/throttleMiddleware";
35
29
  import { createRequestLoggingMiddleware } from "@getstrata/core/logging/requestLoggingMiddleware";
36
- import { isViewsEnabled } from "@getstrata/core/runtime/frontendMode";
37
- import { isPublicReadsEnabled } from "@getstrata/core/security/publicReads";
38
- import { createTenantMiddleware } from "@getstrata/core/tenant/tenantMiddleware";
39
30
  import { createTracingMiddleware } from "@getstrata/core/tracing/tracingMiddleware";
31
+ import { CORE_WEB_ERROR_VIEW_TOKEN } from "@getstrata/core/view/tokens";
32
+ import {
33
+ assertHttpHandler,
34
+ identityModes,
35
+ ownedHttpRoute,
36
+ ownedPublicHttpRoute,
37
+ scimMiddleware
38
+ } from "#strata-http-route";
40
39
 
41
40
  // ../../src/bootstrap/config.ts
42
41
  import {
@@ -51,8 +50,7 @@ import {
51
50
  CORE_PUBLIC_TENANCY_TOKEN,
52
51
  CORE_QUEUE_TOKEN,
53
52
  CORE_TENANT_RESOLVER_TOKEN,
54
- CORE_THROTTLE_QUOTA_POLICY_TOKEN,
55
- CORE_TOKEN_SERVICE_TOKEN
53
+ CORE_THROTTLE_QUOTA_POLICY_TOKEN
56
54
  } from "@getstrata/core/contracts/serviceTokens";
57
55
  var APP_PORT_CONFIG_KEY = "app.port";
58
56
  var CACHE_TTL_MS_CONFIG_KEY = "cache.ttlMs";
@@ -69,6 +67,189 @@ var DEFAULT_CACHE_DRIVER = "array";
69
67
  var DEFAULT_API_TOKEN = "";
70
68
  var DEFAULT_QUEUE_DRIVER = "sync";
71
69
 
70
+ // ../../src/bootstrap/httpPersistence.ts
71
+ import { establishedAuthReader, runWithEstablishedAuth } from "@getstrata/core/auth/authReader";
72
+ import { validatedAuthOutcome } from "@getstrata/core/auth/guard";
73
+ import { runWithMembershipSnapshot } from "@getstrata/core/auth/membershipContext";
74
+ import { InternalServerError, InvalidCredentialsError } from "@getstrata/core/errors/http";
75
+ import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
76
+ import { errorResponse } from "@getstrata/core/http/response";
77
+ import { webErrorResponse } from "@getstrata/core/http/webErrorResponse";
78
+ import { createPublicTenantSelector } from "@getstrata/core/tenant/publicTenantHost";
79
+ import { runWithTenant } from "@getstrata/core/tenant/tenantContext";
80
+ import { DEFAULT_TENANT, resolveTenantForRequest } from "@getstrata/core/tenant/tenantMiddleware";
81
+ import { businessPorts } from "#strata-http-route";
82
+ import { HTTP_PERSISTENCE_OPTIONS } from "#strata-http-route";
83
+ function snapshotAuth(input) {
84
+ const auth = validatedAuthOutcome(input);
85
+ if (auth.status === "error")
86
+ throw Object.assign(new InternalServerError, { cause: auth.error });
87
+ if (auth.status === "invalid")
88
+ throw new InvalidCredentialsError;
89
+ const user = auth.user;
90
+ const name = user?.name;
91
+ const email = user?.email;
92
+ return Object.freeze({
93
+ credentialSource: auth.credentialSource,
94
+ user: user ? Object.freeze({
95
+ id: user.id,
96
+ ...typeof name === "string" ? { name } : {},
97
+ ...typeof email === "string" ? { email } : {},
98
+ ...user.role !== undefined ? { role: user.role } : {},
99
+ ...user.isActive !== undefined ? { isActive: user.isActive } : {},
100
+ ...user.authVersion !== undefined ? { authVersion: user.authVersion } : {},
101
+ ...user.tokenId !== undefined ? { tokenId: user.tokenId } : {},
102
+ ...user.abilities ? { abilities: Object.freeze([...user.abilities]) } : {},
103
+ ...user.emailVerifiedAt !== undefined ? {
104
+ emailVerifiedAt: user.emailVerifiedAt instanceof Date ? user.emailVerifiedAt.toISOString() : user.emailVerifiedAt
105
+ } : {}
106
+ }) : null
107
+ });
108
+ }
109
+ function snapshotTenant(tenant) {
110
+ const snapshot = structuredClone(tenant);
111
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot) || !Number.isSafeInteger(snapshot.id) || snapshot.id < 1 || typeof snapshot.slug !== "string")
112
+ throw new TypeError("HTTP metadata must establish a valid tenant identity.");
113
+ return Object.freeze(snapshot);
114
+ }
115
+ function createHttpPersistence(invoke, options) {
116
+ const invalidSessionCookie = options.invalidSessionCookie ? Object.freeze({ ...options.invalidSessionCookie }) : undefined;
117
+ const selectPublic = options.publicTenancy ? createPublicTenantSelector(options.publicTenancy) : undefined;
118
+ return async (request, handler, identity, scim = false) => {
119
+ const externalId = currentRequestMeta().requestId;
120
+ const metadata = { routeTemplate: currentRequestMeta().routeTemplate ?? "", phase: "metadata" };
121
+ const established = await invoke({
122
+ kind: "request",
123
+ externalId,
124
+ signal: request.signal,
125
+ metadata,
126
+ actor: { kind: "system", policy: "http.identity-metadata" }
127
+ }, async (ports) => {
128
+ if (scim) {
129
+ if (!options.scim)
130
+ throw new Error("Explicit SCIM metadata authentication is required.");
131
+ const tenant = await options.scim(request, ports.database);
132
+ if (tenant instanceof Response)
133
+ return tenant;
134
+ return Object.freeze({
135
+ auth: Object.freeze({ user: null, credentialSource: "bearer" }),
136
+ memberships: Object.freeze([]),
137
+ tenant: snapshotTenant(tenant)
138
+ });
139
+ }
140
+ const lookup = options.metadata(ports);
141
+ const outcome = validatedAuthOutcome(await lookup.authenticate(request));
142
+ if (outcome.status === "invalid" && outcome.credentialSource === "session" && invalidSessionCookie && request.headers.get("cookie")?.split(";").some((part) => part.trim().startsWith(`${invalidSessionCookie.name}=`))) {
143
+ const error = new InvalidCredentialsError;
144
+ const response = await webErrorResponse(error, request) ?? errorResponse(error);
145
+ response.headers.append("Set-Cookie", invalidSessionCookie.expiredHeader);
146
+ return response;
147
+ }
148
+ const auth = snapshotAuth(outcome);
149
+ const memberships = auth.user ? await lookup.memberships(auth.user) : [];
150
+ const resolveTenant = async (id) => {
151
+ const result = await lookup.tenant(id);
152
+ if (result === null)
153
+ return null;
154
+ const snapshot = snapshotTenant(result);
155
+ if (snapshot.id !== id)
156
+ throw new Error("Tenant resolver returned a different tenant identity.");
157
+ return snapshot;
158
+ };
159
+ const tenant = options.tenancy === "none" ? snapshotTenant(DEFAULT_TENANT) : await resolveTenantForRequest(request, {
160
+ auth,
161
+ config: {
162
+ enabled: true,
163
+ production: options.production,
164
+ allowDevHeaders: options.allowTenantDevHeaders
165
+ },
166
+ resolveTenant,
167
+ userTenantId: lookup.userTenantId
168
+ }, resolveTenant, selectPublic);
169
+ return Object.freeze({
170
+ auth,
171
+ tenant,
172
+ memberships: Object.freeze(memberships.map((row) => Object.freeze({ ...row })))
173
+ });
174
+ });
175
+ if (established instanceof Response)
176
+ return established;
177
+ const claims = {};
178
+ if (established.auth.user) {
179
+ for (const [key, value] of Object.entries(established.auth.user))
180
+ if (value !== undefined) {
181
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || Array.isArray(value))
182
+ claims[key] = value;
183
+ }
184
+ }
185
+ return invoke({
186
+ kind: "request",
187
+ externalId,
188
+ signal: request.signal,
189
+ metadata: {
190
+ ...metadata,
191
+ phase: identity ? "identity-operation" : "business",
192
+ credentialSource: established.auth.credentialSource
193
+ },
194
+ ...scim ? { actor: { kind: "system", policy: "http.scim" } } : identity ? { actor: { kind: "system", policy: "http.identity-operation" } } : established.auth.user ? { actor: { kind: "principal", claims } } : {},
195
+ tenant: { id: established.tenant.id, slug: established.tenant.slug }
196
+ }, (ports) => {
197
+ const policy = Object.freeze({
198
+ run: (selected, mode, work) => {
199
+ const allowed = mode.kind === "tenant" ? identity === undefined : identity?.includes(mode.kind) === true;
200
+ if (!allowed)
201
+ throw new Error("Database policy is not allowed by this route declaration.");
202
+ return ports.policy.run(selected, mode, work);
203
+ }
204
+ });
205
+ const work = (database) => runWithEstablishedAuth(request, established.auth, () => runWithMembershipSnapshot(established.memberships, () => {
206
+ const execute = () => handler(request, businessPorts({
207
+ database,
208
+ auth: establishedAuthReader,
209
+ established,
210
+ policy
211
+ }));
212
+ return runWithTenant(established.tenant, execute);
213
+ }));
214
+ return !identity && options.tenancy === "rls" ? ports.policy.run(ports.database, { kind: "tenant", tenantId: established.tenant.id }, work) : work(ports.database);
215
+ });
216
+ };
217
+ }
218
+
219
+ // ../../src/bootstrap/moduleRouteMiddleware.ts
220
+ function enterModuleRoutes(routes, enter) {
221
+ const wrapped = {};
222
+ for (const [path, value] of Object.entries(routes)) {
223
+ if (value instanceof Response) {
224
+ const methods = {};
225
+ for (const method of ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]) {
226
+ methods[method] = enter(() => value.clone());
227
+ }
228
+ wrapped[path] = methods;
229
+ continue;
230
+ }
231
+ if (typeof value === "function") {
232
+ wrapped[path] = enter(value);
233
+ continue;
234
+ }
235
+ if (value && typeof value === "object" && !Array.isArray(value)) {
236
+ const entries = Object.entries(value);
237
+ if (entries.some(([, handler]) => typeof handler === "function" || handler instanceof Response)) {
238
+ wrapped[path] = Object.fromEntries(entries.map(([method, handler]) => {
239
+ const callback = handler instanceof Response ? () => handler.clone() : handler;
240
+ return [
241
+ method,
242
+ typeof callback === "function" ? enter(callback) : callback
243
+ ];
244
+ }));
245
+ continue;
246
+ }
247
+ }
248
+ wrapped[path] = value;
249
+ }
250
+ return wrapped;
251
+ }
252
+
72
253
  // ../../src/bootstrap/rateLimit.ts
73
254
  var LOCAL_LOGIN_RATE_LIMIT = {
74
255
  maxAttempts: 100,
@@ -78,9 +259,6 @@ var PRODUCTION_LOGIN_RATE_LIMIT = {
78
259
  maxAttempts: 5,
79
260
  decaySeconds: 900
80
261
  };
81
- function isLocalAppEnv() {
82
- return (process.env.APP_ENV ?? "local") === "local";
83
- }
84
262
  function parsePositiveInt(value, fallback) {
85
263
  const parsed = Number(value);
86
264
  if (!Number.isFinite(parsed) || parsed <= 0) {
@@ -100,18 +278,18 @@ function parseWindowSeconds(secondsValue, msValue, fallback) {
100
278
  }
101
279
  return fallback;
102
280
  }
103
- function resolveLoginRateLimit() {
104
- const defaults = isLocalAppEnv() ? LOCAL_LOGIN_RATE_LIMIT : PRODUCTION_LOGIN_RATE_LIMIT;
281
+ function resolveLoginRateLimit(env = {}) {
282
+ const defaults = env.APP_ENV === "local" ? LOCAL_LOGIN_RATE_LIMIT : PRODUCTION_LOGIN_RATE_LIMIT;
105
283
  return {
106
- maxAttempts: parsePositiveInt(process.env.LOGIN_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
107
- decaySeconds: parseWindowSeconds(process.env.LOGIN_RATE_LIMIT_WINDOW_SECONDS, process.env.LOGIN_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
284
+ maxAttempts: parsePositiveInt(env.LOGIN_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
285
+ decaySeconds: parseWindowSeconds(env.LOGIN_RATE_LIMIT_WINDOW_SECONDS, env.LOGIN_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
108
286
  };
109
287
  }
110
- function resolveRegisterRateLimit() {
111
- const defaults = isLocalAppEnv() ? { maxAttempts: 100, decaySeconds: 60 } : { maxAttempts: 10, decaySeconds: 60 };
288
+ function resolveRegisterRateLimit(env = {}) {
289
+ const defaults = env.APP_ENV === "local" ? { maxAttempts: 100, decaySeconds: 60 } : { maxAttempts: 10, decaySeconds: 60 };
112
290
  return {
113
- maxAttempts: parsePositiveInt(process.env.REGISTER_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
114
- decaySeconds: parseWindowSeconds(process.env.REGISTER_RATE_LIMIT_WINDOW_SECONDS, process.env.REGISTER_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
291
+ maxAttempts: parsePositiveInt(env.REGISTER_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
292
+ decaySeconds: parseWindowSeconds(env.REGISTER_RATE_LIMIT_WINDOW_SECONDS, env.REGISTER_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
115
293
  };
116
294
  }
117
295
 
@@ -120,15 +298,78 @@ class HttpKernel {
120
298
  dependencies;
121
299
  ownedThrottles = new Set;
122
300
  disposed = false;
301
+ emailVerificationRequired;
302
+ viewsEnabled;
303
+ publicReadsEnabled;
304
+ etagEnabled;
305
+ httpOptions;
306
+ responsePolicy;
123
307
  configuredCsrfMiddleware;
308
+ responses;
309
+ persistence;
124
310
  constructor(dependencies) {
125
311
  this.dependencies = dependencies;
312
+ const http = dependencies.container.has(HTTP_PERSISTENCE_OPTIONS) ? dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS) : undefined;
313
+ this.httpOptions = http;
314
+ const config = dependencies.container.has(CORE_CONFIG_TOKEN) ? dependencies.container.resolve(CORE_CONFIG_TOKEN) : undefined;
315
+ const features = http?.features ?? config?.get("http.features");
316
+ this.emailVerificationRequired = features?.emailVerificationRequired ?? false;
317
+ this.viewsEnabled = features?.viewsEnabled ?? false;
318
+ this.publicReadsEnabled = features?.publicReadsEnabled ?? false;
319
+ this.etagEnabled = features?.etagEnabled ?? true;
320
+ const policy = http?.responsePolicy ?? config?.get("http.responsePolicy");
321
+ if (policy?.cors)
322
+ resolveCorsConfig(policy.cors);
323
+ this.responsePolicy = Object.freeze({
324
+ cors: policy?.cors ? {
325
+ allowedOrigins: [...policy.cors.allowedOrigins ?? []],
326
+ additionalAllowedHeaders: [...policy.cors.additionalAllowedHeaders ?? []]
327
+ } : undefined,
328
+ securityHeaders: policy?.securityHeaders ?? {
329
+ production: http?.production ?? true,
330
+ frontendMode: this.viewsEnabled ? "server-htmx" : "api"
331
+ },
332
+ maxBodyBytes: policy?.maxBodyBytes ?? 1048576,
333
+ rateLimitPerMinute: policy?.rateLimitPerMinute ?? 120,
334
+ namespace: policy?.namespace ?? "strata",
335
+ trustForwardedFor: policy?.trustForwardedFor ?? false,
336
+ loginRateLimit: Object.freeze({ ...policy?.loginRateLimit ?? resolveLoginRateLimit() }),
337
+ registerRateLimit: Object.freeze({
338
+ ...policy?.registerRateLimit ?? resolveRegisterRateLimit()
339
+ })
340
+ });
126
341
  const targetOrigin = dependencies.container.has(CORE_CONFIG_TOKEN) ? dependencies.container.resolve(CORE_CONFIG_TOKEN).get(CSRF_TARGET_ORIGIN_CONFIG_KEY) : undefined;
127
- this.configuredCsrfMiddleware = createCsrfMiddleware({ targetOrigin });
342
+ this.configuredCsrfMiddleware = createCsrfMiddleware({ targetOrigin, ...http?.csrf });
343
+ this.responses = Object.freeze({
344
+ json: Object.freeze(this.responseMiddleware("json")),
345
+ web: Object.freeze(this.responseMiddleware("web"))
346
+ });
347
+ this.persistence = dependencies.container.has(HTTP_PERSISTENCE_OPTIONS) ? createHttpPersistence(dependencies.invoke, dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS)) : undefined;
128
348
  if (dependencies.container.has(CORE_HTTP_CLEANUP_TOKEN)) {
129
349
  dependencies.container.resolve(CORE_HTTP_CLEANUP_TOKEN)(() => this.dispose());
130
350
  }
131
351
  }
352
+ requireFlashOptions() {
353
+ const options = this.httpOptions?.flash;
354
+ if (!options)
355
+ throw new TypeError("Explicit flash configuration is required for web routes.");
356
+ return options;
357
+ }
358
+ requireIntendedOptions() {
359
+ const options = this.httpOptions?.intendedUrl;
360
+ if (!options)
361
+ throw new TypeError("Explicit intended URL cookie configuration is required for web authentication.");
362
+ return options;
363
+ }
364
+ routeModelBindingPorts(auth) {
365
+ const gate = this.dependencies.container.resolve(CORE_POLICY_GATE_TOKEN);
366
+ const authorize = gate.authorize;
367
+ return Object.freeze({
368
+ auth,
369
+ authorize: (...args) => authorize.call(gate, ...args),
370
+ etagEnabled: this.etagEnabled
371
+ });
372
+ }
132
373
  dispose() {
133
374
  this.disposed = true;
134
375
  const owned = [...this.ownedThrottles];
@@ -156,39 +397,73 @@ class HttpKernel {
156
397
  return throttle;
157
398
  }
158
399
  globalMiddleware(errorFormat = "json") {
159
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
160
- return [
161
- ...this.responseMiddleware(errorFormat),
162
- createAuthMiddleware(auth),
163
- createMembershipMiddleware(),
164
- createTenantMiddleware({
165
- publicTenancy: this.dependencies.container.has(CORE_PUBLIC_TENANCY_TOKEN) ? this.dependencies.container.resolve(CORE_PUBLIC_TENANCY_TOKEN) : undefined,
166
- resolveTenant: this.dependencies.container.has(CORE_TENANT_RESOLVER_TOKEN) ? this.dependencies.container.resolve(CORE_TENANT_RESOLVER_TOKEN) : undefined
167
- })
168
- ];
400
+ return [...this.responses[errorFormat]];
401
+ }
402
+ run(request, handler, format = "json", identity, scim) {
403
+ assertHttpHandler(handler);
404
+ const execute = this.persistence;
405
+ if (!execute)
406
+ throw new Error("Explicit HTTP persistence composition is required.");
407
+ const outer = withMiddleware(...this.responses[format])((req) => withMiddleware(...scim ?? [])((req) => execute(req, handler, identity, scim !== undefined))(req));
408
+ return Promise.resolve(outer(request));
409
+ }
410
+ composed(handler, format, identity = identityModes(handler), scim = scimMiddleware(handler)) {
411
+ assertHttpHandler(handler);
412
+ if (identity !== undefined && scim !== undefined)
413
+ throw new TypeError("SCIM and identity operation declarations cannot be combined.");
414
+ return ownedHttpRoute(handler, (request, work) => this.run(request, work, format, identity, scim), identity, scim);
415
+ }
416
+ wrapIdentity(handler, modes = ["identifier"]) {
417
+ assertHttpHandler(handler);
418
+ if (scimMiddleware(handler) !== undefined)
419
+ throw new TypeError("SCIM and identity operation declarations cannot be combined.");
420
+ if (!Array.isArray(modes) || modes.some((mode) => mode !== "identifier" && mode !== "bypass"))
421
+ throw new TypeError("Invalid identity route policy modes.");
422
+ return this.composed(handler, "web", Object.freeze([...modes]));
423
+ }
424
+ wrapPasswordConfirm(handler) {
425
+ assertHttpHandler(handler);
426
+ const options = this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).passwordConfirmation;
427
+ if (!options)
428
+ throw new Error("Explicit password confirmation configuration is required.");
429
+ return this.composed(withMiddleware(createRequirePasswordConfirmMiddleware(options))(handler), "json", identityModes(handler), scimMiddleware(handler));
430
+ }
431
+ wrapRouteMap(routes, middleware) {
432
+ return enterModuleRoutes(routes, (callback) => this.composed(withMiddleware(...middleware)(callback), "json", identityModes(callback), scimMiddleware(callback)));
433
+ }
434
+ wrapScim(handler, before = []) {
435
+ assertHttpHandler(handler);
436
+ if (identityModes(handler) !== undefined)
437
+ throw new TypeError("SCIM and identity operation declarations cannot be combined.");
438
+ return this.composed(handler, "json", undefined, Object.freeze([...before]));
169
439
  }
170
440
  responseMiddleware(errorFormat) {
171
441
  return [
172
- createCorsMiddleware(),
173
- createSecurityHeadersMiddleware(),
174
- createBodySizeLimitMiddleware(),
175
- createTracingMiddleware(),
442
+ createCorsMiddleware(this.responsePolicy.cors),
443
+ createSecurityHeadersMiddleware(this.responsePolicy.securityHeaders),
444
+ createBodySizeLimitMiddleware(this.responsePolicy.maxBodyBytes),
445
+ ...this.dependencies.container.has(CORE_TRACING_RUNTIME_TOKEN) ? [createTracingMiddleware(this.dependencies.container.resolve(CORE_TRACING_RUNTIME_TOKEN))] : [],
176
446
  createMetricsMiddleware(),
177
- createRequestLoggingMiddleware(),
447
+ createRequestLoggingMiddleware(this.responsePolicy.trustForwardedFor),
178
448
  requestIdMiddleware,
179
- errorFormat === "json" ? createJsonErrorMiddleware() : createWebErrorMiddleware()
449
+ errorFormat === "json" ? createJsonErrorMiddleware() : createWebErrorMiddleware({
450
+ enabled: this.viewsEnabled,
451
+ production: this.dependencies.container.has(HTTP_PERSISTENCE_OPTIONS) ? this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).production ?? true : true,
452
+ render: this.dependencies.container.has(CORE_WEB_ERROR_VIEW_TOKEN) ? this.dependencies.container.resolve(CORE_WEB_ERROR_VIEW_TOKEN) : undefined
453
+ })
180
454
  ];
181
455
  }
182
456
  wrapPublicDocument(handler) {
183
- return withMiddleware(...this.responseMiddleware("web"))(handler);
457
+ assertHttpHandler(handler);
458
+ return ownedPublicHttpRoute(handler, (request, work) => Promise.resolve(withMiddleware(...this.responses.web)(work)(request)));
184
459
  }
185
460
  group(name) {
186
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
461
+ const auth = establishedAuthReader2;
187
462
  switch (name) {
188
463
  case "authenticated":
189
464
  return [createRequireAuthMiddleware(auth)];
190
465
  case "web":
191
- return isViewsEnabled() ? [createFlashMiddleware(), this.configuredCsrfMiddleware] : [];
466
+ return this.viewsEnabled ? [createFlashMiddleware(this.requireFlashOptions()), this.configuredCsrfMiddleware] : [];
192
467
  case "api": {
193
468
  const csrf = this.configuredCsrfMiddleware;
194
469
  if (!this.dependencies.container.has(CORE_CONFIG_TOKEN)) {
@@ -198,9 +473,11 @@ class HttpKernel {
198
473
  const config = this.dependencies.container.resolve(CORE_CONFIG_TOKEN);
199
474
  const redisUrl = config.get(REDIS_URL_CONFIG_KEY)?.trim() ?? "";
200
475
  if (!redisUrl) {
201
- const maxAttempts = Number(process.env.RATE_LIMIT_PER_MINUTE ?? "120");
476
+ const maxAttempts = this.responsePolicy.rateLimitPerMinute ?? 120;
202
477
  return [
203
478
  this.ownThrottle(createMemoryThrottleMiddleware({
479
+ namespace: this.responsePolicy.namespace,
480
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
204
481
  maxAttempts: Number.isFinite(maxAttempts) ? maxAttempts : 120,
205
482
  decaySeconds: 60,
206
483
  quotaPolicy
@@ -208,9 +485,11 @@ class HttpKernel {
208
485
  csrf
209
486
  ];
210
487
  }
211
- const maxAttempts = Number(process.env.RATE_LIMIT_PER_MINUTE ?? "120");
488
+ const maxAttempts = this.responsePolicy.rateLimitPerMinute ?? 120;
212
489
  return [
213
490
  this.ownThrottle(createThrottleMiddleware({
491
+ namespace: this.responsePolicy.namespace,
492
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
214
493
  redisUrl,
215
494
  maxAttempts: Number.isFinite(maxAttempts) ? maxAttempts : 120,
216
495
  decaySeconds: 60,
@@ -224,146 +503,183 @@ class HttpKernel {
224
503
  }
225
504
  }
226
505
  wrap(groups, handler) {
506
+ assertHttpHandler(handler);
227
507
  const names = Array.isArray(groups) ? groups : [groups];
228
508
  const middleware = names.flatMap((name) => this.group(name));
229
509
  const wrapped = middleware.length === 0 ? handler : withMiddleware(...middleware)(handler);
230
510
  if (names.includes("api")) {
231
- return withJsonErrorHandling(wrapped);
511
+ return this.composed(wrapped, "json", identityModes(handler), scimMiddleware(handler));
232
512
  }
233
- return wrapped;
513
+ return this.composed(wrapped, "web", identityModes(handler), scimMiddleware(handler));
234
514
  }
235
515
  wrapApi(handler) {
516
+ assertHttpHandler(handler);
236
517
  return this.wrap(["api", "authenticated"], handler);
237
518
  }
238
519
  wrapWeb(handler) {
239
- return withErrorHandling(this.wrap("web", handler));
520
+ assertHttpHandler(handler);
521
+ return this.wrap("web", handler);
240
522
  }
241
523
  wrapWebGuest(handler, home = "/") {
242
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
243
- return this.wrapWeb(async (request) => {
524
+ assertHttpHandler(handler);
525
+ const auth = establishedAuthReader2;
526
+ const guest = this.wrapWeb(async (request, ports) => {
244
527
  const user = await auth.resolve(request);
245
528
  if (user) {
246
- if (isEmailVerificationRequired() && !hasVerifiedEmail(user)) {
529
+ if (this.emailVerificationRequired && !hasVerifiedEmail(user)) {
247
530
  return Response.redirect("/email/verify", 302);
248
531
  }
249
532
  const location = typeof home === "function" ? await home(user) : home;
250
533
  return Response.redirect(location, 302);
251
534
  }
252
- return handler(request);
535
+ return handler(request, ports);
253
536
  });
537
+ return this.composed(guest, "web", identityModes(handler), scimMiddleware(handler));
254
538
  }
255
539
  wrapWebPublicRead(handler, options = {}) {
256
- if (options.allowAnonymous ?? isPublicReadsEnabled()) {
540
+ assertHttpHandler(handler);
541
+ if (options.allowAnonymous ?? this.publicReadsEnabled) {
257
542
  return this.wrapWeb(handler);
258
543
  }
259
544
  return this.wrapWebAuthenticated(handler);
260
545
  }
261
546
  wrapWebAuthenticated(handler) {
547
+ assertHttpHandler(handler);
262
548
  return this.wrapWebAuth(handler, { verified: true });
263
549
  }
264
550
  wrapWebAuthenticatedAllowUnverified(handler) {
551
+ assertHttpHandler(handler);
265
552
  return this.wrapWebAuth(handler, { verified: false });
266
553
  }
267
554
  wrapWebVerified(handler) {
555
+ assertHttpHandler(handler);
268
556
  return this.wrapWebAuth(handler, { verified: true });
269
557
  }
270
558
  wrapWebPasswordConfirm(handler) {
271
- return this.wrapWebAuth(withMiddleware(createRequirePasswordConfirmMiddleware())(handler), {
559
+ assertHttpHandler(handler);
560
+ const options = this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).passwordConfirmation;
561
+ if (!options)
562
+ throw new Error("Explicit password confirmation configuration is required.");
563
+ return this.wrapWebAuth(this.composed(withMiddleware(createRequirePasswordConfirmMiddleware(options))(handler), "web", identityModes(handler), scimMiddleware(handler)), {
272
564
  verified: true
273
565
  });
274
566
  }
275
567
  wrapWebAbility(ability, handler) {
276
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
568
+ assertHttpHandler(handler);
569
+ const auth = establishedAuthReader2;
277
570
  const abilityChecker = resolveAbilityChecker(this.dependencies.container);
278
- const requireAbility = createRequireAbilityMiddleware(abilityChecker);
571
+ const requireAbility = createRequireAbilityMiddleware(abilityChecker, this.viewsEnabled);
279
572
  const middleware = [
280
- createRequireWebAuthMiddleware(auth),
573
+ createRequireWebAuthMiddleware(auth, this.requireIntendedOptions()),
281
574
  ...this.verifiedMiddleware(),
282
575
  requireAbility(ability)
283
576
  ];
284
- return this.wrapWeb(withMiddleware(...middleware)(handler));
577
+ return this.wrapWeb(this.composed(withMiddleware(...middleware)(handler), "web", identityModes(handler), scimMiddleware(handler)));
285
578
  }
286
579
  wrapWebGlobalAdmin(handler) {
287
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
580
+ assertHttpHandler(handler);
581
+ const auth = establishedAuthReader2;
288
582
  const middleware = [
289
- createRequireWebAuthMiddleware(auth),
583
+ createRequireWebAuthMiddleware(auth, this.requireIntendedOptions()),
290
584
  ...this.verifiedMiddleware(),
291
585
  createRequireGlobalAdminMiddleware()
292
586
  ];
293
- return this.wrapWeb(withMiddleware(...middleware)(handler));
587
+ return this.wrapWeb(this.composed(withMiddleware(...middleware)(handler), "web", identityModes(handler), scimMiddleware(handler)));
294
588
  }
295
589
  wrapAuthenticated(handler) {
590
+ assertHttpHandler(handler);
296
591
  return this.wrap("authenticated", handler);
297
592
  }
298
593
  wrapVerified(handler) {
594
+ assertHttpHandler(handler);
299
595
  const middleware = [...this.group("authenticated"), ...this.verifiedMiddleware()];
300
- return withMiddleware(...middleware)(handler);
596
+ return this.composed(withMiddleware(...middleware)(handler), "json", identityModes(handler), scimMiddleware(handler));
301
597
  }
302
598
  wrapPublicRead(handler, options = {}) {
303
- if (options.allowAnonymous ?? isPublicReadsEnabled()) {
304
- return handler;
599
+ assertHttpHandler(handler);
600
+ if (options.allowAnonymous ?? this.publicReadsEnabled) {
601
+ return this.composed(handler, "json");
305
602
  }
306
603
  return this.wrapAuthenticated(handler);
307
604
  }
308
605
  wrapGlobalAdmin(handler) {
606
+ assertHttpHandler(handler);
309
607
  const middleware = [...this.group("authenticated"), createRequireGlobalAdminMiddleware()];
310
- return withMiddleware(...middleware)(handler);
608
+ return this.composed(withMiddleware(...middleware)(handler), "json", identityModes(handler), scimMiddleware(handler));
311
609
  }
312
610
  wrapAbility(ability, handler) {
611
+ assertHttpHandler(handler);
313
612
  const abilityChecker = resolveAbilityChecker(this.dependencies.container);
314
- const requireAbility = createRequireAbilityMiddleware(abilityChecker);
613
+ const requireAbility = createRequireAbilityMiddleware(abilityChecker, this.viewsEnabled);
315
614
  const middleware = [...this.group("authenticated"), requireAbility(ability)];
316
- return withMiddleware(...middleware)(handler);
615
+ return this.composed(withMiddleware(...middleware)(handler), "json", identityModes(handler), scimMiddleware(handler));
317
616
  }
318
617
  wrapPolicy(resource, action, handler) {
319
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
618
+ assertHttpHandler(handler);
619
+ const auth = establishedAuthReader2;
320
620
  const gate = this.dependencies.container.resolve(CORE_POLICY_GATE_TOKEN);
321
- return withMiddleware(createAuthorizeMiddleware(gate, auth, resource, action))(handler);
621
+ return this.composed(withMiddleware(createAuthorizeMiddleware(gate, auth, resource, action))(handler), "json", identityModes(handler), scimMiddleware(handler));
322
622
  }
323
623
  wrapLogin(handler) {
324
- return this.wrapThrottle("login", resolveLoginRateLimit(), handler);
624
+ assertHttpHandler(handler);
625
+ return this.wrapThrottle("login", this.responsePolicy.loginRateLimit ?? resolveLoginRateLimit(), handler);
325
626
  }
326
627
  wrapSigned(handler) {
327
- return withMiddleware(createValidateSignatureMiddleware())(handler);
628
+ assertHttpHandler(handler);
629
+ const secret = this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).signatureSecret;
630
+ if (!secret)
631
+ throw new Error("Explicit signed URL configuration is required.");
632
+ return this.composed(withMiddleware(createValidateSignatureMiddleware({ secret }))(handler), "json", identityModes(handler), scimMiddleware(handler));
328
633
  }
329
634
  wrapRegister(handler) {
330
- return this.wrapThrottle("register", resolveRegisterRateLimit(), handler);
635
+ assertHttpHandler(handler);
636
+ return this.wrapThrottle("register", this.responsePolicy.registerRateLimit ?? resolveRegisterRateLimit(), handler);
331
637
  }
332
638
  wrapWebAuth(handler, options) {
333
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
639
+ assertHttpHandler(handler);
640
+ const auth = establishedAuthReader2;
334
641
  const middleware = [
335
- createRequireWebAuthMiddleware(auth),
642
+ createRequireWebAuthMiddleware(auth, this.requireIntendedOptions()),
336
643
  ...options.verified ? this.verifiedMiddleware() : []
337
644
  ];
338
- return this.wrapWeb(withMiddleware(...middleware)(handler));
645
+ return this.wrapWeb(this.composed(withMiddleware(...middleware)(handler), "web", identityModes(handler), scimMiddleware(handler)));
339
646
  }
340
647
  verifiedMiddleware() {
341
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
342
- return [createRequireVerifiedMiddleware(auth)];
648
+ const auth = establishedAuthReader2;
649
+ return [
650
+ createRequireVerifiedMiddleware(auth, this.emailVerificationRequired, this.requireIntendedOptions())
651
+ ];
343
652
  }
344
653
  wrapThrottle(scope, rateLimit, handler) {
654
+ assertHttpHandler(handler);
345
655
  const memoryKeyPrefix = scope === "login" ? "login-throttle:" : "register-throttle:";
346
656
  const redisUrl = this.dependencies.container.has(CORE_CONFIG_TOKEN) ? this.dependencies.container.resolve(CORE_CONFIG_TOKEN).get(REDIS_URL_CONFIG_KEY)?.trim() ?? "" : "";
347
657
  if (scope === "login") {
348
- return withMiddleware(this.ownThrottle(createLoginThrottleMiddleware({
658
+ return this.composed(withMiddleware(this.ownThrottle(createLoginThrottleMiddleware({
659
+ namespace: this.responsePolicy.namespace,
660
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
349
661
  ...redisUrl ? { redisUrl } : {},
350
662
  maxAttempts: rateLimit.maxAttempts,
351
663
  decaySeconds: rateLimit.decaySeconds
352
- })))(handler);
664
+ })))(handler), "json", identityModes(handler), scimMiddleware(handler));
353
665
  }
354
666
  if (redisUrl) {
355
- return withMiddleware(this.ownThrottle(createThrottleMiddleware({
667
+ return this.composed(withMiddleware(this.ownThrottle(createThrottleMiddleware({
668
+ namespace: this.responsePolicy.namespace,
669
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
356
670
  redisUrl,
357
671
  maxAttempts: rateLimit.maxAttempts,
358
672
  decaySeconds: rateLimit.decaySeconds,
359
673
  keyPrefix: memoryKeyPrefix
360
- })))(handler);
674
+ })))(handler), "json", identityModes(handler), scimMiddleware(handler));
361
675
  }
362
- return withMiddleware(this.ownThrottle(createMemoryThrottleMiddleware({
676
+ return this.composed(withMiddleware(this.ownThrottle(createMemoryThrottleMiddleware({
677
+ namespace: this.responsePolicy.namespace,
678
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
363
679
  maxAttempts: rateLimit.maxAttempts,
364
680
  decaySeconds: rateLimit.decaySeconds,
365
681
  keyPrefix: memoryKeyPrefix
366
- })))(handler);
682
+ })))(handler), "json", identityModes(handler), scimMiddleware(handler));
367
683
  }
368
684
  }
369
685
  function createHttpKernel(dependencies) {