From 2896499c5327f2a3eb5272b0d6a351444886fe89 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 18 Feb 2026 13:12:56 +0000 Subject: [PATCH] refactor: use cookie package for parsing and serializing auth cookies --- src/lib/auth.js | 35 ++++++++++++++++------------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/src/lib/auth.js b/src/lib/auth.js index c465ebc..a4db957 100644 --- a/src/lib/auth.js +++ b/src/lib/auth.js @@ -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) {