fix(auth): race-safe first-run setup + rolling cookie max-age refresh

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
saopig1andClaude Sonnet 4.6 committed 2026-05-27 14:54:19 +08:00
1 parent fb7feec5cf
commit ceb24595e6
6 files changed
+82 -8

No files matched your search

+12
View File
@@ -53,4 +53,16 @@ describe("requireAuth middleware", () => {
expect(res.body.ok).toBe(true);
expect(res.body.user.username).toBe("alice");
});
it("rolls the cookie max-age forward on successful auth", async () => {
const res = await request(app)
.get("/protected")
.set("Cookie", `${SESSION_COOKIE_NAME}=${validToken}`);
expect(res.status).toBe(200);
const setCookieHeaders = res.headers["set-cookie"];
const arr = Array.isArray(setCookieHeaders) ? setCookieHeaders : setCookieHeaders ? [setCookieHeaders] : [];
const refreshed = arr.find((c) => c.startsWith(`${SESSION_COOKIE_NAME}=`));
expect(refreshed).toBeDefined();
expect(refreshed!).toMatch(/Max-Age=\d+/);
});
});
+16 -1
View File
@@ -1,6 +1,11 @@
import type { Request, Response, NextFunction, RequestHandler } from "express";
import type { SessionStore } from "../../data/sessions.js";
import { validateSessionFromHeaders, SESSION_COOKIE_NAME } from "../auth/validateSession.js";
import { SESSION_TTL_MS } from "../../data/sessions.js";
import {
validateSessionFromHeaders,
extractSessionToken,
SESSION_COOKIE_NAME,
} from "../auth/validateSession.js";
declare module "express-serve-static-core" {
interface Request {
@@ -17,6 +22,16 @@ export function createRequireAuth(sessions: SessionStore): RequestHandler {
return;
}
req.user = { id: result.userId, username: result.username };
const token = extractSessionToken(req.headers.cookie);
if (token) {
res.cookie(SESSION_COOKIE_NAME, token, {
httpOnly: true,
sameSite: "lax",
secure: req.secure,
path: "/",
maxAge: SESSION_TTL_MS,
});
}
next();
};
}