Fix security vulnerabilities and request handling bugs
- Move page cache out of the publicly served .bunext/public dir and hash cache keys - Skip caching credentialed requests, non-2xx and Set-Cookie responses; cap entries - Enforce API body size limit while reading; keep req body readable for handlers - Hide error messages from clients in production - Escape inline script JSON; strip cookies from HMR payloads - Only trust X-Forwarded-Proto with trust_proxy config - Fix console race in SSR, dotted page paths, middleware rewrites, excluded path status, encoded static file names, symlinked dirs - Upgrade vulnerable deps, remove micromatch, pin bun versions, delete dead code Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import grabContants from "../../../utils/grab-constants";
|
||||
import EJSON from "../../../utils/ejson";
|
||||
import serializeForScript from "../../../utils/serialize-for-script";
|
||||
import type { LivePageDistGenParams } from "../../../types";
|
||||
import isDevelopment from "../../../utils/is-development";
|
||||
import grabWebPageHydrationScript from "./grab-web-page-hydration-script";
|
||||
@@ -37,10 +37,11 @@ export default async function genWebHTML({
|
||||
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
|
||||
@@ -106,7 +107,7 @@ export default async function genWebHTML({
|
||||
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `window.${ClientWindowPagePropsName} = ${serializedProps};\nwindow.process = ${JSON.stringify(client_process)}`,
|
||||
__html: `window.${ClientWindowPagePropsName} = ${serializedProps};\nwindow.process = ${serializeForScript(client_process)}`,
|
||||
}}
|
||||
data-bunext-head
|
||||
/>
|
||||
@@ -121,7 +122,7 @@ export default async function genWebHTML({
|
||||
<script
|
||||
type="importmap"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: JSON.stringify(
|
||||
__html: serializeForScript(
|
||||
global.BUNEXT_REACT_IMPORTS_MAP,
|
||||
),
|
||||
}}
|
||||
@@ -170,19 +171,7 @@ export default async function genWebHTML({
|
||||
|
||||
// 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: string;
|
||||
let render_error: any;
|
||||
@@ -198,13 +187,13 @@ export default async function genWebHTML({
|
||||
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
|
||||
@@ -218,3 +207,41 @@ export default async function genWebHTML({
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
let original_console: Pick<
|
||||
Console,
|
||||
"log" | "warn" | "error" | "info" | "debug"
|
||||
> = 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);
|
||||
}
|
||||
|
||||
@@ -29,6 +29,29 @@ export default async function generateWebPageGetCachePage({
|
||||
|
||||
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
|
||||
|
||||
@@ -16,6 +16,15 @@ export default async function generateWebPageResponseFromComponentReturn({
|
||||
}: GrabPageComponentRes) {
|
||||
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,
|
||||
@@ -30,15 +39,6 @@ export default async function generateWebPageResponseFromComponentReturn({
|
||||
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: ResponseInit = {
|
||||
...serverRes?.response_options,
|
||||
headers: {
|
||||
|
||||
@@ -12,6 +12,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();
|
||||
|
||||
@@ -57,9 +58,11 @@ export default async function grabPageComponent(
|
||||
const router = global.BUNEXT_ROUTER;
|
||||
const is_dev = isDevelopment();
|
||||
|
||||
const forwarded_proto = req?.headers.get("x-forwarded-proto");
|
||||
const forwarded_proto = global.BUNEXT_CONFIG?.trust_proxy
|
||||
? req?.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()
|
||||
: undefined;
|
||||
|
||||
if (url && forwarded_proto) {
|
||||
if (url && (forwarded_proto == "http" || forwarded_proto == "https")) {
|
||||
url.protocol = forwarded_proto;
|
||||
}
|
||||
|
||||
@@ -131,10 +134,6 @@ export default async function grabPageComponent(
|
||||
}
|
||||
}
|
||||
|
||||
if (req && !is_hydration) {
|
||||
global.BUNEXT_BUNDLER_CTX_MAP[relative_file_path].req_url = req.url;
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
log.info(`bundledMap:`, bundledMap);
|
||||
}
|
||||
@@ -176,6 +175,10 @@ export default async function grabPageComponent(
|
||||
success: true,
|
||||
};
|
||||
} catch (error: any) {
|
||||
if (error instanceof RequestBodyTooLargeError) {
|
||||
return new Response("Request Body Too Large", { status: 413 });
|
||||
}
|
||||
|
||||
const is404 =
|
||||
error instanceof NotFoundError ||
|
||||
error?.name === "NotFoundError" ||
|
||||
|
||||
@@ -35,6 +35,11 @@ export default async function grabPageErrorComponent({
|
||||
? 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,
|
||||
@@ -50,7 +55,7 @@ export default async function grabPageErrorComponent({
|
||||
);
|
||||
const Component = default_module.default as FC<any>;
|
||||
const default_jsx: FC = () => {
|
||||
return <Component>{<span>{error.message}</span>}</Component>;
|
||||
return <Component>{<span>{error_message}</span>}</Component>;
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -104,7 +109,7 @@ export default async function grabPageErrorComponent({
|
||||
}}
|
||||
>
|
||||
<h1>{is404 ? "404 Not Found" : "500 Internal Server Error"}</h1>
|
||||
<span>{error.message}</span>
|
||||
<span>{error_message}</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
} from "../../../types";
|
||||
import _ from "lodash";
|
||||
import { log } from "../../../utils/log";
|
||||
import isDevelopment from "../../../utils/is-development";
|
||||
|
||||
type Params = {
|
||||
url?: URL;
|
||||
@@ -36,9 +37,7 @@ export default async function grabPageServerRes({
|
||||
"searchParams",
|
||||
"hash",
|
||||
"href",
|
||||
"password",
|
||||
"protocol",
|
||||
"username",
|
||||
]) as any),
|
||||
}
|
||||
: null,
|
||||
@@ -65,8 +64,12 @@ export default async function grabPageServerRes({
|
||||
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,96 +0,0 @@
|
||||
import isDevelopment from "../../../utils/is-development";
|
||||
import * as esbuild from "esbuild";
|
||||
|
||||
type Params = {
|
||||
tsx: string;
|
||||
};
|
||||
|
||||
export default async function grabTsxStringModule<T>({
|
||||
tsx,
|
||||
}: Params): Promise<T> {
|
||||
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 as T;
|
||||
}
|
||||
|
||||
// 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;
|
||||
// }
|
||||
Reference in New Issue
Block a user