sh2/d2ypp2/web-console/middleware.ts
2026-06-02 03:19:23 -05:00

83 lines
2.0 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
/**
* 仅 `next dev` 生效:把 FastAPI 同名路由代理到本机 uvicorn。
* 生产环境由 FastAPI 托管 web-console/out,浏览器与 API 同域,不需要本中间件。
*/
const TARGET = process.env.API_PROXY_TARGET || "http://127.0.0.1:8001";
const API_ROOTS = new Set([
"process_monitor",
"server_info",
"health",
"status",
"start",
"stop",
"restart",
"get_config",
"save_config",
"get_url_config",
"save_url_config",
"stack",
"service_action",
"managed_roots",
"managed_files",
"managed_file",
"deploy",
"shellcrash",
"hardware_profile",
"system_snapshot",
"android",
"hub",
"youtube_pro_channels",
"tiktok_replay",
]);
const SHELLCRASH_API_PATHS = new Set(["/shellcrash/apply_profile", "/shellcrash/web_panel"]);
export function middleware(request: NextRequest) {
if (process.env.NODE_ENV !== "development") {
return NextResponse.next();
}
const path = request.nextUrl.pathname;
const root = path.split("/").filter(Boolean)[0] ?? "";
if (root === "shellcrash" && !SHELLCRASH_API_PATHS.has(path)) {
return NextResponse.next();
}
if (!API_ROOTS.has(root)) {
return NextResponse.next();
}
const dest = new URL(path + request.nextUrl.search, TARGET);
return NextResponse.rewrite(dest);
}
/** Dev 代理:含 GET/POST 等同名 API(进程与服务控制已优先使用 POST) */
export const config = {
matcher: [
"/process_monitor",
"/server_info",
"/health",
"/status",
"/start",
"/stop",
"/restart",
"/get_config",
"/save_config",
"/get_url_config",
"/save_url_config",
"/stack/:path*",
"/service_action",
"/managed_roots",
"/managed_files",
"/managed_file",
"/deploy/:path*",
"/shellcrash/:path*",
"/hardware_profile",
"/system_snapshot",
"/android/:path*",
"/hub/:path*",
"/youtube_pro_channels",
"/tiktok_replay/:path*",
],
};