@getstrata/core 2.2.41 → 2.2.43

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/dist/index.js CHANGED
@@ -384,7 +384,7 @@ function groupQueuedModelEvents(queued) {
384
384
  for (const item of queued) {
385
385
  const lastGroup = groups[groups.length - 1];
386
386
  const last = lastGroup?.[lastGroup.length - 1];
387
- if (!lastGroup || !last || !sameTenant(last.tenant, item.tenant)) {
387
+ if (!lastGroup || !last || !sameTenant(last.tenant, item.tenant) || "callback" in last !== "callback" in item) {
388
388
  groups.push([item]);
389
389
  } else {
390
390
  lastGroup.push(item);
@@ -394,7 +394,10 @@ function groupQueuedModelEvents(queued) {
394
394
  }
395
395
  async function dispatchEventBatch(batch) {
396
396
  for (const item of batch) {
397
- await eventBus.dispatch(item.event, item.payload);
397
+ if ("callback" in item)
398
+ await item.callback();
399
+ else
400
+ await eventBus.dispatch(item.event, item.payload);
398
401
  }
399
402
  }
400
403
  async function dispatchQueuedModelEvents(queued) {
@@ -405,7 +408,11 @@ async function dispatchQueuedModelEvents(queued) {
405
408
  for (const batch of groupQueuedModelEvents(queued)) {
406
409
  const tenant = batch[0]?.tenant ?? null;
407
410
  if (tenant) {
408
- await runWithTenantDatabase(tenant, () => dispatchEventBatch(batch));
411
+ if (batch.some((item) => ("callback" in item))) {
412
+ await runWithTenant(tenant, () => dispatchEventBatch(batch));
413
+ } else {
414
+ await runWithTenantDatabase(tenant, () => dispatchEventBatch(batch));
415
+ }
409
416
  } else {
410
417
  await dispatchEventBatch(batch);
411
418
  }
@@ -425,6 +432,14 @@ async function dispatchModelEvent(event, payload) {
425
432
  }
426
433
  await eventBus.dispatch(event, payload);
427
434
  }
435
+ async function afterCommit(callback) {
436
+ const frame = deferredModelEvents.getStore()?.frames.at(-1);
437
+ if (frame) {
438
+ frame.push({ callback, tenant: currentTenant() });
439
+ return;
440
+ }
441
+ await callback();
442
+ }
428
443
  async function runWithDeferredModelEvents(callback) {
429
444
  const existing = deferredModelEvents.getStore();
430
445
  if (existing) {
@@ -11545,98 +11560,32 @@ function mail() {
11545
11560
  function storageFacade() {
11546
11561
  return storage();
11547
11562
  }
11548
- // ../../src/core/http/bodySizeLimitMiddleware.ts
11549
- var guards = new WeakMap;
11550
- function guardBody(request, maxBytes) {
11551
- const existing = guards.get(request);
11552
- if (existing && existing.maxBytes <= maxBytes)
11553
- return existing;
11554
- const state = { maxBytes, exceeded: false };
11555
- const body = request.body;
11556
- if (!body)
11557
- return state;
11558
- let consumed = 0;
11559
- const stream = body.pipeThrough(new TransformStream({
11560
- transform(chunk, controller) {
11561
- const bytes = typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
11562
- consumed += bytes.byteLength;
11563
- if (consumed > maxBytes) {
11564
- state.exceeded = true;
11565
- throw new PayloadTooLargeError(`Request body exceeds the ${maxBytes} byte limit.`);
11566
- }
11567
- controller.enqueue(bytes);
11568
- }
11569
- }));
11570
- const bounded = new Request(request, { body: stream });
11571
- const decorateClone = (clone) => {
11572
- for (const field of ["params", "cookies"]) {
11573
- if (field in request)
11574
- Object.defineProperty(clone, field, { value: Reflect.get(request, field) });
11575
- }
11576
- const nativeClone = () => Reflect.apply(Request.prototype.clone, clone, []);
11577
- Object.defineProperty(clone, "clone", {
11578
- value: () => decorateClone(nativeClone())
11579
- });
11580
- guards.set(clone, state);
11581
- return clone;
11582
- };
11583
- const descriptors = {
11584
- body: { configurable: true, get: () => bounded.body },
11585
- bodyUsed: { configurable: true, get: () => bounded.bodyUsed },
11586
- clone: {
11587
- configurable: true,
11588
- value: () => decorateClone(Reflect.apply(Request.prototype.clone, bounded, []))
11589
- }
11590
- };
11591
- for (const method of [
11592
- "text",
11593
- "json",
11594
- "formData",
11595
- "arrayBuffer",
11596
- "blob",
11597
- "bytes",
11598
- "textStream"
11599
- ]) {
11600
- descriptors[method] = { configurable: true, value: bounded[method].bind(bounded) };
11563
+ // ../../src/core/runtime/frontendMode.ts
11564
+ var FRONTEND_MODES = ["api", "server-htmx", "spa-react", "hybrid"];
11565
+ var FRONTEND_MODE_PATTERN = new RegExp(`^(${FRONTEND_MODES.join("|")})$`);
11566
+ function parseFrontendMode(value) {
11567
+ const mode = (value ?? "api").trim();
11568
+ if (mode === "server-htmx" || mode === "spa-react" || mode === "hybrid") {
11569
+ return mode;
11601
11570
  }
11602
- Object.defineProperties(request, descriptors);
11603
- guards.set(request, state);
11604
- return state;
11571
+ return "api";
11605
11572
  }
11606
- var DEFAULT_MAX_BODY_BYTES = 1048576;
11607
- function resolveMaxBodyBytes() {
11608
- const raw = process.env.MAX_REQUEST_BODY_BYTES?.trim();
11609
- if (!raw) {
11610
- return DEFAULT_MAX_BODY_BYTES;
11611
- }
11612
- const parsed = Number(raw);
11613
- if (!Number.isSafeInteger(parsed) || parsed <= 0) {
11614
- return DEFAULT_MAX_BODY_BYTES;
11615
- }
11616
- return parsed;
11573
+ function readFrontendMode() {
11574
+ return parseFrontendMode(process.env.FRONTEND_MODE);
11617
11575
  }
11618
- function createBodySizeLimitMiddleware(maxBytes = resolveMaxBodyBytes()) {
11619
- if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
11620
- throw new RangeError("Body limit must be a positive safe integer.");
11621
- return async (request, next) => {
11622
- const tooLarge = () => {
11623
- const error = new PayloadTooLargeError(`Request body exceeds the ${maxBytes} byte limit.`);
11624
- return Response.json({ error: error.message }, { status: error.status });
11625
- };
11626
- const length = Number(request.headers.get("content-length"));
11627
- if (Number.isFinite(length) && length > maxBytes)
11628
- return tooLarge();
11629
- const state = guardBody(request, maxBytes);
11630
- try {
11631
- const response = await next();
11632
- return state.exceeded ? tooLarge() : response;
11633
- } catch (error) {
11634
- if (state.exceeded || error instanceof PayloadTooLargeError)
11635
- return tooLarge();
11636
- throw error;
11637
- }
11638
- };
11576
+ function isViewsMode(mode) {
11577
+ return mode === "server-htmx" || mode === "hybrid";
11578
+ }
11579
+ function isSpaMode(mode) {
11580
+ return mode === "spa-react" || mode === "hybrid";
11581
+ }
11582
+ function isViewsEnabled() {
11583
+ return isViewsMode(readFrontendMode());
11639
11584
  }
11585
+ function isSpaEnabled() {
11586
+ return isSpaMode(readFrontendMode());
11587
+ }
11588
+
11640
11589
  // ../../src/core/http/requestMetaContext.ts
11641
11590
  init_asyncContextStore();
11642
11591
  var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
@@ -11650,1428 +11599,1500 @@ function currentRequestMeta() {
11650
11599
  };
11651
11600
  }
11652
11601
 
11653
- // ../../src/core/http/clientIp.ts
11654
- function trustForwardedFor(env = process.env) {
11655
- return (env.TRUST_FORWARDED_FOR ?? "false") === "true";
11656
- }
11657
- function isPrivateAddress(address) {
11658
- const ip = address.replace(/^::ffff:/i, "");
11659
- return ip === "::1" || ip === "localhost" || /^127\./.test(ip) || /^10\./.test(ip) || /^192\.168\./.test(ip) || /^172\.(1[6-9]|2\d|3[01])\./.test(ip) || /^169\.254\./.test(ip) || /^f[cd][0-9a-f]{2}:/i.test(ip) || /^fe80:/i.test(ip);
11660
- }
11661
- function forwardedClientIp(request) {
11662
- const hops = (request.headers.get("x-forwarded-for") ?? "").split(",").map((hop) => hop.trim()).filter(Boolean);
11663
- for (let index = hops.length - 1;index >= 0; index -= 1) {
11664
- const hop = hops[index];
11665
- if (hop && !isPrivateAddress(hop)) {
11666
- return hop;
11667
- }
11602
+ // ../../src/core/http/safeInternalPath.ts
11603
+ var NESTED_REDIRECT_KEYS = new Set(["redirect", "next", "return", "returnTo", "return_to"]);
11604
+ function looksLikeExternalTarget(value) {
11605
+ const trimmed = value.trim();
11606
+ if (!trimmed.startsWith("/") || trimmed.startsWith("//") || trimmed.includes("\\")) {
11607
+ return true;
11668
11608
  }
11669
- if (hops.length > 0) {
11670
- return hops[hops.length - 1];
11609
+ if (trimmed.includes("://") || trimmed.includes(":/") || trimmed.includes(":\\")) {
11610
+ return true;
11671
11611
  }
11672
- return request.headers.get("x-real-ip")?.trim() || undefined;
11673
- }
11674
- function readClientIp(request, env = process.env) {
11675
- if (trustForwardedFor(env)) {
11676
- const forwarded = forwardedClientIp(request);
11677
- if (forwarded) {
11678
- return forwarded;
11612
+ try {
11613
+ const decoded = decodeURIComponent(trimmed);
11614
+ if (decoded.startsWith("//") || decoded.includes("\\") || /https?:/i.test(decoded)) {
11615
+ return true;
11679
11616
  }
11617
+ } catch {
11618
+ return true;
11680
11619
  }
11681
- return currentRequestMeta().ipAddress ?? undefined;
11682
- }
11683
- // ../../src/core/crypto/nonCryptographicHash.ts
11684
- function nonCryptographicDigest(input) {
11685
- return Bun.hash(input).toString(16);
11620
+ return false;
11686
11621
  }
11687
-
11688
- // ../../src/core/http/etag.ts
11689
- function isEtagEnabled() {
11690
- return (process.env.FEATURE_ETAG ?? "true") !== "false";
11622
+ function sanitizeNestedQuery(search) {
11623
+ if (!search) {
11624
+ return "";
11625
+ }
11626
+ const params = new URLSearchParams(search.startsWith("?") ? search.slice(1) : search);
11627
+ const next = new URLSearchParams;
11628
+ for (const [key, value] of params.entries()) {
11629
+ if (NESTED_REDIRECT_KEYS.has(key)) {
11630
+ const sanitized = sanitizeInternalPath(value, "/");
11631
+ next.set(key, sanitized);
11632
+ continue;
11633
+ }
11634
+ if (looksLikeExternalTarget(value) && value.includes("://")) {
11635
+ continue;
11636
+ }
11637
+ next.set(key, value);
11638
+ }
11639
+ const serialized = next.toString();
11640
+ return serialized ? `?${serialized}` : "";
11691
11641
  }
11692
- function formatWeakEtag(digest) {
11693
- return `W/"${digest}"`;
11642
+ function sanitizeInternalPath(raw, fallback = "/") {
11643
+ const trimmed = raw.trim();
11644
+ if (looksLikeExternalTarget(trimmed)) {
11645
+ return fallback;
11646
+ }
11647
+ const queryIndex = trimmed.indexOf("?");
11648
+ const hashIndex = trimmed.indexOf("#");
11649
+ const end = [queryIndex, hashIndex].filter((index) => index >= 0).sort((a, b) => a - b)[0];
11650
+ const pathname = end === undefined ? trimmed : trimmed.slice(0, end);
11651
+ if (looksLikeExternalTarget(pathname)) {
11652
+ return fallback;
11653
+ }
11654
+ const search = queryIndex >= 0 ? trimmed.slice(queryIndex, hashIndex >= 0 ? hashIndex : undefined) : "";
11655
+ return `${pathname}${sanitizeNestedQuery(search)}`;
11694
11656
  }
11695
- function computeEtagFromJson(data) {
11696
- const digest = nonCryptographicDigest(JSON.stringify(data)).slice(0, 32);
11697
- return formatWeakEtag(digest);
11657
+ function safeInternalRedirectPath(request, fallback = "/") {
11658
+ const url = new URL(request.url);
11659
+ return sanitizeInternalPath(`${url.pathname}${url.search}`, fallback);
11698
11660
  }
11699
- function etagFromResource(resource) {
11700
- const version = resource.updated_at ?? resource.created_at ?? "";
11701
- const versionText = version instanceof Date ? version.toISOString() : version ? String(version) : "0";
11702
- const digest = nonCryptographicDigest(`${String(resource.id ?? "0")}:${versionText}`).slice(0, 32);
11703
- return formatWeakEtag(digest);
11661
+ function loginRedirectLocation(request) {
11662
+ return `/login?redirect=${encodeURIComponent(safeInternalRedirectPath(request))}`;
11704
11663
  }
11705
- function normalizeEtag(value) {
11706
- return value.trim();
11664
+
11665
+ // ../../src/core/view/htmlResponse.ts
11666
+ function withCharset(contentType) {
11667
+ return contentType.includes("charset=") ? contentType : `${contentType}; charset=utf-8`;
11707
11668
  }
11708
- function etagValuesMatch(left, right) {
11709
- return normalizeEtag(left) === normalizeEtag(right);
11669
+ function htmlResponse(html, init = {}) {
11670
+ return new Response(html, {
11671
+ status: init.status ?? 200,
11672
+ statusText: init.statusText,
11673
+ headers: {
11674
+ "Content-Type": "text/html; charset=utf-8"
11675
+ }
11676
+ });
11710
11677
  }
11711
- function parseEtagList(header) {
11712
- if (!header) {
11713
- return [];
11714
- }
11715
- return header.split(",").map((value) => normalizeEtag(value)).filter(Boolean);
11678
+ function isHtmxRequest(request) {
11679
+ return request.headers.get("HX-Request") === "true";
11716
11680
  }
11717
- function ifNoneMatchSatisfied(request, etag) {
11718
- const header = request.headers.get("if-none-match");
11719
- if (!header) {
11720
- return false;
11721
- }
11722
- if (header.trim() === "*") {
11723
- return true;
11681
+ function redirectResponse(location, status = 302) {
11682
+ if (!location.startsWith("/") || location.startsWith("//")) {
11683
+ throw new Error("Redirect location must be an internal path.");
11724
11684
  }
11725
- return parseEtagList(header).some((candidate) => etagValuesMatch(candidate, etag));
11685
+ return new Response(null, {
11686
+ status,
11687
+ headers: {
11688
+ Location: sanitizeInternalPath(location, "/")
11689
+ }
11690
+ });
11726
11691
  }
11727
- function ifMatchSatisfied(request, etag) {
11728
- const header = request.headers.get("if-match");
11729
- if (!header) {
11730
- return false;
11692
+ function textResponse(body, init = {}) {
11693
+ return new Response(body, {
11694
+ status: init.status ?? 200,
11695
+ headers: {
11696
+ "Content-Type": "text/plain; charset=utf-8"
11697
+ }
11698
+ });
11699
+ }
11700
+ function xmlResponse(body, init = {}) {
11701
+ return new Response(body, {
11702
+ status: init.status ?? 200,
11703
+ headers: {
11704
+ "Content-Type": withCharset(init.contentType ?? "application/xml")
11705
+ }
11706
+ });
11707
+ }
11708
+ function rssResponse(body, init = {}) {
11709
+ return xmlResponse(body, { ...init, contentType: "application/rss+xml" });
11710
+ }
11711
+
11712
+ // ../../src/core/view/webErrorView.ts
11713
+ var configuredErrorView = {};
11714
+ function configureWebErrorView(options) {
11715
+ configuredErrorView = { ...options };
11716
+ }
11717
+ function escapeHtml(value) {
11718
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
11719
+ }
11720
+ function errorReturnPath(request) {
11721
+ if (!request)
11722
+ return "/";
11723
+ try {
11724
+ const current = new URL(request.url);
11725
+ const previous = new URL(request.headers.get("referer") ?? "");
11726
+ if (previous.origin !== current.origin || (request.method === "GET" || request.method === "HEAD") && previous.pathname === current.pathname)
11727
+ return "/";
11728
+ return sanitizeInternalPath(previous.pathname, "/");
11729
+ } catch {
11730
+ return "/";
11731
11731
  }
11732
- if (header.trim() === "*") {
11732
+ }
11733
+ function renderKernelErrorChrome(input) {
11734
+ const title = escapeHtml(input.title);
11735
+ const message = escapeHtml(input.message);
11736
+ const errorLines = Object.entries(input.errors ?? {}).flatMap(([field, messages]) => messages.map((item) => `${field}: ${item}`)).map((line) => `<li>${escapeHtml(line)}</li>`).join("");
11737
+ const details = errorLines ? `<ul class="error-list">${errorLines}</ul>` : "";
11738
+ const goBack = input.status === 422 ? `<p><a href="${escapeHtml(errorReturnPath(input.request ?? currentRequestMeta().request))}">Go back</a></p>` : "";
11739
+ return `<!doctype html>
11740
+ <html lang="en">
11741
+ <head>
11742
+ <meta charset="UTF-8" />
11743
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
11744
+ <title>${title}</title>
11745
+ <link rel="stylesheet" href="/assets/app.css" />
11746
+ </head>
11747
+ <body>
11748
+ <header class="site-header">
11749
+ <a class="brand" href="/">Home</a>
11750
+ </header>
11751
+ <main class="site-main">
11752
+ <section class="page-header">
11753
+ <h1>${title}</h1>
11754
+ <p>${message}</p>
11755
+ ${details}
11756
+ ${goBack}
11757
+ </section>
11758
+ </main>
11759
+ </body>
11760
+ </html>
11761
+ `;
11762
+ }
11763
+ function errorTemplateName(status) {
11764
+ if (status === 404) {
11765
+ return "errors/not-found";
11766
+ }
11767
+ if (status === 403) {
11768
+ return "errors/forbidden";
11769
+ }
11770
+ return "errors/error";
11771
+ }
11772
+ async function renderWebErrorHtml(input) {
11773
+ const render = configuredErrorView.render;
11774
+ if (!render) {
11775
+ return renderKernelErrorChrome(input);
11776
+ }
11777
+ try {
11778
+ return await render({
11779
+ ...input,
11780
+ request: input.request ?? currentRequestMeta().request
11781
+ });
11782
+ } catch {
11783
+ return renderKernelErrorChrome(input);
11784
+ }
11785
+ }
11786
+ async function htmlErrorResponse(input) {
11787
+ const response = htmlResponse(await renderWebErrorHtml(input), { status: input.status });
11788
+ response.headers.set("Cache-Control", "no-store");
11789
+ return response;
11790
+ }
11791
+ async function notFoundHtmlResponse(body) {
11792
+ if (body !== undefined) {
11793
+ const response = htmlResponse(body, { status: 404 });
11794
+ response.headers.set("Cache-Control", "no-store");
11795
+ return response;
11796
+ }
11797
+ return htmlErrorResponse({
11798
+ status: 404,
11799
+ title: "Not Found",
11800
+ message: "The page you requested was not found."
11801
+ });
11802
+ }
11803
+
11804
+ // ../../src/core/http/contentNegotiation.ts
11805
+ function requestPrefersJson(request) {
11806
+ if (!request) {
11733
11807
  return true;
11734
11808
  }
11735
- return parseEtagList(header).some((candidate) => etagValuesMatch(candidate, etag));
11809
+ if (request.headers.get("HX-Request") === "true") {
11810
+ return false;
11811
+ }
11812
+ const pathname = new URL(request.url).pathname;
11813
+ if (pathname.startsWith("/api/")) {
11814
+ return true;
11815
+ }
11816
+ const accept = request.headers.get("accept")?.toLowerCase() ?? "";
11817
+ if (accept.includes("text/html")) {
11818
+ return false;
11819
+ }
11820
+ if (accept.includes("application/json")) {
11821
+ return true;
11822
+ }
11823
+ const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
11824
+ if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
11825
+ return false;
11826
+ }
11827
+ return false;
11736
11828
  }
11737
- function assertIfMatch(request, etag, options = {}) {
11738
- const header = request.headers.get("if-match");
11739
- if (!header) {
11740
- if (options.required) {
11741
- throw new PreconditionFailedError("If-Match header is required.");
11829
+
11830
+ // ../../src/core/http/webErrorResponse.ts
11831
+ function normalizeFieldErrors(details) {
11832
+ if (!details || typeof details !== "object" || Array.isArray(details)) {
11833
+ return {};
11834
+ }
11835
+ const errors = {};
11836
+ for (const [field, messages] of Object.entries(details)) {
11837
+ if (Array.isArray(messages)) {
11838
+ errors[field] = messages.map(String);
11839
+ continue;
11840
+ }
11841
+ if (typeof messages === "string") {
11842
+ errors[field] = [messages];
11742
11843
  }
11743
- return;
11744
11844
  }
11745
- if (!ifMatchSatisfied(request, etag)) {
11746
- throw new PreconditionFailedError("Resource ETag does not match If-Match.");
11845
+ return errors;
11846
+ }
11847
+ function errorPageTitle(status, message) {
11848
+ if (status === 404) {
11849
+ return "Not Found";
11850
+ }
11851
+ if (status === 403) {
11852
+ return "Forbidden";
11853
+ }
11854
+ if (status >= 500) {
11855
+ return "Server Error";
11747
11856
  }
11857
+ return message;
11748
11858
  }
11749
- function applyEtagHeaders(headers, etag) {
11750
- const next = new Headers(headers);
11751
- next.set("ETag", etag);
11752
- next.set("Cache-Control", "private, must-revalidate");
11753
- next.append("Vary", "Authorization");
11754
- next.append("Vary", "X-Tenant-Id");
11755
- return next;
11859
+ function publicErrorMessage(status, message) {
11860
+ if (status >= 500 && isProductionEnv()) {
11861
+ return "Something went wrong.";
11862
+ }
11863
+ return message;
11756
11864
  }
11757
- function notModifiedResponse(etag) {
11758
- return new Response(null, {
11759
- status: 304,
11760
- headers: applyEtagHeaders(new Headers, etag)
11865
+ function logServerError(error, mappedError) {
11866
+ if (mappedError.status < 500) {
11867
+ return;
11868
+ }
11869
+ appLogger.error("Unhandled request error", {
11870
+ status: mappedError.status,
11871
+ error: error instanceof Error ? error.message : String(error),
11872
+ stack: error instanceof Error ? error.stack : undefined
11761
11873
  });
11762
11874
  }
11763
- function applyConditionalGet(request, response, etag) {
11764
- if (!isEtagEnabled()) {
11765
- return response;
11875
+ async function webErrorResponse(error, request) {
11876
+ if (currentRequestMeta().errorFormat === "json" || !request || !isViewsEnabled() || requestPrefersJson(request)) {
11877
+ return null;
11766
11878
  }
11767
- if (ifNoneMatchSatisfied(request, etag)) {
11768
- return notModifiedResponse(etag);
11879
+ const mappedError = toHttpError(error) ?? mapDatabaseError(error);
11880
+ logServerError(error, mappedError);
11881
+ if (mappedError.status === 401) {
11882
+ return Response.redirect(loginRedirectLocation(request), 302);
11769
11883
  }
11770
- const headers = applyEtagHeaders(new Headers(response.headers), etag);
11771
- return new Response(response.body, {
11772
- status: response.status,
11773
- statusText: response.statusText,
11774
- headers
11884
+ const errors = mappedError instanceof ValidationError || mappedError.name === "ValidationError" ? normalizeFieldErrors(mappedError.details) : undefined;
11885
+ return htmlErrorResponse({
11886
+ status: mappedError.status,
11887
+ title: errorPageTitle(mappedError.status, mappedError.message),
11888
+ message: publicErrorMessage(mappedError.status, mappedError.message),
11889
+ errors,
11890
+ request
11775
11891
  });
11776
11892
  }
11777
11893
 
11778
- // ../../src/core/http/conditionalResponse.ts
11894
+ // ../../src/core/http/response.ts
11895
+ init_transactionControl();
11779
11896
  function jsonResponse(data, init = {}) {
11780
11897
  return Response.json(data, {
11781
11898
  status: init.status ?? 200,
11782
11899
  headers: init.headers
11783
11900
  });
11784
11901
  }
11785
- function conditionalJsonResponse(request, data, init = {}) {
11786
- if (!request || !isEtagEnabled()) {
11787
- return jsonResponse(data, init);
11788
- }
11789
- const etag = computeEtagFromJson(data);
11790
- if (ifNoneMatchSatisfied(request, etag)) {
11791
- return notModifiedResponse(etag);
11792
- }
11902
+ function privateJsonResponse(data, init = {}) {
11793
11903
  const response = jsonResponse(data, init);
11794
- const headers = new Headers(response.headers);
11795
- headers.set("ETag", etag);
11796
- headers.set("Cache-Control", "private, must-revalidate");
11797
- headers.append("Vary", "Authorization");
11798
- headers.append("Vary", "X-Tenant-Id");
11799
- return new Response(response.body, {
11800
- status: response.status,
11801
- statusText: response.statusText,
11802
- headers
11803
- });
11804
- }
11805
- // ../../src/core/runtime/frontendMode.ts
11806
- var FRONTEND_MODES = ["api", "server-htmx", "spa-react", "hybrid"];
11807
- var FRONTEND_MODE_PATTERN = new RegExp(`^(${FRONTEND_MODES.join("|")})$`);
11808
- function parseFrontendMode(value) {
11809
- const mode = (value ?? "api").trim();
11810
- if (mode === "server-htmx" || mode === "spa-react" || mode === "hybrid") {
11811
- return mode;
11812
- }
11813
- return "api";
11904
+ response.headers.set("Cache-Control", "private, no-store");
11905
+ return response;
11814
11906
  }
11815
- function readFrontendMode() {
11816
- return parseFrontendMode(process.env.FRONTEND_MODE);
11907
+ function createdResponse(data, init = {}) {
11908
+ return jsonResponse(data, { ...init, status: init.status ?? 201 });
11817
11909
  }
11818
- function isViewsMode(mode) {
11819
- return mode === "server-htmx" || mode === "hybrid";
11910
+ function noContentResponse() {
11911
+ return new Response(null, { status: 204 });
11820
11912
  }
11821
- function isSpaMode(mode) {
11822
- return mode === "spa-react" || mode === "hybrid";
11823
- }
11824
- function isViewsEnabled() {
11825
- return isViewsMode(readFrontendMode());
11913
+ function errorResponse(error) {
11914
+ const mappedError = toHttpError(error) ?? mapDatabaseError(error);
11915
+ logServerError(error, mappedError);
11916
+ return Response.json({
11917
+ error: mappedError.message,
11918
+ ...mappedError.details === undefined ? {} : { details: mappedError.details }
11919
+ }, { status: mappedError.status, headers: { "Cache-Control": "no-store" } });
11826
11920
  }
11827
- function isSpaEnabled() {
11828
- return isSpaMode(readFrontendMode());
11921
+ function withErrorHandling(handler) {
11922
+ return async (...args) => {
11923
+ try {
11924
+ return await handler(...args);
11925
+ } catch (error) {
11926
+ requestTransactionRollback();
11927
+ const request = args.find((arg) => arg instanceof Request);
11928
+ const webResponse = await webErrorResponse(error, request);
11929
+ if (webResponse) {
11930
+ return webResponse;
11931
+ }
11932
+ return errorResponse(error);
11933
+ }
11934
+ };
11829
11935
  }
11830
11936
 
11831
- // ../../src/core/http/contentSecurityPolicy.ts
11832
- var HTMX_2_0_4_INDICATOR_STYLE_HASH = "'sha256-bsV5JivYxvGywDAZ22EZJKBFip65Ng9xoJVLbBg7bdo='";
11833
- var API_DIRECTIVES = {
11834
- "default-src": ["'none'"],
11835
- "frame-ancestors": ["'none'"],
11836
- "base-uri": ["'none'"]
11837
- };
11838
- var HTMX_HTML_DIRECTIVES = {
11839
- "default-src": ["'self'"],
11840
- "script-src": ["'self'"],
11841
- "style-src": ["'self'", HTMX_2_0_4_INDICATOR_STYLE_HASH],
11842
- "connect-src": ["'self'"],
11843
- "img-src": ["'self'", "data:", "https:"],
11844
- "font-src": ["'self'"],
11845
- "media-src": ["'self'", "https:"],
11846
- "frame-src": [
11847
- "https://www.youtube.com",
11848
- "https://www.youtube-nocookie.com",
11849
- "https://player.vimeo.com"
11850
- ],
11851
- "form-action": ["'self'"],
11852
- "frame-ancestors": ["'none'"],
11853
- "base-uri": ["'self'"]
11854
- };
11855
- var SPA_HTML_DIRECTIVES = {
11856
- "default-src": ["'self'"],
11857
- "script-src": ["'self'"],
11858
- "style-src": ["'self'"],
11859
- "connect-src": ["'self'"],
11860
- "img-src": ["'self'", "data:", "https:"],
11861
- "font-src": ["'self'"],
11862
- "frame-ancestors": ["'none'"],
11863
- "base-uri": ["'self'"]
11864
- };
11865
- var configuredHtmlOptions = {};
11866
- function generateCspNonce() {
11867
- const bytes = new Uint8Array(16);
11868
- crypto.getRandomValues(bytes);
11869
- return Buffer.from(bytes).toString("base64");
11870
- }
11871
- function configureContentSecurityPolicy(options) {
11872
- configuredHtmlOptions = { ...options };
11873
- }
11874
- function resetContentSecurityPolicyForTests() {
11875
- configuredHtmlOptions = {};
11876
- }
11877
- function cloneDirectives(source) {
11878
- const copy = {};
11879
- for (const [directive, values] of Object.entries(source)) {
11880
- copy[directive] = [...values];
11881
- }
11882
- return copy;
11883
- }
11884
- function normalizeSources(value) {
11885
- if (Array.isArray(value)) {
11886
- return value.flatMap((item) => item.split(/\s+/).filter(Boolean));
11887
- }
11888
- return value.split(/\s+/).filter(Boolean);
11889
- }
11890
- function mergeDirectives(base, extra) {
11891
- const merged = cloneDirectives(base);
11892
- for (const [directive, value] of Object.entries(extra ?? {})) {
11893
- if (value === false) {
11894
- delete merged[directive];
11895
- continue;
11937
+ // ../../src/core/http/bodySizeLimitMiddleware.ts
11938
+ var guards = new WeakMap;
11939
+ function guardBody(request, maxBytes) {
11940
+ const existing = guards.get(request);
11941
+ if (existing && existing.maxBytes <= maxBytes)
11942
+ return existing;
11943
+ const state = { maxBytes, exceeded: false };
11944
+ const body = request.body;
11945
+ if (!body)
11946
+ return state;
11947
+ let consumed = 0;
11948
+ const stream = body.pipeThrough(new TransformStream({
11949
+ transform(chunk, controller) {
11950
+ const bytes = typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
11951
+ consumed += bytes.byteLength;
11952
+ if (consumed > maxBytes) {
11953
+ state.exceeded = true;
11954
+ throw new PayloadTooLargeError(`Request body exceeds the ${maxBytes} byte limit.`);
11955
+ }
11956
+ controller.enqueue(bytes);
11896
11957
  }
11897
- const sources = normalizeSources(value);
11898
- const existing = merged[directive] ?? [];
11899
- merged[directive] = [...existing, ...sources.filter((source) => !existing.includes(source))];
11900
- }
11901
- return merged;
11902
- }
11903
- function serializeDirectives(directives) {
11904
- return Object.entries(directives).map(([directive, values]) => values.length > 0 ? `${directive} ${values.join(" ")}` : directive).join("; ");
11905
- }
11906
- function applyNonce(directives, nonce) {
11907
- if (!nonce) {
11908
- return directives;
11909
- }
11910
- const token = `'nonce-${nonce}'`;
11911
- const next = cloneDirectives(directives);
11912
- for (const directive of ["script-src", "style-src"]) {
11913
- const values = next[directive] ?? ["'self'"];
11914
- if (!values.includes(token)) {
11915
- next[directive] = [...values, token];
11958
+ }));
11959
+ const bounded = new Request(request, { body: stream });
11960
+ const decorateClone = (clone) => {
11961
+ for (const field of ["params", "cookies"]) {
11962
+ if (field in request)
11963
+ Object.defineProperty(clone, field, { value: Reflect.get(request, field) });
11964
+ }
11965
+ const nativeClone = () => Reflect.apply(Request.prototype.clone, clone, []);
11966
+ Object.defineProperty(clone, "clone", {
11967
+ value: () => decorateClone(nativeClone())
11968
+ });
11969
+ guards.set(clone, state);
11970
+ return clone;
11971
+ };
11972
+ const descriptors = {
11973
+ body: { configurable: true, get: () => bounded.body },
11974
+ bodyUsed: { configurable: true, get: () => bounded.bodyUsed },
11975
+ clone: {
11976
+ configurable: true,
11977
+ value: () => decorateClone(Reflect.apply(Request.prototype.clone, bounded, []))
11916
11978
  }
11979
+ };
11980
+ for (const method of [
11981
+ "text",
11982
+ "json",
11983
+ "formData",
11984
+ "arrayBuffer",
11985
+ "blob",
11986
+ "bytes",
11987
+ "textStream"
11988
+ ]) {
11989
+ descriptors[method] = { configurable: true, value: bounded[method].bind(bounded) };
11917
11990
  }
11918
- return next;
11991
+ Object.defineProperties(request, descriptors);
11992
+ guards.set(request, state);
11993
+ return state;
11919
11994
  }
11920
- function htmlBaselineDirectives() {
11921
- if (isViewsEnabled()) {
11922
- return cloneDirectives(HTMX_HTML_DIRECTIVES);
11995
+ var DEFAULT_MAX_BODY_BYTES = 1048576;
11996
+ function resolveMaxBodyBytes() {
11997
+ const raw = process.env.MAX_REQUEST_BODY_BYTES?.trim();
11998
+ if (!raw) {
11999
+ return DEFAULT_MAX_BODY_BYTES;
11923
12000
  }
11924
- if (isSpaEnabled()) {
11925
- return cloneDirectives(SPA_HTML_DIRECTIVES);
12001
+ const parsed = Number(raw);
12002
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
12003
+ return DEFAULT_MAX_BODY_BYTES;
11926
12004
  }
11927
- return cloneDirectives(API_DIRECTIVES);
12005
+ return parsed;
11928
12006
  }
11929
- function strictApiContentSecurityPolicy() {
11930
- return serializeDirectives(API_DIRECTIVES);
12007
+ function createBodySizeLimitMiddleware(maxBytes = resolveMaxBodyBytes()) {
12008
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
12009
+ throw new RangeError("Body limit must be a positive safe integer.");
12010
+ return async (request, next) => {
12011
+ const tooLarge = () => {
12012
+ const error = new PayloadTooLargeError(`Request body exceeds the ${maxBytes} byte limit.`);
12013
+ return errorResponse(error);
12014
+ };
12015
+ const length = Number(request.headers.get("content-length"));
12016
+ if (Number.isFinite(length) && length > maxBytes)
12017
+ return tooLarge();
12018
+ const state = guardBody(request, maxBytes);
12019
+ try {
12020
+ const response = await next();
12021
+ return state.exceeded ? tooLarge() : response;
12022
+ } catch (error) {
12023
+ if (state.exceeded || error instanceof PayloadTooLargeError)
12024
+ return tooLarge();
12025
+ throw error;
12026
+ }
12027
+ };
11931
12028
  }
11932
- function serverHtmxContentSecurityPolicy(nonce) {
11933
- return serializeDirectives(applyNonce(cloneDirectives(HTMX_HTML_DIRECTIVES), nonce));
12029
+ // ../../src/core/http/clientIp.ts
12030
+ function trustForwardedFor(env = process.env) {
12031
+ return (env.TRUST_FORWARDED_FOR ?? "false") === "true";
11934
12032
  }
11935
- function spaContentSecurityPolicy(nonce) {
11936
- return serializeDirectives(applyNonce(cloneDirectives(SPA_HTML_DIRECTIVES), nonce));
12033
+ function isPrivateAddress(address) {
12034
+ const ip = address.replace(/^::ffff:/i, "");
12035
+ return ip === "::1" || ip === "localhost" || /^127\./.test(ip) || /^10\./.test(ip) || /^192\.168\./.test(ip) || /^172\.(1[6-9]|2\d|3[01])\./.test(ip) || /^169\.254\./.test(ip) || /^f[cd][0-9a-f]{2}:/i.test(ip) || /^fe80:/i.test(ip);
11937
12036
  }
11938
- function resolveHtmlContentSecurityPolicy(options = {}) {
11939
- const resolved = {
11940
- ...configuredHtmlOptions,
11941
- ...options,
11942
- directives: {
11943
- ...configuredHtmlOptions.directives,
11944
- ...options.directives
12037
+ function forwardedClientIp(request) {
12038
+ const hops = (request.headers.get("x-forwarded-for") ?? "").split(",").map((hop) => hop.trim()).filter(Boolean);
12039
+ for (let index = hops.length - 1;index >= 0; index -= 1) {
12040
+ const hop = hops[index];
12041
+ if (hop && !isPrivateAddress(hop)) {
12042
+ return hop;
11945
12043
  }
11946
- };
11947
- const override = resolved.htmlCsp ?? resolved.csp;
11948
- if (override) {
11949
- return override;
11950
12044
  }
11951
- return serializeDirectives(applyNonce(mergeDirectives(htmlBaselineDirectives(), resolved.directives), options.nonce));
11952
- }
11953
- function resolveContentSecurityPolicy(response, options = {}) {
11954
- const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
11955
- if (!contentType.includes("text/html")) {
11956
- return strictApiContentSecurityPolicy();
12045
+ if (hops.length > 0) {
12046
+ return hops[hops.length - 1];
11957
12047
  }
11958
- return resolveHtmlContentSecurityPolicy(options);
12048
+ return request.headers.get("x-real-ip")?.trim() || undefined;
11959
12049
  }
11960
- // ../../src/core/http/corsMiddleware.ts
11961
- function additionalHeaders(options) {
11962
- const configured = process.env.CORS_ADDITIONAL_ALLOWED_HEADERS?.trim();
11963
- const supplied = options.additionalAllowedHeaders === undefined ? [] : options.additionalAllowedHeaders;
11964
- if (!Array.isArray(supplied)) {
11965
- throw new TypeError("CORS additionalAllowedHeaders must be an array of header names.");
11966
- }
11967
- const names = [
11968
- ...configured ? configured.split(",").map((name) => name.trim()) : [],
11969
- ...supplied
11970
- ];
11971
- return names.map((name) => {
11972
- if (typeof name !== "string" || name === "*" || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) {
11973
- throw new TypeError("CORS additional headers must be explicit valid HTTP header names; wildcards are not allowed.");
12050
+ function readClientIp(request, env = process.env) {
12051
+ if (trustForwardedFor(env)) {
12052
+ const forwarded = forwardedClientIp(request);
12053
+ if (forwarded) {
12054
+ return forwarded;
11974
12055
  }
11975
- return name;
11976
- });
12056
+ }
12057
+ return currentRequestMeta().ipAddress ?? undefined;
11977
12058
  }
11978
- function defaultAllowedOrigins() {
11979
- return appUrl();
12059
+ // ../../src/core/crypto/nonCryptographicHash.ts
12060
+ function nonCryptographicDigest(input) {
12061
+ return Bun.hash(input).toString(16);
11980
12062
  }
11981
- function resolveCorsConfig(options = {}) {
11982
- const extraHeaders = additionalHeaders(options);
11983
- return {
11984
- allowedOrigins: (process.env.CORS_ALLOWED_ORIGINS ?? defaultAllowedOrigins()).split(",").map((origin) => origin.trim()).filter(Boolean),
11985
- allowedMethods: ["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"],
11986
- allowedHeaders: [
11987
- "Authorization",
11988
- "Content-Type",
11989
- "X-Request-Id",
11990
- "X-Tenant-Id",
11991
- "X-Authenticated-User-Id",
11992
- "X-Authenticated-User-Role",
11993
- "If-Match",
11994
- "If-None-Match",
11995
- "X-CSRF-Token",
11996
- ...extraHeaders
11997
- ].filter((name, index, names) => names.findIndex((other) => other.toLowerCase() === name.toLowerCase()) === index),
11998
- maxAgeSeconds: 86400
11999
- };
12063
+
12064
+ // ../../src/core/http/etag.ts
12065
+ function isEtagEnabled() {
12066
+ return (process.env.FEATURE_ETAG ?? "true") !== "false";
12000
12067
  }
12001
- function createCorsMiddleware(options = {}) {
12002
- resolveCorsConfig(options);
12003
- const captured = {
12004
- additionalAllowedHeaders: [...options.additionalAllowedHeaders ?? []]
12005
- };
12006
- return async (request, next) => {
12007
- if (request.method === "OPTIONS") {
12008
- return new Response(null, {
12009
- status: 204,
12010
- headers: buildCorsHeaders(request, captured)
12011
- });
12012
- }
12013
- const response = await next();
12014
- const headers = new Headers(response.headers);
12015
- for (const [key, value] of buildCorsHeaders(request, captured)) {
12016
- if (key === "vary") {
12017
- const fields = (headers.get("Vary") ?? "").split(",").map((field) => field.trim()).filter(Boolean);
12018
- if (fields.includes("*"))
12019
- continue;
12020
- if (!fields.some((field) => field.toLowerCase() === "origin"))
12021
- fields.push(value);
12022
- headers.set("Vary", fields.join(", "));
12023
- } else {
12024
- headers.set(key, value);
12025
- }
12026
- }
12027
- return new Response(response.body, {
12028
- status: response.status,
12029
- statusText: response.statusText,
12030
- headers
12031
- });
12032
- };
12068
+ function formatWeakEtag(digest) {
12069
+ return `W/"${digest}"`;
12033
12070
  }
12034
- function buildCorsHeaders(request, options) {
12035
- const headers = new Headers;
12036
- const origin = request.headers.get("origin");
12037
- const corsConfig = resolveCorsConfig(options);
12038
- const allowedOrigins = corsConfig.allowedOrigins;
12039
- headers.set("Vary", "Origin");
12040
- const allowOrigin = allowedOrigins.includes("*") ? "*" : origin && allowedOrigins.includes(origin) ? origin : null;
12041
- if (!allowOrigin) {
12042
- return headers;
12043
- }
12044
- headers.set("Access-Control-Allow-Origin", allowOrigin);
12045
- headers.set("Access-Control-Allow-Methods", corsConfig.allowedMethods.join(", "));
12046
- headers.set("Access-Control-Allow-Headers", corsConfig.allowedHeaders.join(", "));
12047
- headers.set("Access-Control-Max-Age", String(corsConfig.maxAgeSeconds));
12048
- if (allowOrigin !== "*") {
12049
- headers.set("Access-Control-Allow-Credentials", "true");
12050
- }
12051
- return headers;
12071
+ function computeEtagFromJson(data) {
12072
+ const digest = nonCryptographicDigest(JSON.stringify(data)).slice(0, 32);
12073
+ return formatWeakEtag(digest);
12052
12074
  }
12053
- // ../../src/core/http/csrfToken.ts
12054
- import { timingSafeEqual as timingSafeEqual3 } from "crypto";
12055
- var CSRF_COOKIE = appCookieName("csrf");
12056
- var CSRF_TTL_MS = 60 * 60 * 1000;
12057
- function csrfCookieName() {
12058
- return process.env.CSRF_COOKIE_NAME?.trim() || appCookieName("csrf");
12075
+ function etagFromResource(resource) {
12076
+ const version = resource.updated_at ?? resource.created_at ?? "";
12077
+ const versionText = version instanceof Date ? version.toISOString() : version ? String(version) : "0";
12078
+ const digest = nonCryptographicDigest(`${String(resource.id ?? "0")}:${versionText}`).slice(0, 32);
12079
+ return formatWeakEtag(digest);
12059
12080
  }
12060
- function resolveCsrfSecret() {
12061
- return requireConfiguredSecret(["SESSION_SECRET", "CSRF_SECRET"], "csrf-secret");
12081
+ function normalizeEtag(value) {
12082
+ return value.trim();
12062
12083
  }
12063
- function csrfVerifyOptions() {
12064
- return { secret: resolveCsrfSecret(), maxAge: CSRF_TTL_MS };
12084
+ function etagValuesMatch(left, right) {
12085
+ return normalizeEtag(left) === normalizeEtag(right);
12065
12086
  }
12066
- function tokensMatch(left, right) {
12067
- const leftBuffer = Buffer.from(left);
12068
- const rightBuffer = Buffer.from(right);
12069
- if (leftBuffer.length !== rightBuffer.length) {
12070
- return false;
12087
+ function parseEtagList(header) {
12088
+ if (!header) {
12089
+ return [];
12071
12090
  }
12072
- return timingSafeEqual3(leftBuffer, rightBuffer);
12073
- }
12074
- function createCsrfTokenCookie() {
12075
- const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
12076
- const secure = isProductionEnv() ? "; Secure" : "";
12077
- return {
12078
- token,
12079
- cookie: `${csrfCookieName()}=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}${secure}`
12080
- };
12091
+ return header.split(",").map((value) => normalizeEtag(value)).filter(Boolean);
12081
12092
  }
12082
- function resolveCsrfToken(request) {
12083
- const cookieValue = readRequestCookie(request, csrfCookieName());
12084
- if (cookieValue && Bun.CSRF.verify(cookieValue, csrfVerifyOptions())) {
12085
- return { token: cookieValue };
12093
+ function ifNoneMatchSatisfied(request, etag) {
12094
+ const header = request.headers.get("if-none-match");
12095
+ if (!header) {
12096
+ return false;
12086
12097
  }
12087
- return createCsrfTokenCookie();
12088
- }
12089
- function readSubmittedCsrfToken(request) {
12090
- const headerToken = request.headers.get("x-csrf-token")?.trim();
12091
- if (headerToken) {
12092
- return headerToken;
12098
+ if (header.trim() === "*") {
12099
+ return true;
12093
12100
  }
12094
- return null;
12101
+ return parseEtagList(header).some((candidate) => etagValuesMatch(candidate, etag));
12095
12102
  }
12096
- async function readSubmittedCsrfTokenFromBody(request) {
12097
- const headerToken = readSubmittedCsrfToken(request);
12098
- if (headerToken) {
12099
- return headerToken;
12103
+ function ifMatchSatisfied(request, etag) {
12104
+ const header = request.headers.get("if-match");
12105
+ if (!header) {
12106
+ return false;
12100
12107
  }
12101
- const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
12102
- if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
12103
- const formData = await request.clone().formData();
12104
- const field = formData.get("_token");
12105
- if (typeof field === "string" && field.trim().length > 0) {
12106
- return field.trim();
12107
- }
12108
- const legacyField = formData.get("_csrf");
12109
- if (typeof legacyField === "string" && legacyField.trim().length > 0) {
12110
- return legacyField.trim();
12111
- }
12108
+ if (header.trim() === "*") {
12109
+ return true;
12112
12110
  }
12113
- return null;
12111
+ return parseEtagList(header).some((candidate) => etagValuesMatch(candidate, etag));
12114
12112
  }
12115
- function verifyCsrfToken(request, submittedToken) {
12116
- if (!submittedToken) {
12117
- return false;
12118
- }
12119
- const cookieValue = readRequestCookie(request, csrfCookieName());
12120
- if (!cookieValue) {
12121
- return false;
12113
+ function assertIfMatch(request, etag, options = {}) {
12114
+ const header = request.headers.get("if-match");
12115
+ if (!header) {
12116
+ if (options.required) {
12117
+ throw new PreconditionFailedError("If-Match header is required.");
12118
+ }
12119
+ return;
12122
12120
  }
12123
- if (!tokensMatch(submittedToken, cookieValue)) {
12124
- return false;
12121
+ if (!ifMatchSatisfied(request, etag)) {
12122
+ throw new PreconditionFailedError("Resource ETag does not match If-Match.");
12125
12123
  }
12126
- return Bun.CSRF.verify(submittedToken, csrfVerifyOptions());
12127
12124
  }
12128
- function resolveCsrfTokenForRequest(request) {
12129
- const metaToken = currentRequestMeta().csrfToken;
12130
- if (metaToken) {
12131
- return metaToken;
12132
- }
12133
- return resolveCsrfToken(request).token;
12125
+ function applyEtagHeaders(headers, etag) {
12126
+ const next = new Headers(headers);
12127
+ next.set("ETag", etag);
12128
+ next.set("Cache-Control", "private, must-revalidate");
12129
+ next.append("Vary", "Authorization");
12130
+ next.append("Vary", "X-Tenant-Id");
12131
+ return next;
12134
12132
  }
12135
-
12136
- // ../../src/core/http/csrfMiddleware.ts
12137
- var MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
12138
- function samlAcsPathname() {
12139
- const configured = process.env.SAML_ACS_URL?.trim();
12140
- if (!configured) {
12141
- return "/auth/saml/acs";
12133
+ function notModifiedResponse(etag) {
12134
+ return new Response(null, {
12135
+ status: 304,
12136
+ headers: applyEtagHeaders(new Headers, etag)
12137
+ });
12138
+ }
12139
+ function applyConditionalGet(request, response, etag) {
12140
+ if (!isEtagEnabled()) {
12141
+ return response;
12142
12142
  }
12143
- try {
12144
- return new URL(configured, "http://strata.invalid").pathname;
12145
- } catch {
12146
- return "/auth/saml/acs";
12143
+ if (ifNoneMatchSatisfied(request, etag)) {
12144
+ return notModifiedResponse(etag);
12147
12145
  }
12146
+ const headers = applyEtagHeaders(new Headers(response.headers), etag);
12147
+ return new Response(response.body, {
12148
+ status: response.status,
12149
+ statusText: response.statusText,
12150
+ headers
12151
+ });
12148
12152
  }
12149
- function skipsCsrfPath(pathname) {
12150
- return pathname === samlAcsPathname() || pathname.startsWith("/scim/") || pathname.startsWith("/billing/webhooks/");
12153
+
12154
+ // ../../src/core/http/conditionalResponse.ts
12155
+ function jsonResponse2(data, init = {}) {
12156
+ return Response.json(data, {
12157
+ status: init.status ?? 200,
12158
+ headers: init.headers
12159
+ });
12151
12160
  }
12152
- function appendSetCookie(response, cookie) {
12161
+ function conditionalJsonResponse(request, data, init = {}) {
12162
+ if (!request || !isEtagEnabled()) {
12163
+ return jsonResponse2(data, init);
12164
+ }
12165
+ const etag = computeEtagFromJson(data);
12166
+ if (ifNoneMatchSatisfied(request, etag)) {
12167
+ return notModifiedResponse(etag);
12168
+ }
12169
+ const response = jsonResponse2(data, init);
12153
12170
  const headers = new Headers(response.headers);
12154
- headers.append("set-cookie", cookie);
12171
+ headers.set("ETag", etag);
12172
+ headers.set("Cache-Control", "private, must-revalidate");
12173
+ headers.append("Vary", "Authorization");
12174
+ headers.append("Vary", "X-Tenant-Id");
12155
12175
  return new Response(response.body, {
12156
12176
  status: response.status,
12157
12177
  statusText: response.statusText,
12158
12178
  headers
12159
12179
  });
12160
12180
  }
12161
- function createCsrfMiddleware() {
12162
- return async (request, next) => {
12163
- const credentialSource = currentCredentialSource();
12164
- if (credentialSource === "bearer" || credentialSource === "basic") {
12165
- return await next();
12166
- }
12167
- const pathname = new URL(request.url).pathname;
12168
- if (skipsCsrfPath(pathname)) {
12169
- return await next();
12170
- }
12171
- const method = request.method.toUpperCase();
12172
- if (!MUTATING_METHODS.has(method)) {
12173
- const meta = currentRequestMeta();
12174
- const csrf = meta.csrfToken ? { token: meta.csrfToken } : resolveCsrfToken(request);
12175
- meta.csrfToken = csrf.token;
12176
- const response = await next();
12177
- if (!csrf.cookie) {
12178
- return response;
12179
- }
12180
- return appendSetCookie(response, csrf.cookie);
12181
- }
12182
- const submitted = await readSubmittedCsrfTokenFromBody(request);
12183
- if (!verifyCsrfToken(request, submitted)) {
12184
- throw new ForbiddenError("Invalid or missing CSRF token.");
12185
- }
12186
- const originHeader = request.headers.get("origin");
12187
- let headerOrigin = null;
12188
- if (originHeader) {
12189
- try {
12190
- headerOrigin = new URL(originHeader).origin;
12191
- } catch {
12192
- headerOrigin = null;
12193
- }
12194
- }
12195
- if (!headerOrigin || headerOrigin !== new URL(request.url).origin) {
12196
- throw new ForbiddenError("Cross-site cookie requests are not allowed.");
12197
- }
12198
- return await next();
12199
- };
12200
- }
12201
- // ../../src/core/http/csrfProtection.ts
12202
- var DEFAULT_CSRF_TTL_MS = 60 * 60 * 1000;
12203
- function createCsrfProtection(secret, options = {}) {
12204
- const expiresIn = options.expiresIn ?? DEFAULT_CSRF_TTL_MS;
12205
- const maxAge = options.maxAge ?? expiresIn;
12206
- return {
12207
- generate(_sessionKey) {
12208
- return Bun.CSRF.generate(secret, { expiresIn });
12209
- },
12210
- verify(token, _sessionKey) {
12211
- if (!token) {
12212
- return false;
12213
- }
12214
- return Bun.CSRF.verify(token, { secret, maxAge });
12215
- },
12216
- secret
12217
- };
12181
+ // ../../src/core/http/contentSecurityPolicy.ts
12182
+ var HTMX_2_0_4_INDICATOR_STYLE_HASH = "'sha256-bsV5JivYxvGywDAZ22EZJKBFip65Ng9xoJVLbBg7bdo='";
12183
+ var API_DIRECTIVES = {
12184
+ "default-src": ["'none'"],
12185
+ "frame-ancestors": ["'none'"],
12186
+ "base-uri": ["'none'"]
12187
+ };
12188
+ var HTMX_HTML_DIRECTIVES = {
12189
+ "default-src": ["'self'"],
12190
+ "script-src": ["'self'"],
12191
+ "style-src": ["'self'", HTMX_2_0_4_INDICATOR_STYLE_HASH],
12192
+ "connect-src": ["'self'"],
12193
+ "img-src": ["'self'", "data:", "https:"],
12194
+ "font-src": ["'self'"],
12195
+ "media-src": ["'self'", "https:"],
12196
+ "frame-src": [
12197
+ "https://www.youtube.com",
12198
+ "https://www.youtube-nocookie.com",
12199
+ "https://player.vimeo.com"
12200
+ ],
12201
+ "form-action": ["'self'"],
12202
+ "frame-ancestors": ["'none'"],
12203
+ "base-uri": ["'self'"]
12204
+ };
12205
+ var SPA_HTML_DIRECTIVES = {
12206
+ "default-src": ["'self'"],
12207
+ "script-src": ["'self'"],
12208
+ "style-src": ["'self'"],
12209
+ "connect-src": ["'self'"],
12210
+ "img-src": ["'self'", "data:", "https:"],
12211
+ "font-src": ["'self'"],
12212
+ "frame-ancestors": ["'none'"],
12213
+ "base-uri": ["'self'"]
12214
+ };
12215
+ var configuredHtmlOptions = {};
12216
+ function generateCspNonce() {
12217
+ const bytes = new Uint8Array(16);
12218
+ crypto.getRandomValues(bytes);
12219
+ return Buffer.from(bytes).toString("base64");
12218
12220
  }
12219
- // ../../src/core/http/flashSession.ts
12220
- import { createHmac as createHmac5, timingSafeEqual as timingSafeEqual4 } from "crypto";
12221
- var FLASH_COOKIE = appCookieName("flash");
12222
- var FLASH_TTL_MS = 60 * 1000;
12223
- function flashCookieName() {
12224
- return process.env.FLASH_COOKIE_NAME?.trim() || appCookieName("flash");
12221
+ function configureContentSecurityPolicy(options) {
12222
+ configuredHtmlOptions = { ...options };
12225
12223
  }
12226
- function resolveFlashSecret() {
12227
- return requireConfiguredSecret(["SESSION_SECRET", "OAUTH_STATE_SECRET"], "flash-secret");
12224
+ function resetContentSecurityPolicyForTests() {
12225
+ configuredHtmlOptions = {};
12228
12226
  }
12229
- function signFlashPayload(payload, issuedAt) {
12230
- const signature = createHmac5("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
12231
- return `${payload}.${issuedAt}.${signature}`;
12227
+ function cloneDirectives(source) {
12228
+ const copy = {};
12229
+ for (const [directive, values] of Object.entries(source)) {
12230
+ copy[directive] = [...values];
12231
+ }
12232
+ return copy;
12232
12233
  }
12233
- function readFlashCookie(request) {
12234
- const cookieHeader = request.headers.get("cookie");
12235
- if (!cookieHeader) {
12236
- return null;
12234
+ function normalizeSources(value) {
12235
+ if (Array.isArray(value)) {
12236
+ return value.flatMap((item) => item.split(/\s+/).filter(Boolean));
12237
12237
  }
12238
- for (const part of cookieHeader.split(";")) {
12239
- const [name, ...rest] = part.trim().split("=");
12240
- if (name === flashCookieName()) {
12241
- return decodeURIComponent(rest.join("="));
12238
+ return value.split(/\s+/).filter(Boolean);
12239
+ }
12240
+ function mergeDirectives(base, extra) {
12241
+ const merged = cloneDirectives(base);
12242
+ for (const [directive, value] of Object.entries(extra ?? {})) {
12243
+ if (value === false) {
12244
+ delete merged[directive];
12245
+ continue;
12242
12246
  }
12247
+ const sources = normalizeSources(value);
12248
+ const existing = merged[directive] ?? [];
12249
+ merged[directive] = [...existing, ...sources.filter((source) => !existing.includes(source))];
12243
12250
  }
12244
- return null;
12251
+ return merged;
12245
12252
  }
12246
- function parseFlashCookie(cookieValue) {
12247
- const parts = cookieValue.split(".");
12248
- if (parts.length < 3) {
12249
- return null;
12250
- }
12251
- const signature = parts.pop();
12252
- const issuedAtRaw = parts.pop();
12253
- const payload = parts.join(".");
12254
- if (!signature || !issuedAtRaw || !payload) {
12255
- return null;
12256
- }
12257
- const issuedAt = Number.parseInt(issuedAtRaw, 10);
12258
- if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
12259
- return null;
12253
+ function serializeDirectives(directives) {
12254
+ return Object.entries(directives).map(([directive, values]) => values.length > 0 ? `${directive} ${values.join(" ")}` : directive).join("; ");
12255
+ }
12256
+ function applyNonce(directives, nonce) {
12257
+ if (!nonce) {
12258
+ return directives;
12260
12259
  }
12261
- const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
12262
- if (!expectedSignature) {
12263
- return null;
12260
+ const token = `'nonce-${nonce}'`;
12261
+ const next = cloneDirectives(directives);
12262
+ for (const directive of ["script-src", "style-src"]) {
12263
+ const values = next[directive] ?? ["'self'"];
12264
+ if (!values.includes(token)) {
12265
+ next[directive] = [...values, token];
12266
+ }
12264
12267
  }
12265
- const expectedBuffer = Buffer.from(expectedSignature);
12266
- const actualBuffer = Buffer.from(signature);
12267
- if (expectedBuffer.length !== actualBuffer.length) {
12268
- return null;
12268
+ return next;
12269
+ }
12270
+ function htmlBaselineDirectives() {
12271
+ if (isViewsEnabled()) {
12272
+ return cloneDirectives(HTMX_HTML_DIRECTIVES);
12269
12273
  }
12270
- if (!timingSafeEqual4(expectedBuffer, actualBuffer)) {
12271
- return null;
12274
+ if (isSpaEnabled()) {
12275
+ return cloneDirectives(SPA_HTML_DIRECTIVES);
12272
12276
  }
12273
- try {
12274
- const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
12275
- if (!parsed?.message || typeof parsed.message !== "string") {
12276
- return null;
12277
- }
12278
- if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
12279
- return null;
12277
+ return cloneDirectives(API_DIRECTIVES);
12278
+ }
12279
+ function strictApiContentSecurityPolicy() {
12280
+ return serializeDirectives(API_DIRECTIVES);
12281
+ }
12282
+ function serverHtmxContentSecurityPolicy(nonce) {
12283
+ return serializeDirectives(applyNonce(cloneDirectives(HTMX_HTML_DIRECTIVES), nonce));
12284
+ }
12285
+ function spaContentSecurityPolicy(nonce) {
12286
+ return serializeDirectives(applyNonce(cloneDirectives(SPA_HTML_DIRECTIVES), nonce));
12287
+ }
12288
+ function resolveHtmlContentSecurityPolicy(options = {}) {
12289
+ const resolved = {
12290
+ ...configuredHtmlOptions,
12291
+ ...options,
12292
+ directives: {
12293
+ ...configuredHtmlOptions.directives,
12294
+ ...options.directives
12280
12295
  }
12281
- return parsed;
12282
- } catch {
12283
- return null;
12296
+ };
12297
+ const override = resolved.htmlCsp ?? resolved.csp;
12298
+ if (override) {
12299
+ return override;
12284
12300
  }
12301
+ return serializeDirectives(applyNonce(mergeDirectives(htmlBaselineDirectives(), resolved.directives), options.nonce));
12285
12302
  }
12286
- function clearFlashCookie() {
12287
- const secure = isProductionEnv() ? "; Secure" : "";
12288
- return `${flashCookieName()}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure}`;
12289
- }
12290
- function pullFlash(request) {
12291
- const cookieValue = readFlashCookie(request);
12292
- if (!cookieValue) {
12293
- return null;
12303
+ function resolveContentSecurityPolicy(response, options = {}) {
12304
+ const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
12305
+ if (!contentType.includes("text/html")) {
12306
+ return strictApiContentSecurityPolicy();
12294
12307
  }
12295
- return parseFlashCookie(cookieValue);
12308
+ return resolveHtmlContentSecurityPolicy(options);
12296
12309
  }
12297
- function withFlashClear(response) {
12298
- const headers = new Headers(response.headers);
12299
- headers.append("set-cookie", clearFlashCookie());
12300
- return new Response(response.body, {
12301
- status: response.status,
12302
- statusText: response.statusText,
12303
- headers
12310
+ // ../../src/core/http/corsMiddleware.ts
12311
+ function additionalHeaders(options) {
12312
+ const configured = process.env.CORS_ADDITIONAL_ALLOWED_HEADERS?.trim();
12313
+ const supplied = options.additionalAllowedHeaders === undefined ? [] : options.additionalAllowedHeaders;
12314
+ if (!Array.isArray(supplied)) {
12315
+ throw new TypeError("CORS additionalAllowedHeaders must be an array of header names.");
12316
+ }
12317
+ const names = [
12318
+ ...configured ? configured.split(",").map((name) => name.trim()) : [],
12319
+ ...supplied
12320
+ ];
12321
+ return names.map((name) => {
12322
+ if (typeof name !== "string" || name === "*" || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) {
12323
+ throw new TypeError("CORS additional headers must be explicit valid HTTP header names; wildcards are not allowed.");
12324
+ }
12325
+ return name;
12304
12326
  });
12305
12327
  }
12306
-
12307
- // ../../src/core/http/flashMiddleware.ts
12308
- function createFlashMiddleware() {
12328
+ function defaultAllowedOrigins() {
12329
+ return appUrl();
12330
+ }
12331
+ function resolveCorsConfig(options = {}) {
12332
+ const extraHeaders = additionalHeaders(options);
12333
+ return {
12334
+ allowedOrigins: (process.env.CORS_ALLOWED_ORIGINS ?? defaultAllowedOrigins()).split(",").map((origin) => origin.trim()).filter(Boolean),
12335
+ allowedMethods: ["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"],
12336
+ allowedHeaders: [
12337
+ "Authorization",
12338
+ "Content-Type",
12339
+ "X-Request-Id",
12340
+ "X-Tenant-Id",
12341
+ "X-Authenticated-User-Id",
12342
+ "X-Authenticated-User-Role",
12343
+ "If-Match",
12344
+ "If-None-Match",
12345
+ "X-CSRF-Token",
12346
+ ...extraHeaders
12347
+ ].filter((name, index, names) => names.findIndex((other) => other.toLowerCase() === name.toLowerCase()) === index),
12348
+ maxAgeSeconds: 86400
12349
+ };
12350
+ }
12351
+ function createCorsMiddleware(options = {}) {
12352
+ resolveCorsConfig(options);
12353
+ const captured = {
12354
+ additionalAllowedHeaders: [...options.additionalAllowedHeaders ?? []]
12355
+ };
12309
12356
  return async (request, next) => {
12310
- const flash = pullFlash(request);
12311
- const meta = currentRequestMeta();
12312
- return await runWithRequestMeta({ ...meta, request, flash }, async () => {
12313
- const response = await next();
12314
- if (flash) {
12315
- return withFlashClear(response);
12357
+ if (request.method === "OPTIONS") {
12358
+ return new Response(null, {
12359
+ status: 204,
12360
+ headers: buildCorsHeaders(request, captured)
12361
+ });
12362
+ }
12363
+ const response = await next();
12364
+ const headers = new Headers(response.headers);
12365
+ for (const [key, value] of buildCorsHeaders(request, captured)) {
12366
+ if (key === "vary") {
12367
+ const fields = (headers.get("Vary") ?? "").split(",").map((field) => field.trim()).filter(Boolean);
12368
+ if (fields.includes("*"))
12369
+ continue;
12370
+ if (!fields.some((field) => field.toLowerCase() === "origin"))
12371
+ fields.push(value);
12372
+ headers.set("Vary", fields.join(", "));
12373
+ } else {
12374
+ headers.set(key, value);
12316
12375
  }
12317
- return response;
12376
+ }
12377
+ return new Response(response.body, {
12378
+ status: response.status,
12379
+ statusText: response.statusText,
12380
+ headers
12318
12381
  });
12319
12382
  };
12320
12383
  }
12321
- // ../../src/core/http/validation.ts
12322
- init_tenantContext();
12323
- function buildRequestCacheKey(fallbackPath, request) {
12324
- if (!request) {
12325
- return fallbackPath;
12384
+ function buildCorsHeaders(request, options) {
12385
+ const headers = new Headers;
12386
+ const origin = request.headers.get("origin");
12387
+ const corsConfig = resolveCorsConfig(options);
12388
+ const allowedOrigins = corsConfig.allowedOrigins;
12389
+ headers.set("Vary", "Origin");
12390
+ const allowOrigin = allowedOrigins.includes("*") ? "*" : origin && allowedOrigins.includes(origin) ? origin : null;
12391
+ if (!allowOrigin) {
12392
+ return headers;
12326
12393
  }
12327
- const url = new URL(request.url);
12328
- const user = currentAuthUser();
12329
- const authScope = user ? `u:${user.id}` : "guest";
12330
- const tenantScope = `t:${currentTenant()?.id ?? "none"}`;
12331
- return `${authScope}|${tenantScope}|${url.pathname}${url.search}`;
12332
- }
12333
- function getQueryParams(request) {
12334
- if (!request) {
12335
- return new URLSearchParams;
12394
+ headers.set("Access-Control-Allow-Origin", allowOrigin);
12395
+ headers.set("Access-Control-Allow-Methods", corsConfig.allowedMethods.join(", "));
12396
+ headers.set("Access-Control-Allow-Headers", corsConfig.allowedHeaders.join(", "));
12397
+ headers.set("Access-Control-Max-Age", String(corsConfig.maxAgeSeconds));
12398
+ if (allowOrigin !== "*") {
12399
+ headers.set("Access-Control-Allow-Credentials", "true");
12336
12400
  }
12337
- return new URL(request.url).searchParams;
12401
+ return headers;
12338
12402
  }
12339
- function parseOptionalPositiveIntQueryParam(params, name) {
12340
- const value = params.get(name);
12341
- if (value === null || value.trim() === "") {
12342
- return;
12343
- }
12344
- const parsed = Number.parseInt(value, 10);
12345
- if (!Number.isInteger(parsed) || parsed <= 0) {
12346
- throw new BadRequestError(`Invalid query parameter "${name}". Expected a positive integer.`);
12347
- }
12348
- return parsed;
12403
+ // ../../src/core/http/csrfToken.ts
12404
+ import { timingSafeEqual as timingSafeEqual3 } from "crypto";
12405
+ var CSRF_COOKIE = appCookieName("csrf");
12406
+ var CSRF_TTL_MS = 60 * 60 * 1000;
12407
+ function csrfCookieName() {
12408
+ return process.env.CSRF_COOKIE_NAME?.trim() || appCookieName("csrf");
12349
12409
  }
12350
- function parseOptionalBooleanQueryParam(params, name) {
12351
- const value = params.get(name);
12352
- if (value === null || value.trim() === "") {
12353
- return;
12354
- }
12355
- switch (value.toLowerCase()) {
12356
- case "true":
12357
- case "1":
12358
- return true;
12359
- case "false":
12360
- case "0":
12361
- return false;
12362
- default:
12363
- throw new BadRequestError(`Invalid query parameter "${name}". Expected a boolean.`);
12364
- }
12410
+ function resolveCsrfSecret() {
12411
+ return requireConfiguredSecret(["SESSION_SECRET", "CSRF_SECRET"], "csrf-secret");
12365
12412
  }
12366
- function parseOptionalEnumQueryParam(params, name, allowedValues) {
12367
- const value = params.get(name);
12368
- if (value === null || value.trim() === "") {
12369
- return;
12370
- }
12371
- if (!allowedValues.includes(value)) {
12372
- throw new BadRequestError(`Invalid query parameter "${name}". Expected one of: ${allowedValues.join(", ")}.`);
12373
- }
12374
- return value;
12413
+ function csrfVerifyOptions() {
12414
+ return { secret: resolveCsrfSecret(), maxAge: CSRF_TTL_MS };
12375
12415
  }
12376
- function expectObject(value, label = "request body") {
12377
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
12378
- throw new BadRequestError(`${label} must be a JSON object.`);
12416
+ function tokensMatch(left, right) {
12417
+ const leftBuffer = Buffer.from(left);
12418
+ const rightBuffer = Buffer.from(right);
12419
+ if (leftBuffer.length !== rightBuffer.length) {
12420
+ return false;
12379
12421
  }
12380
- return value;
12422
+ return timingSafeEqual3(leftBuffer, rightBuffer);
12381
12423
  }
12382
- async function parseJsonBody(request, validator) {
12383
- let payload;
12384
- try {
12385
- payload = await request.json();
12386
- } catch {
12387
- throw new BadRequestError("Request body must be valid JSON.");
12388
- }
12389
- return validator(payload);
12424
+ function createCsrfTokenCookie() {
12425
+ const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
12426
+ const secure = isProductionEnv() ? "; Secure" : "";
12427
+ return {
12428
+ token,
12429
+ cookie: `${csrfCookieName()}=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}${secure}`
12430
+ };
12390
12431
  }
12391
- function readRequiredString(payload, field, options = {}) {
12392
- const value = payload[field];
12393
- if (typeof value !== "string" || value.trim() === "") {
12394
- throw new BadRequestError(`"${field}" is required and must be a string.`);
12395
- }
12396
- const trimmed = value.trim();
12397
- if (options.minLength !== undefined && trimmed.length < options.minLength) {
12398
- throw new BadRequestError(`"${field}" must be at least ${options.minLength} characters.`);
12399
- }
12400
- if (options.maxLength !== undefined && trimmed.length > options.maxLength) {
12401
- throw new BadRequestError(`"${field}" must be at most ${options.maxLength} characters.`);
12402
- }
12403
- if (options.pattern && !options.pattern.test(trimmed)) {
12404
- throw new BadRequestError(`"${field}" has an invalid format.`);
12432
+ function resolveCsrfToken(request) {
12433
+ const cookieValue = readRequestCookie(request, csrfCookieName());
12434
+ if (cookieValue && Bun.CSRF.verify(cookieValue, csrfVerifyOptions())) {
12435
+ return { token: cookieValue };
12405
12436
  }
12406
- return trimmed;
12437
+ return createCsrfTokenCookie();
12407
12438
  }
12408
- function readOptionalString(payload, field, options = {}) {
12409
- if (!(field in payload) || payload[field] === undefined) {
12410
- return;
12439
+ function readSubmittedCsrfToken(request) {
12440
+ const headerToken = request.headers.get("x-csrf-token")?.trim();
12441
+ if (headerToken) {
12442
+ return headerToken;
12411
12443
  }
12412
- return readRequiredString(payload, field, options);
12444
+ return null;
12413
12445
  }
12414
- function readRequiredEnum(payload, field, allowedValues) {
12415
- const value = readRequiredString(payload, field);
12416
- if (!allowedValues.includes(value)) {
12417
- throw new BadRequestError(`"${field}" must be one of: ${allowedValues.join(", ")}.`);
12446
+ async function readSubmittedCsrfTokenFromBody(request) {
12447
+ const headerToken = readSubmittedCsrfToken(request);
12448
+ if (headerToken) {
12449
+ return headerToken;
12418
12450
  }
12419
- return value;
12420
- }
12421
- function readOptionalEnum(payload, field, allowedValues) {
12422
- if (!(field in payload) || payload[field] === undefined) {
12423
- return;
12451
+ const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
12452
+ if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
12453
+ const formData = await request.clone().formData();
12454
+ const field = formData.get("_token");
12455
+ if (typeof field === "string" && field.trim().length > 0) {
12456
+ return field.trim();
12457
+ }
12458
+ const legacyField = formData.get("_csrf");
12459
+ if (typeof legacyField === "string" && legacyField.trim().length > 0) {
12460
+ return legacyField.trim();
12461
+ }
12424
12462
  }
12425
- return readRequiredEnum(payload, field, allowedValues);
12463
+ return null;
12426
12464
  }
12427
- function readRequiredPositiveInt(payload, field) {
12428
- const value = payload[field];
12429
- if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
12430
- throw new BadRequestError(`"${field}" is required and must be a positive integer.`);
12465
+ function verifyCsrfToken(request, submittedToken) {
12466
+ if (!submittedToken) {
12467
+ return false;
12431
12468
  }
12432
- return value;
12433
- }
12434
- function readOptionalPositiveInt(payload, field) {
12435
- if (!(field in payload) || payload[field] === undefined) {
12436
- return;
12469
+ const cookieValue = readRequestCookie(request, csrfCookieName());
12470
+ if (!cookieValue) {
12471
+ return false;
12437
12472
  }
12438
- return readRequiredPositiveInt(payload, field);
12439
- }
12440
- function parsePositiveIntParam(value, name = "id") {
12441
- const parsed = Number.parseInt(value, 10);
12442
- if (!Number.isInteger(parsed) || parsed <= 0) {
12443
- throw new BadRequestError(`Invalid ${name}. Expected a positive integer.`);
12473
+ if (!tokensMatch(submittedToken, cookieValue)) {
12474
+ return false;
12444
12475
  }
12445
- return parsed;
12476
+ return Bun.CSRF.verify(submittedToken, csrfVerifyOptions());
12446
12477
  }
12447
-
12448
- // ../../src/core/http/formRequest.ts
12449
- class FormRequest {
12450
- authorize(_request) {
12451
- return true;
12452
- }
12453
- async validate(request) {
12454
- if (!await this.authorize(request)) {
12455
- throw new ForbiddenError;
12456
- }
12457
- return await parseJsonBody(request, (payload) => this.parse(payload));
12478
+ function resolveCsrfTokenForRequest(request) {
12479
+ const metaToken = currentRequestMeta().csrfToken;
12480
+ if (metaToken) {
12481
+ return metaToken;
12458
12482
  }
12483
+ return resolveCsrfToken(request).token;
12459
12484
  }
12460
12485
 
12461
- class QueryFormRequest {
12462
- validate(request) {
12463
- return this.parseQuery(request);
12486
+ // ../../src/core/http/csrfMiddleware.ts
12487
+ var MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
12488
+ function samlAcsPathname() {
12489
+ const configured = process.env.SAML_ACS_URL?.trim();
12490
+ if (!configured) {
12491
+ return "/auth/saml/acs";
12464
12492
  }
12465
- }
12466
- // ../../src/core/http/authMiddleware.ts
12467
- function createAuthMiddleware(auth) {
12468
- return async (request, next) => {
12469
- const resolved = typeof auth.resolveWithSource === "function" ? await auth.resolveWithSource(request) : { user: await auth.resolve(request), credentialSource: null };
12470
- return await runWithAuthContext(resolved.user, resolved.credentialSource, async () => {
12471
- return await next();
12472
- });
12473
- };
12474
- }
12475
- // ../../src/core/http/authorizeMiddleware.ts
12476
- function createAuthorizeMiddleware(gate, auth, resource, action) {
12477
- return async (request, next) => {
12478
- const user = currentAuthUser() ?? await auth.resolve(request);
12479
- if (!gate.allows(resource, action, user)) {
12480
- const error = new ForbiddenError;
12481
- return Response.json({ error: error.message }, { status: error.status });
12482
- }
12483
- return await next();
12484
- };
12485
- }
12486
- // ../../src/core/http/middleware.ts
12487
- function isRouteHandler(value) {
12488
- return typeof value === "function";
12489
- }
12490
- function isMethodRouteMap(value) {
12491
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
12492
- return false;
12493
+ try {
12494
+ return new URL(configured, "http://strata.invalid").pathname;
12495
+ } catch {
12496
+ return "/auth/saml/acs";
12493
12497
  }
12494
- const entries = Object.entries(value);
12495
- return entries.length > 0 && entries.every(([, handler]) => isRouteHandler(handler));
12496
12498
  }
12497
- function composeMiddleware(...middleware) {
12498
- return (handler) => {
12499
- return async (request) => {
12500
- let index = 0;
12501
- const dispatch = async () => {
12502
- if (index >= middleware.length) {
12503
- return await handler(request);
12504
- }
12505
- const current = middleware[index];
12506
- index += 1;
12507
- if (!current) {
12508
- return await handler(request);
12509
- }
12510
- return await current(request, dispatch);
12511
- };
12512
- return await dispatch();
12513
- };
12514
- };
12499
+ function skipsCsrfPath(pathname) {
12500
+ return pathname === samlAcsPathname() || pathname.startsWith("/scim/") || pathname.startsWith("/billing/webhooks/");
12515
12501
  }
12516
- async function requestIdMiddleware(request, next) {
12517
- const requestId = request.headers.get("x-request-id") ?? crypto.randomUUID();
12518
- const response = await next();
12502
+ function appendSetCookie(response, cookie) {
12519
12503
  const headers = new Headers(response.headers);
12520
- headers.set("x-request-id", requestId);
12504
+ headers.append("set-cookie", cookie);
12521
12505
  return new Response(response.body, {
12522
12506
  status: response.status,
12523
12507
  statusText: response.statusText,
12524
12508
  headers
12525
12509
  });
12526
12510
  }
12527
- function wrapRouteHandler(handler, middleware) {
12528
- if (isMethodRouteMap(handler)) {
12529
- const wrapped = {};
12530
- for (const [method, routeHandler] of Object.entries(handler)) {
12531
- wrapped[method] = composeMiddleware(...middleware)(routeHandler);
12511
+ function createCsrfMiddleware() {
12512
+ return async (request, next) => {
12513
+ const credentialSource = currentCredentialSource();
12514
+ if (credentialSource === "bearer" || credentialSource === "basic") {
12515
+ return await next();
12532
12516
  }
12533
- return wrapped;
12534
- }
12535
- if (isRouteHandler(handler)) {
12536
- return composeMiddleware(...middleware)(handler);
12537
- }
12538
- return handler;
12517
+ const pathname = new URL(request.url).pathname;
12518
+ if (skipsCsrfPath(pathname)) {
12519
+ return await next();
12520
+ }
12521
+ const method = request.method.toUpperCase();
12522
+ if (!MUTATING_METHODS.has(method)) {
12523
+ const meta = currentRequestMeta();
12524
+ const csrf = meta.csrfToken ? { token: meta.csrfToken } : resolveCsrfToken(request);
12525
+ meta.csrfToken = csrf.token;
12526
+ const response = await next();
12527
+ if (!csrf.cookie) {
12528
+ return response;
12529
+ }
12530
+ return appendSetCookie(response, csrf.cookie);
12531
+ }
12532
+ const submitted = await readSubmittedCsrfTokenFromBody(request);
12533
+ if (!verifyCsrfToken(request, submitted)) {
12534
+ throw new ForbiddenError("Invalid or missing CSRF token.");
12535
+ }
12536
+ const originHeader = request.headers.get("origin");
12537
+ let headerOrigin = null;
12538
+ if (originHeader) {
12539
+ try {
12540
+ headerOrigin = new URL(originHeader).origin;
12541
+ } catch {
12542
+ headerOrigin = null;
12543
+ }
12544
+ }
12545
+ if (!headerOrigin || headerOrigin !== new URL(request.url).origin) {
12546
+ throw new ForbiddenError("Cross-site cookie requests are not allowed.");
12547
+ }
12548
+ return await next();
12549
+ };
12539
12550
  }
12540
- function applyMiddlewareToRoutes(routes, middleware) {
12541
- const wrapped = {};
12542
- for (const [path, routeHandler] of Object.entries(routes)) {
12543
- const identity = async (_request, next) => await runWithRequestMeta({ ...currentRequestMeta(), routeTemplate: path }, next);
12544
- wrapped[path] = wrapRouteHandler(routeHandler, [identity, ...middleware]);
12545
- }
12546
- return wrapped;
12551
+ // ../../src/core/http/csrfProtection.ts
12552
+ var DEFAULT_CSRF_TTL_MS = 60 * 60 * 1000;
12553
+ function createCsrfProtection(secret, options = {}) {
12554
+ const expiresIn = options.expiresIn ?? DEFAULT_CSRF_TTL_MS;
12555
+ const maxAge = options.maxAge ?? expiresIn;
12556
+ return {
12557
+ generate(_sessionKey) {
12558
+ return Bun.CSRF.generate(secret, { expiresIn });
12559
+ },
12560
+ verify(token, _sessionKey) {
12561
+ if (!token) {
12562
+ return false;
12563
+ }
12564
+ return Bun.CSRF.verify(token, { secret, maxAge });
12565
+ },
12566
+ secret
12567
+ };
12547
12568
  }
12548
- // ../../src/core/http/pagination.ts
12549
- var DEFAULT_PER_PAGE = 15;
12550
- var MAX_PER_PAGE = 100;
12551
- function parseRequiredPositiveIntQueryParam(params, name) {
12552
- const value = params.get(name);
12553
- if (value === null || value.trim() === "") {
12554
- throw new BadRequestError(`Invalid query parameter "${name}". Expected a positive integer.`);
12555
- }
12556
- const parsed = Number.parseInt(value, 10);
12557
- if (!Number.isInteger(parsed) || parsed <= 0) {
12558
- throw new BadRequestError(`Invalid query parameter "${name}". Expected a positive integer.`);
12559
- }
12560
- return parsed;
12569
+ // ../../src/core/http/flashSession.ts
12570
+ import { createHmac as createHmac5, timingSafeEqual as timingSafeEqual4 } from "crypto";
12571
+ var FLASH_COOKIE = appCookieName("flash");
12572
+ var FLASH_TTL_MS = 60 * 1000;
12573
+ function flashCookieName() {
12574
+ return process.env.FLASH_COOKIE_NAME?.trim() || appCookieName("flash");
12561
12575
  }
12562
- function parsePaginationQuery(request) {
12563
- const params = getQueryParams(request);
12564
- const pageParam = params.get("page");
12565
- const perPageParam = params.get("per_page");
12566
- const page = pageParam === null || pageParam.trim() === "" ? 1 : parseRequiredPositiveIntQueryParam(params, "page");
12567
- if (perPageParam === null || perPageParam.trim() === "") {
12568
- return { page, perPage: DEFAULT_PER_PAGE };
12569
- }
12570
- const perPage = parseRequiredPositiveIntQueryParam(params, "per_page");
12571
- if (perPage > MAX_PER_PAGE) {
12572
- throw new BadRequestError(`Invalid query parameter "per_page". Maximum allowed value is ${MAX_PER_PAGE}.`);
12573
- }
12574
- return { page, perPage };
12576
+ function resolveFlashSecret() {
12577
+ return requireConfiguredSecret(["SESSION_SECRET", "OAUTH_STATE_SECRET"], "flash-secret");
12575
12578
  }
12576
- function paginatedResponse(data, meta, init = {}) {
12577
- return Response.json({ data, meta }, init);
12579
+ function signFlashPayload(payload, issuedAt) {
12580
+ const signature = createHmac5("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
12581
+ return `${payload}.${issuedAt}.${signature}`;
12578
12582
  }
12579
- // ../../src/core/http/uploads.ts
12580
- var DEFAULT_MAX_UPLOAD_BYTES = 5 * 1024 * 1024;
12581
- var ALLOWED_UPLOAD_MIME_TYPES = new Set([
12582
- "application/pdf",
12583
- "application/json",
12584
- "application/zip",
12585
- "application/x-zip-compressed",
12586
- "image/jpeg",
12587
- "image/png",
12588
- "image/gif",
12589
- "image/webp",
12590
- "text/plain",
12591
- "text/csv"
12592
- ]);
12593
- function resolveMaxUploadBytes() {
12594
- const raw = process.env.MAX_UPLOAD_BYTES?.trim() ?? process.env.MAX_REQUEST_BODY_BYTES?.trim();
12595
- if (!raw) {
12596
- return DEFAULT_MAX_UPLOAD_BYTES;
12597
- }
12598
- const parsed = Number.parseInt(raw, 10);
12599
- if (!Number.isInteger(parsed) || parsed <= 0) {
12600
- return DEFAULT_MAX_UPLOAD_BYTES;
12583
+ function readFlashCookie(request) {
12584
+ const cookieHeader = request.headers.get("cookie");
12585
+ if (!cookieHeader) {
12586
+ return null;
12601
12587
  }
12602
- return parsed;
12603
- }
12604
- function normalizeMimeType(mimeType) {
12605
- return mimeType.split(";")[0]?.trim().toLowerCase() ?? "";
12606
- }
12607
- function isAllowedMimeType(mimeType) {
12608
- const normalized = normalizeMimeType(mimeType);
12609
- if (!normalized || normalized === "application/octet-stream") {
12610
- return envFlagEnabled(process.env.UPLOAD_ALLOW_UNKNOWN_MIME);
12588
+ for (const part of cookieHeader.split(";")) {
12589
+ const [name, ...rest] = part.trim().split("=");
12590
+ if (name === flashCookieName()) {
12591
+ return decodeURIComponent(rest.join("="));
12592
+ }
12611
12593
  }
12612
- return ALLOWED_UPLOAD_MIME_TYPES.has(normalized);
12613
- }
12614
-
12615
- // ../../src/core/http/parseMultipartUpload.ts
12616
- function normalizeMimeType2(mimeType) {
12617
- return mimeType.split(";")[0]?.trim().toLowerCase() || "application/octet-stream";
12618
- }
12619
- function sanitizeUploadFileName(name) {
12620
- const base = name.split(/[/\\]/).pop()?.trim() ?? "upload";
12621
- const sanitized = base.replace(/[^\w.\-()+ ]+/g, "_").slice(0, 200);
12622
- return sanitized.length > 0 ? sanitized : "upload";
12594
+ return null;
12623
12595
  }
12624
- async function validateUploadFile(file, fieldName = "file") {
12625
- if (!(file instanceof File)) {
12626
- throw new BadRequestError(`Missing upload field "${fieldName}".`);
12596
+ function parseFlashCookie(cookieValue) {
12597
+ const parts = cookieValue.split(".");
12598
+ if (parts.length < 3) {
12599
+ return null;
12627
12600
  }
12628
- if (file.size <= 0) {
12629
- throw new BadRequestError("Uploaded file is empty.");
12601
+ const signature = parts.pop();
12602
+ const issuedAtRaw = parts.pop();
12603
+ const payload = parts.join(".");
12604
+ if (!signature || !issuedAtRaw || !payload) {
12605
+ return null;
12630
12606
  }
12631
- const maxBytes = resolveMaxUploadBytes();
12632
- if (file.size > maxBytes) {
12633
- throw new PayloadTooLargeError(`Upload exceeds the ${maxBytes} byte limit.`);
12607
+ const issuedAt = Number.parseInt(issuedAtRaw, 10);
12608
+ if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
12609
+ return null;
12634
12610
  }
12635
- const mimeType = normalizeMimeType2(file.type.trim() || "application/octet-stream");
12636
- if (!isAllowedMimeType(mimeType)) {
12637
- throw new BadRequestError(`File type "${mimeType}" is not allowed.`);
12611
+ const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
12612
+ if (!expectedSignature) {
12613
+ return null;
12638
12614
  }
12639
- return {
12640
- fileName: sanitizeUploadFileName(file.name),
12641
- mimeType,
12642
- size: file.size,
12643
- contents: new Uint8Array(await file.arrayBuffer())
12644
- };
12645
- }
12646
- async function parseMultipartUpload(request, fieldName = "file") {
12647
- const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
12648
- if (!contentType.includes("multipart/form-data")) {
12649
- throw new BadRequestError("Expected multipart form data.");
12615
+ const expectedBuffer = Buffer.from(expectedSignature);
12616
+ const actualBuffer = Buffer.from(signature);
12617
+ if (expectedBuffer.length !== actualBuffer.length) {
12618
+ return null;
12650
12619
  }
12651
- const formData = await request.formData();
12652
- const value = formData.get(fieldName);
12653
- if (!(value instanceof File)) {
12654
- throw new BadRequestError(`Missing upload field "${fieldName}".`);
12620
+ if (!timingSafeEqual4(expectedBuffer, actualBuffer)) {
12621
+ return null;
12655
12622
  }
12656
- return validateUploadFile(value, fieldName);
12657
- }
12658
- // ../../src/core/http/requireAuthMiddleware.ts
12659
- function createRequireAuthMiddleware(auth) {
12660
- return async (request, next) => {
12661
- if (!await auth.check(request)) {
12662
- const error = new UnauthorizedError;
12663
- return Response.json({ error: error.message }, { status: error.status });
12623
+ try {
12624
+ const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
12625
+ if (!parsed?.message || typeof parsed.message !== "string") {
12626
+ return null;
12664
12627
  }
12665
- return await next();
12666
- };
12628
+ if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
12629
+ return null;
12630
+ }
12631
+ return parsed;
12632
+ } catch {
12633
+ return null;
12634
+ }
12667
12635
  }
12668
- // ../../src/core/http/resources.ts
12669
- function serializeDate(value) {
12670
- return value instanceof Date ? value.toISOString() : value;
12636
+ function clearFlashCookie() {
12637
+ const secure = isProductionEnv() ? "; Secure" : "";
12638
+ return `${flashCookieName()}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure}`;
12671
12639
  }
12672
- function whenLoaded(model, relation, transform) {
12673
- const value = model.loaded(relation);
12674
- if (value === undefined) {
12675
- return;
12676
- }
12677
- if (value === null) {
12640
+ function pullFlash(request) {
12641
+ const cookieValue = readFlashCookie(request);
12642
+ if (!cookieValue) {
12678
12643
  return null;
12679
12644
  }
12680
- return transform ? transform(value) : value;
12645
+ return parseFlashCookie(cookieValue);
12646
+ }
12647
+ function withFlashClear(response) {
12648
+ const headers = new Headers(response.headers);
12649
+ headers.append("set-cookie", clearFlashCookie());
12650
+ return new Response(response.body, {
12651
+ status: response.status,
12652
+ statusText: response.statusText,
12653
+ headers
12654
+ });
12681
12655
  }
12682
12656
 
12683
- class JsonResource {
12684
- resource;
12685
- static wrap = "data";
12686
- extra = {};
12687
- constructor(resource) {
12688
- this.resource = resource;
12689
- }
12690
- static make(resource) {
12691
- return new JsonResource(resource);
12692
- }
12693
- static collection(items) {
12694
- return new ResourceCollection(items);
12657
+ // ../../src/core/http/flashMiddleware.ts
12658
+ function createFlashMiddleware() {
12659
+ return async (request, next) => {
12660
+ const flash = pullFlash(request);
12661
+ const meta = currentRequestMeta();
12662
+ return await runWithRequestMeta({ ...meta, request, flash }, async () => {
12663
+ const response = await next();
12664
+ if (flash) {
12665
+ return withFlashClear(response);
12666
+ }
12667
+ return response;
12668
+ });
12669
+ };
12670
+ }
12671
+ // ../../src/core/http/validation.ts
12672
+ init_tenantContext();
12673
+ function buildRequestCacheKey(fallbackPath, request) {
12674
+ if (!request) {
12675
+ return fallbackPath;
12695
12676
  }
12696
- additional(data) {
12697
- this.extra = { ...this.extra, ...data };
12698
- return this;
12677
+ const url = new URL(request.url);
12678
+ const user = currentAuthUser();
12679
+ const authScope = user ? `u:${user.id}` : "guest";
12680
+ const tenantScope = `t:${currentTenant()?.id ?? "none"}`;
12681
+ return `${authScope}|${tenantScope}|${url.pathname}${url.search}`;
12682
+ }
12683
+ function getQueryParams(request) {
12684
+ if (!request) {
12685
+ return new URLSearchParams;
12699
12686
  }
12700
- when(condition, value) {
12701
- return condition ? value : undefined;
12687
+ return new URL(request.url).searchParams;
12688
+ }
12689
+ function parseOptionalPositiveIntQueryParam(params, name) {
12690
+ const value = params.get(name);
12691
+ if (value === null || value.trim() === "") {
12692
+ return;
12702
12693
  }
12703
- whenLoaded(relation, transform) {
12704
- const model = this.resource;
12705
- if (this.resource == null || typeof model.loaded !== "function") {
12706
- return;
12707
- }
12708
- return whenLoaded(model, relation, transform);
12694
+ const parsed = Number.parseInt(value, 10);
12695
+ if (!Number.isInteger(parsed) || parsed <= 0) {
12696
+ throw new BadRequestError(`Invalid query parameter "${name}". Expected a positive integer.`);
12709
12697
  }
12710
- toArray() {
12711
- if (this.resource && typeof this.resource === "object" && "toArray" in this.resource) {
12712
- return this.resource.toArray();
12713
- }
12714
- return { ...this.resource };
12698
+ return parsed;
12699
+ }
12700
+ function parseOptionalBooleanQueryParam(params, name) {
12701
+ const value = params.get(name);
12702
+ if (value === null || value.trim() === "") {
12703
+ return;
12715
12704
  }
12716
- toResponse() {
12717
- const wrap = this.constructor.wrap;
12718
- const payload = this.toArray();
12719
- if (wrap === null) {
12720
- return { ...payload, ...this.extra };
12721
- }
12722
- return { [wrap]: payload, ...this.extra };
12705
+ switch (value.toLowerCase()) {
12706
+ case "true":
12707
+ case "1":
12708
+ return true;
12709
+ case "false":
12710
+ case "0":
12711
+ return false;
12712
+ default:
12713
+ throw new BadRequestError(`Invalid query parameter "${name}". Expected a boolean.`);
12723
12714
  }
12724
12715
  }
12725
-
12726
- class ResourceCollection extends JsonResource {
12727
- toArray() {
12728
- const items = this.resource.map((item) => item instanceof JsonResource ? item.toArray() : { ...item });
12729
- const wrap = this.constructor.wrap;
12730
- if (wrap === null) {
12731
- return { data: items };
12732
- }
12733
- return { [wrap]: items };
12716
+ function parseOptionalEnumQueryParam(params, name, allowedValues) {
12717
+ const value = params.get(name);
12718
+ if (value === null || value.trim() === "") {
12719
+ return;
12734
12720
  }
12735
- toResponse() {
12736
- return { ...this.toArray(), ...this.extra };
12721
+ if (!allowedValues.includes(value)) {
12722
+ throw new BadRequestError(`Invalid query parameter "${name}". Expected one of: ${allowedValues.join(", ")}.`);
12737
12723
  }
12724
+ return value;
12738
12725
  }
12739
- function toResourceCollection(items, transformer) {
12740
- return items.map(transformer);
12726
+ function expectObject(value, label = "request body") {
12727
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
12728
+ throw new BadRequestError(`${label} must be a JSON object.`);
12729
+ }
12730
+ return value;
12741
12731
  }
12742
- function toPaginatedResourceCollection(items, meta, transformer) {
12743
- return {
12744
- data: toResourceCollection(items, transformer),
12745
- meta
12746
- };
12732
+ async function parseJsonBody(request, validator) {
12733
+ let payload;
12734
+ try {
12735
+ payload = await request.json();
12736
+ } catch {
12737
+ throw new BadRequestError("Request body must be valid JSON.");
12738
+ }
12739
+ return validator(payload);
12747
12740
  }
12748
- // ../../src/core/http/safeInternalPath.ts
12749
- var NESTED_REDIRECT_KEYS = new Set(["redirect", "next", "return", "returnTo", "return_to"]);
12750
- function looksLikeExternalTarget(value) {
12741
+ function readRequiredString(payload, field, options = {}) {
12742
+ const value = payload[field];
12743
+ if (typeof value !== "string" || value.trim() === "") {
12744
+ throw new BadRequestError(`"${field}" is required and must be a string.`);
12745
+ }
12751
12746
  const trimmed = value.trim();
12752
- if (!trimmed.startsWith("/") || trimmed.startsWith("//") || trimmed.includes("\\")) {
12753
- return true;
12747
+ if (options.minLength !== undefined && trimmed.length < options.minLength) {
12748
+ throw new BadRequestError(`"${field}" must be at least ${options.minLength} characters.`);
12754
12749
  }
12755
- if (trimmed.includes("://") || trimmed.includes(":/") || trimmed.includes(":\\")) {
12756
- return true;
12750
+ if (options.maxLength !== undefined && trimmed.length > options.maxLength) {
12751
+ throw new BadRequestError(`"${field}" must be at most ${options.maxLength} characters.`);
12757
12752
  }
12758
- try {
12759
- const decoded = decodeURIComponent(trimmed);
12760
- if (decoded.startsWith("//") || decoded.includes("\\") || /https?:/i.test(decoded)) {
12761
- return true;
12762
- }
12763
- } catch {
12764
- return true;
12753
+ if (options.pattern && !options.pattern.test(trimmed)) {
12754
+ throw new BadRequestError(`"${field}" has an invalid format.`);
12765
12755
  }
12766
- return false;
12756
+ return trimmed;
12767
12757
  }
12768
- function sanitizeNestedQuery(search) {
12769
- if (!search) {
12770
- return "";
12758
+ function readOptionalString(payload, field, options = {}) {
12759
+ if (!(field in payload) || payload[field] === undefined) {
12760
+ return;
12771
12761
  }
12772
- const params = new URLSearchParams(search.startsWith("?") ? search.slice(1) : search);
12773
- const next = new URLSearchParams;
12774
- for (const [key, value] of params.entries()) {
12775
- if (NESTED_REDIRECT_KEYS.has(key)) {
12776
- const sanitized = sanitizeInternalPath(value, "/");
12777
- next.set(key, sanitized);
12778
- continue;
12779
- }
12780
- if (looksLikeExternalTarget(value) && value.includes("://")) {
12781
- continue;
12782
- }
12783
- next.set(key, value);
12762
+ return readRequiredString(payload, field, options);
12763
+ }
12764
+ function readRequiredEnum(payload, field, allowedValues) {
12765
+ const value = readRequiredString(payload, field);
12766
+ if (!allowedValues.includes(value)) {
12767
+ throw new BadRequestError(`"${field}" must be one of: ${allowedValues.join(", ")}.`);
12768
+ }
12769
+ return value;
12770
+ }
12771
+ function readOptionalEnum(payload, field, allowedValues) {
12772
+ if (!(field in payload) || payload[field] === undefined) {
12773
+ return;
12784
12774
  }
12785
- const serialized = next.toString();
12786
- return serialized ? `?${serialized}` : "";
12775
+ return readRequiredEnum(payload, field, allowedValues);
12787
12776
  }
12788
- function sanitizeInternalPath(raw, fallback = "/") {
12789
- const trimmed = raw.trim();
12790
- if (looksLikeExternalTarget(trimmed)) {
12791
- return fallback;
12777
+ function readRequiredPositiveInt(payload, field) {
12778
+ const value = payload[field];
12779
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
12780
+ throw new BadRequestError(`"${field}" is required and must be a positive integer.`);
12792
12781
  }
12793
- const queryIndex = trimmed.indexOf("?");
12794
- const hashIndex = trimmed.indexOf("#");
12795
- const end = [queryIndex, hashIndex].filter((index) => index >= 0).sort((a, b) => a - b)[0];
12796
- const pathname = end === undefined ? trimmed : trimmed.slice(0, end);
12797
- if (looksLikeExternalTarget(pathname)) {
12798
- return fallback;
12782
+ return value;
12783
+ }
12784
+ function readOptionalPositiveInt(payload, field) {
12785
+ if (!(field in payload) || payload[field] === undefined) {
12786
+ return;
12799
12787
  }
12800
- const search = queryIndex >= 0 ? trimmed.slice(queryIndex, hashIndex >= 0 ? hashIndex : undefined) : "";
12801
- return `${pathname}${sanitizeNestedQuery(search)}`;
12788
+ return readRequiredPositiveInt(payload, field);
12802
12789
  }
12803
- function safeInternalRedirectPath(request, fallback = "/") {
12804
- const url = new URL(request.url);
12805
- return sanitizeInternalPath(`${url.pathname}${url.search}`, fallback);
12790
+ function parsePositiveIntParam(value, name = "id") {
12791
+ const parsed = Number.parseInt(value, 10);
12792
+ if (!Number.isInteger(parsed) || parsed <= 0) {
12793
+ throw new BadRequestError(`Invalid ${name}. Expected a positive integer.`);
12794
+ }
12795
+ return parsed;
12806
12796
  }
12807
- function loginRedirectLocation(request) {
12808
- return `/login?redirect=${encodeURIComponent(safeInternalRedirectPath(request))}`;
12797
+
12798
+ // ../../src/core/http/formRequest.ts
12799
+ class FormRequest {
12800
+ authorize(_request) {
12801
+ return true;
12802
+ }
12803
+ async validate(request) {
12804
+ if (!await this.authorize(request)) {
12805
+ throw new ForbiddenError;
12806
+ }
12807
+ return await parseJsonBody(request, (payload) => this.parse(payload));
12808
+ }
12809
12809
  }
12810
12810
 
12811
- // ../../src/core/view/htmlResponse.ts
12812
- function withCharset(contentType) {
12813
- return contentType.includes("charset=") ? contentType : `${contentType}; charset=utf-8`;
12811
+ class QueryFormRequest {
12812
+ validate(request) {
12813
+ return this.parseQuery(request);
12814
+ }
12814
12815
  }
12815
- function htmlResponse(html, init = {}) {
12816
- return new Response(html, {
12817
- status: init.status ?? 200,
12818
- statusText: init.statusText,
12819
- headers: {
12820
- "Content-Type": "text/html; charset=utf-8"
12816
+ // ../../src/core/http/authMiddleware.ts
12817
+ function createAuthMiddleware(auth) {
12818
+ return async (request, next) => {
12819
+ const resolved = typeof auth.resolveWithSource === "function" ? await auth.resolveWithSource(request) : { user: await auth.resolve(request), credentialSource: null };
12820
+ return await runWithAuthContext(resolved.user, resolved.credentialSource, async () => {
12821
+ return await next();
12822
+ });
12823
+ };
12824
+ }
12825
+ // ../../src/core/http/authorizeMiddleware.ts
12826
+ function createAuthorizeMiddleware(gate, auth, resource, action) {
12827
+ return async (request, next) => {
12828
+ const user = currentAuthUser() ?? await auth.resolve(request);
12829
+ if (!gate.allows(resource, action, user)) {
12830
+ const error = new ForbiddenError;
12831
+ return errorResponse(error);
12821
12832
  }
12822
- });
12833
+ return await next();
12834
+ };
12823
12835
  }
12824
- function isHtmxRequest(request) {
12825
- return request.headers.get("HX-Request") === "true";
12836
+ // ../../src/core/http/middleware.ts
12837
+ function isRouteHandler(value) {
12838
+ return typeof value === "function";
12826
12839
  }
12827
- function redirectResponse(location, status = 302) {
12828
- if (!location.startsWith("/") || location.startsWith("//")) {
12829
- throw new Error("Redirect location must be an internal path.");
12840
+ function isMethodRouteMap(value) {
12841
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
12842
+ return false;
12830
12843
  }
12831
- return new Response(null, {
12832
- status,
12833
- headers: {
12834
- Location: sanitizeInternalPath(location, "/")
12835
- }
12836
- });
12844
+ const entries = Object.entries(value);
12845
+ return entries.length > 0 && entries.every(([, handler]) => isRouteHandler(handler));
12837
12846
  }
12838
- function textResponse(body, init = {}) {
12839
- return new Response(body, {
12840
- status: init.status ?? 200,
12841
- headers: {
12842
- "Content-Type": "text/plain; charset=utf-8"
12843
- }
12844
- });
12847
+ function composeMiddleware(...middleware) {
12848
+ return (handler) => {
12849
+ return async (request) => {
12850
+ let index = 0;
12851
+ const dispatch = async () => {
12852
+ if (index >= middleware.length) {
12853
+ return await handler(request);
12854
+ }
12855
+ const current = middleware[index];
12856
+ index += 1;
12857
+ if (!current) {
12858
+ return await handler(request);
12859
+ }
12860
+ return await current(request, dispatch);
12861
+ };
12862
+ return await dispatch();
12863
+ };
12864
+ };
12845
12865
  }
12846
- function xmlResponse(body, init = {}) {
12847
- return new Response(body, {
12848
- status: init.status ?? 200,
12849
- headers: {
12850
- "Content-Type": withCharset(init.contentType ?? "application/xml")
12851
- }
12866
+ async function requestIdMiddleware(request, next) {
12867
+ const requestId = request.headers.get("x-request-id") ?? crypto.randomUUID();
12868
+ const response = await next();
12869
+ const headers = new Headers(response.headers);
12870
+ headers.set("x-request-id", requestId);
12871
+ return new Response(response.body, {
12872
+ status: response.status,
12873
+ statusText: response.statusText,
12874
+ headers
12852
12875
  });
12853
12876
  }
12854
- function rssResponse(body, init = {}) {
12855
- return xmlResponse(body, { ...init, contentType: "application/rss+xml" });
12856
- }
12857
-
12858
- // ../../src/core/view/webErrorView.ts
12859
- var configuredErrorView = {};
12860
- function configureWebErrorView(options) {
12861
- configuredErrorView = { ...options };
12862
- }
12863
- function escapeHtml(value) {
12864
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
12877
+ function wrapRouteHandler(handler, middleware) {
12878
+ if (isMethodRouteMap(handler)) {
12879
+ const wrapped = {};
12880
+ for (const [method, routeHandler] of Object.entries(handler)) {
12881
+ wrapped[method] = composeMiddleware(...middleware)(routeHandler);
12882
+ }
12883
+ return wrapped;
12884
+ }
12885
+ if (isRouteHandler(handler)) {
12886
+ return composeMiddleware(...middleware)(handler);
12887
+ }
12888
+ return handler;
12865
12889
  }
12866
- function errorReturnPath(request) {
12867
- if (!request)
12868
- return "/";
12869
- try {
12870
- const current = new URL(request.url);
12871
- const previous = new URL(request.headers.get("referer") ?? "");
12872
- if (previous.origin !== current.origin || (request.method === "GET" || request.method === "HEAD") && previous.pathname === current.pathname)
12873
- return "/";
12874
- return sanitizeInternalPath(previous.pathname, "/");
12875
- } catch {
12876
- return "/";
12890
+ function applyMiddlewareToRoutes(routes, middleware) {
12891
+ const wrapped = {};
12892
+ for (const [path, routeHandler] of Object.entries(routes)) {
12893
+ const identity = async (_request, next) => await runWithRequestMeta({ ...currentRequestMeta(), routeTemplate: path }, next);
12894
+ wrapped[path] = wrapRouteHandler(routeHandler, [identity, ...middleware]);
12877
12895
  }
12896
+ return wrapped;
12878
12897
  }
12879
- function renderKernelErrorChrome(input) {
12880
- const title = escapeHtml(input.title);
12881
- const message = escapeHtml(input.message);
12882
- const errorLines = Object.entries(input.errors ?? {}).flatMap(([field, messages]) => messages.map((item) => `${field}: ${item}`)).map((line) => `<li>${escapeHtml(line)}</li>`).join("");
12883
- const details = errorLines ? `<ul class="error-list">${errorLines}</ul>` : "";
12884
- const goBack = input.status === 422 ? `<p><a href="${escapeHtml(errorReturnPath(input.request ?? currentRequestMeta().request))}">Go back</a></p>` : "";
12885
- return `<!doctype html>
12886
- <html lang="en">
12887
- <head>
12888
- <meta charset="UTF-8" />
12889
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
12890
- <title>${title}</title>
12891
- <link rel="stylesheet" href="/assets/app.css" />
12892
- </head>
12893
- <body>
12894
- <header class="site-header">
12895
- <a class="brand" href="/">Home</a>
12896
- </header>
12897
- <main class="site-main">
12898
- <section class="page-header">
12899
- <h1>${title}</h1>
12900
- <p>${message}</p>
12901
- ${details}
12902
- ${goBack}
12903
- </section>
12904
- </main>
12905
- </body>
12906
- </html>
12907
- `;
12898
+ // ../../src/core/http/pagination.ts
12899
+ var DEFAULT_PER_PAGE = 15;
12900
+ var MAX_PER_PAGE = 100;
12901
+ function parseRequiredPositiveIntQueryParam(params, name) {
12902
+ const value = params.get(name);
12903
+ if (value === null || value.trim() === "") {
12904
+ throw new BadRequestError(`Invalid query parameter "${name}". Expected a positive integer.`);
12905
+ }
12906
+ const parsed = Number.parseInt(value, 10);
12907
+ if (!Number.isInteger(parsed) || parsed <= 0) {
12908
+ throw new BadRequestError(`Invalid query parameter "${name}". Expected a positive integer.`);
12909
+ }
12910
+ return parsed;
12908
12911
  }
12909
- function errorTemplateName(status) {
12910
- if (status === 404) {
12911
- return "errors/not-found";
12912
+ function parsePaginationQuery(request) {
12913
+ const params = getQueryParams(request);
12914
+ const pageParam = params.get("page");
12915
+ const perPageParam = params.get("per_page");
12916
+ const page = pageParam === null || pageParam.trim() === "" ? 1 : parseRequiredPositiveIntQueryParam(params, "page");
12917
+ if (perPageParam === null || perPageParam.trim() === "") {
12918
+ return { page, perPage: DEFAULT_PER_PAGE };
12912
12919
  }
12913
- if (status === 403) {
12914
- return "errors/forbidden";
12920
+ const perPage = parseRequiredPositiveIntQueryParam(params, "per_page");
12921
+ if (perPage > MAX_PER_PAGE) {
12922
+ throw new BadRequestError(`Invalid query parameter "per_page". Maximum allowed value is ${MAX_PER_PAGE}.`);
12915
12923
  }
12916
- return "errors/error";
12924
+ return { page, perPage };
12917
12925
  }
12918
- async function renderWebErrorHtml(input) {
12919
- const render = configuredErrorView.render;
12920
- if (!render) {
12921
- return renderKernelErrorChrome(input);
12926
+ function paginatedResponse(data, meta, init = {}) {
12927
+ return Response.json({ data, meta }, init);
12928
+ }
12929
+ // ../../src/core/http/uploads.ts
12930
+ var DEFAULT_MAX_UPLOAD_BYTES = 5 * 1024 * 1024;
12931
+ var ALLOWED_UPLOAD_MIME_TYPES = new Set([
12932
+ "application/pdf",
12933
+ "application/json",
12934
+ "application/zip",
12935
+ "application/x-zip-compressed",
12936
+ "image/jpeg",
12937
+ "image/png",
12938
+ "image/gif",
12939
+ "image/webp",
12940
+ "text/plain",
12941
+ "text/csv"
12942
+ ]);
12943
+ function resolveMaxUploadBytes() {
12944
+ const raw = process.env.MAX_UPLOAD_BYTES?.trim() ?? process.env.MAX_REQUEST_BODY_BYTES?.trim();
12945
+ if (!raw) {
12946
+ return DEFAULT_MAX_UPLOAD_BYTES;
12922
12947
  }
12923
- try {
12924
- return await render({
12925
- ...input,
12926
- request: input.request ?? currentRequestMeta().request
12927
- });
12928
- } catch {
12929
- return renderKernelErrorChrome(input);
12948
+ const parsed = Number.parseInt(raw, 10);
12949
+ if (!Number.isInteger(parsed) || parsed <= 0) {
12950
+ return DEFAULT_MAX_UPLOAD_BYTES;
12930
12951
  }
12952
+ return parsed;
12931
12953
  }
12932
- async function htmlErrorResponse(input) {
12933
- const response = htmlResponse(await renderWebErrorHtml(input), { status: input.status });
12934
- response.headers.set("Cache-Control", "no-store");
12935
- return response;
12954
+ function normalizeMimeType(mimeType) {
12955
+ return mimeType.split(";")[0]?.trim().toLowerCase() ?? "";
12936
12956
  }
12937
- async function notFoundHtmlResponse(body) {
12938
- if (body !== undefined) {
12939
- const response = htmlResponse(body, { status: 404 });
12940
- response.headers.set("Cache-Control", "no-store");
12941
- return response;
12957
+ function isAllowedMimeType(mimeType) {
12958
+ const normalized = normalizeMimeType(mimeType);
12959
+ if (!normalized || normalized === "application/octet-stream") {
12960
+ return envFlagEnabled(process.env.UPLOAD_ALLOW_UNKNOWN_MIME);
12942
12961
  }
12943
- return htmlErrorResponse({
12944
- status: 404,
12945
- title: "Not Found",
12946
- message: "The page you requested was not found."
12947
- });
12962
+ return ALLOWED_UPLOAD_MIME_TYPES.has(normalized);
12948
12963
  }
12949
12964
 
12950
- // ../../src/core/http/contentNegotiation.ts
12951
- function requestPrefersJson(request) {
12952
- if (!request) {
12953
- return true;
12954
- }
12955
- if (request.headers.get("HX-Request") === "true") {
12956
- return false;
12965
+ // ../../src/core/http/parseMultipartUpload.ts
12966
+ function normalizeMimeType2(mimeType) {
12967
+ return mimeType.split(";")[0]?.trim().toLowerCase() || "application/octet-stream";
12968
+ }
12969
+ function sanitizeUploadFileName(name) {
12970
+ const base = name.split(/[/\\]/).pop()?.trim() ?? "upload";
12971
+ const sanitized = base.replace(/[^\w.\-()+ ]+/g, "_").slice(0, 200);
12972
+ return sanitized.length > 0 ? sanitized : "upload";
12973
+ }
12974
+ async function validateUploadFile(file, fieldName = "file") {
12975
+ if (!(file instanceof File)) {
12976
+ throw new BadRequestError(`Missing upload field "${fieldName}".`);
12957
12977
  }
12958
- const pathname = new URL(request.url).pathname;
12959
- if (pathname.startsWith("/api/")) {
12960
- return true;
12978
+ if (file.size <= 0) {
12979
+ throw new BadRequestError("Uploaded file is empty.");
12961
12980
  }
12962
- const accept = request.headers.get("accept")?.toLowerCase() ?? "";
12963
- if (accept.includes("text/html")) {
12964
- return false;
12981
+ const maxBytes = resolveMaxUploadBytes();
12982
+ if (file.size > maxBytes) {
12983
+ throw new PayloadTooLargeError(`Upload exceeds the ${maxBytes} byte limit.`);
12965
12984
  }
12966
- if (accept.includes("application/json")) {
12967
- return true;
12985
+ const mimeType = normalizeMimeType2(file.type.trim() || "application/octet-stream");
12986
+ if (!isAllowedMimeType(mimeType)) {
12987
+ throw new BadRequestError(`File type "${mimeType}" is not allowed.`);
12968
12988
  }
12989
+ return {
12990
+ fileName: sanitizeUploadFileName(file.name),
12991
+ mimeType,
12992
+ size: file.size,
12993
+ contents: new Uint8Array(await file.arrayBuffer())
12994
+ };
12995
+ }
12996
+ async function parseMultipartUpload(request, fieldName = "file") {
12969
12997
  const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
12970
- if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
12971
- return false;
12998
+ if (!contentType.includes("multipart/form-data")) {
12999
+ throw new BadRequestError("Expected multipart form data.");
12972
13000
  }
12973
- return false;
12974
- }
12975
-
12976
- // ../../src/core/http/webErrorResponse.ts
12977
- function normalizeFieldErrors(details) {
12978
- if (!details || typeof details !== "object" || Array.isArray(details)) {
12979
- return {};
13001
+ const formData = await request.formData();
13002
+ const value = formData.get(fieldName);
13003
+ if (!(value instanceof File)) {
13004
+ throw new BadRequestError(`Missing upload field "${fieldName}".`);
12980
13005
  }
12981
- const errors = {};
12982
- for (const [field, messages] of Object.entries(details)) {
12983
- if (Array.isArray(messages)) {
12984
- errors[field] = messages.map(String);
12985
- continue;
12986
- }
12987
- if (typeof messages === "string") {
12988
- errors[field] = [messages];
13006
+ return validateUploadFile(value, fieldName);
13007
+ }
13008
+ // ../../src/core/http/requireAuthMiddleware.ts
13009
+ function createRequireAuthMiddleware(auth) {
13010
+ return async (request, next) => {
13011
+ if (!await auth.check(request)) {
13012
+ const error = new UnauthorizedError;
13013
+ return errorResponse(error);
12989
13014
  }
13015
+ return await next();
13016
+ };
13017
+ }
13018
+ // ../../src/core/http/resources.ts
13019
+ function serializeDate(value) {
13020
+ return value instanceof Date ? value.toISOString() : value;
13021
+ }
13022
+ function whenLoaded(model, relation, transform) {
13023
+ const value = model.loaded(relation);
13024
+ if (value === undefined) {
13025
+ return;
12990
13026
  }
12991
- return errors;
13027
+ if (value === null) {
13028
+ return null;
13029
+ }
13030
+ return transform ? transform(value) : value;
12992
13031
  }
12993
- function errorPageTitle(status, message) {
12994
- if (status === 404) {
12995
- return "Not Found";
13032
+
13033
+ class JsonResource {
13034
+ resource;
13035
+ static wrap = "data";
13036
+ extra = {};
13037
+ constructor(resource) {
13038
+ this.resource = resource;
12996
13039
  }
12997
- if (status === 403) {
12998
- return "Forbidden";
13040
+ static make(resource) {
13041
+ return new JsonResource(resource);
12999
13042
  }
13000
- if (status >= 500) {
13001
- return "Server Error";
13043
+ static collection(items) {
13044
+ return new ResourceCollection(items);
13002
13045
  }
13003
- return message;
13004
- }
13005
- function publicErrorMessage(status, message) {
13006
- if (status >= 500 && isProductionEnv()) {
13007
- return "Something went wrong.";
13046
+ additional(data) {
13047
+ this.extra = { ...this.extra, ...data };
13048
+ return this;
13008
13049
  }
13009
- return message;
13010
- }
13011
- function logServerError(error, mappedError) {
13012
- if (mappedError.status < 500) {
13013
- return;
13050
+ when(condition, value) {
13051
+ return condition ? value : undefined;
13014
13052
  }
13015
- appLogger.error("Unhandled request error", {
13016
- status: mappedError.status,
13017
- error: error instanceof Error ? error.message : String(error),
13018
- stack: error instanceof Error ? error.stack : undefined
13019
- });
13020
- }
13021
- async function webErrorResponse(error, request) {
13022
- if (currentRequestMeta().errorFormat === "json" || !request || !isViewsEnabled() || requestPrefersJson(request)) {
13023
- return null;
13053
+ whenLoaded(relation, transform) {
13054
+ const model = this.resource;
13055
+ if (this.resource == null || typeof model.loaded !== "function") {
13056
+ return;
13057
+ }
13058
+ return whenLoaded(model, relation, transform);
13024
13059
  }
13025
- const mappedError = toHttpError(error) ?? mapDatabaseError(error);
13026
- logServerError(error, mappedError);
13027
- if (mappedError.status === 401) {
13028
- return Response.redirect(loginRedirectLocation(request), 302);
13060
+ toArray() {
13061
+ if (this.resource && typeof this.resource === "object" && "toArray" in this.resource) {
13062
+ return this.resource.toArray();
13063
+ }
13064
+ return { ...this.resource };
13065
+ }
13066
+ toResponse() {
13067
+ const wrap = this.constructor.wrap;
13068
+ const payload = this.toArray();
13069
+ if (wrap === null) {
13070
+ return { ...payload, ...this.extra };
13071
+ }
13072
+ return { [wrap]: payload, ...this.extra };
13029
13073
  }
13030
- const errors = mappedError instanceof ValidationError || mappedError.name === "ValidationError" ? normalizeFieldErrors(mappedError.details) : undefined;
13031
- return htmlErrorResponse({
13032
- status: mappedError.status,
13033
- title: errorPageTitle(mappedError.status, mappedError.message),
13034
- message: publicErrorMessage(mappedError.status, mappedError.message),
13035
- errors,
13036
- request
13037
- });
13038
13074
  }
13039
13075
 
13040
- // ../../src/core/http/response.ts
13041
- init_transactionControl();
13042
- function jsonResponse2(data, init = {}) {
13043
- return Response.json(data, {
13044
- status: init.status ?? 200,
13045
- headers: init.headers
13046
- });
13047
- }
13048
- function createdResponse(data, init = {}) {
13049
- return jsonResponse2(data, { ...init, status: init.status ?? 201 });
13050
- }
13051
- function noContentResponse() {
13052
- return new Response(null, { status: 204 });
13076
+ class ResourceCollection extends JsonResource {
13077
+ toArray() {
13078
+ const items = this.resource.map((item) => item instanceof JsonResource ? item.toArray() : { ...item });
13079
+ const wrap = this.constructor.wrap;
13080
+ if (wrap === null) {
13081
+ return { data: items };
13082
+ }
13083
+ return { [wrap]: items };
13084
+ }
13085
+ toResponse() {
13086
+ return { ...this.toArray(), ...this.extra };
13087
+ }
13053
13088
  }
13054
- function errorResponse(error) {
13055
- const mappedError = toHttpError(error) ?? mapDatabaseError(error);
13056
- logServerError(error, mappedError);
13057
- return Response.json({
13058
- error: mappedError.message,
13059
- ...mappedError.details === undefined ? {} : { details: mappedError.details }
13060
- }, { status: mappedError.status, headers: { "Cache-Control": "no-store" } });
13089
+ function toResourceCollection(items, transformer) {
13090
+ return items.map(transformer);
13061
13091
  }
13062
- function withErrorHandling(handler) {
13063
- return async (...args) => {
13064
- try {
13065
- return await handler(...args);
13066
- } catch (error) {
13067
- requestTransactionRollback();
13068
- const request = args.find((arg) => arg instanceof Request);
13069
- const webResponse = await webErrorResponse(error, request);
13070
- if (webResponse) {
13071
- return webResponse;
13072
- }
13073
- return errorResponse(error);
13074
- }
13092
+ function toPaginatedResourceCollection(items, meta, transformer) {
13093
+ return {
13094
+ data: toResourceCollection(items, transformer),
13095
+ meta
13075
13096
  };
13076
13097
  }
13077
13098
  // ../../src/core/http/route.ts
@@ -13691,7 +13712,7 @@ function createRequireAbilityMiddleware(abilityChecker) {
13691
13712
  if (isViewsEnabled() && !requestPrefersJson(request)) {
13692
13713
  throw error;
13693
13714
  }
13694
- return Response.json({ error: error.message }, { status: error.status });
13715
+ return errorResponse(new HttpError(error.status, error.message));
13695
13716
  }
13696
13717
  throw error;
13697
13718
  }
@@ -13724,7 +13745,7 @@ function createRequireGlobalAdminMiddleware() {
13724
13745
  path: new URL(_request.url).pathname
13725
13746
  });
13726
13747
  const error = new ForbiddenError("Platform admin access required.");
13727
- return Response.json({ error: error.message }, { status: error.status });
13748
+ return errorResponse(error);
13728
13749
  }
13729
13750
  return await next();
13730
13751
  };
@@ -16977,16 +16998,32 @@ class ViewRenderer {
16977
16998
  this.engine = engine;
16978
16999
  this.defaultLayout = defaultLayout;
16979
17000
  }
16980
- namespace(prefix) {
17001
+ namespace(prefix, defaults = {}) {
16981
17002
  validateRelativeViewName(prefix);
17003
+ const defaultHeaders = new Headers(defaults.headers);
17004
+ const responseHeaders = (headers) => {
17005
+ const merged = new Headers(defaultHeaders);
17006
+ const overrides = new Headers(headers);
17007
+ for (const [name, value] of overrides) {
17008
+ if (name !== "set-cookie")
17009
+ merged.set(name, value);
17010
+ }
17011
+ if (overrides.has("set-cookie")) {
17012
+ merged.delete("set-cookie");
17013
+ for (const cookie of overrides.getSetCookie())
17014
+ merged.append("set-cookie", cookie);
17015
+ }
17016
+ return merged;
17017
+ };
16982
17018
  const qualify = (name) => {
16983
17019
  validateRelativeViewName(name);
16984
17020
  return `${prefix}/${name}`;
16985
17021
  };
16986
17022
  return {
16987
- render: async (name, data, options) => this.render(qualify(name), data, options),
17023
+ render: async (name, data, options = {}) => this.render(qualify(name), data, { ...options, headers: responseHeaders(options.headers) }),
16988
17024
  renderHtmx: async (name, data, options = {}) => this.renderHtmx(qualify(name), data, {
16989
17025
  ...options,
17026
+ headers: responseHeaders(options.headers),
16990
17027
  ...options.fragment === undefined ? {} : { fragment: qualify(options.fragment) }
16991
17028
  })
16992
17029
  };
@@ -17175,6 +17212,7 @@ export {
17175
17212
  WhereBuilder,
17176
17213
  absoluteTemporarySignedUrl,
17177
17214
  acquireTracingRuntime,
17215
+ afterCommit,
17178
17216
  apiPrefix,
17179
17217
  appCookieName,
17180
17218
  appDevSecret,
@@ -17374,7 +17412,7 @@ export {
17374
17412
  isRlsTenancy,
17375
17413
  isTenancyEnabled,
17376
17414
  jobRegistry,
17377
- jsonResponse2 as jsonResponse,
17415
+ jsonResponse,
17378
17416
  jwtTtlSeconds,
17379
17417
  loadMigrationsFromDirectory,
17380
17418
  loadSeedersFromDirectory,
@@ -17415,6 +17453,7 @@ export {
17415
17453
  pinUrlToAddress,
17416
17454
  pivotTableName,
17417
17455
  policyGate,
17456
+ privateJsonResponse,
17418
17457
  projectPluck,
17419
17458
  prometheusRegistry,
17420
17459
  qualifyColumn,