Fix security vulnerabilities
This commit is contained in:
+41
-18
@@ -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
-5
@@ -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
@@ -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
@@ -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
@@ -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 {};
|
||||
|
||||
Reference in New Issue
Block a user