Vibe Coding: build real apps with AI · Episode 16. Every agent run below is real: Claude Code 2.1.322 (model claude-opus-5-5, from the run's init line) in print mode (claude -p), on 11 November 2026, in /home/ravi/projects/notes-app (one Git repository with episode 15's server/ and web/ folders). Server: Node.js v22.23.4, Express 5.3.0, better-sqlite3 13.1.1. Front end: Vite 8.3.8, React 19.3.1, @vitejs/plugin-react 6.3.0. Browser results come from Chromium driven by Playwright against the real dev servers. The password and token demos run in the SyntaxPilot online compiler (Python's hashlib and hmac). Replies are quoted exactly, shortened where marked .... Every password in these notes is a made-up demo value.
The problem: the server doesn't know who is calling
Episode 15's notes API stores notes in SQLite, but every request looks the same. Ravi saves a note; his cousin Neha, using the same API, can read it and delete it:
$ curl localhost:3000/notes
[{"id":2,"title":"Asha birthday gift",...},
{"id":1,"title":"Bank PIN hint","body":"Mum's birthday, reversed",...}]
$ curl -i -X DELETE localhost:3000/notes/2
HTTP/1.1 204 No Content
We need two things: to know who is calling, and to decide what they may do.
Authentication vs authorization (a hotel)
| A hotel | Our app |
|---|---|
| Reception checks your ID: are you really Ravi? | Authentication: proving who you are (email + password) |
| Your key card opens room 204 and no other room | Authorization: deciding what you may touch (only your notes) |
| At checkout the card stops working | Logout: the server forgets your login |
Supabase's Auth docs (fetched 11 Nov 2026) say it in one line each: "Authentication means checking that a user is who they say they are. Authorization means checking what resources a user is allowed to access."
| Status code | Meaning | When |
|---|---|---|
401 Unauthorized |
"I don't know who you are" (really: unauthenticated) | no valid login cookie |
403 Forbidden |
"I know you, and the answer is no" | logged in, not allowed |
404 Not Found |
some apps use it instead of 403 | so a stranger can't even tell the thing exists |
Storing passwords safely
The obvious way, and why it fails
The obvious design is a users table with an email and a password column; at login, find the email and compare. If the database ever leaks (a lost laptop with a backup, a careless copy, a hacked server), the thief gets every password, and because people reuse passwords, probably their email and bank logins too.
Plain text vs SHA-256 (run in the compiler)
import hashlib
users = {"ravi@example.com": "chai-at-4pm",
"neha@example.com": "masala-dosa-99",
"asha@example.com": "chai-at-4pm"}
print("A thief copies the users table:")
for email, pw in users.items():
print(" ", email, "->", pw)
print("Stored as SHA-256 instead:")
for email, pw in users.items():
print(" ", email, "->", hashlib.sha256(pw.encode()).hexdigest()[:20] + "...")
Output:
A thief copies the users table:
ravi@example.com -> chai-at-4pm
neha@example.com -> masala-dosa-99
asha@example.com -> chai-at-4pm
Stored as SHA-256 instead:
ravi@example.com -> fd86990cd81db7a0e27a...
neha@example.com -> f720841e2effe41a2d80...
asha@example.com -> fd86990cd81db7a0e27a...
A hash function turns any text into a fixed-length scramble and works only one way, like a mixer grinder: tomatoes in, chutney out, and nobody turns chutney back into tomatoes. At login you hash what the user typed and compare hashes, so the password itself is never stored.
But SHA-256 alone has two problems:
- Same password, same hash. Ravi and Asha both get
fd86990c...: crack one, crack both. Attackers also keep huge pre-computed lists of common passwords and their hashes and simply look yours up. - It's fast. It was designed to be fast (great for checking files), so an attacker can try millions of guesses per second.
Salt + a slow hash (run in the compiler)
| In a kitchen | Password storage |
|---|---|
| a mixer grinder: chutney can't become tomatoes | hash: a one-way scramble |
| each family's own masala: same tomatoes, different chutney | salt: a random string, different per user, mixed in before hashing |
| a lock that takes a second per try | slow hash: scrypt, bcrypt, Argon2id, PBKDF2 |
import hashlib, os, time
# The thief's guessing speed: hash a guess, compare, repeat.
t = time.perf_counter()
for i in range(200_000):
hashlib.sha256(b"guess-%d" % i).digest()
fast = 200_000 / (time.perf_counter() - t)
def hash_pw(pw, salt):
return hashlib.pbkdf2_hmac("sha256", pw.encode(), salt, 600_000)
t = time.perf_counter()
hash_pw("guess-1", b"0123456789abcdef")
slow = 1 / (time.perf_counter() - t)
print(f"SHA-256 guesses per second: {fast:>10,.0f}")
print(f"PBKDF2 (600,000 rounds) per s: {slow:>10,.1f}")
for email in ["ravi@example.com", "asha@example.com"]:
salt = os.urandom(16)
print(email, "salt", salt.hex()[:8], "hash", hash_pw("chai-at-4pm", salt).hex()[:12])
Output from one run (speeds depend on the machine; salts are random each run):
SHA-256 guesses per second: 2,358,733
PBKDF2 (600,000 rounds) per s: 10.7
ravi@example.com salt aa3f238e hash a3f092f32ac0
asha@example.com salt 48e23b01 hash d16ac65c401c
Millions of guesses a second with plain SHA-256, about ten with PBKDF2, on the same computer. And the same password with two random salts gives two different hashes. The salt is not secret: it's stored next to the hash. Its job is to make every hash unique.
The rules (OWASP Password Storage Cheat Sheet, fetched 11 Nov 2026)
OWASP (the Open Worldwide Application Security Project) is a non-profit that publishes free security guides. Its cheat sheet: "Fast hashing algorithms such as SHA-256 are not suitable for password storage", and a salt is "a unique, randomly generated string that is added to each password as part of the hashing process". Minimum settings it lists:
| Algorithm | Minimum setting (OWASP) |
|---|---|
| Argon2id | m=19456 (19 MiB), t=2, p=1 |
| scrypt | N=2^17 (128 MiB), r=8 (1024 bytes), p=1 |
| bcrypt | work factor 10 or more |
| PBKDF2-HMAC-SHA256 | 600,000 iterations |
Sessions vs tokens (a temple shoe stand vs a train ticket)
After login, every click is a new request. The server needs a way to remember you without asking for the password every time.
| Everyday life | After you log in |
|---|---|
| shoe-stand token No. 47; the stand keeps a register | session: the server keeps a record and gives you only a random session ID |
| you keep the token in your pocket and show it each time | cookie: a small piece of text the server asks the browser to store and send back with every request to that server |
| a stamped train ticket: everything printed on it, the ticket checker checks the stamp | signed token: the data travels with you plus a signature only the server can make. JWT (JSON Web Token) is the common format |
A signed token in 20 lines (run in the compiler)
import base64, hashlib, hmac, json
SECRET = b"placeholder-secret" # the real one lives only on the server, in .env
def sign(data):
body = base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
sig = hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()[:16]
return body + "." + sig
def check(token):
body, sig = token.split(".")
good = hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()[:16]
if not hmac.compare_digest(sig, good):
return "REJECTED: signature does not match"
return json.loads(base64.urlsafe_b64decode(body))
neha = sign({"user": 2, "exp": "2026-11-18"})
print("Neha's token:", neha)
print("Server reads:", check(neha))
body, sig = neha.split(".")
print("Anyone can decode it:", base64.urlsafe_b64decode(body).decode())
forged = base64.urlsafe_b64encode(b'{"user": 1, "exp": "2026-11-18"}').decode()
print("Forged (user 1):", check(forged + "." + sig))
Output:
Neha's token: eyJ1c2VyIjogMiwgImV4cCI6ICIyMDI2LTExLTE4In0=.0d3b07b3f08e79b7
Server reads: {'user': 2, 'exp': '2026-11-18'}
Anyone can decode it: {"user": 2, "exp": "2026-11-18"}
Forged (user 1): REJECTED: signature does not match
- HMAC = a signature made from the data plus a secret key; change one character of the data and the signature no longer matches.
- Base64 is an encoding, not encryption: anyone can read a token's data. Never put secrets in a token.
- This is the idea behind JWT, simplified (a real JWT has three parts: header, payload, signature). In real apps use a well-tested library, not your own code.
| Session (cookie with a random ID) | Signed token (JWT idea) | |
|---|---|---|
| Where the data lives | on the server | inside the token |
| Logout | delete the record: the cookie is dead at once | hard to cancel before it expires |
| Readable by the user? | no, just a random ID | yes |
| Cost | a lookup on every request | no lookup; easy across many servers |
For one server and one database, sessions are the simple, safe choice, so that's what we ask the AI for.
The AI builds accounts (agent run 1)
Prompt (in server/), allowed tools: Read, Write, Edit, Glob, Grep, npm, node, curl, ls:
Add user accounts to this notes API. People should be able to sign up with an email and a password, log in and log out. Each note belongs to the user who created it, and a user can only see, change and delete their own notes. Use sessions with a cookie. The React front end in ../web runs at http://localhost:5173 (do not change it yet). Plain JavaScript. Then test it with curl.
The real log, shortened:
Read app.js, db.js, server.js
Write db.js tables users, sessions; notes.user_id
Write auth.js signup, login, logout, me
Edit app.js every /notes query: AND user_id = ?
Bash bash curl-test.sh → "This command requires approval"
Bash node curl-test.js → all 31 checks passed
From its reply: "Passwords are hashed with Node's built-in scrypt, and sessions are stored in a new sessions table in SQLite ... Only a hash of the session token is stored, so someone with a copy of the database can't use it to log in as a user. ... Before going live: set COOKIE_SECURE=true when serving over HTTPS, and add rate limiting on login and signup. There's none yet."
server/auth.js (part, the AI's real code)
async function hashPassword(password) {
const salt = crypto.randomBytes(16);
const key = await scrypt(password, salt, 64);
return `scrypt$${salt.toString('hex')}$${key.toString('hex')}`;
}
function createSession(res, userId) {
const token = crypto.randomBytes(32).toString('base64url');
const expiresAt = Date.now() + SESSION_TTL_MS;
db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(Date.now());
db.prepare('INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (?, ?, ?)').run(hashToken(token), userId, expiresAt);
res.cookie(COOKIE_NAME, token, {
httpOnly: true,
sameSite: 'lax',
secure: COOKIE_SECURE,
path: '/',
maxAge: SESSION_TTL_MS,
});
}
- A random 16-byte salt per user, then scrypt, a slow password hash built into Node.
- The session ID is 32 random bytes. The database keeps only its SHA-256 hash. A fast hash is fine here: a random 32-byte value can't be guessed the way a human password can.
- Cookie flags (web.dev, "first-party cookie recipes", fetched 11 Nov 2026):
| Flag | What it does | Why |
|---|---|---|
HttpOnly |
page JavaScript can't read the cookie (document.cookie) |
a malicious script can't steal the session |
SameSite=Lax |
the cookie is only sent on same-site requests | other websites can't make your browser use it in the background |
Secure |
only sent over HTTPS | can't be stolen on an insecure network; switch on with COOKIE_SECURE=true when the app goes live |
Protected routes (server/app.js, part)
app.use('/notes', auth.requireAuth);
app.delete('/notes/:id', parseId, (req, res) => {
const info = db
.prepare('DELETE FROM notes WHERE id = ? AND user_id = ?')
.run(req.noteId, req.user.id);
if (info.changes === 0) return res.status(404).json({ error: 'Note not found' });
res.status(204).end();
});
function requireAuth(req, res, next) {
if (!req.user) return res.status(401).json({ error: 'Not logged in' });
next();
}
A protected route is an address you can only use when logged in. requireAuth is middleware (a function that runs before the route) acting as the guard. Authorization lives in the SQL: AND user_id = ?. Someone else's note changes zero rows, so the answer is 404.
Testing it ourselves (real)
$ curl -i localhost:3000/notes → 401 {"error":"Not logged in"}
$ curl -i -c ravi.txt -X POST localhost:3000/auth/signup -H "Content-Type: application/json" \
-d '{"email":"ravi@example.com","password":"chai-at-4pm"}'
HTTP/1.1 201 Created
Set-Cookie: sid=p5hIOogG...; Max-Age=604800; Path=/; Expires=Wed, 18 Nov 2026 19:47:47 GMT; HttpOnly; SameSite=Lax
{"id":1,"email":"ravi@example.com"}
$ curl -b ravi.txt -X POST localhost:3000/notes ... '{"title":"Bank PIN hint",...}' → 201
$ curl -b neha.txt localhost:3000/notes → []
$ curl -i -b neha.txt -X DELETE localhost:3000/notes/1
HTTP/1.1 404 Not Found {"error":"Note not found"}
password "1234" → {"errors":["password must be at least 8 characters"]}
sign up again as Ravi@Example.com → {"error":"An account with that email already exists"}
wrong password / unknown email → {"error":"Invalid email or password"} (the same message for both)
The users table holds no passwords:
1 ravi@example.com scrypt$81ed4da5b7b054798da5550ea0069a37$9c932f51a4fb...
2 neha@example.com scrypt$9b4c2b165ab77b0df0c697735335d598$27386141684e...
Logout, and a copied cookie:
$ cp ravi.txt ravi_old.txt
$ curl -i -b ravi.txt -X POST localhost:3000/auth/logout
HTTP/1.1 204 No Content
Set-Cookie: sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Lax
$ curl -i -b ravi_old.txt localhost:3000/notes
HTTP/1.1 401 Unauthorized {"error":"Not logged in"}
The server deleted the session record, so the old ID means nothing. That's the advantage of sessions.
AI weakness 1: no rate limit (an ATM keeps your card)
An ATM keeps your card after three wrong PINs. Our login had no such limit:
$ for i in $(seq 1 50); do curl ... /auth/login -d '{"email":"ravi@example.com","password":"guess-'$i'-xyz"}'; done
401 401 401 ... (50 times)
secs 2.08
$ curl -i ... /auth/login -d '{"email":"ravi@example.com","password":"chai-at-4pm"}'
HTTP/1.1 200 OK {"id":1,"email":"ravi@example.com"}
Rate limiting = allowing only a certain number of requests in a time window, then answering 429 Too Many Requests, usually with a Retry-After header (how many seconds to wait). The AI mentioned it at the end of its reply but didn't build it. Read the warnings at the end of every AI reply.
AI weakness 2: the right algorithm, a weak setting
The AI called scrypt(password, salt, 64) with no cost options, so Node's defaults apply. We checked what they are:
$ node -e "... scryptSync('asha@1234', s, 64) vs scryptSync(..., { N: 16384, r: 8, p: 1 }) ..."
default == N 16384, r 8, p 1: true
default ms/hash 29.8
N 2^17 ms/hash 345.4
Node's default cost is N=16384 = 2^14. The OWASP minimum for scrypt is N=2^17: eight times more work. Every test passes either way, which is exactly why it's easy to miss.
Prompt 2
Two problems I found by testing the accounts. 1) I sent 50 wrong passwords for ravi@example.com in 2 seconds: all 50 got 401 and nothing slowed me down or blocked me, so anyone can guess passwords as fast as they like. Add rate limiting to login and signup: after 5 failed logins for the same email (or 20 requests from one IP) in 15 minutes, answer 429 Too Many Requests with a Retry-After header. 2) auth.js calls crypto.scrypt with Node's default cost, N=16384 (2^14). The OWASP Password Storage Cheat Sheet's minimum for scrypt is N=2^17, r=8, p=1. Use those parameters for new passwords, keep old hashes working (store the parameters in the hash string), and upgrade an old hash when that user logs in. Change only what is needed, then test it.
Edit auth.js SCRYPT_PARAMS = { N: 2 ** 17, r: 8, p: 1 }, maxmem raised
Edit auth.js createLimiter(): per email (5 failures), per IP (20)
Bash node test.js email; reset; ip; upgrade → PASS x4
Trade-offs it reported (quoted, shortened): "each hash now takes about 330 ms instead of about 50 ms on this machine, and uses 128 MB while it runs ... the counts are kept in memory, so restarting the server clears them ... someone could type 5 wrong passwords for your email and block it for 15 minutes. That's the usual trade-off with this kind of rule."
The new hashing code (part):
const SCRYPT_PARAMS = { N: 2 ** 17, r: 8, p: 1 };
const LEGACY_SCRYPT_PARAMS = { N: 2 ** 14, r: 8, p: 1 };
// scrypt needs about 128 * N * r bytes. Node refuses more than 32 MB unless
// maxmem is raised, and N=2^17, r=8 needs 128 MB.
const scryptWith = (password, salt, keylen, { N, r, p }) =>
scrypt(password, salt, keylen, { N, r, p, maxmem: 256 * N * r });
Re-test (real, server restarted)
try 1: HTTP/1.1 401 Unauthorized {"error":"Invalid email or password"}
try 2: HTTP/1.1 401 Unauthorized {"error":"Invalid email or password"}
try 3: HTTP/1.1 401 Unauthorized {"error":"Invalid email or password"}
try 4: HTTP/1.1 401 Unauthorized {"error":"Invalid email or password"}
try 5: HTTP/1.1 401 Unauthorized {"error":"Invalid email or password"}
try 6: HTTP/1.1 429 Too Many Requests Retry-After: 899 {"error":"Too many attempts, try again later"}
correct password: HTTP/1.1 429 Too Many Requests Retry-After: 899
1 ravi@example.com scrypt$N=131072,r=8,p=1$a20866dbf88d2fbc...
A login screen (agent run 3)
Add accounts to this React front end. The API at http://localhost:3000 now has POST /auth/signup, POST /auth/login, POST /auth/logout and GET /auth/me, and every /notes route needs the session cookie (read ../server/auth.js and ../server/app.js, but do not change anything in ../server). Show a log in / sign up screen when nobody is logged in, then the notes of the logged-in user with their email at the top and a Log out button. Show the server's error messages. Plain JavaScript.
Write src/api.js credentials: 'include'
Write src/AuthForm.jsx log in / sign up form
Write src/App.jsx, src/Notes.jsx, Edit src/styles.css
Bash npx vite build ... → "This command requires approval"
Its reply: "I couldn't build or run them ... Open the app at http://localhost:5173, not 127.0.0.1. The server only accepts requests from that address."
The key line in src/api.js:
res = await fetch(`${BASE_URL}${path}`, {
headers: { 'Content-Type': 'application/json' },
credentials: 'include', // send and receive the session cookie
...options,
});
Without credentials: 'include', fetch doesn't send cookies to another origin (the API is on port 3000, the page on 5173). The server side needs Access-Control-Allow-Credentials: true, which run 1 added.
Browser test (Playwright, real)
- Ravi signs up, adds "Bank PIN hint":
Logged in as ravi@example.com | Log out | Notes | ... Bank PIN hint. - Neha, in a second browser profile:
Logged in as neha@example.com ... No notes yet. - In Ravi's page,
document.cookieis"": HttpOnly works. - Log out, reload: the log in screen again.
- Six wrong guesses from the form: five times
Error: Invalid email or password, thenError: Too many attempts, try again later. - Opened at
http://127.0.0.1:5173:Error: Could not reach the server. The console:
Access to fetch at 'http://localhost:3000/auth/me' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:5173' that is not equal to the supplied origin. Have the server send the header with a valid value.
localhost and 127.0.0.1 both mean this computer, but an origin is scheme + host + port, so they're different origins (episode 15).
$ git log --oneline
6150706 Log in / sign up screens, credentials: include (AI)
506e42d Rate-limit login/signup; scrypt N=2^17 (AI)
7a542ad Accounts: signup, login, logout, sessions (AI)
2d57afd React front end (episode 15)
c0ef506 Notes API with SQLite + CORS (episode 15)
Or use an auth service
An auth service is a company that runs sign up, login, password resets and sessions for you; your app calls its SDK or API. Checked on their own sites on 11 Nov 2026 (prices and limits change; check again before you choose):
| Firebase Authentication (Google) | Supabase Auth | |
|---|---|---|
| Sign-in methods | email and password, phone numbers, Google, Apple, Facebook, Twitter, GitHub, anonymous | password, magic link, one-time password (OTP), social sign-in, single sign-on (SSO) |
| No-cost tier | Spark and Blaze: 50K monthly active users at no cost, then Google Cloud pricing | Free plan ($0/month): 50,000 monthly active users |
| Paid | Blaze (pay as you go); phone auth "Billed per SMS sent", Blaze only | Pro from $25/month: 100,000 MAU, then $0.00325 per MAU |
| Limits to know | Spark: 150 password-reset emails a day (Blaze: 10,000) | "Free projects are paused after 1 week of inactivity" |
A monthly active user (MAU), in Supabase's words: "distinct users who sign in or refresh their token during the billing cycle." Supabase Auth uses JWTs and works with Row Level Security (database rules per row) for authorization. With any service, deciding who may touch which data is still your job.
Sources: firebase.google.com/docs/auth, firebase.google.com/pricing, firebase.google.com/docs/auth/limits (last updated 2026-11-10), supabase.com/docs/guides/auth, supabase.com/pricing, supabase.com/docs/guides/platform/manage-your-usage/monthly-active-users (last updated 29 Oct 2026), cheatsheetseries.owasp.org Password Storage Cheat Sheet, web.dev first-party cookie recipes.
Common mistakes (real)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
| No owner check in the query | DELETE /notes/2 → 204 No Content for anyone |
no authorization | AND user_id = ? on every query |
| Unlimited login attempts | 50 wrong passwords → 50 × 401 in 2 s |
guessing is free | rate limit: 429 Too Many Requests + Retry-After |
scrypt(password, salt, 64) with defaults |
N = 16384 (2^14), every test passes | below OWASP's minimum (N=2^17) | { N: 2**17, r: 8, p: 1 } (raise maxmem) or Argon2id |
| Plain text or SHA-256 alone | a leaked table shows every password, or millions of guesses a second | readable / too fast | random salt + slow hash |
Page opened at 127.0.0.1:5173 |
... 'Access-Control-Allow-Origin' header has a value 'http://localhost:5173' that is not equal to the supplied origin |
different origin | open the allowed origin, or allow that origin on the server |
fetch without credentials: 'include' (cross-origin) |
401 {"error":"Not logged in"} though you just logged in |
the browser didn't send the cookie | credentials: 'include' + Access-Control-Allow-Credentials: true |
Mini project
Add accounts to an app you built earlier (the to-do app from episode 10 or the expense tracker from episode 11, with a small server):
- Ask the AI for sign up, log in and log out with sessions in a cookie, and "each item belongs to its owner".
- Test as two users with curl: can user B read, change or delete user A's items?
- Send 20 wrong passwords in a loop. Is there a limit? If not, ask for one with exact numbers.
- Find the password hashing call. Compare its settings with the OWASP table above.
- Log out with a copied cookie: does the copy stop working?
- Commit after every AI change.
Practice questions
- Ravi logs in, then tries to open Neha's note. Which check stops him: authentication or authorization?
Answer
Authorization. He's authenticated (the server knows he's Ravi); the AND user_id = ? check decides he may not touch Neha's note.
- Why isn't SHA-256 alone good enough for passwords?
Answer
The same password always gives the same hash (one crack reveals everyone with that password, and pre-computed lists work), and it's fast, so attackers can try millions of guesses per second.
- Is the salt a secret? Where is it stored?
Answer
No. It's stored next to the hash (e.g. scrypt$<salt>$<hash>). Its job is to make every hash unique, not to be hidden.
- Why could the server store the session token with plain SHA-256, but not the password?
Answer
The session token is 32 random bytes, far too many possibilities to guess. Human passwords come from a small, predictable set, so they need a slow hash.
- After logout, why did the copied cookie get 401?
Answer
The server deleted the session record. The cookie only holds a random ID; without the record, it identifies nobody.
- Why is a JWT hard to "log out"?
Answer
The server doesn't keep a record; any token with a valid signature is accepted until it expires, unless you add a block list or short expiry with refresh tokens.
- What does
HttpOnlyprotect against?
Answer
Scripts running in the page (including injected malicious ones) can't read the cookie through document.cookie, so they can't steal the session ID.
Quiz
What should the users table store?
- A) the password itself
- B) SHA-256(password)
- C) a random salt + a slow hash, e.g. scrypt(password, salt)
- D) the password, encrypted with a key written in the code
Answer
C. A leaks everything; B gives the same hash for the same password and allows fast guessing; D keeps the key next to the data, so a thief who gets the code gets the key too.
Interview questions
- Explain authentication vs authorization with an example. Authentication proves identity (log in with a password); authorization decides permissions (Ravi may edit only his own notes; an admin may delete any).
- 401 vs 403? 401: not authenticated (no or invalid credentials). 403: authenticated but not allowed. Some APIs return 404 to hide that a resource exists.
- How should passwords be stored? A unique random salt per user and a slow, memory-hard hash (Argon2id, scrypt, bcrypt, or PBKDF2 with a high iteration count), with settings at least at the OWASP minimums; compare with a constant-time comparison.
- Sessions vs JWTs: trade-offs? Sessions: server-side record, instant revocation, a lookup per request. JWTs: self-contained, no lookup, readable payload, hard to revoke before expiry.
- What do HttpOnly, Secure and SameSite do? HttpOnly hides the cookie from JavaScript; Secure sends it only over HTTPS; SameSite limits sending it on cross-site requests (helps against CSRF).
- How would you stop password guessing? Rate limit per account and per IP (429 + Retry-After), slow hashing, optional CAPTCHA or MFA; be aware that per-account limits allow deliberate lockouts.
- What would you check in AI-generated auth code? Owner checks in every query, password hashing settings, rate limits, cookie flags, session expiry and logout, same error for wrong email/password, no secrets in code.
Glossary
| Term | Meaning (plain words) | Example |
|---|---|---|
| Account | a record of one user that the app remembers | ravi@example.com in the users table |
| Authentication | proving who you are | logging in with email + password |
| Authorization | deciding what you're allowed to do | only your own notes |
| Logout | ending a login so the server forgets you | deleting the session record |
| 401 Unauthorized | the server doesn't know who you are | no cookie → {"error":"Not logged in"} |
| 403 Forbidden | known, but not allowed | a normal user opening an admin page |
| Hash function | a one-way function that turns any text into a fixed-length scramble | SHA-256 |
| SHA-256 | a fast, well-known hash function | fd86990cd81db7a0e27a... |
| Salt | a random string, unique per user, mixed into the password before hashing | 16 random bytes |
| Slow (password) hash | a hash made deliberately slow and memory-hungry so guessing is expensive | scrypt, bcrypt, Argon2id, PBKDF2 |
| scrypt | a slow, memory-hard password hash built into Node and Python | scrypt$N=131072,r=8,p=1$... |
| PBKDF2 | a password hash that repeats HMAC many times | 600,000 iterations |
| bcrypt / Argon2id | other slow password hashes recommended by OWASP | Argon2id m=19 MiB, t=2, p=1 |
| OWASP | a non-profit that publishes free web security guides | the Password Storage Cheat Sheet |
| Session | the server's record of a logged-in user | a row in the sessions table |
| Session ID | the random number that points to a session | sid=p5hIOogG... |
| Cookie | a small piece of text the browser stores and sends back to the same server automatically | Set-Cookie: sid=... |
| HttpOnly | cookie flag: page JavaScript can't read it | document.cookie is "" |
| Secure | cookie flag: only sent over HTTPS | COOKIE_SECURE=true in production |
| SameSite | cookie flag: limits sending the cookie on requests started by other sites | SameSite=Lax |
| Token | a piece of data that proves something, carried by the client | a signed token |
| Signed token | data plus a signature only the server can make | body.signature |
| JWT | JSON Web Token: the common signed-token format (header.payload.signature) | used by Supabase Auth |
| HMAC | a signature made from data plus a secret key | hmac.new(SECRET, body, sha256) |
| Base64 | a way to write bytes as text; an encoding, not encryption | eyJ1c2VyIjogMn0= |
| Protected route | an address you can only use when logged in | every /notes route |
| Middleware | a function that runs before a route | requireAuth |
| Rate limiting | allowing only N requests in a time window | 5 failed logins per 15 minutes |
| 429 Too Many Requests | the status code for "slow down" | after the 5th wrong password |
| Retry-After | header saying how many seconds to wait | Retry-After: 899 |
| Brute force | trying many passwords until one works | 50 guesses in 2 s |
credentials: 'include' |
tells fetch to send cookies on cross-origin requests |
in src/api.js |
| Auth service | a company that runs sign up and login for you | Firebase Authentication, Supabase Auth |
| Monthly active user (MAU) | a distinct user who signs in (or refreshes a token) in a month | billing unit for auth services |
| SDK | a ready-made library for using a service from your code | the Firebase or Supabase client library |
| Magic link / OTP | sign-in by a link sent to your email, or a one-time code | Supabase Auth methods |
| SSO | single sign-on: one company login for many apps | "Sign in with your work account" |
Summary
- The server must know who is calling (authentication) and decide what they may do (authorization).
401= unknown,403(or404) = not allowed. - Never store plain passwords or a fast hash alone. Use a random salt per user and a slow password hash with at least OWASP's minimum settings.
- A session keeps the login record on the server; a cookie carries its random ID. A signed token (JWT) carries the data itself: readable by anyone, unforgeable without the secret, hard to revoke.
- Protect routes with middleware and check the owner in every query (
AND user_id = ?). - The AI's code was careful, but testing found two real weaknesses: no rate limit (it said so at the end of its reply) and a hashing cost below OWASP's minimum. Give it the evidence and exact numbers, then test again.
- Auth services (Firebase Authentication, Supabase Auth) can run login for you; check their current limits, and authorization stays your job.
- Next: episode 17, a real-time chat app with WebSockets.