type RouteRule = { path: string; methods?: string[]; }; const API_ALLOWLIST: RouteRule[] = [ { path: "/api/auth/login", methods: ["POST"] }, { path: "/api/auth/register", methods: ["POST"] }, { path: "/api/config/global", methods: ["GET"] }, ]; /** 允许访客发表评论的公开 POST(其余 /api/public/ 写操作仍拒绝) */ function isPublicCommentPostPath(path: string) { if (!path.endsWith("/comments")) { return false; } if (/^\/api\/public\/profile\/[^/]+\/posts\/[^/]+\/comments$/.test(path)) { return true; } if (/^\/api\/public\/unlisted\/[^/]+\/[^/]+\/comments$/.test(path)) { return true; } return false; } /** 公开 API 以只读为主;评论创建为例外,需配合服务端校验与限流 */ export function isPublicApiPath(path: string, method?: string) { if (!path.startsWith("/api/public/")) { return false; } const requestMethod = method?.toUpperCase() ?? "GET"; if (requestMethod === "GET") { return true; } if (requestMethod === "POST" && isPublicCommentPostPath(path)) { return true; } return false; } export function isAllowlistedApiPath(path: string, method?: string) { if (isPublicApiPath(path, method)) { return true; } const requestMethod = method?.toUpperCase() ?? "GET"; return API_ALLOWLIST.some((rule) => { if (rule.path !== path) { return false; } if (!rule.methods || rule.methods.length === 0) { return true; } return rule.methods.includes(requestMethod); }); }