34 lines
1.1 KiB
TypeScript
34 lines
1.1 KiB
TypeScript
/**
|
||
* 认证 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 };
|
||
|
||
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;
|
||
}
|