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