refactor: use cookie package for parsing and serializing auth cookies

This commit is contained in:
Codex
2026-02-18 13:12:56 +00:00
parent 82fbefda10
commit 2896499c53

View File

@@ -1,26 +1,14 @@
"use strict";
const cookie = require("cookie");
const COOKIE_NAME = "xartaudio_user";
function parseCookies(cookieHeader) {
if (!cookieHeader) {
if (!cookieHeader || typeof cookieHeader !== "string") {
return {};
}
return String(cookieHeader)
.split(";")
.map((part) => part.trim())
.filter(Boolean)
.reduce((acc, pair) => {
const eq = pair.indexOf("=");
if (eq <= 0) {
return acc;
}
const key = pair.slice(0, eq).trim();
const value = pair.slice(eq + 1).trim();
acc[key] = decodeURIComponent(value);
return acc;
}, {});
return cookie.parse(cookieHeader);
}
function serializeUserCookie(userId, maxAgeSeconds) {
@@ -28,16 +16,25 @@ function serializeUserCookie(userId, maxAgeSeconds) {
throw new Error("user_id_required");
}
const encoded = encodeURIComponent(String(userId));
const maxAge = Number.isInteger(maxAgeSeconds) && maxAgeSeconds > 0
? maxAgeSeconds
: 60 * 60 * 24 * 30;
return `${COOKIE_NAME}=${encoded}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;
return cookie.serialize(COOKIE_NAME, String(userId), {
path: "/",
httpOnly: true,
sameSite: "lax",
maxAge,
});
}
function clearUserCookie() {
return `${COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
return cookie.serialize(COOKIE_NAME, "", {
path: "/",
httpOnly: true,
sameSite: "lax",
maxAge: 0,
});
}
function getAuthenticatedUserId(headers) {