36 lines
1.2 KiB
TypeScript
36 lines
1.2 KiB
TypeScript
/**
|
||
* 认证 Cookie 配置
|
||
* 生产环境设置 AUTH_COOKIE_DOMAIN 实现跨子域 SSO(如 .hackrobot.cn)
|
||
* 本地开发不设置 domain,避免 IP 访问时 cookie 失效
|
||
*/
|
||
|
||
import { IS_DEVELOPMENT, IS_PRODUCTION } from "@/config/runtime-env";
|
||
|
||
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 domain = process.env.AUTH_COOKIE_DOMAIN?.trim();
|
||
const opts: Record<string, unknown> = {
|
||
path: "/",
|
||
maxAge: clear ? 0 : COOKIE_MAX_AGE,
|
||
secure: IS_PRODUCTION,
|
||
sameSite: "lax" as const,
|
||
httpOnly: true,
|
||
};
|
||
if (domain && IS_PRODUCTION) {
|
||
opts.domain = domain;
|
||
} else if (IS_DEVELOPMENT && requestHost && /^(\d{1,3}\.){3}\d{1,3}$/.test(requestHost)) {
|
||
opts.domain = requestHost;
|
||
}
|
||
return opts;
|
||
}
|