@thexjs/core 1.7.1 → 1.8.1
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 +2 -2
- package/dist/{chunk-KKWPKTJ6.js → chunk-3VMZCMAF.js} +7 -2
- package/dist/{chunk-OIPCIXYR.js → chunk-OXV2QTWV.js} +10 -2
- package/dist/data.js +1 -1
- package/dist/index.d.ts +102 -8
- package/dist/index.js +87 -12
- package/package.json +1 -1
package/dist/adapter.js
CHANGED
|
@@ -9,8 +9,8 @@ import {
|
|
|
9
9
|
scanNotFound,
|
|
10
10
|
scanPages,
|
|
11
11
|
scanRoutes
|
|
12
|
-
} from "./chunk-
|
|
13
|
-
import "./chunk-
|
|
12
|
+
} from "./chunk-3VMZCMAF.js";
|
|
13
|
+
import "./chunk-OXV2QTWV.js";
|
|
14
14
|
|
|
15
15
|
// src/adapter/bundle.ts
|
|
16
16
|
import { mkdirSync, rmSync, writeFileSync } from "fs";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
OTEL_ERROR_STATUS_CODE,
|
|
3
3
|
tracePhase
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-OXV2QTWV.js";
|
|
5
5
|
|
|
6
6
|
// src/security/env-isolation.ts
|
|
7
7
|
var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
|
|
@@ -661,16 +661,21 @@ function reportHydrationMismatch(error, name) {
|
|
|
661
661
|
}
|
|
662
662
|
}
|
|
663
663
|
|
|
664
|
+
// Preserve roots from a prior hydration entry on the same page (e.g. partial
|
|
665
|
+
// re-hydration). Only initialize when the array doesn't exist yet.
|
|
666
|
+
if (!window.__xIslandRoots) window.__xIslandRoots = [];
|
|
667
|
+
|
|
664
668
|
document.querySelectorAll("[data-island]").forEach((el) => {
|
|
665
669
|
const name = el.getAttribute("data-island");
|
|
666
670
|
if (!name) return;
|
|
667
671
|
const Component = resolveIsland(name);
|
|
668
672
|
if (!Component) return;
|
|
669
|
-
hydrateRoot(el, React.createElement(Component), {
|
|
673
|
+
const root = hydrateRoot(el, React.createElement(Component), {
|
|
670
674
|
onRecoverableError(error) {
|
|
671
675
|
reportHydrationMismatch(error, name);
|
|
672
676
|
},
|
|
673
677
|
});
|
|
678
|
+
window.__xIslandRoots.push(root);
|
|
674
679
|
});
|
|
675
680
|
`;
|
|
676
681
|
}
|
|
@@ -21,6 +21,9 @@ function redactValue(value, depth = 0) {
|
|
|
21
21
|
return value;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
// src/security/validation.ts
|
|
25
|
+
var SAFE_REQUEST_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
|
|
26
|
+
|
|
24
27
|
// src/observability/tracing.ts
|
|
25
28
|
var noopSpan = {
|
|
26
29
|
setAttribute: () => {
|
|
@@ -132,12 +135,16 @@ function dbTraceAttributes(system, statement) {
|
|
|
132
135
|
};
|
|
133
136
|
}
|
|
134
137
|
var requestIds = /* @__PURE__ */ new WeakMap();
|
|
138
|
+
function safeRequestId(raw) {
|
|
139
|
+
if (raw === null) return null;
|
|
140
|
+
return SAFE_REQUEST_ID_RE.test(raw) ? raw : null;
|
|
141
|
+
}
|
|
135
142
|
function traceRequestId(req) {
|
|
136
|
-
return requestIds.get(req) ?? req.headers.get("x-request-id") ?? crypto.randomUUID();
|
|
143
|
+
return requestIds.get(req) ?? safeRequestId(req.headers.get("x-request-id")) ?? crypto.randomUUID();
|
|
137
144
|
}
|
|
138
145
|
function withRequestTracing(handler) {
|
|
139
146
|
return async (req, server) => {
|
|
140
|
-
const existing = req.headers.get("x-request-id");
|
|
147
|
+
const existing = safeRequestId(req.headers.get("x-request-id"));
|
|
141
148
|
const requestId = existing ?? crypto.randomUUID();
|
|
142
149
|
if (!existing) requestIds.set(req, requestId);
|
|
143
150
|
const url = new URL(req.url);
|
|
@@ -154,6 +161,7 @@ function withRequestTracing(handler) {
|
|
|
154
161
|
}
|
|
155
162
|
|
|
156
163
|
export {
|
|
164
|
+
SAFE_REQUEST_ID_RE,
|
|
157
165
|
REDACTED,
|
|
158
166
|
isSensitiveKey,
|
|
159
167
|
redactString,
|
package/dist/data.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -83,6 +83,13 @@ declare function build(options: BuildOptions): Promise<void>;
|
|
|
83
83
|
* - data-no-nav — skip client navigation (full page load)
|
|
84
84
|
* - data-no-prefetch — skip hover prefetch (navigation still works)
|
|
85
85
|
*/
|
|
86
|
+
declare global {
|
|
87
|
+
interface Window {
|
|
88
|
+
__xIslandRoots?: Array<{
|
|
89
|
+
unmount(): void;
|
|
90
|
+
}>;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
86
93
|
declare const CLIENT_NAV_SCRIPT: string;
|
|
87
94
|
|
|
88
95
|
interface Frontmatter {
|
|
@@ -552,6 +559,12 @@ interface CreateAppOptions {
|
|
|
552
559
|
* crossed. Default: 1 MiB.
|
|
553
560
|
*/
|
|
554
561
|
maxBodySize?: number;
|
|
562
|
+
/**
|
|
563
|
+
* Maximum entries in the per-route island bundle caches (both the
|
|
564
|
+
* route→script-list mapping and the URL→bundled-JS file cache). Entries are
|
|
565
|
+
* evicted LRU (oldest-first) once the cap is exceeded. Default: 500.
|
|
566
|
+
*/
|
|
567
|
+
islandCacheMaxEntries?: number;
|
|
555
568
|
/**
|
|
556
569
|
* Pre-resolved routes/actions for runtimes that can't scan the filesystem
|
|
557
570
|
* or dynamically `import()` a `.tsx` file at request time (e.g. Vercel's
|
|
@@ -682,9 +695,18 @@ declare function Link({ href, children, clientNav, prefetch, ...rest }: LinkProp
|
|
|
682
695
|
declare function DefaultNotFound(_props: RouteProps): react.JSX.Element;
|
|
683
696
|
|
|
684
697
|
/**
|
|
685
|
-
* Returns the client IP from a request
|
|
686
|
-
*
|
|
687
|
-
* to
|
|
698
|
+
* Returns the client IP from a request.
|
|
699
|
+
*
|
|
700
|
+
* When the application has opted in to trusting forwarded headers (via
|
|
701
|
+
* `configureTrustedProxy({ trustForwardedHeaders: true })`), this function
|
|
702
|
+
* checks `X-Forwarded-For` first (for proxied/edge deployments), falls back
|
|
703
|
+
* to `X-Real-IP`, and finally to `null` if neither is present.
|
|
704
|
+
*
|
|
705
|
+
* When forwarded headers are **not** trusted (the default), both headers are
|
|
706
|
+
* ignored entirely and the function returns `null` — the IP is simply
|
|
707
|
+
* unavailable. This is the safe behaviour: a client can set
|
|
708
|
+
* `X-Forwarded-For` to any value on every request, defeating IP-based rate
|
|
709
|
+
* limiting and poisoning audit trails if trusted.
|
|
688
710
|
*/
|
|
689
711
|
declare function clientIpFromRequest(req: Request): string | null;
|
|
690
712
|
|
|
@@ -773,15 +795,31 @@ declare function auditSessionRevoked(input: AuditEventInput & {
|
|
|
773
795
|
*
|
|
774
796
|
* These handlers report the crash through the configured error reporter so an
|
|
775
797
|
* operator sees it, rather than dying silently (or staying up silently with no
|
|
776
|
-
* trace of what happened).
|
|
777
|
-
*
|
|
778
|
-
*
|
|
798
|
+
* trace of what happened).
|
|
799
|
+
*
|
|
800
|
+
* A throw that escapes to the event loop (module eval, background sweep,
|
|
801
|
+
* native callback, timer) leaves module-scope singletons in an undefined
|
|
802
|
+
* state, so the process must not keep serving corrupted traffic. By default
|
|
803
|
+
* an `uncaughtException` fails fast (`exitOnCrash` defaults `true`) so the
|
|
804
|
+
* orchestrator (systemd/K8s) restarts the box clean. Unhandled rejections are
|
|
805
|
+
* usually recoverable and stay survivable by default.
|
|
779
806
|
*/
|
|
780
807
|
interface ProcessCrashHandlerOptions {
|
|
781
808
|
/** Phase tag forwarded to the error reporter. Defaults to "api". */
|
|
782
809
|
phase?: "ssr" | "action" | "api" | "loader";
|
|
783
|
-
/**
|
|
810
|
+
/**
|
|
811
|
+
* When true, `process.exit(1)` after an uncaught exception. Defaults to
|
|
812
|
+
* `true` — an uncaughtException can leave process singletons half-mutated,
|
|
813
|
+
* so it must fail fast for the orchestrator to restart clean. Set `false`
|
|
814
|
+
* to keep serving after reporting.
|
|
815
|
+
*/
|
|
784
816
|
exitOnCrash?: boolean;
|
|
817
|
+
/**
|
|
818
|
+
* When true, `process.exit(1)` after an unhandled rejection. Defaults to
|
|
819
|
+
* `false` — an unhandledRejection is usually a lone async failure the
|
|
820
|
+
* process can survive.
|
|
821
|
+
*/
|
|
822
|
+
exitOnUnhandledRejection?: boolean;
|
|
785
823
|
}
|
|
786
824
|
/** Registers `uncaughtException`/`unhandledRejection` handlers; returns a disposer. */
|
|
787
825
|
declare function installProcessCrashHandlers(options?: ProcessCrashHandlerOptions): () => void;
|
|
@@ -1006,9 +1044,65 @@ declare class EnvLeakageError extends Error {
|
|
|
1006
1044
|
/** Throws EnvLeakageError if the given bundle source references non-public env vars. */
|
|
1007
1045
|
declare function assertNoEnvLeakage(code: string, file: string): void;
|
|
1008
1046
|
|
|
1047
|
+
/**
|
|
1048
|
+
* Global setting that controls whether client-supplied forwarding headers
|
|
1049
|
+
* (`X-Forwarded-For`, `X-Real-IP`) are trusted for IP resolution.
|
|
1050
|
+
*
|
|
1051
|
+
* ## Security boundary
|
|
1052
|
+
*
|
|
1053
|
+
* When `trustForwardedHeaders` is **false** (the default), the framework
|
|
1054
|
+
* ignores `X-Forwarded-For` and `X-Real-IP` entirely. A client can set
|
|
1055
|
+
* these headers to arbitrary values on every request, which — if trusted —
|
|
1056
|
+
* lets them defeat IP-based rate limiting (brute-force guards) and poison
|
|
1057
|
+
* audit trails with attacker-chosen IPs. This is the safe default because
|
|
1058
|
+
* the framework cannot distinguish a legitimate proxy chain from a direct
|
|
1059
|
+
* connection with spoofed headers.
|
|
1060
|
+
*
|
|
1061
|
+
* Only set `trustForwardedHeaders: true` when **all** of the following hold:
|
|
1062
|
+
* 1. The application sits behind a reverse proxy / edge that scrubs or
|
|
1063
|
+
* overwrites forwarded headers (e.g. Vercel Edge, Cloudflare, AWS ALB).
|
|
1064
|
+
* 2. The proxy always sets `X-Forwarded-For` to the real client IP chain,
|
|
1065
|
+
* and clients cannot reach the origin without going through that proxy.
|
|
1066
|
+
*
|
|
1067
|
+
* Adapters (e.g. `@thexjs/adapter-vercel`) call {@link configureTrustedProxy}
|
|
1068
|
+
* at their own initialization point when the deployment platform guarantees
|
|
1069
|
+
* header integrity. Applications that deploy directly (no proxy) or sit
|
|
1070
|
+
* behind a proxy that does not scrub headers must **not** enable this.
|
|
1071
|
+
*/
|
|
1072
|
+
interface TrustedProxyOptions {
|
|
1073
|
+
/**
|
|
1074
|
+
* When `true`, `clientIpFromRequest()` reads `X-Forwarded-For` /
|
|
1075
|
+
* `X-Real-IP` headers. When `false` (default), those headers are ignored
|
|
1076
|
+
* and `clientIpFromRequest()` returns `null` (unavailable).
|
|
1077
|
+
*/
|
|
1078
|
+
trustForwardedHeaders?: boolean;
|
|
1079
|
+
}
|
|
1080
|
+
/**
|
|
1081
|
+
* Returns `true` when the application has opted in to trusting client-supplied
|
|
1082
|
+
* forwarding headers for IP resolution.
|
|
1083
|
+
*/
|
|
1084
|
+
declare function isTrustedProxy(): boolean;
|
|
1085
|
+
/**
|
|
1086
|
+
* Configures the global trusted-proxy policy. Call once at application
|
|
1087
|
+
* initialization (e.g. inside an adapter's build output or a top-level
|
|
1088
|
+
* `x.config.ts` callback). Subsequent calls overwrite the previous value.
|
|
1089
|
+
*
|
|
1090
|
+
* @example
|
|
1091
|
+
* ```ts
|
|
1092
|
+
* // Vercel adapter — edge always sets X-Forwarded-For correctly
|
|
1093
|
+
* configureTrustedProxy({ trustForwardedHeaders: true });
|
|
1094
|
+
* ```
|
|
1095
|
+
*/
|
|
1096
|
+
declare function configureTrustedProxy(options: TrustedProxyOptions): void;
|
|
1097
|
+
/**
|
|
1098
|
+
* Resets the trusted-proxy setting to the default (`false`).
|
|
1099
|
+
* Exported for test isolation — production code should never need this.
|
|
1100
|
+
*/
|
|
1101
|
+
declare function resetTrustedProxy(): void;
|
|
1102
|
+
|
|
1009
1103
|
declare function generateServerFunctionClient(routeFilePath: string, fnNames: string[], endpointBase: string): string;
|
|
1010
1104
|
declare function resetServerFunctions(): void;
|
|
1011
1105
|
declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
|
|
1012
1106
|
declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
|
|
1013
1107
|
|
|
1014
|
-
export { type AuditEntry, type AuditEvent, type AuditSink, type BackpressureController, type BackpressureHandler, type BackpressureLease, type BackpressureOptions, BackpressureSaturatedError, type BackpressureSnapshot, 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, createBackpressureController, 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, withBackpressure, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
|
|
1108
|
+
export { type AuditEntry, type AuditEvent, type AuditSink, type BackpressureController, type BackpressureHandler, type BackpressureLease, type BackpressureOptions, BackpressureSaturatedError, type BackpressureSnapshot, 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, type TrustedProxyOptions, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, configureTrustedProxy, createApp, createBackpressureController, 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, isTrustedProxy, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, resetTrustedProxy, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withBackpressure, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
|
package/dist/index.js
CHANGED
|
@@ -39,10 +39,11 @@ import {
|
|
|
39
39
|
verifyOrigin,
|
|
40
40
|
withCsrfCookie,
|
|
41
41
|
writeManifest
|
|
42
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-3VMZCMAF.js";
|
|
43
43
|
import {
|
|
44
44
|
OTEL_ERROR_STATUS_CODE,
|
|
45
45
|
REDACTED,
|
|
46
|
+
SAFE_REQUEST_ID_RE,
|
|
46
47
|
dbTraceAttributes,
|
|
47
48
|
getTracer,
|
|
48
49
|
isSensitiveKey,
|
|
@@ -54,7 +55,7 @@ import {
|
|
|
54
55
|
tracePhaseSync,
|
|
55
56
|
traceRequestId,
|
|
56
57
|
withRequestTracing
|
|
57
|
-
} from "./chunk-
|
|
58
|
+
} from "./chunk-OXV2QTWV.js";
|
|
58
59
|
|
|
59
60
|
// src/backpressure.ts
|
|
60
61
|
var BackpressureSaturatedError = class extends Error {
|
|
@@ -457,6 +458,14 @@ var CLIENT_NAV_SCRIPT = `
|
|
|
457
458
|
}
|
|
458
459
|
if (push) history.pushState({ xNav: true }, "", payload.finalUrl);
|
|
459
460
|
if (doc.title) document.title = doc.title;
|
|
461
|
+
if (window.__xIslandRoots) {
|
|
462
|
+
// Must stay in sync with unmountIslandRoots() \u2014 same logic, different
|
|
463
|
+
// execution context (this is an inline script, not a module import).
|
|
464
|
+
for (var i = 0; i < window.__xIslandRoots.length; i++) {
|
|
465
|
+
try { window.__xIslandRoots[i]?.unmount(); } catch (_) {}
|
|
466
|
+
}
|
|
467
|
+
window.__xIslandRoots.length = 0;
|
|
468
|
+
}
|
|
460
469
|
root.innerHTML = next.innerHTML;
|
|
461
470
|
reexecuteScripts(root);
|
|
462
471
|
if (url.hash) {
|
|
@@ -942,7 +951,9 @@ function buildServerEntry(opts, configImportPath, stylesheetHref) {
|
|
|
942
951
|
"// a rejected promise from a background sweep) is reported through the",
|
|
943
952
|
"// error reporter so the box reports instead of dying silently.",
|
|
944
953
|
'const { installProcessCrashHandlers } = await import("@thexjs/core");',
|
|
945
|
-
|
|
954
|
+
// Fail fast on an uncaughtException: the singleton state may be corrupted,
|
|
955
|
+
// so drain and let the orchestrator restart clean (see crash-handlers).
|
|
956
|
+
"installProcessCrashHandlers({ exitOnCrash: true });"
|
|
946
957
|
);
|
|
947
958
|
return lines.join("\n");
|
|
948
959
|
}
|
|
@@ -956,6 +967,44 @@ import { existsSync as existsSync2, watch } from "fs";
|
|
|
956
967
|
import { join as join3, resolve, sep as sep2 } from "path";
|
|
957
968
|
import { createElement as createElement2 } from "react";
|
|
958
969
|
|
|
970
|
+
// src/bounded-cache.ts
|
|
971
|
+
var BoundedCache = class {
|
|
972
|
+
entries = /* @__PURE__ */ new Map();
|
|
973
|
+
maxEntries;
|
|
974
|
+
constructor(maxEntries = 500) {
|
|
975
|
+
this.maxEntries = maxEntries;
|
|
976
|
+
}
|
|
977
|
+
get(key) {
|
|
978
|
+
const value = this.entries.get(key);
|
|
979
|
+
if (value !== void 0) {
|
|
980
|
+
this.entries.delete(key);
|
|
981
|
+
this.entries.set(key, value);
|
|
982
|
+
}
|
|
983
|
+
return value;
|
|
984
|
+
}
|
|
985
|
+
set(key, value) {
|
|
986
|
+
this.entries.delete(key);
|
|
987
|
+
this.entries.set(key, value);
|
|
988
|
+
this.evict();
|
|
989
|
+
}
|
|
990
|
+
delete(key) {
|
|
991
|
+
this.entries.delete(key);
|
|
992
|
+
}
|
|
993
|
+
clear() {
|
|
994
|
+
this.entries.clear();
|
|
995
|
+
}
|
|
996
|
+
get size() {
|
|
997
|
+
return this.entries.size;
|
|
998
|
+
}
|
|
999
|
+
evict() {
|
|
1000
|
+
while (this.entries.size > this.maxEntries) {
|
|
1001
|
+
const oldestKey = this.entries.keys().next().value;
|
|
1002
|
+
if (oldestKey === void 0) break;
|
|
1003
|
+
this.entries.delete(oldestKey);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
|
|
959
1008
|
// src/error-overlay.ts
|
|
960
1009
|
function escapeHtml3(s) {
|
|
961
1010
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
@@ -1769,15 +1818,31 @@ function isrCacheKey(requestUrl) {
|
|
|
1769
1818
|
return url.pathname + url.search;
|
|
1770
1819
|
}
|
|
1771
1820
|
|
|
1821
|
+
// src/security/trusted-proxy.ts
|
|
1822
|
+
var trustForwardedHeaders = false;
|
|
1823
|
+
function isTrustedProxy() {
|
|
1824
|
+
return trustForwardedHeaders;
|
|
1825
|
+
}
|
|
1826
|
+
function configureTrustedProxy(options) {
|
|
1827
|
+
trustForwardedHeaders = options.trustForwardedHeaders ?? false;
|
|
1828
|
+
}
|
|
1829
|
+
function resetTrustedProxy() {
|
|
1830
|
+
trustForwardedHeaders = false;
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1772
1833
|
// src/security/rate-limit.ts
|
|
1773
1834
|
function defaultKeyFn(req, server) {
|
|
1774
1835
|
if (server?.requestIP) {
|
|
1775
1836
|
const ip = server.requestIP(req);
|
|
1776
1837
|
if (ip) return ip.address;
|
|
1777
1838
|
}
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1839
|
+
if (isTrustedProxy()) {
|
|
1840
|
+
const forwarded = req.headers.get("x-forwarded-for");
|
|
1841
|
+
if (forwarded) return forwarded.split(",")[0]?.trim() ?? "unknown";
|
|
1842
|
+
const realIp = req.headers.get("x-real-ip");
|
|
1843
|
+
if (realIp) return realIp;
|
|
1844
|
+
}
|
|
1845
|
+
return "unknown";
|
|
1781
1846
|
}
|
|
1782
1847
|
function createRateLimiter(options = {}) {
|
|
1783
1848
|
const limit = options.limit ?? 60;
|
|
@@ -1975,8 +2040,10 @@ async function createApp(options) {
|
|
|
1975
2040
|
const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
|
|
1976
2041
|
const staticCache = new IsrCache(500);
|
|
1977
2042
|
let actionModules = /* @__PURE__ */ new Map();
|
|
1978
|
-
const islandBundleCache =
|
|
1979
|
-
|
|
2043
|
+
const islandBundleCache = new BoundedCache(
|
|
2044
|
+
options.islandCacheMaxEntries ?? 500
|
|
2045
|
+
);
|
|
2046
|
+
const islandFileCache = new BoundedCache(options.islandCacheMaxEntries ?? 500);
|
|
1980
2047
|
async function resolveIslandScripts(routeFilePath, layoutFilePaths, entries) {
|
|
1981
2048
|
if (entries.length === 0) return [];
|
|
1982
2049
|
const uniqueNames = [...new Set(entries.map((e) => e.name))].sort();
|
|
@@ -2861,6 +2928,7 @@ function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
|
|
|
2861
2928
|
|
|
2862
2929
|
// src/security/ip.ts
|
|
2863
2930
|
function clientIpFromRequest(req) {
|
|
2931
|
+
if (!isTrustedProxy()) return null;
|
|
2864
2932
|
const forwarded = req.headers.get("x-forwarded-for");
|
|
2865
2933
|
if (forwarded) return forwarded.split(",")[0]?.trim() || null;
|
|
2866
2934
|
return req.headers.get("x-real-ip");
|
|
@@ -2886,7 +2954,10 @@ function getAuditSink() {
|
|
|
2886
2954
|
return activeSink;
|
|
2887
2955
|
}
|
|
2888
2956
|
function requestIdFromRequest(req) {
|
|
2889
|
-
|
|
2957
|
+
const raw = req.headers.get("x-request-id");
|
|
2958
|
+
if (raw === null) return void 0;
|
|
2959
|
+
if (!SAFE_REQUEST_ID_RE.test(raw)) return void 0;
|
|
2960
|
+
return raw;
|
|
2890
2961
|
}
|
|
2891
2962
|
function audit(entry) {
|
|
2892
2963
|
const redacted = {
|
|
@@ -2955,16 +3026,17 @@ function auditSessionRevoked(input) {
|
|
|
2955
3026
|
// src/observability/crash-handlers.ts
|
|
2956
3027
|
function installProcessCrashHandlers(options = {}) {
|
|
2957
3028
|
const phase = options.phase ?? "api";
|
|
2958
|
-
const
|
|
3029
|
+
const exitOnUncaughtException = options.exitOnCrash ?? true;
|
|
3030
|
+
const exitOnUnhandledRejection = options.exitOnUnhandledRejection ?? false;
|
|
2959
3031
|
const onUncaughtException = (error) => {
|
|
2960
3032
|
console.error("[x] uncaught exception:", error);
|
|
2961
3033
|
reportException(error, { phase });
|
|
2962
|
-
if (
|
|
3034
|
+
if (exitOnUncaughtException) process.exit(1);
|
|
2963
3035
|
};
|
|
2964
3036
|
const onUnhandledRejection = (reason) => {
|
|
2965
3037
|
console.error("[x] unhandled rejection:", reason);
|
|
2966
3038
|
reportException(reason, { phase });
|
|
2967
|
-
if (
|
|
3039
|
+
if (exitOnUnhandledRejection) process.exit(1);
|
|
2968
3040
|
};
|
|
2969
3041
|
process.on("uncaughtException", onUncaughtException);
|
|
2970
3042
|
process.on("unhandledRejection", onUnhandledRejection);
|
|
@@ -3006,6 +3078,7 @@ export {
|
|
|
3006
3078
|
clientIpFromRequest,
|
|
3007
3079
|
combineReporters,
|
|
3008
3080
|
composeMiddleware,
|
|
3081
|
+
configureTrustedProxy,
|
|
3009
3082
|
createApp,
|
|
3010
3083
|
createBackpressureController,
|
|
3011
3084
|
createConsoleAuditSink,
|
|
@@ -3033,6 +3106,7 @@ export {
|
|
|
3033
3106
|
getTracer,
|
|
3034
3107
|
installProcessCrashHandlers,
|
|
3035
3108
|
isSensitiveKey,
|
|
3109
|
+
isTrustedProxy,
|
|
3036
3110
|
logger,
|
|
3037
3111
|
noopAuditSink,
|
|
3038
3112
|
noopMetrics,
|
|
@@ -3049,6 +3123,7 @@ export {
|
|
|
3049
3123
|
reportException,
|
|
3050
3124
|
requestIdFromRequest,
|
|
3051
3125
|
resetServerFunctions,
|
|
3126
|
+
resetTrustedProxy,
|
|
3052
3127
|
runWithRequestSpan,
|
|
3053
3128
|
scanApiDir,
|
|
3054
3129
|
scanContent,
|
package/package.json
CHANGED