Specify sessions that are secure by default
Server-side sessions hinge on a few details that are easy to get subtly wrong: where the session lives, how long it lasts, which cookie flags protect it, and exactly when it must be destroyed. This builder turns those choices into a precise spec — including a copy-paste Set-Cookie line — so the implementation can’t drift from the security intent.
How it works
The spec opens with the store. Redis is the common choice because it supports automatic TTL eviction, so expired sessions clean themselves up; Postgres or a signed cookie are alternatives with different trade-offs. The session record carries the userId, timestamps, a CSRF token, and request fingerprints for anomaly detection, and the session ID itself is a high-entropy random value — never derived from user data.
Next it assembles the cookie. Based on your toggles it emits a real Set-Cookie header with HttpOnly (hide the ID from JavaScript, defeating XSS theft), Secure (HTTPS only), SameSite (the CSRF lever), Path, optional Domain, and Max-Age. Each flag is annotated so a reader understands why it’s set. Then it fixes expiry: an idle timeout for inactivity, an absolute timeout as a hard ceiling, and an optional sliding mode where each request resets the idle timer and cookie lifetime.
Invalidation rules
The most security-relevant section is invalidation. On logout you delete the server record and expire the cookie with Max-Age=0 — deleting only one leaves a usable session. On login you regenerate the session ID to prevent fixation. On password reset or privilege change you invalidate every session for that user, and a “sign out everywhere” action purges them all. Because the store enforces TTLs, idle and absolute expiry simply evict the record and the next request is treated as unauthenticated.