Triển Khai Xác Thực

Authentication là tính năng mà mọi dự án đều cần và là tính năng gây ra nhiều sự cố bảo mật nhất khi được triển khai cẩu thả. Trong các dự án outsourcing, auth thường là deliverable đầu tiên mà khách hàng đánh giá — và là thứ họ sẽ đổ lỗi cho bạn nếu có sự cố sáu tháng sau. Sun Agent Kit triển khai toàn bộ auth stack — đăng ký, đăng nhập, xác minh email, đặt lại mật khẩu, OAuth provider, và 2FA tùy chọn — theo chuẩn OWASP, kèm test, trong một phần nhỏ thời gian.

Tổng Quan

Mục tiêu: Triển khai hệ thống authentication hoàn chỉnh, bảo mật production từ đầu hoặc mở rộng một hệ thống hiện có
Thời gian: 20–40 phút (so với 4–8 giờ thủ công)
Agents sử dụng: planner, implementer, tester, reviewer
Commands: /sk:plan, /sk:cook, /sk:test, /sk:code-review

Yêu Cầu Trước Khi Bắt Đầu

  • Sun Agent Kit đã cài đặt với scaffold dự án đang hoạt động
  • Database migrations tooling đã cấu hình (Prisma, Drizzle, hoặc raw SQL — hãy chỉ định cái nào)
  • Email sending infrastructure có sẵn hoặc đã mock cho development (SendGrid, Resend, nodemailer)
  • Các environment variable đã cấu hình: JWT_SECRET, REFRESH_TOKEN_SECRET, DATABASE_URL
  • Danh sách rõ ràng các tính năng auth nào trong phạm vi delivery này

Quy Trình Từng Bước

Bước 1: Lên Kế Hoạch Hệ Thống Auth

/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."

Điều gì xảy ra: Agent thực hiện:

  1. Phân tích codebase để tìm code liên quan đến auth, model, và middleware hiện có
  2. Thiết kế chiến lược lưu trữ token, email verification flow, và cách tiếp cận OAuth integration
  3. Viết kế hoạch triển khai theo giai đoạn được lưu vào plans/ với các ghi chú bảo mật được đánh dấu để review

Bước 2: Triển Khai Auth Cốt Lõi (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"

Điều gì xảy ra: Agent thực hiện:

  1. Cập nhật database schema với bảng refresh token và áp dụng migration
  2. Triển khai auth service với các operation register, login, token refresh, và logout
  3. Tạo route handler cho tất cả core auth endpoint với status code phù hợp
  4. Thêm auth middleware để validate access token và gắn user vào request

Bước 3: Thêm Xác Minh Email và Đặt Lại Mật Khẩu

/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"

Điều gì xảy ra: Agent thực hiện:

  1. Thêm bảng verification và password reset token với expiry và single-use tracking
  2. Tạo email template với HTML và plain-text fallback
  3. Triển khai route handler cho verify-email, resend-verification, forgot-password, và reset-password

Bước 4: Thêm 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)"

Điều gì xảy ra: Agent thực hiện:

  1. Cấu hình Passport.js với Google OAuth strategy và validate các env var cần thiết khi khởi động
  2. Triển khai OAuth redirect và callback handler
  3. Xử lý account linking khi Google email trùng với tài khoản đã đăng ký hiện có

Bước 5: Thêm 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"

Điều gì xảy ra: Agent thực hiện:

  1. Mở rộng user schema với encrypted TOTP secret, enabled flag, và hashed backup code
  2. Triển khai endpoint setup, verify-setup, và disable
  3. Cập nhật login flow để trả về temporary token khi 2FA được bật, và thêm 2FA validation endpoint

Bước 6: Test và 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)"

Điều gì xảy ra: Agent thực hiện:

  1. Viết test file bao gồm mỗi tính năng auth với happy path và security boundary case
  2. Chạy full test suite — tất cả test pass
  3. Review các vấn đề bảo mật phổ biến: timing attack vector, email enumeration, token rotation, và dữ liệu nhạy cảm trong JWT payload

Ví Dụ Thực Tế: Ứng Dụng E-Commerce Cần Hệ Thống Auth Đầy Đủ

Tình huống: Một khách hàng e-commerce mới cần hệ thống auth hoàn chỉnh cho platform của họ: người mua đăng ký bằng email, social login với Google là bắt buộc để tăng mobile conversion, và admin user cần 2FA như một hard requirement. Backend là Node.js/Express/PostgreSQL. Deadline Sprint 1 là thứ Sáu tuần sau.

Sáng thứ Hai — hệ thống auth đầy đủ trong một session:

# 1. Hiểu những gì đã có trước khi viết bất cứ thứ gì
/sk:scout "check what auth-related code, middleware, or database tables already exist in this project"

# 2. Lên kế hoạch dựa trên yêu cầu chính xác của khách hàng
/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 trước — unblock các công việc sprint khác
/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 — khách hàng nói đây là bắt buộc cho 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 — bắt buộc cho admin user
/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 trước khi bất cứ thứ gì được ship
/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 các phát hiện bảo mật
/sk:cook "apply security fixes from plans/reports/review-auth.md"

