Files

178 lines
6.1 KiB
JavaScript

import { createServer, request as httpRequest } from "node:http";
import { request as httpsRequest } from "node:https";
import { createReadStream, existsSync } from "node:fs";
import { stat } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { resolve, extname, sep } from "node:path";
const envPath = fileURLToPath(new URL("../.env.local", import.meta.url));
if (existsSync(envPath)) process.loadEnvFile(envPath);
export const backendTarget =
process.env.ROBOT_API_TARGET || "https://dev-cadworld-api.robotquan.com";
export const rewriteDevCookie = (value) =>
value
.replace(/;\s*Domain=[^;]+/gi, "")
.replace(/;\s*Secure(?=;|$)/gi, "")
.replace(/;\s*SameSite=None/gi, "; SameSite=Lax");
const dist = resolve(fileURLToPath(new URL("../dist/", import.meta.url)));
const jsonError = (res, code = "DEMAND_UNAVAILABLE", status = 502) => {
if (res.headersSent) {
res.destroy();
return;
}
res.writeHead(status, {
"Content-Type": "application/json",
"Cache-Control": "no-store",
});
res.end(JSON.stringify({ code, message: "请求未完成", data: null }));
};
export function createBackendServer({
target = backendTarget,
production = process.env.NODE_ENV === "production",
} = {}) {
const upstream = new URL(target);
if (!["http:", "https:"].includes(upstream.protocol))
throw Error("Invalid ROBOT_API_TARGET");
return createServer(async (req, res) => {
res.setHeader("X-Content-Type-Options", "nosniff");
const url = new URL(req.url || "/", "http://localhost");
const modelAsset = url.pathname.startsWith("/api/robot-model-assets/");
const authApi =
url.pathname.startsWith("/api/auth/") ||
url.pathname.startsWith("/api/users/");
const projectApi =
url.pathname.startsWith("/api/projects") ||
url.pathname.startsWith("/api/plaza/");
const robotApi = url.pathname.startsWith("/api/robot-");
if (modelAsset) {
try {
const key = decodeURIComponent(
url.pathname.slice("/api/robot-model-assets/".length),
);
if (
!key ||
key.includes("\\") ||
key.includes("\0") ||
key.split("/").some((part) => part === "." || part === "..")
) {
jsonError(res, "INVALID_REQUEST", 400);
return;
}
} catch {
jsonError(res, "INVALID_REQUEST", 400);
return;
}
}
if (modelAsset && !["GET", "HEAD"].includes(req.method)) {
jsonError(res, "METHOD_NOT_ALLOWED", 405);
return;
}
if (authApi || projectApi || robotApi) {
try {
if (
req.headers.origin &&
new URL(req.headers.origin).host !== req.headers.host
) {
jsonError(res, "INVALID_REQUEST", 403);
return;
}
} catch {
jsonError(res, "INVALID_REQUEST", 403);
return;
}
const headers = { ...req.headers, host: upstream.host };
delete headers.origin;
const request = (
upstream.protocol === "https:" ? httpsRequest : httpRequest
)(
new URL(
(modelAsset
? url.pathname.replace(
/^\/api\/robot-model-assets\//,
"/admin-api/component-assets/",
)
: url.pathname) + url.search,
upstream,
),
{ method: req.method, headers, timeout: authApi || projectApi ? 30000 : 240000 },
(response) => {
const responseHeaders = {
...response.headers,
"x-accel-buffering": "no",
...(projectApi ? {} : { "cache-control": "no-store" }),
};
if (responseHeaders["set-cookie"])
responseHeaders["set-cookie"] = responseHeaders["set-cookie"].map(
(cookie) =>
production
? cookie.replace(/;\s*Domain=[^;]+/gi, "")
: rewriteDevCookie(cookie),
);
res.writeHead(response.statusCode || 502, responseHeaders);
response.pipe(res);
response.on("error", () => res.destroy());
},
);
request.on("timeout", () => request.destroy());
request.on("error", () => jsonError(res));
req.on("aborted", () => request.destroy());
res.on("close", () => request.destroy());
req.pipe(request);
return;
}
if (
!["GET", "HEAD"].includes(req.method) ||
/^\/(?:api|server|scripts|tests|docs|shared|ai-rules|handoff|downloads)(?:\/|$)/.test(
url.pathname,
)
) {
jsonError(res, "NOT_FOUND", 404);
return;
}
let path;
try {
path = resolve(dist, "." + decodeURIComponent(url.pathname));
} catch {
jsonError(res, "NOT_FOUND", 404);
return;
}
if (
(!path.startsWith(dist + sep) && path !== dist) ||
url.pathname.split("/").some((part) => part.startsWith("."))
) {
jsonError(res, "NOT_FOUND", 404);
return;
}
if (path === dist) path = resolve(dist, "index.html");
try {
const info = await stat(path);
if (!info.isFile()) throw Error();
const mime =
{
".html": "text/html; charset=utf-8",
".js": "text/javascript",
".css": "text/css",
".json": "application/json",
".png": "image/png",
".svg": "image/svg+xml",
".woff2": "font/woff2",
}[extname(path)] || "application/octet-stream";
res.writeHead(200, { "Content-Type": mime, "Content-Length": info.size });
if (req.method === "HEAD") res.end();
else createReadStream(path).pipe(res);
} catch {
if (path.startsWith(dist + sep) && !extname(url.pathname)) {
try {
const indexPath = resolve(dist, "index.html");
const info = await stat(indexPath);
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": info.size });
if (req.method === "HEAD") res.end();
else createReadStream(indexPath).pipe(res);
return;
} catch { /* Build output is missing; return the normal 404. */ }
}
jsonError(res, "NOT_FOUND", 404);
}
});
}