Sessions and expiry
In short
- The threat
Whoever holds the session value is the user, so a leaked store or a cookie that never expires gives the account away.
- The rule
An opaque random token, only its hash in the store, two clocks that end every session, and no late write that can bring a revoked one back.
- In the package
session/session-manager.ts, configured undersession.
What goes wrong
Section titled “What goes wrong”A session is a bearer credential: whoever holds the value is the user. Two things make that dangerous. If the server stores the value itself, a leaked store (a database dump, a Redis snapshot, a backup) hands the attacker every live session. And if sessions never expire, one stolen cookie works forever.
A session kept in use still ends at its absolute expiry, the store's TTL on the record: 24 h after sign-in, or 30 d with remember me. Its last-active time is written at most once per 60 s, and never past that TTL. A session left open ends after 30 min with no request, or 7 d with remember me. A password change ends every session of the user at once; a refresh still in flight finds no record to update, so it cannot bring the session back, and the device that changed the password gets a new session. An 11th sign-in for the same user evicts the oldest session.
Text version
The rule
Section titled “The rule”Make the token worthless to anyone who reads the store, end every session on two clocks, and never let a write bring one back.
The token is opaque and random
Section titled “The token is opaque and random”The cookie carries 32 bytes from a cryptographically secure random source. It encodes nothing: no user id, no expiry, nothing to forge or parse.
The store keeps only the hash
Section titled “The store keeps only the hash”The store key is the SHA-256 of the token, never the token. A leaked store cannot be replayed, because the attacker holds hashes and needs the preimage. SHA-256 is enough here (no slow password hash) because the input already has 256 bits of entropy, so there is nothing to brute force.
Two expiries, for two threats
Section titled “Two expiries, for two threats”| Expiry | Default | What it bounds |
|---|---|---|
Absolute (absoluteTtl) |
24 hours, 30 days with remember me | The damage of a stolen cookie. |
Idle (idleTimeout) |
30 minutes, 7 days with remember me | Sessions left open on a shared machine. |
- Absolute is the store’s TTL on the session record. However active the user is, the session ends when the TTL does.
- Idle is per session: if the user has not been seen for the idle window, the session is rejected.
Refreshing last-active without resurrecting
Section titled “Refreshing last-active without resurrecting”Validating a session would otherwise write on every request. Instead, the stored last-active time is refreshed at most once per interval, and the write is careful in two ways:
- Update only if it exists. A plain “set” could recreate a record that was revoked a moment earlier, between the read and the write. Update-only-if-exists means a revoked session can never be resurrected by a late refresh.
- Keep the remaining TTL. A refresh never extends the absolute expiry.
Background polls
Section titled “Background polls”Only requests the user makes should count as activity. A page that polls on a timer (a notification badge, a status check) would otherwise refresh the last-active time every few minutes and keep an idle session alive for its whole absolute lifetime, which is exactly what the idle timeout exists to stop.
So validateRequest takes touch: false for traffic the client makes on its own: the session is still validated and answered, but its last-active time is left alone, and an idle session expires while only such requests arrive. Both adapters take a touch option that decides this per request, before the one validation: a predicate over the request for NestJS, a predicate over the procedure paths (or touch: false in a procedure’s meta) for tRPC, where a batch counts as activity when any of its procedures does. The default is unchanged: every request touches. See Use with NestJS and Use with tRPC.
A cap per user, and word of what it ends
Section titled “A cap per user, and word of what it ends”A user holds at most session.maxPerUser sessions (10 by default). Issuing one more evicts the oldest, after the new session is written, so sign-ins racing at the cap still end up within it. The oldest are picked by creation time, then by id, and the session being issued is never one of them: a sign-in in the same millisecond as an older session, or on an instance whose clock is behind, still hands out a live session. A session written while the sign-in ran is evicted only if it sorts before the new one, so of two sign-ins racing at a cap of one, exactly one is left. Two narrow cases remain. A sign-in that stalls between reading the clock and writing its session, while a later one runs to the end, leaves the user one session over the cap until the next sign-in. And two sign-ins on instances whose clocks disagree (or in the same millisecond) can each evict the other, leaving none, when the one written first sorts last.
An evicted session is gone like a revoked one, but whatever the app holds for it (an open socket, a cache entry) is not, so the library names it:
- the issued session carries the evicted sessions’ handles in
evictedHandles(the names the session list showed, safe for a client) and their store keys inevicted(server-side only, likesession.id); onSessionsRevokedfires with reasonevicted, the same store keys assessionIdsand the same handles assessionHandles.
Each eviction is reported once: when two racing sign-ins both pick the same oldest session, or a sign-in evicts a session while it is being signed out, only the call whose delete removed it reports it, under its own reason. That needs a session store whose delete returns the ids it removed; the memory and Redis stores do. The hook is awaited on the sign-in that evicts, so hand slow cleanup to a queue.
Session handles
Section titled “Session handles”A “where you’re signed in” page needs a name for each session, so the user can sign one out. The store key would do, but it is the storage identity of a bearer secret: anything that reads the page (a script injected into it, a browser extension, a shared screen, a client log) would learn the key of every session on the account, and could match those keys against a leaked session store.
So auth.sessions.list(session) names each session by a handle instead: an HMAC-SHA-256 of the store key under a key derived from the server secret, as 43 characters of unpadded base64url. A plain hash of the key would hide it too, but anyone holding a leaked store could compute it and match the two; the HMAC needs the secret as well. The handle never has the 64-character hex shape of a store key, so the two cannot be mixed up.
Revoking by handle. auth.sessions.revoke({ session, handle, meta }) looks the handle up among the caller’s own live sessions only. A handle it does not find (garbage, a raw store key, a session already gone, or another user’s session) answers { revoked: false }, every time the same, so revoke cannot tell anyone whether a handle belongs to someone. A session it ended answers { revoked: true, sessionId }: the store key, the same id onSessionsRevoked reports, for closing that session’s live connections on the server. It is server-side only, like every store key: answer the client { revoked } (the tRPC adapter’s revokedOutput strips it). Revoking another device still needs a fresh password proof by default, asked before any lookup.
The current session is the entry with current: true. Signing it out is better done with logout, which also clears the cookie.
Correlating server-side. onSessionsRevoked receives sessionHandles beside sessionIds, in the same order, so a socket server or a client cache keyed by handle can drop the right entries, whatever the reason (revoke-one, evicted, password-change and the rest). auth.sessions.handle(session.id) gives the handle of any session id you hold on the server.
Rotating the server secret changes every handle (sessions themselves survive it). A client holding an old handle gets { revoked: false } and lists again.
Upgrading to handles
Section titled “Upgrading to handles”Up to @noctcore/auth 0.5 the list returned the store key as id, and revoke took it as id. Both are now handle, and a store key is no longer accepted by revoke: it answers { revoked: false }, like any handle it does not know. Rename the field in your list and revoke routes (and in revokeSessionInput and sessionSummaryOutput with the tRPC adapter), and drop any session ids a client kept: list again and use the handles it returns. Code that kept store keys on the server, from session.id or the hook’s sessionIds, can map them with auth.sessions.handle(id).
In code
Section titled “In code”The defaults written out, and the two routes behind a “where you’re signed in” page.
import type { SessionOptions } from '@noctcore/auth';
// The defaults, written out. Pass them as `session` to createAuth, or leave the// option out and get the same values.export const session = { // The store's TTL on the record: activity never extends it. absoluteTtl: '24h', rememberMeTtl: '30d', // Ends a session nobody has used for this long. idleTimeout: ({ rememberMe }) => (rememberMe ? '7d' : '30m'), // last-active is written at most this often, and never past the TTL. touchInterval: '60s', // One more sign-in evicts the oldest session. maxPerUser: 10,} satisfies SessionOptions<unknown>;import { toPublicError, type RequestMeta, type StoredSession } from '@noctcore/auth';import type { AppAuth } from '../build/node-server/auth';
type Session = StoredSession<Record<string, never>>;
/** "Where you're signed in": sessions named by handle, never store key. */export function signedInDevices(auth: AppAuth, current: Session) { return auth.sessions.list(current);}
/** Signs out one device. Another device needs a fresh password proof by default. */export async function signOutDevice( auth: AppAuth, input: { current: Session; handle: string; meta: RequestMeta },) { const result = await auth.sessions.revoke({ session: input.current, handle: input.handle, meta: input.meta, });
if (!result.ok) return { error: toPublicError(result) };
// A handle it does not find answers { revoked: false }, // another user's included. return { revoked: result.value.revoked };}Where the package and the guide differ
Section titled “Where the package and the guide differ”- Token shape. The guide recommends a session id plus a separate secret, so the session can be referenced without exposing a credential. The package keeps a single random token and uses its SHA-256 as the store key, which keeps sessions issued by the existing apps valid on adoption. That key never goes to a client: what an app lists and revokes is a separate handle, above.
- Refresh interval. The guide suggests refreshing the expiry hourly or daily. The package refreshes last-active at most once a minute, because the default idle timeout is 30 minutes; the refresh never moves the absolute expiry.
- Sign-out on password change. The guide leaves it to the user. The package always revokes every session and re-issues the current one.
- Revoking sessions. As the guide asks, revoking another device’s session, or every other session at once, needs a fresh credential proof (within 10 minutes), so a stolen session cannot sign the owner out. Signing out of the current device needs none. An app may turn either check off with
session.requireFreshAuth(see Fresh authentication); the door then still needs a live session of the same user.
Attack tests
Section titled “Attack tests”| Test | Attack | Stopped by |
|---|---|---|
| A010 | A stolen session cookie outliving a password change | flows/password-change.ts, session/session-manager.ts |
| A017 | Replaying secrets from a leaked store | session/session-manager.ts, crypto/hash.ts |
| A018 | Cookie tossing and reading the session cookie from script | http/cookie.ts |
| A028 | Passing a fresh-auth check with a stale proof | auth-nestjs/session.guard.ts |
| A087 | Reading a session’s store key through the session list, or revoking another user’s session by handle | flows/session-management.ts |
| A097 | Bringing back a revoked session through the legacy store an app adopts sessions from | session/legacy-sessions.ts |
| A103 | Keeping a revoked session alive on a tRPC WebSocket connection | auth-trpc/context.ts |
| A107 | Keeping a revoked session alive on an open tRPC SSE subscription | auth-trpc/subscription.ts |
Further reading
Section titled “Further reading”Sessions and Auth sessions in Pilcrow’s auth guide.
Related
Section titled “Related”Revocation races and the epoch fence covers how revoking every session of a user stays correct while a login is in flight.