Files
Endoleap/src/lib/session-cookie.ts
T

20 lines
1.5 KiB
TypeScript
Raw 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的纯字符串与寿命辅助,不读取或写入浏览器Cookie。
* 调用方决定何时采用上游过期提示、是否Secure,并把返回字符串放进响应Set-Cookie。
*/
/** 会话 Cookie 的默认寿命上限30天,单位秒;是否滑动续期由调用方重新设置 Cookie 决定。 */
export const SESSION_IDLE_SECONDS = 30 * 24 * 60 * 60;
/** 上游向代理传递剩余会话寿命的响应头名,不是Cookie名。 */
export const SESSION_EXPIRY_HEADER = "X-Foundry-Session-Expires-In";
/** 数字或纯数字字符串可采用,非负安全整数封顶30天,0可用于清除。
* 不合法输入原样退回fallback;自定义fallback由调用方提供有效值,不在此再次封顶。 */
export function sessionMaxAge(value: unknown, fallback = SESSION_IDLE_SECONDS) {
const seconds = typeof value === "number" ? value : typeof value === "string" && /^\d+$/.test(value) ? Number(value) : NaN;
return Number.isSafeInteger(seconds) && seconds >= 0 ? Math.min(seconds, SESSION_IDLE_SECONDS) : fallback;
}
/** URL编码会话值,固定HttpOnly/SameSite=Lax/根路径并规范Max-Age;secure参数为true才添加Secure。
* maxAge 非法时使用默认30天,不自动推断为登出;明确清除须传0。此处不设置 Domain 或 Expires。 */
export function sessionCookie(value: string, maxAge: number, secure: boolean) {
return `foundry_session=${encodeURIComponent(value)}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${sessionMaxAge(maxAge)}${secure ? "; Secure" : ""}`;
}