# 8. Test tất cả mọi thứ
/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"

Kết quả: Đến chiều thứ Ba, hệ thống auth đã có mặt trên staging. Phần còn lại của Sprint 1 (product catalog, cart) tiến hành song song trên cùng codebase mà không bị auth làm blocker. Security review sạch. Mobile team của khách hàng có thể bắt đầu build với Google OAuth endpoint ngay lập tức.

Checklist Bảo Mật (Theo Chuẩn OWASP)

Chạy /sk:code-review "OWASP auth security checklist" với implementation của bạn để xác minh:

Kiểm soátNhững gì cần kiểm tra
Password hashingbcrypt/argon2 với cost factor ≥ 10
Timing attackscrypto.timingSafeEqual hoặc bcrypt.compare — không có early return
Token entropyRefresh token là ≥ 256 bits dữ liệu ngẫu nhiên
Token storageRefresh token được hash trong DB, không bao giờ lưu dạng thô
Email enumerationForgot-password trả về 200 bất kể email có tồn tại hay không
Brute forceRate limiting trên login và forgot-password endpoint
Token revocationLogout thu hồi refresh token; đặt lại mật khẩu thu hồi tất cả session
JWT claimsChỉ user_id trong payload — không có role, email, hoặc PII trong token
Secret validationApp từ chối start nếu JWT_SECRET yếu hoặc chưa set
2FA backup codesOne-use, hashed, có thể tạo lại

So Sánh Thời Gian

Tính năng AuthThủ côngVới Sun Agent Kit
Registration + login + JWT1–2 giờ5–10 phút
Token refresh + revocation30–60 phútđã có
Email verification30–60 phút5–10 phút
Password reset30–60 phútđã có
Google OAuth1–2 giờ5–10 phút
TOTP 2FA2–3 giờ5–10 phút
Security review + test1–2 giờ10–15 phút
Tổng4–8 giờ20–40 phút

Các Thực Hành Tốt Nhất

1. Luôn chạy /sk:code-review với phạm vi OWASP rõ ràng ✅

Review chung phát hiện vấn đề code quality. Security review cần một khung cụ thể: /sk:code-review "OWASP auth security review — timing attacks, enumeration, brute force, secret handling". Agent áp dụng đúng checklist.

2. Chỉ định TTL token rõ ràng trong prompt kế hoạch ✅

“Short-lived access token” là mơ hồ. Hãy nói với agent TTL chính xác mà khách hàng đã đồng ý: “access tokens 15 minutes, refresh tokens 7 days, remember-me refresh tokens 30 days.” Các khách hàng khác nhau có yêu cầu bảo mật khác nhau.

3. Triển khai email verification trước OAuth ✅

OAuth user đã được provider xác minh sẵn, nhưng user đăng ký bằng email cần verification trước khi có thể truy cập các resource được bảo vệ. Build verification flow trước — OAuth đến sau.

4. Lưu refresh token dưới dạng plaintext trong database ❌

Nếu database của bạn bị xâm phạm, refresh token plaintext có thể sử dụng ngay lập tức. Luôn lưu hash và chỉ truyền raw token đến client một lần duy nhất. /sk:cook xử lý điều này theo mặc định, nhưng hãy xác minh trong output review.

5. Dùng cùng một secret cho access token và refresh token ❌

Nếu access token secret bị lộ (ví dụ trong log), nó không nên cũng làm lộ refresh token. Dùng các environment variable riêng biệt JWT_SECRETREFRESH_TOKEN_SECRET.

Xử Lý Sự Cố

Giải pháp: Kiểm tra environment variable APP_URL của bạn được set đúng URL public. Nếu link chứa localhost, user click từ điện thoại sẽ thấy link bị lỗi. Chạy /sk:fix --quick "email verification links use localhost instead of the APP_URL env variable".

Vấn đề: Google OAuth callback trả về trang trắng hoặc 404

Giải pháp: URL callback đăng ký trong Google Cloud Console phải khớp chính xác với cái trong code của bạn. Chạy /sk:ask "what is the exact OAuth callback URL configured in the Passport.js Google strategy?" và xác minh nó khớp với cài đặt Google Cloud Console của bạn.

Vấn đề: /sk:test viết test pass vì chúng mock bcrypt

Giải pháp: Chỉ định trong prompt test: “do not mock bcrypt or JWT — test with real hashing and real token signing, use a separate test database”. Integration test mock crypto cho sự tự tin giả tạo.

Vấn đề: TOTP code bị từ chối dù authenticator app hiển thị đúng code

Giải pháp: TOTP nhạy cảm với thời gian. Kiểm tra đồng hồ hệ thống server đã được đồng bộ (NTP). Chạy /sk:fix --quick "TOTP verification is rejecting valid codes — add a 1-step (30s) time tolerance window to speakeasy.totp.verify".

Bước Tiếp Theo


Điểm mấu chốt: Auth làm sai là một khoản nợ tồn tại lâu hơn dự án — /sk:cook theo một kế hoạch đã được security review build toàn bộ stack trong 40 phút và tạo ra code sẽ không làm bạn xấu hổ trong một pentest sáu tháng sau.