@thexjs/core 1.10.2 → 1.11.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 +1 -1
- package/dist/{chunk-GVDJW4PD.js → chunk-5FY3ROGN.js} +28 -2
- package/dist/index.d.ts +110 -2
- package/dist/index.js +135 -30
- package/package.json +1 -1
package/dist/adapter.js
CHANGED
|
@@ -466,11 +466,33 @@ function enforceRequestBodySize(req, maxBytes) {
|
|
|
466
466
|
});
|
|
467
467
|
}
|
|
468
468
|
|
|
469
|
+
// src/security/trusted-proxy.ts
|
|
470
|
+
var trustForwardedHeaders = false;
|
|
471
|
+
function isTrustedProxy() {
|
|
472
|
+
return trustForwardedHeaders;
|
|
473
|
+
}
|
|
474
|
+
function configureTrustedProxy(options) {
|
|
475
|
+
trustForwardedHeaders = options.trustForwardedHeaders ?? false;
|
|
476
|
+
}
|
|
477
|
+
function resetTrustedProxy() {
|
|
478
|
+
trustForwardedHeaders = false;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// src/security/secure-request.ts
|
|
482
|
+
function isSecureRequest(req) {
|
|
483
|
+
if (new URL(req.url).protocol === "https:") return true;
|
|
484
|
+
if (!isTrustedProxy()) return false;
|
|
485
|
+
return req.headers.get("x-forwarded-proto") === "https";
|
|
486
|
+
}
|
|
487
|
+
|
|
469
488
|
// src/security/csrf.ts
|
|
470
489
|
var CSRF_COOKIE_NAME = "x_csrf_token";
|
|
471
490
|
var CSRF_HEADER_NAME = "x-csrf-token";
|
|
472
491
|
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
|
|
473
|
-
|
|
492
|
+
function secureCookieFlag(req) {
|
|
493
|
+
const secure = process.env.NODE_ENV === "production" || isSecureRequest(req);
|
|
494
|
+
return secure ? "; Secure" : "";
|
|
495
|
+
}
|
|
474
496
|
function originFromHeader(value) {
|
|
475
497
|
if (!value) return null;
|
|
476
498
|
try {
|
|
@@ -536,7 +558,7 @@ function withCsrfCookie(req, res) {
|
|
|
536
558
|
const headers = new Headers(res.headers);
|
|
537
559
|
headers.append(
|
|
538
560
|
"Set-Cookie",
|
|
539
|
-
`${CSRF_COOKIE_NAME}=${token}; Path=/; SameSite=Lax${
|
|
561
|
+
`${CSRF_COOKIE_NAME}=${token}; Path=/; SameSite=Lax${secureCookieFlag(req)}`
|
|
540
562
|
);
|
|
541
563
|
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
542
564
|
}
|
|
@@ -893,6 +915,10 @@ export {
|
|
|
893
915
|
DEFAULT_MAX_BODY_SIZE,
|
|
894
916
|
RequestBodyTooLargeError,
|
|
895
917
|
enforceRequestBodySize,
|
|
918
|
+
isTrustedProxy,
|
|
919
|
+
configureTrustedProxy,
|
|
920
|
+
resetTrustedProxy,
|
|
921
|
+
isSecureRequest,
|
|
896
922
|
originFromHeader,
|
|
897
923
|
requestOrigin,
|
|
898
924
|
verifyOrigin,
|
package/dist/index.d.ts
CHANGED
|
@@ -340,6 +340,79 @@ declare function buildSecurityHeaders(options?: SecurityHeadersOptions): Headers
|
|
|
340
340
|
/** Returns a new Response with security headers merged onto the original response's headers. */
|
|
341
341
|
declare function applySecurityHeaders(res: Response, options?: SecurityHeadersOptions): Response;
|
|
342
342
|
|
|
343
|
+
/**
|
|
344
|
+
* ISR (revalidate) cache with a bounded size and in-flight dedup. In-memory
|
|
345
|
+
* (per-process) by default; pass `store` (see `createRedisIsrCacheStore`) for
|
|
346
|
+
* multi-instance deployments, where purging one replica's local cache isn't
|
|
347
|
+
* enough — `/__x/revalidate` needs to invalidate the HTML every replica
|
|
348
|
+
* shares, not just the one that happened to handle the purge request.
|
|
349
|
+
*
|
|
350
|
+
* Three problems this solves over a plain `Map`:
|
|
351
|
+
*
|
|
352
|
+
* 1. **Unbounded growth** — cached HTML for every distinct URL ever requested
|
|
353
|
+
* would otherwise live for the life of the process. Entries are capped at
|
|
354
|
+
* `maxEntries` and evicted oldest-first (LRU via Map insertion order).
|
|
355
|
+
* (The Redis store has its own bound — a TTL, not an entry cap; see
|
|
356
|
+
* `createRedisIsrCacheStore`.)
|
|
357
|
+
*
|
|
358
|
+
* 2. **Cache stampede** — N concurrent misses for the same URL all ran the
|
|
359
|
+
* loader and rendered. `getOrCompute` shares one in-flight computation
|
|
360
|
+
* across all waiters, so a busy page rebuilds its entry exactly once.
|
|
361
|
+
* This dedup is per-process even with a shared store: two different
|
|
362
|
+
* replicas can still both miss and both recompute once each, same as two
|
|
363
|
+
* independent single-instance deployments would. Closing that too would
|
|
364
|
+
* need a distributed lock, which is a bigger step than what a shared
|
|
365
|
+
* cache store is for.
|
|
366
|
+
*
|
|
367
|
+
* 3. **Cross-replica staleness** — with no shared store, revalidating or
|
|
368
|
+
* purging a path on one instance leaves every sibling instance still
|
|
369
|
+
* serving the old cached HTML until their own TTL naturally expires.
|
|
370
|
+
*
|
|
371
|
+
* Keys are full URLs (pathname + search). The caller is responsible for that
|
|
372
|
+
* contract; see `isrCacheKey`.
|
|
373
|
+
*/
|
|
374
|
+
interface StaticCacheEntry {
|
|
375
|
+
html: string;
|
|
376
|
+
timestamp: number;
|
|
377
|
+
/** CSP nonce baked into the inline scripts of `html`; must be reused when serving from cache. */
|
|
378
|
+
cspNonce: string;
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* A shared backend for ISR cache entries, so `IsrCache` can be backed by
|
|
382
|
+
* Redis (or any other store) instead of a local `Map`. All methods are
|
|
383
|
+
* async, even though the in-memory default resolves synchronously-fast —
|
|
384
|
+
* one uniform interface regardless of backend, the same choice
|
|
385
|
+
* `RateLimitStore` already makes.
|
|
386
|
+
*/
|
|
387
|
+
interface IsrCacheStore {
|
|
388
|
+
get(key: string): Promise<StaticCacheEntry | undefined>;
|
|
389
|
+
set(key: string, entry: StaticCacheEntry): Promise<void>;
|
|
390
|
+
delete(key: string): Promise<void>;
|
|
391
|
+
/** Deletes every entry whose pathname matches (query-blind purge); returns the count removed. */
|
|
392
|
+
deletePath(pathname: string): Promise<number>;
|
|
393
|
+
clear(): Promise<void>;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Shared ISR cache store backed by Redis, so `/__x/revalidate` invalidates
|
|
397
|
+
* the HTML every replica serves, not just the one that handled the purge
|
|
398
|
+
* request. Connects lazily on first use and keeps retrying after a failed
|
|
399
|
+
* connection attempt — same lazy-connect contract as
|
|
400
|
+
* `createRedisRateLimitStore`.
|
|
401
|
+
*
|
|
402
|
+
* Entries carry a TTL (default 7 days) so an abandoned URL's cached HTML
|
|
403
|
+
* eventually falls out of Redis on its own, the same reason the in-memory
|
|
404
|
+
* `IsrCache` bounds itself with `maxEntries` -- a shared store needs its own
|
|
405
|
+
* answer to "unbounded growth," since there's no LRU cap to reuse here. The
|
|
406
|
+
* TTL only guards against a replica never requesting a URL again; the
|
|
407
|
+
* app-level `revalidate` staleness check (comparing `entry.timestamp`
|
|
408
|
+
* against `revalidateSeconds`) is unaffected and keeps working exactly as it
|
|
409
|
+
* does for the in-memory store.
|
|
410
|
+
*/
|
|
411
|
+
declare function createRedisIsrCacheStore(options?: {
|
|
412
|
+
url?: string;
|
|
413
|
+
ttlSeconds?: number;
|
|
414
|
+
}): IsrCacheStore;
|
|
415
|
+
|
|
343
416
|
/**
|
|
344
417
|
* Lightweight fixed-window rate limiter. In-memory by default, keyed by client
|
|
345
418
|
* IP — good enough for a single-process Bun deployment or as a first line of
|
|
@@ -449,6 +522,16 @@ interface CreateAppOptions$1 {
|
|
|
449
522
|
headers?: SecurityHeadersOptions | false;
|
|
450
523
|
/** Rate limiting applied ahead of all routing. Pass false to disable entirely. */
|
|
451
524
|
rateLimit?: RateLimitOptions | false;
|
|
525
|
+
/**
|
|
526
|
+
* Shared ISR cache store (e.g. `createRedisIsrCacheStore()`) for
|
|
527
|
+
* multi-instance deployments, so `/__x/revalidate` purges the cache
|
|
528
|
+
* every replica serves, not just the one that handled the request.
|
|
529
|
+
* In-memory per-process by default.
|
|
530
|
+
*/
|
|
531
|
+
isrCache?: {
|
|
532
|
+
store?: IsrCacheStore;
|
|
533
|
+
maxEntries?: number;
|
|
534
|
+
};
|
|
452
535
|
};
|
|
453
536
|
observability?: {
|
|
454
537
|
/** Structured JSON request logging. Default: true. */
|
|
@@ -1058,6 +1141,31 @@ declare class EnvLeakageError extends Error {
|
|
|
1058
1141
|
/** Throws EnvLeakageError if the given bundle source references non-public env vars. */
|
|
1059
1142
|
declare function assertNoEnvLeakage(code: string, file: string): void;
|
|
1060
1143
|
|
|
1144
|
+
/**
|
|
1145
|
+
* True when a request should be treated as HTTPS for deciding whether a
|
|
1146
|
+
* cookie needs the `Secure` flag. Checks, in order:
|
|
1147
|
+
*
|
|
1148
|
+
* 1. The request URL's own protocol. Every adapter bridge (adapter-node,
|
|
1149
|
+
* adapter-vercel) and `Bun.serve` itself already resolve this correctly
|
|
1150
|
+
* for direct TLS termination — `req.url` reads `https:` whenever the
|
|
1151
|
+
* process itself holds the TLS connection, with no trust decision
|
|
1152
|
+
* involved.
|
|
1153
|
+
* 2. `X-Forwarded-Proto`, but only when the application has opted in to
|
|
1154
|
+
* trusting forwarded headers (`configureTrustedProxy({
|
|
1155
|
+
* trustForwardedHeaders: true })`) — the same trust boundary
|
|
1156
|
+
* `clientIpFromRequest` (`security/ip.ts`) already gates on. Without
|
|
1157
|
+
* this gate a client could set the header to downgrade the check at
|
|
1158
|
+
* will; with it, a reverse-proxy deployment that terminates TLS in
|
|
1159
|
+
* front of a plain-HTTP Bun process is correctly recognized as secure.
|
|
1160
|
+
*
|
|
1161
|
+
* This is meant to be used *alongside* an explicit `NODE_ENV === "production"`
|
|
1162
|
+
* / `forceSecureCookie` check, not as a replacement for one — a request can
|
|
1163
|
+
* be genuinely HTTPS in a non-"production" environment (a staging
|
|
1164
|
+
* deployment, a platform that names its env var something else), and this
|
|
1165
|
+
* closes exactly that gap.
|
|
1166
|
+
*/
|
|
1167
|
+
declare function isSecureRequest(req: Request): boolean;
|
|
1168
|
+
|
|
1061
1169
|
/**
|
|
1062
1170
|
* Global setting that controls whether client-supplied forwarding headers
|
|
1063
1171
|
* (`X-Forwarded-For`, `X-Real-IP`) are trusted for IP resolution.
|
|
@@ -1119,5 +1227,5 @@ declare function resetServerFunctions(): void;
|
|
|
1119
1227
|
declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
|
|
1120
1228
|
declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
|
|
1121
1229
|
|
|
1122
|
-
export { BackpressureOptions, CLIENT_NAV_SCRIPT, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, Image, Island, IslandProvider, Link, OTEL_ERROR_STATUS_CODE, PUBLIC_ENV_PREFIX, REDACTED, RequestBodyTooLargeError, SRCSET_WIDTHS, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, configureTrustedProxy, 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, 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, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
|
|
1123
|
-
export type { AuditEntry, AuditEvent, AuditSink, BuildOptions, ContentEntry, CounterSeries, CreateAppOptions, CsrfOptions, CsrfResult, ErrorContext, ErrorReporter, Frontmatter, HealthCheck, HealthCheckOptions, HistogramSeries, ImageProps, ImageProxyOptions, InMemoryMetricsOptions, InMemoryMetricsReporter, IslandEntry, IslandMode, LayoutEntry, LinkProps, LoaderArgs, LoaderReturn, LogFields, Logger, MetricLabels, MetricsReporter, MetricsSnapshot, MiddlewareContext, MiddlewareEntry, MiddlewareFn, MiddlewareNext, NotFoundEntry, OtelMeterLike, OtelTracerLike, ProcessCrashHandlerOptions, RateLimitOptions, RateLimitResult, RateLimitStore, ReadinessResult, RevalidateOptions, RouteEntry, RouteMode, RouteProps, SecurityHeadersOptions, SentryLike, TraceSpan, TracerLike, TrustedProxyOptions };
|
|
1230
|
+
export { BackpressureOptions, CLIENT_NAV_SCRIPT, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, Image, Island, IslandProvider, Link, OTEL_ERROR_STATUS_CODE, PUBLIC_ENV_PREFIX, REDACTED, RequestBodyTooLargeError, SRCSET_WIDTHS, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, configureTrustedProxy, createApp, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisIsrCacheStore, createRedisRateLimitStore, createSentryReporter, dbTraceAttributes, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, getTracer, installProcessCrashHandlers, isSecureRequest, 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, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
|
|
1231
|
+
export type { AuditEntry, AuditEvent, AuditSink, BuildOptions, ContentEntry, CounterSeries, CreateAppOptions, CsrfOptions, CsrfResult, ErrorContext, ErrorReporter, Frontmatter, HealthCheck, HealthCheckOptions, HistogramSeries, ImageProps, ImageProxyOptions, InMemoryMetricsOptions, InMemoryMetricsReporter, IslandEntry, IslandMode, IsrCacheStore, LayoutEntry, LinkProps, LoaderArgs, LoaderReturn, LogFields, Logger, MetricLabels, MetricsReporter, MetricsSnapshot, MiddlewareContext, MiddlewareEntry, MiddlewareFn, MiddlewareNext, NotFoundEntry, OtelMeterLike, OtelTracerLike, ProcessCrashHandlerOptions, RateLimitOptions, RateLimitResult, RateLimitStore, ReadinessResult, RevalidateOptions, RouteEntry, RouteMode, RouteProps, SecurityHeadersOptions, SentryLike, TraceSpan, TracerLike, TrustedProxyOptions };
|
package/dist/index.js
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
bundleRouteIslandsToDisk,
|
|
9
9
|
checkCsrf,
|
|
10
10
|
combineReporters,
|
|
11
|
+
configureTrustedProxy,
|
|
11
12
|
createOtelReporter,
|
|
12
13
|
createSentryReporter,
|
|
13
14
|
enforceRequestBodySize,
|
|
@@ -20,6 +21,8 @@ import {
|
|
|
20
21
|
generateServerFunctionClient,
|
|
21
22
|
getErrorReporter,
|
|
22
23
|
getServerFunctionHandler,
|
|
24
|
+
isSecureRequest,
|
|
25
|
+
isTrustedProxy,
|
|
23
26
|
islandEntryId,
|
|
24
27
|
noopReporter,
|
|
25
28
|
originFromHeader,
|
|
@@ -27,6 +30,7 @@ import {
|
|
|
27
30
|
reportException,
|
|
28
31
|
requestOrigin,
|
|
29
32
|
resetServerFunctions,
|
|
33
|
+
resetTrustedProxy,
|
|
30
34
|
scanApiDir,
|
|
31
35
|
scanLayouts,
|
|
32
36
|
scanLayoutsDir,
|
|
@@ -39,7 +43,7 @@ import {
|
|
|
39
43
|
verifyOrigin,
|
|
40
44
|
withCsrfCookie,
|
|
41
45
|
writeManifest
|
|
42
|
-
} from "./chunk-
|
|
46
|
+
} from "./chunk-5FY3ROGN.js";
|
|
43
47
|
import {
|
|
44
48
|
OTEL_ERROR_STATUS_CODE,
|
|
45
49
|
REDACTED,
|
|
@@ -319,7 +323,7 @@ function decodeLinkUrl(url) {
|
|
|
319
323
|
return prev;
|
|
320
324
|
}
|
|
321
325
|
function stripUrlControlChars(url) {
|
|
322
|
-
return url.replace(/[\
|
|
326
|
+
return url.replace(/[\x00-\x1F]/g, "");
|
|
323
327
|
}
|
|
324
328
|
function isSafeLinkUrl(url) {
|
|
325
329
|
const clean = stripUrlControlChars(url);
|
|
@@ -1470,10 +1474,13 @@ var IsrCache = class {
|
|
|
1470
1474
|
entries = /* @__PURE__ */ new Map();
|
|
1471
1475
|
inFlight = /* @__PURE__ */ new Map();
|
|
1472
1476
|
maxEntries;
|
|
1473
|
-
|
|
1477
|
+
store;
|
|
1478
|
+
constructor(maxEntries = 500, store) {
|
|
1474
1479
|
this.maxEntries = maxEntries;
|
|
1480
|
+
this.store = store;
|
|
1475
1481
|
}
|
|
1476
|
-
get(key) {
|
|
1482
|
+
async get(key) {
|
|
1483
|
+
if (this.store) return this.store.get(key);
|
|
1477
1484
|
const entry = this.entries.get(key);
|
|
1478
1485
|
if (entry) {
|
|
1479
1486
|
this.entries.delete(key);
|
|
@@ -1481,19 +1488,33 @@ var IsrCache = class {
|
|
|
1481
1488
|
}
|
|
1482
1489
|
return entry;
|
|
1483
1490
|
}
|
|
1484
|
-
set(key, html, cspNonce) {
|
|
1491
|
+
async set(key, html, cspNonce) {
|
|
1492
|
+
const entry = { html, timestamp: Date.now(), cspNonce };
|
|
1493
|
+
if (this.store) {
|
|
1494
|
+
await this.store.set(key, entry);
|
|
1495
|
+
return;
|
|
1496
|
+
}
|
|
1485
1497
|
this.entries.delete(key);
|
|
1486
|
-
this.entries.set(key,
|
|
1498
|
+
this.entries.set(key, entry);
|
|
1487
1499
|
this.evict();
|
|
1488
1500
|
}
|
|
1489
|
-
delete(key) {
|
|
1501
|
+
async delete(key) {
|
|
1502
|
+
if (this.store) {
|
|
1503
|
+
await this.store.delete(key);
|
|
1504
|
+
return;
|
|
1505
|
+
}
|
|
1490
1506
|
this.entries.delete(key);
|
|
1491
1507
|
}
|
|
1492
|
-
clear() {
|
|
1508
|
+
async clear() {
|
|
1509
|
+
if (this.store) {
|
|
1510
|
+
await this.store.clear();
|
|
1511
|
+
return;
|
|
1512
|
+
}
|
|
1493
1513
|
this.entries.clear();
|
|
1494
1514
|
}
|
|
1495
1515
|
/** Deletes every entry whose pathname matches (query-blind purge). */
|
|
1496
|
-
deletePath(pathname) {
|
|
1516
|
+
async deletePath(pathname) {
|
|
1517
|
+
if (this.store) return this.store.deletePath(pathname);
|
|
1497
1518
|
let removed = 0;
|
|
1498
1519
|
for (const key of this.entries.keys()) {
|
|
1499
1520
|
const url = new URL(key, "http://localhost");
|
|
@@ -1504,6 +1525,7 @@ var IsrCache = class {
|
|
|
1504
1525
|
}
|
|
1505
1526
|
return removed;
|
|
1506
1527
|
}
|
|
1528
|
+
/** In-process entry count. With a shared store, this only reflects in-flight dedup bookkeeping, not the store's size. */
|
|
1507
1529
|
get size() {
|
|
1508
1530
|
return this.entries.size;
|
|
1509
1531
|
}
|
|
@@ -1513,14 +1535,14 @@ var IsrCache = class {
|
|
|
1513
1535
|
* `Response` returned by `compute` (e.g. a loader redirect) is passed
|
|
1514
1536
|
* through and never cached.
|
|
1515
1537
|
*/
|
|
1516
|
-
getOrCompute(key, compute) {
|
|
1517
|
-
const cached = this.get(key);
|
|
1518
|
-
if (cached) return
|
|
1538
|
+
async getOrCompute(key, compute) {
|
|
1539
|
+
const cached = await this.get(key);
|
|
1540
|
+
if (cached) return { html: cached.html, cspNonce: cached.cspNonce };
|
|
1519
1541
|
const existing = this.inFlight.get(key);
|
|
1520
1542
|
if (existing) return existing;
|
|
1521
|
-
const promise = compute().then((result) => {
|
|
1543
|
+
const promise = compute().then(async (result) => {
|
|
1522
1544
|
if (result instanceof Response) return result;
|
|
1523
|
-
this.set(key, result.html, result.cspNonce);
|
|
1545
|
+
await this.set(key, result.html, result.cspNonce);
|
|
1524
1546
|
return result;
|
|
1525
1547
|
}).finally(() => {
|
|
1526
1548
|
this.inFlight.delete(key);
|
|
@@ -1540,17 +1562,95 @@ function isrCacheKey(requestUrl) {
|
|
|
1540
1562
|
const url = new URL(requestUrl);
|
|
1541
1563
|
return url.pathname + url.search;
|
|
1542
1564
|
}
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1565
|
+
function createBunRedisClient(options) {
|
|
1566
|
+
return async () => {
|
|
1567
|
+
const BunRedis = globalThis.Bun.RedisClient;
|
|
1568
|
+
const instance = options.url ? new BunRedis(options.url) : new BunRedis();
|
|
1569
|
+
await instance.connect();
|
|
1570
|
+
return {
|
|
1571
|
+
sendCommand: (command, ...args) => instance.send(command, args)
|
|
1572
|
+
};
|
|
1573
|
+
};
|
|
1574
|
+
}
|
|
1575
|
+
var REDIS_KEY_PREFIX = "x:isr:";
|
|
1576
|
+
function escapeRedisGlob(value) {
|
|
1577
|
+
return value.replace(/[*?[\]\\]/g, "\\$&");
|
|
1548
1578
|
}
|
|
1549
|
-
function
|
|
1550
|
-
|
|
1579
|
+
async function scanKeys(client, pattern) {
|
|
1580
|
+
const found = [];
|
|
1581
|
+
let cursor = "0";
|
|
1582
|
+
do {
|
|
1583
|
+
const reply = await client.sendCommand("SCAN", cursor, "MATCH", pattern, "COUNT", "200");
|
|
1584
|
+
cursor = reply[0];
|
|
1585
|
+
found.push(...reply[1]);
|
|
1586
|
+
} while (cursor !== "0");
|
|
1587
|
+
return found;
|
|
1551
1588
|
}
|
|
1552
|
-
function
|
|
1553
|
-
|
|
1589
|
+
function createRedisIsrCacheStore(options = {}) {
|
|
1590
|
+
return createRedisIsrCacheStoreFromClient(createBunRedisClient(options), options.ttlSeconds);
|
|
1591
|
+
}
|
|
1592
|
+
function createRedisIsrCacheStoreFromClient(clientFactory, ttlSeconds = 7 * 24 * 60 * 60) {
|
|
1593
|
+
let client = null;
|
|
1594
|
+
let connecting = null;
|
|
1595
|
+
function getClient() {
|
|
1596
|
+
if (client) return Promise.resolve(client);
|
|
1597
|
+
if (!connecting) {
|
|
1598
|
+
connecting = clientFactory().then(
|
|
1599
|
+
(c) => {
|
|
1600
|
+
client = c;
|
|
1601
|
+
return c;
|
|
1602
|
+
},
|
|
1603
|
+
(err) => {
|
|
1604
|
+
connecting = null;
|
|
1605
|
+
throw err;
|
|
1606
|
+
}
|
|
1607
|
+
);
|
|
1608
|
+
}
|
|
1609
|
+
return connecting;
|
|
1610
|
+
}
|
|
1611
|
+
return {
|
|
1612
|
+
async get(key) {
|
|
1613
|
+
const c = await getClient();
|
|
1614
|
+
const raw = await c.sendCommand("GET", REDIS_KEY_PREFIX + key);
|
|
1615
|
+
if (typeof raw !== "string") return void 0;
|
|
1616
|
+
try {
|
|
1617
|
+
return JSON.parse(raw);
|
|
1618
|
+
} catch {
|
|
1619
|
+
return void 0;
|
|
1620
|
+
}
|
|
1621
|
+
},
|
|
1622
|
+
async set(key, entry) {
|
|
1623
|
+
const c = await getClient();
|
|
1624
|
+
await c.sendCommand(
|
|
1625
|
+
"SET",
|
|
1626
|
+
REDIS_KEY_PREFIX + key,
|
|
1627
|
+
JSON.stringify(entry),
|
|
1628
|
+
"EX",
|
|
1629
|
+
String(ttlSeconds)
|
|
1630
|
+
);
|
|
1631
|
+
},
|
|
1632
|
+
async delete(key) {
|
|
1633
|
+
const c = await getClient();
|
|
1634
|
+
await c.sendCommand("DEL", REDIS_KEY_PREFIX + key);
|
|
1635
|
+
},
|
|
1636
|
+
async deletePath(pathname) {
|
|
1637
|
+
const c = await getClient();
|
|
1638
|
+
const exactKey = REDIS_KEY_PREFIX + pathname;
|
|
1639
|
+
const escapedKey = REDIS_KEY_PREFIX + escapeRedisGlob(pathname);
|
|
1640
|
+
const withQuery = await scanKeys(c, `${escapedKey}\\?*`);
|
|
1641
|
+
const exists = await c.sendCommand("EXISTS", exactKey);
|
|
1642
|
+
const keysToDelete = [...Number(exists) > 0 ? [exactKey] : [], ...withQuery];
|
|
1643
|
+
if (keysToDelete.length === 0) return 0;
|
|
1644
|
+
await c.sendCommand("DEL", ...keysToDelete);
|
|
1645
|
+
return keysToDelete.length;
|
|
1646
|
+
},
|
|
1647
|
+
async clear() {
|
|
1648
|
+
const c = await getClient();
|
|
1649
|
+
const keys = await scanKeys(c, `${REDIS_KEY_PREFIX}*`);
|
|
1650
|
+
if (keys.length === 0) return;
|
|
1651
|
+
await c.sendCommand("DEL", ...keys);
|
|
1652
|
+
}
|
|
1653
|
+
};
|
|
1554
1654
|
}
|
|
1555
1655
|
|
|
1556
1656
|
// src/security/rate-limit.ts
|
|
@@ -1613,7 +1713,7 @@ async function rateLimitMiddleware(limiter, req, server) {
|
|
|
1613
1713
|
}
|
|
1614
1714
|
});
|
|
1615
1715
|
}
|
|
1616
|
-
function
|
|
1716
|
+
function createBunRedisClient2(options) {
|
|
1617
1717
|
return async () => {
|
|
1618
1718
|
const BunRedis = globalThis.Bun.RedisClient;
|
|
1619
1719
|
const instance = options.url ? new BunRedis(options.url) : new BunRedis();
|
|
@@ -1624,7 +1724,7 @@ function createBunRedisClient(options) {
|
|
|
1624
1724
|
};
|
|
1625
1725
|
}
|
|
1626
1726
|
function createRedisRateLimitStore(options = {}) {
|
|
1627
|
-
return createRedisRateLimitStoreFromClient(
|
|
1727
|
+
return createRedisRateLimitStoreFromClient(createBunRedisClient2(options));
|
|
1628
1728
|
}
|
|
1629
1729
|
var INCR_WITH_WINDOW_SCRIPT = `local c = redis.call('INCR', KEYS[1])
|
|
1630
1730
|
if redis.call('PTTL', KEYS[1]) == -1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
|
|
@@ -1790,7 +1890,10 @@ async function createApp(options) {
|
|
|
1790
1890
|
let notFoundComponent = DefaultNotFound;
|
|
1791
1891
|
let notFoundLayout;
|
|
1792
1892
|
const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
|
|
1793
|
-
const staticCache = new IsrCache(
|
|
1893
|
+
const staticCache = new IsrCache(
|
|
1894
|
+
options.security?.isrCache?.maxEntries ?? 500,
|
|
1895
|
+
options.security?.isrCache?.store
|
|
1896
|
+
);
|
|
1794
1897
|
let actionModules = /* @__PURE__ */ new Map();
|
|
1795
1898
|
const islandBundleCache = new BoundedCache(
|
|
1796
1899
|
options.islandCacheMaxEntries ?? 500
|
|
@@ -1967,7 +2070,7 @@ async function createApp(options) {
|
|
|
1967
2070
|
}
|
|
1968
2071
|
const revalidateSeconds = revalidate ?? 0;
|
|
1969
2072
|
if (revalidateSeconds > 0) {
|
|
1970
|
-
const cached = staticCache.get(cacheKey);
|
|
2073
|
+
const cached = await staticCache.get(cacheKey);
|
|
1971
2074
|
if (cached && Date.now() - cached.timestamp < revalidateSeconds * 1e3) {
|
|
1972
2075
|
const res2 = new Response(cached.html, {
|
|
1973
2076
|
headers: {
|
|
@@ -1978,7 +2081,7 @@ async function createApp(options) {
|
|
|
1978
2081
|
res2.headers.set(CSP_NONCE_HEADER, cached.cspNonce);
|
|
1979
2082
|
return res2;
|
|
1980
2083
|
}
|
|
1981
|
-
if (cached) staticCache.delete(cacheKey);
|
|
2084
|
+
if (cached) await staticCache.delete(cacheKey);
|
|
1982
2085
|
}
|
|
1983
2086
|
const computeHtml = async () => {
|
|
1984
2087
|
let loaderData = {};
|
|
@@ -2323,10 +2426,10 @@ async function createApp(options) {
|
|
|
2323
2426
|
return new Response("Invalid JSON body", { status: 400 });
|
|
2324
2427
|
}
|
|
2325
2428
|
if (body.path) {
|
|
2326
|
-
const removed = staticCache.deletePath(new URL(body.path, "http://localhost").pathname);
|
|
2429
|
+
const removed = await staticCache.deletePath(new URL(body.path, "http://localhost").pathname);
|
|
2327
2430
|
return new Response(`Revalidated: ${body.path} (${removed} cached variant(s))`);
|
|
2328
2431
|
}
|
|
2329
|
-
staticCache.clear();
|
|
2432
|
+
await staticCache.clear();
|
|
2330
2433
|
return new Response("Revalidated all");
|
|
2331
2434
|
}
|
|
2332
2435
|
async function handleHydrationMismatch(req) {
|
|
@@ -3206,6 +3309,7 @@ export {
|
|
|
3206
3309
|
createOtelReporter,
|
|
3207
3310
|
createOtlpMetricsReporter,
|
|
3208
3311
|
createRateLimiter,
|
|
3312
|
+
createRedisIsrCacheStore,
|
|
3209
3313
|
createRedisRateLimitStore,
|
|
3210
3314
|
createSentryReporter,
|
|
3211
3315
|
dbTraceAttributes,
|
|
@@ -3223,6 +3327,7 @@ export {
|
|
|
3223
3327
|
getServerFunctionHandler,
|
|
3224
3328
|
getTracer,
|
|
3225
3329
|
installProcessCrashHandlers,
|
|
3330
|
+
isSecureRequest,
|
|
3226
3331
|
isSensitiveKey,
|
|
3227
3332
|
isTrustedProxy,
|
|
3228
3333
|
logger,
|
package/package.json
CHANGED