Files
frontend/shared/local-api-guard.ts

48 lines
1.3 KiB
TypeScript

import type { IncomingMessage, ServerResponse } from "node:http";
/** Local Vite is the API client. Reject foreign browser origins before forwarding. */
export function localApiGuard(
req: IncomingMessage,
res: ServerResponse,
next: () => void,
) {
const path = new URL(req.url || "/", "http://localhost").pathname;
if (
path.startsWith("/api/auth/") ||
path.startsWith("/api/users/") ||
path.startsWith("/api/projects") ||
path.startsWith("/api/plaza/") ||
path.startsWith("/api/robot-") ||
path === "/admin-api" ||
path.startsWith("/admin-api/")
) {
const origin = req.headers.origin;
if (origin) {
let trusted = false;
try {
trusted = new URL(origin).host === req.headers.host;
} catch {
/* reject invalid origin */
}
if (!trusted) {
res.writeHead(403, {
"Content-Type": "application/json",
"Cache-Control": "no-store",
});
res.end(
JSON.stringify({
code: "INVALID_REQUEST",
message: "请求来源不匹配",
data: null,
}),
);
return;
}
}
// Match the standalone local proxy: don't send the browser's local Origin
// to the remote API after the same-origin check has already succeeded.
delete req.headers.origin;
}
next();
}