@getstrata/core 0.5.60 → 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.
@@ -83,219 +83,9 @@ 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
300
90
  function withCharset(contentType) {
301
91
  return contentType.includes("charset=") ? contentType : `${contentType}; charset=utf-8`;
@@ -320,9 +110,6 @@ function redirectResponse(location, status = 302) {
320
110
  }
321
111
  });
322
112
  }
323
- function notFoundHtmlResponse(body = "Not Found") {
324
- return htmlResponse(body, { status: 404 });
325
- }
326
113
  function textResponse(body, init = {}) {
327
114
  return new Response(body, {
328
115
  status: init.status ?? 200,
@@ -342,344 +129,82 @@ function xmlResponse(body, init = {}) {
342
129
  function rssResponse(body, init = {}) {
343
130
  return xmlResponse(body, { ...init, contentType: "application/rss+xml" });
344
131
  }
345
- // ../../src/core/view/webLayoutData.ts
346
- import { currentAuthUser } from "@getstrata/core/auth/authContext";
347
- import { currentRequestMeta as currentRequestMeta2 } from "@getstrata/core/http/requestMetaContext";
348
-
349
- // ../../src/core/contracts/serviceTokens.ts
350
- var CORE_CONFIG_TOKEN = "core.config";
351
- var CORE_CACHE_TOKEN = "core.cache";
352
- var CORE_QUEUE_TOKEN = "core.queue";
353
- var CORE_EVENT_BUS_TOKEN = "core.eventBus";
354
- var CORE_POLICY_GATE_TOKEN = "core.policyGate";
355
- var CORE_AUTH_TOKEN = "core.auth";
356
- var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
357
- var CORE_ABILITY_CHECKER_TOKEN = "core.abilityChecker";
358
- var CORE_AUTH_USER_DIRECTORY_TOKEN = "core.authUserDirectory";
359
- function isAbilityChecker(value) {
360
- if (!value || typeof value !== "object") {
361
- return false;
362
- }
363
- const candidate = value;
364
- return typeof candidate.tokenCan === "function" && typeof candidate.requireAbility === "function";
365
- }
366
- function isAuthUserDirectory(value) {
367
- if (!value || typeof value !== "object") {
368
- return false;
369
- }
370
- return typeof value.findByIdOrThrow === "function";
371
- }
372
- function resolveAbilityChecker(container) {
373
- if (container.has(CORE_ABILITY_CHECKER_TOKEN)) {
374
- return container.resolve(CORE_ABILITY_CHECKER_TOKEN);
375
- }
376
- return container.resolve(CORE_TOKEN_SERVICE_TOKEN);
377
- }
378
- function resolveAuthUserDirectory(container) {
379
- if (container.has(CORE_AUTH_USER_DIRECTORY_TOKEN)) {
380
- const directory = container.resolve(CORE_AUTH_USER_DIRECTORY_TOKEN);
381
- if (isAuthUserDirectory(directory)) {
382
- return directory;
383
- }
384
- }
385
- if (container.has(CORE_TOKEN_SERVICE_TOKEN)) {
386
- const tokenService = container.resolve(CORE_TOKEN_SERVICE_TOKEN);
387
- if (isAuthUserDirectory(tokenService)) {
388
- return tokenService;
389
- }
390
- }
391
- return null;
392
- }
393
-
394
- // ../../src/core/http/csrfToken.ts
395
- import { timingSafeEqual } from "crypto";
396
-
397
- // ../../src/core/http/cookies.ts
398
- function readRequestCookie(request, name) {
399
- const cookies = request.cookies;
400
- if (cookies && typeof cookies.get === "function") {
401
- const value = cookies.get(name);
402
- if (value) {
403
- return value;
404
- }
405
- }
406
- const header = request.headers.get("cookie");
407
- if (!header) {
408
- return null;
409
- }
410
- for (const part of header.split(";")) {
411
- const idx = part.indexOf("=");
412
- if (idx === -1)
413
- continue;
414
- const cookieName = part.slice(0, idx).trim();
415
- if (cookieName !== name)
416
- continue;
417
- return decodeURIComponent(part.slice(idx + 1).trim());
418
- }
419
- return null;
420
- }
421
- function readBunRequestCookie(request, name) {
422
- return request.cookies.get(name) ?? readRequestCookie(request, name);
423
- }
424
132
 
425
- // ../../src/core/runtime/asyncContextStore.ts
426
- import { AsyncLocalStorage } from "async_hooks";
427
- function createAsyncContextStore(key) {
428
- const symbol = Symbol.for(key);
429
- const globalRecord = globalThis;
430
- const existing = globalRecord[symbol];
431
- if (existing) {
432
- return existing;
433
- }
434
- const store = new AsyncLocalStorage;
435
- globalRecord[symbol] = store;
436
- return store;
437
- }
438
-
439
- // ../../src/core/http/requestMetaContext.ts
440
- var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
441
- function runWithRequestMeta(meta, callback) {
442
- return requestMetaContext.run(meta, callback);
443
- }
444
- function currentRequestMeta() {
445
- return requestMetaContext.getStore() ?? {
446
- ipAddress: null,
447
- userAgent: null
448
- };
449
- }
450
-
451
- // ../../src/core/http/csrfToken.ts
452
- var CSRF_COOKIE = "workhub_csrf";
453
- var CSRF_TTL_MS = 60 * 60 * 1000;
454
- function csrfCookieName() {
455
- return process.env.CSRF_COOKIE_NAME?.trim() || CSRF_COOKIE;
456
- }
457
- function resolveCsrfSecret() {
458
- return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || process.env.ADMIN_API_TOKEN?.trim() || "workhub-dev-csrf-secret";
459
- }
460
- function csrfVerifyOptions() {
461
- return { secret: resolveCsrfSecret(), maxAge: CSRF_TTL_MS };
462
- }
463
- function tokensMatch(left, right) {
464
- const leftBuffer = Buffer.from(left);
465
- const rightBuffer = Buffer.from(right);
466
- if (leftBuffer.length !== rightBuffer.length) {
467
- return false;
468
- }
469
- return timingSafeEqual(leftBuffer, rightBuffer);
470
- }
471
- function createCsrfTokenCookie() {
472
- const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
473
- const secure = process.env.APP_ENV === "production" ? "; Secure" : "";
474
- return {
475
- token,
476
- cookie: `${csrfCookieName()}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}${secure}`
477
- };
478
- }
479
- function resolveCsrfToken(request) {
480
- const cookieValue = readRequestCookie(request, csrfCookieName());
481
- if (cookieValue && Bun.CSRF.verify(cookieValue, csrfVerifyOptions())) {
482
- return { token: cookieValue };
483
- }
484
- return createCsrfTokenCookie();
485
- }
486
- function readSubmittedCsrfToken(request) {
487
- const headerToken = request.headers.get("x-csrf-token")?.trim();
488
- if (headerToken) {
489
- return headerToken;
490
- }
491
- return null;
492
- }
493
- async function readSubmittedCsrfTokenFromBody(request) {
494
- const headerToken = readSubmittedCsrfToken(request);
495
- if (headerToken) {
496
- return headerToken;
497
- }
498
- const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
499
- if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
500
- const formData = await request.clone().formData();
501
- const field = formData.get("_token");
502
- if (typeof field === "string" && field.trim().length > 0) {
503
- return field.trim();
504
- }
505
- const legacyField = formData.get("_csrf");
506
- if (typeof legacyField === "string" && legacyField.trim().length > 0) {
507
- return legacyField.trim();
508
- }
509
- }
510
- return null;
511
- }
512
- function verifyCsrfToken(request, submittedToken) {
513
- if (!submittedToken) {
514
- return false;
515
- }
516
- const cookieValue = readRequestCookie(request, csrfCookieName());
517
- if (!cookieValue) {
518
- return false;
519
- }
520
- if (!tokensMatch(submittedToken, cookieValue)) {
521
- return false;
522
- }
523
- return Bun.CSRF.verify(submittedToken, csrfVerifyOptions());
524
- }
525
- function resolveCsrfTokenForRequest(request) {
526
- const metaToken = currentRequestMeta().csrfToken;
527
- if (metaToken) {
528
- return metaToken;
529
- }
530
- return resolveCsrfToken(request).token;
531
- }
532
-
533
- // ../../src/core/http/flashSession.ts
534
- import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
535
- var FLASH_COOKIE = "workhub_flash";
536
- var FLASH_TTL_MS = 60 * 1000;
537
- function resolveFlashSecret() {
538
- return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || "workhub-dev-flash-secret";
539
- }
540
- function signFlashPayload(payload, issuedAt) {
541
- const signature = createHmac("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
542
- return `${payload}.${issuedAt}.${signature}`;
543
- }
544
- function readFlashCookie(request) {
545
- const cookieHeader = request.headers.get("cookie");
546
- if (!cookieHeader) {
547
- return null;
548
- }
549
- for (const part of cookieHeader.split(";")) {
550
- const [name, ...rest] = part.trim().split("=");
551
- if (name === FLASH_COOKIE) {
552
- return decodeURIComponent(rest.join("="));
553
- }
554
- }
555
- return null;
556
- }
557
- function parseFlashCookie(cookieValue) {
558
- const parts = cookieValue.split(".");
559
- if (parts.length < 3) {
560
- return null;
561
- }
562
- const signature = parts.pop();
563
- const issuedAtRaw = parts.pop();
564
- const payload = parts.join(".");
565
- if (!signature || !issuedAtRaw || !payload) {
566
- return null;
567
- }
568
- const issuedAt = Number.parseInt(issuedAtRaw, 10);
569
- if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
570
- return null;
571
- }
572
- const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
573
- if (!expectedSignature) {
574
- return null;
575
- }
576
- const expectedBuffer = Buffer.from(expectedSignature);
577
- const actualBuffer = Buffer.from(signature);
578
- if (expectedBuffer.length !== actualBuffer.length) {
579
- return null;
580
- }
581
- if (!timingSafeEqual2(expectedBuffer, actualBuffer)) {
582
- 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);
583
184
  }
584
185
  try {
585
- const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
586
- if (!parsed?.message || typeof parsed.message !== "string") {
587
- return null;
588
- }
589
- if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
590
- return null;
591
- }
592
- return parsed;
186
+ return await render({
187
+ ...input,
188
+ request: input.request ?? currentRequestMeta().request
189
+ });
593
190
  } catch {
594
- return null;
191
+ return renderKernelErrorChrome(input);
595
192
  }
596
193
  }
597
- function createFlashCookie(message) {
598
- const payload = Buffer.from(JSON.stringify(message), "utf8").toString("base64url");
599
- const issuedAt = Date.now();
600
- const value = signFlashPayload(payload, issuedAt);
601
- 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 });
602
196
  }
