@getstrata/core 0.5.59 → 0.5.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +2 -2
  3. package/dist/core/database/bindConnection.d.ts +1 -3
  4. package/dist/core/database/bunSql.d.ts +13 -0
  5. package/dist/core/http/contentSecurityPolicy.d.ts +27 -0
  6. package/dist/core/http/memoryThrottleMiddleware.d.ts +2 -1
  7. package/dist/core/http/requestMetaContext.d.ts +1 -0
  8. package/dist/core/http/safeInternalPath.d.ts +4 -0
  9. package/dist/core/http/securedRouteModelBinding.d.ts +2 -0
  10. package/dist/core/http/securityHeadersMiddleware.d.ts +5 -2
  11. package/dist/core/http/webErrorResponse.d.ts +1 -1
  12. package/dist/core/view/etaViewEngine.d.ts +3 -2
  13. package/dist/core/view/htmlResponse.d.ts +5 -2
  14. package/dist/core/view/index.d.ts +4 -1
  15. package/dist/core/view/viewEngine.d.ts +1 -0
  16. package/dist/core/view/webErrorView.d.ts +21 -0
  17. package/dist/entries/database/bunSql.js +1 -0
  18. package/dist/entries/http/contentSecurityPolicy.js +1 -0
  19. package/dist/entries/http/memoryThrottleMiddleware.js +10 -2
  20. package/dist/entries/http/requireWebAuthMiddleware.js +34 -2
  21. package/dist/entries/http/response.js +133 -555
  22. package/dist/entries/http/safeInternalPath.js +38 -0
  23. package/dist/entries/http/securedRouteModelBinding.js +27 -5
  24. package/dist/entries/http/securityHeadersMiddleware.js +33 -60
  25. package/dist/entries/http/webErrorResponse.js +132 -554
  26. package/dist/entries/logging/requestLoggingMiddleware.js +2 -1
  27. package/dist/entries/view.js +96 -9
  28. package/dist/framework/public-api.d.ts +7 -3
  29. package/dist/index.js +665 -384
  30. package/package.json +17 -2
  31. package/dist/config/contentSecurityPolicy.d.ts +0 -5
@@ -83,220 +83,13 @@ function isViewsEnabled() {
83
83
  return readFrontendMode() === "server-htmx";
84
84
  }
85
85
 
86
- // ../../src/core/view/etaViewEngine.ts
87
- import { join, relative } from "path";
88
- import { Eta } from "eta";
86
+ // ../../src/core/view/webErrorView.ts
87
+ import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
89
88
 
