@thexjs/core 1.3.5 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/dist/adapter.js +2 -1
- package/dist/{chunk-PQ7ZVWEJ.js → chunk-VC5XI6HX.js} +113 -7
- package/dist/chunk-VIXLBKMC.js +170 -0
- package/dist/data.d.ts +0 -1
- package/dist/data.js +89 -21
- package/dist/index.d.ts +274 -7
- package/dist/index.js +559 -98
- 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,
|
|
@@ -19,8 +22,10 @@ import {
|
|
|
19
22
|
getServerFunctionHandler,
|
|
20
23
|
islandEntryId,
|
|
21
24
|
noopReporter,
|
|
25
|
+
originFromHeader,
|
|
22
26
|
registerServerFunctions,
|
|
23
27
|
reportException,
|
|
28
|
+
requestOrigin,
|
|
24
29
|
resetServerFunctions,
|
|
25
30
|
scanApiDir,
|
|
26
31
|
scanLayouts,
|
|
@@ -34,7 +39,22 @@ import {
|
|
|
34
39
|
verifyOrigin,
|
|
35
40
|
withCsrfCookie,
|
|
36
41
|
writeManifest
|
|
37
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-VC5XI6HX.js";
|
|
43
|
+
import {
|
|
44
|
+
OTEL_ERROR_STATUS_CODE,
|
|
45
|
+
REDACTED,
|
|
46
|
+
dbTraceAttributes,
|
|
47
|
+
getTracer,
|
|
48
|
+
isSensitiveKey,
|
|
49
|
+
redactString,
|
|
50
|
+
redactValue,
|
|
51
|
+
runWithRequestSpan,
|
|
52
|
+
setTracer,
|
|
53
|
+
tracePhase,
|
|
54
|
+
tracePhaseSync,
|
|
55
|
+
traceRequestId,
|
|
56
|
+
withRequestTracing
|
|
57
|
+
} from "./chunk-VIXLBKMC.js";
|
|
38
58
|
|
|
39
59
|
// src/build.ts
|
|
40
60
|
import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
|
|
@@ -384,13 +404,16 @@ function buildHeadExtras(stylesheet) {
|
|
|
384
404
|
return stylesheet ? `
|
|
385
405
|
<link rel="stylesheet" href="${escapeHtml2(stylesheet)}" />` : "";
|
|
386
406
|
}
|
|
387
|
-
function
|
|
407
|
+
function nonceAttr(nonce) {
|
|
408
|
+
return nonce ? ` nonce="${nonce}"` : "";
|
|
409
|
+
}
|
|
410
|
+
function buildNavScriptTag(clientNav, nonce) {
|
|
388
411
|
return clientNav === false ? "" : `
|
|
389
|
-
<script>${CLIENT_NAV_SCRIPT}</script>`;
|
|
412
|
+
<script${nonceAttr(nonce)}>${CLIENT_NAV_SCRIPT}</script>`;
|
|
390
413
|
}
|
|
391
|
-
function buildLiveReloadTag(liveReload) {
|
|
414
|
+
function buildLiveReloadTag(liveReload, nonce) {
|
|
392
415
|
return liveReload ? `
|
|
393
|
-
<script>${LIVE_RELOAD_SCRIPT}</script>` : "";
|
|
416
|
+
<script${nonceAttr(nonce)}>${LIVE_RELOAD_SCRIPT}</script>` : "";
|
|
394
417
|
}
|
|
395
418
|
function htmlShell(title, headExtras, propsScript, scripts, bodySlot, navScriptTag, liveReloadTag) {
|
|
396
419
|
const finalScripts = scripts ?? "";
|
|
@@ -426,8 +449,9 @@ async function renderPageOnce(node, options = {}) {
|
|
|
426
449
|
function buildShellHtml(body, options, islandScripts) {
|
|
427
450
|
const { islandProps } = options;
|
|
428
451
|
const title = options.title ?? "x app";
|
|
452
|
+
const nonce = options.cspNonce;
|
|
429
453
|
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
430
|
-
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
454
|
+
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
|
|
431
455
|
const islandScriptsHtml = islandScripts.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
|
|
432
456
|
return htmlShell(
|
|
433
457
|
title,
|
|
@@ -435,8 +459,8 @@ function buildShellHtml(body, options, islandScripts) {
|
|
|
435
459
|
propsScript,
|
|
436
460
|
islandScriptsHtml,
|
|
437
461
|
body,
|
|
438
|
-
buildNavScriptTag(options.clientNav),
|
|
439
|
-
buildLiveReloadTag(options.liveReload)
|
|
462
|
+
buildNavScriptTag(options.clientNav, nonce),
|
|
463
|
+
buildLiveReloadTag(options.liveReload, nonce)
|
|
440
464
|
);
|
|
441
465
|
}
|
|
442
466
|
function pumpStreamingResponse(source, options) {
|
|
@@ -492,10 +516,11 @@ function pumpStreamingResponse(source, options) {
|
|
|
492
516
|
async function renderStreamingPage(node, options = {}) {
|
|
493
517
|
const { islandScripts, islandProps } = options;
|
|
494
518
|
const title = escapeHtml2(options.title ?? "x app");
|
|
519
|
+
const nonce = options.cspNonce;
|
|
495
520
|
const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
|
|
496
|
-
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
|
|
497
|
-
const navScriptTag = buildNavScriptTag(options.clientNav);
|
|
498
|
-
const liveReloadTag = buildLiveReloadTag(options.liveReload);
|
|
521
|
+
const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
|
|
522
|
+
const navScriptTag = buildNavScriptTag(options.clientNav, nonce);
|
|
523
|
+
const liveReloadTag = buildLiveReloadTag(options.liveReload, nonce);
|
|
499
524
|
const headExtras = buildHeadExtras(options.stylesheet);
|
|
500
525
|
const footer = `</div>${navScriptTag}
|
|
501
526
|
${liveReloadTag} </body>
|
|
@@ -791,17 +816,10 @@ function buildServerEntry(opts, configImportPath, stylesheetHref) {
|
|
|
791
816
|
"",
|
|
792
817
|
"// Request-level errors are caught inside createApp's fetch boundary;",
|
|
793
818
|
"// anything that still escapes (a throw outside the request lifecycle,",
|
|
794
|
-
"// a rejected promise from a background sweep) is
|
|
795
|
-
"// reporter so the box reports instead of dying.",
|
|
796
|
-
'const {
|
|
797
|
-
|
|
798
|
-
' reportException(err, { phase: "api" });',
|
|
799
|
-
' console.error("[x] uncaught exception:", err);',
|
|
800
|
-
"});",
|
|
801
|
-
'process.on("unhandledRejection", (reason) => {',
|
|
802
|
-
' reportException(reason, { phase: "api" });',
|
|
803
|
-
' console.error("[x] unhandled rejection:", reason);',
|
|
804
|
-
"});"
|
|
819
|
+
"// a rejected promise from a background sweep) is reported through the",
|
|
820
|
+
"// error reporter so the box reports instead of dying silently.",
|
|
821
|
+
'const { installProcessCrashHandlers } = await import("@thexjs/core");',
|
|
822
|
+
"installProcessCrashHandlers();"
|
|
805
823
|
);
|
|
806
824
|
return lines.join("\n");
|
|
807
825
|
}
|
|
@@ -938,6 +956,7 @@ function renderErrorOverlay(error) {
|
|
|
938
956
|
}
|
|
939
957
|
|
|
940
958
|
// src/images/proxy.ts
|
|
959
|
+
var DEFAULT_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
941
960
|
var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
942
961
|
"image/png",
|
|
943
962
|
"image/jpeg",
|
|
@@ -946,8 +965,172 @@ var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
|
946
965
|
"image/avif",
|
|
947
966
|
"image/x-icon"
|
|
948
967
|
]);
|
|
968
|
+
var RFC2606_RESERVED_TLD = /\.(example|test|invalid|localhost)$|^(localhost)$/;
|
|
969
|
+
var UpstreamImageTooLargeError = class extends Error {
|
|
970
|
+
maxBytes;
|
|
971
|
+
constructor(maxBytes) {
|
|
972
|
+
super(`Upstream image exceeds the ${maxBytes} byte limit`);
|
|
973
|
+
this.name = "UpstreamImageTooLargeError";
|
|
974
|
+
this.maxBytes = maxBytes;
|
|
975
|
+
}
|
|
976
|
+
};
|
|
977
|
+
function isIpLiteral(host) {
|
|
978
|
+
const stem = host.startsWith("[") ? host.slice(1, -1) : host;
|
|
979
|
+
return /^\d{1,3}(\.\d{1,3}){3}$/.test(stem) || stem.includes(":");
|
|
980
|
+
}
|
|
981
|
+
function isPrivateOrReservedAddress(host) {
|
|
982
|
+
const stem = host.startsWith("[") ? host.slice(1, -1) : host;
|
|
983
|
+
if (!stem.includes(":") && /^\d{1,3}(\.\d{1,3}){3}$/.test(stem)) {
|
|
984
|
+
const parts = stem.split(".").map((o) => Number(o));
|
|
985
|
+
if (parts.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) return false;
|
|
986
|
+
return isPrivateOrReservedIPv4(parts);
|
|
987
|
+
}
|
|
988
|
+
if (stem.includes(":")) {
|
|
989
|
+
const v4Match = /(\d{1,3}(?:\.\d{1,3}){3})$/.exec(stem);
|
|
990
|
+
if (v4Match) {
|
|
991
|
+
const octets = (v4Match[1] ?? "").split(".").map((o) => Number(o));
|
|
992
|
+
return isPrivateOrReservedIPv4(octets);
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
const groups = ipv6Groups(stem);
|
|
996
|
+
if (groups) return isPrivateOrReservedIPv6(groups);
|
|
997
|
+
return false;
|
|
998
|
+
}
|
|
999
|
+
function isPrivateOrReservedIPv4(parts) {
|
|
1000
|
+
const [a = 0, b = 0, c = 0] = parts;
|
|
1001
|
+
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;
|
|
1002
|
+
}
|
|
1003
|
+
function ipv6Groups(ip) {
|
|
1004
|
+
let head = ip;
|
|
1005
|
+
let tailV4 = null;
|
|
1006
|
+
const lastColon = ip.lastIndexOf(":");
|
|
1007
|
+
if (lastColon !== -1) {
|
|
1008
|
+
const tail = ip.slice(lastColon + 1);
|
|
1009
|
+
if (tail.includes(".")) {
|
|
1010
|
+
const [v0 = 0, v1 = 0, v2 = 0, v3 = 0] = tail.split(".").map((o) => Number(o));
|
|
1011
|
+
if (v0 > 255 || v1 > 255 || v2 > 255 || v3 > 255) {
|
|
1012
|
+
return null;
|
|
1013
|
+
}
|
|
1014
|
+
tailV4 = [v0 * 256 + v1, v2 * 256 + v3];
|
|
1015
|
+
head = ip.slice(0, lastColon);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
const doubleColon = head.indexOf("::");
|
|
1019
|
+
let left = "";
|
|
1020
|
+
let right = "";
|
|
1021
|
+
if (doubleColon !== -1) {
|
|
1022
|
+
left = head.slice(0, doubleColon);
|
|
1023
|
+
right = head.slice(doubleColon + 2);
|
|
1024
|
+
} else {
|
|
1025
|
+
left = head;
|
|
1026
|
+
}
|
|
1027
|
+
const parseGroups = (s, out) => {
|
|
1028
|
+
if (s === "") return true;
|
|
1029
|
+
for (const part of s.split(":")) {
|
|
1030
|
+
if (!/^[0-9a-fA-F]{1,4}$/.test(part)) return false;
|
|
1031
|
+
out.push(Number.parseInt(part, 16));
|
|
1032
|
+
}
|
|
1033
|
+
return true;
|
|
1034
|
+
};
|
|
1035
|
+
const l = [];
|
|
1036
|
+
const r = [];
|
|
1037
|
+
if (!parseGroups(left, l) || !parseGroups(right, r)) return null;
|
|
1038
|
+
if (doubleColon !== -1) {
|
|
1039
|
+
const zeros = 8 - l.length - r.length - (tailV4?.length ?? 0);
|
|
1040
|
+
if (zeros < 1) return null;
|
|
1041
|
+
return [...l, ...new Array(zeros).fill(0), ...r, ...tailV4 ?? []];
|
|
1042
|
+
}
|
|
1043
|
+
const all = [...l, ...tailV4 ?? [], ...r];
|
|
1044
|
+
return all.length === 8 ? all : null;
|
|
1045
|
+
}
|
|
1046
|
+
function isPrivateOrReservedIPv6(groups) {
|
|
1047
|
+
const [a = 0, b = 0, , , , , , last = 0] = groups;
|
|
1048
|
+
return a === 0 && last === 1 || // loopback ::1
|
|
1049
|
+
groups.every((g) => g === 0) || // unspecified ::
|
|
1050
|
+
(a & 65024) === 64512 || // unique local fc00::/7
|
|
1051
|
+
(a & 65472) === 65152 || // link-local fe80::/10
|
|
1052
|
+
(a & 65280) === 65280 || // multicast ff00::/8
|
|
1053
|
+
a === 8193 && b === 3512 || // documentation 2001:db8::/32
|
|
1054
|
+
a === 100 && b === 65435 || // NAT64 64:ff9b::/96
|
|
1055
|
+
a === 8193 && b === 16;
|
|
1056
|
+
}
|
|
1057
|
+
async function resolveHostDefault(hostname) {
|
|
1058
|
+
if (RFC2606_RESERVED_TLD.test(hostname)) return [];
|
|
1059
|
+
try {
|
|
1060
|
+
const results = await Bun.dns.lookup(hostname);
|
|
1061
|
+
return results.map((r) => r.address);
|
|
1062
|
+
} catch {
|
|
1063
|
+
return [];
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
function urlForIp(target, ip) {
|
|
1067
|
+
const pinned = new URL(target.toString());
|
|
1068
|
+
pinned.hostname = ip.includes(":") ? `[${ip}]` : ip;
|
|
1069
|
+
return pinned;
|
|
1070
|
+
}
|
|
1071
|
+
function pinToVerifiedIp(target, verifiedIp) {
|
|
1072
|
+
const init = { redirect: "manual", headers: { host: target.host } };
|
|
1073
|
+
if (target.protocol === "https:") {
|
|
1074
|
+
init.tls = { serverName: target.hostname };
|
|
1075
|
+
}
|
|
1076
|
+
return { url: urlForIp(target, verifiedIp), init };
|
|
1077
|
+
}
|
|
1078
|
+
async function resolveProxyTarget(target, resolveHost) {
|
|
1079
|
+
if (isIpLiteral(target.hostname)) {
|
|
1080
|
+
if (isPrivateOrReservedAddress(target.hostname)) {
|
|
1081
|
+
return { status: "reject-literal" };
|
|
1082
|
+
}
|
|
1083
|
+
return { status: "ok", url: target, init: { redirect: "manual" } };
|
|
1084
|
+
}
|
|
1085
|
+
let ips = [];
|
|
1086
|
+
try {
|
|
1087
|
+
ips = await resolveHost(target.hostname);
|
|
1088
|
+
} catch {
|
|
1089
|
+
ips = [];
|
|
1090
|
+
}
|
|
1091
|
+
if (ips.some((ip) => isPrivateOrReservedAddress(ip))) {
|
|
1092
|
+
return { status: "reject-dns" };
|
|
1093
|
+
}
|
|
1094
|
+
const verifiedIp = ips[0];
|
|
1095
|
+
if (verifiedIp !== void 0) {
|
|
1096
|
+
const { url, init } = pinToVerifiedIp(target, verifiedIp);
|
|
1097
|
+
return { status: "ok", url, init };
|
|
1098
|
+
}
|
|
1099
|
+
return { status: "ok", url: target, init: { redirect: "manual" } };
|
|
1100
|
+
}
|
|
1101
|
+
function enforceImageByteCount(body, maxBytes) {
|
|
1102
|
+
if (body === null) return null;
|
|
1103
|
+
const source = body;
|
|
1104
|
+
const { readable, writable } = new TransformStream();
|
|
1105
|
+
const writer = writable.getWriter();
|
|
1106
|
+
let total = 0;
|
|
1107
|
+
const pump = async () => {
|
|
1108
|
+
const reader = source.getReader();
|
|
1109
|
+
try {
|
|
1110
|
+
while (true) {
|
|
1111
|
+
const { done, value } = await reader.read();
|
|
1112
|
+
if (done) break;
|
|
1113
|
+
total += value.byteLength;
|
|
1114
|
+
if (total > maxBytes) {
|
|
1115
|
+
await reader.cancel().catch(() => {
|
|
1116
|
+
});
|
|
1117
|
+
await writer.abort(new UpstreamImageTooLargeError(maxBytes));
|
|
1118
|
+
return;
|
|
1119
|
+
}
|
|
1120
|
+
await writer.write(value);
|
|
1121
|
+
}
|
|
1122
|
+
await writer.close();
|
|
1123
|
+
} catch (err) {
|
|
1124
|
+
await writer.abort(err);
|
|
1125
|
+
}
|
|
1126
|
+
};
|
|
1127
|
+
void pump();
|
|
1128
|
+
return readable;
|
|
1129
|
+
}
|
|
949
1130
|
function createImageProxyHandler(options = {}) {
|
|
950
1131
|
const allowedHosts = new Set(options.remoteHosts ?? []);
|
|
1132
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_IMAGE_BYTES;
|
|
1133
|
+
const resolveHost = options.resolveHost ?? resolveHostDefault;
|
|
951
1134
|
return async (req) => {
|
|
952
1135
|
const reqUrl = new URL(req.url);
|
|
953
1136
|
if (reqUrl.pathname !== "/_x/image") return null;
|
|
@@ -964,6 +1147,22 @@ function createImageProxyHandler(options = {}) {
|
|
|
964
1147
|
if (!allowedUrl(parsed)) {
|
|
965
1148
|
return new Response("host not allow-listed for image proxy", { status: 403 });
|
|
966
1149
|
}
|
|
1150
|
+
const rejectFor = (status, hop) => {
|
|
1151
|
+
if (status === "reject-literal") {
|
|
1152
|
+
return new Response(
|
|
1153
|
+
hop ? "upstream redirected to a private or reserved address" : "target is a private or reserved address",
|
|
1154
|
+
{ status: 403 }
|
|
1155
|
+
);
|
|
1156
|
+
}
|
|
1157
|
+
return new Response(
|
|
1158
|
+
hop ? "upstream redirect resolves to a private or reserved address" : "target resolves to a private or reserved address",
|
|
1159
|
+
{ status: 403 }
|
|
1160
|
+
);
|
|
1161
|
+
};
|
|
1162
|
+
const initial = await resolveProxyTarget(parsed, resolveHost);
|
|
1163
|
+
if (initial.status !== "ok") {
|
|
1164
|
+
return rejectFor(initial.status, false);
|
|
1165
|
+
}
|
|
967
1166
|
const wParam = reqUrl.searchParams.get("w");
|
|
968
1167
|
const qParam = reqUrl.searchParams.get("q");
|
|
969
1168
|
if (wParam !== null) {
|
|
@@ -981,7 +1180,7 @@ function createImageProxyHandler(options = {}) {
|
|
|
981
1180
|
const isRedirect = (status) => status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
982
1181
|
let upstream;
|
|
983
1182
|
try {
|
|
984
|
-
upstream = await fetch(
|
|
1183
|
+
upstream = await fetch(initial.url, initial.init);
|
|
985
1184
|
for (let hop = 0; hop < 5; hop++) {
|
|
986
1185
|
if (!isRedirect(upstream.status)) break;
|
|
987
1186
|
const location = upstream.headers.get("location");
|
|
@@ -994,7 +1193,11 @@ function createImageProxyHandler(options = {}) {
|
|
|
994
1193
|
if (!allowedUrl(next)) {
|
|
995
1194
|
return new Response("upstream redirected off the allow-list", { status: 403 });
|
|
996
1195
|
}
|
|
997
|
-
|
|
1196
|
+
const hopTarget = await resolveProxyTarget(next, resolveHost);
|
|
1197
|
+
if (hopTarget.status !== "ok") {
|
|
1198
|
+
return rejectFor(hopTarget.status, true);
|
|
1199
|
+
}
|
|
1200
|
+
upstream = await fetch(hopTarget.url, hopTarget.init);
|
|
998
1201
|
}
|
|
999
1202
|
} catch (err) {
|
|
1000
1203
|
return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
|
|
@@ -1010,7 +1213,13 @@ function createImageProxyHandler(options = {}) {
|
|
|
1010
1213
|
if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
|
|
1011
1214
|
return new Response("upstream did not return an image", { status: 502 });
|
|
1012
1215
|
}
|
|
1013
|
-
|
|
1216
|
+
const contentLength = upstream.headers.get("content-length");
|
|
1217
|
+
if (contentLength !== null && Number(contentLength) > maxBytes) {
|
|
1218
|
+
await upstream.body?.cancel().catch(() => {
|
|
1219
|
+
});
|
|
1220
|
+
return new Response("upstream image exceeds the size limit", { status: 502 });
|
|
1221
|
+
}
|
|
1222
|
+
return new Response(enforceImageByteCount(upstream.body, maxBytes), {
|
|
1014
1223
|
status: 200,
|
|
1015
1224
|
headers: {
|
|
1016
1225
|
"Content-Type": contentType,
|
|
@@ -1036,7 +1245,11 @@ function composeMiddleware(fns, handler) {
|
|
|
1036
1245
|
}
|
|
1037
1246
|
return handler(ctx);
|
|
1038
1247
|
};
|
|
1039
|
-
return
|
|
1248
|
+
return tracePhase(
|
|
1249
|
+
"x.middleware",
|
|
1250
|
+
{ route: new URL(ctx.request.url).pathname },
|
|
1251
|
+
() => dispatch(0)
|
|
1252
|
+
);
|
|
1040
1253
|
};
|
|
1041
1254
|
}
|
|
1042
1255
|
|
|
@@ -1111,8 +1324,8 @@ function write(level, message, fields) {
|
|
|
1111
1324
|
const entry = {
|
|
1112
1325
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1113
1326
|
level,
|
|
1114
|
-
message,
|
|
1115
|
-
...fields
|
|
1327
|
+
message: redactString(message),
|
|
1328
|
+
...redactValue(fields)
|
|
1116
1329
|
};
|
|
1117
1330
|
const line = JSON.stringify(entry);
|
|
1118
1331
|
if (level === "error") {
|
|
@@ -1131,7 +1344,7 @@ var logger = {
|
|
|
1131
1344
|
function withRequestLogging(handler) {
|
|
1132
1345
|
return async (req, server) => {
|
|
1133
1346
|
const start = performance.now();
|
|
1134
|
-
const requestId = req
|
|
1347
|
+
const requestId = traceRequestId(req);
|
|
1135
1348
|
const route = new URL(req.url).pathname;
|
|
1136
1349
|
try {
|
|
1137
1350
|
const res = await handler(req, server);
|
|
@@ -1157,7 +1370,9 @@ function withRequestLogging(handler) {
|
|
|
1157
1370
|
method: req.method,
|
|
1158
1371
|
status: 500,
|
|
1159
1372
|
durationMs: Math.round(performance.now() - start),
|
|
1160
|
-
|
|
1373
|
+
// Redacted before emission — a throwing driver or app error whose
|
|
1374
|
+
// message embeds a secret must never leak it into the log sink.
|
|
1375
|
+
error: redactString(err instanceof Error ? err.message : String(err))
|
|
1161
1376
|
});
|
|
1162
1377
|
throw err;
|
|
1163
1378
|
}
|
|
@@ -1322,10 +1537,12 @@ function withRequestMetrics(reporter, handler) {
|
|
|
1322
1537
|
}
|
|
1323
1538
|
|
|
1324
1539
|
// src/security/headers.ts
|
|
1325
|
-
|
|
1540
|
+
function defaultCsp(nonce) {
|
|
1541
|
+
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'";
|
|
1542
|
+
}
|
|
1326
1543
|
function buildSecurityHeaders(options = {}) {
|
|
1327
1544
|
const headers = new Headers();
|
|
1328
|
-
const csp = options.contentSecurityPolicy ??
|
|
1545
|
+
const csp = options.contentSecurityPolicy ?? defaultCsp(options.cspNonce);
|
|
1329
1546
|
if (csp !== false) headers.set("Content-Security-Policy", csp);
|
|
1330
1547
|
const hstsMaxAge = options.hstsMaxAge ?? 15552e3;
|
|
1331
1548
|
if (hstsMaxAge !== false) {
|
|
@@ -1369,9 +1586,9 @@ var IsrCache = class {
|
|
|
1369
1586
|
}
|
|
1370
1587
|
return entry;
|
|
1371
1588
|
}
|
|
1372
|
-
set(key, html) {
|
|
1589
|
+
set(key, html, cspNonce) {
|
|
1373
1590
|
this.entries.delete(key);
|
|
1374
|
-
this.entries.set(key, { html, timestamp: Date.now() });
|
|
1591
|
+
this.entries.set(key, { html, timestamp: Date.now(), cspNonce });
|
|
1375
1592
|
this.evict();
|
|
1376
1593
|
}
|
|
1377
1594
|
delete(key) {
|
|
@@ -1403,13 +1620,12 @@ var IsrCache = class {
|
|
|
1403
1620
|
*/
|
|
1404
1621
|
getOrCompute(key, compute) {
|
|
1405
1622
|
const cached = this.get(key);
|
|
1406
|
-
if (cached) return Promise.resolve(cached.html);
|
|
1623
|
+
if (cached) return Promise.resolve({ html: cached.html, cspNonce: cached.cspNonce });
|
|
1407
1624
|
const existing = this.inFlight.get(key);
|
|
1408
1625
|
if (existing) return existing;
|
|
1409
1626
|
const promise = compute().then((result) => {
|
|
1410
|
-
if (
|
|
1411
|
-
|
|
1412
|
-
}
|
|
1627
|
+
if (result instanceof Response) return result;
|
|
1628
|
+
this.set(key, result.html, result.cspNonce);
|
|
1413
1629
|
return result;
|
|
1414
1630
|
}).finally(() => {
|
|
1415
1631
|
this.inFlight.delete(key);
|
|
@@ -1526,7 +1742,9 @@ function createRedisRateLimitStoreFromClient(clientFactory) {
|
|
|
1526
1742
|
if (count === 1) {
|
|
1527
1743
|
await c.sendCommand("EXPIRE", redisKey, String(ttlSeconds));
|
|
1528
1744
|
}
|
|
1529
|
-
|
|
1745
|
+
const pttl = Number(await c.sendCommand("PTTL", redisKey));
|
|
1746
|
+
const remainingMs = pttl > 0 ? pttl : 0;
|
|
1747
|
+
return { count, resetAt: Date.now() + remainingMs };
|
|
1530
1748
|
}
|
|
1531
1749
|
};
|
|
1532
1750
|
}
|
|
@@ -1534,9 +1752,12 @@ function createRedisRateLimitStoreFromClient(clientFactory) {
|
|
|
1534
1752
|
// src/createApp.ts
|
|
1535
1753
|
function sortRoutes(handlers) {
|
|
1536
1754
|
return handlers.sort((a, b) => {
|
|
1537
|
-
const
|
|
1538
|
-
|
|
1539
|
-
|
|
1755
|
+
const category = routeMatchesForSort(a.entry) - routeMatchesForSort(b.entry);
|
|
1756
|
+
if (category !== 0) return category;
|
|
1757
|
+
for (const [as, bs] of zip(segmentSpecificity(a.entry), segmentSpecificity(b.entry))) {
|
|
1758
|
+
if (as !== bs) return as - bs;
|
|
1759
|
+
}
|
|
1760
|
+
return a.entry.routePath < b.entry.routePath ? -1 : 1;
|
|
1540
1761
|
});
|
|
1541
1762
|
}
|
|
1542
1763
|
function routeMatchesForSort(entry) {
|
|
@@ -1544,6 +1765,16 @@ function routeMatchesForSort(entry) {
|
|
|
1544
1765
|
const isCatchAll = entry.routePath.includes("*");
|
|
1545
1766
|
return isStatic ? 0 : isCatchAll ? 2 : 1;
|
|
1546
1767
|
}
|
|
1768
|
+
function segmentSpecificity(entry) {
|
|
1769
|
+
return entry.routePath.split("/").filter((seg) => seg.length > 0).map((seg) => seg === "*" ? 2 : seg.startsWith(":") ? 1 : 0);
|
|
1770
|
+
}
|
|
1771
|
+
function zip(as, bs) {
|
|
1772
|
+
const out = [];
|
|
1773
|
+
for (let i = 0; i < Math.max(as.length, bs.length); i++) {
|
|
1774
|
+
out.push([as[i], bs[i]]);
|
|
1775
|
+
}
|
|
1776
|
+
return out;
|
|
1777
|
+
}
|
|
1547
1778
|
function projectRootFromRoutesDir(routesDir) {
|
|
1548
1779
|
return join3(routesDir, "..", "..");
|
|
1549
1780
|
}
|
|
@@ -1579,7 +1810,7 @@ function wrapWithLayouts(Component, params, loaderData, layoutModules) {
|
|
|
1579
1810
|
}
|
|
1580
1811
|
return content;
|
|
1581
1812
|
}
|
|
1582
|
-
function renderContentPage(content, stylesheet, dev = false) {
|
|
1813
|
+
function renderContentPage(content, stylesheet, dev = false, nonce) {
|
|
1583
1814
|
const title = content.frontmatter.title ?? content.slug;
|
|
1584
1815
|
const bodyHtml = renderMarkdown(content.body);
|
|
1585
1816
|
const body = renderPage(
|
|
@@ -1592,7 +1823,12 @@ function renderContentPage(content, stylesheet, dev = false) {
|
|
|
1592
1823
|
dangerouslySetInnerHTML: { __html: bodyHtml }
|
|
1593
1824
|
})
|
|
1594
1825
|
),
|
|
1595
|
-
{
|
|
1826
|
+
{
|
|
1827
|
+
title,
|
|
1828
|
+
stylesheet,
|
|
1829
|
+
liveReload: dev,
|
|
1830
|
+
...nonce ? { cspNonce: nonce } : {}
|
|
1831
|
+
}
|
|
1596
1832
|
);
|
|
1597
1833
|
return body;
|
|
1598
1834
|
}
|
|
@@ -1654,30 +1890,53 @@ async function createApp(options) {
|
|
|
1654
1890
|
const healthHandler = createHealthCheckHandler(options.observability?.health ?? {});
|
|
1655
1891
|
const metricsReporter = options.observability?.metrics;
|
|
1656
1892
|
const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
|
|
1893
|
+
const maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;
|
|
1657
1894
|
const securityHeadersOptions = options.security?.headers;
|
|
1658
1895
|
const loggingEnabled = options.observability?.logging ?? true;
|
|
1659
1896
|
const imageProxyHandler = createImageProxyHandler(options.images);
|
|
1897
|
+
const CSP_NONCE_HEADER = "x-csp-nonce";
|
|
1898
|
+
function generateCspNonce() {
|
|
1899
|
+
const bytes = new Uint8Array(16);
|
|
1900
|
+
crypto.getRandomValues(bytes);
|
|
1901
|
+
let bin = "";
|
|
1902
|
+
for (const byte of bytes) bin += String.fromCharCode(byte);
|
|
1903
|
+
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1904
|
+
}
|
|
1660
1905
|
function withResponseHardening(res) {
|
|
1661
|
-
|
|
1906
|
+
if (securityHeadersOptions === false) return res;
|
|
1907
|
+
const cspNonce = res.headers.get(CSP_NONCE_HEADER) ?? void 0;
|
|
1908
|
+
if (cspNonce) res.headers.delete(CSP_NONCE_HEADER);
|
|
1909
|
+
return applySecurityHeaders(res, {
|
|
1910
|
+
...securityHeadersOptions,
|
|
1911
|
+
...cspNonce ? { cspNonce } : {}
|
|
1912
|
+
});
|
|
1662
1913
|
}
|
|
1663
1914
|
async function renderNotFound(_req) {
|
|
1664
1915
|
const content = notFoundLayout ? createElement2(notFoundLayout, null, createElement2(notFoundComponent, { params: {} })) : createElement2(notFoundComponent, { params: {} });
|
|
1916
|
+
const cspNonce = generateCspNonce();
|
|
1665
1917
|
const html = renderPage(content, {
|
|
1666
1918
|
title: "404 \u2014 Not Found",
|
|
1667
1919
|
stylesheet: stylesheetHref,
|
|
1668
|
-
liveReload: dev
|
|
1920
|
+
liveReload: dev,
|
|
1921
|
+
cspNonce
|
|
1669
1922
|
});
|
|
1670
|
-
|
|
1923
|
+
const res = new Response(html, {
|
|
1671
1924
|
status: 404,
|
|
1672
1925
|
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
1673
1926
|
});
|
|
1927
|
+
res.headers.set(CSP_NONCE_HEADER, cspNonce);
|
|
1928
|
+
return res;
|
|
1674
1929
|
}
|
|
1675
1930
|
const makeApiHandler = (route, module) => async (req) => {
|
|
1676
1931
|
try {
|
|
1677
1932
|
const method = req.method;
|
|
1678
1933
|
const handlerFn = module[method];
|
|
1679
1934
|
if (typeof handlerFn === "function") {
|
|
1680
|
-
const result = await
|
|
1935
|
+
const result = await tracePhase(
|
|
1936
|
+
"x.api",
|
|
1937
|
+
{ route: route.routePath, method },
|
|
1938
|
+
async () => handlerFn(req)
|
|
1939
|
+
);
|
|
1681
1940
|
if (result instanceof Response) return result;
|
|
1682
1941
|
if (result === void 0 || result === null) {
|
|
1683
1942
|
return new Response("OK", { status: 200 });
|
|
@@ -1686,6 +1945,9 @@ async function createApp(options) {
|
|
|
1686
1945
|
}
|
|
1687
1946
|
return new Response(`Method ${method} not allowed`, { status: 405 });
|
|
1688
1947
|
} catch (err) {
|
|
1948
|
+
if (err instanceof RequestBodyTooLargeError) {
|
|
1949
|
+
return new Response("Payload too large", { status: 413 });
|
|
1950
|
+
}
|
|
1689
1951
|
reportException(err, { route: route.routePath, phase: "api" });
|
|
1690
1952
|
metricsReporter?.incr("x_http_errors_total", 1, { phase: "api" });
|
|
1691
1953
|
console.error("[x] API handler error:", err);
|
|
@@ -1718,9 +1980,13 @@ async function createApp(options) {
|
|
|
1718
1980
|
if (mode === "server") {
|
|
1719
1981
|
let loaderData = {};
|
|
1720
1982
|
if (loader) {
|
|
1721
|
-
const
|
|
1722
|
-
|
|
1723
|
-
|
|
1983
|
+
const result2 = await tracePhase(
|
|
1984
|
+
"x.loader",
|
|
1985
|
+
{ route: route.routePath },
|
|
1986
|
+
() => loader(ctx)
|
|
1987
|
+
);
|
|
1988
|
+
if (result2 instanceof Response) return result2;
|
|
1989
|
+
loaderData = result2;
|
|
1724
1990
|
}
|
|
1725
1991
|
const registry = createIslandRegistry();
|
|
1726
1992
|
const content = createElement2(
|
|
@@ -1728,45 +1994,59 @@ async function createApp(options) {
|
|
|
1728
1994
|
{ registry },
|
|
1729
1995
|
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
|
|
1730
1996
|
);
|
|
1731
|
-
const
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1997
|
+
const cspNonce = generateCspNonce();
|
|
1998
|
+
const stream = await tracePhase(
|
|
1999
|
+
"x.ssr",
|
|
2000
|
+
{ route: route.routePath, streaming: true },
|
|
2001
|
+
() => renderStreamingPage(content, {
|
|
2002
|
+
stylesheet: stylesheetHref,
|
|
2003
|
+
liveReload: dev,
|
|
2004
|
+
cspNonce,
|
|
2005
|
+
...islandScripts === void 0 ? {
|
|
2006
|
+
// Single-render mode: islands register into `registry`
|
|
2007
|
+
// during the one render that produces the HTML, and the
|
|
2008
|
+
// script list is resolved from that same pass in the lazy
|
|
2009
|
+
// footer — no separate discovery render, so non-deterministic
|
|
2010
|
+
// components can't diverge between two passes.
|
|
2011
|
+
resolveIslandScripts: () => resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries)
|
|
2012
|
+
} : { islandScripts },
|
|
2013
|
+
onRenderError: (error) => {
|
|
2014
|
+
reportException(error, { route: route.routePath, phase: "ssr" });
|
|
2015
|
+
metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
|
|
2016
|
+
}
|
|
2017
|
+
})
|
|
2018
|
+
);
|
|
2019
|
+
const res2 = new Response(stream, {
|
|
1748
2020
|
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
1749
2021
|
});
|
|
2022
|
+
res2.headers.set(CSP_NONCE_HEADER, cspNonce);
|
|
2023
|
+
return res2;
|
|
1750
2024
|
}
|
|
1751
2025
|
const revalidateSeconds = revalidate ?? 0;
|
|
1752
2026
|
if (revalidateSeconds > 0) {
|
|
1753
2027
|
const cached = staticCache.get(cacheKey);
|
|
1754
2028
|
if (cached && Date.now() - cached.timestamp < revalidateSeconds * 1e3) {
|
|
1755
|
-
|
|
2029
|
+
const res2 = new Response(cached.html, {
|
|
1756
2030
|
headers: {
|
|
1757
2031
|
"Content-Type": "text/html; charset=utf-8",
|
|
1758
2032
|
"X-Revalidated": "hit"
|
|
1759
2033
|
}
|
|
1760
2034
|
});
|
|
2035
|
+
res2.headers.set(CSP_NONCE_HEADER, cached.cspNonce);
|
|
2036
|
+
return res2;
|
|
1761
2037
|
}
|
|
1762
2038
|
if (cached) staticCache.delete(cacheKey);
|
|
1763
2039
|
}
|
|
1764
2040
|
const computeHtml = async () => {
|
|
1765
2041
|
let loaderData = {};
|
|
1766
2042
|
if (loader) {
|
|
1767
|
-
const
|
|
1768
|
-
|
|
1769
|
-
|
|
2043
|
+
const result2 = await tracePhase(
|
|
2044
|
+
"x.loader",
|
|
2045
|
+
{ route: route.routePath },
|
|
2046
|
+
() => loader(ctx)
|
|
2047
|
+
);
|
|
2048
|
+
if (result2 instanceof Response) return result2;
|
|
2049
|
+
loaderData = result2;
|
|
1770
2050
|
}
|
|
1771
2051
|
const registry = createIslandRegistry();
|
|
1772
2052
|
const content = createElement2(
|
|
@@ -1774,32 +2054,43 @@ async function createApp(options) {
|
|
|
1774
2054
|
{ registry },
|
|
1775
2055
|
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
|
|
1776
2056
|
);
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
2057
|
+
const cspNonce = generateCspNonce();
|
|
2058
|
+
const html = await tracePhase(
|
|
2059
|
+
"x.ssr",
|
|
2060
|
+
{ route: route.routePath, streaming: false },
|
|
2061
|
+
() => renderPageOnce(content, {
|
|
2062
|
+
stylesheet: stylesheetHref,
|
|
2063
|
+
liveReload: dev,
|
|
2064
|
+
cspNonce,
|
|
2065
|
+
...islandScripts === void 0 ? {
|
|
2066
|
+
resolveIslandScripts: () => resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries)
|
|
2067
|
+
} : { islandScripts }
|
|
2068
|
+
})
|
|
2069
|
+
);
|
|
2070
|
+
return { html, cspNonce };
|
|
1784
2071
|
};
|
|
1785
2072
|
if (revalidateSeconds > 0) {
|
|
1786
|
-
const
|
|
1787
|
-
if (
|
|
1788
|
-
|
|
2073
|
+
const result2 = await staticCache.getOrCompute(cacheKey, computeHtml);
|
|
2074
|
+
if (result2 instanceof Response) return result2;
|
|
2075
|
+
const res2 = new Response(result2.html, {
|
|
1789
2076
|
headers: {
|
|
1790
2077
|
"Content-Type": "text/html; charset=utf-8",
|
|
1791
2078
|
"X-Revalidated": "miss"
|
|
1792
2079
|
}
|
|
1793
2080
|
});
|
|
2081
|
+
res2.headers.set(CSP_NONCE_HEADER, result2.cspNonce);
|
|
2082
|
+
return res2;
|
|
1794
2083
|
}
|
|
1795
|
-
const
|
|
1796
|
-
if (
|
|
1797
|
-
|
|
2084
|
+
const result = await computeHtml();
|
|
2085
|
+
if (result instanceof Response) return result;
|
|
2086
|
+
const res = new Response(result.html, {
|
|
1798
2087
|
headers: {
|
|
1799
2088
|
"Content-Type": "text/html; charset=utf-8",
|
|
1800
2089
|
"X-Revalidated": "none"
|
|
1801
2090
|
}
|
|
1802
2091
|
});
|
|
2092
|
+
res.headers.set(CSP_NONCE_HEADER, result.cspNonce);
|
|
2093
|
+
return res;
|
|
1803
2094
|
};
|
|
1804
2095
|
if (middlewareModules.length > 0) {
|
|
1805
2096
|
const composed = composeMiddleware(middlewareModules, baseHandler);
|
|
@@ -1810,6 +2101,9 @@ async function createApp(options) {
|
|
|
1810
2101
|
}
|
|
1811
2102
|
return baseHandler({ params, request: req });
|
|
1812
2103
|
} catch (err) {
|
|
2104
|
+
if (err instanceof RequestBodyTooLargeError) {
|
|
2105
|
+
return new Response("Payload too large", { status: 413 });
|
|
2106
|
+
}
|
|
1813
2107
|
reportException(err, { route: route.routePath, phase: "ssr" });
|
|
1814
2108
|
metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
|
|
1815
2109
|
console.error("[x] route handler error:", err);
|
|
@@ -2012,16 +2306,24 @@ async function createApp(options) {
|
|
|
2012
2306
|
const loadedContent = content.map((entry) => ({
|
|
2013
2307
|
entry,
|
|
2014
2308
|
handler: async () => {
|
|
2015
|
-
const
|
|
2016
|
-
|
|
2309
|
+
const cspNonce = generateCspNonce();
|
|
2310
|
+
const html = renderContentPage(entry, stylesheetHref, dev, cspNonce);
|
|
2311
|
+
const res = new Response(html, {
|
|
2017
2312
|
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
2018
2313
|
});
|
|
2314
|
+
res.headers.set(CSP_NONCE_HEADER, cspNonce);
|
|
2315
|
+
return res;
|
|
2019
2316
|
}
|
|
2020
2317
|
}));
|
|
2021
2318
|
contentHandlers = loadedContent;
|
|
2022
2319
|
}
|
|
2023
2320
|
}
|
|
2024
2321
|
await buildHandlers();
|
|
2322
|
+
const withBodySizeLimit = (inner) => async (req, server) => {
|
|
2323
|
+
const guarded = enforceRequestBodySize(req, maxBodySize);
|
|
2324
|
+
if (guarded instanceof Response) return guarded;
|
|
2325
|
+
return inner(guarded, server);
|
|
2326
|
+
};
|
|
2025
2327
|
async function guardFetchErrors(inner, req, server) {
|
|
2026
2328
|
try {
|
|
2027
2329
|
return await inner(req, server);
|
|
@@ -2046,7 +2348,10 @@ async function createApp(options) {
|
|
|
2046
2348
|
let body;
|
|
2047
2349
|
try {
|
|
2048
2350
|
body = await req.json();
|
|
2049
|
-
} catch {
|
|
2351
|
+
} catch (err) {
|
|
2352
|
+
if (err instanceof RequestBodyTooLargeError) {
|
|
2353
|
+
return new Response("Payload too large", { status: 413 });
|
|
2354
|
+
}
|
|
2050
2355
|
return new Response("Invalid JSON body", { status: 400 });
|
|
2051
2356
|
}
|
|
2052
2357
|
if (body.path) {
|
|
@@ -2059,11 +2364,18 @@ async function createApp(options) {
|
|
|
2059
2364
|
async function handleHydrationMismatch(req) {
|
|
2060
2365
|
if (new URL(req.url).pathname !== "/__x/hydration-mismatch") return null;
|
|
2061
2366
|
if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
|
|
2062
|
-
const
|
|
2063
|
-
const
|
|
2064
|
-
const
|
|
2065
|
-
const
|
|
2066
|
-
|
|
2367
|
+
const selfOrigin = requestOrigin(req);
|
|
2368
|
+
const rawOrigin = req.headers.get("origin");
|
|
2369
|
+
const rawReferer = req.headers.get("referer");
|
|
2370
|
+
const origin = originFromHeader(rawOrigin);
|
|
2371
|
+
const referer = originFromHeader(rawReferer);
|
|
2372
|
+
if (origin !== null) {
|
|
2373
|
+
if (origin !== selfOrigin) return new Response("Forbidden", { status: 403 });
|
|
2374
|
+
} else if (rawOrigin !== null) {
|
|
2375
|
+
return new Response("Forbidden", { status: 403 });
|
|
2376
|
+
} else if (referer !== null) {
|
|
2377
|
+
if (referer !== selfOrigin) return new Response("Forbidden", { status: 403 });
|
|
2378
|
+
} else if (rawReferer !== null) {
|
|
2067
2379
|
return new Response("Forbidden", { status: 403 });
|
|
2068
2380
|
}
|
|
2069
2381
|
let body;
|
|
@@ -2071,7 +2383,10 @@ async function createApp(options) {
|
|
|
2071
2383
|
const text = await req.text();
|
|
2072
2384
|
if (text.length > 2048) return new Response("Payload too large", { status: 413 });
|
|
2073
2385
|
body = JSON.parse(text);
|
|
2074
|
-
} catch {
|
|
2386
|
+
} catch (err) {
|
|
2387
|
+
if (err instanceof RequestBodyTooLargeError) {
|
|
2388
|
+
return new Response("Payload too large", { status: 413 });
|
|
2389
|
+
}
|
|
2075
2390
|
return new Response("Invalid JSON body", { status: 400 });
|
|
2076
2391
|
}
|
|
2077
2392
|
const error = new Error(body.error ?? "hydration mismatch");
|
|
@@ -2221,9 +2536,10 @@ data: ${data}
|
|
|
2221
2536
|
}
|
|
2222
2537
|
return renderNotFound(req);
|
|
2223
2538
|
};
|
|
2224
|
-
const devFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(devFetchInner, req, server));
|
|
2539
|
+
const devFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(devFetchInner), req, server));
|
|
2225
2540
|
const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
|
|
2226
|
-
const
|
|
2541
|
+
const devFetchTraced = withRequestTracing(devFetchBase);
|
|
2542
|
+
const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchTraced) : devFetchTraced;
|
|
2227
2543
|
return {
|
|
2228
2544
|
routes: {},
|
|
2229
2545
|
development: true,
|
|
@@ -2279,9 +2595,10 @@ data: ${data}
|
|
|
2279
2595
|
}
|
|
2280
2596
|
return renderNotFound(req);
|
|
2281
2597
|
};
|
|
2282
|
-
const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(prodFetchInner, req, server));
|
|
2598
|
+
const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(prodFetchInner), req, server));
|
|
2283
2599
|
const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
|
|
2284
|
-
const
|
|
2600
|
+
const prodFetchTraced = withRequestTracing(prodFetchBase);
|
|
2601
|
+
const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchTraced) : prodFetchTraced;
|
|
2285
2602
|
return {
|
|
2286
2603
|
routes: {},
|
|
2287
2604
|
development: false,
|
|
@@ -2418,26 +2735,153 @@ function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
|
|
|
2418
2735
|
}
|
|
2419
2736
|
);
|
|
2420
2737
|
}
|
|
2738
|
+
|
|
2739
|
+
// src/observability/audit.ts
|
|
2740
|
+
var noopAuditSink = {
|
|
2741
|
+
write: () => {
|
|
2742
|
+
}
|
|
2743
|
+
};
|
|
2744
|
+
function createConsoleAuditSink() {
|
|
2745
|
+
return {
|
|
2746
|
+
write(entry) {
|
|
2747
|
+
console.log(JSON.stringify(entry));
|
|
2748
|
+
}
|
|
2749
|
+
};
|
|
2750
|
+
}
|
|
2751
|
+
var activeSink = noopAuditSink;
|
|
2752
|
+
function setAuditSink(sink) {
|
|
2753
|
+
activeSink = sink;
|
|
2754
|
+
}
|
|
2755
|
+
function getAuditSink() {
|
|
2756
|
+
return activeSink;
|
|
2757
|
+
}
|
|
2758
|
+
function clientIpFromRequest(req) {
|
|
2759
|
+
const forwarded = req.headers.get("x-forwarded-for");
|
|
2760
|
+
if (forwarded) return forwarded.split(",")[0]?.trim() || null;
|
|
2761
|
+
return req.headers.get("x-real-ip");
|
|
2762
|
+
}
|
|
2763
|
+
function requestIdFromRequest(req) {
|
|
2764
|
+
return req.headers.get("x-request-id") ?? void 0;
|
|
2765
|
+
}
|
|
2766
|
+
function audit(entry) {
|
|
2767
|
+
const redacted = {
|
|
2768
|
+
timestamp: entry.timestamp,
|
|
2769
|
+
event: entry.event,
|
|
2770
|
+
userId: entry.userId,
|
|
2771
|
+
ip: entry.ip,
|
|
2772
|
+
...entry.reason !== void 0 ? { reason: redactString(entry.reason) } : {},
|
|
2773
|
+
...entry.provider !== void 0 ? { provider: entry.provider } : {},
|
|
2774
|
+
...entry.requestId !== void 0 ? { requestId: entry.requestId } : {},
|
|
2775
|
+
...entry.sessionHash !== void 0 ? { sessionHash: entry.sessionHash } : {},
|
|
2776
|
+
...entry.metadata !== void 0 ? { metadata: redactValue(entry.metadata) } : {}
|
|
2777
|
+
};
|
|
2778
|
+
activeSink.write(redacted);
|
|
2779
|
+
}
|
|
2780
|
+
function auditLoginSuccess(input) {
|
|
2781
|
+
audit({
|
|
2782
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2783
|
+
event: "auth.login.success",
|
|
2784
|
+
...input
|
|
2785
|
+
});
|
|
2786
|
+
}
|
|
2787
|
+
function auditLoginFailure(input) {
|
|
2788
|
+
audit({
|
|
2789
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2790
|
+
event: "auth.login.failure",
|
|
2791
|
+
...input
|
|
2792
|
+
});
|
|
2793
|
+
}
|
|
2794
|
+
function auditLogout(input) {
|
|
2795
|
+
audit({
|
|
2796
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2797
|
+
event: "auth.logout",
|
|
2798
|
+
...input
|
|
2799
|
+
});
|
|
2800
|
+
}
|
|
2801
|
+
function auditPasswordChanged(input) {
|
|
2802
|
+
audit({
|
|
2803
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2804
|
+
event: "auth.password_changed",
|
|
2805
|
+
...input
|
|
2806
|
+
});
|
|
2807
|
+
}
|
|
2808
|
+
function auditRoleChanged(input) {
|
|
2809
|
+
audit({
|
|
2810
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2811
|
+
event: "auth.role_changed",
|
|
2812
|
+
...input
|
|
2813
|
+
});
|
|
2814
|
+
}
|
|
2815
|
+
function auditPermissionDenied(input) {
|
|
2816
|
+
audit({
|
|
2817
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2818
|
+
event: "auth.permission_denied",
|
|
2819
|
+
...input
|
|
2820
|
+
});
|
|
2821
|
+
}
|
|
2822
|
+
function auditSessionRevoked(input) {
|
|
2823
|
+
audit({
|
|
2824
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2825
|
+
event: "auth.session_revoked",
|
|
2826
|
+
...input
|
|
2827
|
+
});
|
|
2828
|
+
}
|
|
2829
|
+
|
|
2830
|
+
// src/observability/crash-handlers.ts
|
|
2831
|
+
function installProcessCrashHandlers(options = {}) {
|
|
2832
|
+
const phase = options.phase ?? "api";
|
|
2833
|
+
const exitOnCrash = options.exitOnCrash ?? false;
|
|
2834
|
+
const onUncaughtException = (error) => {
|
|
2835
|
+
console.error("[x] uncaught exception:", error);
|
|
2836
|
+
reportException(error, { phase });
|
|
2837
|
+
if (exitOnCrash) process.exit(1);
|
|
2838
|
+
};
|
|
2839
|
+
const onUnhandledRejection = (reason) => {
|
|
2840
|
+
console.error("[x] unhandled rejection:", reason);
|
|
2841
|
+
reportException(reason, { phase });
|
|
2842
|
+
if (exitOnCrash) process.exit(1);
|
|
2843
|
+
};
|
|
2844
|
+
process.on("uncaughtException", onUncaughtException);
|
|
2845
|
+
process.on("unhandledRejection", onUnhandledRejection);
|
|
2846
|
+
return () => {
|
|
2847
|
+
process.off("uncaughtException", onUncaughtException);
|
|
2848
|
+
process.off("unhandledRejection", onUnhandledRejection);
|
|
2849
|
+
};
|
|
2850
|
+
}
|
|
2421
2851
|
export {
|
|
2422
2852
|
CLIENT_NAV_SCRIPT,
|
|
2423
2853
|
DEFAULT_HISTOGRAM_BUCKETS_MS,
|
|
2854
|
+
DEFAULT_MAX_BODY_SIZE,
|
|
2424
2855
|
DefaultNotFound,
|
|
2425
2856
|
EnvLeakageError,
|
|
2426
2857
|
Image,
|
|
2427
2858
|
Island,
|
|
2428
2859
|
IslandProvider,
|
|
2429
2860
|
Link,
|
|
2861
|
+
OTEL_ERROR_STATUS_CODE,
|
|
2430
2862
|
PUBLIC_ENV_PREFIX,
|
|
2863
|
+
REDACTED,
|
|
2864
|
+
RequestBodyTooLargeError,
|
|
2431
2865
|
SRCSET_WIDTHS,
|
|
2432
2866
|
applySecurityHeaders,
|
|
2433
2867
|
assertNoEnvLeakage,
|
|
2868
|
+
audit,
|
|
2869
|
+
auditLoginFailure,
|
|
2870
|
+
auditLoginSuccess,
|
|
2871
|
+
auditLogout,
|
|
2872
|
+
auditPasswordChanged,
|
|
2873
|
+
auditPermissionDenied,
|
|
2874
|
+
auditRoleChanged,
|
|
2875
|
+
auditSessionRevoked,
|
|
2434
2876
|
build,
|
|
2435
2877
|
buildSecurityHeaders,
|
|
2436
2878
|
buildSrcSet,
|
|
2437
2879
|
checkCsrf,
|
|
2880
|
+
clientIpFromRequest,
|
|
2438
2881
|
combineReporters,
|
|
2439
2882
|
composeMiddleware,
|
|
2440
2883
|
createApp,
|
|
2884
|
+
createConsoleAuditSink,
|
|
2441
2885
|
createHealthCheckHandler,
|
|
2442
2886
|
createImageProxyHandler,
|
|
2443
2887
|
createInMemoryMetrics,
|
|
@@ -2446,7 +2890,9 @@ export {
|
|
|
2446
2890
|
createRateLimiter,
|
|
2447
2891
|
createRedisRateLimitStore,
|
|
2448
2892
|
createSentryReporter,
|
|
2893
|
+
dbTraceAttributes,
|
|
2449
2894
|
defineConfig,
|
|
2895
|
+
enforceRequestBodySize,
|
|
2450
2896
|
escapeHtml,
|
|
2451
2897
|
findLayoutChain,
|
|
2452
2898
|
findLeakedEnvKeys,
|
|
@@ -2454,12 +2900,19 @@ export {
|
|
|
2454
2900
|
generateCsrfToken,
|
|
2455
2901
|
generateManifestSource,
|
|
2456
2902
|
generateServerFunctionClient,
|
|
2903
|
+
getAuditSink,
|
|
2457
2904
|
getErrorReporter,
|
|
2458
2905
|
getServerFunctionHandler,
|
|
2906
|
+
getTracer,
|
|
2907
|
+
installProcessCrashHandlers,
|
|
2908
|
+
isSensitiveKey,
|
|
2459
2909
|
logger,
|
|
2910
|
+
noopAuditSink,
|
|
2460
2911
|
noopMetrics,
|
|
2461
2912
|
noopReporter,
|
|
2462
2913
|
rateLimitMiddleware,
|
|
2914
|
+
redactString,
|
|
2915
|
+
redactValue,
|
|
2463
2916
|
registerServerFunctions,
|
|
2464
2917
|
renderErrorOverlay,
|
|
2465
2918
|
renderMarkdown,
|
|
@@ -2467,7 +2920,9 @@ export {
|
|
|
2467
2920
|
renderStaticPage,
|
|
2468
2921
|
renderStreamingPage,
|
|
2469
2922
|
reportException,
|
|
2923
|
+
requestIdFromRequest,
|
|
2470
2924
|
resetServerFunctions,
|
|
2925
|
+
runWithRequestSpan,
|
|
2471
2926
|
scanApiDir,
|
|
2472
2927
|
scanContent,
|
|
2473
2928
|
scanLayouts,
|
|
@@ -2476,12 +2931,18 @@ export {
|
|
|
2476
2931
|
scanNotFound,
|
|
2477
2932
|
scanPages,
|
|
2478
2933
|
scanRoutes,
|
|
2934
|
+
setAuditSink,
|
|
2479
2935
|
setErrorReporter,
|
|
2480
2936
|
setImageRemoteHosts,
|
|
2937
|
+
setTracer,
|
|
2938
|
+
tracePhase,
|
|
2939
|
+
tracePhaseSync,
|
|
2940
|
+
traceRequestId,
|
|
2481
2941
|
verifyCsrfToken,
|
|
2482
2942
|
verifyOrigin,
|
|
2483
2943
|
withCsrfCookie,
|
|
2484
2944
|
withRequestLogging,
|
|
2485
2945
|
withRequestMetrics,
|
|
2946
|
+
withRequestTracing,
|
|
2486
2947
|
writeManifest
|
|
2487
2948
|
};
|