@getstrata/bootstrap 2.2.59 → 3.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -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,10 +1,299 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// ../../src/bootstrap/web/server.ts
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { resolve } from "path";
|
|
4
|
+
import { resolveMaxBodyBytes as resolveMaxBodyBytes2 } from "@getstrata/core/http/bodySizeLimitMiddleware";
|
|
5
|
+
import {
|
|
6
|
+
createCorsMiddleware,
|
|
7
|
+
resolveCorsConfig as resolveCorsConfig2
|
|
8
|
+
} from "@getstrata/core/http/corsMiddleware";
|
|
5
9
|
import { currentRequestMeta, runWithRequestMeta } from "@getstrata/core/http/requestMetaContext";
|
|
6
10
|
import { assertUrlPathUnderRoot } from "@getstrata/core/security/safePath";
|
|
7
11
|
import { notFoundHtmlResponse } from "@getstrata/core/view";
|
|
12
|
+
import { dispatchOwnedRoute } from "#strata-http-route";
|
|
13
|
+
|
|
14
|
+
// ../../src/bootstrap/providers/config.ts
|
|
15
|
+
import { validateEnv } from "@getstrata/core/config/envSchema";
|
|
16
|
+
import { CORE_JSON_RESPONSE_POLICY_TOKEN } from "@getstrata/core/contracts/serviceTokens";
|
|
17
|
+
import { resolveMaxBodyBytes } from "@getstrata/core/http/bodySizeLimitMiddleware";
|
|
18
|
+
import { resolveCorsConfig } from "@getstrata/core/http/corsMiddleware";
|
|
19
|
+
import { resolveMaxUploadBytes } from "@getstrata/core/http/uploads";
|
|
20
|
+
import { envFlagEnabled, isProductionEnv } from "@getstrata/core/runtime/appEnv";
|
|
21
|
+
import { parseFrontendMode } from "@getstrata/core/runtime/frontendMode";
|
|
22
|
+
import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";
|
|
23
|
+
|
|
24
|
+
// ../../src/core/queue/queueConfig.ts
|
|
25
|
+
function snapshotQueueRetryPolicy(policy) {
|
|
26
|
+
const { maxAttempts, backoffMs } = policy;
|
|
27
|
+
if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1)
|
|
28
|
+
throw new TypeError("QUEUE_MAX_ATTEMPTS must be a positive safe integer.");
|
|
29
|
+
if (!Number.isSafeInteger(backoffMs) || backoffMs < 0 || backoffMs > 2147483647)
|
|
30
|
+
throw new TypeError("QUEUE_BACKOFF_MS must be a non-negative integer within the timer range.");
|
|
31
|
+
return Object.freeze({ maxAttempts, backoffMs });
|
|
32
|
+
}
|
|
33
|
+
function resolveQueueConfig(env = process.env) {
|
|
34
|
+
const driver = env.QUEUE_DRIVER ?? "sync";
|
|
35
|
+
if (!["sync", "async", "redis"].includes(driver))
|
|
36
|
+
throw new TypeError("Unknown queue driver.");
|
|
37
|
+
const policy = snapshotQueueRetryPolicy({
|
|
38
|
+
maxAttempts: Number(env.QUEUE_MAX_ATTEMPTS ?? "3"),
|
|
39
|
+
backoffMs: Number(env.QUEUE_BACKOFF_MS ?? "1000")
|
|
40
|
+
});
|
|
41
|
+
return Object.freeze({ driver, ...policy });
|
|
42
|
+
}
|
|
43
|
+
// ../../src/bootstrap/config.ts
|
|
44
|
+
import {
|
|
45
|
+
CORE_ABILITY_CHECKER_TOKEN,
|
|
46
|
+
CORE_AUTH_TOKEN,
|
|
47
|
+
CORE_AUTH_USER_DIRECTORY_TOKEN,
|
|
48
|
+
CORE_CACHE_TOKEN,
|
|
49
|
+
CORE_CONFIG_TOKEN,
|
|
50
|
+
CORE_EVENT_BUS_TOKEN,
|
|
51
|
+
CORE_HTTP_CLEANUP_TOKEN,
|
|
52
|
+
CORE_POLICY_GATE_TOKEN,
|
|
53
|
+
CORE_PUBLIC_TENANCY_TOKEN,
|
|
54
|
+
CORE_QUEUE_TOKEN,
|
|
55
|
+
CORE_TENANT_RESOLVER_TOKEN,
|
|
56
|
+
CORE_THROTTLE_QUOTA_POLICY_TOKEN
|
|
57
|
+
} from "@getstrata/core/contracts/serviceTokens";
|
|
58
|
+
var APP_PORT_CONFIG_KEY = "app.port";
|
|
59
|
+
var CACHE_TTL_MS_CONFIG_KEY = "cache.ttlMs";
|
|
60
|
+
var CACHE_MAX_ENTRIES_CONFIG_KEY = "cache.maxEntries";
|
|
61
|
+
var CACHE_DRIVER_CONFIG_KEY = "cache.driver";
|
|
62
|
+
var REDIS_URL_CONFIG_KEY = "cache.redisUrl";
|
|
63
|
+
var DATABASE_URL_CONFIG_KEY = "database.url";
|
|
64
|
+
var CSRF_TARGET_ORIGIN_CONFIG_KEY = "http.csrf.targetOrigin";
|
|
65
|
+
var AUTH_DEV_HEADERS_CONFIG_KEY = "auth.allowDevHeaders";
|
|
66
|
+
var DEFAULT_APP_PORT = 3000;
|
|
67
|
+
var DEFAULT_CACHE_TTL_MS = 3600000;
|
|
68
|
+
var DEFAULT_CACHE_MAX_ENTRIES = 100;
|
|
69
|
+
var DEFAULT_CACHE_DRIVER = "array";
|
|
70
|
+
var DEFAULT_API_TOKEN = "";
|
|
71
|
+
var DEFAULT_QUEUE_DRIVER = "sync";
|
|
72
|
+
|
|
73
|
+
// ../../src/bootstrap/env.ts
|
|
74
|
+
import { defineEnvSchema } from "@getstrata/core/config/envSchema";
|
|
75
|
+
import { DEFAULT_SPA_PREFIX, FRONTEND_MODE_PATTERN } from "@getstrata/core/runtime/frontendMode";
|
|
76
|
+
var appEnvSchema = defineEnvSchema({
|
|
77
|
+
DATABASE_URL: {
|
|
78
|
+
required: true,
|
|
79
|
+
pattern: /^(?:(?:postgres(?:ql)?|mysql):\/\/\S+|sqlite:(?:\/\/)?\S+)$/i
|
|
80
|
+
},
|
|
81
|
+
PORT: {
|
|
82
|
+
integer: true,
|
|
83
|
+
minimum: 1,
|
|
84
|
+
default: String(DEFAULT_APP_PORT)
|
|
85
|
+
},
|
|
86
|
+
CACHE_TTL_MS: {
|
|
87
|
+
integer: true,
|
|
88
|
+
minimum: 0,
|
|
89
|
+
default: String(DEFAULT_CACHE_TTL_MS)
|
|
90
|
+
},
|
|
91
|
+
CACHE_MAX_ENTRIES: {
|
|
92
|
+
integer: true,
|
|
93
|
+
minimum: 1,
|
|
94
|
+
default: String(DEFAULT_CACHE_MAX_ENTRIES)
|
|
95
|
+
},
|
|
96
|
+
CACHE_DRIVER: {
|
|
97
|
+
default: DEFAULT_CACHE_DRIVER,
|
|
98
|
+
pattern: /^(array|redis)$/
|
|
99
|
+
},
|
|
100
|
+
REDIS_URL: {
|
|
101
|
+
default: ""
|
|
102
|
+
},
|
|
103
|
+
QUEUE_DRIVER: {
|
|
104
|
+
default: DEFAULT_QUEUE_DRIVER,
|
|
105
|
+
pattern: /^(sync|async|redis)$/
|
|
106
|
+
},
|
|
107
|
+
AUTH_DEV_HEADERS: {
|
|
108
|
+
default: "false",
|
|
109
|
+
pattern: /^(true|false|0|1)$/
|
|
110
|
+
},
|
|
111
|
+
DB_CONNECTION: {
|
|
112
|
+
default: "",
|
|
113
|
+
pattern: /^(pgsql|postgres|postgresql|mysql|mariadb|sqlite)?$/i
|
|
114
|
+
},
|
|
115
|
+
AUTH_DEFAULT_GUARD: {
|
|
116
|
+
default: "web"
|
|
117
|
+
},
|
|
118
|
+
JWT_TTL_SECONDS: {
|
|
119
|
+
integer: true,
|
|
120
|
+
minimum: 60,
|
|
121
|
+
default: "3600"
|
|
122
|
+
},
|
|
123
|
+
APP_ENV: {
|
|
124
|
+
default: "local"
|
|
125
|
+
},
|
|
126
|
+
APP_DEBUG: {
|
|
127
|
+
default: "true"
|
|
128
|
+
},
|
|
129
|
+
APP_URL: {
|
|
130
|
+
default: "http://localhost:3000"
|
|
131
|
+
},
|
|
132
|
+
FRONTEND_MODE: {
|
|
133
|
+
default: "api",
|
|
134
|
+
pattern: FRONTEND_MODE_PATTERN
|
|
135
|
+
},
|
|
136
|
+
SPA_PREFIX: {
|
|
137
|
+
default: DEFAULT_SPA_PREFIX
|
|
138
|
+
},
|
|
139
|
+
API_PREFIX: {
|
|
140
|
+
default: "/api/v1"
|
|
141
|
+
},
|
|
142
|
+
CORS_ADDITIONAL_ALLOWED_HEADERS: {
|
|
143
|
+
default: ""
|
|
144
|
+
},
|
|
145
|
+
CORS_ALLOWED_ORIGINS: {
|
|
146
|
+
default: "*"
|
|
147
|
+
},
|
|
148
|
+
QUEUE_MAX_ATTEMPTS: {
|
|
149
|
+
integer: true,
|
|
150
|
+
minimum: 1,
|
|
151
|
+
default: "3"
|
|
152
|
+
},
|
|
153
|
+
QUEUE_BACKOFF_MS: {
|
|
154
|
+
integer: true,
|
|
155
|
+
minimum: 0,
|
|
156
|
+
default: "1000"
|
|
157
|
+
},
|
|
158
|
+
ADMIN_API_TOKEN: {
|
|
159
|
+
default: DEFAULT_API_TOKEN
|
|
160
|
+
},
|
|
161
|
+
MEMBER_API_TOKEN: {
|
|
162
|
+
default: ""
|
|
163
|
+
},
|
|
164
|
+
DB_POOL_MAX: {
|
|
165
|
+
integer: true,
|
|
166
|
+
minimum: 1,
|
|
167
|
+
default: "10"
|
|
168
|
+
},
|
|
169
|
+
DB_POOL_IDLE_TIMEOUT: {
|
|
170
|
+
integer: true,
|
|
171
|
+
minimum: 0,
|
|
172
|
+
default: "30"
|
|
173
|
+
},
|
|
174
|
+
DB_POOL_MAX_LIFETIME: {
|
|
175
|
+
integer: true,
|
|
176
|
+
minimum: 0,
|
|
177
|
+
default: "3600"
|
|
178
|
+
},
|
|
179
|
+
DB_CONNECTION_TIMEOUT: {
|
|
180
|
+
integer: true,
|
|
181
|
+
minimum: 1,
|
|
182
|
+
default: "10"
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
// ../../src/bootstrap/rateLimit.ts
|
|
187
|
+
var LOCAL_LOGIN_RATE_LIMIT = {
|
|
188
|
+
maxAttempts: 100,
|
|
189
|
+
decaySeconds: 60
|
|
190
|
+
};
|
|
191
|
+
var PRODUCTION_LOGIN_RATE_LIMIT = {
|
|
192
|
+
maxAttempts: 5,
|
|
193
|
+
decaySeconds: 900
|
|
194
|
+
};
|
|
195
|
+
function parsePositiveInt(value, fallback) {
|
|
196
|
+
const parsed = Number(value);
|
|
197
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
198
|
+
return fallback;
|
|
199
|
+
}
|
|
200
|
+
return Math.trunc(parsed);
|
|
201
|
+
}
|
|
202
|
+
function parseWindowSeconds(secondsValue, msValue, fallback) {
|
|
203
|
+
if (secondsValue !== undefined && secondsValue.trim() !== "") {
|
|
204
|
+
return parsePositiveInt(secondsValue, fallback);
|
|
205
|
+
}
|
|
206
|
+
if (msValue !== undefined && msValue.trim() !== "") {
|
|
207
|
+
const parsedMs = Number(msValue);
|
|
208
|
+
if (Number.isFinite(parsedMs) && parsedMs > 0) {
|
|
209
|
+
return Math.max(1, Math.trunc(parsedMs / 1000));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return fallback;
|
|
213
|
+
}
|
|
214
|
+
function resolveLoginRateLimit(env = {}) {
|
|
215
|
+
const defaults = env.APP_ENV === "local" ? LOCAL_LOGIN_RATE_LIMIT : PRODUCTION_LOGIN_RATE_LIMIT;
|
|
216
|
+
return {
|
|
217
|
+
maxAttempts: parsePositiveInt(env.LOGIN_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
|
|
218
|
+
decaySeconds: parseWindowSeconds(env.LOGIN_RATE_LIMIT_WINDOW_SECONDS, env.LOGIN_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
function resolveRegisterRateLimit(env = {}) {
|
|
222
|
+
const defaults = env.APP_ENV === "local" ? { maxAttempts: 100, decaySeconds: 60 } : { maxAttempts: 10, decaySeconds: 60 };
|
|
223
|
+
return {
|
|
224
|
+
maxAttempts: parsePositiveInt(env.REGISTER_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
|
|
225
|
+
decaySeconds: parseWindowSeconds(env.REGISTER_RATE_LIMIT_WINDOW_SECONDS, env.REGISTER_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// ../../src/bootstrap/providers/config.ts
|
|
230
|
+
function resolveHttpResponsePolicy(source) {
|
|
231
|
+
const cors = Object.freeze({
|
|
232
|
+
allowedOrigins: Object.freeze((source.CORS_ALLOWED_ORIGINS ?? (source.APP_URL?.trim() || "http://localhost:3000").replace(/\/$/, "")).split(",").map((origin) => origin.trim()).filter(Boolean)),
|
|
233
|
+
additionalAllowedHeaders: Object.freeze(source.CORS_ADDITIONAL_ALLOWED_HEADERS?.trim() ? source.CORS_ADDITIONAL_ALLOWED_HEADERS.split(",").map((name) => name.trim()) : [])
|
|
234
|
+
});
|
|
235
|
+
resolveCorsConfig(cors);
|
|
236
|
+
const maxAttempts = Number(source.RATE_LIMIT_PER_MINUTE ?? "120");
|
|
237
|
+
return Object.freeze({
|
|
238
|
+
cors,
|
|
239
|
+
securityHeaders: Object.freeze({
|
|
240
|
+
frontendMode: parseFrontendMode(source.FRONTEND_MODE),
|
|
241
|
+
production: isProductionEnv(source)
|
|
242
|
+
}),
|
|
243
|
+
maxBodyBytes: resolveMaxBodyBytes(source.MAX_REQUEST_BODY_BYTES),
|
|
244
|
+
rateLimitPerMinute: Number.isFinite(maxAttempts) ? maxAttempts : 120,
|
|
245
|
+
namespace: source.APP_KEY_PREFIX?.trim() || "strata",
|
|
246
|
+
trustForwardedFor: source.TRUST_FORWARDED_FOR === "true",
|
|
247
|
+
loginRateLimit: Object.freeze(resolveLoginRateLimit({ APP_ENV: "local", ...source })),
|
|
248
|
+
registerRateLimit: Object.freeze(resolveRegisterRateLimit({ APP_ENV: "local", ...source }))
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
function createConfigProvider(input) {
|
|
252
|
+
const source = Object.freeze({ ...input });
|
|
253
|
+
const env = validateEnv(appEnvSchema, source);
|
|
254
|
+
const queue = resolveQueueConfig(env);
|
|
255
|
+
const values = Object.freeze({
|
|
256
|
+
[DATABASE_URL_CONFIG_KEY]: env.DATABASE_URL,
|
|
257
|
+
[APP_PORT_CONFIG_KEY]: Number(env.PORT),
|
|
258
|
+
[CACHE_TTL_MS_CONFIG_KEY]: Number(env.CACHE_TTL_MS),
|
|
259
|
+
[CACHE_MAX_ENTRIES_CONFIG_KEY]: Number(env.CACHE_MAX_ENTRIES),
|
|
260
|
+
[CACHE_DRIVER_CONFIG_KEY]: env.CACHE_DRIVER,
|
|
261
|
+
[REDIS_URL_CONFIG_KEY]: env.REDIS_URL,
|
|
262
|
+
"http.responsePolicy": resolveHttpResponsePolicy({ ...source, APP_URL: env.APP_URL }),
|
|
263
|
+
"http.features": Object.freeze({
|
|
264
|
+
emailVerificationRequired: source.FEATURE_EMAIL_VERIFICATION === "true",
|
|
265
|
+
viewsEnabled: ["server-htmx", "hybrid"].includes(source.FRONTEND_MODE ?? "api"),
|
|
266
|
+
publicReadsEnabled: source.FEATURE_PUBLIC_READS === "true",
|
|
267
|
+
etagEnabled: source.FEATURE_ETAG !== "false"
|
|
268
|
+
}),
|
|
269
|
+
"http.uploadPolicy": Object.freeze({
|
|
270
|
+
maxBytes: resolveMaxUploadBytes(source.MAX_UPLOAD_BYTES?.trim() ?? source.MAX_REQUEST_BODY_BYTES?.trim()),
|
|
271
|
+
allowUnknownMime: envFlagEnabled(source.UPLOAD_ALLOW_UNKNOWN_MIME)
|
|
272
|
+
}),
|
|
273
|
+
"auth.defaultTokenExpiryDays": resolveDefaultTokenExpiryDays(source.API_TOKEN_DEFAULT_EXPIRY_DAYS),
|
|
274
|
+
"app.name": source.APP_NAME?.trim() || "Strata",
|
|
275
|
+
"app.env": env.APP_ENV,
|
|
276
|
+
"app.debug": source.APP_DEBUG === "true",
|
|
277
|
+
"app.url": env.APP_URL,
|
|
278
|
+
"app.apiPrefix": env.API_PREFIX,
|
|
279
|
+
"auth.allowDevHeaders": envFlagEnabled(env.AUTH_DEV_HEADERS),
|
|
280
|
+
"queue.driver": queue.driver,
|
|
281
|
+
"queue.maxAttempts": queue.maxAttempts,
|
|
282
|
+
"queue.backoffMs": queue.backoffMs,
|
|
283
|
+
...source.CSRF_TARGET_ORIGIN !== undefined ? { [CSRF_TARGET_ORIGIN_CONFIG_KEY]: source.CSRF_TARGET_ORIGIN } : {}
|
|
284
|
+
});
|
|
285
|
+
return Object.freeze({
|
|
286
|
+
name: "core.config",
|
|
287
|
+
register({ container, config }) {
|
|
288
|
+
container.set(CORE_CONFIG_TOKEN, config);
|
|
289
|
+
container.set(CORE_JSON_RESPONSE_POLICY_TOKEN, Object.freeze({ etagEnabled: source.FEATURE_ETAG !== "false" }));
|
|
290
|
+
for (const [key, value] of Object.entries(values))
|
|
291
|
+
config.set(key, value);
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// ../../src/bootstrap/web/server.ts
|
|
8
297
|
function socketAddress(server, request) {
|
|
9
298
|
const address = server?.requestIP(request)?.address;
|
|
10
299
|
return address ? address.replace(/^::ffff:/i, "") : null;
|
|
@@ -12,7 +301,7 @@ function socketAddress(server, request) {
|
|
|
12
301
|
async function missingHtmlResponse() {
|
|
13
302
|
return notFoundHtmlResponse();
|
|
14
303
|
}
|
|
15
|
-
function wrapRouteHandler(handler, path, onRequest, track = (work) => work()) {
|
|
304
|
+
function wrapRouteHandler(handler, path, onRequest, track = (work) => work(), enter, validate) {
|
|
16
305
|
return async (request, server) => {
|
|
17
306
|
return await track(async () => await runWithRequestMeta({
|
|
18
307
|
...currentRequestMeta(),
|
|
@@ -22,15 +311,24 @@ function wrapRouteHandler(handler, path, onRequest, track = (work) => work()) {
|
|
|
22
311
|
peerAddress: socketAddress(server, request),
|
|
23
312
|
userAgent: request.headers.get("user-agent")
|
|
24
313
|
}, async () => {
|
|
25
|
-
const
|
|
26
|
-
if (
|
|
27
|
-
return
|
|
28
|
-
const
|
|
29
|
-
|
|
314
|
+
const invalid = validate?.(request, server);
|
|
315
|
+
if (invalid)
|
|
316
|
+
return invalid;
|
|
317
|
+
const owned = await dispatchOwnedRoute(handler, request, (ports) => onRequest?.(request, server, ports));
|
|
318
|
+
if (owned)
|
|
319
|
+
return owned;
|
|
320
|
+
const work = async (_request, ports) => {
|
|
321
|
+
const intercepted = await onRequest?.(request, server, ports);
|
|
322
|
+
if (intercepted instanceof Response)
|
|
323
|
+
return intercepted;
|
|
324
|
+
const response = await handler(request, server, ports);
|
|
325
|
+
return response ?? await missingHtmlResponse();
|
|
326
|
+
};
|
|
327
|
+
return enter ? enter(request, work) : work(request);
|
|
30
328
|
}));
|
|
31
329
|
};
|
|
32
330
|
}
|
|
33
|
-
function convertAppRoutesToBunRoutes(routes, cors = {}, onRequest, track) {
|
|
331
|
+
function convertAppRoutesToBunRoutes(routes, cors = {}, onRequest, track, enter, validate) {
|
|
34
332
|
const bunRoutes = {};
|
|
35
333
|
const middleware = createCorsMiddleware(cors);
|
|
36
334
|
const preflight = (request) => middleware(request, async () => new Response(null, { status: 405 }));
|
|
@@ -38,16 +336,16 @@ function convertAppRoutesToBunRoutes(routes, cors = {}, onRequest, track) {
|
|
|
38
336
|
if (handler instanceof Response) {
|
|
39
337
|
const methods = {};
|
|
40
338
|
for (const method of ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"]) {
|
|
41
|
-
methods[method] = wrapRouteHandler(() => handler.clone(), path, onRequest, track);
|
|
339
|
+
methods[method] = wrapRouteHandler(() => handler.clone(), path, onRequest, track, enter, validate);
|
|
42
340
|
}
|
|
43
|
-
methods.OPTIONS = wrapRouteHandler(preflight, path, onRequest, track);
|
|
341
|
+
methods.OPTIONS = wrapRouteHandler(preflight, path, onRequest, track, enter, validate);
|
|
44
342
|
bunRoutes[path] = methods;
|
|
45
343
|
continue;
|
|
46
344
|
}
|
|
47
345
|
if (typeof handler === "function") {
|
|
48
346
|
bunRoutes[path] = {
|
|
49
|
-
GET: wrapRouteHandler(handler, path, onRequest, track),
|
|
50
|
-
OPTIONS: wrapRouteHandler(preflight, path, onRequest, track)
|
|
347
|
+
GET: wrapRouteHandler(handler, path, onRequest, track, enter, validate),
|
|
348
|
+
OPTIONS: wrapRouteHandler(preflight, path, onRequest, track, enter, validate)
|
|
51
349
|
};
|
|
52
350
|
continue;
|
|
53
351
|
}
|
|
@@ -55,16 +353,16 @@ function convertAppRoutesToBunRoutes(routes, cors = {}, onRequest, track) {
|
|
|
55
353
|
const methods = {};
|
|
56
354
|
for (const [method, methodHandler] of Object.entries(handler)) {
|
|
57
355
|
if (methodHandler instanceof Response) {
|
|
58
|
-
methods[method.toUpperCase()] = wrapRouteHandler(() => methodHandler.clone(), path, onRequest, track);
|
|
356
|
+
methods[method.toUpperCase()] = wrapRouteHandler(() => methodHandler.clone(), path, onRequest, track, enter, validate);
|
|
59
357
|
continue;
|
|
60
358
|
}
|
|
61
359
|
if (typeof methodHandler !== "function") {
|
|
62
360
|
continue;
|
|
63
361
|
}
|
|
64
|
-
methods[method.toUpperCase()] = wrapRouteHandler(methodHandler, path, onRequest, track);
|
|
362
|
+
methods[method.toUpperCase()] = wrapRouteHandler(methodHandler, path, onRequest, track, enter, validate);
|
|
65
363
|
}
|
|
66
364
|
if (Object.keys(methods).length > 0) {
|
|
67
|
-
methods.OPTIONS ??= wrapRouteHandler(preflight, path, onRequest, track);
|
|
365
|
+
methods.OPTIONS ??= wrapRouteHandler(preflight, path, onRequest, track, enter, validate);
|
|
68
366
|
bunRoutes[path] = methods;
|
|
69
367
|
}
|
|
70
368
|
}
|
|
@@ -72,10 +370,13 @@ function convertAppRoutesToBunRoutes(routes, cors = {}, onRequest, track) {
|
|
|
72
370
|
return bunRoutes;
|
|
73
371
|
}
|
|
74
372
|
function createWebServer(options) {
|
|
373
|
+
return openWebServer(options);
|
|
374
|
+
}
|
|
375
|
+
function openWebServer(options, ownership) {
|
|
75
376
|
if (options.lifecycle?.isShuttingDown)
|
|
76
377
|
throw new Error("Cannot start HTTP during shutdown.");
|
|
77
378
|
let abortedDuringShutdown = 0;
|
|
78
|
-
const
|
|
379
|
+
const validate = (request, _server) => {
|
|
79
380
|
if (options.lifecycle?.isShuttingDown)
|
|
80
381
|
return new Response("Service Unavailable", { status: 503 });
|
|
81
382
|
if (!URL.canParse(request.url))
|
|
@@ -89,16 +390,28 @@ function createWebServer(options) {
|
|
|
89
390
|
abortedDuringShutdown++;
|
|
90
391
|
}, { once: true });
|
|
91
392
|
}
|
|
92
|
-
return options.onRequest?.(request, server);
|
|
93
393
|
};
|
|
394
|
+
const onRequest = options.onRequest;
|
|
94
395
|
for (const field of ["fetch", "routes", "port", "unix"])
|
|
95
396
|
if (options.native && field in options.native)
|
|
96
397
|
throw new TypeError(`native.${field} is owned by createWebServer.`);
|
|
97
|
-
const
|
|
398
|
+
const responsePolicy = resolveHttpResponsePolicy(Object.freeze({ ...options.env ?? process.env }));
|
|
399
|
+
if (options.cors)
|
|
400
|
+
resolveCorsConfig2(options.cors);
|
|
401
|
+
const cors = {
|
|
402
|
+
...responsePolicy.cors,
|
|
403
|
+
...options.cors,
|
|
404
|
+
additionalAllowedHeaders: [
|
|
405
|
+
...responsePolicy.cors?.additionalAllowedHeaders ?? [],
|
|
406
|
+
...options.cors?.additionalAllowedHeaders ?? []
|
|
407
|
+
]
|
|
408
|
+
};
|
|
409
|
+
const maxRequestBodySize = options.native?.maxRequestBodySize ?? responsePolicy.maxBodyBytes ?? resolveMaxBodyBytes2();
|
|
98
410
|
if (!Number.isSafeInteger(maxRequestBodySize) || maxRequestBodySize <= 0)
|
|
99
411
|
throw new RangeError("maxRequestBodySize must be a positive safe integer.");
|
|
412
|
+
const renderError = options.errorView;
|
|
100
413
|
const active = new Set;
|
|
101
|
-
const
|
|
414
|
+
const trackOwned = (work) => {
|
|
102
415
|
if (!options.lifecycle)
|
|
103
416
|
return work();
|
|
104
417
|
const running = work();
|
|
@@ -107,8 +420,9 @@ function createWebServer(options) {
|
|
|
107
420
|
active.delete(running);
|
|
108
421
|
});
|
|
109
422
|
};
|
|
110
|
-
const
|
|
111
|
-
const
|
|
423
|
+
const track = (work) => trackOwned(async () => await runWithRequestMeta({ ...currentRequestMeta(), webErrorView: renderError }, work));
|
|
424
|
+
const publicDir = resolve(options.publicDir ?? "./public");
|
|
425
|
+
const bunRoutes = options.routes ? convertAppRoutesToBunRoutes(options.routes, cors, onRequest, track, options.enter, validate) : undefined;
|
|
112
426
|
const { websocket, ...native } = options.native ?? {};
|
|
113
427
|
const configuration = {
|
|
114
428
|
...native,
|
|
@@ -123,11 +437,16 @@ function createWebServer(options) {
|
|
|
123
437
|
peerAddress: socketAddress(server, request),
|
|
124
438
|
userAgent: request.headers.get("user-agent")
|
|
125
439
|
}, async () => {
|
|
126
|
-
const
|
|
127
|
-
if (
|
|
128
|
-
return
|
|
440
|
+
const invalid = validate(request, server);
|
|
441
|
+
if (invalid)
|
|
442
|
+
return invalid;
|
|
129
443
|
const url = new URL(request.url);
|
|
444
|
+
let assetAdmission = false;
|
|
130
445
|
if (url.pathname.startsWith("/assets/")) {
|
|
446
|
+
const intercepted = await onRequest?.(request, server);
|
|
447
|
+
if (intercepted instanceof Response)
|
|
448
|
+
return intercepted;
|
|
449
|
+
assetAdmission = true;
|
|
131
450
|
try {
|
|
132
451
|
const filePath = assertUrlPathUnderRoot(publicDir, url.pathname);
|
|
133
452
|
const file = Bun.file(filePath);
|
|
@@ -139,7 +458,24 @@ function createWebServer(options) {
|
|
|
139
458
|
}
|
|
140
459
|
}
|
|
141
460
|
if (options.handle) {
|
|
142
|
-
const
|
|
461
|
+
const owned = await dispatchOwnedRoute(options.handle, request, (ports) => assetAdmission ? undefined : onRequest?.(request, server, ports));
|
|
462
|
+
if (owned)
|
|
463
|
+
return owned;
|
|
464
|
+
if (websocket && !options.enter) {
|
|
465
|
+
const intercepted = assetAdmission ? undefined : await onRequest?.(request, server);
|
|
466
|
+
if (intercepted instanceof Response)
|
|
467
|
+
return intercepted;
|
|
468
|
+
return await options.handle(request, server) ?? undefined;
|
|
469
|
+
}
|
|
470
|
+
const work = async (_request, ports) => {
|
|
471
|
+
const intercepted = assetAdmission ? undefined : await onRequest?.(request, server, ports);
|
|
472
|
+
if (intercepted instanceof Response)
|
|
473
|
+
return intercepted;
|
|
474
|
+
return await options.handle?.(request, server, ports) ?? await missingHtmlResponse();
|
|
475
|
+
};
|
|
476
|
+
if (options.enter)
|
|
477
|
+
return options.enter(request, work);
|
|
478
|
+
const response = await work(request);
|
|
143
479
|
if (response === undefined && websocket)
|
|
144
480
|
return;
|
|
145
481
|
return response ?? await missingHtmlResponse();
|
|
@@ -148,12 +484,22 @@ function createWebServer(options) {
|
|
|
148
484
|
}));
|
|
149
485
|
}
|
|
150
486
|
};
|
|
151
|
-
const
|
|
487
|
+
const nativeOptions = websocket ? { ...configuration, websocket } : {
|
|
152
488
|
...configuration,
|
|
153
489
|
async fetch(request, server) {
|
|
154
490
|
return await configuration.fetch(request, server) ?? await missingHtmlResponse();
|
|
155
491
|
}
|
|
156
|
-
}
|
|
492
|
+
};
|
|
493
|
+
const provenScalarOptions = typeof configuration.port === "number" && Number.isSafeInteger(configuration.port) && configuration.port >= 0 && configuration.port <= 65535 && websocket === undefined && scalarNativeOptions(native);
|
|
494
|
+
let server;
|
|
495
|
+
try {
|
|
496
|
+
server = Bun.serve(nativeOptions);
|
|
497
|
+
} catch (error) {
|
|
498
|
+
if (provenScalarOptions && isNativeListenConflict(error))
|
|
499
|
+
ownership?.bindRejected();
|
|
500
|
+
throw error;
|
|
501
|
+
}
|
|
502
|
+
ownership?.acquired(server);
|
|
157
503
|
if (options.lifecycle) {
|
|
158
504
|
const lifecycle = options.lifecycle;
|
|
159
505
|
const name = `http:${crypto.randomUUID()}`;
|
|
@@ -173,7 +519,93 @@ function createWebServer(options) {
|
|
|
173
519
|
}
|
|
174
520
|
return server;
|
|
175
521
|
}
|
|
522
|
+
function scalarNativeOptions(options) {
|
|
523
|
+
try {
|
|
524
|
+
for (const key of Reflect.ownKeys(options)) {
|
|
525
|
+
const descriptor = Object.getOwnPropertyDescriptor(options, key);
|
|
526
|
+
if (!descriptor || !("value" in descriptor))
|
|
527
|
+
return false;
|
|
528
|
+
const value = descriptor.value;
|
|
529
|
+
if (value !== null && value !== undefined && !["string", "number", "boolean"].includes(typeof value))
|
|
530
|
+
return false;
|
|
531
|
+
}
|
|
532
|
+
return true;
|
|
533
|
+
} catch {
|
|
534
|
+
return false;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
function isNativeListenConflict(error) {
|
|
538
|
+
if (!error || typeof error !== "object")
|
|
539
|
+
return false;
|
|
540
|
+
try {
|
|
541
|
+
const code = Object.getOwnPropertyDescriptor(error, "code");
|
|
542
|
+
const syscall = Object.getOwnPropertyDescriptor(error, "syscall");
|
|
543
|
+
return code !== undefined && "value" in code && code.value === "EADDRINUSE" && syscall !== undefined && "value" in syscall && syscall.value === "listen";
|
|
544
|
+
} catch {
|
|
545
|
+
return false;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
function webServerResource(options) {
|
|
549
|
+
const hooks = new Map;
|
|
550
|
+
let stopping = false;
|
|
551
|
+
const lifecycle = {
|
|
552
|
+
get isShuttingDown() {
|
|
553
|
+
return stopping;
|
|
554
|
+
},
|
|
555
|
+
register(_name, handler, phase = "close") {
|
|
556
|
+
const group = hooks.get(phase) ?? [];
|
|
557
|
+
group.push(handler);
|
|
558
|
+
hooks.set(phase, group);
|
|
559
|
+
return () => {
|
|
560
|
+
const index = group.indexOf(handler);
|
|
561
|
+
if (index >= 0)
|
|
562
|
+
group.splice(index, 1);
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
const run = async (phase, context) => {
|
|
567
|
+
for (const hook of hooks.get(phase) ?? [])
|
|
568
|
+
await hook(context);
|
|
569
|
+
};
|
|
570
|
+
return {
|
|
571
|
+
name: "http.server",
|
|
572
|
+
open: async () => {
|
|
573
|
+
let acquired;
|
|
574
|
+
let bindRejected = false;
|
|
575
|
+
try {
|
|
576
|
+
const server = openWebServer({ ...options, lifecycle }, {
|
|
577
|
+
acquired: (server) => {
|
|
578
|
+
acquired = server;
|
|
579
|
+
},
|
|
580
|
+
bindRejected: () => {
|
|
581
|
+
bindRejected = true;
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
return { ok: true, value: server };
|
|
585
|
+
} catch (error) {
|
|
586
|
+
if (acquired) {
|
|
587
|
+
try {
|
|
588
|
+
await acquired.stop(true);
|
|
589
|
+
return { ok: false, error, disposition: "cleaned" };
|
|
590
|
+
} catch (cleanupError) {
|
|
591
|
+
return { ok: false, error, disposition: "unknown", cleanupErrors: [cleanupError] };
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
if (bindRejected)
|
|
595
|
+
return { ok: false, error, disposition: "not-acquired" };
|
|
596
|
+
throw error;
|
|
597
|
+
}
|
|
598
|
+
},
|
|
599
|
+
stop: async (_server, context) => {
|
|
600
|
+
stopping = true;
|
|
601
|
+
await run("stop", context);
|
|
602
|
+
},
|
|
603
|
+
drain: (_server, context) => run("drain", context),
|
|
604
|
+
close: (_server, context) => run("close", context)
|
|
605
|
+
};
|
|
606
|
+
}
|
|
176
607
|
export {
|
|
177
608
|
convertAppRoutesToBunRoutes,
|
|
178
|
-
createWebServer
|
|
609
|
+
createWebServer,
|
|
610
|
+
webServerResource
|
|
179
611
|
};
|