Skip to content

@plinthjs/session ​

Plinth's session layer. A swappable store contract with an in-memory implementation, a Session value object (attribute bag + flash + CSRF token), a manager that loads/ages/saves sessions, and cookie + CSRF helpers. Everything that observes time or entropy is injected, so flash lifetimes, garbage collection, and id rotation are deterministic in tests.

Usage ​

ts
import { arraySession, parseCookies, serializeCookie, verifyToken } from '@plinthjs/session'

// A manager + array store sharing one injected clock (production omits `now`).
let at = Date.now()
const { manager, store } = arraySession({ now: () => at })

// Start a request: load (or mint) the session and age flash data once.
const session = await manager.start(/* id? */)

session.put('user_id', 7)
session.flash('status', 'Saved!') // visible this request and the next
const csrf = session.token() // lazily minted, unguessable

await manager.save(session) // persist the bag back to the store

// Next request: re-start with the same id.
const next = await manager.start(session.getId())
next.get('status') // 'Saved!' - still here for one more request

Flash lifetime ​

Flash data follows the conventional _flash.old / _flash.new convention:

  • flash(key, value) - available this request and the next.
  • now(key, value) - available this request only.
  • reflash() / keep(keys) - extend currently-old flash for one more request.

manager.start() calls session.ageFlashData() exactly once per load, promoting new -> old and sweeping away keys that have already lived their two requests.

Cookies & CSRF ​

ts
const cookies = parseCookies(req.headers.cookie ?? '')
const header = serializeCookie('plinth_session', session.getId(), {
  path: '/',
  httpOnly: true,
  sameSite: 'Lax',
  maxAge: 7200,
})

verifyToken(submittedToken, session.token()) // constant-time comparison

Optional signed cookies (sign / unsign) prepend an HMAC-SHA256 tag and reject tampering with a timing-safe compare.

Stores ​

SessionStore is the handler seam (read / write / destroy / gc). ArraySessionStore is the in-memory default; gc(maxLifetimeSeconds) prunes entries untouched for longer than the lifetime under the injected clock.

Released under the MIT License.