chore: 完善生产发布与部署校验
This commit is contained in:
1 parent
048c42207c
commit
5c6ad02f46
18 files changed
+1013
-47
No files matched your search
@@ -0,0 +1,182 @@
|
||||
import { createReadStream } from "node:fs";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { createServer } from "node:http";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const contentTypes = new Map([
|
||||
[".css", "text/css; charset=utf-8"],
|
||||
[".gif", "image/gif"],
|
||||
[".html", "text/html; charset=utf-8"],
|
||||
[".ico", "image/x-icon"],
|
||||
[".jpeg", "image/jpeg"],
|
||||
[".jpg", "image/jpeg"],
|
||||
[".js", "text/javascript; charset=utf-8"],
|
||||
[".json", "application/json; charset=utf-8"],
|
||||
[".map", "application/json; charset=utf-8"],
|
||||
[".png", "image/png"],
|
||||
[".svg", "image/svg+xml"],
|
||||
[".webmanifest", "application/manifest+json"],
|
||||
[".webp", "image/webp"],
|
||||
[".woff", "font/woff"],
|
||||
[".woff2", "font/woff2"],
|
||||
]);
|
||||
|
||||
function setSecurityHeaders(response) {
|
||||
response.setHeader("X-Content-Type-Options", "nosniff");
|
||||
response.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
|
||||
response.setHeader("X-Frame-Options", "SAMEORIGIN");
|
||||
}
|
||||
|
||||
function sendError(response, status, message) {
|
||||
response.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
|
||||
response.end(message);
|
||||
}
|
||||
|
||||
function resolveInside(root, relativePath) {
|
||||
const target = path.resolve(root, relativePath);
|
||||
const relative = path.relative(root, target);
|
||||
if (relative === ".." || relative.startsWith(".." + path.sep) || path.isAbsolute(relative)) {
|
||||
return null;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
function routeFor(pathname, adminRoot) {
|
||||
if (pathname === "/") return { redirect: "/admin/" };
|
||||
if (pathname === "/admin") return { redirect: "/admin/" };
|
||||
if (pathname === "/template-preview") return { redirect: "/template-preview/" };
|
||||
if (pathname === "/favicon.ico") return { root: adminRoot, relativePath: "favicon.ico" };
|
||||
if (pathname.startsWith("/admin/")) {
|
||||
return { root: adminRoot, relativePath: pathname.slice("/admin/".length), spa: true };
|
||||
}
|
||||
if (pathname.startsWith("/template-preview/")) {
|
||||
return {
|
||||
root: path.join(adminRoot, "template-preview"),
|
||||
relativePath: pathname.slice("/template-preview/".length),
|
||||
spa: true,
|
||||
};
|
||||
}
|
||||
if (pathname.startsWith("/assets/")) {
|
||||
return { root: adminRoot, relativePath: pathname.slice(1) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function createStaticServer({ adminRoot }) {
|
||||
const root = path.resolve(adminRoot);
|
||||
|
||||
return createServer(async (request, response) => {
|
||||
setSecurityHeaders(response);
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
response.setHeader("Allow", "GET, HEAD");
|
||||
sendError(response, 405, "Method Not Allowed");
|
||||
return;
|
||||
}
|
||||
|
||||
let pathname;
|
||||
try {
|
||||
pathname = new URL(request.url ?? "/", "http://localhost").pathname;
|
||||
} catch {
|
||||
sendError(response, 400, "Bad Request");
|
||||
return;
|
||||
}
|
||||
const route = routeFor(pathname, root);
|
||||
if (!route) {
|
||||
sendError(response, 404, "Not Found");
|
||||
return;
|
||||
}
|
||||
if (route.redirect) {
|
||||
response.writeHead(308, { location: route.redirect });
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
|
||||
let relativePath;
|
||||
try {
|
||||
relativePath = decodeURIComponent(route.relativePath);
|
||||
} catch {
|
||||
sendError(response, 400, "Bad Request");
|
||||
return;
|
||||
}
|
||||
const target = resolveInside(route.root, relativePath || "index.html");
|
||||
if (!target) {
|
||||
sendError(response, 404, "Not Found");
|
||||
return;
|
||||
}
|
||||
|
||||
let filePath = target;
|
||||
let fileInfo;
|
||||
try {
|
||||
fileInfo = await stat(filePath);
|
||||
if (fileInfo.isDirectory()) {
|
||||
filePath = path.join(filePath, "index.html");
|
||||
fileInfo = await stat(filePath);
|
||||
}
|
||||
if (!fileInfo.isFile()) throw new Error("Not a regular file");
|
||||
} catch {
|
||||
const wantsHtml = request.headers.accept?.includes("text/html");
|
||||
if (!route.spa || !wantsHtml || path.extname(relativePath)) {
|
||||
sendError(response, 404, "Not Found");
|
||||
return;
|
||||
}
|
||||
filePath = path.join(route.root, "index.html");
|
||||
try {
|
||||
fileInfo = await stat(filePath);
|
||||
} catch {
|
||||
sendError(response, 404, "Not Found");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const etag =
|
||||
'"' + fileInfo.size.toString(16) + "-" + Math.trunc(fileInfo.mtimeMs).toString(16) + '"';
|
||||
response.setHeader("ETag", etag);
|
||||
if (request.headers["if-none-match"] === etag) {
|
||||
response.writeHead(304);
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const extension = path.extname(filePath).toLowerCase();
|
||||
response.setHeader("Content-Type", contentTypes.get(extension) ?? "application/octet-stream");
|
||||
response.setHeader("Content-Length", fileInfo.size);
|
||||
response.setHeader(
|
||||
"Cache-Control",
|
||||
extension === ".html"
|
||||
? "no-cache"
|
||||
: /(?:^|[.-])[a-zA-Z0-9_-]{8,}(?:[.-])/.test(path.basename(filePath))
|
||||
? "public, max-age=31536000, immutable"
|
||||
: "public, max-age=300",
|
||||
);
|
||||
response.writeHead(200);
|
||||
if (request.method === "HEAD") {
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const stream = createReadStream(filePath);
|
||||
stream.on("error", () => {
|
||||
if (!response.headersSent) sendError(response, 500, "Internal Server Error");
|
||||
else response.destroy();
|
||||
});
|
||||
stream.pipe(response);
|
||||
});
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const port = Number(process.env.ADMIN_STATIC_PORT ?? 3010);
|
||||
const adminRoot = process.env.ADMIN_STATIC_ROOT ?? path.resolve("apps/admin/dist");
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error("ADMIN_STATIC_PORT must be between 1 and 65535");
|
||||
}
|
||||
const server = createStaticServer({ adminRoot });
|
||||
server.listen(port, "0.0.0.0");
|
||||
server.on("error", (error) => {
|
||||
console.error("admin static server failed", error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
for (const signal of ["SIGINT", "SIGTERM"]) {
|
||||
process.on(signal, () => server.close(() => process.exit(0)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user