@thexjs/core 1.3.5 → 1.3.6

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/adapter.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  scanNotFound,
10
10
  scanPages,
11
11
  scanRoutes
12
- } from "./chunk-PQ7ZVWEJ.js";
12
+ } from "./chunk-VAWSOVGY.js";
13
13
 
14
14
  // src/adapter/bundle.ts
15
15
  import { mkdirSync, rmSync, writeFileSync } from "fs";
@@ -267,8 +267,8 @@ function findMiddlewareChain(routeFilePath, middleware, routesDir) {
267
267
  return chain;
268
268
  }
269
269
  function routePatternToRegex(routePath) {
270
- const regexStr = routePath.replace(/\//g, "\\/").replace(/:(\w+)/g, "([^/]+)").replace(/\*/g, "(.+)");
271
- return new RegExp(`^${regexStr}$`);
270
+ const escaped = routePath.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\//g, "\\/").replace(/:(\w+)/g, "([^/]+)").replace(/\*/g, "(.+)");
271
+ return new RegExp(`^${escaped}$`);
272
272
  }
273
273
  function extractParams(routePath, paramNames, url) {
274
274
  const regex = routePatternToRegex(routePath);
@@ -323,6 +323,65 @@ function writeManifest(routes, routesDir) {
323
323
  return manifestPath;
324
324
  }
325
325
 
326
+ // src/security/body-size.ts
327
+ var DEFAULT_MAX_BODY_SIZE = 1048576;
328
+ var RequestBodyTooLargeError = class extends Error {
329
+ maxBytes;
330
+ constructor(maxBytes) {
331
+ super(`Request body exceeds the ${maxBytes} byte limit`);
332
+ this.name = "RequestBodyTooLargeError";
333
+ this.maxBytes = maxBytes;
334
+ }
335
+ };
336
+ function isBodylessMethod(method) {
337
+ return method === "GET" || method === "HEAD" || method === "OPTIONS";
338
+ }
339
+ function enforceRequestBodySize(req, maxBytes) {
340
+ if (isBodylessMethod(req.method)) return req;
341
+ const contentLength = req.headers.get("content-length");
342
+ if (contentLength !== null) {
343
+ const declared = Number(contentLength);
344
+ if (Number.isFinite(declared) && declared > maxBytes) {
345
+ return new Response("Payload too large", {
346
+ status: 413,
347
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
348
+ });
349
+ }
350
+ return req;
351
+ }
352
+ const source = req.body;
353
+ if (source === null) return req;
354
+ const { readable, writable } = new TransformStream();
355
+ const writer = writable.getWriter();
356
+ let total = 0;
357
+ const pump = async () => {
358
+ const reader = source.getReader();
359
+ try {
360
+ while (true) {
361
+ const { done, value } = await reader.read();
362
+ if (done) break;
363
+ total += value.byteLength;
364
+ if (total > maxBytes) {
365
+ await reader.cancel().catch(() => {
366
+ });
367
+ await writer.abort(new RequestBodyTooLargeError(maxBytes));
368
+ return;
369
+ }
370
+ await writer.write(value);
371
+ }
372
+ await writer.close();
373
+ } catch (err) {
374
+ await writer.abort(err);
375
+ }
376
+ };
377
+ void pump();
378
+ return new Request(req.url, {
379
+ method: req.method,
380
+ headers: req.headers,
381
+ body: readable
382
+ });
383
+ }
384
+
326
385
  // src/security/csrf.ts
327
386
  var CSRF_COOKIE_NAME = "x_csrf_token";
328
387
  var CSRF_HEADER_NAME = "x-csrf-token";
@@ -366,6 +425,15 @@ function readCookie(req, name) {
366
425
  }
367
426
  return null;
368
427
  }
428
+ function tokensEqual(a, b) {
429
+ const encoder = new TextEncoder();
430
+ const aBytes = encoder.encode(a);
431
+ const bBytes = encoder.encode(b);
432
+ if (aBytes.length !== bBytes.length) return false;
433
+ let diff = 0;
434
+ for (let i = 0; i < aBytes.length; i++) diff |= (aBytes[i] ?? 0) ^ (bBytes[i] ?? 0);
435
+ return diff === 0;
436
+ }
369
437
  function verifyCsrfToken(req) {
370
438
  if (SAFE_METHODS.has(req.method)) return { ok: true };
371
439
  const cookieToken = readCookie(req, CSRF_COOKIE_NAME);
@@ -373,7 +441,7 @@ function verifyCsrfToken(req) {
373
441
  if (!cookieToken || !headerToken) {
374
442
  return { ok: false, reason: `missing CSRF cookie or "${CSRF_HEADER_NAME}" header` };
375
443
  }
376
- if (cookieToken !== headerToken) {
444
+ if (!tokensEqual(cookieToken, headerToken)) {
377
445
  return { ok: false, reason: "CSRF token mismatch" };
378
446
  }
379
447
  return { ok: true };
@@ -466,14 +534,24 @@ function getServerFunctionHandler(csrfOptions) {
466
534
  try {
467
535
  const body = await req.json();
468
536
  args = Array.isArray(body) ? body : [body];
469
- } catch {
537
+ } catch (err) {
538
+ if (err instanceof RequestBodyTooLargeError) {
539
+ return new Response("Payload too large", { status: 413 });
540
+ }
470
541
  return new Response("Invalid request body", { status: 400 });
471
542
  }
472
543
  try {
473
544
  const result = await fn(...args);
474
545
  return Response.json(result);
475
546
  } catch (err) {
476
- reportException(err, { route: concretePath, phase: "action" });
547
+ const errorId = crypto.randomUUID().replace(/-/g, "");
548
+ reportException(err, { route: concretePath, phase: "action", errorId });
549
+ if (process.env.NODE_ENV === "production") {
550
+ return new Response(`Internal error (id: ${errorId})`, {
551
+ status: 500,
552
+ headers: { "x-x-error-id": errorId }
553
+ });
554
+ }
477
555
  const message = err instanceof Error ? err.message : "Internal error";
478
556
  return new Response(message, { status: 500 });
479
557
  }
@@ -694,6 +772,9 @@ export {
694
772
  extractParams,
695
773
  generateManifestSource,
696
774
  writeManifest,
775
+ DEFAULT_MAX_BODY_SIZE,
776
+ RequestBodyTooLargeError,
777
+ enforceRequestBodySize,
697
778
  verifyOrigin,
698
779
  generateCsrfToken,
699
780
  verifyCsrfToken,
package/dist/index.d.ts CHANGED
@@ -50,15 +50,23 @@ declare function scanContent(rootDir: string): ContentEntry[];
50
50
  declare function escapeHtml(s: string): string;
51
51
  declare function renderMarkdown(md: string): string;
52
52
 
53
- /**
54
- * Minimal remote-image proxy. Fetches an allow-listed remote image
55
- * server-side and streams it back from your own origin at /_x/image, so the
56
- * browser never makes a cross-origin request and CSP img-src can stay
57
- * 'self'-only. No resizing/optimization — just proxy + cache headers.
58
- */
59
53
  interface ImageProxyOptions {
60
54
  /** Hostnames allowed to be proxied, e.g. ["stardance.hackclub.com"]. Required — an empty/missing list disables the route (404). */
61
55
  remoteHosts?: string[];
56
+ /**
57
+ * Max bytes to accept from an upstream image. Enforced via `Content-Length`
58
+ * (rejected before streaming) and a counting stream (aborted mid-transfer).
59
+ * Default: 10 MiB.
60
+ */
61
+ maxBytes?: number;
62
+ /**
63
+ * Resolves an allow-listed hostname to its IPs for the DNS-rebinding check.
64
+ * Every returned IP must be public. The default uses `Bun.dns.lookup`
65
+ * (RFC 2606 test/reserved TLDs are skipped). Override to pin answers or
66
+ * route through a resolver. A resolver error fails open — an unreachable
67
+ * DNS must not break image loading.
68
+ */
69
+ resolveHost?: (hostname: string) => Promise<string[]>;
62
70
  }
63
71
  /** Returns a handler for GET /_x/image?url=<encoded remote url>, or null if the request doesn't match. */
64
72
  declare function createImageProxyHandler(options?: ImageProxyOptions): (req: Request) => Promise<Response | null>;
@@ -200,6 +208,8 @@ declare function withRequestMetrics<Server = unknown>(reporter: MetricsReporter,
200
208
  interface ErrorContext {
201
209
  route?: string;
202
210
  requestId?: string;
211
+ /** Opaque correlation id echoed to clients so they can reference the incident. */
212
+ errorId?: string;
203
213
  phase: "ssr" | "action" | "api" | "loader";
204
214
  /** Free-form discriminator, e.g. `hydration-mismatch`, for filtering. */
205
215
  tag?: string;
@@ -343,6 +353,14 @@ interface SecurityHeadersOptions {
343
353
  contentTypeOptions?: string | false;
344
354
  /** Referrer-Policy. Default: "strict-origin-when-cross-origin". Set false to disable. */
345
355
  referrerPolicy?: string | false;
356
+ /**
357
+ * Per-response random nonce for the default Content-Security-Policy. When
358
+ * present, `script-src` becomes `'self' 'nonce-<value>'` instead of
359
+ * `'self' 'unsafe-inline'`, letting HTML responses defend against inline
360
+ * script injection. Ignored when a custom `contentSecurityPolicy` is set —
361
+ * that value is applied verbatim.
362
+ */
363
+ cspNonce?: string;
346
364
  }
347
365
  declare function buildSecurityHeaders(options?: SecurityHeadersOptions): Headers;
348
366
  /** Returns a new Response with security headers merged onto the original response's headers. */
@@ -476,6 +494,14 @@ interface CreateAppOptions {
476
494
  };
477
495
  /** Remote-image proxy at /_x/image?url=... — see ImageProxyOptions. Unset/empty remoteHosts means the route 404s. */
478
496
  images?: ImageProxyOptions;
497
+ /**
498
+ * Maximum request body size in bytes, enforced ahead of route/action
499
+ * dispatch (including `/api/*` and `/__x/actions/*`). Requests whose
500
+ * `Content-Length` exceeds this are rejected with 413; chunked requests
501
+ * without a `Content-Length` are aborted mid-stream once the limit is
502
+ * crossed. Default: 1 MiB.
503
+ */
504
+ maxBodySize?: number;
479
505
  /**
480
506
  * Pre-resolved routes/actions for runtimes that can't scan the filesystem
481
507
  * or dynamically `import()` a `.tsx` file at request time (e.g. Vercel's
@@ -605,6 +631,105 @@ declare function Link({ href, children, clientNav, prefetch, ...rest }: LinkProp
605
631
 
606
632
  declare function DefaultNotFound(_props: RouteProps): react.JSX.Element;
607
633
 
634
+ /**
635
+ * Structured, append-only audit logging for security-relevant events.
636
+ *
637
+ * Mirrors the `MetricsReporter`/`ErrorReporter` pluggability discipline: a
638
+ * default sink prints one JSON line per event to stdout (append-only at the OS
639
+ * level), and enterprise deployments swap in a SIEM sink via `setAuditSink`
640
+ * without forking the framework. Every entry carries the event type, a
641
+ * timestamp, `userId` (or null), the client IP (or null) and a human-readable
642
+ * reason, so a compliance reviewer can answer "who did what, when" and an
643
+ * operator can spot brute-force patterns.
644
+ *
645
+ * Secrets are scrubbed before emission: the reason string and any metadata are
646
+ * passed through the same redaction used by the logger, and fields are
647
+ * structured (typed keys) rather than free-form blobs, so a password or token
648
+ * value cannot slip into an entry.
649
+ */
650
+ type AuditEvent = "auth.login.success" | "auth.login.failure" | "auth.logout" | "auth.password_changed" | "auth.role_changed" | "auth.permission_denied" | "auth.session_revoked";
651
+ interface AuditEntry {
652
+ timestamp: string;
653
+ event: AuditEvent;
654
+ userId: string | null;
655
+ ip: string | null;
656
+ reason?: string;
657
+ provider?: string;
658
+ requestId?: string;
659
+ /** HMAC digest of the session token (safe to store — not the token itself). */
660
+ sessionHash?: string;
661
+ metadata?: Record<string, unknown>;
662
+ }
663
+ /** Receives audit entries. Implementations must treat them as append-only. */
664
+ interface AuditSink {
665
+ write(entry: AuditEntry): void;
666
+ }
667
+ /** No-op sink used until an app installs one. */
668
+ declare const noopAuditSink: AuditSink;
669
+ /** Default sink: one JSON object per line on stdout — append-only at the OS level. */
670
+ declare function createConsoleAuditSink(): AuditSink;
671
+ declare function setAuditSink(sink: AuditSink): void;
672
+ declare function getAuditSink(): AuditSink;
673
+ /** Best-effort client IP from proxy headers; null when the request has none. */
674
+ declare function clientIpFromRequest(req: Request): string | null;
675
+ /** Correlation id already assigned to the request by `withRequestLogging`, if any. */
676
+ declare function requestIdFromRequest(req: Request): string | undefined;
677
+ /**
678
+ * Emits an audit entry with the reason (and any metadata) redacted so secret
679
+ * patterns that ride along in error strings or metadata objects never reach
680
+ * the sink.
681
+ */
682
+ declare function audit(entry: AuditEntry): void;
683
+ interface AuditEventInput {
684
+ userId: string | null;
685
+ ip: string | null;
686
+ reason?: string;
687
+ provider?: string;
688
+ requestId?: string;
689
+ sessionHash?: string;
690
+ metadata?: Record<string, unknown>;
691
+ }
692
+ /** Convenience helpers for the framework's own events and app-driven events. */
693
+ declare function auditLoginSuccess(input: AuditEventInput & {
694
+ userId: string;
695
+ }): void;
696
+ declare function auditLoginFailure(input: AuditEventInput): void;
697
+ declare function auditLogout(input: AuditEventInput): void;
698
+ declare function auditPasswordChanged(input: AuditEventInput & {
699
+ userId: string;
700
+ }): void;
701
+ declare function auditRoleChanged(input: AuditEventInput & {
702
+ userId: string;
703
+ }): void;
704
+ declare function auditPermissionDenied(input: AuditEventInput): void;
705
+ declare function auditSessionRevoked(input: AuditEventInput & {
706
+ userId: string;
707
+ }): void;
708
+
709
+ /**
710
+ * Process-level crash handlers for the Bun server path.
711
+ *
712
+ * Request-scoped errors are contained inside `createApp`'s fetch boundary
713
+ * (route handlers, API handlers, server actions). What still escapes to the
714
+ * event loop is a crash *outside* the request lifecycle — a throw during
715
+ * module eval, a rejected promise from a background sweep, a timer callback —
716
+ * which would otherwise take the whole process down with it.
717
+ *
718
+ * These handlers report the crash through the configured error reporter so an
719
+ * operator sees it, rather than dying silently (or staying up silently with no
720
+ * trace of what happened). By default the process keeps serving; set
721
+ * `exitOnCrash` to opt into crash-on-error semantics (e.g. when running under
722
+ * a supervisor like systemd/K8s that restarts the box).
723
+ */
724
+ interface ProcessCrashHandlerOptions {
725
+ /** Phase tag forwarded to the error reporter. Defaults to "api". */
726
+ phase?: "ssr" | "action" | "api" | "loader";
727
+ /** When true, `process.exit(1)` after reporting. Defaults to false. */
728
+ exitOnCrash?: boolean;
729
+ }
730
+ /** Registers `uncaughtException`/`unhandledRejection` handlers; returns a disposer. */
731
+ declare function installProcessCrashHandlers(options?: ProcessCrashHandlerOptions): () => void;
732
+
608
733
  /**
609
734
  * Structured JSON logging. Replaces ad-hoc `console.log` with one JSON
610
735
  * object per line — easy to ingest into Datadog, Grafana Loki, Kibana, etc.
@@ -626,6 +751,33 @@ declare const logger: Logger;
626
751
  */
627
752
  declare function withRequestLogging<Server = unknown>(handler: (req: Request, server?: Server) => Response | Promise<Response>): (req: Request, server?: Server) => Promise<Response>;
628
753
 
754
+ /**
755
+ * Secret redaction for structured logging.
756
+ *
757
+ * Server logs can silently echo secrets — a DB driver error interpolating a
758
+ * connection string, an app error whose message contains a token, or a caller
759
+ * passing `{ password }` into the logger. This is separate from the build-time
760
+ * env-leak scanner: that one protects client bundles; this one keeps values
761
+ * shaped like secrets out of anything emitted to the log sink, in dev and prod
762
+ * alike. It is belt-and-suspenders, not a substitute for not logging secrets —
763
+ * the pass is deliberately conservative (a key containing "token" anywhere is
764
+ * treated as sensitive).
765
+ */
766
+ declare const REDACTED = "[REDACTED]";
767
+ /** True when a field key looks like it holds a secret value. */
768
+ declare function isSensitiveKey(key: string): boolean;
769
+ /** Masks bearer/basic credentials and inline `Authorization: ...` values in a string. */
770
+ declare function redactString(input: string): string;
771
+ /**
772
+ * Recursively redacts a value before it is serialized to a log line:
773
+ * - values under a sensitive key names are replaced with {@link REDACTED};
774
+ * - string values (including error messages) are scanned for embedded bearer
775
+ * tokens / `Authorization:` values;
776
+ * - arrays and plain objects are walked recursively. Non-plain objects and
777
+ * primitives other than strings pass through untouched.
778
+ */
779
+ declare function redactValue(value: unknown, depth?: number): unknown;
780
+
629
781
  interface RenderOptions {
630
782
  title?: string;
631
783
  islandScripts?: string[];
@@ -649,6 +801,13 @@ interface RenderOptions {
649
801
  * to eliminate the two-pass discovery render.
650
802
  */
651
803
  resolveIslandScripts?: () => Promise<string[]>;
804
+ /**
805
+ * CSP nonce applied to every inline script the shell emits. Lets responses
806
+ * drop `'unsafe-inline'` from the default `script-src` (see
807
+ * `buildSecurityHeaders`) while keeping client navigation, live-reload and
808
+ * island hydration props working.
809
+ */
810
+ cspNonce?: string;
652
811
  }
653
812
  interface LoaderArgs {
654
813
  params: Record<string, string>;
@@ -659,6 +818,42 @@ declare function renderPage(node: ReactNode, options?: RenderOptions): string;
659
818
  declare function renderStaticPage(node: ReactNode, options?: RenderOptions): string;
660
819
  declare function renderStreamingPage(node: ReactNode, options?: RenderOptions): Promise<ReadableStream<Uint8Array>>;
661
820
 
821
+ /**
822
+ * Request body size enforcement.
823
+ *
824
+ * The framework buffers whatever a route, server function, or API handler asks
825
+ * for (`req.json()`, `req.text()`, `req.formData()`, ...) in memory before any
826
+ * validation runs. Without a byte budget an attacker can POST an arbitrarily
827
+ * large body and drive the single Bun process toward OOM — the exact crash
828
+ * class the hardening work on #85 is trying to contain. This module gives
829
+ * `createApp` a `maxBodySize` knob applied ahead of route/action dispatch.
830
+ */
831
+ declare const DEFAULT_MAX_BODY_SIZE = 1048576;
832
+ /**
833
+ * The error a wrapped request body stream is rejected with the moment it
834
+ * exceeds the configured `maxBodySize`. Kept distinct from a generic stream
835
+ * error so dispatch paths can map it to a 413 instead of a generic 500.
836
+ */
837
+ declare class RequestBodyTooLargeError extends Error {
838
+ readonly maxBytes: number;
839
+ constructor(maxBytes: number);
840
+ }
841
+ /**
842
+ * Enforces `maxBytes` on a request body.
843
+ *
844
+ * - When `Content-Length` is declared and exceeds the limit, the request is
845
+ * rejected immediately with a 413 `Response`.
846
+ * - When `Content-Length` is absent (chunked transfer) the body is wrapped in
847
+ * a counting stream that errors with {@link RequestBodyTooLargeError} the
848
+ * instant the limit is crossed. The wrapper only pulls from the source as
849
+ * fast as the downstream consumer reads, so an oversized body is aborted
850
+ * before it is ever fully buffered, instead of being read wholesale.
851
+ *
852
+ * Returns the (possibly wrapped) request, or a 413 `Response` when the
853
+ * declared size is already over the limit.
854
+ */
855
+ declare function enforceRequestBodySize(req: Request, maxBytes: number): Request | Response;
856
+
662
857
  /**
663
858
  * Compiler boundary between server-only environment variables and the
664
859
  * client bundle. Convention: only variables prefixed with `THEXJS_PUBLIC_`
@@ -688,4 +883,4 @@ declare function resetServerFunctions(): void;
688
883
  declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
689
884
  declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
690
885
 
691
- export { type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CounterSeries, type CreateAppOptions, type CsrfOptions, type CsrfResult, DEFAULT_HISTOGRAM_BUCKETS_MS, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, type HistogramSeries, Image, type ImageProps, type ImageProxyOptions, type InMemoryMetricsOptions, type InMemoryMetricsReporter, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MetricLabels, type MetricsReporter, type MetricsSnapshot, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, type OtelMeterLike, type OtelTracerLike, PUBLIC_ENV_PREFIX, type RateLimitOptions, type RateLimitResult, type RateLimitStore, type ReadinessResult, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, SRCSET_WIDTHS, type SecurityHeadersOptions, type SentryLike, applySecurityHeaders, assertNoEnvLeakage, build, buildSecurityHeaders, buildSrcSet, checkCsrf, combineReporters, composeMiddleware, createApp, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, defineConfig, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getErrorReporter, getServerFunctionHandler, logger, noopMetrics, noopReporter, rateLimitMiddleware, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, resetServerFunctions, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setErrorReporter, setImageRemoteHosts, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, writeManifest };
886
+ export { type AuditEntry, type AuditEvent, type AuditSink, type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CounterSeries, type CreateAppOptions, type CsrfOptions, type CsrfResult, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, type HistogramSeries, Image, type ImageProps, type ImageProxyOptions, type InMemoryMetricsOptions, type InMemoryMetricsReporter, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MetricLabels, type MetricsReporter, type MetricsSnapshot, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, type OtelMeterLike, type OtelTracerLike, PUBLIC_ENV_PREFIX, type ProcessCrashHandlerOptions, REDACTED, type RateLimitOptions, type RateLimitResult, type RateLimitStore, type ReadinessResult, RequestBodyTooLargeError, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, SRCSET_WIDTHS, type SecurityHeadersOptions, type SentryLike, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, createApp, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, installProcessCrashHandlers, isSensitiveKey, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, writeManifest };
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import {
2
+ DEFAULT_MAX_BODY_SIZE,
2
3
  EnvLeakageError,
3
4
  PUBLIC_ENV_PREFIX,
5
+ RequestBodyTooLargeError,
4
6
  assertNoEnvLeakage,
5
7
  buildIslandBundleInMemory,
6
8
  bundleRouteIslandsToDisk,
@@ -8,6 +10,7 @@ import {
8
10
  combineReporters,
9
11
  createOtelReporter,
10
12
  createSentryReporter,
13
+ enforceRequestBodySize,
11
14
  extractParams,
12
15
  findLayoutChain,
13
16
  findLeakedEnvKeys,
@@ -34,7 +37,7 @@ import {
34
37
  verifyOrigin,
35
38
  withCsrfCookie,
36
39
  writeManifest
37
- } from "./chunk-PQ7ZVWEJ.js";
40
+ } from "./chunk-VAWSOVGY.js";
38
41
 
39
42
  // src/build.ts
40
43
  import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
@@ -384,13 +387,16 @@ function buildHeadExtras(stylesheet) {
384
387
  return stylesheet ? `
385
388
  <link rel="stylesheet" href="${escapeHtml2(stylesheet)}" />` : "";
386
389
  }
387
- function buildNavScriptTag(clientNav) {
390
+ function nonceAttr(nonce) {
391
+ return nonce ? ` nonce="${nonce}"` : "";
392
+ }
393
+ function buildNavScriptTag(clientNav, nonce) {
388
394
  return clientNav === false ? "" : `
389
- <script>${CLIENT_NAV_SCRIPT}</script>`;
395
+ <script${nonceAttr(nonce)}>${CLIENT_NAV_SCRIPT}</script>`;
390
396
  }
391
- function buildLiveReloadTag(liveReload) {
397
+ function buildLiveReloadTag(liveReload, nonce) {
392
398
  return liveReload ? `
393
- <script>${LIVE_RELOAD_SCRIPT}</script>` : "";
399
+ <script${nonceAttr(nonce)}>${LIVE_RELOAD_SCRIPT}</script>` : "";
394
400
  }
395
401
  function htmlShell(title, headExtras, propsScript, scripts, bodySlot, navScriptTag, liveReloadTag) {
396
402
  const finalScripts = scripts ?? "";
@@ -426,8 +432,9 @@ async function renderPageOnce(node, options = {}) {
426
432
  function buildShellHtml(body, options, islandScripts) {
427
433
  const { islandProps } = options;
428
434
  const title = options.title ?? "x app";
435
+ const nonce = options.cspNonce;
429
436
  const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
430
- const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
437
+ const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
431
438
  const islandScriptsHtml = islandScripts.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
432
439
  return htmlShell(
433
440
  title,
@@ -435,8 +442,8 @@ function buildShellHtml(body, options, islandScripts) {
435
442
  propsScript,
436
443
  islandScriptsHtml,
437
444
  body,
438
- buildNavScriptTag(options.clientNav),
439
- buildLiveReloadTag(options.liveReload)
445
+ buildNavScriptTag(options.clientNav, nonce),
446
+ buildLiveReloadTag(options.liveReload, nonce)
440
447
  );
441
448
  }
442
449
  function pumpStreamingResponse(source, options) {
@@ -492,10 +499,11 @@ function pumpStreamingResponse(source, options) {
492
499
  async function renderStreamingPage(node, options = {}) {
493
500
  const { islandScripts, islandProps } = options;
494
501
  const title = escapeHtml2(options.title ?? "x app");
502
+ const nonce = options.cspNonce;
495
503
  const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
496
- const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
497
- const navScriptTag = buildNavScriptTag(options.clientNav);
498
- const liveReloadTag = buildLiveReloadTag(options.liveReload);
504
+ const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
505
+ const navScriptTag = buildNavScriptTag(options.clientNav, nonce);
506
+ const liveReloadTag = buildLiveReloadTag(options.liveReload, nonce);
499
507
  const headExtras = buildHeadExtras(options.stylesheet);
500
508
  const footer = `</div>${navScriptTag}
501
509
  ${liveReloadTag} </body>
@@ -791,17 +799,10 @@ function buildServerEntry(opts, configImportPath, stylesheetHref) {
791
799
  "",
792
800
  "// Request-level errors are caught inside createApp's fetch boundary;",
793
801
  "// anything that still escapes (a throw outside the request lifecycle,",
794
- "// a rejected promise from a background sweep) is routed to the error",
795
- "// reporter so the box reports instead of dying.",
796
- 'const { reportException } = await import("@thexjs/core");',
797
- 'process.on("uncaughtException", (err) => {',
798
- ' reportException(err, { phase: "api" });',
799
- ' console.error("[x] uncaught exception:", err);',
800
- "});",
801
- 'process.on("unhandledRejection", (reason) => {',
802
- ' reportException(reason, { phase: "api" });',
803
- ' console.error("[x] unhandled rejection:", reason);',
804
- "});"
802
+ "// a rejected promise from a background sweep) is reported through the",
803
+ "// error reporter so the box reports instead of dying silently.",
804
+ 'const { installProcessCrashHandlers } = await import("@thexjs/core");',
805
+ "installProcessCrashHandlers();"
805
806
  );
806
807
  return lines.join("\n");
807
808
  }
@@ -938,6 +939,7 @@ function renderErrorOverlay(error) {
938
939
  }
939
940
 
940
941
  // src/images/proxy.ts
942
+ var DEFAULT_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
941
943
  var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
942
944
  "image/png",
943
945
  "image/jpeg",
@@ -946,8 +948,137 @@ var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
946
948
  "image/avif",
947
949
  "image/x-icon"
948
950
  ]);
951
+ var RFC2606_RESERVED_TLD = /\.(example|test|invalid|localhost)$|^(localhost)$/;
952
+ var UpstreamImageTooLargeError = class extends Error {
953
+ maxBytes;
954
+ constructor(maxBytes) {
955
+ super(`Upstream image exceeds the ${maxBytes} byte limit`);
956
+ this.name = "UpstreamImageTooLargeError";
957
+ this.maxBytes = maxBytes;
958
+ }
959
+ };
960
+ function isIpLiteral(host) {
961
+ const stem = host.startsWith("[") ? host.slice(1, -1) : host;
962
+ return /^\d{1,3}(\.\d{1,3}){3}$/.test(stem) || stem.includes(":");
963
+ }
964
+ function isPrivateOrReservedAddress(host) {
965
+ const stem = host.startsWith("[") ? host.slice(1, -1) : host;
966
+ if (!stem.includes(":") && /^\d{1,3}(\.\d{1,3}){3}$/.test(stem)) {
967
+ const parts = stem.split(".").map((o) => Number(o));
968
+ if (parts.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) return false;
969
+ return isPrivateOrReservedIPv4(parts);
970
+ }
971
+ if (stem.includes(":")) {
972
+ const v4Match = /(\d{1,3}(?:\.\d{1,3}){3})$/.exec(stem);
973
+ if (v4Match) {
974
+ const octets = (v4Match[1] ?? "").split(".").map((o) => Number(o));
975
+ return isPrivateOrReservedIPv4(octets);
976
+ }
977
+ }
978
+ const groups = ipv6Groups(stem);
979
+ if (groups) return isPrivateOrReservedIPv6(groups);
980
+ return false;
981
+ }
982
+ function isPrivateOrReservedIPv4(parts) {
983
+ const [a = 0, b = 0, c = 0] = parts;
984
+ return a === 0 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 127 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127 || a === 192 && b === 0 && c === 0 || a === 192 && b === 0 && c === 2 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && c === 100 || a === 203 && b === 0 && c === 113 || a >= 224;
985
+ }
986
+ function ipv6Groups(ip) {
987
+ let head = ip;
988
+ let tailV4 = null;
989
+ const lastColon = ip.lastIndexOf(":");
990
+ if (lastColon !== -1) {
991
+ const tail = ip.slice(lastColon + 1);
992
+ if (tail.includes(".")) {
993
+ const [v0 = 0, v1 = 0, v2 = 0, v3 = 0] = tail.split(".").map((o) => Number(o));
994
+ if (v0 > 255 || v1 > 255 || v2 > 255 || v3 > 255) {
995
+ return null;
996
+ }
997
+ tailV4 = [v0 * 256 + v1, v2 * 256 + v3];
998
+ head = ip.slice(0, lastColon);
999
+ }
1000
+ }
1001
+ const doubleColon = head.indexOf("::");
1002
+ let left = "";
1003
+ let right = "";
1004
+ if (doubleColon !== -1) {
1005
+ left = head.slice(0, doubleColon);
1006
+ right = head.slice(doubleColon + 2);
1007
+ } else {
1008
+ left = head;
1009
+ }
1010
+ const parseGroups = (s, out) => {
1011
+ if (s === "") return true;
1012
+ for (const part of s.split(":")) {
1013
+ if (!/^[0-9a-fA-F]{1,4}$/.test(part)) return false;
1014
+ out.push(Number.parseInt(part, 16));
1015
+ }
1016
+ return true;
1017
+ };
1018
+ const l = [];
1019
+ const r = [];
1020
+ if (!parseGroups(left, l) || !parseGroups(right, r)) return null;
1021
+ if (doubleColon !== -1) {
1022
+ const zeros = 8 - l.length - r.length - (tailV4?.length ?? 0);
1023
+ if (zeros < 1) return null;
1024
+ return [...l, ...new Array(zeros).fill(0), ...r, ...tailV4 ?? []];
1025
+ }
1026
+ const all = [...l, ...tailV4 ?? [], ...r];
1027
+ return all.length === 8 ? all : null;
1028
+ }
1029
+ function isPrivateOrReservedIPv6(groups) {
1030
+ const [a = 0, b = 0, , , , , , last = 0] = groups;
1031
+ return a === 0 && last === 1 || // loopback ::1
1032
+ groups.every((g) => g === 0) || // unspecified ::
1033
+ (a & 65024) === 64512 || // unique local fc00::/7
1034
+ (a & 65472) === 65152 || // link-local fe80::/10
1035
+ (a & 65280) === 65280 || // multicast ff00::/8
1036
+ a === 8193 && b === 3512 || // documentation 2001:db8::/32
1037
+ a === 100 && b === 65435 || // NAT64 64:ff9b::/96
1038
+ a === 8193 && b === 16;
1039
+ }
1040
+ async function resolveHostDefault(hostname) {
1041
+ if (RFC2606_RESERVED_TLD.test(hostname)) return [];
1042
+ try {
1043
+ const results = await Bun.dns.lookup(hostname);
1044
+ return results.map((r) => r.address);
1045
+ } catch {
1046
+ return [];
1047
+ }
1048
+ }
1049
+ function enforceImageByteCount(body, maxBytes) {
1050
+ if (body === null) return null;
1051
+ const source = body;
1052
+ const { readable, writable } = new TransformStream();
1053
+ const writer = writable.getWriter();
1054
+ let total = 0;
1055
+ const pump = async () => {
1056
+ const reader = source.getReader();
1057
+ try {
1058
+ while (true) {
1059
+ const { done, value } = await reader.read();
1060
+ if (done) break;
1061
+ total += value.byteLength;
1062
+ if (total > maxBytes) {
1063
+ await reader.cancel().catch(() => {
1064
+ });
1065
+ await writer.abort(new UpstreamImageTooLargeError(maxBytes));
1066
+ return;
1067
+ }
1068
+ await writer.write(value);
1069
+ }
1070
+ await writer.close();
1071
+ } catch (err) {
1072
+ await writer.abort(err);
1073
+ }
1074
+ };
1075
+ void pump();
1076
+ return readable;
1077
+ }
949
1078
  function createImageProxyHandler(options = {}) {
950
1079
  const allowedHosts = new Set(options.remoteHosts ?? []);
1080
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_IMAGE_BYTES;
1081
+ const resolveHost = options.resolveHost ?? resolveHostDefault;
951
1082
  return async (req) => {
952
1083
  const reqUrl = new URL(req.url);
953
1084
  if (reqUrl.pathname !== "/_x/image") return null;
@@ -964,6 +1095,23 @@ function createImageProxyHandler(options = {}) {
964
1095
  if (!allowedUrl(parsed)) {
965
1096
  return new Response("host not allow-listed for image proxy", { status: 403 });
966
1097
  }
1098
+ if (isIpLiteral(parsed.hostname) && isPrivateOrReservedAddress(parsed.hostname)) {
1099
+ return new Response("target is a private or reserved address", { status: 403 });
1100
+ }
1101
+ if (!isIpLiteral(parsed.hostname)) {
1102
+ let publicIp = true;
1103
+ try {
1104
+ const ips = await resolveHost(parsed.hostname);
1105
+ publicIp = !ips.some((ip) => isPrivateOrReservedAddress(ip));
1106
+ } catch {
1107
+ publicIp = true;
1108
+ }
1109
+ if (!publicIp) {
1110
+ return new Response("target resolves to a private or reserved address", {
1111
+ status: 403
1112
+ });
1113
+ }
1114
+ }
967
1115
  const wParam = reqUrl.searchParams.get("w");
968
1116
  const qParam = reqUrl.searchParams.get("q");
969
1117
  if (wParam !== null) {
@@ -994,6 +1142,25 @@ function createImageProxyHandler(options = {}) {
994
1142
  if (!allowedUrl(next)) {
995
1143
  return new Response("upstream redirected off the allow-list", { status: 403 });
996
1144
  }
1145
+ if (isIpLiteral(next.hostname) && isPrivateOrReservedAddress(next.hostname)) {
1146
+ return new Response("upstream redirected to a private or reserved address", {
1147
+ status: 403
1148
+ });
1149
+ }
1150
+ if (!isIpLiteral(next.hostname)) {
1151
+ let publicIp = true;
1152
+ try {
1153
+ const ips = await resolveHost(next.hostname);
1154
+ publicIp = !ips.some((ip) => isPrivateOrReservedAddress(ip));
1155
+ } catch {
1156
+ publicIp = true;
1157
+ }
1158
+ if (!publicIp) {
1159
+ return new Response("upstream redirect resolves to a private or reserved address", {
1160
+ status: 403
1161
+ });
1162
+ }
1163
+ }
997
1164
  upstream = await fetch(next, { redirect: "manual" });
998
1165
  }
999
1166
  } catch (err) {
@@ -1010,7 +1177,13 @@ function createImageProxyHandler(options = {}) {
1010
1177
  if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
1011
1178
  return new Response("upstream did not return an image", { status: 502 });
1012
1179
  }
1013
- return new Response(upstream.body, {
1180
+ const contentLength = upstream.headers.get("content-length");
1181
+ if (contentLength !== null && Number(contentLength) > maxBytes) {
1182
+ await upstream.body?.cancel().catch(() => {
1183
+ });
1184
+ return new Response("upstream image exceeds the size limit", { status: 502 });
1185
+ }
1186
+ return new Response(enforceImageByteCount(upstream.body, maxBytes), {
1014
1187
  status: 200,
1015
1188
  headers: {
1016
1189
  "Content-Type": contentType,
@@ -1106,13 +1279,36 @@ function createHealthCheckHandler(options = {}) {
1106
1279
  };
1107
1280
  }
1108
1281
 
1282
+ // src/observability/redact.ts
1283
+ var REDACTED = "[REDACTED]";
1284
+ var SENSITIVE_KEY_RE = /(password|passwd|token|secret|authorization|cookie|session|credential|api[_ -]?key|private[_ -]?key|access[_ -]?key|refresh[_ -]?token|bearer)/i;
1285
+ function isSensitiveKey(key) {
1286
+ return SENSITIVE_KEY_RE.test(key);
1287
+ }
1288
+ function redactString(input) {
1289
+ return input.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=:-]+/gi, "$1 " + REDACTED).replace(/\b(?:authorization|auth)\s*[:=]\s*[^\s,;]+/gi, "$1 " + REDACTED);
1290
+ }
1291
+ function redactValue(value, depth = 0) {
1292
+ if (typeof value === "string") return redactString(value);
1293
+ if (depth > 10) return value;
1294
+ if (Array.isArray(value)) return value.map((v) => redactValue(v, depth + 1));
1295
+ if (value !== null && typeof value === "object") {
1296
+ const out = {};
1297
+ for (const [key, val] of Object.entries(value)) {
1298
+ out[key] = isSensitiveKey(key) ? REDACTED : redactValue(val, depth + 1);
1299
+ }
1300
+ return out;
1301
+ }
1302
+ return value;
1303
+ }
1304
+
1109
1305
  // src/observability/logger.ts
1110
1306
  function write(level, message, fields) {
1111
1307
  const entry = {
1112
1308
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1113
1309
  level,
1114
- message,
1115
- ...fields
1310
+ message: redactString(message),
1311
+ ...redactValue(fields)
1116
1312
  };
1117
1313
  const line = JSON.stringify(entry);
1118
1314
  if (level === "error") {
@@ -1157,7 +1353,9 @@ function withRequestLogging(handler) {
1157
1353
  method: req.method,
1158
1354
  status: 500,
1159
1355
  durationMs: Math.round(performance.now() - start),
1160
- error: err instanceof Error ? err.message : String(err)
1356
+ // Redacted before emission — a throwing driver or app error whose
1357
+ // message embeds a secret must never leak it into the log sink.
1358
+ error: redactString(err instanceof Error ? err.message : String(err))
1161
1359
  });
1162
1360
  throw err;
1163
1361
  }
@@ -1322,10 +1520,12 @@ function withRequestMetrics(reporter, handler) {
1322
1520
  }
1323
1521
 
1324
1522
  // src/security/headers.ts
1325
- var DEFAULT_CSP = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'";
1523
+ function defaultCsp(nonce) {
1524
+ return nonce ? `default-src 'self'; script-src 'self' 'nonce-${nonce}'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'` : "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'";
1525
+ }
1326
1526
  function buildSecurityHeaders(options = {}) {
1327
1527
  const headers = new Headers();
1328
- const csp = options.contentSecurityPolicy ?? DEFAULT_CSP;
1528
+ const csp = options.contentSecurityPolicy ?? defaultCsp(options.cspNonce);
1329
1529
  if (csp !== false) headers.set("Content-Security-Policy", csp);
1330
1530
  const hstsMaxAge = options.hstsMaxAge ?? 15552e3;
1331
1531
  if (hstsMaxAge !== false) {
@@ -1369,9 +1569,9 @@ var IsrCache = class {
1369
1569
  }
1370
1570
  return entry;
1371
1571
  }
1372
- set(key, html) {
1572
+ set(key, html, cspNonce) {
1373
1573
  this.entries.delete(key);
1374
- this.entries.set(key, { html, timestamp: Date.now() });
1574
+ this.entries.set(key, { html, timestamp: Date.now(), cspNonce });
1375
1575
  this.evict();
1376
1576
  }
1377
1577
  delete(key) {
@@ -1403,13 +1603,12 @@ var IsrCache = class {
1403
1603
  */
1404
1604
  getOrCompute(key, compute) {
1405
1605
  const cached = this.get(key);
1406
- if (cached) return Promise.resolve(cached.html);
1606
+ if (cached) return Promise.resolve({ html: cached.html, cspNonce: cached.cspNonce });
1407
1607
  const existing = this.inFlight.get(key);
1408
1608
  if (existing) return existing;
1409
1609
  const promise = compute().then((result) => {
1410
- if (typeof result === "string") {
1411
- this.set(key, result);
1412
- }
1610
+ if (result instanceof Response) return result;
1611
+ this.set(key, result.html, result.cspNonce);
1413
1612
  return result;
1414
1613
  }).finally(() => {
1415
1614
  this.inFlight.delete(key);
@@ -1579,7 +1778,7 @@ function wrapWithLayouts(Component, params, loaderData, layoutModules) {
1579
1778
  }
1580
1779
  return content;
1581
1780
  }
1582
- function renderContentPage(content, stylesheet, dev = false) {
1781
+ function renderContentPage(content, stylesheet, dev = false, nonce) {
1583
1782
  const title = content.frontmatter.title ?? content.slug;
1584
1783
  const bodyHtml = renderMarkdown(content.body);
1585
1784
  const body = renderPage(
@@ -1592,7 +1791,12 @@ function renderContentPage(content, stylesheet, dev = false) {
1592
1791
  dangerouslySetInnerHTML: { __html: bodyHtml }
1593
1792
  })
1594
1793
  ),
1595
- { title, stylesheet, liveReload: dev }
1794
+ {
1795
+ title,
1796
+ stylesheet,
1797
+ liveReload: dev,
1798
+ ...nonce ? { cspNonce: nonce } : {}
1799
+ }
1596
1800
  );
1597
1801
  return body;
1598
1802
  }
@@ -1654,23 +1858,42 @@ async function createApp(options) {
1654
1858
  const healthHandler = createHealthCheckHandler(options.observability?.health ?? {});
1655
1859
  const metricsReporter = options.observability?.metrics;
1656
1860
  const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
1861
+ const maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;
1657
1862
  const securityHeadersOptions = options.security?.headers;
1658
1863
  const loggingEnabled = options.observability?.logging ?? true;
1659
1864
  const imageProxyHandler = createImageProxyHandler(options.images);
1865
+ const CSP_NONCE_HEADER = "x-csp-nonce";
1866
+ function generateCspNonce() {
1867
+ const bytes = new Uint8Array(16);
1868
+ crypto.getRandomValues(bytes);
1869
+ let bin = "";
1870
+ for (const byte of bytes) bin += String.fromCharCode(byte);
1871
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1872
+ }
1660
1873
  function withResponseHardening(res) {
1661
- return securityHeadersOptions === false ? res : applySecurityHeaders(res, securityHeadersOptions);
1874
+ if (securityHeadersOptions === false) return res;
1875
+ const cspNonce = res.headers.get(CSP_NONCE_HEADER) ?? void 0;
1876
+ if (cspNonce) res.headers.delete(CSP_NONCE_HEADER);
1877
+ return applySecurityHeaders(res, {
1878
+ ...securityHeadersOptions,
1879
+ ...cspNonce ? { cspNonce } : {}
1880
+ });
1662
1881
  }
1663
1882
  async function renderNotFound(_req) {
1664
1883
  const content = notFoundLayout ? createElement2(notFoundLayout, null, createElement2(notFoundComponent, { params: {} })) : createElement2(notFoundComponent, { params: {} });
1884
+ const cspNonce = generateCspNonce();
1665
1885
  const html = renderPage(content, {
1666
1886
  title: "404 \u2014 Not Found",
1667
1887
  stylesheet: stylesheetHref,
1668
- liveReload: dev
1888
+ liveReload: dev,
1889
+ cspNonce
1669
1890
  });
1670
- return new Response(html, {
1891
+ const res = new Response(html, {
1671
1892
  status: 404,
1672
1893
  headers: { "Content-Type": "text/html; charset=utf-8" }
1673
1894
  });
1895
+ res.headers.set(CSP_NONCE_HEADER, cspNonce);
1896
+ return res;
1674
1897
  }
1675
1898
  const makeApiHandler = (route, module) => async (req) => {
1676
1899
  try {
@@ -1686,6 +1909,9 @@ async function createApp(options) {
1686
1909
  }
1687
1910
  return new Response(`Method ${method} not allowed`, { status: 405 });
1688
1911
  } catch (err) {
1912
+ if (err instanceof RequestBodyTooLargeError) {
1913
+ return new Response("Payload too large", { status: 413 });
1914
+ }
1689
1915
  reportException(err, { route: route.routePath, phase: "api" });
1690
1916
  metricsReporter?.incr("x_http_errors_total", 1, { phase: "api" });
1691
1917
  console.error("[x] API handler error:", err);
@@ -1718,9 +1944,9 @@ async function createApp(options) {
1718
1944
  if (mode === "server") {
1719
1945
  let loaderData = {};
1720
1946
  if (loader) {
1721
- const result = await loader(ctx);
1722
- if (result instanceof Response) return result;
1723
- loaderData = result;
1947
+ const result2 = await loader(ctx);
1948
+ if (result2 instanceof Response) return result2;
1949
+ loaderData = result2;
1724
1950
  }
1725
1951
  const registry = createIslandRegistry();
1726
1952
  const content = createElement2(
@@ -1728,9 +1954,11 @@ async function createApp(options) {
1728
1954
  { registry },
1729
1955
  wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1730
1956
  );
1957
+ const cspNonce = generateCspNonce();
1731
1958
  const stream = await renderStreamingPage(content, {
1732
1959
  stylesheet: stylesheetHref,
1733
1960
  liveReload: dev,
1961
+ cspNonce,
1734
1962
  ...islandScripts === void 0 ? {
1735
1963
  // Single-render mode: islands register into `registry`
1736
1964
  // during the one render that produces the HTML, and the
@@ -1744,29 +1972,33 @@ async function createApp(options) {
1744
1972
  metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
1745
1973
  }
1746
1974
  });
1747
- return new Response(stream, {
1975
+ const res2 = new Response(stream, {
1748
1976
  headers: { "Content-Type": "text/html; charset=utf-8" }
1749
1977
  });
1978
+ res2.headers.set(CSP_NONCE_HEADER, cspNonce);
1979
+ return res2;
1750
1980
  }
1751
1981
  const revalidateSeconds = revalidate ?? 0;
1752
1982
  if (revalidateSeconds > 0) {
1753
1983
  const cached = staticCache.get(cacheKey);
1754
1984
  if (cached && Date.now() - cached.timestamp < revalidateSeconds * 1e3) {
1755
- return new Response(cached.html, {
1985
+ const res2 = new Response(cached.html, {
1756
1986
  headers: {
1757
1987
  "Content-Type": "text/html; charset=utf-8",
1758
1988
  "X-Revalidated": "hit"
1759
1989
  }
1760
1990
  });
1991
+ res2.headers.set(CSP_NONCE_HEADER, cached.cspNonce);
1992
+ return res2;
1761
1993
  }
1762
1994
  if (cached) staticCache.delete(cacheKey);
1763
1995
  }
1764
1996
  const computeHtml = async () => {
1765
1997
  let loaderData = {};
1766
1998
  if (loader) {
1767
- const result = await loader(ctx);
1768
- if (result instanceof Response) return result;
1769
- loaderData = result;
1999
+ const result2 = await loader(ctx);
2000
+ if (result2 instanceof Response) return result2;
2001
+ loaderData = result2;
1770
2002
  }
1771
2003
  const registry = createIslandRegistry();
1772
2004
  const content = createElement2(
@@ -1774,32 +2006,39 @@ async function createApp(options) {
1774
2006
  { registry },
1775
2007
  wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1776
2008
  );
1777
- return renderPageOnce(content, {
2009
+ const cspNonce = generateCspNonce();
2010
+ const html = await renderPageOnce(content, {
1778
2011
  stylesheet: stylesheetHref,
1779
2012
  liveReload: dev,
2013
+ cspNonce,
1780
2014
  ...islandScripts === void 0 ? {
1781
2015
  resolveIslandScripts: () => resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries)
1782
2016
  } : { islandScripts }
1783
2017
  });
2018
+ return { html, cspNonce };
1784
2019
  };
1785
2020
  if (revalidateSeconds > 0) {
1786
- const result = await staticCache.getOrCompute(cacheKey, computeHtml);
1787
- if (result instanceof Response) return result;
1788
- return new Response(result, {
2021
+ const result2 = await staticCache.getOrCompute(cacheKey, computeHtml);
2022
+ if (result2 instanceof Response) return result2;
2023
+ const res2 = new Response(result2.html, {
1789
2024
  headers: {
1790
2025
  "Content-Type": "text/html; charset=utf-8",
1791
2026
  "X-Revalidated": "miss"
1792
2027
  }
1793
2028
  });
2029
+ res2.headers.set(CSP_NONCE_HEADER, result2.cspNonce);
2030
+ return res2;
1794
2031
  }
1795
- const html = await computeHtml();
1796
- if (html instanceof Response) return html;
1797
- return new Response(html, {
2032
+ const result = await computeHtml();
2033
+ if (result instanceof Response) return result;
2034
+ const res = new Response(result.html, {
1798
2035
  headers: {
1799
2036
  "Content-Type": "text/html; charset=utf-8",
1800
2037
  "X-Revalidated": "none"
1801
2038
  }
1802
2039
  });
2040
+ res.headers.set(CSP_NONCE_HEADER, result.cspNonce);
2041
+ return res;
1803
2042
  };
1804
2043
  if (middlewareModules.length > 0) {
1805
2044
  const composed = composeMiddleware(middlewareModules, baseHandler);
@@ -1810,6 +2049,9 @@ async function createApp(options) {
1810
2049
  }
1811
2050
  return baseHandler({ params, request: req });
1812
2051
  } catch (err) {
2052
+ if (err instanceof RequestBodyTooLargeError) {
2053
+ return new Response("Payload too large", { status: 413 });
2054
+ }
1813
2055
  reportException(err, { route: route.routePath, phase: "ssr" });
1814
2056
  metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
1815
2057
  console.error("[x] route handler error:", err);
@@ -2012,16 +2254,24 @@ async function createApp(options) {
2012
2254
  const loadedContent = content.map((entry) => ({
2013
2255
  entry,
2014
2256
  handler: async () => {
2015
- const html = renderContentPage(entry, stylesheetHref, dev);
2016
- return new Response(html, {
2257
+ const cspNonce = generateCspNonce();
2258
+ const html = renderContentPage(entry, stylesheetHref, dev, cspNonce);
2259
+ const res = new Response(html, {
2017
2260
  headers: { "Content-Type": "text/html; charset=utf-8" }
2018
2261
  });
2262
+ res.headers.set(CSP_NONCE_HEADER, cspNonce);
2263
+ return res;
2019
2264
  }
2020
2265
  }));
2021
2266
  contentHandlers = loadedContent;
2022
2267
  }
2023
2268
  }
2024
2269
  await buildHandlers();
2270
+ const withBodySizeLimit = (inner) => async (req, server) => {
2271
+ const guarded = enforceRequestBodySize(req, maxBodySize);
2272
+ if (guarded instanceof Response) return guarded;
2273
+ return inner(guarded, server);
2274
+ };
2025
2275
  async function guardFetchErrors(inner, req, server) {
2026
2276
  try {
2027
2277
  return await inner(req, server);
@@ -2046,7 +2296,10 @@ async function createApp(options) {
2046
2296
  let body;
2047
2297
  try {
2048
2298
  body = await req.json();
2049
- } catch {
2299
+ } catch (err) {
2300
+ if (err instanceof RequestBodyTooLargeError) {
2301
+ return new Response("Payload too large", { status: 413 });
2302
+ }
2050
2303
  return new Response("Invalid JSON body", { status: 400 });
2051
2304
  }
2052
2305
  if (body.path) {
@@ -2071,7 +2324,10 @@ async function createApp(options) {
2071
2324
  const text = await req.text();
2072
2325
  if (text.length > 2048) return new Response("Payload too large", { status: 413 });
2073
2326
  body = JSON.parse(text);
2074
- } catch {
2327
+ } catch (err) {
2328
+ if (err instanceof RequestBodyTooLargeError) {
2329
+ return new Response("Payload too large", { status: 413 });
2330
+ }
2075
2331
  return new Response("Invalid JSON body", { status: 400 });
2076
2332
  }
2077
2333
  const error = new Error(body.error ?? "hydration mismatch");
@@ -2221,7 +2477,7 @@ data: ${data}
2221
2477
  }
2222
2478
  return renderNotFound(req);
2223
2479
  };
2224
- const devFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(devFetchInner, req, server));
2480
+ const devFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(devFetchInner), req, server));
2225
2481
  const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2226
2482
  const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchBase) : devFetchBase;
2227
2483
  return {
@@ -2279,7 +2535,7 @@ data: ${data}
2279
2535
  }
2280
2536
  return renderNotFound(req);
2281
2537
  };
2282
- const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(prodFetchInner, req, server));
2538
+ const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(prodFetchInner), req, server));
2283
2539
  const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2284
2540
  const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchBase) : prodFetchBase;
2285
2541
  return {
@@ -2418,9 +2674,123 @@ function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
2418
2674
  }
2419
2675
  );
2420
2676
  }
2677
+
2678
+ // src/observability/audit.ts
2679
+ var noopAuditSink = {
2680
+ write: () => {
2681
+ }
2682
+ };
2683
+ function createConsoleAuditSink() {
2684
+ return {
2685
+ write(entry) {
2686
+ console.log(JSON.stringify(entry));
2687
+ }
2688
+ };
2689
+ }
2690
+ var activeSink = noopAuditSink;
2691
+ function setAuditSink(sink) {
2692
+ activeSink = sink;
2693
+ }
2694
+ function getAuditSink() {
2695
+ return activeSink;
2696
+ }
2697
+ function clientIpFromRequest(req) {
2698
+ const forwarded = req.headers.get("x-forwarded-for");
2699
+ if (forwarded) return forwarded.split(",")[0]?.trim() || null;
2700
+ return req.headers.get("x-real-ip");
2701
+ }
2702
+ function requestIdFromRequest(req) {
2703
+ return req.headers.get("x-request-id") ?? void 0;
2704
+ }
2705
+ function audit(entry) {
2706
+ const redacted = {
2707
+ timestamp: entry.timestamp,
2708
+ event: entry.event,
2709
+ userId: entry.userId,
2710
+ ip: entry.ip,
2711
+ ...entry.reason !== void 0 ? { reason: redactString(entry.reason) } : {},
2712
+ ...entry.provider !== void 0 ? { provider: entry.provider } : {},
2713
+ ...entry.requestId !== void 0 ? { requestId: entry.requestId } : {},
2714
+ ...entry.sessionHash !== void 0 ? { sessionHash: entry.sessionHash } : {},
2715
+ ...entry.metadata !== void 0 ? { metadata: redactValue(entry.metadata) } : {}
2716
+ };
2717
+ activeSink.write(redacted);
2718
+ }
2719
+ function auditLoginSuccess(input) {
2720
+ audit({
2721
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2722
+ event: "auth.login.success",
2723
+ ...input
2724
+ });
2725
+ }
2726
+ function auditLoginFailure(input) {
2727
+ audit({
2728
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2729
+ event: "auth.login.failure",
2730
+ ...input
2731
+ });
2732
+ }
2733
+ function auditLogout(input) {
2734
+ audit({
2735
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2736
+ event: "auth.logout",
2737
+ ...input
2738
+ });
2739
+ }
2740
+ function auditPasswordChanged(input) {
2741
+ audit({
2742
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2743
+ event: "auth.password_changed",
2744
+ ...input
2745
+ });
2746
+ }
2747
+ function auditRoleChanged(input) {
2748
+ audit({
2749
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2750
+ event: "auth.role_changed",
2751
+ ...input
2752
+ });
2753
+ }
2754
+ function auditPermissionDenied(input) {
2755
+ audit({
2756
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2757
+ event: "auth.permission_denied",
2758
+ ...input
2759
+ });
2760
+ }
2761
+ function auditSessionRevoked(input) {
2762
+ audit({
2763
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2764
+ event: "auth.session_revoked",
2765
+ ...input
2766
+ });
2767
+ }
2768
+
2769
+ // src/observability/crash-handlers.ts
2770
+ function installProcessCrashHandlers(options = {}) {
2771
+ const phase = options.phase ?? "api";
2772
+ const exitOnCrash = options.exitOnCrash ?? false;
2773
+ const onUncaughtException = (error) => {
2774
+ console.error("[x] uncaught exception:", error);
2775
+ reportException(error, { phase });
2776
+ if (exitOnCrash) process.exit(1);
2777
+ };
2778
+ const onUnhandledRejection = (reason) => {
2779
+ console.error("[x] unhandled rejection:", reason);
2780
+ reportException(reason, { phase });
2781
+ if (exitOnCrash) process.exit(1);
2782
+ };
2783
+ process.on("uncaughtException", onUncaughtException);
2784
+ process.on("unhandledRejection", onUnhandledRejection);
2785
+ return () => {
2786
+ process.off("uncaughtException", onUncaughtException);
2787
+ process.off("unhandledRejection", onUnhandledRejection);
2788
+ };
2789
+ }
2421
2790
  export {
2422
2791
  CLIENT_NAV_SCRIPT,
2423
2792
  DEFAULT_HISTOGRAM_BUCKETS_MS,
2793
+ DEFAULT_MAX_BODY_SIZE,
2424
2794
  DefaultNotFound,
2425
2795
  EnvLeakageError,
2426
2796
  Image,
@@ -2428,16 +2798,28 @@ export {
2428
2798
  IslandProvider,
2429
2799
  Link,
2430
2800
  PUBLIC_ENV_PREFIX,
2801
+ REDACTED,
2802
+ RequestBodyTooLargeError,
2431
2803
  SRCSET_WIDTHS,
2432
2804
  applySecurityHeaders,
2433
2805
  assertNoEnvLeakage,
2806
+ audit,
2807
+ auditLoginFailure,
2808
+ auditLoginSuccess,
2809
+ auditLogout,
2810
+ auditPasswordChanged,
2811
+ auditPermissionDenied,
2812
+ auditRoleChanged,
2813
+ auditSessionRevoked,
2434
2814
  build,
2435
2815
  buildSecurityHeaders,
2436
2816
  buildSrcSet,
2437
2817
  checkCsrf,
2818
+ clientIpFromRequest,
2438
2819
  combineReporters,
2439
2820
  composeMiddleware,
2440
2821
  createApp,
2822
+ createConsoleAuditSink,
2441
2823
  createHealthCheckHandler,
2442
2824
  createImageProxyHandler,
2443
2825
  createInMemoryMetrics,
@@ -2447,6 +2829,7 @@ export {
2447
2829
  createRedisRateLimitStore,
2448
2830
  createSentryReporter,
2449
2831
  defineConfig,
2832
+ enforceRequestBodySize,
2450
2833
  escapeHtml,
2451
2834
  findLayoutChain,
2452
2835
  findLeakedEnvKeys,
@@ -2454,12 +2837,18 @@ export {
2454
2837
  generateCsrfToken,
2455
2838
  generateManifestSource,
2456
2839
  generateServerFunctionClient,
2840
+ getAuditSink,
2457
2841
  getErrorReporter,
2458
2842
  getServerFunctionHandler,
2843
+ installProcessCrashHandlers,
2844
+ isSensitiveKey,
2459
2845
  logger,
2846
+ noopAuditSink,
2460
2847
  noopMetrics,
2461
2848
  noopReporter,
2462
2849
  rateLimitMiddleware,
2850
+ redactString,
2851
+ redactValue,
2463
2852
  registerServerFunctions,
2464
2853
  renderErrorOverlay,
2465
2854
  renderMarkdown,
@@ -2467,6 +2856,7 @@ export {
2467
2856
  renderStaticPage,
2468
2857
  renderStreamingPage,
2469
2858
  reportException,
2859
+ requestIdFromRequest,
2470
2860
  resetServerFunctions,
2471
2861
  scanApiDir,
2472
2862
  scanContent,
@@ -2476,6 +2866,7 @@ export {
2476
2866
  scanNotFound,
2477
2867
  scanPages,
2478
2868
  scanRoutes,
2869
+ setAuditSink,
2479
2870
  setErrorReporter,
2480
2871
  setImageRemoteHosts,
2481
2872
  verifyCsrfToken,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "1.3.5",
3
+ "version": "1.3.6",
4
4
  "description": "Full-stack React framework core (router, SSR/SSG renderer, islands, server functions) for the x framework, built on Bun.",
5
5
  "keywords": [
6
6
  "react",