# Phase 9 — QA + Security + Regression

วันที่: 2026-02-24

## Scope ที่ทำแล้ว

1) **Security hardening (backend)**
- เพิ่ม security headers ฝั่ง server (เปิดได้/ปิดได้ผ่าน env):
  - `X-Content-Type-Options: nosniff`
  - `X-Frame-Options: SAMEORIGIN`
  - `Referrer-Policy: strict-origin-when-cross-origin`
  - `Permissions-Policy: geolocation=(), microphone=(), camera=()`
- เพิ่ม CSRF origin check สำหรับ endpoint ที่แก้ไขข้อมูล:
  - `/auth/change-password`
  - `/auth/logout`
  - `/auth/users*`
  - `/auth/token-profiles*`
- เพิ่ม brute-force protection ให้ `/auth/login`:
  - จำกัดจำนวนครั้งภายใน window
  - block ชั่วคราวเมื่อเกิน threshold
  - metric ติดตาม success/fail/blocked

2) **Regression automation**
- เพิ่ม test ใหม่:
  - `tests/http-security.test.ts`
    - allowed origin policy
    - origin/referer resolution
    - login rate limiter block/unblock/reset

3) **Config/ops**
- เพิ่ม env ที่เกี่ยวข้องกับ security:
  - `SECURITY_HEADERS_ENABLED`
  - `CSRF_ORIGIN_CHECK_ENABLED`
  - `CSRF_ALLOWED_ORIGINS`
  - `LOGIN_RATE_LIMIT_MAX_ATTEMPTS`
  - `LOGIN_RATE_LIMIT_WINDOW_SECONDS`
  - `LOGIN_RATE_LIMIT_BLOCK_SECONDS`

## QA Checklist (รอบนี้)

- [x] Token profile CRUD ยังทำงานได้ตามเดิม
- [x] Dashboard/live accounts flow ยังผ่าน test เดิม
- [x] Cache/performance test (phase 8) ยังผ่าน
- [x] Security guard unit tests ผ่าน
- [x] ไม่มีการเปิดเผย token ในข้อความ error ใหม่

## คำสั่ง regression suite

```bash
npx vitest run \
  tests/http-security.test.ts \
  tests/live-cache.test.ts \
  tests/live-dashboard.test.ts \
  tests/token-security.test.ts \
  tests/token-profiles.test.ts \
  tests/db-plan.test.ts
```

## Residual risk / ข้อที่ต้องเฝ้าระวัง

- CSRF guard ใช้ Origin/Referer policy; ถ้า deploy หลัง reverse proxy ต้องตั้งค่า host/proto ให้ถูกต้อง
- ถ้ามี trusted frontend หลายโดเมน ต้องเพิ่มใน `CSRF_ALLOWED_ORIGINS`
- ปัจจุบันยังไม่มี endpoint-level integration test ผ่าน `fastify.inject()` (ยังเน้น module-level regression)
