Skip to content
Back to CurriculumLesson 04 of 30
cryptography-passwordsIntermediate

Secure Account Recovery, Password Reset Tokens & Defense Against Takeovers

Password reset is the most targeted account takeover vector. A secure reset pipeline uses short-lived (15 min) single-use hashed tokens, invalidates all existing active sessions upon password change, and notifies the original email address.

Interactive Visual Concept ExplainerStep-by-Step Educational Simulation
Visual Step-by-Step Concept Explainercryptography-passwords
Secure Account Recovery, Password Reset Tokens & Defense Against Takeovers
Steps:
Timing-Safe Enumeration DefenseOWASP ASVS
Request: POST /auth/forgot-password { email }
"If an account exists, a reset link was dispatched."
Response time identical whether email exists or not. Zero information leakage.
Global Session InvalidationZero-Trust Kill Switch
Action: User submits new password
DB Execution: DELETE FROM sessions WHERE user_id = 42
Sessions active
Step 1 of 6
Auto-stepping (1x)

Step 1: User requests password reset for an email address.

Security Guarantee: Reset tokens must have a strict 15-minute expiration and be strictly single-use.
Why This Architectural Concept Exists

Users inevitably forget passwords. Without secure recovery, users are permanently locked out. However, flawed reset mechanisms (predictable tokens, lack of expiration, or failure to revoke old sessions) allow attackers to hijack accounts permanently.

Intuitive Mental Model

The Burner Vault Key: When you lose your safe key, the bank issues a temporary one-time key that melts and destroys itself after 15 minutes. Once you open the safe and change the combination, all previously existing duplicate keys are rendered physically inert.

Architectural System TopologyProtocol Diagram
[ Attacker / User ] ──(POST /forgot-password)──► [ CosmosApp API ]
                                                  │
                                  ┌───────────────┴───────────────┐
                                  ▼                               ▼
                      [ Email Found? ]                     [ Anti-Enumeration: ]
                        │                                  "If your email exists,
                        ├─► Yes: Generate Token (15m TTL)  a link was sent."
                        │        Hash with SHA-256
                        │        Send Email
                        └─► No:  Do nothing (same timing)
                                  │
                                  ▼ (User clicks /reset-password?token=...)
                      [ Verify Token Hash & Check TTL ]
                                  │
                                  ▼ (Valid Token)
                      [ Update Password with Argon2id ]
                      [ DESTROY all active sessions in Redis ]
                      [ Send Security Notification Email ]
CosmosApp Production Milestone

Bob forgets his CosmosApp password. He requests a reset. CosmosApp returns 'If your account exists, a link was sent' regardless of whether the email is registered. Bob receives an email with an expiring token (15 mins). Upon submitting his new password, CosmosApp updates Bob's Argon2id hash and immediately revokes all of Bob's active sessions in Redis, kicking out any potential intruder.

Step-by-Step Execution Sequence
01

Step 1: User requests password reset for an email address.

02

Step 2: Server responds with uniform HTTP 200 response to prevent email harvesting.

03

Step 3: If user exists, server generates a cryptographically secure 32-byte reset token, hashes it with SHA-256, and stores the hash with a 15-minute expiration.

04

Step 4: User receives email and clicks the reset link.

05

Step 5: Server validates token hash, ensures current time < expires_at, and ensures token has not been used.

06

Step 6: Server updates the password hash, marks token as consumed, and revokes all active session IDs in Redis.

Production Architecture Blueprint
// CosmosApp Password Reset Session Revocation:
export async function executePasswordReset(rawToken: string, newPasswordPlaintext: string) {
  const tokenHash = crypto.createHash('sha256').update(rawToken).digest('hex');
  const record = await db.query('SELECT * FROM reset_tokens WHERE token_hash = $1', [tokenHash]);

  if (!record || record.expires_at < new Date() || record.used) {
    throw new Error('Invalid or expired reset token');
  }

  // 1. Hash new password:
  const newHash = await hashPassword(newPasswordPlaintext);

  // 2. Mark token used:
  await db.query('UPDATE reset_tokens SET used = true WHERE id = $1', [record.id]);
  await db.query('UPDATE users SET password_hash = $1 WHERE id = $2', [newHash, record.user_id]);

  // 3. CRITICAL: Revoke all active Redis sessions for this user!
  await redis.del(`user_sessions:${record.user_id}`);
  await sendSecurityEmail(record.user_id, 'Your password was recently updated.');
}
Common Architectural Misconceptions
  • ✕Allowing password reset links to remain valid for 24 hours is standard (Reset tokens grant direct account takeover and should expire in 15 minutes).
  • ✕Keeping existing sessions logged in after a password reset is fine (If an attacker had stolen a session cookie, failing to revoke sessions lets them maintain access).

Key Architectural Takeaways

  • ✓Reset tokens must have a strict 15-minute expiration and be strictly single-use.
  • ✓Always invalidate every active user session and refresh token family when a password is reset.
  • ✓Never reveal whether an email exists in the database during password reset requests.
Common Architectural Pitfall

Leaving active sessions valid after a password reset, allowing an attacker with a hijacked session to remain authenticated.

Production Best Practice Fix

Destroy all active session IDs and refresh tokens across Redis and database tables immediately upon password change.

Interactive Knowledge Check

What critical security operation must be performed alongside updating the password hash during a password reset?