Lightweight in-memory session manager for Supranim core.
This module provides the minimal building blocks that were missing from core: session creation, lookup, renewal, expiry, CSRF tokens and flash notifications — without requiring a database or the out-of-tree supranim-session provider.
For persistent, multi-process or DB-backed sessions (users table, remember-me, 2FA, email confirmation) use supranim-session. This core store is process-local and suitable for single-instance apps, tests and as a foundation for custom providers.
Thread safety: all SessionStore mutations are guarded by pkg/threading/rwlock. Read paths use readWith, writes use writeWith, matching the convention in supranim-session.
Types
Session = ref object id*: string userId*: Option[string] payload*: Table[string, string] created*: DateTime lastAccess*: DateTime csrfSecret*: string csrfTokens*: Table[string, string] flash*: Table[string, seq[string]]
- A single user session.
SessionConfig = object cookieName*: string expiration*: Duration cookieDomain*: string cookiePath*: string httpOnly*: bool sameSite*: SameSite secure*: CookieSecureMode trustProxy*: bool
- Code-first configuration. No config file required.
SessionStore = ref object config*: SessionConfig sessions*: Table[string, Session]
- Process-local session container.
Procs
proc buildSessionCookie(req: var Request; id: string; store: SessionStore): Cookie {. ...raises: [KeyError], tags: [], forbids: [].}
- Builds a session cookie honoring the store config and the request's effective scheme (Safari-safe Secure handling).
proc cleanupExpired(store: SessionStore): int {....raises: [KeyError], tags: [TimeEffect], forbids: [].}
- Removes all expired sessions. Returns the number removed. Call periodically (timer, background thread, or per-request sampling).
proc createSession(store: SessionStore; userId = none(string)): Session {. ...raises: [OSError, OSError], tags: [TimeEffect], forbids: [].}
- Creates, registers and returns a new session with a unique id. Retries on NanoID collision.
proc defaultSessionConfig(): SessionConfig {....raises: [], tags: [], forbids: [].}
- Sensible defaults: ssid cookie, 720h expiry, Safari-safe secureAuto, host-only domain.
proc defaultStoreInit(): SessionStore {....gcsafe, raises: [], tags: [], forbids: [].}
- Returns the process-global default store, creating it on first use. Lock-guarded; the gcsafe blocks assert manual safety for the shared global (same pattern as supranim-session's singleton).
proc destroySession(store: SessionStore; id: string) {....raises: [], tags: [], forbids: [].}
- Deletes a session by id. No-op when missing.
proc destroySession(store: SessionStore; s: Session) {....raises: [], tags: [], forbids: [].}
- Deletes a session object.
proc destroySessionWithHeaders(req: var Request; res: var Response; store: SessionStore; s: Session) {. ...raises: [KeyError], tags: [TimeEffect], forbids: [].}
- Destroys the session and emits an expired cookie so the browser drops it.
proc getNotifications(s: Session; path: string): seq[string] {. ...raises: [KeyError], tags: [], forbids: [].}
- Returns and clears flash messages for path.
proc getPayloadValue(s: Session; key: string): Option[string] {. ...raises: [KeyError], tags: [], forbids: [].}
- Returns a payload value, if present.
proc getSession(store: SessionStore; id: string): Session {....raises: [KeyError], tags: [TimeEffect], forbids: [].}
- Returns the session by id, or nil when missing or expired. Expired sessions are removed lazily on access.
proc getSessionFromRequest(req: var Request): Session {....raises: [KeyError], tags: [TimeEffect], forbids: [].}
- Overload using the default store.
proc getSessionFromRequest(req: var Request; store: SessionStore): Session {. ...raises: [KeyError], tags: [TimeEffect], forbids: [].}
- Returns the current session, or nil when absent/invalid.
proc getSessionIdFromRequest(req: var Request): Option[string] {. ...raises: [KeyError], tags: [TimeEffect], forbids: [].}
- Overload using the process-global default store's cookie name.
proc getSessionIdFromRequest(req: var Request; store: SessionStore): Option[ string] {....raises: [KeyError], tags: [TimeEffect], forbids: [].}
- Reads the session id from the request cookie.
proc hasSession(store: SessionStore; id: string): bool {....raises: [KeyError], tags: [TimeEffect], forbids: [].}
- True when a non-expired session exists for id.
proc initSessionWithHeaders(req: var Request; res: var Response): Session {. ...raises: [KeyError, OSError], tags: [TimeEffect], forbids: [].}
- Overload using the default store.
proc initSessionWithHeaders(req: var Request; res: var Response; store: SessionStore): Session {. ...raises: [KeyError, OSError], tags: [TimeEffect], forbids: [].}
- Creates a session and emits a set-cookie header. Clears any stale cookie first so the browser drops it.
proc isExpired(s: Session; store: SessionStore): bool {....raises: [], tags: [TimeEffect], forbids: [].}
- True when now - created exceeds the configured expiration.
proc newSessionStore(config = defaultSessionConfig()): SessionStore {. ...raises: [], tags: [], forbids: [].}
- Creates an empty SessionStore with the given config.
proc renewSessionId(store: SessionStore; s: Session): string {. ...raises: [OSError], tags: [], forbids: [].}
- Regenerates the session id (call after login to prevent fixation). Returns the new id.
proc renewSessionWithHeaders(req: var Request; res: var Response; store: SessionStore; s: Session) {. ...raises: [OSError, KeyError], tags: [], forbids: [].}
- Renews the session id and emits the replacement cookie.
proc sessionCookieName(store: SessionStore): string {....raises: [], tags: [], forbids: [].}
- Resolves the cookie name, falling back to ssid.
proc sessionCount(store: SessionStore): int {....raises: [], tags: [], forbids: [].}
- Number of sessions currently held (including expired not yet GC'd).
proc setDefaultSessionStore(store: SessionStore) {....gcsafe, raises: [], tags: [], forbids: [].}
- Replaces the process-global default store (useful in tests).
proc setPayloadValue(s: Session; key, value: string) {....raises: [], tags: [], forbids: [].}
- Stores an arbitrary string value in the session payload.
proc touchSession(store: SessionStore; s: Session) {....raises: [], tags: [TimeEffect], forbids: [].}
- Refreshes lastAccess without changing the id.
proc validateCSRF(s: Session; formId, clientToken: string): bool {. ...raises: [KeyError], tags: [], forbids: [].}
- Validates then consumes a CSRF token (single-use).
Templates
template withSession(body: untyped) {.dirty.}
- Overload using the default store.
template withSession(store: SessionStore; body: untyped) {.dirty.}
- Ensures a userSession: Session is in scope. Creates one (with set-cookie) when the request has none. Requires req: var Request and res: var Response in scope.