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