Back to Security Academy
AUTHENTICATION SESSIONADVANCED9 min readCWE-384ZX-SESS-001ZX-COOKIE-001

Cryptographically Secure Session Management with Token Hashing

Why raw session tokens must never be persisted in databases, and how to implement SHA-256 session token hashing with __Host- cookie prefixes.

Why AI coding tools introduce this vulnerability

AI generators often store raw session tokens in the database: INSERT INTO sessions (token, user_id) VALUES ($1, $2). If the database is compromised via SQLi or an exposed backup, attackers gain instant, persistent session access to all user accounts without needing passwords.

Technical Vulnerability Analysis

Just like passwords must be hashed with bcrypt or Argon2, session tokens should be hashed (SHA-256) before persistence. If a database dump is leaked, attackers cannot reconstruct the active raw session cookies.

VULNERABLE IMPLEMENTATION (DO NOT USE)
// AI-Generated Session Creator (VULNERABLE)
export async function createSession(userId: string) {
  const rawToken = crypto.randomUUID();
  // Storing plaintext token in DB!
  await db.query('INSERT INTO sessions (token, user_id) VALUES ($1, $2)', [rawToken, userId]);
  return rawToken;
}
Plaintext tokens in database expose all active sessions upon database leak.

Remediation Playbook & Code Fixes

SECURE HARDENED PATCH (src/core/auth/session.ts)
import crypto from 'crypto';

export async function createHashedSession(userId: string): Promise<string> {
  // 1. Generate 256-bit CSPRNG raw token
  const rawToken = crypto.randomBytes(32).toString('hex');

  // 2. Hash token with SHA-256 before database insertion
  const tokenHash = crypto.createHash('sha256').update(rawToken).digest('hex');

  await db.query(
    'INSERT INTO sessions (token_hash, user_id, expires_at) VALUES ($1, $2, NOW() + INTERVAL \'14 days\')',
    [tokenHash, userId]
  );

  // 3. Return only raw token to client in __Host- cookie
  return rawToken;
}

Why this fix works: Only token_hash is persisted. Reconstruct hash upon request validation.

Local CLI Verification Commands

Verify session cookie includes __Host- prefix, HttpOnly, Secure, and SameSite.
curl -sI https://example.com/api/auth/login | grep -i 'set-cookie'
Expected result: __Host-zerivex_session=...; HttpOnly; Secure; SameSite=Lax; Path=/

Pre-Deployment Self-Audit Checklist

Knowledge Check: Verify Your Understanding

What is the primary architectural cause of cryptographically secure session management with token hashing?

Test your website for ZX-SESS-001

Run our 14 deterministic engines to inspect your live deployment.

Launch scan for this flaw