feat(auth): validate agent requests
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import type { NextFunction, Request, Response } from "express";
|
||||
|
||||
import { config } from "../config.js";
|
||||
import { logger } from "../logger.js";
|
||||
|
||||
export const extractBearerToken = (authorization?: string) => {
|
||||
const value = authorization?.trim();
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
return value.replace(/^Bearer\s+/i, "").trim();
|
||||
};
|
||||
|
||||
// Agent API 复用 TJWater 后端的登录态:每个请求都向 /auth/me 校验 Bearer token,
|
||||
// 成功后才允许进入会话路由,避免 Agent 服务维护第二套用户体系。
|
||||
export const requireAgentAuth = async (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
const token = extractBearerToken(req.header("authorization"));
|
||||
if (!token) {
|
||||
res.status(401).json({ message: "authorization token is required" });
|
||||
return;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), config.AGENT_AUTH_TIMEOUT_MS);
|
||||
|
||||
try {
|
||||
const response = await fetch(new URL("/api/v1/auth/me", config.TJWATER_API_BASE_URL), {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
const detail = await response.text();
|
||||
res.status(response.status === 403 ? 403 : 401).json({
|
||||
message: response.status === 403 ? "forbidden" : "unauthorized",
|
||||
detail: detail || undefined,
|
||||
});
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
logger.warn({ err: error }, "agent auth validation failed");
|
||||
res.status(503).json({
|
||||
message: "authentication service unavailable",
|
||||
detail,
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user