From ec59262411cfc1582a8c1428cd539f924b430063 Mon Sep 17 00:00:00 2001 From: Ho Ngoc Hai Date: Mon, 12 Jan 2026 12:26:20 +0700 Subject: [PATCH] feat(docs): Remove outdated analysis files to streamline documentation - Deleted several analysis files including breaking-changes.txt, docs-audit-matrix.md, docs-changes.txt, features.txt, git-history.txt, iam-architecture.md, patterns-comparison.md, template-architecture.md to reduce clutter and focus on relevant content. - This cleanup aims to enhance usability and maintain a more organized documentation structure. --- analysis/breaking-changes.txt | 0 analysis/docs-audit-matrix.md | 272 ------------- analysis/docs-changes.txt | 2 - analysis/features.txt | 31 -- analysis/git-history.txt | 50 --- analysis/iam-architecture.md | 625 ---------------------------- analysis/patterns-comparison.md | 650 ------------------------------ analysis/template-architecture.md | 235 ----------- 8 files changed, 1865 deletions(-) delete mode 100644 analysis/breaking-changes.txt delete mode 100644 analysis/docs-audit-matrix.md delete mode 100644 analysis/docs-changes.txt delete mode 100644 analysis/features.txt delete mode 100644 analysis/git-history.txt delete mode 100644 analysis/iam-architecture.md delete mode 100644 analysis/patterns-comparison.md delete mode 100644 analysis/template-architecture.md diff --git a/analysis/breaking-changes.txt b/analysis/breaking-changes.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/analysis/docs-audit-matrix.md b/analysis/docs-audit-matrix.md deleted file mode 100644 index 4880be4b..00000000 --- a/analysis/docs-audit-matrix.md +++ /dev/null @@ -1,272 +0,0 @@ -# Documentation Audit Matrix - -## Summary Statistics - -**Total Documentation Files**: 87 -- **English**: 43 files -- **Vietnamese**: 44 files - -**By Category**: -| Category | EN Files | VI Files | Total | % of Total | -|----------|----------|----------|-------|------------| -| Architecture | 3 | 3 | 6 | 7% | -| Guides | 10 | 10 | 20 | 23% | -| Skills/Patterns | 27 | 0 | 27 | 31% | -| Runbooks | 2 | 2 | 4 | 5% | -| Onboarding | 1 | 1 | 2 | 2% | - -**Note**: Skills EN/VI count is currently being verified - ---- - -## Architecture Documentation (6 files) - -| File | Has Mermaid? | EN Complete? | VI Complete? | Matches Code? | Priority | Notes | -|------|--------------|--------------|--------------|---------------|----------|-------| -| `en/architecture/system-design.md` | ❓ | ⚠️ | N/A | ❓ | **HIGHEST** | Needs comprehensive system diagram | -| `en/architecture/service-communication.md` | ❓ | ⚠️ | N/A | ❓ | **HIGHEST** | Needs sequence diagrams for inter-service calls | -| `en/architecture/iam-proposal.md` | ❓ | ⚠️ | N/A | ❓ | **HIGHEST** | Needs RBAC/auth flow diagrams | -| `vi/architecture/system-design.md` | ❓ | N/A | ⚠️ | ❓ | **HIGHEST** | Must match EN version | -| `vi/architecture/service-communication.md` | ❓ | N/A | ⚠️ | ❓ | **HIGHEST** | Must match EN version | -| `vi/architecture/iam-proposal.md` | ❓ | N/A | ⚠️ | ❓ | **HIGHEST** | Must match EN version | - -**Key Updates Needed**: -1. Add C4 context diagrams for system architecture -2. Add service mesh diagrams showing Traefik routing -3. Add sequence diagrams for authentication/authorization flows -4. Update based on actual `_template` and `iam-service` implementations -5. Add database ERD diagrams -6. Ensure EN/VI parity - ---- - -## Guides Documentation (20 files) - -### English Guides (10 files) - -| File | Has Mermaid? | Complete? | Matches Code? | Priority | Recent Updates | -|------|--------------|-----------|---------------|----------|----------------| -| `en/guides/getting-started.md` | ❓ | ⚠️ | ❓ | **HIGH** | Needs onboarding workflow diagram | -| `en/guides/local-development.md` | ❓ | ⚠️ | ❓ | **HIGH** | Needs setup flowchart, Docker compose diagram | -| `en/guides/kubernetes-local.md` | ✅ | ✅ | ✅ | **MEDIUM** | **Recently updated** (commit 4f48ead) with workflow diagram ✓ | -| `en/guides/deployment.md` | ❓ | ⚠️ | ❓ | **HIGH** | Needs CI/CD pipeline diagram | -| `en/guides/development.md` | ❓ | ⚠️ | ❓ | **MEDIUM** | Needs development workflow diagram | -| `en/guides/iam-migration.md` | ❓ | ⚠️ | ❌ | **MEDIUM** | Needs migration steps diagram | -| `en/guides/neon-database.md` | ❓ | ⚠️ | ❓ | **MEDIUM** | Needs database setup flowchart | -| `en/guides/observability.md` | ❓ | ⚠️ | ❓ | **MEDIUM** | Needs observability stack diagram | -| `en/guides/troubleshooting.md` | ❓ | ⚠️ | ❓ | **MEDIUM** | Needs decision tree diagrams | -| `en/guides/local-deployment.md` | ❓ | ⚠️ | ❓ | **MEDIUM** | Verify if duplicate of `local-development.md` | - -### Vietnamese Guides (10 files) - -All VI guides should mirror EN structure with equivalent content. - -| File | Status | Priority | -|------|--------|----------| -| `vi/guides/*.md` (all 10) | ❓ Must check parity with EN | **HIGH** | - -**Key Updates Needed**: -1. **`getting-started.md`**: Add quick start workflow, prerequisite checklist, setup verification steps -2. **`local-development.md`**: Add Docker Compose architecture diagram, environment variable matrix -3. **`deployment.md`**: Add deployment pipeline flowchart, rollback procedure diagram -4. **`kubernetes-local.md`**: ✅ Already has diagrams, verify accuracy only -5. All guides: Ensure bilingual parity, verify all commands work - ---- - -## Skills/Patterns Documentation (54 files estimated) - -### Breakdown by Topic (English only shown, each has VI equivalent) - -#### API & Communication (6 files) -| File | Priority | Diagrams Needed? | Code Examples Source | -|------|----------|------------------|----------------------| -| `api-design.md` | **HIGH** | ✅ RESTful API flow, response format | `_template/src/routes/` | -| `api-gateway-advanced.md` | MEDIUM | ✅ Gateway architecture | `infra/traefik/` | -| `api-versioning-strategy.md` | MEDIUM | ✅ Versioning decision tree | N/A | -| `inter-service-communication.md` | MEDIUM | ✅ Service mesh, gRPC vs REST | IAM examples | -| (2 more files) | | | | - -#### Data & Database (6 files) -| File | Priority | Diagrams Needed? | Code Examples Source | -|------|----------|------------------|----------------------| -| `database-prisma.md` | **HIGH** | ✅ Prisma workflow, migration process | `_template/prisma/` | -| `caching-patterns.md` | **HIGH** | ✅ Multi-layer cache flow | `iam-service/src/core/cache/` | -| `data-consistency-patterns.md` | MEDIUM | ✅ Saga pattern, event sourcing | N/A | -| `repository-pattern.md` | **HIGH** | ✅ Repository pattern flow | `_template/src/modules/common/` | -| (2 more files) | | | | - -#### Security & Auth (4 files) -| File | Priority | Diagrams Needed? | Code Examples Source | -|------|----------|------------------|----------------------| -| `security.md` | **HIGHEST** | ✅ Security layers, JWT flow, zero-trust | `iam-service/src/core/security/` | -| `middleware-patterns.md` | **HIGH** | ✅ Middleware execution order | `_template/src/middlewares/` | -| (2 more files) | | | | - -#### Testing (2 files) -| File | Priority | Diagrams Needed? | Code Examples Source | -|------|----------|------------------|----------------------| -| `testing-patterns.md` | **HIGH** | ✅ Testing strategy pyramid | `_template/__tests__/` | -| (1 more file) | | | | - -#### DevOps (8 files) -| File | Priority | Diagrams Needed? | Code Examples Source | -|------|----------|------------------|----------------------| -| `deployment-kubernetes.md` | MEDIUM | ✅ K8s architecture | `deployments/*/kubernetes/` | -| `cicd-advanced-patterns.md` | MEDIUM | ✅ CI/CD pipeline | `.github/workflows/` | -| `infrastructure-as-code.md` | MEDIUM | ✅ IaC workflow | N/A | -| `observability-monitoring.md` | MEDIUM | ✅ Observability stack | `_template/src/modules/metrics/` | -| (4 more files) | | | | - -#### Other Patterns (6+ files) -| File | Priority | Diagrams Needed? | -|------|----------|------------------| -| `project-rules.md` | **HIGHEST** | ✅ Project structure, workflow decision tree | -| `service-layer-patterns.md` | **HIGH** | ✅ Service pattern flow | -| `error-handling-patterns.md` | **HIGH** | ✅ Error flow diagram | -| `event-driven-architecture.md` | MEDIUM | ✅ Event flow | -| `resilience-patterns.md` | MEDIUM | ✅ Circuit breaker, retry flow | -| `performance-optimization.md` | MEDIUM | ✅ Optimization decision tree | - -**Key Updates Needed**: -1. **All skills docs**: Add relevant Mermaid diagrams -2. **Code examples**: Update to use actual code from `_template` and `iam-service` -3. **Bilingual parity**: Ensure EN/VI equivalence -4. **New examples**: Add advanced patterns from `iam-service` where applicable - ---- - -## Runbooks Documentation (4 files) - -| File | Has Mermaid? | Complete? | Priority | Notes | -|------|--------------|-----------|----------|-------| -| `en/runbooks/incident-response.md` | ❓ | ⚠️ | **HIGH** | Needs incident response flowchart, escalation matrix | -| `en/runbooks/rollback-procedure.md` | ❓ | ⚠️ | **HIGH** | Needs rollback decision tree, verification checklist | -| `vi/runbooks/incident-response.md` | ❓ | ⚠️ | **HIGH** | Must match EN | -| `vi/runbooks/rollback-procedure.md` | ❓ | ⚠️ | **HIGH** | Must match EN | - -**Key Updates Needed**: -1. Add incident severity decision tree -2. Add rollback procedure flowchart -3. Add verification checklist diagrams -4. Ensure operational accuracy (test procedures!) - ---- - -## Onboarding Documentation (2 files) - -| File | Has Mermaid? | Complete? | Priority | Notes | -|------|--------------|-----------|----------|-------| -| `en/onboarding/new-developer-guide.md` | ❓ | ⚠️ | **MEDIUM** | Needs onboarding journey timeline, setup workflow | -| `vi/onboarding/new-developer-guide.md` | ❓ | ⚠️ | **MEDIUM** | Must match EN | - -**Key Updates Needed**: -1. Add onboarding timeline (Day 1-30) -2. Add setup workflow diagram -3. Add learning path diagram -4. Test guide with new developer! - ---- - -## Gaps Analysis - -### Missing Diagrams (Estimated) - -Based on initial scan: -- **Architecture docs**: 6 files, need 15+ diagrams total -- **Guides**: 20 files, need 20-30 diagrams total -- **Skills**: 54 files, need 50-80 diagrams total -- **Runbooks**: 4 files, need 8-12 diagrams total -- **Onboarding**: 2 files, need 4-6 diagrams total - -**Total diagrams to create**: **~100-150 Mermaid diagrams** - -### Outdated Information - -**Sources of Truth** for updates: -1. **`_template/`**: 38 TypeScript files - - Module structure (4 modules) - - Basic patterns - - Configuration examples - -2. **`iam-service/`**: 176 TypeScript files - - Production patterns (14 modules) - - Advanced features - - Real-world implementations - -3. **Recent Git Commits**: 32 feature commits to review - - UI/UX updates (Mood Board, Auth pages) - - IAM enhancements (RBAC, Kubernetes configs) - - Infrastructure updates (Redis, Traefik) - -### Coverage Gaps - -Missing documentation for: -1. **Event sourcing pattern** (used in `iam-service/src/core/events/`) -2. **Zero-trust architecture** (implemented in `iam-service/src/core/security/`) -3. **Multi-layer caching** (needs detailed doc with flow diagrams) -4. **RBAC advanced patterns** (permission wildcards, temporary assignments) -5. **Compliance framework integration** (GDPR, SOC2 reporting) - ---- - -## Next Steps - -### Immediate Actions (Phase 1.3 completion) - -1. ✅ **Wait for Mermaid diagram count** (command in progress) -2. ❓ **Scan for outdated code examples** - - Compare code in docs vs actual source - - Identify deprecated patterns -3. ❓ **Create priority matrix** - - High priority: Architecture + Core Skills + Critical Guides - - Medium priority: Remaining Guides + Skills - - Low priority: Nice-to-have enhancements - -### Phase 2 Preparation - -Create templates for: -- Architecture documentation -- Guide documentation -- Skill/pattern documentation -- Runbook documentation - -Create Mermaid diagram library for common patterns: -- System architecture (C4 model) -- Sequence diagrams (authentication flows) -- Flowcharts (decision trees, workflows) -- Data flow diagrams -- Class diagrams (patterns) - ---- - -## Status Codes Legend - -- ✅ **Complete**: Has diagrams, up-to-date, EN/VI parity -- ⚠️ **Needs Update**: Missing diagrams or outdated -- ❓ **Unknown**: Needs verification -- ❌ **Major Issues**: Significantly outdated or missing -- N/A: Not applicable - ---- - -## Update Strategy - -### High Priority (Phase 3) -1. Architecture docs (6 files) - Foundation for everything -2. Core guides (getting-started, local-development, deployment) - Daily use -3. Core skills (project-rules, api-design, database-prisma, security) - Most referenced - -### Medium Priority (Phase 4) -4. Remaining guides (8 files) - Important but less frequently used -5. Remaining skills (20+ files) - Complete coverage -6. Runbooks (4 files) - Operational readiness - -### Low Priority (Continuous) -7. Onboarding (2 files) - Nice to have polish -8. Additional enhancements - Based on feedback - ---- - -**Last Updated**: 2026-01-05 (Phase 1 Analysis) -**Completion Estimate**: Phase 1 is 90% complete, waiting for final Mermaid diagram statistics diff --git a/analysis/docs-changes.txt b/analysis/docs-changes.txt deleted file mode 100644 index 68d86804..00000000 --- a/analysis/docs-changes.txt +++ /dev/null @@ -1,2 +0,0 @@ -4f48ead docs: Nâng cấp hướng dẫn triển khai Kubernetes cục bộ với sơ đồ quy trình, hướng dẫn chi tiết và chú thích song ngữ. -e785d64 docs: Thêm báo cáo trạng thái triển khai xác thực và điều chỉnh hiệu ứng kính trong CSS. diff --git a/analysis/features.txt b/analysis/features.txt deleted file mode 100644 index 372045c5..00000000 --- a/analysis/features.txt +++ /dev/null @@ -1,31 +0,0 @@ -d8d013e feat: Xóa bỏ file `test.sql` không còn cần thiết. -5c7c6cc feat: Thêm trang Mood Board mới và cập nhật giao diện người dùng, đồng thời loại bỏ các script cũ. -3998bc5 feat: giới thiệu component `AuthCard` để chuẩn hóa giao diện trang xác thực và cập nhật biến thể nút. -ffebc93 feat: triển khai các cải tiến giao diện người dùng và bổ sung tài liệu báo cáo hoàn thiện theme. -26fa062 feat: Cập nhật giao diện xác thực với thiết kế tối giản X.ai, loại bỏ nền vũ trụ và hiệu ứng động, điều chỉnh màu sắc nút và trạng thái focus, đồng thời -d079072 feat: Cải thiện trải nghiệm người dùng trên các trang xác thực bằng cách thêm hiệu ứng kínhmorphism và chức năng hiển thị mật khẩu, đồng thời cập nhật giao diện cho phù hợp với phong cách tối giản. -d678d3a feat: Cập nhật giao diện các trang xác thực với nền vũ trụ và hiệu ứng kínhmorphism, cải thiện trải nghiệm người dùng và thêm chức năng hiển thị mật khẩu cho trường nhập liệu. -14c7839 feat: Thêm component AuthControls chứa bộ chuyển đổi theme và ngôn ngữ vào các trang xác thực. -b00b5ea feat: Tích hợp bộ chuyển đổi chủ đề và ngôn ngữ vào thanh điều hướng, cập nhật hook i18n, và đặt chủ đề tối làm mặc định. -df5545e feat: Thêm các tiện ích an toàn cho khu vực di động, cải thiện cấu trúc footer và cập nhật layout cho trải nghiệm ứng dụng gốc. -d404689 feat: Cải thiện giao diện trang chủ với thành phần Banner thông báo, cập nhật cấu trúc điều hướng và tối ưu hóa màu sắc cho phong cách tối giản. -863e821 feat: Cập nhật các thành phần UI với cấu trúc dựa trên tính năng, thêm các thành phần glassmorphism, và cải thiện cấu hình đường dẫn trong tsconfig. -5a71b11 feat: Thêm các component Popover, Tooltip và refactor Switch sử dụng Radix UI, đồng thời cập nhật biến màu và dependencies. -92f4918 feat: Cải thiện giao diện trang chủ với hiệu ứng lơ lửng, mesh gradient pastel động và cập nhật phong cách các thành phần UI. -403b167 feat: Triển khai nền mesh gradient động và làm mới giao diện người dùng phần hero. -5db698b feat: Thêm thành phần footer, loại bỏ biểu tượng cờ khỏi bộ chuyển đổi ngôn ngữ, và cải thiện an toàn SSR cho ngữ cảnh chủ đề. -b831058 feat: Thêm header điều hướng responsive, bộ chuyển đổi ngôn ngữ, thành phần UI chuyển đổi chủ đề và phím tắt chuyển đổi chủ đề. -7cf4111 feat: Thêm các thành phần UI cho trạng thái tải (loading states), trạng thái rỗng (empty states) và tích hợp tài sản thương hiệu. -c54a9de feat: Vô hiệu hóa tạm thời Redis cache và sử dụng in-memory cache làm fallback. -101c333 feat: Cải thiện cấu hình Redis client với tùy chọn kết nối ổn định hơn, chiến lược thử lại nâng cao và xử lý sự kiện kết nối tốt hơn. -e3cc83b feat: Thêm chuyển hướng từ /auth/login sang /login -a383d87 feat: Cấu hình lại ứng dụng IAM, cập nhật cấu trúc routes, tích hợp RBAC và thêm các bài kiểm tra tích hợp. -ccfb2a7 feat: Thêm định nghĩa schema cho yêu cầu truy cập, đánh giá truy cập, chính sách, báo cáo tuân thủ và phiên vào tài liệu Swagger. -67fef54 feat: Thêm hướng dẫn triển khai dịch vụ lên Kubernetes cục bộ bằng tiếng Việt và tiếng Anh, đồng thời cập nhật tài liệu phát triển hiện có. -300b79e feat: Thêm cấu hình và script triển khai Kubernetes cục bộ cho dịch vụ IAM. -202b998 feat: Thêm cấu hình môi trường cục bộ và hoàn thành các tác vụ tăng cường bảo mật cho IAM service, bao gồm tạo dịch vụ mã hóa. -fcbe176 feat: Tối ưu Dockerfile của `iam-service` bằng cách lọc cài đặt pnpm, tinh chỉnh loại bỏ dev dependencies và thiết lập workspace đúng cách. -c05ce82 feat: Thêm bước generate Prisma Client rõ ràng vào Dockerfile của iam-service. -7154c37 feat: Cải thiện dịch vụ mã hóa AES-256-GCM và tích hợp khóa mã hóa vào cấu hình môi trường để bảo vệ dữ liệu nhạy cảm. -6abea5b feat: Bổ sung nhiều tài liệu quy tắc mới về thiết kế, kiến trúc và phát triển, đồng thời loại bỏ các quy tắc cũ về kiến trúc và đặt tên. -0d48ded feat: Khởi tạo Prisma client, bổ sung các bài kiểm tra đơn vị và tích hợp, đồng thời điều chỉnh cấu hình dịch vụ. diff --git a/analysis/git-history.txt b/analysis/git-history.txt deleted file mode 100644 index 813a3f63..00000000 --- a/analysis/git-history.txt +++ /dev/null @@ -1,50 +0,0 @@ -* 4f48ead docs: Nâng cấp hướng dẫn triển khai Kubernetes cục bộ với sơ đồ quy trình, hướng dẫn chi tiết và chú thích song ngữ. -* d8d013e feat: Xóa bỏ file `test.sql` không còn cần thiết. -* 5c7c6cc feat: Thêm trang Mood Board mới và cập nhật giao diện người dùng, đồng thời loại bỏ các script cũ. -* 3998bc5 feat: giới thiệu component `AuthCard` để chuẩn hóa giao diện trang xác thực và cập nhật biến thể nút. -* dfa045e refactor: Cập nhật các thành phần UI để sử dụng các lớp Tailwind CSS ngữ nghĩa cho việc tạo chủ đề tốt hơn và xóa tài liệu thiết kế. -* ffebc93 feat: triển khai các cải tiến giao diện người dùng và bổ sung tài liệu báo cáo hoàn thiện theme. -* e785d64 docs: Thêm báo cáo trạng thái triển khai xác thực và điều chỉnh hiệu ứng kính trong CSS. -* b0df44f refactor: di chuyển các trường nhập liệu sang sử dụng `Controller` của React Hook Form. -* 29de865 refactor: Cập nhật các trường nhập liệu form để sử dụng React Hook Form Controller và sửa lỗi không khớp hydration của nút chuyển đổi chủ đề. -* 62a008e refactor: Xóa bỏ import Card và `watch` không sử dụng từ useForm trong các trang xác thực. -* 686a092 refactor: Tách cấu hình viewport thành một export riêng biệt. -* 26fa062 feat: Cập nhật giao diện xác thực với thiết kế tối giản X.ai, loại bỏ nền vũ trụ và hiệu ứng động, điều chỉnh màu sắc nút và trạng thái focus, đồng thời -* d079072 feat: Cải thiện trải nghiệm người dùng trên các trang xác thực bằng cách thêm hiệu ứng kínhmorphism và chức năng hiển thị mật khẩu, đồng thời cập nhật giao diện cho phù hợp với phong cách tối giản. -* d678d3a feat: Cập nhật giao diện các trang xác thực với nền vũ trụ và hiệu ứng kínhmorphism, cải thiện trải nghiệm người dùng và thêm chức năng hiển thị mật khẩu cho trường nhập liệu. -* 2e26f71 style: Điều chỉnh hiệu ứng glassmorphism và animation để phù hợp với phong cách X.ai minimalist, loại bỏ các animation phức tạp và giảm độ mờ của hiệu ứng glass. -* 14c7839 feat: Thêm component AuthControls chứa bộ chuyển đổi theme và ngôn ngữ vào các trang xác thực. -* b00b5ea feat: Tích hợp bộ chuyển đổi chủ đề và ngôn ngữ vào thanh điều hướng, cập nhật hook i18n, và đặt chủ đề tối làm mặc định. -* d2da321 fix: Ngăn chặn lỗi hydration của i18n bằng cách tái cấu trúc logic phát hiện locale và trì hoãn áp dụng locale phía client. -* 2d783af refactor: Thay thế hook dịch thuật tùy chỉnh bằng hook useTranslations từ next-intl, cập nhật các thành phần liên quan đến dịch thuật và điều hướng sau khi đăng nhập thành công. -* df5545e feat: Thêm các tiện ích an toàn cho khu vực di động, cải thiện cấu trúc footer và cập nhật layout cho trải nghiệm ứng dụng gốc. -* d404689 feat: Cải thiện giao diện trang chủ với thành phần Banner thông báo, cập nhật cấu trúc điều hướng và tối ưu hóa màu sắc cho phong cách tối giản. -* f989a2f chore: Xóa các tệp cấu hình và thành phần không còn sử dụng trong ứng dụng client-example, bao gồm các tệp .eslintrc, .gitignore, .npmrc, và nhiều thành phần UI khác. -* 863e821 feat: Cập nhật các thành phần UI với cấu trúc dựa trên tính năng, thêm các thành phần glassmorphism, và cải thiện cấu hình đường dẫn trong tsconfig. -* 5a71b11 feat: Thêm các component Popover, Tooltip và refactor Switch sử dụng Radix UI, đồng thời cập nhật biến màu và dependencies. -* 92f4918 feat: Cải thiện giao diện trang chủ với hiệu ứng lơ lửng, mesh gradient pastel động và cập nhật phong cách các thành phần UI. -* 403b167 feat: Triển khai nền mesh gradient động và làm mới giao diện người dùng phần hero. -* 5db698b feat: Thêm thành phần footer, loại bỏ biểu tượng cờ khỏi bộ chuyển đổi ngôn ngữ, và cải thiện an toàn SSR cho ngữ cảnh chủ đề. -* b831058 feat: Thêm header điều hướng responsive, bộ chuyển đổi ngôn ngữ, thành phần UI chuyển đổi chủ đề và phím tắt chuyển đổi chủ đề. -* 7cf4111 feat: Thêm các thành phần UI cho trạng thái tải (loading states), trạng thái rỗng (empty states) và tích hợp tài sản thương hiệu. -* c54a9de feat: Vô hiệu hóa tạm thời Redis cache và sử dụng in-memory cache làm fallback. -* 101c333 feat: Cải thiện cấu hình Redis client với tùy chọn kết nối ổn định hơn, chiến lược thử lại nâng cao và xử lý sự kiện kết nối tốt hơn. -* 96dc13c fix: Cấu hình thủ công Traefik và cập nhật phiên bản để khắc phục sự cố Docker provider cục bộ. -* e3cc83b feat: Thêm chuyển hướng từ /auth/login sang /login -* d4f6115 refactor: Cập nhật cấu hình các tuyến đường (routes) của dịch vụ IAM và API xác thực phía client, đồng thời loại bỏ tệp sao lưu RBAC cũ. -* a383d87 feat: Cấu hình lại ứng dụng IAM, cập nhật cấu trúc routes, tích hợp RBAC và thêm các bài kiểm tra tích hợp. -* ccfb2a7 feat: Thêm định nghĩa schema cho yêu cầu truy cập, đánh giá truy cập, chính sách, báo cáo tuân thủ và phiên vào tài liệu Swagger. -* 7e7a7a5 refactor: Modularize IAM service routes into dedicated modules and add home page description -* 76b1c9b refactor: chuẩn hóa xử lý lỗi bằng cách giới thiệu tiện ích `getErrorMessage` và cập nhật kiểu `catch` thành `unknown`. -* 19e5e9b refactor: Cập nhật các import thư viện sang named imports cho `express-rate-limit`, `jsonwebtoken` và `dompurify`. -* 67fef54 feat: Thêm hướng dẫn triển khai dịch vụ lên Kubernetes cục bộ bằng tiếng Việt và tiếng Anh, đồng thời cập nhật tài liệu phát triển hiện có. -* 15a77a6 chore: Điều chỉnh đường dẫn script triển khai cục bộ và cập nhật chính sách kéo ảnh IAM service thành IfNotPresent. -* f5d04e1 chore: Cập nhật trạng thái các tác vụ trong kế hoạch kiểm toán dịch vụ IAM thành `skipped`. -* 300b79e feat: Thêm cấu hình và script triển khai Kubernetes cục bộ cho dịch vụ IAM. -* 202b998 feat: Thêm cấu hình môi trường cục bộ và hoàn thành các tác vụ tăng cường bảo mật cho IAM service, bao gồm tạo dịch vụ mã hóa. -* f315a7a refactor: Replaced dynamic rate limit creation with pre-configured role-based limiters. -* fc33f02 build: Thêm binary targets cho Prisma, chuyển rate limiter sang memory store, và cập nhật Dockerfile để sử dụng pnpm hoisting cùng openssl runtime. -* fcbe176 feat: Tối ưu Dockerfile của `iam-service` bằng cách lọc cài đặt pnpm, tinh chỉnh loại bỏ dev dependencies và thiết lập workspace đúng cách. -* c05ce82 feat: Thêm bước generate Prisma Client rõ ràng vào Dockerfile của iam-service. -* 7154c37 feat: Cải thiện dịch vụ mã hóa AES-256-GCM và tích hợp khóa mã hóa vào cấu hình môi trường để bảo vệ dữ liệu nhạy cảm. -* 9aed3da refactor: Đổi tên các model Prisma `userPermissions`, `userRoles`, `riskAssessment` và bỏ `backupCode` trong IAM service. diff --git a/analysis/iam-architecture.md b/analysis/iam-architecture.md deleted file mode 100644 index ce0e59cd..00000000 --- a/analysis/iam-architecture.md +++ /dev/null @@ -1,625 +0,0 @@ -# IAM Service Architecture Analysis - -## Overview / Tổng quan - -**Service**: `iam-service` - Enterprise-Grade Identity & Access Management -**TypeScript Files**: 176 files -**Status**: Production Ready (95% implementation) -**Last Updated**: Jan 4, 2026 - -## Module Structure / Cấu trúc Module - -### Production Modules (14 modules) - -``` -src/modules/ -├── common/ # Shared utilities, base classes -├── feature/ # Feature flags (inherited from template) -├── health/ # Health check endpoints -├── metrics/ # Prometheus metrics -├── auth/ # Core authentication (login, register, logout) -├── rbac/ # Role-Based Access Control -├── token/ # JWT & Refresh token management -├── session/ # Session management with device tracking -├── mfa/ # Multi-Factor Authentication (TOTP) -├── social/ # Social OAuth (Google, Facebook, GitHub) -├── oidc/ # OpenID Connect (Provider + Client) -├── identity/ # Identity management (users, profiles, orgs) -├── access/ # Access management (requests, reviews, analytics) -└── governance/ # Governance & compliance (reports, policies, risk) -``` - -### Module Breakdown - -#### Core Authentication Modules - -##### 1. Auth Module -**Purpose**: Core authentication flows -**Key Features**: -- Email/password registration & login -- Password reset & change -- Bcrypt hashing (cost factor 12) -- JWT token generation -- CSRF protection - -**Endpoints**: -``` -POST /api/v1/auth/register -POST /api/v1/auth/login -POST /api/v1/auth/logout -POST /api/v1/auth/refresh -POST /api/v1/auth/change-password -GET /api/v1/auth/me -``` - -##### 2. Token Module -**Purpose**: JWT and refresh token management -**Features**: -- Access tokens (15min lifetime) -- Refresh tokens (7 days lifetime) -- Token rotation with family tracking -- Secure HTTP-only cookies -- Token blacklisting (on logout) - -##### 3. Session Module -**Purpose**: User session management -**Features**: -- Device fingerprinting -- IP address tracking -- Location analysis -- Multiple concurrent sessions -- Session listing & termination - -**Endpoints**: -``` -GET /api/v1/sessions # List user sessions -DELETE /api/v1/sessions/:id # Terminate specific session -DELETE /api/v1/sessions/all # Terminate all sessions -``` - -##### 4. MFA Module -**Purpose**: Multi-Factor Authentication -**Features**: -- TOTP (Time-based One-Time Password) -- QR code generation -- Backup codes -- Device management -- Recovery procedures - -**Endpoints**: -``` -POST /api/v1/mfa/totp/enable -POST /api/v1/mfa/totp/verify -POST /api/v1/mfa/totp/validate -POST /api/v1/mfa/totp/disable -GET /api/v1/mfa/devices -``` - -##### 5. Social Module -**Purpose**: Social OAuth integration -**Supported Providers**: -- Google OAuth 2.0 -- Facebook Login -- GitHub OAuth - -**Flow**: -``` -User → Redirect to Provider → Callback → Create/Link Account → JWT Token -``` - -**Endpoints**: -``` -GET /api/v1/auth/social/google -GET /api/v1/auth/social/facebook -GET /api/v1/auth/social/github -GET /api/v1/auth/social/google/callback -GET /api/v1/auth/social/facebook/callback -GET /api/v1/auth/social/github/callback -``` - -##### 6. OIDC Module -**Purpose**: OpenID Connect Provider & Client -**Features**: -- OIDC Provider implementation -- OIDC Client for SSO -- Discovery endpoint -- UserInfo endpoint -- Token introspection - -#### Authorization Modules - -##### 7. RBAC Module -**Purpose**: Role-Based Access Control -**Permission Model**: `resource:action:scope` -**Features**: -- Role management (CRUD) -- Permission management -- User-role assignments (with expiration) -- User-permission overrides (direct permissions) -- Permission caching (5min TTL) -- Group-based permissions - -**Key Entities**: -- **Role**: Named collection of permissions (e.g., ADMIN, MANAGER, USER) -- **Permission**: Granular access (e.g., `users:create:org`, `posts:delete:own`) -- **UserRole**: User-role assignment (can expire) -- **UserPermission**: Direct permission grants (override roles) - -**Endpoints**: -``` -GET /api/v1/rbac/roles -POST /api/v1/rbac/roles -GET /api/v1/rbac/permissions -POST /api/v1/users/:id/roles -DELETE /api/v1/users/:id/roles/:roleId -POST /api/v1/users/:id/permissions -``` - -**Permission Check Flow**: -``` -Request → Check Direct Permissions → Check Role Permissions → Check Group Permissions → Allow/Deny -``` - -#### Identity Management Modules - -##### 8. Identity Module -**Purpose**: User lifecycle & profile management -**Features**: -- User CRUD operations -- Extended user profiles -- Email/phone/document verification -- Multi-tenant organizations -- Groups with hierarchical structure -- Bulk user import/export -- User deactivation/reactivation - -**Database Models**: -- `User` - Core user accounts -- `UserProfile` - Extended user information -- `Organization` - Multi-tenant organizations -- `Group` - User groups within orgs -- `GroupMember` - Group membership -- `IdentityVerification` - Verification records - -**Endpoints**: -``` -GET /api/v1/identity/users -POST /api/v1/identity/users -GET /api/v1/identity/users/:id -PUT /api/v1/identity/users/:id -POST /api/v1/identity/users/:id/deactivate -POST /api/v1/identity/users/:id/reactivate -GET /api/v1/identity/users/:id/profile -PUT /api/v1/identity/users/:id/profile -POST /api/v1/identity/users/:id/avatar -``` - -#### Access Management Modules - -##### 9. Access Module -**Purpose**: Access request workflows & reviews -**Features**: -- Access request workflows with multi-person approval -- Access reviews & certification campaigns -- Access analytics & usage reporting -- Anomaly detection -- Just-In-Time (JIT) access -- Temporary access grants - -**Database Models**: -- `AccessRequest` - Access request workflows -- `AccessRequestApprover` - Multi-person approval chains -- `AccessReview` - Access certification campaigns -- `AccessReviewItem` - Individual review items - -**Endpoints**: -``` -POST /api/v1/access/requests -GET /api/v1/access/requests -POST /api/v1/access/requests/:id/approve -POST /api/v1/access/requests/:id/reject -POST /api/v1/access/reviews -GET /api/v1/access/reviews -POST /api/v1/access/reviews/:id/items/:itemId/review -GET /api/v1/access/analytics/usage -``` - -##### 10. Governance Module -**Purpose**: Compliance & governance reporting -**Features**: -- GDPR compliance reporting -- SOC2 compliance reporting -- ISO27001 compliance reporting -- HIPAA compliance support -- Policy templates & versioning -- Risk scoring & management -- Audit log analysis - -**Database Models**: -- `ComplianceReport` - Compliance reports (GDPR, SOC2, ISO27001, HIPAA) -- `PolicyTemplate` - Reusable policy templates -- `RiskScore` - User risk scoring - -**Endpoints**: -``` -POST /api/v1/governance/compliance/reports -GET /api/v1/governance/compliance/reports -POST /api/v1/governance/compliance/reports/:id/generate -GET /api/v1/governance/risk/scores -POST /api/v1/governance/risk/calculate -GET /api/v1/governance/policies/templates -``` - -## Core Services / Core Services - -### 1. Multi-Layer Cache Service -**Location**: `src/core/cache/` -**Pattern**: L1 (Memory) → L2 (Redis) → L3 (Database) - -**Implementation**: -- **L1 Cache**: NodeCache (in-memory), 60s TTL, 10k keys max -- **L2 Cache**: Redis, 5-15min TTL, distributed -- **L3**: Prisma with connection pooling - -**Cached Data**: -| Data Type | L1 TTL | L2 TTL | Use Case | -|-----------|--------|--------|----------| -| User Data | 60s | 15min | Profile, permissions | -| Permissions | 60s | 5min | Authorization checks | -| User Roles | 60s | 5min | Role assignments | -| Token Validation | N/A | Token lifetime | JWT blacklist | - -**Cache Invalidation**: -```typescript -// Pattern-based invalidation -await cacheService.invalidatePattern('user:123:*'); - -// Event-driven invalidation -onUserUpdate → invalidateCache('user:${userId}') -onPermissionChange → invalidateCache('user:${userId}:permissions') -``` - -### 2. Audit Service (Event Sourcing) -**Location**: `src/core/events/` -**Purpose**: Complete audit trail for compliance - -**Features**: -- Event sourcing for all authentication and authorization events -- 7-year retention for compliance (GDPR, SOC2) -- Correlation ID tracking -- Event replay capability - -**Event Types**: -```typescript -enum AuditEventType { - LOGIN_SUCCESS = 'LOGIN_SUCCESS', - LOGIN_FAILURE = 'LOGIN_FAILURE', - LOGOUT = 'LOGOUT', - TOKEN_REFRESH = 'TOKEN_REFRESH', - PASSWORD_CHANGE = 'PASSWORD_CHANGE', - ROLE_ASSIGNED = 'ROLE_ASSIGNED', - PERMISSION_GRANTED = 'PERMISSION_GRANTED', - ACCESS_DENIED = 'ACCESS_DENIED', - SESSION_CREATED = 'SESSION_CREATED', - SESSION_TERMINATED = 'SESSION_TERMINATED', - MFA_ENABLED = 'MFA_ENABLED', - // ... many more -} -``` - -**Database Model**: -```prisma -model AuthEvent { - id String @id @default(cuid()) - eventType String // AuditEventType - userId String? - email String? - ipAddress String? - userAgent String? - success Boolean - metadata Json? - correlationId String? - createdAt DateTime @default(now()) - - @@index([userId, createdAt]) - @@index([eventType, createdAt]) - @@index([correlationId]) -} -``` - -### 3. Security Service (Zero-Trust Validator) -**Location**: `src/core/security/` -**Purpose**: Zero-trust security validation - -**Features**: -- Device fingerprinting -- IP address analysis -- Location validation -- Behavioral analysis -- Risk-based authentication -- Anomaly detection - -**Zero-Trust Checks**: -``` -1. Valid JWT token? ✓ -2. Token not blacklisted? ✓ -3. Session still active? ✓ -4. Device fingerprint matches? ✓ -5. IP address in allowed range? ✓ -6. No suspicious behavior detected? ✓ -→ ALLOW REQUEST -``` - -### 4. Encryption Service -**Location**: `src/core/security/encryption.service.ts` -**Algorithm**: AES-256-GCM -**Purpose**: Encrypt PII at rest - -**Features**: -- Symmetric encryption for sensitive data -- IV (Initialization Vector) per encryption -- Authentication tag for integrity -- Key rotation support - -**Usage**: -```typescript -// Encrypt sensitive data -const encrypted = encryptionService.encrypt(ssn); -// Store: "iv:tag:ciphertext" - -// Decrypt when needed -const ssn = encryptionService.decrypt(encrypted); -``` - -## Middleware Stack / Stack Middleware - -```typescript -// Execution Order (from main.ts) -1. Helmet // Security headers -2. CORS // Cross-origin config -3. Rate Limiting // Dynamic rate limiting (by role) -4. Correlation ID // Request tracing -5. Request Logger // Structured logging -6. Zero-Trust Validator // Security validation -7. Body Parsers // JSON, URL-encoded -8. Cookie Parser // Parse cookies -9. Metrics // Prometheus instrumentation -10. Routes // API routes -11. Not Found Handler // 404 handling -12. Error Handler // Global error handling (LAST) -``` - -### Dynamic Rate Limiting -**Implementation**: Redis-backed distributed rate limiting - -**Limits by Role**: -```typescript -const rateLimitsByRole = { - anonymous: { windowMs: 15 * 60 * 1000, max: 50 }, // 50 req/15min - user: { windowMs: 15 * 60 * 1000, max: 100 }, // 100 req/15min - moderator: { windowMs: 15 * 60 * 1000, max: 300 }, // 300 req/15min - admin: { windowMs: 15 * 60 * 1000, max: 500 }, // 500 req/15min - superadmin: { windowMs: 15 * 60 * 1000, max: 1000 }, // 1000 req/15min -}; -``` - -**Login-Specific Limit**: -```typescript -const loginLimiter = { - windowMs: 15 * 60 * 1000, - max: 5, // 5 login attempts per 15 minutes - message: 'Too many login attempts, please try again later', -}; -``` - -## Database Schema / Schema Database - -**Database**: PostgreSQL 14+ -**ORM**: Prisma -**Total Models**: 30+ - -### Core Models - -#### Authentication -- `User` - User accounts (email, password, MFA status) -- `Session` - Active sessions (device, IP, location) -- `RefreshToken` - Refresh tokens (with family tracking) -- `AuthEvent` - Audit log (event sourcing) -- `SocialAccount` - Linked OAuth accounts -- `MFADevice` - TOTP and WebAuthn devices - -#### Authorization -- `Role` - Named roles (ADMIN, MANAGER, USER) -- `Permission` - Granular permissions (`resource:action:scope`) -- `UserRole` - User-role assignments (with expiration) -- `RolePermission` - Role-permission mappings -- `UserPermission` - Direct user permissions (override roles) -- `Policy` - ABAC policies (JSON Logic conditions) - -#### Identity -- `Organization` - Multi-tenant organizations -- `Group` - User groups within organizations -- `GroupMember` - Group membership (with roles) -- `UserProfile` - Extended user information -- `IdentityVerification` - Email/phone/document verification - -#### Access Management -- `AccessRequest` - Access request workflows -- `AccessRequestApprover` - Multi-person approval chains -- `AccessReview` - Access certification campaigns -- `AccessReviewItem` - Individual review items - -#### Governance -- `ComplianceReport` - GDPR, SOC2, ISO27001, HIPAA reports -- `PolicyTemplate` - Reusable policy templates -- `RiskScore` - User risk scores - -## API Surface / Bề mặt API - -**Total Endpoints**: 50+ -**Base Path**: `/api/v1` - -### Endpoint Categories - -| Category | Endpoints | Module | -|----------|-----------|--------| -| Authentication | 10+ | auth, token, session | -| Social Auth | 6 | social | -| OIDC | 5+ | oidc | -| MFA | 5 | mfa | -| RBAC | 8 | rbac | -| Identity | 12+ | identity | -| Access | 8+ | access | -| Governance | 6+ | governance | -| Health | 3 | health | -| Metrics | 1 | metrics | - -## Security Features / Tính năng Bảo mật - -### Defense-in-Depth Layers - -1. **Network Layer**: - - HTTPS/TLS enforcement - - CORS configuration - - Rate limiting (distributed) - -2. **Application Layer**: - - Helmet (security headers) - - Input validation (Zod) - - SQL injection prevention (Prisma ORM) - - XSS prevention (CSP) - -3. **Authentication Layer**: - - Bcrypt (cost factor 12) - - JWT with short lifetime (15min) - - Refresh token rotation - - MFA (TOTP) - - Social OAuth - -4. **Authorization Layer**: - - RBAC (role-based) - - ABAC (attribute-based) - - Direct permissions (override roles) - - Permission caching - -5. **Data Layer**: - - AES-256-GCM encryption for PII - - Token hashing (SHA-256) - - Password hashing (bcrypt) - -6. **Audit Layer**: - - Event sourcing - - Correlation IDs - - 7-year retention - - Compliance reporting - -## Performance Optimizations / Tối ưu Hiệu suất - -### Caching Strategy -- **Cache Hit Rate**: 80-90% for permissions -- **Response Time**: P95 < 100ms -- **Token Validation**: < 1ms (L1 cache hit) -- **Permission Check**: < 5ms (L2 cache hit) - -### Database Optimizations -- Connection pooling (Prisma default: 10) -- Indexed queries (25+ indexes) -- Selective field fetching -- Batch operations where possible - -### Redis Optimizations -- Connection pooling -- Pipeline operations -- Pub/Sub for cache invalidation -- Distributed rate limiting - -## Observability / Khả năng quan sát - -### Metrics (Prometheus) -- HTTP request duration (by endpoint, status) -- HTTP request count -- Active sessions (gauge) -- Cache hit/miss ratio -- Database query duration -- Authentication success/failure rate -- Authorization checks (allow/deny) - -### Logging (Winston) -- Structured JSON logs -- Correlation IDs in every log -- Request/response logging -- Error stack traces (dev only) -- Audit event logging - -### Tracing (OpenTelemetry + Jaeger) -- HTTP request spans -- Database query spans -- Cache operation spans -- External API call spans -- Authentication flow spans - -### Health Checks -- `/health/live` - Liveness (is process running?) -- `/health/ready` - Readiness (can serve traffic? checks DB + Redis) -- `/health` - Full health (with dependency status) - -## Production Readiness / Sẵn sàng Production - -- ✅ Multi-layer caching (L1/L2/L3) -- ✅ Zero-trust architecture -- ✅ Device fingerprinting -- ✅ Dynamic rate limiting -- ✅ Event sourcing for audit -- ✅ Compliance reporting (GDPR, SOC2, ISO27001, HIPAA) -- ✅ Multi-factor authentication -- ✅ Social OAuth integration -- ✅ OpenID Connect -- ✅ RBAC + ABAC authorization -- ✅ Encryption for PII -- ✅ Comprehensive logging -- ✅ Prometheus metrics -- ✅ Jaeger tracing -- ✅ Health checks (K8s compatible) -- ✅ Docker deployment -- ✅ Kubernetes manifests -- ✅ Graceful shutdown -- ✅ Connection pooling - -## Comparison with Template / So sánh với Template - -| Feature | Template | IAM Service | -|---------|----------|-------------| -| **Modules** | 4 | 14 | -| **TypeScript Files** | 38 | 176 | -| **Database Models** | 1 (example) | 30+ | -| **API Endpoints** | 5 (example) | 50+ | -| **Authentication** | ❌ | ✅ (7 methods) | -| **Authorization** | ❌ | ✅ (RBAC + ABAC) | -| **Caching** | ❌ | ✅ (3-layer) | -| **Rate Limiting** | ❌ | ✅ (Dynamic by role) | -| **Audit Logging** | Basic | ✅ (Event sourcing) | -| **Security** | Basic (Helmet) | ✅ (Zero-trust) | -| **MFA** | ❌ | ✅ (TOTP) | -| **Social OAuth** | ❌ | ✅ (3 providers) | -| **OIDC** | ❌ | ✅ (Provider + Client) | -| **Compliance** | ❌ | ✅ (4 frameworks) | -| **Encryption** | ❌ | ✅ (AES-256-GCM) | - -## Summary / Tóm tắt - -`iam-service` is an **enterprise-grade IAM platform** built on top of the `_template` foundation, demonstrating: - -- **Complete authentication system** (password, social, OIDC, MFA) -- **Advanced authorization** (RBAC + ABAC + direct permissions) -- **Zero-trust security** (device fingerprinting, behavioral analysis) -- **High performance** (multi-layer caching, 80-90% cache hit rate) -- **Compliance-ready** (GDPR, SOC2, ISO27001, HIPAA reporting) -- **Production-hardened** (95% implementation complete) - -It showcases **real-world patterns** for: -- Distributed caching -- Event sourcing -- Zero-trust architecture -- Multi-tenant support -- Access governance -- Compliance automation diff --git a/analysis/patterns-comparison.md b/analysis/patterns-comparison.md deleted file mode 100644 index 53eec668..00000000 --- a/analysis/patterns-comparison.md +++ /dev/null @@ -1,650 +0,0 @@ -# Pattern Comparison: Template vs IAM Service - -## Overview - -This document compares implementation patterns between `_template` (baseline microservice) and `iam-service` (production implementation) to guide documentation updates. - -## Module Structure Pattern - -### Template Pattern (Simple) -``` -src/modules/ -├── common/ # Base repository, shared types -├── feature/ # Example CRUD module -├── health/ # Health checks -└── metrics/ # Prometheus metrics -``` - -### IAM Pattern (Production) -``` -src/modules/ -├── common/ # Base repository, shared types (same) -├── feature/ # Example CRUD module (inherited) -├── health/ # Health checks (same) -├── metrics/ # Prometheus metrics (same) -├── auth/ # + Core authentication -├── rbac/ # + Authorization -├── token/ # + Token management -├── session/ # + Session management -├── mfa/ # + Multi-factor auth -├── social/ # + Social OAuth -├── oidc/ # + OpenID Connect -├── identity/ # + Identity management -├── access/ # + Access workflows -└── governance/ # + Compliance & reporting -``` - -**Documentation Impact**: -- Template docs should focus on **foundational patterns** -- IAM docs should show **advanced patterns** and **real-world implementation** - ---- - -## Controller Pattern - -### Template (Basic) -```typescript -// src/modules/feature/feature.controller.ts -export class FeatureController { - constructor(private service: FeatureService) {} - - async create(req: Request, res: Response, next: NextFunction) { - try { - const dto = CreateFeatureDto.parse(req.body); - const result = await this.service.create(dto); - res.status(201).json({ success: true, data: result }); - } catch (error) { - next(error); - } - } -} -``` - -### IAM (Production with Auth) -```typescript -// src/modules/identity/identity.controller.ts -export class IdentityController { - constructor( - private service: IdentityService, - private auditService: AuditService - ) {} - - @RequireAuth() - @RequirePermission('users', 'create') - @RateLimit('strict') - async create(req: Request, res: Response, next: NextFunction) { - try { - const dto = CreateUserDto.parse(req.body); - const result = await this.service.create(dto); - - // Audit logging - await this.auditService.log('USER_CREATED', req.user.id, { - userId: result.id, - correlationId: req.correlationId, - }); - - res.status(201).json({ success: true, data: result }); - } catch (error) { - next(error); - } - } -} -``` - -**Pattern Differences**: -1. **Decorators**: IAM uses decorators for auth, permissions, rate limiting -2. **Audit Logging**: IAM logs all operations -3. **Dependency Injection**: IAM injects multiple services (Service + AuditService) - -**Documentation Impact**: -- Template docs: Show basic controller pattern -- IAM docs: Show auth decorators, audit logging, multi-service injection - ---- - -## Service Pattern - -### Template (Simple Business Logic) -```typescript -// src/modules/feature/feature.service.ts -export class FeatureService { - constructor(private repository: FeatureRepository) {} - - async create(data: CreateFeatureDto) { - // Business validation - const existing = await this.repository.findByName(data.name); - if (existing) { - throw new ConflictError('Feature already exists'); - } - - return await this.repository.create(data); - } -} -``` - -### IAM (with Caching & Complex Logic) -```typescript -// src/modules/rbac/rbac.service.ts -export class RBACService { - constructor( - private repository: RBACRepository, - private cacheService: CacheService, - private auditService: AuditService - ) {} - - async checkPermission( - userId: string, - resource: string, - action: string - ): Promise { - // Try cache first (L1 → L2) - const cacheKey = `user:${userId}:permissions`; - const cached = await this.cacheService.get(cacheKey); - - let permissions: string[]; - if (cached) { - permissions = cached; - } else { - // Cache miss - fetch from DB - const userRoles = await this.repository.getUserRoles(userId); - const rolePermissions = await this.repository.getRolePermissions(userRoles); - const directPermissions = await this.repository.getUserPermissions(userId); - - permissions = [...rolePermissions, ...directPermissions]; - - // Cache for 5 minutes - await this.cacheService.set(cacheKey, permissions, 300); - } - - // Check permission - const required = `${resource}:${action}`; - const hasPermission = permissions.some(p => this.matchesPermission(p, required)); - - // Audit log - await this.auditService.log( - hasPermission ? 'ACCESS_GRANTED' : 'ACCESS_DENIED', - userId, - { resource, action } - ); - - return hasPermission; - } - - private matchesPermission(granted: string, required: string): boolean { - // Handle wildcards: users:*:* matches users:create:org - const grantedParts = granted.split(':'); - const requiredParts = required.split(':'); - - return grantedParts.every((part, i) => - part === '*' || part === requiredParts[i] - ); - } -} -``` - -**Pattern Differences**: -1. **Caching**: IAM uses multi-layer caching -2. **Complex Logic**: Permission matching with wildcards -3. **Audit Logging**: Every operation logged -4. **Performance**: Cache-first approach for frequently accessed data - -**Documentation Impact**: -- Template docs: Simple business logic -- IAM docs: Caching strategies, complex permission logic, audit logging - ---- - -## Repository Pattern - -### Template (Basic CRUD) -```typescript -// src/modules/feature/feature.repository.ts -export class FeatureRepository extends BaseRepository { - constructor(prisma: PrismaClient) { - super(prisma, 'feature'); - } - - async findByName(name: string): Promise { - return this.prisma.feature.findUnique({ where: { name } }); - } -} -``` - -### IAM (with Joins & Complex Queries) -```typescript -// src/modules/rbac/rbac.repository.ts -export class RBACRepository extends BaseRepository { - constructor(prisma: PrismaClient) { - super(prisma, 'role'); - } - - async getUserRoles(userId: string): Promise { - const userRoles = await this.prisma.userRole.findMany({ - where: { - userId, - OR: [ - { expiresAt: null }, - { expiresAt: { gt: new Date() } } - ] - }, - include: { role: true } - }); - - return userRoles.map(ur => ur.role.name); - } - - async getRolePermissions(roleNames: string[]): Promise { - const rolePermissions = await this.prisma.rolePermission.findMany({ - where: { role: { name: { in: roleNames } } }, - include: { permission: true } - }); - - return rolePermissions.map(rp => rp.permission.code); - } - - async getUserPermissions(userId: string): Promise { - const userPermissions = await this.prisma.userPermission.findMany({ - where: { userId }, - include: { permission: true } - }); - - return userPermissions.map(up => up.permission.code); - } -} -``` - -**Pattern Differences**: -1. **Complex Joins**: IAM uses nested includes -2. **Conditional Logic**: Expiration checking -3. **Data Aggregation**: Combining data from multiple sources - -**Documentation Impact**: -- Template docs: Basic CRUD with unique lookups -- IAM docs: Complex joins, conditional queries, data aggregation - ---- - -## Middleware Pattern - -### Template (Basic) -```typescript -// src/middlewares/logger.middleware.ts -export const loggerMiddleware = ( - req: Request, - res: Response, - next: NextFunction -) => { - const start = Date.now(); - - res.on('finish', () => { - const duration = Date.now() - start; - logger.info('Request completed', { - method: req.method, - url: req.url, - statusCode: res.statusCode, - duration, - }); - }); - - next(); -}; -``` - -### IAM (with Correlation IDs & Audit) -```typescript -// src/middlewares/logger.middleware.ts -export const loggerMiddleware = ( - req: Request, - res: Response, - next: NextFunction -) => { - const start = Date.now(); - const correlationId = req.correlationId || generateCorrelationId(); - - // Attach to request for downstream use - req.correlationId = correlationId; - res.setHeader('x-correlation-id', correlationId); - - res.on('finish', () => { - const duration = Date.now() - start; - logger.info('Request completed', { - correlationId, - method: req.method, - url: req.url, - statusCode: res.statusCode, - duration, - userId: req.user?.id, - ipAddress: req.ip, - userAgent: req.headers['user-agent'], - }); - - // Audit logging for sensitive endpoints - if (req.url.startsWith('/api/v1/auth') || req.url.startsWith('/api/v1/rbac')) { - auditService.log('API_REQUEST', req.user?.id, { - method: req.method, - url: req.url, - statusCode: res.statusCode, - correlationId, - }); - } - }); - - next(); -}; -``` - -**Pattern Differences**: -1. **Correlation IDs**: IAM propagates correlation IDs -2. **Enhanced Context**: User ID, IP, user agent -3. **Audit Integration**: Sensitive endpoints get audit logs - -**Documentation Impact**: -- Template docs: Basic request logging -- IAM docs: Distributed tracing, audit integration, correlation IDs - ---- - -## Configuration Pattern - -### Template (Simple Zod Validation) -```typescript -// src/config/app.config.ts -import { z } from 'zod'; - -const envSchema = z.object({ - PORT: z.coerce.number().default(5000), - NODE_ENV: z.enum(['development', 'production', 'test']).default('development'), - DATABASE_URL: z.string().url(), - REDIS_URL: z.string().url().optional(), -}); - -const env = envSchema.parse(process.env); - -export const appConfig = { - port: env.PORT, - env: env.NODE_ENV, - database: { url: env.DATABASE_URL }, - redis: { url: env.REDIS_URL }, -}; -``` - -### IAM (with Nested Configs & Secrets) -```typescript -// src/config/app.config.ts -import { z } from 'zod'; - -const envSchema = z.object({ - // Server - PORT: z.coerce.number().default(3001), - NODE_ENV: z.enum(['development', 'production', 'test']).default('development'), - - // Database - DATABASE_URL: z.string().url(), - DATABASE_POOL_SIZE: z.coerce.number().default(10), - - // Redis - REDIS_HOST: z.string().default('localhost'), - REDIS_PORT: z.coerce.number().default(6379), - REDIS_PASSWORD: z.string().optional(), - REDIS_DB: z.coerce.number().default(0), - - // JWT - JWT_SECRET: z.string().min(32), - JWT_REFRESH_SECRET: z.string().min(32), - JWT_ACCESS_EXPIRY: z.string().default('15m'), - JWT_REFRESH_EXPIRY: z.string().default('7d'), - - // Encryption - ENCRYPTION_KEY: z.string().min(32).optional(), - - // OAuth - GOOGLE_CLIENT_ID: z.string().optional(), - GOOGLE_CLIENT_SECRET: z.string().optional(), - FACEBOOK_APP_ID: z.string().optional(), - FACEBOOK_APP_SECRET: z.string().optional(), - GITHUB_CLIENT_ID: z.string().optional(), - GITHUB_CLIENT_SECRET: z.string().optional(), - - // Feature Flags - MFA_ENABLED: z.coerce.boolean().default(true), - SOCIAL_AUTH_ENABLED: z.coerce.boolean().default(true), - TRACING_ENABLED: z.coerce.boolean().default(false), -}); - -const env = envSchema.parse(process.env); - -export const appConfig = { - server: { - port: env.PORT, - env: env.NODE_ENV, - }, - database: { - url: env.DATABASE_URL, - poolSize: env.DATABASE_POOL_SIZE, - }, - redis: { - host: env.REDIS_HOST, - port: env.REDIS_PORT, - password: env.REDIS_PASSWORD, - db: env.REDIS_DB, - }, - jwt: { - secret: env.JWT_SECRET, - refreshSecret: env.JWT_REFRESH_SECRET, - accessExpiry: env.JWT_ACCESS_EXPIRY, - refreshExpiry: env.JWT_REFRESH_EXPIRY, - }, - encryption: { - key: env.ENCRYPTION_KEY, - }, - oauth: { - google: { - clientId: env.GOOGLE_CLIENT_ID, - clientSecret: env.GOOGLE_CLIENT_SECRET, - }, - facebook: { - appId: env.FACEBOOK_APP_ID, - appSecret: env.FACEBOOK_APP_SECRET, - }, - github: { - clientId: env.GITHUB_CLIENT_ID, - clientSecret: env.GITHUB_CLIENT_SECRET, - }, - }, - features: { - mfa: env.MFA_ENABLED, - socialAuth: env.SOCIAL_AUTH_ENABLED, - tracing: env.TRACING_ENABLED, - }, -}; -``` - -**Pattern Differences**: -1. **Nested Configuration**: IAM groups related configs -2. **Secrets Management**: JWT, encryption, OAuth secrets -3. **Feature Flags**: Runtime feature toggles -4. **Complex Validation**: Min length requirements, optional fields - -**Documentation Impact**: --Template docs: Show basic Zod validation -- IAM docs: Show nested configs, secrets management, feature flags - ---- - -## Testing Pattern - -### Template (Simple Unit Test) -```typescript -// src/modules/feature/__tests__/feature.service.test.ts -describe('FeatureService', () => { - let service: FeatureService; - let mockRepository: any; - - beforeEach(() => { - mockRepository = { - findByName: jest.fn(), - create: jest.fn(), - }; - service = new FeatureService(mockRepository); - }); - - it('should create feature', async () => { - mockRepository.findByName.mockResolvedValue(null); - mockRepository.create.mockResolvedValue({ id: '1', name: 'test' }); - - const result = await service.create({ name: 'test' }); - - expect(result).toEqual({ id: '1', name: 'test' }); - expect(mockRepository.create).toHaveBeenCalledWith({ name: 'test' }); - }); - - it('should throw conflict error if feature exists', async () => { - mockRepository.findByName.mockResolvedValue({ id: '1', name: 'test' }); - - await expect(service.create({ name: 'test' })) - .rejects - .toThrow(ConflictError); - }); -}); -``` - -### IAM (with Mocking Complete Dependencies) -```typescript -// src/modules/rbac/__tests__/rbac.service.test.ts -describe('RBACService', () => { - let service: RBACService; - let mockRepository: any; - let mockCacheService: any; - let mockAuditService: any; - - beforeEach(() => { - mockRepository = { - getUserRoles: jest.fn(), - getRolePermissions: jest.fn(), - getUserPermissions: jest.fn(), - }; - mockCacheService = { - get: jest.fn(), - set: jest.fn(), - }; - mockAuditService = { - log: jest.fn(), - }; - - service = new RBACService( - mockRepository, - mockCacheService, - mockAuditService - ); - }); - - describe('checkPermission', () => { - it('should return true if user has permission (cache hit)', async () => { - mockCacheService.get.mockResolvedValue(['users:create:*', 'posts:read:*']); - - const result = await service.checkPermission('user1', 'users', 'create'); - - expect(result).toBe(true); - expect(mockCacheService.get).toHaveBeenCalledWith('user:user1:permissions'); - expect(mockRepository.getUserRoles).not.toHaveBeenCalled(); // Cache hit - expect(mockAuditService.log).toHaveBeenCalledWith( - 'ACCESS_GRANTED', - 'user1', - { resource: 'users', action: 'create' } - ); - }); - - it('should return false if user lacks permission (cache miss)', async () => { - mockCacheService.get.mockResolvedValue(null); // Cache miss - mockRepository.getUserRoles.mockResolvedValue(['user']); - mockRepository.getRolePermissions.mockResolvedValue(['posts:read:*']); - mockRepository.getUserPermissions.mockResolvedValue([]); - - const result = await service.checkPermission('user1', 'users', 'delete'); - - expect(result).toBe(false); - expect(mockCacheService.set).toHaveBeenCalledWith( - 'user:user1:permissions', - ['posts:read:*'], - 300 - ); - expect(mockAuditService.log).toHaveBeenCalledWith( - 'ACCESS_DENIED', - 'user1', - { resource: 'users', action: 'delete' } - ); - }); - - it('should handle wildcard permissions', async () => { - mockCacheService.get.mockResolvedValue(['users:*:*']); - - const result = await service.checkPermission('user1', 'users', 'create'); - - expect(result).toBe(true); - }); - }); -}); -``` - -**Pattern Differences**: -1. **Multiple Dependencies**: IAM mocks repository, cache, audit -2. **Cache Behavior**: Tests cache hit and cache miss scenarios -3. **Audit Verification**: Ensures audit logs are created -4. **Complex Logic**: Tests wildcard permission matching - -**Documentation Impact**: -- Template docs: Simple mocking, basic test cases -- IAM docs: Complex mocking, cache behavior, audit verification - ---- - -## Summary Table - -| Pattern | Template | IAM | Docs to Update | -|---------|----------|-----|----------------| -| **Controller** | Basic try-catch | + Auth decorators, audit | `api-design.md`, `middleware-patterns.md` | -| **Service** | Simple logic | + Caching, complex logic | `service-layer-patterns.md`, `caching-patterns.md` | -| **Repository** | Basic CRUD | + Complex joins, aggregation | `repository-pattern.md`, `database-prisma.md` | -| **Middleware** | Basic logging | + Correlation IDs, audit | `middleware-patterns.md`, `observability-monitoring.md` | -| **Configuration** | Simple Zod | + Nested configs, secrets | `configuration-management.md` | -| **Testing** | Simple mocks | + Multi-dependency mocks | `testing-patterns.md` | -| **Caching** | None | Multi-layer (L1/L2/L3) | `caching-patterns.md` (NEW examples) | -| **Security** | Helmet only | + Zero-trust, encryption | `security.md` (NEW examples) | -| **Authorization** | None | RBAC + ABAC | NEW skill docs needed | -| **Audit Logging** | None | Event sourcing | `observability-monitoring.md` | - ---- - -## Recommended Documentation Updates - -### High Priority -1. **Update `caching-patterns.md`** with IAM multi-layer caching -2. **Update `security.md`** with zero-trust, encryption, JWT patterns -3. **Update `service-layer-patterns.md`** with caching integration -4. **Update `middleware-patterns.md`** with correlation IDs, audit -5. **Update `testing-patterns.md`** with complex mocking examples - -### Medium Priority -6. **Update `repository-pattern.md`** with complex joins -7. **Update `api-design.md`** with auth middleware patterns -8. **Update `configuration-management.md`** with secrets management -9. **Update `observability-monitoring.md`** with audit logging - -### New Content Needed -10. **RBAC patterns** (currently basic in user rules) -11. **Event sourcing** (audit logging implementation) -12. **Zero-trust architecture** (security validation) - ---- - -## Code Example Sources - -All code examples in docs should reference: -- **Template**: For foundational patterns -- **IAM Service**: For production patterns - -**Example Mapping**: -- `_template/src/modules/feature/feature.service.ts` → Basic service pattern -- `iam-service/src/modules/rbac/rbac.service.ts` → Advanced service with caching -- `iam-service/src/core/cache/multi-layer-cache.ts` → Caching implementation -- `iam-service/src/core/security/zero-trust-validator.ts` → Security patterns diff --git a/analysis/template-architecture.md b/analysis/template-architecture.md deleted file mode 100644 index 388b9b8d..00000000 --- a/analysis/template-architecture.md +++ /dev/null @@ -1,235 +0,0 @@ -# Template Architecture Analysis - -## Overview / Tổng quan - -**Service**: `_template` - Standard Microservice Template -**TypeScript Files**: 38 files -**Last Updated**: Dec 27, 2024 - -## Module Structure / Cấu trúc Module - -### Core Modules (4 modules) - -``` -src/modules/ -├── common/ # Shared utilities, base classes -├── feature/ # Example feature module (for demonstration) -├── health/ # Health check endpoints -└── metrics/ # Prometheus metrics -``` - -### Module Breakdown - -#### 1. Common Module -**Purpose**: Shared utilities and base classes for all modules -**Key Files**: -- `repository.ts` - Base repository pattern with Prisma -- `types.ts` - Shared TypeScript types - -#### 2. Feature Module (Example) -**Purpose**: Demonstrates standard module structure -**Key Files**: -- `feature.controller.ts` - Express route handlers -- `feature.service.ts` - Business logic layer -- `feature.repository.ts` - Data access via Prisma -- `feature.dto.ts` - Zod validation schemas -- `feature.module.ts` - Module wiring and router export -- `__tests__/` - Unit and E2E tests - -**Pattern**: -``` -Controller → Service → Repository → Prisma → PostgreSQL -``` - -#### 3. Health Module -**Purpose**: Kubernetes liveness/readiness probes -**Endpoints**: -- `GET /health` - Overall health check -- `GET /health/live` - Liveness probe (is process running?) -- `GET /health/ready` - Readiness probe (can serve traffic?) - -#### 4. Metrics Module -**Purpose**: Prometheus metrics exposure -**Endpoint**: -- `GET /metrics` - Prometheus format metrics -**Metrics**: -- HTTP request duration (histogram) -- HTTP request count (counter) -- Active requests (gauge) -- Error count (counter) - -## Middleware Stack / Stack Middleware - -```typescript -// Execution Order (from main.ts) -1. Correlation ID Middleware // Generate/propagate correlation IDs -2. Request Logger Middleware // Log incoming requests -3. Metrics Middleware // Track request metrics -4. Error Handler Middleware // Global error handling (LAST) -``` - -**Key Middlewares**: -- `correlation.middleware.ts` - Request tracing with x-correlation-id -- `logger.middleware.ts` - Structured logging with Winston -- `metrics.middleware.ts` - Prometheus instrumentation -- `error.middleware.ts` - Centralized error handling - -## Configuration / Cấu hình - -**Config Files** (with Zod validation): -- `app.config.ts` - App-level config (PORT, NODE_ENV, API_VERSION) -- `database.config.ts` - Prisma database configuration -- `redis.config.ts` - Redis cache configuration - -**Environment Variables**: -| Variable | Required | Description | -|----------|----------|-------------| -| `PORT` | No | Server port (default: 5000) | -| `NODE_ENV` | No | Environment (default: development) | -| `DATABASE_URL` | **Yes** | PostgreSQL connection string | -| `REDIS_URL` | No | Redis connection (default: redis://localhost:6379) | -| `SERVICE_NAME` | No | Service identifier | -| `API_VERSION` | No | API version (default: v1) | - -## Database Layer / Tầng Database - -**ORM**: Prisma -**Database**: PostgreSQL -**Pattern**: Repository Pattern with Base Repository - -**Example Model** (from prisma/schema.prisma): -```prisma -model Feature { - id String @id @default(cuid()) - name String @unique - description String? - enabled Boolean @default(true) - config Json? - tags String[] - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - @@map("features") -} -``` - -## API Routes / Routes API - -**Base Path**: `/api/v1` - -**Routing Strategy**: -```typescript -// src/routes/index.ts -/api/v1 - ├── /features → Feature Module - ├── /health → Health Module - └── /metrics → Metrics Module -``` - -## Testing Strategy / Chiến lược Testing - -**Test Structure**: -``` -src/ -├── modules/ -│ └── feature/ -│ └── __tests__/ -│ ├── feature.service.test.ts # Unit tests -│ └── feature.e2e.test.ts # E2E tests -└── __tests__/ - └── setupTests.ts # Test configuration -``` - -**Testing Stack**: -- **Framework**: Jest -- **E2E**: Supertest -- **Coverage**: 70%+ requirement - -## Observability / Khả năng quan sát - -### Logging -- **Library**: Winston -- **Format**: Structured JSON -- **Levels**: error, warn, info, debug -- **Context**: Correlation IDs in every log - -### Metrics -- **Library**: prom-client (Prometheus) -- **Endpoint**: `/metrics` -- **Types**: Counter, Gauge, Histogram - -### Tracing -- **Library**: OpenTelemetry (planned) -- **Backend**: Jaeger (optional) -- **Env Var**: `TRACING_ENABLED` - -## Docker Support / Hỗ trợ Docker - -**Dockerfile Features**: -- Multi-stage build (builder → runner) -- Non-root user (node:node) -- Production dependencies only -- Health check support - -**Image Size**: ~200MB (optimized) - -## Key Patterns Demonstrated / Patterns Chính - -1. **Controller-Service-Repository Pattern** - - Clear separation of concerns - - Testable layers - -2. **Dependency Injection via Constructor** - - Easy mocking for tests - - Clear dependencies - -3. **Zod Validation** - - Runtime type safety - - Environment validation - -4. **Error Handling** - - Custom error classes - - Global error middleware - -5. **Correlation IDs** - - Request tracing - - Distributed debugging - -## Security Features / Tính năng Bảo mật - -- **Helmet**: HTTP security headers -- **CORS**: Configurable CORS -- **Input Validation**: Zod schemas -- **SQL Injection Prevention**: Prisma ORM (parameterized queries) - -## Deployment Ready / Sẵn sàng Deploy - -- ✅ Dockerfile with multi-stage build -- ✅ Health check endpoints (K8s compatible) -- ✅ Prometheus metrics -- ✅ Structured logging -- ✅ Graceful shutdown -- ✅ Connection pooling (Prisma) - -## Gaps / Điểm còn thiếu - -Compared to full production service (iam-service): -- ❌ No caching layer (no Redis integration shown) -- ❌ No authentication middleware -- ❌ No rate limiting -- ❌ No circuit breaker pattern -- ❌ No event sourcing -- ❌ No advanced RBAC - -**Note**: These are intentionally omitted to keep template simple. They are demonstrated in `iam-service`. - -## Summary / Tóm tắt - -`_template` is a **minimal, production-ready microservice template** that demonstrates: -- Clean architecture (Controller-Service-Repository) -- TypeScript best practices -- Testing setup -- Basic observability (logging, metrics, health checks) -- Docker deployment - -It serves as a **starting point** for new services, with `iam-service` showing how to expand into a full production service with advanced features.