Core Architecture
Understand Himayah's request lifecycle, session design, CSRF protection, and how plugins compose together.

Core Architecture
Himayah (حماية — Arabic for protection) is built around three core ideas: portability (runs anywhere Web Crypto is available), composability (plugins register their own endpoints), and schema ownership (you control your database structure entirely).
This guide details the complete internals of the Himayah authentication engine, complete with visual flowcharts and sequence diagrams.
System Topology & Package Layout
Himayah is structured as a monorepo containing decoupled, single-purpose packages under the @himayah/ namespace. This design allows developers to only install what they use, keeping runtime sizes minimal and preventing dependency creep.
Request Execution Pipeline
Every incoming HTTP request flows through a deterministic pipeline that validates incoming security tokens, resolves routes, executes plugins, and issues formatted cookies:
The handleRequest Function
auth.handleRequest(req: Request): Promise<Response> is the single entry point for all auth routes. It:
- Builds an internal context from the incoming
Request - Verifies CSRF token for mutating methods (
POST,PUT,DELETE,PATCH) - Routes to the matching plugin endpoint handler
- Returns a standard
Response
Session Design
Stateless JWE Sessions (default)
By default, Himayah uses stateless sessions via JSON Web Encryption (JWE). The session pipeline has two distinct steps:
Why both?
- PBKDF2 is needed because
AUTH_SECRETis typically a human-readable string — not a cryptographically uniform 32-byte key. PBKDF2 stretches it into one safely, with 100,000 iterations making brute-force impractical. - AES-256-GCM is the actual symmetric cipher that encrypts the session payload. It's authenticated (provides integrity) and is the gold standard for symmetric encryption.
In other words: PBKDF2 creates the key, AES-256-GCM uses the key to encrypt. They're two layers of the same pipeline.
Shortcut for maximum performance: if AUTH_SECRET is already a 32-byte hex or base64 key, Himayah detects this and skips PBKDF2 entirely, importing it directly via crypto.subtle.importKey. Use this on latency-sensitive Edge runtimes:
Session Payload
The decrypted session contains the following shape:
Stateful Database Sessions (for revocation)
When you need to immediately revoke sessions (e.g., account bans, forced sign-out on password change), switch to the database-backed session store:
Here is a visual comparison between stateless JWE session validation and the stateful database revocation pipeline under the hood:
With this store:
- Each session is persisted to the
sessionstable with an expiry timestamp auth.getSession(req)validates the session and checks the database — invalidated sessions immediately return{ ok: false }auth.signOut(req)deletes the database row as well as the cookie
Stateful sessions add one database query per authenticated request. Use JWE sessions when you don't need immediate revocation.
Double-Submit CSRF Protection
All state-mutating requests (POST, PUT, DELETE, PATCH) are protected by double-submit cookie CSRF validation:
- On the first page load, Himayah sets a non-
HttpOnlycookiehimayah.csrf=<random-token> - Your client must echo that token in the
x-csrf-tokenrequest header - Himayah compares the cookie value and the header value using constant-time comparison (prevents timing oracle attacks)
The @himayah/client handles CSRF token extraction and injection automatically.
Timing-Safe Comparison
All token comparisons in Himayah use a bitwise XOR-based timingSafeEqual that runs in constant time regardless of where the strings diverge:
This is applied to: CSRF token checks, OAuth state verification, and password hash comparisons.
Adapter Segment Architecture
Himayah defines decoupled, segment-specific database contracts. Instead of a massive monolithic interface, adapters map individual tables directly to independent segments, providing modular flexibility and letting you omit tables you don't use.
Plugin Composition
Plugins are plain TypeScript functions that return a HimayahPlugin descriptor:
When createAuth is called with plugins: [passwordPlugin(), oauthPlugin()], it:
- Calls each plugin with the shared context (adapter, sessionStore, config)
- Merges all endpoint registrations into a flat route map
- Returns the configured
authobject
Example of what passwordPlugin registers:
| HTTP Endpoint | Method | Description |
|---|---|---|
/api/auth/password/sign-up | POST | Create a new user account |
/api/auth/password/sign-in | POST | Authenticate and create session |
/api/auth/password/change-password | POST | Update password (requires current session) |
Platform Portability
Himayah uses only the Web Crypto API (globalThis.crypto.subtle), which is universally available:
Cookie Security Defaults
| Cookie | HttpOnly | Secure | SameSite | Purpose |
|---|---|---|---|---|
himayah.sid | ✅ | ✅ | Lax | Encrypted session token |
himayah.csrf | ❌ | ✅ | Strict | CSRF double-submit token (readable by JS) |
HttpOnlyon the session cookie prevents XSS-based session theft.Secureforces cookies over TLS in production.SameSite=Laxallows same-site navigations while blocking cross-site POSTs.- The CSRF cookie is intentionally not
HttpOnlyso the browser client can read it.