603
- function clearFlashCookie() {
604
- return `${FLASH_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
605
- }
606
- function pullFlash(request) {
607
- const cookieValue = readFlashCookie(request);
608
- if (!cookieValue) {
609
- return null;
197
+ async function notFoundHtmlResponse(body) {
198
+ if (body !== undefined) {
199
+ return htmlResponse(body, { status: 404 });
610
200
  }
611
- return parseFlashCookie(cookieValue);
612
- }
613
- function flashResponse(response, message) {
614
- const headers = new Headers(response.headers);
615
- headers.append("set-cookie", createFlashCookie(message));
616
- return new Response(response.body, {
617
- status: response.status,
618
- statusText: response.statusText,
619
- headers
620
- });
621
- }
622
- function withFlashClear(response) {
623
- const headers = new Headers(response.headers);
624
- headers.append("set-cookie", clearFlashCookie());
625
- return new Response(response.body, {
626
- status: response.status,
627
- statusText: response.statusText,
628
- headers
201
+ return htmlErrorResponse({
202
+ status: 404,
203
+ title: "Not Found",
204
+ message: "The page you requested was not found."
629
205
  });
630
206
  }
631
207
 
632
- // ../../src/core/view/webLayoutData.ts
633
- var configuredLayoutOptions = {};
634
- function configureWebLayoutData(options) {
635
- configuredLayoutOptions = { ...options };
636
- }
637
- function layoutUserKey(options) {
638
- return options.userKey ?? "authUser";
639
- }
640
- async function defaultLoadLayoutUser(container, _request) {
641
- const authUser = currentAuthUser();
642
- if (!authUser) {
643
- return null;
644
- }
645
- const userId = Number(authUser.id);
646
- if (!Number.isInteger(userId) || userId <= 0) {
647
- return null;
648
- }
649
- const directory = resolveAuthUserDirectory(container);
650
- if (!directory) {
651
- return {
652
- id: userId,
653
- email: "",
654
- role: authUser.role ?? "member"
655
- };
656
- }
657
- try {
658
- const user = await directory.findByIdOrThrow(userId);
659
- return {
660
- id: userId,
661
- email: user.email ?? "",
662
- role: authUser.role ?? user.role ?? "member"
663
- };
664
- } catch {
665
- return null;
666
- }
667
- }
668
- async function resolveWebLayoutData(container, request, options = {}) {
669
- const resolved = { ...configuredLayoutOptions, ...options };
670
- const csrfToken = request ? resolveCsrfTokenForRequest(request) : "";
671
- const flash = request ? currentRequestMeta2().flash ?? pullFlash(request) : null;
672
- const userKey = layoutUserKey(resolved);
673
- const loadUser = resolved.loadUser ?? defaultLoadLayoutUser;
674
- const user = await loadUser(container, request);
675
- const extra = typeof resolved.extra === "function" ? await resolved.extra(user) : resolved.extra ?? {};
676
- return {
677
- [userKey]: user,
678
- csrfToken,
679
- flash,
680
- ...extra
681
- };
682
- }
683
208
  // ../../src/core/http/contentNegotiation.ts
684
209
  function requestPrefersJson(request) {
685
210
  if (!request) {
@@ -703,6 +228,39 @@ function requestPrefersJson(request) {
703
228
  return pathname.startsWith("/api/");
704
229
  }
705
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
+
706
264
  // ../../src/core/http/webErrorResponse.ts
707
265
  function normalizeFieldErrors(details) {
708
266
  if (!details || typeof details !== "object" || Array.isArray(details)) {
@@ -720,23 +278,37 @@ function normalizeFieldErrors(details) {
720
278
  }
721
279
  return errors;
722
280
  }
723
- 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) {
724
298
  if (!request || !isViewsEnabled() || requestPrefersJson(request)) {
725
299
  return null;
726
300
  }
727
301
  const mappedError = error instanceof HttpError2 ? error : mapDatabaseError(error);
728
302
  if (mappedError instanceof UnauthorizedError) {
729
- const redirectTarget = encodeURIComponent(new URL(request.url).pathname);
730
- return Response.redirect(`/login?redirect=${redirectTarget}`, 302);
731
- }
732
- if (mappedError instanceof ValidationError) {
733
- const errors = normalizeFieldErrors(mappedError.details);
734
- const fieldSummary = Object.entries(errors).flatMap(([field, messages]) => messages.map((message) => `${field}: ${message}`)).join(`
735
- `);
736
- 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 });
737
- }
738
- return htmlResponse(`<section class="page-header"><h1>${mappedError.message}</h1></section>`, {
739
- 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
740
312
  });
741
313
  }
742
314
 
@@ -766,7 +338,7 @@ function withErrorHandling(handler) {
766
338
  return await handler(...args);
767
339
  } catch (error) {
768
340
  const request = args.find((arg) => arg instanceof Request);
769
- const webResponse = webErrorResponse(error, request);
341
+ const webResponse = await webErrorResponse(error, request);
770
342
  if (webResponse) {
771
343
  return webResponse;
772
344
  }