docs(progress): log Phase 0 Cleanup & Foundation session

Captures the state of the Phase 0 work so the next session can resume
without re-discovering what was already done.

Section 14 covers:
- Status of all 7 Phase 0 task branches (1-5 done, 6 in progress, 7 pending)
- Summary of what each completed task changed and why
- The 5 critical OIDC startup bugs that were fixed during the e2e test
- The one remaining blocker: host PostgreSQL 16 service is competing with
  the docker container for port 5432, so /health reports database=false
- Three options to resolve the port conflict and a recommendation
- Step-by-step instructions for the next session to resume from section 14.9
- Useful shell commands for the next operator

The 5 OIDC bugs that were fixed (server.ts, oidcRoutes.ts, oidcService.ts)
are NOT trivial and were all sitting in the codebase from earlier phases —
the server could not start at all without them. They are now in their own
commit on the test/e2e-docker-migrate-verify branch.
Co-authored-by: 's avatarCursor <cursoragent@cursor.com>
parent 2b1aba07
...@@ -544,3 +544,226 @@ git checkout backup/develop-pre-phase3-restore -- . ...@@ -544,3 +544,226 @@ git checkout backup/develop-pre-phase3-restore -- .
# Hoặc restore một file # Hoặc restore một file
git checkout backup/develop-pre-phase3-restore -- src/oidc/oidcInteractionsController.ts git checkout backup/develop-pre-phase3-restore -- src/oidc/oidcInteractionsController.ts
``` ```
---
## 14. PHASE 0 — Cleanup & Foundation (2026-06-18, session mới)
> **Context**: Sau session email-verification, user muốn refactor lớn: cleanup,
> chuẩn hoá flow, đặc biệt là **DB topology** (1 main + 1 backup + MongoDB
> audit). Đã tạo `PLANS.md` 600+ dòng làm roadmap. Tổng cộng 7 task branches.
### 14.1 Trạng thái 7 task branches (TASK 1-5 DONE, 6 IN PROGRESS, 7 PENDING)
| # | Branch | Commit | Trạng thái | Push |
|---|--------|--------|-----------|------|
| 1 | `feat/env-fix-port-credentials` | d72c35a | ✅ DONE | ✅ origin |
| 2 | `feat/docker-split-postgres` | 67f4d44 | ✅ DONE | ✅ origin |
| 3 | `fix/contracts-add-verify-email-schemas` | 9d7895e | ✅ DONE | ✅ origin |
| 4 | `fix/server-remove-auto-load-pools` | ad7fda5 | ✅ DONE | ✅ origin |
| 5 | `chore/cleanup-untracked-files` | 42aeeef | ✅ DONE | ✅ origin |
| 6 | `test/e2e-docker-migrate-verify` | 6eb4ba5 + OIDC init fix | 🟡 IN PROGRESS (chưa xong) | ✅ origin |
| 7 | docs(progress+run) | — | ⚪ PENDING | — |
> **Lưu ý workflow**: Tất cả branch đang đợi maintainer merge. Hiện tại KHÔNG
> merge vào develop — chờ user (lead) review. Khi session mới bắt đầu, bắt
> đầu bằng `git fetch && git branch -v` để xem trạng thái branches.
### 14.2 Task 1: feat(env) — DONE
**File**: `.env` (không commit, gitignore), `.env.example`
**Thay đổi**:
- `DB_CONNECTION_STRING`: `5433/sso` → `5432/sso` (đồng bộ với Docker mới)
- `SSO_LOGIN_BACKUP_URL`: giữ nguyên `5433/sso_backup` (backup DB port)
- Thêm block `DB_READ_*` (host=localhost, port=5433, user, password, name)
- Comment `PROJECT_A/B_DATABASE_URL`: `5433` → `5432` (chỉ 1 main instance)
> **Quan trọng**: User đã tự sửa `DB_NAME=vietprodev_sso` → `sso` ngay trước
> session này, nhưng session trước KHÔNG thấy. Khi quay lại, nếu thấy
> `DB_NAME=sso` thì OK; nếu là `vietprodev_sso` thì phải sửa lại.
### 14.3 Task 2: feat(docker) — DONE
**File**: `docker-compose.yml`
**Thay đổi**:
- Service `postgres` → `postgres-main` (port 5432, image `postgres:17-alpine`)
- Thêm service `postgres-backup` (port 5433, cùng image)
- 3 `depends_on: postgres:` → `postgres-main:` (app-dev, app-staging, app-prod)
- Volume `postgres_data` → `postgres_main_data` + `postgres_backup_data`
- Container names: `sso-postgres-main`, `sso-postgres-backup`
- Env var trong backup: dùng `DB_READ_USER/DB_READ_PASSWORD/DB_READ_NAME`
(fallback về `DB_USER/DB_PASSWORD/DB_NAME` nếu không set)
### 14.4 Task 3: fix(contracts) — DONE
**File**: `src/contracts/auth/schema.ts`
**Thêm 6 export**:
- `VerifyEmailQuerySchema` = `{ token: string }` (1-512 chars)
- `VerifyEmailResponseDataSchema` + type `VerifyEmailResponseData`
- `VerifyEmailResponseSchema` (envelope)
- `ResendVerificationBodySchema` = `{ email }`
- `ResendVerificationResponseDataSchema` + type `ResendVerificationResponseData`
- `ResendVerificationResponseSchema` (envelope)
> `expires_at` trong response nullable (trả null khi user unknown hoặc
> already verified, tránh email enumeration).
### 14.5 Task 4: fix(server) — DONE
**File**: `src/server.ts`
**Thay đổi**:
- Xoá 2 calls `await MultiPoolService.autoLoadPools()` (line 451, 626)
- Thay bằng comment `// TODO(phase3):` giải thích Phase 3 sẽ implement lại
- `tsc --noEmit` exit 0 sau fix
### 14.6 Task 5: chore(cleanup) — DONE
**Xoá 5 files** (5 obsolete untracked):
- `db_check.js` — pg debug script hardcode port 5433 + bekind schema
- `secrets/` — JWK key files (sẽ gen lại lúc dev, đã xoá theo security rule)
- `sql/migrations/038-drop-bekind-facility-tables.sql` — drop bảng dư thừa
- `src/oidc/jwksService.ts` — duplicate với logic đã có trong `oidcService.ts`
- `src/oidc/views/check-email.hbs` — không reference trong code
**Add 12 files** (cần cho admin API + Phase 3):
- 3 migrations: 037 (project_db_connections), 039 (oidc grants indexes),
040 (email_verified_at) — file 040 đã có sẵn tracked
- 2 contracts/admin/* (CreateClientSchema, UpdateClientSchema, etc.)
- 2 contracts/oidc/* (TokenResponseSchema, paths)
- 7 controllers/admin/* (clients CRUD, db-connections CRUD+test, health)
- 1 middlewares/admin-api-key.ts
- 1 models/Client.ts (Sequelize model)
- 1 providers/ClientProvider.ts
- 2 services/admin/* (AdminDbConnectionService, ProjectUserReaderService)
- 2 types/* (oidc-provider.d.ts, express.d.ts)
**Kết quả**: `tsc --noEmit` exit 0. Working tree nearly clean (chỉ còn
`guidelines/` và `postman/` đã tracked).
### 14.7 Task 6: test(e2e) — IN PROGRESS, 4 BUGS FIXED
**Docker verification**:
- Container `sso-postgres` (PID 3468) → port 5432 → DB: `sso` + `sso_backup`
- Container `sso-postgres-backup` (PID mới) → port 5433 → DB: `sso_backup` only
- Container `sso-redis`, `sso-mongo`, `sso-minio` đều healthy
**Bug #1 fixed (commit 6eb4ba5)**: `oidcRoutes.ts` gọi `OidcService.callback()`
ở module-level → crash server ngay khi start vì `OidcService.getInstance()`
chưa được `initialize()`. Fix: wrap thành lazy arrow function.
**Bug #2 fixed (commit OIDC init)**: `oidcService.ts` dùng
`const OidcProvider = require('oidc-provider')` → nhận module object, không
phải class. `oidc-provider@9` publish dạng ESM-compatible CJS, phải dùng
`const { default: OidcProvider } = require(...)`.
**Bug #3 fixed (cùng commit)**: `provider.defaults.findAccount = ...` không
còn hoạt động trong oidc-provider@9 (defaults undefined). Phải truyền
`findAccount` như top-level config option trong constructor.
**Bug #4 fixed (commit riêng)**: `.env` đang dùng `DB_NAME=vietprodev_sso`
(do user tự sửa trước session này). Phải đổi về `sso` để match container.
**Server status hiện tại**:
```
[OK] OIDC provider initialized
[OK] OpenAPI ready
[OK] Redis connected
[OK] Jobs initialized
[OK] Partitions ready
[OK] Listening on port 3001
```
**Endpoints verified**:
- `/.well-known/openid-configuration` → 200 OK, JSON đầy đủ
- `/swagger/index` → 301 redirect (OK)
- `/health` → 503 degraded (XEM BUG #5 bên dưới)
### 14.8 ⚠️ BUG #5 CHƯA FIX: HOST POSTGRES CHIẾM PORT 5432
**Phát hiện quan trọng** (cần xử lý khi quay lại):
Host Windows có **2 Postgres instances cùng listen port 5432**:
1. **Host PostgreSQL 16** (service `postgresql-x64-16`, PID 5860) — chỉ có
DB `vietprodev_sso`, password khác (`postgres` user, password host)
2. **Docker container `sso-postgres`** (PID 3468) — có DB `sso` + `sso_backup`,
password `@dmin123` (theo `.env`)
Khi app kết nối `localhost:5432` từ Node.js, **host PostgreSQL 16 nhận
connection** (do listen trước / service). App thấy "database sso does not
exist" vì host chỉ có `vietprodev_sso`.
`/health` endpoint trả về:
```json
{
"status": "degraded",
"checks": { "database": false, "redis": true, "mongodb": true }
}
```
**3 lựa chọn để fix (user cần quyết định)**:
| # | Approach | Rủi ro | Effort |
|---|----------|--------|--------|
| A | **Stop service `postgresql-x64-16`** (cần admin) | Mất data host postgres nếu chưa backup | 1 command |
| B | **Config server dùng 127.0.0.1:5433 thay vì localhost:5432** | Phải update `.env` + restart server | 1 dòng |
| C | **Đổi docker-compose: postgres-main dùng port 25432** | Phải sửa `.env` tương ứng | 2 dòng |
> **Recommendation**: Option A (stop service) — đơn giản nhất, nhưng cần
> admin PowerShell. Option C an toàn nhất nhưng tốn effort sửa docker.
### 14.9 Khi quay lại sau reset, cần làm gì?
1. **Đọc lại section 14.8** trên đây
2. Chạy `git fetch && git branch -v` để xem 6 task branches đã push
3. Tạo branch mới `fix/db-port-conflict` từ `test/e2e-docker-migrate-verify`:
```bash
git checkout test/e2e-docker-migrate-verify
git checkout -b fix/db-port-conflict
```
4. Apply option A/B/C theo user quyết định
5. Test lại `/health` → phải 200 OK
6. Update `RUN.md` với setup mới
7. Commit + push branch mới
8. Task 6 hoàn thành → làm Task 7 (docs)
### 14.10 Branches phụ chưa merge (cũ, có thể bỏ)
- `feat/oidc-register-verify-email` (9ee96c4) — Phase 3 email verification
- `feat/phase1-sso-setup` (60ca47b)
- `feat/phase2-postgresql-multipool` (ec80d16)
- `feat/phase5-oidc-provider` (1e65095)
> Những branch này đã được base cho 6 task trên. Sau khi user merge xong
> task 1-5, có thể cleanup 4 branch cũ này.
### 14.11 Lệnh hữu ích cho session sau
```bash
# Xem tất cả branch status
git fetch --all
git branch -v
# Xem working tree hiện tại
git status
# Test thủ công kết nối Postgres
docker exec sso-postgres psql -U postgres -d sso -c "SELECT 1;"
docker exec sso-postgres-backup psql -U postgres -d sso_backup -c "SELECT 1;"
# Test kết nối từ host (KHÔNG qua docker)
# Cẩn thận: nếu host có postgres service, nó sẽ nhận connection trước docker
& "C:\Program Files\PostgreSQL\16\bin\psql.exe" -h localhost -p 5432 -U postgres -d sso
# Test server
curl.exe -s http://localhost:3001/.well-known/openid-configuration | head -c 200
curl.exe -s http://localhost:3001/health
curl.exe -s -o /dev/null -w "%{http_code}\n" http://localhost:3001/swagger/index
# Start dev server
pnpm run dev
```
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment