CYDERCODER // PLAYBOOK
SYS.STATUS: OK 00%
> INITIALIZING...
Install this playbook for offline access
You're offline — reading cached content
WHO THIS IS FOR

Built for every stage of the builder journey

Beginners

Clear path from zero to deployed product in one afternoon. Exact AI prompts to copy. Explains the why, not just the how — all the way to production with a custom domain.

  • Build your first website end-to-end
  • Deploy with Vercel, set up Google Search Console
  • Understand what React is doing behind the scenes

Senior Devs

A reference manual for AI architecture decisions. RAG chunking, MCP, multi-agent systems, CDN caching, deployment strategies — without the fluff.

  • RAG chunking strategies, MCP protocol architecture
  • Typography scale, color theory, motion design systems
  • CDN caching, edge functions, deployment strategies
Portrait Lock Active
Please rotate your device back to Portrait orientation to read the playbook content.
Back to Dashboard

Authentication & Security Boundaries: Guarding the Gate

01. The Core Split: Authentication vs. Authorization

These two terms are constantly confused. They are different boundaries:

ConcernQuestion It AnswersExample
Authentication”Who are you?”Login form verifies email + password
Authorization”What are you allowed to do?”Admin panel checks if user has admin role

Authentication always comes first. You can’t check permissions until you know who’s asking.


02. Stateless vs. Stateful Auth: The Architecture Decision

Your first architectural decision is how the server remembers the user’s identity across requests.

Stateful Sessions (Server-Side)

User logs in
    │
    ▼
Server generates random Session ID: "abc123"
    │
    ├──▶ Stores in Redis: { "abc123": { userId: 42, role: "admin" } }
    │
    └──▶ Sends to browser as cookie: Set-Cookie: session=abc123; HttpOnly; Secure

Every subsequent request:
    Browser sends cookie: Cookie: session=abc123
    Server looks up "abc123" in Redis → finds userId 42 → "Welcome, user 42"

Pros:

  • Instant revocation — delete the session from Redis, user is logged out immediately
  • Server controls session lifetime — no expiration hacks needed
  • Simple to implement and debug

Cons:

  • Requires a shared session store (Redis) across all server instances
  • Horizontal scaling requires every server to reach the same Redis cluster
  • Redis becomes a single point of failure for auth

Stateless JWTs (Client-Side)

User logs in → Server creates JWT
HeaderHS256 / JWT
Payloadsub: 42, role: admin
SignatureHMAC-SHA256

Server sends: eyJhbGciOi... (encoded string) Browser stores: in HttpOnly cookie (NOT localStorage)

Every subsequent request: Browser sends Authorization: Bearer eyJhbGciOi... → Server decodes JWT, verifies signature, reads payload → “Welcome, user 42” (No database lookup needed).

Pros:

  • No server-side storage — token is self-contained
  • Horizontal scaling works instantly — every server has the same secret key
  • Works across domains and microservices

Cons:

  • Cannot easily revoke before expiration — stolen token = 2-hour access (or whatever the expiry is)
  • Requires token refresh infrastructure to rotate tokens
  • Payload is base64-encoded (not encrypted) — anyone can read it (but not forge it)

The Decision Matrix

FactorSessionsJWTs
RevocationInstant (delete from Redis)Difficult (need blacklist or short expiry)
ScalingRequires shared RedisScales horizontally with zero coordination
ComplexityLower to implementHigher (refresh tokens, rotation, blacklisting)
MicroservicesHarder (central session store)Natural fit (each service verifies independently)
Best ForTraditional server-rendered appsSPAs, mobile apps, microservices

Senior Move: The Hybrid Pattern

Use short-lived JWTs (15 min) paired with long-lived refresh tokens (7 days) stored in HttpOnly cookies. The JWT handles authorization on every request. When it expires, the refresh token silently rotates a new JWT without user interaction. If the refresh token is stolen, revoke it server-side and the attacker loses access.

Access Token (JWT):  15 min expiry  → Sent with every request
Refresh Token:       7 day expiry   → Stored in HttpOnly cookie, used only to get new JWTs

03. JWT Structure Deep Dive

A JWT is three base64url-encoded segments separated by dots:

eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjQyLCJyb2xlIjoiYWRtaW4iLCJleHAiOjE3MjAwMDAwMDB9.signature
│                         │                         │
├─ Header                 ├─ Payload                ├─ Signature
│  {"alg":"HS256",        │  {"sub":42,             │  HMAC-SHA256(
│   "typ":"JWT"}          │   "role":"admin",        │    header + payload,
│                         │   "exp":1720000000}     │    secret_key)
│                         │                         │
│  Algorithm used         │  User data + expiry     │  Proves token wasn't tampered with

Critical: The payload is encoded, not encrypted. Anyone can decode it and read the data. Never put sensitive information (passwords, SSN, credit card numbers) in a JWT payload. Only put what’s needed for authorization (user ID, role, permissions).

JWT Verification Flow

Tell your AI tool: “Add JWT verification middleware. When a request comes in with an Authorization header, verify the token using the JWT_SECRET environment variable. If valid, attach the user payload to the request. If expired, return 401. If invalid, return 403.”

What happens during verification:

  1. The server reads the token from the Authorization header
  2. It uses the JWT_SECRET to verify the signature hasn’t been tampered with
  3. It decodes the payload (user ID, role, expiration)
  4. If valid, the request proceeds with user context attached

04. Token Storage: The Security Battlefield

Where you store tokens determines your entire security posture. This is where most AI-generated code gets it wrong.

The Storage Comparison

StorageXSS Safe?CSRF Safe?AccessibilityVerdict
localStorageNo — JS can read itYes — not sent with requestsEasyNever for auth tokens
sessionStorageNo — JS can read itYes — not sent with requestsEasyNever for auth tokens
HttpOnly CookieYes — JS cannot touch itNo — sent with every requestLimitedBest for access tokens
Memory (JS variable)No — cleared on refreshYesTerribleNever

The Correct Pattern: HttpOnly + Secure + SameSite

Tell your AI tool: “Set authentication cookies with these security flags:

  • httpOnly: true (JavaScript cannot read the cookie)
  • secure: true (only sent over HTTPS)
  • sameSite: ‘lax’ (not sent on cross-origin requests)
  • maxAge: 15 minutes for access token
  • path: ’/’ for access token, ‘/auth/refresh’ for refresh token”

Why these flags matter:

  • HttpOnly: Prevents JavaScript from reading the cookie (blocks XSS theft)
  • Secure: Prevents cookie from being sent over insecure HTTP
  • SameSite: Prevents cookie from being sent on cross-origin requests (blocks CSRF)

Why HttpOnly Blocks XSS

Even if an attacker injects malicious JavaScript into your page:

  • document.cookie → Only shows non-sensitive cookies (HttpOnly cookies are invisible)
  • localStorage.getItem('token') → Works, but you should never store tokens there

The rule: Always store auth tokens in HttpOnly cookies, never in localStorage.


05. XSS, CSRF & CSP: The Three Walls

XSS (Cross-Site Scripting)

What it is: An attacker injects malicious JavaScript into your page that runs in other users’ browsers.

How it happens: Unsanitized user input rendered into HTML.

The Vulnerable Pattern: If a user submits <script>stealCookies()</script> as their name, and you render it directly into HTML, the script executes in every browser that views the page.

The Fix: Always sanitize user input before rendering. Use a library like DOMPurify to strip dangerous HTML tags and attributes.

Tell your AI tool: “Sanitize all user input before rendering it as HTML. Use DOMPurify to strip script tags and event handlers. Apply this to any user-generated content (comments, profile names, search queries).”

CSRF (Cross-Site Request Forgery)

What it is: A malicious site tricks a user’s browser into making requests to your API, automatically attaching their cookies.

How it happens:

<!-- Malicious site: evil-hacker.com -->
<img src="https://api.yourapp.com/account/delete" />
<!-- Browser sends cookie automatically — action executes -->

<form action="https://api.yourapp.com/transfer" method="POST">
  <input type="hidden" name="to" value="attacker-account" />
  <input type="hidden" name="amount" value="10000" />
</form>
<script>document.forms[0].submit();</script>
<!-- Browser sends cookie automatically — transfer executes -->

The Defense: SameSite Cookies + CSRF Tokens

Defense 1: SameSite Cookie Attribute

