# Session 2026-04-21 15:30 — Phase 5 Prep (Production infra + docs + refresh token)

**Dev:** Claude (Opus 4.7)
**Duration:** ~1h
**Base commit:** `fe7ad8e`

## Làm được

### Chunk O — BE production infra

- Packages: `Serilog.Sinks.File`, `Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore` (RateLimiting built-in .NET 10)
- `appsettings.Production.json` template với placeholders `__SET_VIA_SECRETS__`, `AllowedOrigins`, Serilog File sink rolling daily retention 30d, RateLimit config
- `appsettings.Development.json` + `appsettings.json` thêm Serilog `WriteTo.Console`
- `Program.cs` rewrite:
  - Serilog `.ReadFrom.Configuration` (thay hardcode Console) → prod file rolling, dev console
  - Rate limiter: policy `auth-login` (5/min/IP) + global (300/min/IP)
  - Health checks: `/health/live` liveness + `/health/ready` DB probe
  - HSTS production (1 year)
  - CORS origins từ config (`AllowedOrigins`)
- `AuthController.Login` gắn `[EnableRateLimiting("auth-login")]`

### Chunk P — Deploy scripts + CI/CD template

- `scripts/deploy-iis.ps1` — stop pool → backup → clean+extract artifact → start pool → health check loop với rollback instruction nếu fail
- `scripts/backup-sql.ps1` — daily BACKUP DATABASE với COMPRESSION+CHECKSUM + retention 30 ngày .bak
- `.gitea/workflows/deploy.yml` — 4 job: build BE (Windows) + build 2 FE (Ubuntu) + deploy IIS qua WinRM PSSession. Pin Node `.nvmrc` (gotcha #5). Secrets IIS_HOST/USER/PASSWORD/JWT_SECRET/DB_CONNECTION

### Chunk Q — Runbook docs (4 file mới trong `docs/guides/`)

- `deployment-iis.md` — prerequisites + setup lần đầu (app pool, site, HTTPS, secrets) + deploy hàng ngày + troubleshooting + SPA web.config sample
- `cicd.md` — pipeline overview, secrets, runner setup Windows+Ubuntu, branch strategy, build optimizations, common issues
- `security-checklist.md` — OWASP top 10 2021 mapping với status hiện tại + pre go-live checklist + incident response
- `runbook.md` — daily ops (health/logs), restart/rollback, DB backup/restore/migration revert, user management, monitoring, deployment checklist

### Chunk R — FE refresh token auto

- `fe-admin/src/lib/api.ts` + `fe-user/src/lib/api.ts` rewrite:
  - Thêm `REFRESH_KEY` localStorage key
  - Axios response interceptor: 401 → thử POST `/auth/refresh` → retry request gốc với token mới
  - **Queue pattern** để nhiều request song song chỉ 1 refresh call chạy, các request khác chờ token mới
  - Skip retry cho `/auth/login` và `/auth/refresh` (tránh infinite loop)
  - `_retry` flag trên original config để không retry 2 lần
- `contexts/AuthContext.tsx` (cả 2 app): lưu+xóa `REFRESH_KEY` trong login/logout

## E2E verified

```bash
# Health check
GET /health/live  → 200 Healthy
GET /health/ready → 200 Healthy (DB probe pass)

# Rate limit
POST /api/auth/login x 7 lần /phút/IP
  → #1-5: HTTP 400 (invalid cred) — còn trong limit
  → #6-7: HTTP 429 Too Many Requests ✅

# TS check fe-admin + fe-user → pass
# Build BE → pass
```

## Docs consolidation

- Docs: 4 file guides MỚI (`deployment-iis`, `cicd`, `security-checklist`, `runbook`)
- `Program.cs`: rewrite với prod infra
- `appsettings.Production.json` MỚI
- `appsettings.json` + `Development.json` update Serilog Console sink
- `scripts/deploy-iis.ps1` + `backup-sql.ps1` MỚI
- `.gitea/workflows/deploy.yml` MỚI
- fe-admin + fe-user: `lib/api.ts` refresh token queue pattern, `contexts/AuthContext.tsx` update

## Bug gặp + fix

| Bug | Fix |
|---|---|
| Write Program.cs không persist lần đầu (Dropbox?) | Verify qua grep → re-Write full file |
| `Microsoft.AspNetCore.RateLimiting` không có stable package | Dùng built-in `.AddRateLimiter()` ASP.NET Core 7+ không cần package |

## Handoff cho session tiếp theo

### Phase 5 còn cần (với Gitea URL)

- [ ] Setup Gitea remote + push code
- [ ] Enable Gitea Actions runner (Windows + Ubuntu)
- [ ] Set 5 secrets trong Gitea
- [ ] Test CI/CD workflow lần đầu trên staging
- [ ] Windows Server setup IIS theo `deployment-iis.md`
- [ ] HTTPS cert (win-acme)
- [ ] SQL Server prod + backup task schedule
- [ ] Smoke test end-to-end prod
- [ ] UAT 1 tuần với 2-3 user thật

### Security hardening (Phase 5.1)

- [ ] Security headers middleware (X-Content-Type-Options, X-Frame-Options, CSP)
- [ ] Account lockout (Identity options — đã có spec ở security-checklist.md)
- [ ] Password policy production min 12 chars
- [ ] IDOR check trong ContractsController (user không xem được HĐ không liên quan)
- [ ] Dependencies scan vào CI (`dotnet list package --vulnerable`, `npm audit`)

### Quick wins

- [ ] FE Users management + Roles CRUD (để test permission với non-admin user)
- [ ] Filter Inbox theo phase FE
- [ ] Dashboard user-specific

### Blocker

- ⏳ **Gitea URL** — user sẽ cấp

## Thông số cumulative

| | Phase 3 | Phase 4 | **Phase 5 prep** |
|---|---:|---:|---:|
| BE LOC | ~2700 | ~3100 | **~3300** (thêm rate limit + health check wiring) |
| DB tables | 19 | 19 | 19 |
| API endpoints | ~31 | ~33 | **~35** (+ /health/live + /health/ready) |
| FE pages | 14 | 16 | 16 |
| Scripts PS | 2 (parse_forms, parse_workflow) | +1 (convert-doc) | **+3** (deploy-iis, backup-sql, existing) = 6 |
| CI/CD workflow | 0 | 0 | **1** (.gitea/workflows/deploy.yml) |
| Docs files | 26 | 30 | **35** (+4 guides + session log) |
| Commits | 6 | 7 | **8** (sắp) |
