Implement Authentication
Authentication is the feature every project needs and the one that causes the most security incidents when implemented carelessly. On outsourcing projects, auth is often the first deliverable the client evaluates — and the one they’ll blame you for if it goes wrong six months later. Sun Agent Kit implements the full auth stack — registration, login, email verification, password reset, OAuth providers, and optional 2FA — against OWASP standards, with tests, in a fraction of the time.
Overview
Goal: Implement a complete, production-secure authentication system from scratch or extend an existing one
Time: 20–40 minutes (vs 4–8 hours manual)
Agents used: planner, implementer, tester, reviewer
Commands: /sk:plan, /sk:cook, /sk:test, /sk:code-review
Prerequisites
- Sun Agent Kit installed with a working project scaffold
- Database migrations tooling configured (Prisma, Drizzle, or raw SQL — specify which)
- Email sending infrastructure available or mocked for development (SendGrid, Resend, nodemailer)
- Environment variables configured:
JWT_SECRET,REFRESH_TOKEN_SECRET,DATABASE_URL - A clear list of which auth features are in scope for this delivery
Step-by-Step Workflow
Step 1: Plan the Auth System
/sk:plan "implement full authentication system: email/password registration with email verification, JWT access tokens (15min TTL) + refresh tokens (7 days), password reset via email, Google OAuth, optional TOTP 2FA. Stack: Node.js/Express, PostgreSQL, Prisma."
What happens: The agent:
- Analyzes the codebase for existing auth-related code, models, and middleware
- Designs the token storage strategy, email verification flow, and OAuth integration approach
- Writes a phased implementation plan saved to
plans/with security notes flagged for review
Step 2: Implement Core Auth (Register, Login, JWT)
/sk:cook "implement Step 1 from plans/phase-auth-system.md: user registration, login, JWT access token + refresh token pair, token refresh endpoint, and logout with refresh token revocation"
What happens: The agent:
- Updates the database schema with a refresh tokens table and applies the migration
- Implements the auth service with register, login, token refresh, and logout operations
- Creates route handlers for all core auth endpoints with appropriate status codes
- Adds auth middleware that validates access tokens and attaches the user to the request
Step 3: Add Email Verification and Password Reset
/sk:cook "implement Step 2 from plans/phase-auth-system.md: email verification on registration, resend verification endpoint, password reset request + confirmation with time-limited signed tokens"
What happens: The agent:
- Adds verification and password reset token tables with expiry and single-use tracking
- Creates email templates with HTML and plain-text fallbacks
- Implements route handlers for verify-email, resend-verification, forgot-password, and reset-password
Step 4: Add Google OAuth
/sk:cook "implement Step 3 from plans/phase-auth-system.md: Google OAuth 2.0 login and registration using Passport.js, handle both new users (create account) and existing users (link or login)"
What happens: The agent:
- Configures Passport.js with the Google OAuth strategy and validates required env vars at startup
- Implements the OAuth redirect and callback handlers
- Handles account linking when the Google email matches an existing registered account
Step 5: Add TOTP Two-Factor Authentication
/sk:cook "implement Step 4 from plans/phase-auth-system.md: optional TOTP 2FA — setup flow with QR code, verification, backup codes, and enforcing 2FA on login when enabled"
What happens: The agent:
- Extends the user schema with encrypted TOTP secret, enabled flag, and hashed backup codes
- Implements setup, verify-setup, and disable endpoints
- Updates the login flow to return a temporary token when 2FA is enabled, and adds the 2FA validation endpoint
Step 6: Test and Security Review
/sk:test "comprehensive auth test suite: registration, login, token refresh, logout, email verification, password reset, OAuth callback, 2FA setup and login flow, and all security boundaries (expired tokens, revoked tokens, token reuse)"
What happens: The agent:
- Writes test files covering each auth feature with happy path and security boundary cases
- Runs the full test suite — all tests pass
- Reviews for common security issues: timing attack vectors, email enumeration, token rotation, and sensitive data in JWT payload
Complete Example: E-Commerce App Needs Full Auth System
Scenario: A new e-commerce client needs a complete auth system for their platform: shoppers register with email, social login with Google is required for mobile conversion, and admin users need 2FA as a hard requirement. The backend is Node.js/Express/PostgreSQL. Sprint 1 deadline is next Friday.
Monday morning — full auth system in one session:
# 1. Understand what exists before writing anything
/sk:scout "check what auth-related code, middleware, or database tables already exist in this project"
# 2. Plan based on the client's exact requirements
/sk:plan "auth system for e-commerce: email registration with verification, JWT (15min) + refresh (30 days for 'remember me', 24h otherwise), password reset, Google OAuth (required), TOTP 2FA (required for admin role users, optional for shoppers). PostgreSQL + Prisma."
# 3. Core auth first — unblock other sprint work
/sk:cook "implement core auth per plans/phase-auth-system.md steps 1-2: registration, login, token pair, refresh, logout, email verification, password reset"
# 4. Google OAuth — client said this is required for mobile
/sk:cook "implement Google OAuth per plans/phase-auth-system.md step 3 — handle the case where a Google email matches an existing email-registered account"
# 5. 2FA — required for admin users
/sk:cook "implement TOTP 2FA per plans/phase-auth-system.md step 4 — enforce 2FA for users with role=admin, make it optional for shoppers"
# 6. Security review before anything ships
/sk:code-review "security review of the full auth implementation — check against OWASP Authentication Cheat Sheet: timing attacks, enumeration, brute force, token storage, secret handling"
# 7. Fix any security findings
/sk:cook "apply security fixes from plans/reports/review-auth.md"
# 8. Test everything
/sk:test "full auth test suite — focus on security boundaries: token reuse attacks, expired token handling, 2FA bypass attempts, OAuth failure paths"
# 9. Commit
/sk:git cm "feat: complete authentication system — JWT, email verification, password reset, Google OAuth, TOTP 2FA"
Result: By Tuesday afternoon, the auth system is in staging. The rest of Sprint 1 (product catalog, cart) proceeds in parallel on the same codebase without auth being a blocker. Security review is clean. The client’s mobile team can immediately start building against the Google OAuth endpoint.
Security Checklist (OWASP-Aligned)
Run /sk:code-review "OWASP auth security checklist" against your implementation to verify:
| Control | What to Check |
|---|---|
| Password hashing | bcrypt/argon2 with cost factor ≥ 10 |
| Timing attacks | crypto.timingSafeEqual or bcrypt.compare — no early returns |
| Token entropy | Refresh tokens are ≥ 256 bits of random data |
| Token storage | Refresh tokens hashed in DB, never stored raw |
| Email enumeration | Forgot-password returns 200 regardless of whether email exists |
| Brute force | Rate limiting on login and forgot-password endpoints |
| Token revocation | Logout revokes refresh token; password reset revokes all sessions |
| JWT claims | Only user_id in payload — no role, email, or PII in the token |
| Secret validation | App refuses to start if JWT_SECRET is weak or unset |
| 2FA backup codes | One-use, hashed, regeneratable |
Time Comparison
| Auth Feature | Manual | With Sun Agent Kit |
|---|---|---|
| Registration + login + JWT | 1–2 hours | 5–10 minutes |
| Token refresh + revocation | 30–60 min | included |
| Email verification | 30–60 min | 5–10 minutes |
| Password reset | 30–60 min | included |
| Google OAuth | 1–2 hours | 5–10 minutes |
| TOTP 2FA | 2–3 hours | 5–10 minutes |
| Security review + tests | 1–2 hours | 10–15 minutes |
| Total | 4–8 hours | 20–40 minutes |
Best Practices
1. Always run /sk:code-review with an explicit OWASP scope ✅
Generic review catches code quality issues. Security review requires a specific frame: /sk:code-review "OWASP auth security review — timing attacks, enumeration, brute force, secret handling". The agent applies the right checklist.
2. Specify token TTLs explicitly in the plan prompt ✅
“Short-lived access tokens” is ambiguous. Tell the agent the exact TTLs the client agreed to: “access tokens 15 minutes, refresh tokens 7 days, remember-me refresh tokens 30 days.” Different clients have different security requirements.
3. Implement email verification before OAuth ✅
OAuth users are pre-verified by the provider, but email-registered users need verification before they can access protected resources. Build the verification flow first — OAuth comes after.
4. Storing refresh tokens in plaintext in the database ❌
If your database is compromised, plaintext refresh tokens are immediately usable. Always store the hash and transmit the raw token to the client only once. /sk:cook handles this by default, but verify in the review output.
5. Using the same secret for access tokens and refresh tokens ❌
If the access token secret is ever exposed (e.g., in a log), it shouldn’t also compromise refresh tokens. Use separate JWT_SECRET and REFRESH_TOKEN_SECRET environment variables.
Troubleshooting
Problem: Email verification links expire before users click them
Solution: Check your APP_URL environment variable is set to the correct public URL. If links contain localhost, users clicking from their phone see a broken link. Run /sk:fix --quick "email verification links use localhost instead of the APP_URL env variable".
Problem: Google OAuth callback returns a blank page or 404
Solution: The callback URL registered in Google Cloud Console must exactly match the one in your code. Run /sk:ask "what is the exact OAuth callback URL configured in the Passport.js Google strategy?" and verify it matches your Google Cloud Console settings.
Problem: /sk:test writes tests that pass because they mock bcrypt
Solution: Specify in the test prompt: “do not mock bcrypt or JWT — test with real hashing and real token signing, use a separate test database”. Integration tests that mock crypto give false confidence.
Problem: TOTP codes are rejected even when the authenticator app shows the right code
Solution: TOTP is time-sensitive. Check that your server’s system clock is synchronized (NTP). Run /sk:fix --quick "TOTP verification is rejecting valid codes — add a 1-step (30s) time tolerance window to speakeasy.totp.verify".
Next Steps
- Build a REST API — protect your API endpoints with the auth middleware you just built
- Add a New Feature — extend the auth system with SSO, magic links, or session management UI
- Fix Bugs Systematically — for when production reveals edge cases in the auth flow
Key takeaway: Auth done wrong is a liability that outlives the project — /sk:cook against a security-reviewed plan builds the full stack in 40 minutes and produces code that won’t embarrass you in a pentest six months later.