Set your session cookie to sameSite: 'lax'. This tells the browser: “Don’t send this cookie on cross-origin POST requests.” Since CSRF attacks rely on the browser automatically attaching cookies, this blocks them.

Tell your AI tool: “Set all session cookies with sameSite: ‘lax’. This prevents CSRF attacks by not sending cookies on cross-origin POST requests.”

Defense 2: Anti-CSRF Tokens

Generate a random token for each user session. Embed it in every form as a hidden field. When the form is submitted, verify the token matches what the server expects. A malicious site can’t guess this token, so their forged requests fail.

Tell your AI tool: “Implement anti-CSRF tokens. Generate a random token per session, embed it in all forms as a hidden field, and validate it on every POST/PUT/DELETE request.”

CSP (Content Security Policy)

CSP (Content Security Policy)

CSP is an HTTP header that tells the browser which sources of scripts, styles, and resources are trusted. Even if an attacker injects a <script> tag, the browser blocks it if the source isn’t in your policy.

What CSP does: Tells the browser which sources of scripts, styles, and resources are trusted. Even if an attacker injects a <script> tag, the browser blocks it if the source isn’t in your policy.

Tell your AI tool: “Add Content Security Policy headers. Allow scripts only from your own domain. Block inline scripts. Block frames embedding your site. Block forms submitting to external sites.”

The Complete Security Headers

Tell your AI tool: “Add these security headers to all responses:

  • Content-Security-Policy: restrict script sources to your domain
  • X-Content-Type-Options: nosniff (prevent MIME sniffing)
  • X-Frame-Options: DENY (prevent clickjacking)
  • Strict-Transport-Security: max-age=31536000 (force HTTPS for 1 year)
  • Referrer-Policy: strict-origin-when-cross-origin
  • Permissions-Policy: disable camera, microphone, geolocation”

Or use a library: Tell your AI tool to “Add helmet middleware for Express.js” — it sets all security headers automatically.


06. Password Hashing: Never Store Plaintext

The rule: Never store passwords in plaintext. Never MD5 them. Never SHA-256 them. Use a purpose-built password hashing algorithm with a salt.

Why Not MD5/SHA-256?

MD5 and SHA-256 are designed to be fast. That’s great for checksums, terrible for passwords. An attacker with a GPU can brute-force 100 billion MD5 hashes per second. A bcrypt hash takes 100ms to verify — making brute-force 10 million times slower.

bcrypt in Practice

Tell your AI tool: “Use bcrypt to hash passwords during registration with cost factor 12. During login, use bcrypt.compare to verify the password against the stored hash. Never store plaintext passwords.”

What bcrypt does:

  • Takes a password and adds random salt (unique per user)
  • Hashes the password with the salt using a slow algorithm (cost factor 12 = ~100ms)
  • Stores the hash (which includes the salt) in the database
  • During login, hashes the input password and compares to stored hash

The Registration Flow

Tell your AI tool: “Create a registration endpoint that:

  1. Validates password is at least 8 characters
  2. Checks if email already exists
  3. Hashes the password with bcrypt (cost factor 12)
  4. Stores email + hash in the database
  5. Returns success message”

Argon2: The Modern Alternative

Argon2 is newer than bcrypt and designed to resist GPU-based attacks. It’s the recommended choice for new projects.

Tell your AI tool: “Use Argon2id for password hashing instead of bcrypt. Configure with memoryCost: 64MB, timeCost: 3 iterations, parallelism: 4 threads.”

Senior Moves for Passwords

  1. Never reveal which field is wrong. If login fails, say “Invalid email or password” — not “Email not found” or “Wrong password.” This prevents enumeration attacks.
  2. Enforce password strength at registration. Minimum 8 characters, check against common password lists (haveibeenpwned API).
  3. Implement account lockout. After 5 failed login attempts, lock the account for 15 minutes or require CAPTCHA.
  4. Use bcrypt cost factor 12+. Lower is faster to hash but easier to brute-force. 12 is the modern standard.

07. OAuth 2.0: Social Login Without Seeing Passwords

When users click “Sign in with Google” or “Continue with GitHub,” they’re using OAuth 2.0. Your platform never sees their password — you request permission from the provider.

The Authorization Code Flow

