BlueGit

timfa questward

Files

questward / server / src / auth / cookies.js

cookies.js

cookies.js 1.4 KiB Download Raw
1export function parseCookies (header)
2{
3 const out = Object.create(null);
4 if (!header)
5 { return out; }
6 for (const part of String(header).split(";"))
7 {
8 const trimmed = part.trim();
9 if (!trimmed)
10 { continue; }
11 const eq = trimmed.indexOf("=");
12 if (eq <= 0)
13 { continue; }
14 const key = trimmed.slice(0, eq);
15 const value = trimmed.slice(eq + 1);
16 out[key] = decodeURIComponent(value);
17 }
18 return out;
19}
20
21export function publicOrigin (req)
22{
23 const host = req.headers["x-forwarded-host"] ?? req.headers.host ?? "localhost";
24 const proto = req.headers["x-forwarded-proto"] ?? "http";
25 return `${proto}://${host}`;
26}
27
28export function isSecureRequest (req)
29{
30 const proto = req.headers["x-forwarded-proto"];
31 if (proto)
32 { return proto === "https"; }
33 return false;
34}
35
36export function setCookie (res, name, value, { maxAgeSec, httpOnly = true, sameSite = "Lax", secure = false, path = "/" } = {})
37{
38 const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${path}`, `SameSite=${sameSite}`];
39 if (httpOnly)
40 { parts.push("HttpOnly"); }
41 if (secure)
42 { parts.push("Secure"); }
43 if (maxAgeSec != null)
44 { parts.push(`Max-Age=${maxAgeSec}`); }
45 res.appendHeader("Set-Cookie", parts.join("; "));
46}
47
48export function clearCookie (res, name, { secure = false, path = "/" } = {})
49{
50 const parts = [`${name}=`, `Path=${path}`, "Max-Age=0", "SameSite=Lax"];
51 parts.push("HttpOnly");
52 if (secure)
53 { parts.push("Secure"); }
54 res.appendHeader("Set-Cookie", parts.join("; "));
55}