@thexjs/core 1.3.5 → 1.4.0

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.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,105 @@ 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, inline `Authorization: ...` values and URI userinfo (connection strings) 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
+
781
+ /**
782
+ * Request-scoped tracing.
783
+ *
784
+ * `@thexjs/core` never initializes an OpenTelemetry SDK — apps opt in by
785
+ * providing a tracer whose spans match the tiny surface below (the real OTel
786
+ * `startSpan(name, { attributes })` fits). When no tracer is configured the
787
+ * whole layer degrades to synchronous no-ops, and when work runs outside a
788
+ * traced request (a scheduler, a build-time render, a worker thread) phase
789
+ * spans are skipped entirely.
790
+ *
791
+ * Correlation: every span carries the request's `x.requestId` as the
792
+ * `x.requestId` attribute, and the root `x.http` span also records route,
793
+ * method and response status. SDK-level parent/child wiring is the app's
794
+ * concern (it owns the OTel context); this module records the correlation
795
+ * attribute that makes spans drillable.
796
+ */
797
+ interface TraceSpan {
798
+ setAttribute(key: string, value: unknown): void;
799
+ recordException(error: unknown): void;
800
+ setStatus(status: {
801
+ code: number;
802
+ message?: string;
803
+ }): void;
804
+ end(): void;
805
+ }
806
+ /** Minimal surface a tracer must expose. Compatible with OTel's `Tracer`. */
807
+ interface TracerLike {
808
+ startSpan(name: string, options?: {
809
+ attributes?: Record<string, unknown>;
810
+ }): TraceSpan;
811
+ }
812
+ declare function setTracer(tracer: TracerLike): void;
813
+ declare function getTracer(): TracerLike;
814
+ /** Matches @opentelemetry/api's SpanStatusCode.ERROR. */
815
+ declare const OTEL_ERROR_STATUS_CODE = 2;
816
+ /**
817
+ * Runs `work` inside a traced request context and the `x.http` root span.
818
+ * `finish` records extra attributes on the root span before it closes (e.g.
819
+ * the response status); `fail` records the error as an exception + error
820
+ * status. Spans started via {@link tracePhase} inside `work` inherit the
821
+ * request id.
822
+ */
823
+ declare function runWithRequestSpan<T>(requestId: string, initAttributes: Record<string, unknown>, work: (finish: (attributes?: Record<string, unknown>) => void, fail: (error: unknown) => void) => Promise<T>): Promise<T>;
824
+ /**
825
+ * Opens a `x.<name>` span carrying the current request's id around `work`,
826
+ * recording any thrown error. Outside a traced request this is a transparent
827
+ * passthrough (no span, no overhead).
828
+ */
829
+ declare function tracePhase<T>(name: string, attributes: Record<string, unknown>, work: () => Promise<T>): Promise<T>;
830
+ /**
831
+ * Synchronous variant of {@link tracePhase}, for sync APIs like
832
+ * `bun:sqlite`. Same rules: no request context → plain passthrough.
833
+ */
834
+ declare function tracePhaseSync<T>(name: string, attributes: Record<string, unknown>, work: () => T): T;
835
+ /**
836
+ * Attribute set for a `x.db` span: driver vendor, the statement's operation
837
+ * family (SELECT/INSERT/...) and a redacted + truncated statement. Statements
838
+ * can embed literals; `redactString` masks bearer/authorization-shaped parts,
839
+ * `maskSqlLiterals` collapses every quoted string, and truncation keeps giant
840
+ * queries out of the trace backend.
841
+ */
842
+ declare function dbTraceAttributes(system: string, statement: string): Record<string, unknown>;
843
+ declare function traceRequestId(req: Request): string;
844
+ /**
845
+ * Wraps a fetch handler so every request gets an `x.http` root span carrying
846
+ * the request id (reusing an inbound `x-request-id` if the ingress already
847
+ * assigned one, otherwise minting one and sharing it via
848
+ * {@link traceRequestId} so downstream wrappers correlate to the same id).
849
+ * The request object is passed through untouched — see {@link traceRequestId}.
850
+ */
851
+ declare function withRequestTracing<Server = unknown>(handler: (req: Request, server?: Server) => Response | Promise<Response>): (req: Request, server?: Server) => Promise<Response>;
852
+
629
853
  interface RenderOptions {
630
854
  title?: string;
631
855
  islandScripts?: string[];
@@ -649,6 +873,13 @@ interface RenderOptions {
649
873
  * to eliminate the two-pass discovery render.
650
874
  */
651
875
  resolveIslandScripts?: () => Promise<string[]>;
876
+ /**
877
+ * CSP nonce applied to every inline script the shell emits. Lets responses
878
+ * drop `'unsafe-inline'` from the default `script-src` (see
879
+ * `buildSecurityHeaders`) while keeping client navigation, live-reload and
880
+ * island hydration props working.
881
+ */
882
+ cspNonce?: string;
652
883
  }
653
884
  interface LoaderArgs {
654
885
  params: Record<string, string>;
@@ -659,6 +890,42 @@ declare function renderPage(node: ReactNode, options?: RenderOptions): string;
659
890
  declare function renderStaticPage(node: ReactNode, options?: RenderOptions): string;
660
891
  declare function renderStreamingPage(node: ReactNode, options?: RenderOptions): Promise<ReadableStream<Uint8Array>>;
661
892
 
893
+ /**
894
+ * Request body size enforcement.
895
+ *
896
+ * The framework buffers whatever a route, server function, or API handler asks
897
+ * for (`req.json()`, `req.text()`, `req.formData()`, ...) in memory before any
898
+ * validation runs. Without a byte budget an attacker can POST an arbitrarily
899
+ * large body and drive the single Bun process toward OOM — the exact crash
900
+ * class the hardening work on #85 is trying to contain. This module gives
901
+ * `createApp` a `maxBodySize` knob applied ahead of route/action dispatch.
902
+ */
903
+ declare const DEFAULT_MAX_BODY_SIZE = 1048576;
904
+ /**
905
+ * The error a wrapped request body stream is rejected with the moment it
906
+ * exceeds the configured `maxBodySize`. Kept distinct from a generic stream
907
+ * error so dispatch paths can map it to a 413 instead of a generic 500.
908
+ */
909
+ declare class RequestBodyTooLargeError extends Error {
910
+ readonly maxBytes: number;
911
+ constructor(maxBytes: number);
912
+ }
913
+ /**
914
+ * Enforces `maxBytes` on a request body.
915
+ *
916
+ * - When `Content-Length` is declared and exceeds the limit, the request is
917
+ * rejected immediately with a 413 `Response`.
918
+ * - When `Content-Length` is absent (chunked transfer) the body is wrapped in
919
+ * a counting stream that errors with {@link RequestBodyTooLargeError} the
920
+ * instant the limit is crossed. The wrapper only pulls from the source as
921
+ * fast as the downstream consumer reads, so an oversized body is aborted
922
+ * before it is ever fully buffered, instead of being read wholesale.
923
+ *
924
+ * Returns the (possibly wrapped) request, or a 413 `Response` when the
925
+ * declared size is already over the limit.
926
+ */
927
+ declare function enforceRequestBodySize(req: Request, maxBytes: number): Request | Response;
928
+
662
929
  /**
663
930
  * Compiler boundary between server-only environment variables and the
664
931
  * client bundle. Convention: only variables prefixed with `THEXJS_PUBLIC_`
@@ -688,4 +955,4 @@ declare function resetServerFunctions(): void;
688
955
  declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
689
956
  declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
690
957
 
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 };
958
+ 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, OTEL_ERROR_STATUS_CODE, 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, type TraceSpan, type TracerLike, 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, dbTraceAttributes, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, getTracer, installProcessCrashHandlers, isSensitiveKey, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };