@thexjs/core 1.3.4 → 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 +1 -1
- package/dist/{chunk-LV4CJQYM.js → chunk-VAWSOVGY.js} +110 -10
- package/dist/index.d.ts +211 -7
- package/dist/index.js +519 -103
- package/package.json +1 -1
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-
|
|
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
|
|
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 ?? "";
|
|
@@ -411,37 +417,33 @@ function htmlShell(title, headExtras, propsScript, scripts, bodySlot, navScriptT
|
|
|
411
417
|
</html>`;
|
|
412
418
|
}
|
|
413
419
|
function renderPage(node, options = {}) {
|
|
414
|
-
const { islandScripts, islandProps } = options;
|
|
415
|
-
const title = options.title ?? "x app";
|
|
416
420
|
const body = renderToString(node);
|
|
417
|
-
|
|
418
|
-
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
419
|
-
const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
|
|
420
|
-
return htmlShell(
|
|
421
|
-
title,
|
|
422
|
-
buildHeadExtras(options.stylesheet),
|
|
423
|
-
propsScript,
|
|
424
|
-
islandScriptsHtml,
|
|
425
|
-
body,
|
|
426
|
-
buildNavScriptTag(options.clientNav),
|
|
427
|
-
buildLiveReloadTag(options.liveReload)
|
|
428
|
-
);
|
|
421
|
+
return buildShellHtml(body, options, options.islandScripts ?? []);
|
|
429
422
|
}
|
|
430
423
|
function renderStaticPage(node, options = {}) {
|
|
431
|
-
const { islandScripts, islandProps } = options;
|
|
432
|
-
const title = options.title ?? "x app";
|
|
433
424
|
const body = renderToStaticMarkup(node);
|
|
425
|
+
return buildShellHtml(body, options, options.islandScripts ?? []);
|
|
426
|
+
}
|
|
427
|
+
async function renderPageOnce(node, options = {}) {
|
|
428
|
+
const body = renderToString(node);
|
|
429
|
+
const scripts = options.resolveIslandScripts ? await options.resolveIslandScripts() : options.islandScripts ?? [];
|
|
430
|
+
return buildShellHtml(body, options, scripts);
|
|
431
|
+
}
|
|
432
|
+
function buildShellHtml(body, options, islandScripts) {
|
|
433
|
+
const { islandProps } = options;
|
|
434
|
+
const title = options.title ?? "x app";
|
|
435
|
+
const nonce = options.cspNonce;
|
|
434
436
|
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
435
|
-
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
436
|
-
const islandScriptsHtml = islandScripts
|
|
437
|
+
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
|
|
438
|
+
const islandScriptsHtml = islandScripts.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
|
|
437
439
|
return htmlShell(
|
|
438
440
|
title,
|
|
439
441
|
buildHeadExtras(options.stylesheet),
|
|
440
442
|
propsScript,
|
|
441
443
|
islandScriptsHtml,
|
|
442
444
|
body,
|
|
443
|
-
buildNavScriptTag(options.clientNav),
|
|
444
|
-
buildLiveReloadTag(options.liveReload)
|
|
445
|
+
buildNavScriptTag(options.clientNav, nonce),
|
|
446
|
+
buildLiveReloadTag(options.liveReload, nonce)
|
|
445
447
|
);
|
|
446
448
|
}
|
|
447
449
|
function pumpStreamingResponse(source, options) {
|
|
@@ -458,9 +460,10 @@ function pumpStreamingResponse(source, options) {
|
|
|
458
460
|
const { done, value } = await reader.read();
|
|
459
461
|
if (done) {
|
|
460
462
|
if (!ended) {
|
|
463
|
+
const footerBytes = typeof footer === "function" ? await footer() : footer;
|
|
461
464
|
ended = true;
|
|
462
465
|
try {
|
|
463
|
-
controller.enqueue(
|
|
466
|
+
controller.enqueue(footerBytes);
|
|
464
467
|
} catch {
|
|
465
468
|
}
|
|
466
469
|
controller.close();
|
|
@@ -496,15 +499,12 @@ function pumpStreamingResponse(source, options) {
|
|
|
496
499
|
async function renderStreamingPage(node, options = {}) {
|
|
497
500
|
const { islandScripts, islandProps } = options;
|
|
498
501
|
const title = escapeHtml2(options.title ?? "x app");
|
|
502
|
+
const nonce = options.cspNonce;
|
|
499
503
|
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
500
|
-
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
501
|
-
const
|
|
502
|
-
const
|
|
503
|
-
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);
|
|
504
507
|
const headExtras = buildHeadExtras(options.stylesheet);
|
|
505
|
-
const rootFooter = `${propsScript ? ` ${propsScript}
|
|
506
|
-
` : ""}${islandScriptsHtml ? ` ${islandScriptsHtml}
|
|
507
|
-
` : ""}`;
|
|
508
508
|
const footer = `</div>${navScriptTag}
|
|
509
509
|
${liveReloadTag} </body>
|
|
510
510
|
</html>`;
|
|
@@ -525,8 +525,18 @@ ${liveReloadTag} </body>
|
|
|
525
525
|
<div id="root">`;
|
|
526
526
|
return pumpStreamingResponse(reactStream, {
|
|
527
527
|
header: encoder.encode(header),
|
|
528
|
-
footer:
|
|
529
|
-
|
|
528
|
+
// Lazy footer: the island script list may only be knowable after the
|
|
529
|
+
// render completed (single-render mode), so resolve it right before the
|
|
530
|
+
// closing tags are emitted rather than up front.
|
|
531
|
+
footer: async () => {
|
|
532
|
+
const scripts = islandScripts ?? await options.resolveIslandScripts?.() ?? [];
|
|
533
|
+
const islandScriptsHtml = scripts.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
|
|
534
|
+
const rootFooter = `${propsScript ? ` ${propsScript}
|
|
535
|
+
` : ""}${islandScriptsHtml ? ` ${islandScriptsHtml}
|
|
536
|
+
` : ""}`;
|
|
537
|
+
return encoder.encode(`${rootFooter}
|
|
538
|
+
${footer}`);
|
|
539
|
+
},
|
|
530
540
|
...options.onRenderError ? { onRenderError: options.onRenderError } : {}
|
|
531
541
|
});
|
|
532
542
|
}
|
|
@@ -789,17 +799,10 @@ function buildServerEntry(opts, configImportPath, stylesheetHref) {
|
|
|
789
799
|
"",
|
|
790
800
|
"// Request-level errors are caught inside createApp's fetch boundary;",
|
|
791
801
|
"// anything that still escapes (a throw outside the request lifecycle,",
|
|
792
|
-
"// a rejected promise from a background sweep) is
|
|
793
|
-
"// reporter so the box reports instead of dying.",
|
|
794
|
-
'const {
|
|
795
|
-
|
|
796
|
-
' reportException(err, { phase: "api" });',
|
|
797
|
-
' console.error("[x] uncaught exception:", err);',
|
|
798
|
-
"});",
|
|
799
|
-
'process.on("unhandledRejection", (reason) => {',
|
|
800
|
-
' reportException(reason, { phase: "api" });',
|
|
801
|
-
' console.error("[x] unhandled rejection:", reason);',
|
|
802
|
-
"});"
|
|
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();"
|
|
803
806
|
);
|
|
804
807
|
return lines.join("\n");
|
|
805
808
|
}
|
|
@@ -936,6 +939,7 @@ function renderErrorOverlay(error) {
|
|
|
936
939
|
}
|
|
937
940
|
|
|
938
941
|
// src/images/proxy.ts
|
|
942
|
+
var DEFAULT_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
939
943
|
var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
940
944
|
"image/png",
|
|
941
945
|
"image/jpeg",
|
|
@@ -944,8 +948,137 @@ var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
|
944
948
|
"image/avif",
|
|
945
949
|
"image/x-icon"
|
|
946
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
|
+
}
|
|
947
1078
|
function createImageProxyHandler(options = {}) {
|
|
948
1079
|
const allowedHosts = new Set(options.remoteHosts ?? []);
|
|
1080
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_IMAGE_BYTES;
|
|
1081
|
+
const resolveHost = options.resolveHost ?? resolveHostDefault;
|
|
949
1082
|
return async (req) => {
|
|
950
1083
|
const reqUrl = new URL(req.url);
|
|
951
1084
|
if (reqUrl.pathname !== "/_x/image") return null;
|
|
@@ -962,6 +1095,23 @@ function createImageProxyHandler(options = {}) {
|
|
|
962
1095
|
if (!allowedUrl(parsed)) {
|
|
963
1096
|
return new Response("host not allow-listed for image proxy", { status: 403 });
|
|
964
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
|
+
}
|
|
965
1115
|
const wParam = reqUrl.searchParams.get("w");
|
|
966
1116
|
const qParam = reqUrl.searchParams.get("q");
|
|
967
1117
|
if (wParam !== null) {
|
|
@@ -992,6 +1142,25 @@ function createImageProxyHandler(options = {}) {
|
|
|
992
1142
|
if (!allowedUrl(next)) {
|
|
993
1143
|
return new Response("upstream redirected off the allow-list", { status: 403 });
|
|
994
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
|
+
}
|
|
995
1164
|
upstream = await fetch(next, { redirect: "manual" });
|
|
996
1165
|
}
|
|
997
1166
|
} catch (err) {
|
|
@@ -1008,7 +1177,13 @@ function createImageProxyHandler(options = {}) {
|
|
|
1008
1177
|
if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
|
|
1009
1178
|
return new Response("upstream did not return an image", { status: 502 });
|
|
1010
1179
|
}
|
|
1011
|
-
|
|
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), {
|
|
1012
1187
|
status: 200,
|
|
1013
1188
|
headers: {
|
|
1014
1189
|
"Content-Type": contentType,
|
|
@@ -1104,13 +1279,36 @@ function createHealthCheckHandler(options = {}) {
|
|
|
1104
1279
|
};
|
|
1105
1280
|
}
|
|
1106
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
|
+
|
|
1107
1305
|
// src/observability/logger.ts
|
|
1108
1306
|
function write(level, message, fields) {
|
|
1109
1307
|
const entry = {
|
|
1110
1308
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1111
1309
|
level,
|
|
1112
|
-
message,
|
|
1113
|
-
...fields
|
|
1310
|
+
message: redactString(message),
|
|
1311
|
+
...redactValue(fields)
|
|
1114
1312
|
};
|
|
1115
1313
|
const line = JSON.stringify(entry);
|
|
1116
1314
|
if (level === "error") {
|
|
@@ -1155,7 +1353,9 @@ function withRequestLogging(handler) {
|
|
|
1155
1353
|
method: req.method,
|
|
1156
1354
|
status: 500,
|
|
1157
1355
|
durationMs: Math.round(performance.now() - start),
|
|
1158
|
-
|
|
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))
|
|
1159
1359
|
});
|
|
1160
1360
|
throw err;
|
|
1161
1361
|
}
|
|
@@ -1320,10 +1520,12 @@ function withRequestMetrics(reporter, handler) {
|
|
|
1320
1520
|
}
|
|
1321
1521
|
|
|
1322
1522
|
// src/security/headers.ts
|
|
1323
|
-
|
|
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
|
+
}
|
|
1324
1526
|
function buildSecurityHeaders(options = {}) {
|
|
1325
1527
|
const headers = new Headers();
|
|
1326
|
-
const csp = options.contentSecurityPolicy ??
|
|
1528
|
+
const csp = options.contentSecurityPolicy ?? defaultCsp(options.cspNonce);
|
|
1327
1529
|
if (csp !== false) headers.set("Content-Security-Policy", csp);
|
|
1328
1530
|
const hstsMaxAge = options.hstsMaxAge ?? 15552e3;
|
|
1329
1531
|
if (hstsMaxAge !== false) {
|
|
@@ -1367,9 +1569,9 @@ var IsrCache = class {
|
|
|
1367
1569
|
}
|
|
1368
1570
|
return entry;
|
|
1369
1571
|
}
|
|
1370
|
-
set(key, html) {
|
|
1572
|
+
set(key, html, cspNonce) {
|
|
1371
1573
|
this.entries.delete(key);
|
|
1372
|
-
this.entries.set(key, { html, timestamp: Date.now() });
|
|
1574
|
+
this.entries.set(key, { html, timestamp: Date.now(), cspNonce });
|
|
1373
1575
|
this.evict();
|
|
1374
1576
|
}
|
|
1375
1577
|
delete(key) {
|
|
@@ -1401,13 +1603,12 @@ var IsrCache = class {
|
|
|
1401
1603
|
*/
|
|
1402
1604
|
getOrCompute(key, compute) {
|
|
1403
1605
|
const cached = this.get(key);
|
|
1404
|
-
if (cached) return Promise.resolve(cached.html);
|
|
1606
|
+
if (cached) return Promise.resolve({ html: cached.html, cspNonce: cached.cspNonce });
|
|
1405
1607
|
const existing = this.inFlight.get(key);
|
|
1406
1608
|
if (existing) return existing;
|
|
1407
1609
|
const promise = compute().then((result) => {
|
|
1408
|
-
if (
|
|
1409
|
-
|
|
1410
|
-
}
|
|
1610
|
+
if (result instanceof Response) return result;
|
|
1611
|
+
this.set(key, result.html, result.cspNonce);
|
|
1411
1612
|
return result;
|
|
1412
1613
|
}).finally(() => {
|
|
1413
1614
|
this.inFlight.delete(key);
|
|
@@ -1577,7 +1778,7 @@ function wrapWithLayouts(Component, params, loaderData, layoutModules) {
|
|
|
1577
1778
|
}
|
|
1578
1779
|
return content;
|
|
1579
1780
|
}
|
|
1580
|
-
function renderContentPage(content, stylesheet, dev = false) {
|
|
1781
|
+
function renderContentPage(content, stylesheet, dev = false, nonce) {
|
|
1581
1782
|
const title = content.frontmatter.title ?? content.slug;
|
|
1582
1783
|
const bodyHtml = renderMarkdown(content.body);
|
|
1583
1784
|
const body = renderPage(
|
|
@@ -1590,7 +1791,12 @@ function renderContentPage(content, stylesheet, dev = false) {
|
|
|
1590
1791
|
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
1591
1792
|
})
|
|
1592
1793
|
),
|
|
1593
|
-
{
|
|
1794
|
+
{
|
|
1795
|
+
title,
|
|
1796
|
+
stylesheet,
|
|
1797
|
+
liveReload: dev,
|
|
1798
|
+
...nonce ? { cspNonce: nonce } : {}
|
|
1799
|
+
}
|
|
1594
1800
|
);
|
|
1595
1801
|
return body;
|
|
1596
1802
|
}
|
|
@@ -1652,23 +1858,42 @@ async function createApp(options) {
|
|
|
1652
1858
|
const healthHandler = createHealthCheckHandler(options.observability?.health ?? {});
|
|
1653
1859
|
const metricsReporter = options.observability?.metrics;
|
|
1654
1860
|
const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
|
|
1861
|
+
const maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;
|
|
1655
1862
|
const securityHeadersOptions = options.security?.headers;
|
|
1656
1863
|
const loggingEnabled = options.observability?.logging ?? true;
|
|
1657
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
|
+
}
|
|
1658
1873
|
function withResponseHardening(res) {
|
|
1659
|
-
|
|
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
|
+
});
|
|
1660
1881
|
}
|
|
1661
1882
|
async function renderNotFound(_req) {
|
|
1662
1883
|
const content = notFoundLayout ? createElement2(notFoundLayout, null, createElement2(notFoundComponent, { params: {} })) : createElement2(notFoundComponent, { params: {} });
|
|
1884
|
+
const cspNonce = generateCspNonce();
|
|
1663
1885
|
const html = renderPage(content, {
|
|
1664
1886
|
title: "404 \u2014 Not Found",
|
|
1665
1887
|
stylesheet: stylesheetHref,
|
|
1666
|
-
liveReload: dev
|
|
1888
|
+
liveReload: dev,
|
|
1889
|
+
cspNonce
|
|
1667
1890
|
});
|
|
1668
|
-
|
|
1891
|
+
const res = new Response(html, {
|
|
1669
1892
|
status: 404,
|
|
1670
1893
|
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
1671
1894
|
});
|
|
1895
|
+
res.headers.set(CSP_NONCE_HEADER, cspNonce);
|
|
1896
|
+
return res;
|
|
1672
1897
|
}
|
|
1673
1898
|
const makeApiHandler = (route, module) => async (req) => {
|
|
1674
1899
|
try {
|
|
@@ -1684,6 +1909,9 @@ async function createApp(options) {
|
|
|
1684
1909
|
}
|
|
1685
1910
|
return new Response(`Method ${method} not allowed`, { status: 405 });
|
|
1686
1911
|
} catch (err) {
|
|
1912
|
+
if (err instanceof RequestBodyTooLargeError) {
|
|
1913
|
+
return new Response("Payload too large", { status: 413 });
|
|
1914
|
+
}
|
|
1687
1915
|
reportException(err, { route: route.routePath, phase: "api" });
|
|
1688
1916
|
metricsReporter?.incr("x_http_errors_total", 1, { phase: "api" });
|
|
1689
1917
|
console.error("[x] API handler error:", err);
|
|
@@ -1716,9 +1944,9 @@ async function createApp(options) {
|
|
|
1716
1944
|
if (mode === "server") {
|
|
1717
1945
|
let loaderData = {};
|
|
1718
1946
|
if (loader) {
|
|
1719
|
-
const
|
|
1720
|
-
if (
|
|
1721
|
-
loaderData =
|
|
1947
|
+
const result2 = await loader(ctx);
|
|
1948
|
+
if (result2 instanceof Response) return result2;
|
|
1949
|
+
loaderData = result2;
|
|
1722
1950
|
}
|
|
1723
1951
|
const registry = createIslandRegistry();
|
|
1724
1952
|
const content = createElement2(
|
|
@@ -1726,47 +1954,51 @@ async function createApp(options) {
|
|
|
1726
1954
|
{ registry },
|
|
1727
1955
|
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
|
|
1728
1956
|
);
|
|
1729
|
-
|
|
1730
|
-
if (scripts === void 0) {
|
|
1731
|
-
renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
|
|
1732
|
-
scripts = await resolveIslandScripts(
|
|
1733
|
-
route.filePath,
|
|
1734
|
-
layoutFilePaths,
|
|
1735
|
-
registry.entries
|
|
1736
|
-
);
|
|
1737
|
-
}
|
|
1957
|
+
const cspNonce = generateCspNonce();
|
|
1738
1958
|
const stream = await renderStreamingPage(content, {
|
|
1739
1959
|
stylesheet: stylesheetHref,
|
|
1740
1960
|
liveReload: dev,
|
|
1741
|
-
|
|
1961
|
+
cspNonce,
|
|
1962
|
+
...islandScripts === void 0 ? {
|
|
1963
|
+
// Single-render mode: islands register into `registry`
|
|
1964
|
+
// during the one render that produces the HTML, and the
|
|
1965
|
+
// script list is resolved from that same pass in the lazy
|
|
1966
|
+
// footer — no separate discovery render, so non-deterministic
|
|
1967
|
+
// components can't diverge between two passes.
|
|
1968
|
+
resolveIslandScripts: () => resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries)
|
|
1969
|
+
} : { islandScripts },
|
|
1742
1970
|
onRenderError: (error) => {
|
|
1743
1971
|
reportException(error, { route: route.routePath, phase: "ssr" });
|
|
1744
1972
|
metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
|
|
1745
1973
|
}
|
|
1746
1974
|
});
|
|
1747
|
-
|
|
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
|
-
|
|
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
|
|
1768
|
-
if (
|
|
1769
|
-
loaderData =
|
|
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,39 +2006,39 @@ async function createApp(options) {
|
|
|
1774
2006
|
{ registry },
|
|
1775
2007
|
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
|
|
1776
2008
|
);
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
|
|
1780
|
-
scripts = await resolveIslandScripts(
|
|
1781
|
-
route.filePath,
|
|
1782
|
-
layoutFilePaths,
|
|
1783
|
-
registry.entries
|
|
1784
|
-
);
|
|
1785
|
-
}
|
|
1786
|
-
return renderPage(content, {
|
|
2009
|
+
const cspNonce = generateCspNonce();
|
|
2010
|
+
const html = await renderPageOnce(content, {
|
|
1787
2011
|
stylesheet: stylesheetHref,
|
|
1788
2012
|
liveReload: dev,
|
|
1789
|
-
|
|
2013
|
+
cspNonce,
|
|
2014
|
+
...islandScripts === void 0 ? {
|
|
2015
|
+
resolveIslandScripts: () => resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries)
|
|
2016
|
+
} : { islandScripts }
|
|
1790
2017
|
});
|
|
2018
|
+
return { html, cspNonce };
|
|
1791
2019
|
};
|
|
1792
2020
|
if (revalidateSeconds > 0) {
|
|
1793
|
-
const
|
|
1794
|
-
if (
|
|
1795
|
-
|
|
2021
|
+
const result2 = await staticCache.getOrCompute(cacheKey, computeHtml);
|
|
2022
|
+
if (result2 instanceof Response) return result2;
|
|
2023
|
+
const res2 = new Response(result2.html, {
|
|
1796
2024
|
headers: {
|
|
1797
2025
|
"Content-Type": "text/html; charset=utf-8",
|
|
1798
2026
|
"X-Revalidated": "miss"
|
|
1799
2027
|
}
|
|
1800
2028
|
});
|
|
2029
|
+
res2.headers.set(CSP_NONCE_HEADER, result2.cspNonce);
|
|
2030
|
+
return res2;
|
|
1801
2031
|
}
|
|
1802
|
-
const
|
|
1803
|
-
if (
|
|
1804
|
-
|
|
2032
|
+
const result = await computeHtml();
|
|
2033
|
+
if (result instanceof Response) return result;
|
|
2034
|
+
const res = new Response(result.html, {
|
|
1805
2035
|
headers: {
|
|
1806
2036
|
"Content-Type": "text/html; charset=utf-8",
|
|
1807
2037
|
"X-Revalidated": "none"
|
|
1808
2038
|
}
|
|
1809
2039
|
});
|
|
2040
|
+
res.headers.set(CSP_NONCE_HEADER, result.cspNonce);
|
|
2041
|
+
return res;
|
|
1810
2042
|
};
|
|
1811
2043
|
if (middlewareModules.length > 0) {
|
|
1812
2044
|
const composed = composeMiddleware(middlewareModules, baseHandler);
|
|
@@ -1817,6 +2049,9 @@ async function createApp(options) {
|
|
|
1817
2049
|
}
|
|
1818
2050
|
return baseHandler({ params, request: req });
|
|
1819
2051
|
} catch (err) {
|
|
2052
|
+
if (err instanceof RequestBodyTooLargeError) {
|
|
2053
|
+
return new Response("Payload too large", { status: 413 });
|
|
2054
|
+
}
|
|
1820
2055
|
reportException(err, { route: route.routePath, phase: "ssr" });
|
|
1821
2056
|
metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
|
|
1822
2057
|
console.error("[x] route handler error:", err);
|
|
@@ -2019,16 +2254,24 @@ async function createApp(options) {
|
|
|
2019
2254
|
const loadedContent = content.map((entry) => ({
|
|
2020
2255
|
entry,
|
|
2021
2256
|
handler: async () => {
|
|
2022
|
-
const
|
|
2023
|
-
|
|
2257
|
+
const cspNonce = generateCspNonce();
|
|
2258
|
+
const html = renderContentPage(entry, stylesheetHref, dev, cspNonce);
|
|
2259
|
+
const res = new Response(html, {
|
|
2024
2260
|
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
2025
2261
|
});
|
|
2262
|
+
res.headers.set(CSP_NONCE_HEADER, cspNonce);
|
|
2263
|
+
return res;
|
|
2026
2264
|
}
|
|
2027
2265
|
}));
|
|
2028
2266
|
contentHandlers = loadedContent;
|
|
2029
2267
|
}
|
|
2030
2268
|
}
|
|
2031
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
|
+
};
|
|
2032
2275
|
async function guardFetchErrors(inner, req, server) {
|
|
2033
2276
|
try {
|
|
2034
2277
|
return await inner(req, server);
|
|
@@ -2053,7 +2296,10 @@ async function createApp(options) {
|
|
|
2053
2296
|
let body;
|
|
2054
2297
|
try {
|
|
2055
2298
|
body = await req.json();
|
|
2056
|
-
} catch {
|
|
2299
|
+
} catch (err) {
|
|
2300
|
+
if (err instanceof RequestBodyTooLargeError) {
|
|
2301
|
+
return new Response("Payload too large", { status: 413 });
|
|
2302
|
+
}
|
|
2057
2303
|
return new Response("Invalid JSON body", { status: 400 });
|
|
2058
2304
|
}
|
|
2059
2305
|
if (body.path) {
|
|
@@ -2063,6 +2309,37 @@ async function createApp(options) {
|
|
|
2063
2309
|
staticCache.clear();
|
|
2064
2310
|
return new Response("Revalidated all");
|
|
2065
2311
|
}
|
|
2312
|
+
async function handleHydrationMismatch(req) {
|
|
2313
|
+
if (new URL(req.url).pathname !== "/__x/hydration-mismatch") return null;
|
|
2314
|
+
if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
|
|
2315
|
+
const origin = req.headers.get("origin");
|
|
2316
|
+
const referer = req.headers.get("referer");
|
|
2317
|
+
const selfOrigin = `${new URL(req.url).protocol}//${new URL(req.url).host}`;
|
|
2318
|
+
const attempt = origin ?? referer;
|
|
2319
|
+
if (attempt && !attempt.startsWith(selfOrigin)) {
|
|
2320
|
+
return new Response("Forbidden", { status: 403 });
|
|
2321
|
+
}
|
|
2322
|
+
let body;
|
|
2323
|
+
try {
|
|
2324
|
+
const text = await req.text();
|
|
2325
|
+
if (text.length > 2048) return new Response("Payload too large", { status: 413 });
|
|
2326
|
+
body = JSON.parse(text);
|
|
2327
|
+
} catch (err) {
|
|
2328
|
+
if (err instanceof RequestBodyTooLargeError) {
|
|
2329
|
+
return new Response("Payload too large", { status: 413 });
|
|
2330
|
+
}
|
|
2331
|
+
return new Response("Invalid JSON body", { status: 400 });
|
|
2332
|
+
}
|
|
2333
|
+
const error = new Error(body.error ?? "hydration mismatch");
|
|
2334
|
+
const routeFromUrl = body.url ? new URL(body.url).pathname : "/";
|
|
2335
|
+
reportException(error, {
|
|
2336
|
+
route: routeFromUrl,
|
|
2337
|
+
phase: "ssr",
|
|
2338
|
+
tag: "hydration-mismatch"
|
|
2339
|
+
});
|
|
2340
|
+
metricsReporter?.incr("x_http_hydration_mismatch", 1, { island: body.island ?? "unknown" });
|
|
2341
|
+
return new Response(null, { status: 204 });
|
|
2342
|
+
}
|
|
2066
2343
|
if (options.development) {
|
|
2067
2344
|
let notifyClients2 = function() {
|
|
2068
2345
|
for (const send of sseClients) {
|
|
@@ -2177,6 +2454,8 @@ data: ${data}
|
|
|
2177
2454
|
}
|
|
2178
2455
|
const revalidationResult = await handleRevalidation(req);
|
|
2179
2456
|
if (revalidationResult !== null) return revalidationResult;
|
|
2457
|
+
const mismatchResult = await handleHydrationMismatch(req);
|
|
2458
|
+
if (mismatchResult !== null) return mismatchResult;
|
|
2180
2459
|
const serverFnResult = await serverFnHandler(req);
|
|
2181
2460
|
if (serverFnResult !== null) return serverFnResult;
|
|
2182
2461
|
const staticAsset = await serveStaticAsset(publicDir, req);
|
|
@@ -2198,7 +2477,7 @@ data: ${data}
|
|
|
2198
2477
|
}
|
|
2199
2478
|
return renderNotFound(req);
|
|
2200
2479
|
};
|
|
2201
|
-
const devFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(devFetchInner, req, server));
|
|
2480
|
+
const devFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(devFetchInner), req, server));
|
|
2202
2481
|
const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
|
|
2203
2482
|
const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchBase) : devFetchBase;
|
|
2204
2483
|
return {
|
|
@@ -2233,6 +2512,8 @@ data: ${data}
|
|
|
2233
2512
|
}
|
|
2234
2513
|
const revalidationResult = await handleRevalidation(req);
|
|
2235
2514
|
if (revalidationResult !== null) return revalidationResult;
|
|
2515
|
+
const mismatchResult = await handleHydrationMismatch(req);
|
|
2516
|
+
if (mismatchResult !== null) return mismatchResult;
|
|
2236
2517
|
const serverFnResult = await serverFnHandler(req);
|
|
2237
2518
|
if (serverFnResult !== null) return serverFnResult;
|
|
2238
2519
|
const staticAsset = await serveStaticAsset(publicDir, req);
|
|
@@ -2254,7 +2535,7 @@ data: ${data}
|
|
|
2254
2535
|
}
|
|
2255
2536
|
return renderNotFound(req);
|
|
2256
2537
|
};
|
|
2257
|
-
const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(prodFetchInner, req, server));
|
|
2538
|
+
const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(prodFetchInner), req, server));
|
|
2258
2539
|
const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
|
|
2259
2540
|
const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchBase) : prodFetchBase;
|
|
2260
2541
|
return {
|
|
@@ -2393,9 +2674,123 @@ function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
|
|
|
2393
2674
|
}
|
|
2394
2675
|
);
|
|
2395
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
|
+
}
|
|
2396
2790
|
export {
|
|
2397
2791
|
CLIENT_NAV_SCRIPT,
|
|
2398
2792
|
DEFAULT_HISTOGRAM_BUCKETS_MS,
|
|
2793
|
+
DEFAULT_MAX_BODY_SIZE,
|
|
2399
2794
|
DefaultNotFound,
|
|
2400
2795
|
EnvLeakageError,
|
|
2401
2796
|
Image,
|
|
@@ -2403,16 +2798,28 @@ export {
|
|
|
2403
2798
|
IslandProvider,
|
|
2404
2799
|
Link,
|
|
2405
2800
|
PUBLIC_ENV_PREFIX,
|
|
2801
|
+
REDACTED,
|
|
2802
|
+
RequestBodyTooLargeError,
|
|
2406
2803
|
SRCSET_WIDTHS,
|
|
2407
2804
|
applySecurityHeaders,
|
|
2408
2805
|
assertNoEnvLeakage,
|
|
2806
|
+
audit,
|
|
2807
|
+
auditLoginFailure,
|
|
2808
|
+
auditLoginSuccess,
|
|
2809
|
+
auditLogout,
|
|
2810
|
+
auditPasswordChanged,
|
|
2811
|
+
auditPermissionDenied,
|
|
2812
|
+
auditRoleChanged,
|
|
2813
|
+
auditSessionRevoked,
|
|
2409
2814
|
build,
|
|
2410
2815
|
buildSecurityHeaders,
|
|
2411
2816
|
buildSrcSet,
|
|
2412
2817
|
checkCsrf,
|
|
2818
|
+
clientIpFromRequest,
|
|
2413
2819
|
combineReporters,
|
|
2414
2820
|
composeMiddleware,
|
|
2415
2821
|
createApp,
|
|
2822
|
+
createConsoleAuditSink,
|
|
2416
2823
|
createHealthCheckHandler,
|
|
2417
2824
|
createImageProxyHandler,
|
|
2418
2825
|
createInMemoryMetrics,
|
|
@@ -2422,6 +2829,7 @@ export {
|
|
|
2422
2829
|
createRedisRateLimitStore,
|
|
2423
2830
|
createSentryReporter,
|
|
2424
2831
|
defineConfig,
|
|
2832
|
+
enforceRequestBodySize,
|
|
2425
2833
|
escapeHtml,
|
|
2426
2834
|
findLayoutChain,
|
|
2427
2835
|
findLeakedEnvKeys,
|
|
@@ -2429,12 +2837,18 @@ export {
|
|
|
2429
2837
|
generateCsrfToken,
|
|
2430
2838
|
generateManifestSource,
|
|
2431
2839
|
generateServerFunctionClient,
|
|
2840
|
+
getAuditSink,
|
|
2432
2841
|
getErrorReporter,
|
|
2433
2842
|
getServerFunctionHandler,
|
|
2843
|
+
installProcessCrashHandlers,
|
|
2844
|
+
isSensitiveKey,
|
|
2434
2845
|
logger,
|
|
2846
|
+
noopAuditSink,
|
|
2435
2847
|
noopMetrics,
|
|
2436
2848
|
noopReporter,
|
|
2437
2849
|
rateLimitMiddleware,
|
|
2850
|
+
redactString,
|
|
2851
|
+
redactValue,
|
|
2438
2852
|
registerServerFunctions,
|
|
2439
2853
|
renderErrorOverlay,
|
|
2440
2854
|
renderMarkdown,
|
|
@@ -2442,6 +2856,7 @@ export {
|
|
|
2442
2856
|
renderStaticPage,
|
|
2443
2857
|
renderStreamingPage,
|
|
2444
2858
|
reportException,
|
|
2859
|
+
requestIdFromRequest,
|
|
2445
2860
|
resetServerFunctions,
|
|
2446
2861
|
scanApiDir,
|
|
2447
2862
|
scanContent,
|
|
@@ -2451,6 +2866,7 @@ export {
|
|
|
2451
2866
|
scanNotFound,
|
|
2452
2867
|
scanPages,
|
|
2453
2868
|
scanRoutes,
|
|
2869
|
+
setAuditSink,
|
|
2454
2870
|
setErrorReporter,
|
|
2455
2871
|
setImageRemoteHosts,
|
|
2456
2872
|
verifyCsrfToken,
|