Files
eric 37d0883ce9 ''
2026-03-12 19:50:25 -05:00

35 lines
1.1 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.
/**
* 认证 Cookie 配置
* 生产环境设置 AUTH_COOKIE_DOMAIN 实现跨子域 SSO如 .hackrobot.cn
* 本地开发不设置 domain避免 IP 访问时 cookie 失效
*/
const COOKIE_NAME = "pb_session";
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
export { COOKIE_NAME, COOKIE_MAX_AGE };
/** 从请求 Host 头提取 hostname不含端口 */
export function getHostFromRequest(request: { headers: { get: (k: string) => string | null } }): string {
const host = request.headers.get("host") || request.headers.get("x-forwarded-host") || "";
return host.split(",")[0].trim().replace(/:\d+$/, "");
}
export function getCookieOptions(clear = false, requestHost?: string) {
const isProd = process.env.NODE_ENV === "production";
const domain = process.env.AUTH_COOKIE_DOMAIN?.trim();
const opts: Record<string, unknown> = {
path: "/",
maxAge: clear ? 0 : COOKIE_MAX_AGE,
secure: isProd,
sameSite: "lax" as const,
httpOnly: true,
};
if (domain && isProd) {
opts.domain = domain;
} else if (!isProd && requestHost && /^(\d{1,3}\.){3}\d{1,3}$/.test(requestHost)) {
opts.domain = requestHost;
}
return opts;
}