Step 1Client
User clicks “Sign in with Google”
Step 2Client → Google
Redirect to accounts.google.com
With client_id, redirect_uri, scope=profile email
Step 3Google
User logs into Google, approves app
Step 4Google → Client
Redirect back to /callback?code=AUTH_CODE
Step 5Server → Google
Exchange code + client_secret for token
Step 6Google → Server
Access token + user profile returned
Step 7Server → DB
Create or find user in your database
Step 8Server → Client
Set session cookie — user is logged in

Implementation with Passport.js

Tell your AI tool: “Implement Google OAuth login using Passport.js. Create two routes:

  1. GET /auth/google — redirects to Google login with profile and email scopes
  2. GET /auth/google/callback — handles the callback, finds or creates user in database, sets session”

What happens:

  1. User clicks “Sign in with Google”
  2. App redirects to Google’s login page
  3. User logs into Google, approves your app
  4. Google redirects back to your callback URL with an authorization code
  5. Your server exchanges the code for an access token
  6. You use the token to get the user’s profile (name, email, Google ID)
  7. You find or create the user in your database
  8. You set a session cookie — user is logged in

Token Refresh Pattern

Tell your AI tool: “Implement silent token refresh. When the access token expires, use the refresh token to get a new one without user interaction. Store refresh tokens in the database.”

Why refresh tokens matter: Access tokens expire after ~1 hour. Without refresh tokens, users would have to re-login every hour. Refresh tokens let you get new access tokens silently.

Senior Moves for OAuth

  1. Always validate the state parameter. OAuth supports a state parameter to prevent CSRF during the handshake. Generate a random state, store it in the session, and verify it on callback.
  2. Never store the provider’s access token. You only need the user’s profile ID and email. The access token is for the provider’s API, not yours.
  3. Handle account linking. If a user signs up with email first, then later connects Google, link the Google ID to the existing account — don’t create a duplicate.
  4. Implement token refresh. Access tokens expire (usually 1 hour). Use refresh tokens to get new ones silently. Store refresh tokens in your database, not just in cookies.

08. Role-Based Access Control (RBAC)

Authentication tells you who the user is. Authorization tells you what they can do. RBAC is the standard pattern for implementing authorization.

The Schema

Tell your AI tool: “Create an RBAC (Role-Based Access Control) system with these tables:

  • users: id, email, password_hash
  • roles: id, name (admin, editor, viewer)
  • permissions: id, name (posts:create, posts:delete, users:manage)
  • role_permissions: links roles to permissions
  • user_roles: links users to roles”

The Middleware

Tell your AI tool: “Create a requirePermission middleware that checks if the authenticated user has a specific permission. If not, return 403 Forbidden. Use it on routes like: app.delete(‘/api/posts/:id’, requireAuth, requirePermission(‘posts:delete’), handler)“

The Hierarchy Pattern

Tell your AI tool: “Implement role hierarchy where admin inherits editor permissions, and editor inherits viewer permissions. A user with role ‘admin’ automatically has all permissions of lower roles.”

How it works:

  • Viewer: can read posts
  • Editor: can read, create, update posts
  • Admin: can read, create, update, delete posts + manage users

Each higher role inherits all permissions from lower roles.


Key Takeaways

ConceptMental ModelSenior Insight
Authentication vs AuthorizationWho are you? vs What can you do?Always auth first, then check permissions
Sessions vs JWTsServer remembers vs Client carriesUse hybrid: short JWT + long refresh token in HttpOnly cookie
JWT StructureHeader + Payload + SignaturePayload is encoded not encrypted — never put secrets in it
HttpOnly CookiesJavaScript cannot read themThe only safe place for auth tokens — blocks XSS theft
XSSInjected scripts read your dataSanitize all user input, use CSP headers
CSRFMalicious site uses your cookiesSameSite cookies + anti-CSRF tokens
CSPBrowser’s script allowlistBlocks inline scripts and untrusted domains
Password Hashingbcrypt with cost factor 12+Never MD5/SHA-256 — they’re too fast for brute-force
OAuth 2.0Provider authenticates, you get a tokenAlways validate state parameter, never store provider access tokens
RBACUsers → Roles → PermissionsMiddleware checks permissions, not just authentication