cookies.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import type { CookieOptions, Request } from "express";
  2. const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
  3. function isIpAddress(host: string) {
  4. // Basic IPv4 check and IPv6 presence detection.
  5. if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return true;
  6. return host.includes(":");
  7. }
  8. function isSecureRequest(req: Request) {
  9. if (req.protocol === "https") return true;
  10. const forwardedProto = req.headers["x-forwarded-proto"];
  11. if (!forwardedProto) return false;
  12. const protoList = Array.isArray(forwardedProto)
  13. ? forwardedProto
  14. : forwardedProto.split(",");
  15. return protoList.some(proto => proto.trim().toLowerCase() === "https");
  16. }
  17. export function getSessionCookieOptions(
  18. req: Request
  19. ): Pick<CookieOptions, "domain" | "httpOnly" | "path" | "sameSite" | "secure"> {
  20. // const hostname = req.hostname;
  21. // const shouldSetDomain =
  22. // hostname &&
  23. // !LOCAL_HOSTS.has(hostname) &&
  24. // !isIpAddress(hostname) &&
  25. // hostname !== "127.0.0.1" &&
  26. // hostname !== "::1";
  27. // const domain =
  28. // shouldSetDomain && !hostname.startsWith(".")
  29. // ? `.${hostname}`
  30. // : shouldSetDomain
  31. // ? hostname
  32. // : undefined;
  33. return {
  34. httpOnly: true,
  35. path: "/",
  36. sameSite: "none",
  37. secure: isSecureRequest(req),
  38. };
  39. }