Example 1
Example 1
import { createApplication } from '@setu-ts/kernel'; import { RuntimePlugin } from '@setu-ts/runtime'; import { getSession, SessionPlugin } from '@setu-ts/session-plugin'; const app = createApplication({ plugins: [RuntimePlugin(), SessionPlugin({ secret: mySecret, csrf: {} })], }); app.router.get('/me', (ctx) => { const session = getSession(ctx); return ctx.response.json({ userId: session.get<string>('userId') ?? null }); });
ISessionStore over any ICacheStore.
-
destroy(id: string): Promise<boolean>
Removes a stored session.
-
isHealthy(): Promise<boolean>
Reports the store's reachability, for the plugin's health indicator.
-
read(id: string): Promise<SessionData | null>
Reads a stored session payload.
-
write(): Promise<void>id: string,data: SessionData,ttlMs: number
Writes a session payload, replacing any existing one.
Thrown by the form-CSRF verifier when the submitted token is absent or does not match the session's token.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
Map-backed ISessionStore.
-
close(): Promise<void>
Releases resources held by the store (timers, connections).
-
destroy(id: string): Promise<boolean>
Removes a stored session.
-
isHealthy(): Promise<boolean>
Reports the store's reachability, for the plugin's health indicator.
-
read(id: string): Promise<SessionData | null>
Reads a stored session payload.
-
size(): number
How many entries are currently held, expired ones included.
-
sweep(): void
Drops every expired entry. Exposed so the sweep is directly testable.
-
write(): Promise<void>id: string,data: SessionData,ttlMs: number
Writes a session payload, replacing any existing one.
Thrown by getSession(ctx) / SessionService.from(ctx) when the session
middleware did not run for the request.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
Thrown during register() when no usable session secret could be resolved,
or when the resolved secret is too short.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
Loads, exposes, and commits the per-request session.
-
close(): Promise<void>
Releases store resources; called from the plugin's
onClose. -
commit(): Promise<void>ctx: IRequestContext,session: Session
Writes the session back, when it needs writing.
-
from(ctx: IRequestContext): ISession
Returns the session the middleware loaded for this request.
-
fromHeaders(headers: Headers): Promise<SessionView | null>
Opens a session from a
Headersobject alone — the headers-only read for non-HTTP entry points that have no request context to commit onto (a WebSocketonOpenhandler, an auth strategy reading a cookie). -
keyCount(): number
How many keys can open a cookie, for the health indicator.
-
load(ctx: IRequestContext): Promise<Session>
Loads the session for a request, falling back to a fresh one whenever the cookie is absent, malformed, tampered with, expired, idle, or (on the store strategy) no longer present server-side.
-
mode(): string
How the cookie is protected, for the health indicator.
-
storeHealth(): Promise<boolean | undefined>
Reports store reachability for the health indicator.
-
strategy(): "cookie" | "store"
Which strategy is in effect, for the health indicator.
Thrown when a committed session cookie would exceed the configured byte budget, which browsers enforce at roughly 4 KB per cookie.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
Builds the form-CSRF middleware.
Renders this session's CSRF token as a hidden HTML form field.
Returns this session's CSRF token, minting and storing one on first call.
Returns the session the middleware loaded for this request.
Builds the session middleware.
Registers cookie-backed sessions under CAPABILITIES.SESSION, with optional
session-backed form CSRF.
Verifies the request's CSRF token against the session's, throwing on any mismatch.
Options for CacheSessionStore.
-
keyPrefix: string
Key namespace inside the cache. Default
'session:'.
Form-CSRF options.
-
exclude: readonly (string | RegExp)[]
Request paths exempt from form-CSRF verification, matched by exact string equality or
RegExp.test. Omitted means no path is exempt. -
fieldName: string
Form field carrying the token. Default
'_csrf'. -
headerName: string
Header that may carry the token instead of a form field, for
fetch-based posts and formultipart/form-databodies this package does not parse. Default'x-csrf-token'; header reading cannot be disabled — a synchroniser token that cannot be presented is not a security control. -
ignoreMethods: readonly string[]
Methods that skip verification. Default
['GET', 'HEAD', 'OPTIONS'].
Runtime capabilities the store needs.
-
clearInterval: (handle: TimerHandle) => void
Interval canceller, from
IRuntimeServices.clearInterval. -
now: () => number
Wall-clock milliseconds, from
IRuntimeServices.now. -
setInterval: () => TimerHandlefn: () => void,ms: number
Interval scheduler, from
IRuntimeServices.setInterval. -
sweepIntervalMs: number
Milliseconds between expiry sweeps. Default
60000.
Options for SessionPlugin.
-
cookie: SessionCookieOptions
Cookie attributes.
-
csrf: CsrfFormOptions
Enable session-backed form CSRF. Omitted means no CSRF middleware is registered; an empty object enables it with defaults.
-
idleTimeoutMs: number
Expire a session that has received no requests for this long, independently of
maxAge. Omitted by default (no idle check). -
maxAge: number
Absolute session lifetime in seconds. Default
7200(2 hours). -
maxCookieBytes: number
Byte budget for the serialized cookie. Default
4096. Exceeding it throws rather than emitting a cookie the browser would silently drop. -
mode: SessionMode
How the cookie is protected.
'encrypt'(default) hides the payload with AES-256-GCM;'sign'leaves it readable base64url JSON under an HMAC-SHA256 signature, which suits the store strategy where the cookie holds only an opaque id. -
rolling: boolean
Re-issue the cookie on every response, extending the expiry so an active user is not logged out mid-session. Default
false, which commits only when the session actually changed. -
secret: string | readonly string[]
The session secret, or an ordered list of secrets for rotation: index 0 signs/encrypts new cookies while every entry can still open existing ones, so rotating a secret does not log everybody out.
-
secretName: string
Name looked up in the secret manager and the environment. Default
'SESSION_SECRET'. -
store: "memory" | "cache" | ISessionStore
Where the payload lives. Omitted (default) keeps it in the cookie itself, which needs no infrastructure. Set to
'memory','cache', or a customISessionStoreto keep only an opaque id in the cookie and the payload server-side, which makes immediate revocation possible. -
tenantBinding: boolean
Bind a session to the tenant it was minted under. Default
true: when a tenant is resolved for the request, the tenant id is sealed into the session on commit, and a later request presenting that session under a different tenant is refused with403before the handler runs. When either the session or the request carries no tenant, nothing is compared, so an application without tenancy is inert.falserestores the previous behaviour (no seal, no compare).
Runtime capabilities the service needs, injected for testability.
-
now: () => number
Wall-clock milliseconds, from
IRuntimeServices.now. -
randomBytes: (length: number) => Uint8Array
Random bytes, from
IRuntimeServices.randomBytes. -
subtle: SubtleCrypto
Web Crypto, from
IRuntimeServices.subtle. -
uuid: () => string
Identifier source, from
IRuntimeServices.uuid.
How a session cookie is protected.
Reserved session key holding the CSRF token.
Usage
import * as Cookie_backed_sessions_and_session_backed_form_CSRF_for_Setu_TS___Registers_an__ISessionService__under__CAPABILITIES_SESSION___The_default_is_a_self_contained_encrypted_cookie___AES_256_GCM_under_an_HKDF_SHA256_derived_key__entirely_through__runtime_subtle___so_there_is_no_npm_dependency_and_it_runs_on_Cloudflare_Workers__Setting__store__moves_the_payload_server_side_and_leaves_only_an_opaque_id_in_the_cookie__which_makes_immediate_revocation_possible___The_form_CSRF_middleware_here_is_the_synchronizer_token_strategy__which_is_a_different_mechanism_from__http_security_plugin__s_stateless_Origin_Referer_check_rather_than_the_same_feature_configured_differently__A_progressive_enhancement___Form___post_cannot_set_a_custom_header__so_it_can_satisfy_this_and_not_that__running_both_together_is_intended__ from "session-plugin/src/index.ts";