30 lines
857 B
TypeScript
30 lines
857 B
TypeScript
import type { CookieOptions, Request } from "express";
|
|
|
|
/** Detects HTTPS after direct access or a reverse proxy such as Traefik. */
|
|
function isSecureRequest(req: Request) {
|
|
if (req.protocol === "https") return true;
|
|
|
|
const forwardedProto = req.headers["x-forwarded-proto"];
|
|
if (!forwardedProto) return false;
|
|
|
|
const protoList = Array.isArray(forwardedProto)
|
|
? forwardedProto
|
|
: forwardedProto.split(",");
|
|
|
|
return protoList.some(proto => proto.trim().toLowerCase() === "https");
|
|
}
|
|
|
|
export function getSessionCookieOptions(
|
|
req: Request
|
|
): Pick<CookieOptions, "domain" | "httpOnly" | "path" | "sameSite" | "secure"> {
|
|
const secure = isSecureRequest(req);
|
|
|
|
return {
|
|
httpOnly: true,
|
|
path: "/",
|
|
// Browsers reject SameSite=None without Secure; use Lax for local HTTP.
|
|
sameSite: secure ? "none" : "lax",
|
|
secure,
|
|
};
|
|
}
|