Fix security vulnerabilities

This commit is contained in:
2026-10-13 15:52:34 +01:00
parent 74103a19c9
commit eefb2ea5d2
46 changed files with 375 additions and 403 deletions
+10 -3
View File
@@ -9,15 +9,16 @@ import checkExcludedPatterns from "../../utils/check-excluded-patterns";
import { AppData } from "../../data/app-data";
import { log } from "../../utils/log";
import fullRebuild from "./full-rebuild";
import grabRouter from "../../utils/grab-router";
const HMR_RETRY_COOLDOWN_MS = 5000;
let lastHmrRetryTime = 0;
export default async function bunextRequestHandler({ req: initial_req, server, }) {
const is_dev = isDevelopment();
let req = initial_req.clone();
try {
const url = new URL(req.url);
let url = new URL(req.url);
if (checkExcludedPatterns({ path: url.pathname })) {
return Response.json({ success: false, msg: `Invalid Path` });
return Response.json({ success: false, msg: `Invalid Path` }, { status: 404 });
}
let response = undefined;
if (global.BUNEXT_CONSTANTS.config?.middleware) {
@@ -30,6 +31,7 @@ export default async function bunextRequestHandler({ req: initial_req, server, }
}
if (middleware_res instanceof Request) {
req = middleware_res;
url = new URL(req.url);
}
}
if (is_dev && url.pathname == AppData["BunextHMRRetryRoute"]) {
@@ -53,8 +55,13 @@ export default async function bunextRequestHandler({ req: initial_req, server, }
else if (url.pathname.startsWith("/public/")) {
response = await handlePublic({ req });
}
else if (url.pathname.match(/\..*$/)) {
else if (url.pathname.match(/\.[^/]+$/)) {
response = await handleFiles({ req });
// Paths like `/users/john.doe` look like files but can be pages.
if (response.status == 404 &&
grabRouter()?.match(url.pathname)?.filePath) {
response = await handleWebPages({ req });
}
}
else {
response = await handleWebPages({ req });
+1 -1
View File
@@ -8,7 +8,7 @@ export default async function ({ req }) {
try {
const is_dev = isDevelopment();
const url = new URL(req.url);
const file_path = path.join(BUNEXT_PUBLIC_DIR, url.pathname.replace(/\/\.bunext\/public\//, ""));
const file_path = path.join(BUNEXT_PUBLIC_DIR, decodeURIComponent(url.pathname).replace(/\/\.bunext\/public\//, ""));
if (!isSafePath({ filePath: file_path, allowedDir: BUNEXT_PUBLIC_DIR })) {
return new Response("Forbidden", { status: 403 });
}
+1 -1
View File
@@ -8,7 +8,7 @@ export default async function ({ req }) {
try {
const is_dev = isDevelopment();
const url = new URL(req.url);
const file_path = path.join(PUBLIC_DIR, url.pathname);
const file_path = path.join(PUBLIC_DIR, decodeURIComponent(url.pathname));
if (!isSafePath({ filePath: file_path, allowedDir: PUBLIC_DIR })) {
return new Response("Forbidden", { status: 403 });
}
+1 -1
View File
@@ -8,7 +8,7 @@ export default async function ({ req }) {
try {
const is_dev = isDevelopment();
const url = new URL(req.url);
const file_path = path.join(PUBLIC_DIR, url.pathname.replace(/^\/public/, ""));
const file_path = path.join(PUBLIC_DIR, decodeURIComponent(url.pathname).replace(/^\/public/, ""));
if (!isSafePath({ filePath: file_path, allowedDir: PUBLIC_DIR })) {
return new Response("Forbidden", { status: 403 });
}
+43 -47
View File
@@ -7,6 +7,7 @@ import _ from "lodash";
import path from "path";
import grabDirNames from "../../utils/grab-dir-names";
import grabRelativePath from "../../utils/grab-relative-path";
import { RequestBodyTooLargeError } from "../../utils/read-request-body";
const { ROOT_DIR } = grabDirNames();
export default async function ({ req }) {
try {
@@ -27,10 +28,6 @@ export default async function ({ req }) {
},
});
}
const routeParams = await grabRouteParams({
req,
query: match.query,
});
let module;
const now = Date.now();
const relative_match_path = grabRelativePath(match.filePath);
@@ -50,54 +47,37 @@ export default async function ({ req }) {
? config.max_request_body_mb * MBInBytes
: ServerDefaultRequestBodyLimitBytes;
const contentLength = req.headers.get("content-length");
if (contentLength) {
const size = parseInt(contentLength, 10);
if (size > maxBodyBytes) {
return Response.json({
success: false,
msg: "Request Body Too Large!",
}, {
status: 413,
headers: {
"Content-Type": "application/json",
},
});
}
if (contentLength && parseInt(contentLength, 10) > maxBodyBytes) {
return bodyTooLargeResponse();
}
else if (req.method !== "GET" && req.method !== "HEAD") {
const body = await req.arrayBuffer();
if (body.byteLength > maxBodyBytes) {
return Response.json({
success: false,
msg: "Request Body Too Large!",
}, {
status: 413,
headers: {
"Content-Type": "application/json",
},
});
}
try {
routeParams.body = JSON.parse(new TextDecoder().decode(body) || "{}");
}
catch (error) {
log.error(`Invalid JSON body for ${url.pathname}: ${error?.message}`);
return Response.json({
success: false,
msg: "Invalid JSON body",
}, {
status: 400,
headers: {
"Content-Type": "application/json",
},
});
let routeParams;
try {
routeParams = await grabRouteParams({
req,
query: match.query,
max_body_bytes: maxBodyBytes,
});
}
catch (error) {
if (error instanceof RequestBodyTooLargeError) {
return bodyTooLargeResponse();
}
throw error;
}
const target_module = (module["default"] ||
module["handler"]);
if (typeof target_module !== "function") {
log.error(`API Route ${url.pathname} has no default or \`handler\` export`);
return Response.json({
success: false,
msg: is_dev
? `Route ${url.pathname} has no default or \`handler\` export`
: "Internal Server Error",
}, { status: 500 });
}
let res;
try {
res = await target_module?.({
res = await target_module({
...routeParams,
});
}
@@ -105,7 +85,7 @@ export default async function ({ req }) {
log.error(`API Route Error (${url.pathname}): ${error?.message}\n${error?.stack || ""}`);
return Response.json({
success: false,
msg: `Route handler error: ${error?.message || "Internal Server Error"}`,
msg: routeErrorMessage(error),
}, {
status: 500,
headers: {
@@ -138,7 +118,7 @@ export default async function ({ req }) {
log.error(`API Route Error (${url.pathname}): ${error?.message}\n${error?.stack || ""}`);
return Response.json({
success: false,
msg: `Route handler error: ${error?.message || "Internal Server Error"}`,
msg: routeErrorMessage(error),
}, {
status: 500,
headers: {
@@ -147,3 +127,19 @@ export default async function ({ req }) {
});
}
}
function bodyTooLargeResponse() {
return Response.json({
success: false,
msg: "Request Body Too Large!",
}, { status: 413 });
}
/**
* Error details can leak internals, so they are only exposed in
* development. They are always logged server-side.
*/
function routeErrorMessage(error) {
if (!isDevelopment()) {
return "Internal Server Error";
}
return `Route handler error: ${error?.message || "Internal Server Error"}`;
}
+6 -4
View File
@@ -40,9 +40,9 @@ export default async function serverPostBuildFn(params) {
}
continue;
}
const mock_req = target_artifact.req_url
? new Request(target_artifact.req_url, {})
: new Request(controller.page_url);
// Re-render with this tab's own URL and cookie, never another
// client's request.
const mock_req = new Request(controller.page_url);
if (controller.page_cookie) {
mock_req.headers.set("cookie", controller.page_cookie);
}
@@ -59,7 +59,9 @@ export default async function serverPostBuildFn(params) {
}
const { serverRes } = page_component || {};
const final_artifact = {
..._.omit(controller, ["controller"]),
// `page_cookie` holds the raw Cookie header (incl. HttpOnly
// cookies), so it must never be sent back to page JS.
..._.omit(controller, ["controller", "page_cookie", "page_url"]),
target_map: target_artifact,
};
if (!target_artifact) {
+41 -18
View File
@@ -1,6 +1,6 @@
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import grabContants from "../../../utils/grab-constants";
import EJSON from "../../../utils/ejson";
import serializeForScript from "../../../utils/serialize-for-script";
import isDevelopment from "../../../utils/is-development";
import grabWebPageHydrationScript from "./grab-web-page-hydration-script";
import grabWebMetaHTML from "./grab-web-meta-html";
@@ -19,7 +19,11 @@ export default async function genWebHTML({ component: Main, pageProps, bundledMa
if (!Main) {
throw new Error(`Main Component not found!`);
}
const serializedProps = (EJSON.stringify(pageProps || {}) || "{}").replace(/<\//g, "<\\/");
let serializedProps = "{}";
try {
serializedProps = serializeForScript(pageProps || {});
}
catch (error) { }
const page_hydration_script = await grabWebPageHydrationScript();
const root_meta = root_module?.meta
? typeof root_module.meta == "function" && routeParams
@@ -52,9 +56,9 @@ export default async function genWebHTML({ component: Main, pageProps, bundledMa
},
};
let final_component = (_jsxs("html", { ...html_props, children: [_jsxs("head", { children: [_jsx("meta", { charSet: "utf-8", "data-bunext-head": true }), _jsx("meta", { name: "viewport", content: "width=device-width, initial-scale=1.0", "data-bunext-head": true }), final_meta ? grabWebMetaHTML({ meta: final_meta }) : null, bundledMap?.css_path ? (_jsx("link", { rel: "stylesheet", href: `/${bundledMap.css_path}`, "data-bunext-head": true })) : null, _jsx("script", { dangerouslySetInnerHTML: {
__html: `window.${ClientWindowPagePropsName} = ${serializedProps};\nwindow.process = ${JSON.stringify(client_process)}`,
__html: `window.${ClientWindowPagePropsName} = ${serializedProps};\nwindow.process = ${serializeForScript(client_process)}`,
}, "data-bunext-head": true }), RootHead ? (_jsx(RootHead, { serverRes: pageProps, ctx: routeParams })) : null, Head ? _jsx(Head, { serverRes: pageProps, ctx: routeParams }) : null, bundledMap?.path ? (_jsxs(_Fragment, { children: [_jsx("script", { type: "importmap", dangerouslySetInnerHTML: {
__html: JSON.stringify(global.BUNEXT_REACT_IMPORTS_MAP),
__html: serializeForScript(global.BUNEXT_REACT_IMPORTS_MAP),
}, defer: true, "data-bunext-head": true }), _jsx("script", { src: `/${bundledMap.path}`, type: "module", id: AppData["BunextClientHydrationScriptID"], defer: true, "data-bunext-head": true })] })) : null, is_dev ? (_jsx("script", { defer: true, dangerouslySetInnerHTML: {
__html: page_hydration_script,
}, "data-bunext-head": true })) : null] }), _jsx("body", { children: _jsx("div", { id: ClientRootElementIDName, suppressHydrationWarning: !dev, children: _jsx(Main, { ...pageProps }) }) })] }));
@@ -66,18 +70,7 @@ export default async function genWebHTML({ component: Main, pageProps, bundledMa
// },
// });
// const htmlBody = await new Response(stream).text();
const originalConsole = {
log: console.log,
warn: console.warn,
error: console.error,
info: console.info,
debug: console.debug,
};
console.log = () => { };
console.warn = () => { };
console.error = () => { };
console.info = () => { };
console.debug = () => { };
silenceConsole();
let htmlBody;
let render_error;
let has_render_error = false;
@@ -90,13 +83,13 @@ export default async function genWebHTML({ component: Main, pageProps, bundledMa
has_render_error = true;
render_error = error;
}
originalConsole.error(error);
original_console.error(error);
},
});
htmlBody = await new Response(stream).text();
}
finally {
Object.assign(console, originalConsole);
restoreConsole();
}
// A component crash during SSR must surface as a proper error (handled
// upstream as a 500 page). React only reports these to `onError`; without
@@ -107,3 +100,33 @@ export default async function genWebHTML({ component: Main, pageProps, bundledMa
html += htmlBody;
return html;
}
let original_console = console;
let silenced_renders = 0;
/**
* Renders can overlap (each one awaits the stream), so the console is
* swapped only by the first active render and restored by the last one.
* Otherwise a render could save another render's no-ops as the "original"
* console and silence the server for good.
*/
function silenceConsole() {
if (silenced_renders++ > 0)
return;
original_console = {
log: console.log,
warn: console.warn,
error: console.error,
info: console.info,
debug: console.debug,
};
console.log = () => { };
console.warn = () => { };
console.error = () => { };
console.info = () => { };
console.debug = () => { };
}
function restoreConsole() {
if (--silenced_renders > 0)
return;
silenced_renders = 0;
Object.assign(console, original_console);
}
@@ -7,6 +7,19 @@ export default async function generateWebPageGetCachePage({ module, routeParams,
const expiry_seconds = config?.cacheExpiry || serverRes?.cache_expiry;
if (cache_page && routeParams?.url) {
try {
const status = serverRes?.response_options?.status;
if (status && (status < 200 || status >= 300)) {
return false;
}
const res_headers = new Headers(serverRes?.response_options?.headers);
if (res_headers.has("set-cookie")) {
return false;
}
const req_headers = routeParams.req.headers;
if (!global.BUNEXT_CONFIG?.cache_credentialed_requests &&
(req_headers.has("cookie") || req_headers.has("authorization"))) {
return false;
}
const is_cache = typeof cache_page == "boolean"
? cache_page
: await cache_page({ ctx: routeParams, serverRes });
@@ -5,6 +5,11 @@ import genWebHTML from "./generate-web-html";
import generateWebPageGetCachePage from "./generate-web-page-get-cache-page";
export default async function generateWebPageResponseFromComponentReturn({ component, module, bundledMap, routeParams, serverRes, debug, root_module, }) {
const is_dev = isDevelopment();
if (serverRes?.redirect?.destination) {
return Response.redirect(serverRes.redirect.destination, serverRes.redirect.permanent
? 301
: serverRes.redirect.status_code || 302);
}
const html = await genWebHTML({
component,
pageProps: serverRes,
@@ -17,11 +22,6 @@ export default async function generateWebPageResponseFromComponentReturn({ compo
if (debug) {
log.info("html", html);
}
if (serverRes?.redirect?.destination) {
return Response.redirect(serverRes.redirect.destination, serverRes.redirect.permanent
? 301
: serverRes.redirect.status_code || 302);
}
const res_opts = {
...serverRes?.response_options,
headers: {
+8 -5
View File
@@ -11,6 +11,7 @@ import { existsSync } from "fs";
import grabDirNames from "../../../utils/grab-dir-names";
import grabRelativePath from "../../../utils/grab-relative-path";
import { logBuildErrorsOnce } from "../../../utils/build-error-log";
import { RequestBodyTooLargeError } from "../../../utils/read-request-body";
const { BUNX_BUNDLER_ERROR_EXIT_FILE, ROOT_DIR } = grabDirNames();
class NotFoundError extends Error {
status = 404;
@@ -24,8 +25,10 @@ export default async function grabPageComponent(params) {
const url = req?.url ? new URL(req.url) : undefined;
const router = global.BUNEXT_ROUTER;
const is_dev = isDevelopment();
const forwarded_proto = req?.headers.get("x-forwarded-proto");
if (url && forwarded_proto) {
const forwarded_proto = global.BUNEXT_CONFIG?.trust_proxy
? req?.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()
: undefined;
if (url && (forwarded_proto == "http" || forwarded_proto == "https")) {
url.protocol = forwarded_proto;
}
let routeParams = undefined;
@@ -78,9 +81,6 @@ export default async function grabPageComponent(params) {
throw new Error(errMsg);
}
}
if (req && !is_hydration) {
global.BUNEXT_BUNDLER_CTX_MAP[relative_file_path].req_url = req.url;
}
if (debug) {
log.info(`bundledMap:`, bundledMap);
}
@@ -117,6 +117,9 @@ export default async function grabPageComponent(params) {
};
}
catch (error) {
if (error instanceof RequestBodyTooLargeError) {
return new Response("Request Body Too Large", { status: 413 });
}
const is404 = error instanceof NotFoundError ||
error?.name === "NotFoundError" ||
error?.status === 404;
@@ -13,6 +13,9 @@ export default async function grabPageErrorComponent({ error, routeParams, is404
const presetComponent = is404
? BUNX_ROOT_404_PRESET_COMPONENT
: BUNX_ROOT_500_PRESET_COMPONENT;
// 404 messages only contain the requested path. Other error messages can
// leak internals, so they are only shown in development.
const error_message = is404 || is_dev ? error?.message : "Internal Server Error";
const default_server_res = {
response_options: {
status: is404 ? 404 : 500,
@@ -24,7 +27,7 @@ export default async function grabPageErrorComponent({ error, routeParams, is404
const default_module = await import(presetComponent);
const Component = default_module.default;
const default_jsx = () => {
return _jsx(Component, { children: _jsx("span", { children: error.message }) });
return _jsx(Component, { children: _jsx("span", { children: error_message }) });
};
return {
component: default_jsx,
@@ -65,7 +68,7 @@ export default async function grabPageErrorComponent({ error, routeParams, is404
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
}, children: [_jsx("h1", { children: is404 ? "404 Not Found" : "500 Internal Server Error" }), _jsx("span", { children: error.message })] }));
}, children: [_jsx("h1", { children: is404 ? "404 Not Found" : "500 Internal Server Error" }), _jsx("span", { children: error_message })] }));
return {
component: DefaultNotFound,
routeParams,
+6 -3
View File
@@ -1,5 +1,6 @@
import _ from "lodash";
import { log } from "../../../utils/log";
import isDevelopment from "../../../utils/is-development";
export default async function grabPageServerRes({ url, query, routeParams, server_function, props, }) {
const default_props = {
url: url
@@ -14,9 +15,7 @@ export default async function grabPageServerRes({ url, query, routeParams, serve
"searchParams",
"hash",
"href",
"password",
"protocol",
"username",
]),
}
: null,
@@ -36,8 +35,12 @@ export default async function grabPageServerRes({ url, query, routeParams, serve
}
catch (error) {
log.error(`Page ${url?.pathname} Server Error => ${error.message}\n`, error);
// Error details can leak internals, so only expose them in
// development. They are always logged above.
return _.merge(default_props, {
error: error.message,
error: isDevelopment()
? error.message
: "Internal Server Error",
});
}
}
@@ -1,5 +0,0 @@
type Params = {
tsx: string;
};
export default function grabTsxStringModule<T>({ tsx, }: Params): Promise<T>;
export {};
@@ -1,73 +0,0 @@
import isDevelopment from "../../../utils/is-development";
import * as esbuild from "esbuild";
export default async function grabTsxStringModule({ tsx, }) {
const dev = isDevelopment();
const now = Date.now();
const final_tsx = dev ? tsx + `\n// v_${now}` : tsx;
const result = await esbuild.transform(final_tsx, {
loader: "tsx",
format: "esm",
jsx: "automatic",
minify: !dev,
});
const blob = new Blob([result.code], { type: "text/javascript" });
const url = URL.createObjectURL(blob);
const mod = await import(url);
URL.revokeObjectURL(url);
return mod;
}
// export default async function grabTsxStringModule<T extends any = any>({
// tsx,
// }: Params): Promise<T> {
// const dev = isDevelopment();
// const now = Date.now();
// const { BUNX_CWD_MODULE_CACHE_DIR } = grabDirNames();
// const target_cache_file_path = path.join(
// BUNX_CWD_MODULE_CACHE_DIR,
// `server-render-${now}.js`,
// );
// await esbuild.build({
// stdin: {
// contents: dev ? tsx + `\n// v_${now}` : tsx,
// resolveDir: process.cwd(),
// loader: "tsx",
// },
// bundle: true,
// format: "esm",
// target: "es2020",
// platform: "node",
// external: [
// "react",
// "react-dom",
// "react/jsx-runtime",
// "react/jsx-dev-runtime",
// ],
// minify: !dev,
// define: {
// "process.env.NODE_ENV": JSON.stringify(
// dev ? "development" : "production",
// ),
// },
// jsx: "automatic",
// outfile: target_cache_file_path,
// plugins: [tailwindEsbuildPlugin],
// });
// Loader.registry.delete(target_cache_file_path);
// const mod = await import(`${target_cache_file_path}?t=${now}`);
// return mod as T;
// }
// if (!dev) {
// const now = Date.now();
// const final_tsx = dev ? tsx + `\n// v_${now}` : tsx;
// const result = await esbuild.transform(final_tsx, {
// loader: "tsx",
// format: "esm",
// jsx: "automatic",
// minify: !dev,
// });
// const blob = new Blob([result.code], { type: "text/javascript" });
// const url = URL.createObjectURL(blob);
// const mod = await import(url);
// URL.revokeObjectURL(url);
// return mod as T;
// }
+1 -1
View File
@@ -2,5 +2,5 @@ import type { BunextPageModuleMeta } from "../../../types";
type Params = {
meta: BunextPageModuleMeta;
};
export default function grabWebMetaHTML({ meta }: Params): import("react/jsx-runtime").JSX.Element;
export default function grabWebMetaHTML({ meta }: Params): import("react").JSX.Element;
export {};