Examples

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 });
});

Classes

c
CacheSessionStore(
cache: ICacheStore,
options?: CacheSessionStoreOptions
)

ISessionStore over any ICacheStore.

c
CsrfTokenMismatchError(reason: string)

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 instanceof across realms.

c
MemorySessionStore(deps: MemorySessionStoreDeps)

Map-backed ISessionStore.

c
SessionMiddlewareMissingError()

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 instanceof across realms.

c
SessionSecretMissingError(message: string)

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 instanceof across realms.

c
SessionService(
config: ResolvedSessionConfig,
ring: KeyRing,
deps: SessionServiceDeps,
store?: ISessionStore
)

Loads, exposes, and commits the per-request session.

c
SessionTooLargeError(
actual: number,
limit: number
)

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 instanceof across realms.

Functions

f
csrfTokenField(
ctx: IRequestContext,
options?: Pick<CsrfFormOptions, "fieldName">
): string

Renders this session's CSRF token as a hidden HTML form field.

f
getCsrfToken(ctx: IRequestContext): string

Returns this session's CSRF token, minting and storing one on first call.

f
getSession(ctx: IRequestContext): ISession

Returns the session the middleware loaded for this request.

f
SessionPlugin(options?: SessionPluginOptions): IPlugin

Registers cookie-backed sessions under CAPABILITIES.SESSION, with optional session-backed form CSRF.

f
verifyCsrfToken(
ctx: IRequestContext,
options?: CsrfFormOptions
): Promise<void>

Verifies the request's CSRF token against the session's, throwing on any mismatch.

Interfaces

I
CacheSessionStoreOptions

Options for CacheSessionStore.

I
CsrfFormOptions

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 for multipart/form-data bodies 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'].

I
MemorySessionStoreDeps

Runtime capabilities the store needs.

I
SessionCookieOptions

Cookie attributes for the session cookie.

I
SessionPluginOptions

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 custom ISessionStore to 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 with 403 before the handler runs. When either the session or the request carries no tenant, nothing is compared, so an application without tenancy is inert. false restores the previous behaviour (no seal, no compare).

I
SessionServiceDeps

Runtime capabilities the service needs, injected for testability.

Type Aliases

T
SessionMode = "encrypt" | "sign"

How a session cookie is protected.

Variables

v
CSRF_SESSION_KEY: "__csrf"

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";