90
- // ../../src/core/view/assertEtaHtmlSource.ts
91
- var HTML_TAGS = new Set([
92
- "a",
93
- "abbr",
94
- "address",
95
- "article",
96
- "aside",
97
- "audio",
98
- "b",
99
- "blockquote",
100
- "body",
101
- "button",
102
- "canvas",
103
- "caption",
104
- "cite",
105
- "code",
106
- "col",
107
- "colgroup",
108
- "data",
109
- "datalist",
110
- "dd",
111
- "del",
112
- "details",
113
- "dfn",
114
- "dialog",
115
- "div",
116
- "dl",
117
- "dt",
118
- "em",
119
- "fieldset",
120
- "figcaption",
121
- "figure",
122
- "footer",
123
- "form",
124
- "h1",
125
- "h2",
126
- "h3",
127
- "h4",
128
- "h5",
129
- "h6",
130
- "header",
131
- "hgroup",
132
- "hr",
133
- "html",
134
- "i",
135
- "iframe",
136
- "img",
137
- "input",
138
- "ins",
139
- "kbd",
140
- "label",
141
- "legend",
142
- "li",
143
- "main",
144
- "map",
145
- "mark",
146
- "menu",
147
- "meter",
148
- "nav",
149
- "object",
150
- "ol",
151
- "optgroup",
152
- "option",
153
- "output",
154
- "p",
155
- "picture",
156
- "pre",
157
- "progress",
158
- "q",
159
- "rp",
160
- "rt",
161
- "ruby",
162
- "s",
163
- "samp",
164
- "script",
165
- "search",
166
- "section",
167
- "select",
168
- "slot",
169
- "small",
170
- "source",
171
- "span",
172
- "strong",
173
- "style",
174
- "sub",
175
- "summary",
176
- "sup",
177
- "table",
178
- "tbody",
179
- "td",
180
- "template",
181
- "textarea",
182
- "tfoot",
183
- "th",
184
- "thead",
185
- "time",
186
- "title",
187
- "tr",
188
- "track",
189
- "u",
190
- "ul",
191
- "var",
192
- "video",
193
- "wbr"
194
- ]);
195
- var TAG_PATTERN = "([a-z][a-z0-9]*)";
196
- var CLASS_OR_ID_PATTERN = "[.#][\\w-]+";
197
- var CLASS_ID_SHORTHAND = new RegExp(`^${TAG_PATTERN}(?:${CLASS_OR_ID_PATTERN})+`);
198
- var ATTRIBUTE_SHORTHAND = new RegExp(`^${TAG_PATTERN}(?:${CLASS_OR_ID_PATTERN})*\\s+[\\w:-]+=`);
199
- var TAG_SHORTHAND = new RegExp(`^${TAG_PATTERN}(?:>|\\s+\\S|$)`);
200
- function htmlTagName(match) {
201
- const tag = match?.[1];
202
- return tag && HTML_TAGS.has(tag) ? tag : undefined;
203
- }
204
- function describePugLikeLine(line) {
205
- if (/^\|(?:\s|$)/.test(line)) {
206
- return "piped text";
207
- }
208
- if (htmlTagName(line.match(CLASS_ID_SHORTHAND))) {
209
- return "class/id shorthand";
210
- }
211
- if (htmlTagName(line.match(ATTRIBUTE_SHORTHAND))) {
212
- return "attribute shorthand";
213
- }
214
- if (htmlTagName(line.match(TAG_SHORTHAND))) {
215
- return "tag shorthand";
216
- }
217
- return;
218
- }
219
- function updateSkipBlock(lower, skipBlock) {
220
- if (skipBlock) {
221
- if (skipBlock === "comment" && lower.includes("-->")) {
222
- return null;
223
- }
224
- if (skipBlock !== "comment" && lower.includes(`</${skipBlock}`)) {
225
- return null;
226
- }
227
- return skipBlock;
228
- }
229
- if (lower.startsWith("<!--") && !lower.includes("-->")) {
230
- return "comment";
231
- }
232
- if (lower.startsWith("<script") && !lower.includes("</script")) {
233
- return "script";
234
- }
235
- if (lower.startsWith("<style") && !lower.includes("</style")) {
236
- return "style";
237
- }
238
- return null;
239
- }
240
- function assertEtaHtmlSource(templateName, source) {
241
- let skipBlock = null;
242
- for (const rawLine of source.split(/\r?\n/)) {
243
- const trimmed = rawLine.trim();
244
- if (!trimmed) {
245
- continue;
246
- }
247
- const lower = trimmed.toLowerCase();
248
- const nextSkipBlock = updateSkipBlock(lower, skipBlock);
249
- if (skipBlock || nextSkipBlock) {
250
- skipBlock = nextSkipBlock;
251
- continue;
252
- }
253
- if (trimmed.startsWith("<") || trimmed.startsWith("<%")) {
254
- continue;
255
- }
256
- const kind = describePugLikeLine(trimmed);
257
- if (kind) {
258
- throw new Error(`Eta view "${templateName}" contains Pug-like markup (${kind}: ${trimmed}). Eta views must be HTML + <% %> tags, not Pug.`);
259
- }
260
- }
261
- }
262
-
263
- // ../../src/core/view/etaViewEngine.ts
264
- var DEFAULT_VIEWS_DIRECTORY = join(process.cwd(), "resources/views");
265
- var DEFAULT_LAYOUT = "layouts/app.eta";
266
-
267
- class EtaViewEngine {
268
- eta;
269
- resolveLayoutData;
270
- constructor(viewsDirectory = DEFAULT_VIEWS_DIRECTORY, resolveLayoutData) {
271
- this.eta = new Eta({
272
- views: viewsDirectory,
273
- autoTrim: false
274
- });
275
- this.resolveLayoutData = resolveLayoutData;
276
- const readFile = this.eta.readFile?.bind(this.eta);
277
- this.eta.readFile = (path) => {
278
- const source = readFile ? readFile(path) : "";
279
- assertEtaHtmlSource(relative(viewsDirectory, path) || path, source);
280
- return source;
281
- };
282
- }
283
- async render(name, data = {}, options = {}) {
284
- const template = name.endsWith(".eta") ? name : `${name}.eta`;
285
- const layoutData = this.resolveLayoutData ? await this.resolveLayoutData() : {};
286
- const mergedData = { ...layoutData, ...data };
287
- const body = await this.eta.renderAsync(template, mergedData);
288
- const layout = options.layout ?? DEFAULT_LAYOUT;
289
- if (layout === false) {
290
- return body;
291
- }
292
- const layoutTemplate = layout.endsWith(".eta") ? layout : `${layout}.eta`;
293
- return await this.eta.renderAsync(layoutTemplate, {
294
- ...mergedData,
295
- body
296
- });
297
- }
298
- }
299
89
  // ../../src/core/view/htmlResponse.ts
90
+ function withCharset(contentType) {
91
+ return contentType.includes("charset=") ? contentType : `${contentType}; charset=utf-8`;
92
+ }
300
93
  function htmlResponse(html, init = {}) {
301
94
  return new Response(html, {
302
95
  status: init.status ?? 200,
@@ -317,9 +110,6 @@ function redirectResponse(location, status = 302) {
317
110
  }
318
111
  });
319
112
  }
320
- function notFoundHtmlResponse(body = "Not Found") {
321
- return htmlResponse(body, { status: 404 });
322
- }
323
113
  function textResponse(body, init = {}) {
324
114
  return new Response(body, {
325
115
  status: init.status ?? 200,
@@ -332,348 +122,89 @@ function xmlResponse(body, init = {}) {
332
122
  return new Response(body, {
333
123
  status: init.status ?? 200,
334
124
  headers: {
335
- "Content-Type": "application/xml; charset=utf-8"
125
+ "Content-Type": withCharset(init.contentType ?? "application/xml")
336
126
  }
337
127
  });
338
128
  }
339
- // ../../src/core/view/webLayoutData.ts
340
- import { currentAuthUser } from "@getstrata/core/auth/authContext";
341
- import { currentRequestMeta as currentRequestMeta2 } from "@getstrata/core/http/requestMetaContext";
342
-
343
- // ../../src/core/contracts/serviceTokens.ts
344
- var CORE_CONFIG_TOKEN = "core.config";
345
- var CORE_CACHE_TOKEN = "core.cache";
346
- var CORE_QUEUE_TOKEN = "core.queue";
347
- var CORE_EVENT_BUS_TOKEN = "core.eventBus";
348
- var CORE_POLICY_GATE_TOKEN = "core.policyGate";
349
- var CORE_AUTH_TOKEN = "core.auth";
350
- var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
351
- var CORE_ABILITY_CHECKER_TOKEN = "core.abilityChecker";
352
- var CORE_AUTH_USER_DIRECTORY_TOKEN = "core.authUserDirectory";
353
- function isAbilityChecker(value) {
354
- if (!value || typeof value !== "object") {
355
- return false;
356
- }
357
- const candidate = value;
358
- return typeof candidate.tokenCan === "function" && typeof candidate.requireAbility === "function";
359
- }
360
- function isAuthUserDirectory(value) {
361
- if (!value || typeof value !== "object") {
362
- return false;
363
- }
364
- return typeof value.findByIdOrThrow === "function";
365
- }
366
- function resolveAbilityChecker(container) {
367
- if (container.has(CORE_ABILITY_CHECKER_TOKEN)) {
368
- return container.resolve(CORE_ABILITY_CHECKER_TOKEN);
369
- }
370
- return container.resolve(CORE_TOKEN_SERVICE_TOKEN);
371
- }
372
- function resolveAuthUserDirectory(container) {
373
- if (container.has(CORE_AUTH_USER_DIRECTORY_TOKEN)) {
374
- const directory = container.resolve(CORE_AUTH_USER_DIRECTORY_TOKEN);
375
- if (isAuthUserDirectory(directory)) {
376
- return directory;
377
- }
378
- }
379
- if (container.has(CORE_TOKEN_SERVICE_TOKEN)) {
380
- const tokenService = container.resolve(CORE_TOKEN_SERVICE_TOKEN);
381
- if (isAuthUserDirectory(tokenService)) {
382
- return tokenService;
383
- }
384
- }
385
- return null;
386
- }
387
-
388
- // ../../src/core/http/csrfToken.ts
389
- import { timingSafeEqual } from "crypto";
390
-
391
- // ../../src/core/http/cookies.ts
392
- function readRequestCookie(request, name) {
393
- const cookies = request.cookies;
394
- if (cookies && typeof cookies.get === "function") {
395
- const value = cookies.get(name);
396
- if (value) {
397
- return value;
398
- }
399
- }
400
- const header = request.headers.get("cookie");
401
- if (!header) {
402
- return null;
403
- }
404
- for (const part of header.split(";")) {
405
- const idx = part.indexOf("=");
406
- if (idx === -1)
407
- continue;
408
- const cookieName = part.slice(0, idx).trim();
409
- if (cookieName !== name)
410
- continue;
411
- return decodeURIComponent(part.slice(idx + 1).trim());
412
- }
413
- return null;
414
- }
415
- function readBunRequestCookie(request, name) {
416
- return request.cookies.get(name) ?? readRequestCookie(request, name);
129
+ function rssResponse(body, init = {}) {
130
+ return xmlResponse(body, { ...init, contentType: "application/rss+xml" });
417
131
  }
418
132
 
419
- // ../../src/core/runtime/asyncContextStore.ts
420
- import { AsyncLocalStorage } from "async_hooks";
421
- function createAsyncContextStore(key) {
422
- const symbol = Symbol.for(key);
423
- const globalRecord = globalThis;
424
- const existing = globalRecord[symbol];
425
- if (existing) {
426
- return existing;
427
- }
428
- const store = new AsyncLocalStorage;
429
- globalRecord[symbol] = store;
430
- return store;
431
- }
432
-
433
- // ../../src/core/http/requestMetaContext.ts
434
- var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
435
- function runWithRequestMeta(meta, callback) {
436
- return requestMetaContext.run(meta, callback);
437
- }
438
- function currentRequestMeta() {
439
- return requestMetaContext.getStore() ?? {
440
- ipAddress: null,
441
- userAgent: null
442
- };
443
- }
444
-
445
- // ../../src/core/http/csrfToken.ts
446
- var CSRF_COOKIE = "workhub_csrf";
447
- var CSRF_TTL_MS = 60 * 60 * 1000;
448
- function csrfCookieName() {
449
- return process.env.CSRF_COOKIE_NAME?.trim() || CSRF_COOKIE;
450
- }
451
- function resolveCsrfSecret() {
452
- return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || process.env.ADMIN_API_TOKEN?.trim() || "workhub-dev-csrf-secret";
453
- }
454
- function csrfVerifyOptions() {
455
- return { secret: resolveCsrfSecret(), maxAge: CSRF_TTL_MS };
456
- }
457
- function tokensMatch(left, right) {
458
- const leftBuffer = Buffer.from(left);
459
- const rightBuffer = Buffer.from(right);
460
- if (leftBuffer.length !== rightBuffer.length) {
461
- return false;
462
- }
463
- return timingSafeEqual(leftBuffer, rightBuffer);
464
- }
465
- function createCsrfTokenCookie() {
466
- const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
467
- const secure = process.env.APP_ENV === "production" ? "; Secure" : "";
468
- return {
469
- token,
470
- cookie: `${csrfCookieName()}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}${secure}`
471
- };
472
- }
473
- function resolveCsrfToken(request) {
474
- const cookieValue = readRequestCookie(request, csrfCookieName());
475
- if (cookieValue && Bun.CSRF.verify(cookieValue, csrfVerifyOptions())) {
476
- return { token: cookieValue };
477
- }
478
- return createCsrfTokenCookie();
479
- }
480
- function readSubmittedCsrfToken(request) {
481
- const headerToken = request.headers.get("x-csrf-token")?.trim();
482
- if (headerToken) {
483
- return headerToken;
484
- }
485
- return null;
486
- }
487
- async function readSubmittedCsrfTokenFromBody(request) {
488
- const headerToken = readSubmittedCsrfToken(request);
489
- if (headerToken) {
490
- return headerToken;
491
- }
492
- const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
493
- if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
494
- const formData = await request.clone().formData();
495
- const field = formData.get("_token");
496
- if (typeof field === "string" && field.trim().length > 0) {
497
- return field.trim();
498
- }
499
- const legacyField = formData.get("_csrf");
500
- if (typeof legacyField === "string" && legacyField.trim().length > 0) {
501
- return legacyField.trim();
502
- }
503
- }
504
- return null;
505
- }
506
- function verifyCsrfToken(request, submittedToken) {
507
- if (!submittedToken) {
508
- return false;
509
- }
510
- const cookieValue = readRequestCookie(request, csrfCookieName());
511
- if (!cookieValue) {
512
- return false;
513
- }
514
- if (!tokensMatch(submittedToken, cookieValue)) {
515
- return false;
516
- }
517
- return Bun.CSRF.verify(submittedToken, csrfVerifyOptions());
518
- }
519
- function resolveCsrfTokenForRequest(request) {
520
- const metaToken = currentRequestMeta().csrfToken;
521
- if (metaToken) {
522
- return metaToken;
523
- }
524
- return resolveCsrfToken(request).token;
525
- }
526
-
527
- // ../../src/core/http/flashSession.ts
528
- import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
529
- var FLASH_COOKIE = "workhub_flash";
530
- var FLASH_TTL_MS = 60 * 1000;
531
- function resolveFlashSecret() {
532
- return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || "workhub-dev-flash-secret";
533
- }
534
- function signFlashPayload(payload, issuedAt) {
535
- const signature = createHmac("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
536
- return `${payload}.${issuedAt}.${signature}`;
537
- }
538
- function readFlashCookie(request) {
539
- const cookieHeader = request.headers.get("cookie");
540
- if (!cookieHeader) {
541
- return null;
542
- }
543
- for (const part of cookieHeader.split(";")) {
544
- const [name, ...rest] = part.trim().split("=");
545
- if (name === FLASH_COOKIE) {
546
- return decodeURIComponent(rest.join("="));
547
- }
548
- }
549
- return null;
550
- }
551
- function parseFlashCookie(cookieValue) {
552
- const parts = cookieValue.split(".");
553
- if (parts.length < 3) {
554
- return null;
555
- }
556
- const signature = parts.pop();
557
- const issuedAtRaw = parts.pop();
558
- const payload = parts.join(".");
559
- if (!signature || !issuedAtRaw || !payload) {
560
- return null;
561
- }
562
- const issuedAt = Number.parseInt(issuedAtRaw, 10);
563
- if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
564
- return null;
565
- }
566
- const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
567
- if (!expectedSignature) {
568
- return null;
569
- }
570
- const expectedBuffer = Buffer.from(expectedSignature);
571
- const actualBuffer = Buffer.from(signature);
572
- if (expectedBuffer.length !== actualBuffer.length) {
573
- return null;
574
- }
575
- if (!timingSafeEqual2(expectedBuffer, actualBuffer)) {
576
- return null;
133
+ // ../../src/core/view/webErrorView.ts
134
+ var configuredErrorView = {};
135
+ function configureWebErrorView(options) {
136
+ configuredErrorView = { ...options };
137
+ }
138
+ function escapeHtml(value) {
139
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
140
+ }
141
+ function renderKernelErrorChrome(input) {
142
+ const title = escapeHtml(input.title);
143
+ const message = escapeHtml(input.message);
144
+ const errorLines = Object.entries(input.errors ?? {}).flatMap(([field, messages]) => messages.map((item) => `${field}: ${item}`)).map((line) => `<li>${escapeHtml(line)}</li>`).join("");
145
+ const details = errorLines ? `<ul class="error-list">${errorLines}</ul>` : "";
146
+ const goBack = input.status === 422 ? `<p><a href="javascript:history.back()">Go back</a></p>` : "";
147
+ return `<!doctype html>
148
+ <html lang="en">
149
+ <head>
150
+ <meta charset="UTF-8" />
151
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
152
+ <title>${title}</title>
153
+ <link rel="stylesheet" href="/assets/app.css" />
154
+ </head>
155
+ <body>
156
+ <header class="site-header">
157
+ <a class="brand" href="/">Home</a>
158
+ </header>
159
+ <main class="site-main">
160
+ <section class="page-header">
161
+ <h1>${title}</h1>
162
+ <p>${message}</p>
163
+ ${details}
164
+ ${goBack}
165
+ </section>
166
+ </main>
167
+ </body>
168
+ </html>
169
+ `;
170
+ }
171
+ function errorTemplateName(status) {
172
+ if (status === 404) {
173
+ return "errors/not-found";
174
+ }
175
+ if (status === 403) {
176
+ return "errors/forbidden";
177
+ }
178
+ return "errors/error";
179
+ }
180
+ async function renderWebErrorHtml(input) {
181
+ const render = configuredErrorView.render;
182
+ if (!render) {
183
+ return renderKernelErrorChrome(input);
577
184
  }
578
185
  try {
579
- const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
580
- if (!parsed?.message || typeof parsed.message !== "string") {
581
- return null;
582
- }
583
- if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
584
- return null;
585
- }
586
- return parsed;
186
+ return await render({
187
+ ...input,
188
+ request: input.request ?? currentRequestMeta().request
189
+ });
587
190
  } catch {
588
- return null;
191
+ return renderKernelErrorChrome(input);
589
192
  }
590
193
  }
591
- function createFlashCookie(message) {
592
- const payload = Buffer.from(JSON.stringify(message), "utf8").toString("base64url");
593
- const issuedAt = Date.now();
594
- const value = signFlashPayload(payload, issuedAt);
595
- return `${FLASH_COOKIE}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=60`;
194
+ async function htmlErrorResponse(input) {
195
+ return htmlResponse(await renderWebErrorHtml(input), { status: input.status });
596
196
  }
597
- function clearFlashCookie() {
598
- return `${FLASH_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
599
- }
600
- function pullFlash(request) {
601
- const cookieValue = readFlashCookie(request);
602
- if (!cookieValue) {
603
- return null;
197
+ async function notFoundHtmlResponse(body) {
198
+ if (body !== undefined) {
199
+ return htmlResponse(body, { status: 404 });
604
200
  }
605
- return parseFlashCookie(cookieValue);
606
- }
607
- function flashResponse(response, message) {
608
- const headers = new Headers(response.headers);
609
- headers.append("set-cookie", createFlashCookie(message));
610
- return new Response(response.body, {
611
- status: response.status,
612
- statusText: response.statusText,
613
- headers
614
- });
615
- }
616
- function withFlashClear(response) {
617
- const headers = new Headers(response.headers);
618
- headers.append("set-cookie", clearFlashCookie());
619
- return new Response(response.body, {
620
- status: response.status,
621
- statusText: response.statusText,
622
- headers
201
+ return htmlErrorResponse({
202
+ status: 404,
203
+ title: "Not Found",
204
+ message: "The page you requested was not found."
623
205
  });
624
206
  }
625
207
 
626
- // ../../src/core/view/webLayoutData.ts
627
- var configuredLayoutOptions = {};
628
- function configureWebLayoutData(options) {
629
- configuredLayoutOptions = { ...options };
630
- }
631
- function layoutUserKey(options) {
632
- return options.userKey ?? "authUser";
633
- }
634
- async function defaultLoadLayoutUser(container, _request) {
635
- const authUser = currentAuthUser();
636
- if (!authUser) {
637
- return null;
638
- }
639
- const userId = Number(authUser.id);
640
- if (!Number.isInteger(userId) || userId <= 0) {
641
- return null;
642
- }
643
- const directory = resolveAuthUserDirectory(container);
644
- if (!directory) {
645
- return {
646
- id: userId,
647
- email: "",
648
- role: authUser.role ?? "member"
649
- };
650
- }
651
- try {
652
- const user = await directory.findByIdOrThrow(userId);
653
- return {
654
- id: userId,
655
- email: user.email ?? "",
656
- role: authUser.role ?? user.role ?? "member"
657
- };
658
- } catch {
659
- return null;
660
- }
661
- }
662
- async function resolveWebLayoutData(container, request, options = {}) {
663
- const resolved = { ...configuredLayoutOptions, ...options };
664
- const csrfToken = request ? resolveCsrfTokenForRequest(request) : "";
665
- const flash = request ? currentRequestMeta2().flash ?? pullFlash(request) : null;
666
- const userKey = layoutUserKey(resolved);
667
- const loadUser = resolved.loadUser ?? defaultLoadLayoutUser;
668
- const user = await loadUser(container, request);
669
- const extra = typeof resolved.extra === "function" ? await resolved.extra(user) : resolved.extra ?? {};
670
- return {
671
- [userKey]: user,
672
- csrfToken,
673
- flash,
674
- ...extra
675
- };
676
- }
677
208
  // ../../src/core/http/contentNegotiation.ts
678
209
  function requestPrefersJson(request) {
679
210
  if (!request) {
@@ -697,6 +228,39 @@ function requestPrefersJson(request) {
697
228
  return pathname.startsWith("/api/");
698
229
  }
699
230
 
231
+ // ../../src/core/http/safeInternalPath.ts
232
+ function looksLikeExternalTarget(value) {
233
+ const trimmed = value.trim();
234
+ if (!trimmed.startsWith("/") || trimmed.startsWith("//") || trimmed.includes("\\")) {
235
+ return true;
236
+ }
237
+ if (trimmed.includes("://") || trimmed.includes(":/") || trimmed.includes(":\\")) {
238
+ return true;
239
+ }
240
+ try {
241
+ const decoded = decodeURIComponent(trimmed);
242
+ if (decoded.startsWith("//") || decoded.includes("\\") || /https?:/i.test(decoded)) {
243
+ return true;
244
+ }
245
+ } catch {
246
+ return true;
247
+ }
248
+ return false;
249
+ }
250
+ function sanitizeInternalPath(raw, fallback = "/") {
251
+ if (looksLikeExternalTarget(raw)) {
252
+ return fallback;
253
+ }
254
+ return raw;
255
+ }
256
+ function safeInternalRedirectPath(request, fallback = "/") {
257
+ const url = new URL(request.url);
258
+ return sanitizeInternalPath(`${url.pathname}${url.search}`, fallback);
259
+ }
260
+ function loginRedirectLocation(request) {
261
+ return `/login?redirect=${encodeURIComponent(safeInternalRedirectPath(request))}`;
262
+ }
263
+
700
264
  // ../../src/core/http/webErrorResponse.ts
701
265
  function normalizeFieldErrors(details) {
702
266
  if (!details || typeof details !== "object" || Array.isArray(details)) {
@@ -714,23 +278,37 @@ function normalizeFieldErrors(details) {
714
278
  }
715
279
  return errors;
716
280
  }
717
- function webErrorResponse(error, request) {
281
+ function errorPageTitle(status, message) {
282
+ if (status === 404) {
283
+ return "Not Found";
284
+ }
285
+ if (status === 403) {
286
+ return "Forbidden";
287
+ }
288
+ if (status >= 500) {
289
+ return "Server Error";
290
+ }
291
+ return message;
292
+ }
293
+ function publicErrorMessage(status, message) {
294
+ if (status >= 500 && false) {}
295
+ return message;
296
+ }
297
+ async function webErrorResponse(error, request) {
718
298
  if (!request || !isViewsEnabled() || requestPrefersJson(request)) {
719
299
  return null;
720
300
  }
721
301
  const mappedError = error instanceof HttpError2 ? error : mapDatabaseError(error);
722
302
  if (mappedError instanceof UnauthorizedError) {
723
- const redirectTarget = encodeURIComponent(new URL(request.url).pathname);
724
- return Response.redirect(`/login?redirect=${redirectTarget}`, 302);
725
- }
726
- if (mappedError instanceof ValidationError) {
727
- const errors = normalizeFieldErrors(mappedError.details);
728
- const fieldSummary = Object.entries(errors).flatMap(([field, messages]) => messages.map((message) => `${field}: ${message}`)).join(`
729
- `);
730
- return htmlResponse(`<section class="page-header"><h1>Validation failed</h1><pre>${fieldSummary || mappedError.message}</pre><p><a href="javascript:history.back()">Go back</a></p></section>`, { status: mappedError.status });
731
- }
732
- return htmlResponse(`<section class="page-header"><h1>${mappedError.message}</h1></section>`, {
733
- status: mappedError.status
303
+ return Response.redirect(loginRedirectLocation(request), 302);
304
+ }
305
+ const errors = mappedError instanceof ValidationError ? normalizeFieldErrors(mappedError.details) : undefined;
306
+ return htmlErrorResponse({
307
+ status: mappedError.status,
308
+ title: errorPageTitle(mappedError.status, mappedError.message),
309
+ message: publicErrorMessage(mappedError.status, mappedError.message),
310
+ errors,
311
+ request
734
312
  });
735
313
  }
736
314
 
@@ -760,7 +338,7 @@ function withErrorHandling(handler) {
760
338
  return await handler(...args);
761
339
  } catch (error) {
762
340
  const request = args.find((arg) => arg instanceof Request);
763
- const webResponse = webErrorResponse(error, request);
341
+ const webResponse = await webErrorResponse(error, request);
764
342
  if (webResponse) {
765
343
  return webResponse;
766
344
  }