diff --git a/.cursor/skills/api-design/SKILL.md b/.agent/skills/api-design/SKILL.md similarity index 100% rename from .cursor/skills/api-design/SKILL.md rename to .agent/skills/api-design/SKILL.md diff --git a/.cursor/skills/api-design/references/REFERENCE.md b/.agent/skills/api-design/references/REFERENCE.md similarity index 100% rename from .cursor/skills/api-design/references/REFERENCE.md rename to .agent/skills/api-design/references/REFERENCE.md diff --git a/.cursor/skills/api-gateway-advanced/SKILL.md b/.agent/skills/api-gateway-advanced/SKILL.md similarity index 100% rename from .cursor/skills/api-gateway-advanced/SKILL.md rename to .agent/skills/api-gateway-advanced/SKILL.md diff --git a/.cursor/skills/api-gateway-advanced/references/REFERENCE.md b/.agent/skills/api-gateway-advanced/references/REFERENCE.md similarity index 100% rename from .cursor/skills/api-gateway-advanced/references/REFERENCE.md rename to .agent/skills/api-gateway-advanced/references/REFERENCE.md diff --git a/.cursor/skills/api-versioning-strategy/SKILL.md b/.agent/skills/api-versioning-strategy/SKILL.md similarity index 100% rename from .cursor/skills/api-versioning-strategy/SKILL.md rename to .agent/skills/api-versioning-strategy/SKILL.md diff --git a/.cursor/skills/caching-patterns/SKILL.md b/.agent/skills/caching-patterns/SKILL.md similarity index 100% rename from .cursor/skills/caching-patterns/SKILL.md rename to .agent/skills/caching-patterns/SKILL.md diff --git a/.cursor/skills/cicd-advanced-patterns/SKILL.md b/.agent/skills/cicd-advanced-patterns/SKILL.md similarity index 100% rename from .cursor/skills/cicd-advanced-patterns/SKILL.md rename to .agent/skills/cicd-advanced-patterns/SKILL.md diff --git a/.cursor/skills/comment-code/SKILL.md b/.agent/skills/comment-code/SKILL.md similarity index 100% rename from .cursor/skills/comment-code/SKILL.md rename to .agent/skills/comment-code/SKILL.md diff --git a/.cursor/skills/configuration-management/SKILL.md b/.agent/skills/configuration-management/SKILL.md similarity index 100% rename from .cursor/skills/configuration-management/SKILL.md rename to .agent/skills/configuration-management/SKILL.md diff --git a/.cursor/skills/data-consistency-patterns/SKILL.md b/.agent/skills/data-consistency-patterns/SKILL.md similarity index 100% rename from .cursor/skills/data-consistency-patterns/SKILL.md rename to .agent/skills/data-consistency-patterns/SKILL.md diff --git a/.cursor/skills/data-consistency-patterns/references/REFERENCE.md b/.agent/skills/data-consistency-patterns/references/REFERENCE.md similarity index 100% rename from .cursor/skills/data-consistency-patterns/references/REFERENCE.md rename to .agent/skills/data-consistency-patterns/references/REFERENCE.md diff --git a/.cursor/skills/database-prisma/SKILL.md b/.agent/skills/database-prisma/SKILL.md similarity index 100% rename from .cursor/skills/database-prisma/SKILL.md rename to .agent/skills/database-prisma/SKILL.md diff --git a/.cursor/skills/database-prisma/references/REFERENCE.md b/.agent/skills/database-prisma/references/REFERENCE.md similarity index 100% rename from .cursor/skills/database-prisma/references/REFERENCE.md rename to .agent/skills/database-prisma/references/REFERENCE.md diff --git a/.cursor/skills/deployment-kubernetes/SKILL.md b/.agent/skills/deployment-kubernetes/SKILL.md similarity index 100% rename from .cursor/skills/deployment-kubernetes/SKILL.md rename to .agent/skills/deployment-kubernetes/SKILL.md diff --git a/.cursor/skills/deployment-kubernetes/references/REFERENCE.md b/.agent/skills/deployment-kubernetes/references/REFERENCE.md similarity index 100% rename from .cursor/skills/deployment-kubernetes/references/REFERENCE.md rename to .agent/skills/deployment-kubernetes/references/REFERENCE.md diff --git a/.cursor/skills/documentation/SKILL.md b/.agent/skills/documentation/SKILL.md similarity index 100% rename from .cursor/skills/documentation/SKILL.md rename to .agent/skills/documentation/SKILL.md diff --git a/.cursor/skills/error-handling-patterns/SKILL.md b/.agent/skills/error-handling-patterns/SKILL.md similarity index 100% rename from .cursor/skills/error-handling-patterns/SKILL.md rename to .agent/skills/error-handling-patterns/SKILL.md diff --git a/.cursor/skills/event-driven-architecture/SKILL.md b/.agent/skills/event-driven-architecture/SKILL.md similarity index 100% rename from .cursor/skills/event-driven-architecture/SKILL.md rename to .agent/skills/event-driven-architecture/SKILL.md diff --git a/.cursor/skills/event-driven-architecture/references/REFERENCE.md b/.agent/skills/event-driven-architecture/references/REFERENCE.md similarity index 100% rename from .cursor/skills/event-driven-architecture/references/REFERENCE.md rename to .agent/skills/event-driven-architecture/references/REFERENCE.md diff --git a/.cursor/skills/infrastructure-as-code/SKILL.md b/.agent/skills/infrastructure-as-code/SKILL.md similarity index 100% rename from .cursor/skills/infrastructure-as-code/SKILL.md rename to .agent/skills/infrastructure-as-code/SKILL.md diff --git a/.cursor/skills/inter-service-communication/SKILL.md b/.agent/skills/inter-service-communication/SKILL.md similarity index 100% rename from .cursor/skills/inter-service-communication/SKILL.md rename to .agent/skills/inter-service-communication/SKILL.md diff --git a/.cursor/skills/inter-service-communication/references/REFERENCE.md b/.agent/skills/inter-service-communication/references/REFERENCE.md similarity index 100% rename from .cursor/skills/inter-service-communication/references/REFERENCE.md rename to .agent/skills/inter-service-communication/references/REFERENCE.md diff --git a/.cursor/skills/microservices-development-process/SKILL.md b/.agent/skills/microservices-development-process/SKILL.md similarity index 100% rename from .cursor/skills/microservices-development-process/SKILL.md rename to .agent/skills/microservices-development-process/SKILL.md diff --git a/.cursor/skills/microservices-development-process/references/REFERENCE.md b/.agent/skills/microservices-development-process/references/REFERENCE.md similarity index 100% rename from .cursor/skills/microservices-development-process/references/REFERENCE.md rename to .agent/skills/microservices-development-process/references/REFERENCE.md diff --git a/.cursor/skills/middleware-patterns/SKILL.md b/.agent/skills/middleware-patterns/SKILL.md similarity index 100% rename from .cursor/skills/middleware-patterns/SKILL.md rename to .agent/skills/middleware-patterns/SKILL.md diff --git a/.cursor/skills/observability-monitoring/SKILL.md b/.agent/skills/observability-monitoring/SKILL.md similarity index 100% rename from .cursor/skills/observability-monitoring/SKILL.md rename to .agent/skills/observability-monitoring/SKILL.md diff --git a/.cursor/skills/observability-monitoring/references/REFERENCE.md b/.agent/skills/observability-monitoring/references/REFERENCE.md similarity index 100% rename from .cursor/skills/observability-monitoring/references/REFERENCE.md rename to .agent/skills/observability-monitoring/references/REFERENCE.md diff --git a/.cursor/skills/performance-optimization/SKILL.md b/.agent/skills/performance-optimization/SKILL.md similarity index 100% rename from .cursor/skills/performance-optimization/SKILL.md rename to .agent/skills/performance-optimization/SKILL.md diff --git a/.cursor/skills/project-rules/SKILL.md b/.agent/skills/project-rules/SKILL.md similarity index 100% rename from .cursor/skills/project-rules/SKILL.md rename to .agent/skills/project-rules/SKILL.md diff --git a/.cursor/skills/repository-pattern/SKILL.md b/.agent/skills/repository-pattern/SKILL.md similarity index 100% rename from .cursor/skills/repository-pattern/SKILL.md rename to .agent/skills/repository-pattern/SKILL.md diff --git a/.cursor/skills/resilience-patterns/SKILL.md b/.agent/skills/resilience-patterns/SKILL.md similarity index 100% rename from .cursor/skills/resilience-patterns/SKILL.md rename to .agent/skills/resilience-patterns/SKILL.md diff --git a/.cursor/skills/security/SKILL.md b/.agent/skills/security/SKILL.md similarity index 100% rename from .cursor/skills/security/SKILL.md rename to .agent/skills/security/SKILL.md diff --git a/.cursor/skills/security/references/REFERENCE.md b/.agent/skills/security/references/REFERENCE.md similarity index 100% rename from .cursor/skills/security/references/REFERENCE.md rename to .agent/skills/security/references/REFERENCE.md diff --git a/.cursor/skills/service-discovery-registry/SKILL.md b/.agent/skills/service-discovery-registry/SKILL.md similarity index 100% rename from .cursor/skills/service-discovery-registry/SKILL.md rename to .agent/skills/service-discovery-registry/SKILL.md diff --git a/.cursor/skills/service-discovery-registry/references/REFERENCE.md b/.agent/skills/service-discovery-registry/references/REFERENCE.md similarity index 100% rename from .cursor/skills/service-discovery-registry/references/REFERENCE.md rename to .agent/skills/service-discovery-registry/references/REFERENCE.md diff --git a/.cursor/skills/service-layer-patterns/SKILL.md b/.agent/skills/service-layer-patterns/SKILL.md similarity index 100% rename from .cursor/skills/service-layer-patterns/SKILL.md rename to .agent/skills/service-layer-patterns/SKILL.md diff --git a/.cursor/skills/testing-patterns/SKILL.md b/.agent/skills/testing-patterns/SKILL.md similarity index 100% rename from .cursor/skills/testing-patterns/SKILL.md rename to .agent/skills/testing-patterns/SKILL.md diff --git a/.cursor/skills/testing-patterns/references/REFERENCE.md b/.agent/skills/testing-patterns/references/REFERENCE.md similarity index 100% rename from .cursor/skills/testing-patterns/references/REFERENCE.md rename to .agent/skills/testing-patterns/references/REFERENCE.md diff --git a/.cursor/plans/create_cursor_skills_14de746a.plan.md b/.cursor/plans/create_cursor_skills_14de746a.plan.md deleted file mode 100644 index 84c82d4a..00000000 --- a/.cursor/plans/create_cursor_skills_14de746a.plan.md +++ /dev/null @@ -1,450 +0,0 @@ ---- -name: Create Cursor Skills -overview: Create 5 comprehensive Cursor Skills (400-500 lines each, English only) covering testing, API design, database, observability, and Kubernetes deployment patterns based on existing codebase patterns. -todos: - - id: create-testing-skill - content: Create testing-patterns skill with Jest config, mocking strategies, and test examples - status: completed - - id: create-api-skill - content: Create api-design skill with RESTful patterns, DTO validation, and OpenAPI docs - status: completed - - id: create-database-skill - content: Create database-prisma skill with repository pattern, migrations, and query optimization - status: completed - - id: create-observability-skill - content: Create observability-monitoring skill with metrics, logging, tracing, and health checks - status: completed - - id: create-kubernetes-skill - content: Create deployment-kubernetes skill with K8s manifests, HPA, and deployment strategies - status: completed ---- - -# Create Comprehensive Cursor Skills - -## Overview - -Create 5 detailed Cursor Skills (400-500 lines each, English only) to codify best practices and patterns from the GoodGo microservices platform. Each skill will be based on actual code patterns found in the codebase. - -## Skills to Create - -### 1. testing-patterns - -**Location**: `.cursor/skills/testing-patterns/SKILL.md` - -**Content Structure**: - -- Jest configuration patterns (from [`services/_template/jest.config.ts`](services/_template/jest.config.ts)) -- Test setup utilities (from [`services/_template/src/__tests__/setupTests.ts`](services/_template/src/__tests__/setupTests.ts)) -- Unit testing patterns (from feature.service.test.ts, feature.repository.test.ts) -- Integration testing patterns (from health.controller.test.ts) -- E2E testing patterns (from feature.e2e.ts, health.e2e.ts) -- Mocking strategies: - - Prisma mocking - - Redis mocking - - Auth SDK mocking - - Logger mocking -- Test utilities (createMockReq, createMockRes, createMockNext) -- Coverage requirements (>70%) -- Common testing mistakes -- Debugging test failures - -**Key Patterns to Document**: - -```typescript -// Mock setup pattern -jest.mock('@goodgo/logger'); -jest.mock('../feature.repository'); - -// Test structure pattern -describe('FeatureService', () => { - beforeEach(() => { - jest.clearAllMocks(); - }); - - it('should create feature successfully', async () => { - // Arrange - const mockData = {...}; - (repository.create as jest.Mock).mockResolvedValue(mockData); - - // Act - const result = await service.create(input); - - // Assert - expect(repository.create).toHaveBeenCalledWith(input); - expect(result).toEqual(mockData); - }); -}); -``` - -### 2. api-design - -**Location**: `.cursor/skills/api-design/SKILL.md` - -**Content Structure**: - -- RESTful conventions (resource naming, HTTP methods) -- Response format standards (from existing API responses) -- Error response structure (from [`services/_template/src/errors/`](services/_template/src/errors/)) -- DTO validation with Zod (from [`services/_template/src/modules/feature/feature.dto.ts`](services/_template/src/modules/feature/feature.dto.ts)) -- Controller patterns (from feature.controller.ts) -- Route organization (from feature.module.ts) -- OpenAPI/Swagger documentation (from [`services/_template/src/docs/swagger.ts`](services/_template/src/docs/swagger.ts)) -- Pagination patterns -- Filtering and sorting -- API versioning (/api/v1/) -- Authentication headers -- Correlation ID propagation - -**Key Patterns to Document**: - -```typescript -// DTO with Zod -export const createFeatureDtoSchema = z.object({ - name: z.string().min(1).max(100), - title: z.string().max(200).optional(), -}); - -// Controller pattern -export class FeatureController { - async create(req: Request, res: Response, next: NextFunction) { - const dto = createFeatureDtoSchema.parse(req.body); - const result = await this.service.create(dto); - res.status(201).json({ success: true, data: result }); - } -} - -// Route with middleware -router.post('/', - authenticate(), - authorize('admin'), - validateDto(createFeatureDtoSchema), - asyncHandler(controller.create) -); -``` - -### 3. database-prisma - -**Location**: `.cursor/skills/database-prisma/SKILL.md` - -**Content Structure**: - -- Prisma schema conventions (from [`services/_template/prisma/schema.prisma`](services/_template/prisma/schema.prisma)) -- Migration workflow (dev vs production) -- Seeding strategies (from [`services/_template/prisma/seed.ts`](services/_template/prisma/seed.ts)) -- Repository pattern (from [`services/_template/src/modules/common/repository.ts`](services/_template/src/modules/common/repository.ts)) -- BaseRepository implementation -- Feature-specific repositories (from feature.repository.ts) -- Connection pooling with Neon -- Transaction handling -- Query optimization -- Error handling (DatabaseError) -- Soft delete pattern -- Prisma Client generation - -**Key Patterns to Document**: - -```typescript -// BaseRepository pattern -export class BaseRepository { - constructor( - protected prisma: PrismaClient, - protected modelName: string, - protected delegate: any - ) {} - - async findById(id: string): Promise { - try { - return await this.delegate.findUnique({ where: { id } }); - } catch (error: any) { - throw new DatabaseError(`Failed to find ${this.modelName}`, { id }); - } - } -} - -// Feature-specific repository -export class FeatureRepository extends BaseRepository { - async findByName(name: string): Promise { - return this.findByUnique({ name }); - } -} -``` - -### 4. observability-monitoring - -**Location**: `.cursor/skills/observability-monitoring/SKILL.md` - -**Content Structure**: - -- Prometheus metrics patterns (from [`services/_template/src/middlewares/metrics.middleware.ts`](services/_template/src/middlewares/metrics.middleware.ts)) -- Metric types (Counter, Gauge, Histogram, Summary) -- Custom metrics creation -- Correlation ID middleware (from correlation.middleware.ts) -- Structured logging patterns (from logger.middleware.ts) -- Jaeger tracing integration -- Health check patterns (liveness vs readiness) -- Prometheus configuration (from [`infra/observability/prometheus/prometheus.yml`](infra/observability/prometheus/prometheus.yml)) -- Grafana dashboard setup -- Loki log aggregation -- Alert rules -- Debugging with observability tools - -**Key Patterns to Document**: - -```typescript -// Metrics middleware pattern -const httpRequestDurationSeconds = new client.Histogram({ - name: 'http_request_duration_seconds', - help: 'Duration of HTTP requests in seconds', - labelNames: ['method', 'route', 'status_code', 'correlation_id'], - buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10], -}); - -// Correlation ID pattern -export const correlationMiddleware = () => { - return (req: Request, res: Response, next: NextFunction) => { - const correlationId = req.headers['x-correlation-id'] || generateCorrelationId(); - req.correlationId = correlationId; - res.setHeader('X-Correlation-ID', correlationId); - next(); - }; -}; - -// Health check pattern -export class HealthController { - async liveness(req: Request, res: Response) { - res.json({ status: 'ok', timestamp: new Date().toISOString() }); - } - - async readiness(req: Request, res: Response) { - const dbHealthy = await checkDatabaseConnection(); - const redisHealthy = await checkRedisConnection(); - res.json({ status: dbHealthy && redisHealthy ? 'ok' : 'degraded' }); - } -} -``` - -### 5. deployment-kubernetes - -**Location**: `.cursor/skills/deployment-kubernetes/SKILL.md` - -**Content Structure**: - -- Kubernetes manifest structure (from [`deployments/production/kubernetes/`](deployments/production/kubernetes/)) -- Deployment configuration -- Service types (ClusterIP, LoadBalancer) -- ConfigMap and Secrets management (from configmap.yaml, secrets.yaml.example) -- Ingress configuration (from ingress.yaml) -- HorizontalPodAutoscaler setup -- Resource limits and requests -- Health probes (liveness, readiness, startup) -- Rolling update strategy -- Environment variable management -- Multi-environment setup (staging vs production) -- Namespace organization -- Service discovery in K8s -- Troubleshooting K8s deployments - -**Key Patterns to Document**: - -```yaml -# Deployment with HPA -apiVersion: apps/v1 -kind: Deployment -metadata: - name: auth-service - namespace: production -spec: - replicas: 3 - template: - spec: - containers: - - name: auth-service - image: goodgo/auth-service:latest - resources: - requests: - memory: "512Mi" - cpu: "500m" - limits: - memory: "1Gi" - cpu: "1000m" - livenessProbe: - httpGet: - path: /health/live - port: 5001 - readinessProbe: - httpGet: - path: /health/ready - port: 5001 - ---- -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: auth-service-hpa -spec: - scaleTargetRef: - kind: Deployment - name: auth-service - minReplicas: 3 - maxReplicas: 10 - metrics: - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: 70 -``` - -## Implementation Plan - -### Skill Structure Template - -Each skill will follow this structure: - -```markdown ---- -name: skill-name -description: Brief description of when to use this skill ---- - -# Skill Title - -## When to Use This Skill - -Clear description of scenarios where this skill applies. - -## Core Concepts - -Key concepts and terminology. - -## Patterns and Best Practices - -### Pattern 1: Name - -**Purpose**: What this pattern solves -**When to Use**: Specific scenarios -**Implementation**: Code example -**Common Mistakes**: What to avoid - -### Pattern 2: Name - -[Same structure...] - -## Code Examples - -### Example 1: Scenario - -Full working example with explanation. - -### Example 2: Scenario - -[More examples...] - -## Common Mistakes - -List of anti-patterns and how to fix them. - -## Troubleshooting - -Common issues and solutions. - -## Checklist - -- [ ] Item 1 -- [ ] Item 2 - -## Resources - -Links to related docs and code. -``` - -## Content Sources - -Each skill will extract patterns from: - -1. **testing-patterns**: - - - `services/_template/jest.config.ts` - - `services/_template/src/__tests__/setupTests.ts` - - `services/_template/src/modules/feature/__tests__/*.test.ts` - - `services/_template/src/__tests__/*.e2e.ts` - -2. **api-design**: - - - `services/_template/src/modules/feature/feature.dto.ts` - - `services/_template/src/modules/feature/feature.controller.ts` - - `services/_template/src/modules/feature/feature.module.ts` - - `services/_template/src/docs/swagger.ts` - - `services/_template/src/errors/` - -3. **database-prisma**: - - - `services/_template/prisma/schema.prisma` - - `services/_template/prisma/seed.ts` - - `services/_template/src/modules/common/repository.ts` - - `services/_template/src/modules/feature/feature.repository.ts` - - `services/_template/src/config/database.config.ts` - -4. **observability-monitoring**: - - - `services/_template/src/middlewares/metrics.middleware.ts` - - `services/_template/src/middlewares/correlation.middleware.ts` - - `services/_template/src/middlewares/logger.middleware.ts` - - `services/_template/src/modules/health/health.controller.ts` - - `infra/observability/prometheus/prometheus.yml` - -5. **deployment-kubernetes**: - - - `deployments/production/kubernetes/auth-service.yaml` - - `deployments/production/kubernetes/configmap.yaml` - - `deployments/production/kubernetes/secrets.yaml.example` - - `deployments/production/kubernetes/ingress.yaml` - - `deployments/staging/kubernetes/` (for comparison) - -## Skill Features - -Each skill will include: - -- Clear "When to Use" section -- Real code examples from the codebase -- Common mistakes and anti-patterns -- Troubleshooting guide -- Checklist for implementation -- Links to related documentation -- Cross-references to other skills - -## Quality Standards - -- Length: 400-500 lines per skill -- Language: English only (technical content) -- Code examples: Working, tested patterns from codebase -- Format: Markdown with code blocks -- Structure: Consistent across all skills -- Practical: Focus on actionable patterns, not theory - -## Expected Outcomes - -After creating these skills, developers will have: - -1. Clear testing patterns for unit, integration, and E2E tests -2. Standardized API design with validation and documentation -3. Database best practices with Prisma and repository pattern -4. Observability setup for metrics, logging, and tracing -5. Kubernetes deployment patterns for production - -These skills will complement existing skills: - -- `project-rules`: General architecture and standards -- `documentation`: How to write docs -- `comment-code`: Bilingual code comments - -## Implementation Order - -1. `testing-patterns` - Most frequently used -2. `api-design` - Every new feature needs this -3. `database-prisma` - Database work is common -4. `observability-monitoring` - Important for debugging -5. `deployment-kubernetes` - Less frequent but critical - -Each skill will be self-contained and can be used independently. \ No newline at end of file diff --git a/.cursor/plans/enterprise_f5e39e08.plan.md b/.cursor/plans/enterprise_f5e39e08.plan.md deleted file mode 100644 index a480c144..00000000 --- a/.cursor/plans/enterprise_f5e39e08.plan.md +++ /dev/null @@ -1,1323 +0,0 @@ ---- -name: Enterprise Microservices -overview: Thiết lập cấu trúc thư mục enterprise-grade monorepo cho hệ thống microservices, bắt đầu với Auth Service, hỗ trợ Web + Mobile, và full infrastructure stack (Traefik, Observability, CI/CD). -todos: - - id: root-structure - content: Create root folder structure and workspace configuration - status: completed - - id: shared-packages - content: Setup shared packages (logger, types, config, http-client, auth-sdk, tracing) - status: completed - - id: auth-service - content: Create Auth Service with modules, database, and API endpoints - status: completed - - id: service-template - content: Create service template for future microservices - status: completed - - id: infrastructure - content: Setup Traefik, databases, and observability stack - status: completed - - id: web-app - content: Create Next.js web application with API integration - status: completed - - id: mobile-app - content: Create React Native mobile application - status: completed - - id: docker-configs - content: Create Docker and docker-compose configurations for all services - status: completed - - id: cicd-workflows - content: Setup GitHub Actions workflows for CI/CD - status: completed - - id: deployments - content: Create deployment configs for local, staging, and production - status: completed - - id: automation-scripts - content: Create helper scripts for development and deployment - status: completed - - id: documentation - content: Write comprehensive documentation and guides - status: completed ---- - -# Plan: Cấu trúc Microservices Enterprise-Grade - -## Tổng quan kiến trúc - -Dự án sẽ được tổ chức theo mô hình **monorepo** với các nguyên tắc: - -- Tách biệt rõ ràng: Apps - Services - Packages - Infra - Deployments -- Mỗi service deploy độc lập với CI/CD riêng -- Shared packages để tái sử dụng code -- Infrastructure as Code với Traefik + Docker + Observability -- Hỗ trợ cả Docker Compose (dev) và Kubernetes (prod) -```mermaid -graph TB - subgraph apps [Apps Layer] - web[Web App
NextJS] - mobile[Mobile App
React Native] - end - - subgraph gateway [API Gateway] - traefik[Traefik
Routing & Load Balancing] - end - - subgraph services [Services Layer] - auth[Auth Service
Node.js] - future[Future Services
Ready to add] - end - - subgraph packages [Shared Packages] - logger[Logger] - types[Types] - config[Config] - end - - subgraph infra [Infrastructure] - obs[Observability
Prometheus/Grafana/Loki] - db[Databases
PostgreSQL/Redis] - end - - web --> traefik - mobile --> traefik - traefik --> auth - traefik --> future - auth --> packages - auth --> db - future --> packages - obs --> auth - obs --> future -``` - - -## Cấu trúc thư mục chi tiết - -### 1. Root Level Structure - -Tạo cấu trúc thư mục gốc với các folder chính: - -``` -/Users/velikho/Desktop/WORKING/Base/ -├── apps/ # Frontend applications -├── services/ # Backend microservices -├── packages/ # Shared libraries & utilities -├── infra/ # Infrastructure as Code -├── deployments/ # Environment-specific configs -├── .github/ # CI/CD workflows -├── scripts/ # Automation scripts -├── docs/ # Documentation -├── .gitignore -├── .dockerignore -├── README.md -└── package.json # Root workspace config -``` - -### 2. Apps - Frontend Layer - -**[apps/web](apps/web)** - Next.js Web Application: - -``` -apps/web/ -├── public/ -├── src/ -│ ├── app/ # App router (Next.js 14+) -│ ├── components/ -│ │ ├── ui/ # Base UI components -│ │ ├── features/ # Feature-specific components -│ │ └── layouts/ # Layout components -│ ├── hooks/ # Custom React hooks -│ ├── services/ # API client services -│ │ ├── api/ -│ │ │ ├── auth.api.ts -│ │ │ └── client.ts -│ │ └── config.ts -│ ├── stores/ # State management (Zustand) -│ ├── styles/ # Global styles -│ ├── types/ # TypeScript types -│ └── utils/ # Helper functions -├── .env.example -├── .env.local -├── Dockerfile -├── docker-compose.dev.yml -├── next.config.js -├── package.json -├── tsconfig.json -└── README.md -``` - -**[apps/mobile](apps/mobile)** - React Native Application: - -``` -apps/mobile/ -├── src/ -│ ├── screens/ # Screen components -│ ├── components/ # Reusable components -│ ├── navigation/ # React Navigation -│ ├── services/ # API clients -│ ├── stores/ # State management -│ ├── hooks/ -│ ├── utils/ -│ └── types/ -├── ios/ -├── android/ -├── .env.example -├── Dockerfile # For CI builds -├── package.json -└── README.md -``` - -### 3. Services - Backend Microservices - -**[services/auth-service](services/auth-service)** - Authentication Service (Node.js + TypeScript): - -``` -services/auth-service/ -├── src/ -│ ├── modules/ # Feature modules -│ │ ├── auth/ -│ │ │ ├── auth.controller.ts -│ │ │ ├── auth.service.ts -│ │ │ ├── auth.dto.ts -│ │ │ └── auth.module.ts -│ │ ├── user/ -│ │ │ ├── user.controller.ts -│ │ │ ├── user.service.ts -│ │ │ ├── user.dto.ts -│ │ │ └── user.module.ts -│ │ └── health/ -│ ├── config/ # Service configuration -│ │ ├── database.config.ts -│ │ ├── jwt.config.ts -│ │ └── app.config.ts -│ ├── middlewares/ # Express middlewares -│ │ ├── auth.middleware.ts -│ │ ├── error.middleware.ts -│ │ └── logger.middleware.ts -│ ├── routes/ # API routes -│ ├── jobs/ # Background jobs -│ ├── utils/ -│ └── main.ts # Entry point -├── prisma/ # Database schema & migrations -│ ├── schema.prisma -│ ├── migrations/ -│ └── seed.ts -├── tests/ -│ ├── unit/ -│ └── integration/ -├── .env.example -├── Dockerfile -├── docker-compose.yml -├── package.json -├── tsconfig.json -└── README.md -``` - -**[services/_template](services/_template)** - Template cho services tương lai: - -- Sẵn sàng để copy và tạo services mới -- Chứa boilerplate code chuẩn - -### 4. Packages - Shared Libraries - -**[packages/logger](packages/logger)** - Centralized logging: - -```typescript -// packages/logger/src/index.ts -import winston from 'winston' -export const logger = winston.createLogger({...}) -``` - -**[packages/types](packages/types)** - Shared TypeScript types: - -```typescript -// packages/types/src/user.types.ts -export interface User { id: string; email: string; } -``` - -**[packages/config](packages/config)** - Shared configs: - -``` -packages/config/ -├── eslint-config/ # ESLint rules -├── tsconfig/ # TypeScript configs -└── prettier-config/ # Prettier rules -``` - -**[packages/http-client](packages/http-client)** - API client wrapper: - -```typescript -// packages/http-client/src/index.ts -import axios from 'axios' -export const createHttpClient = (baseURL: string) => {...} -``` - -**[packages/auth-sdk](packages/auth-sdk)** - Auth utilities: - -```typescript -// packages/auth-sdk/src/index.ts -export const verifyToken = (token: string) => {...} -``` - -**[packages/tracing](packages/tracing)** - OpenTelemetry setup: - -```typescript -// packages/tracing/src/index.ts -export const initTracing = (serviceName: string) => {...} -``` - -Cấu trúc packages: - -``` -packages/ -├── logger/ -├── types/ -├── config/ -├── http-client/ -├── auth-sdk/ -├── tracing/ -└── ui/ # Design system (optional) -``` - -### 5. Infrastructure - Traefik + Observability - -**[infra/traefik](infra/traefik)** - Traefik configuration: - -``` -infra/traefik/ -├── traefik.yml # Static configuration -├── dynamic/ # Dynamic configuration -│ ├── routes.yml # HTTP routing rules -│ ├── middlewares.yml # Rate limiting, CORS, etc -│ └── services.yml # Service definitions -├── certs/ # SSL certificates -└── README.md -``` - -Traefik routing example: - -```yaml -http: - routers: - auth-router: - rule: "Host(`api.goodgo.vn`) && PathPrefix(`/api/v1/auth`)" - service: auth-service - middlewares: - - auth-ratelimit - - cors -``` - -**[infra/docker](infra/docker)** - Docker configurations: - -``` -infra/docker/ -├── docker-compose.dev.yml # Development environment -├── docker-compose.prod.yml # Production environment -├── networks.yml # Docker networks -└── volumes.yml # Persistent volumes -``` - -**[infra/observability](infra/observability)** - Monitoring stack: - -``` -infra/observability/ -├── prometheus/ -│ ├── prometheus.yml -│ └── rules/ -├── grafana/ -│ ├── dashboards/ -│ │ ├── service-overview.json -│ │ └── auth-service.json -│ └── datasources/ -├── loki/ -│ └── loki-config.yml -└── docker-compose.observability.yml -``` - -**[infra/databases](infra/databases)** - Database configs: - -``` -infra/databases/ -├── postgres/ -│ ├── init.sql -│ └── postgres.conf -├── redis/ -│ └── redis.conf -└── docker-compose.databases.yml -``` - -**[infra/secrets](infra/secrets)** - Secrets management (not committed): - -``` -infra/secrets/ -├── .gitignore # Ignore all secrets -├── dev/ -│ └── .env.example -└── prod/ - └── .env.example -``` - -### 6. Deployments - Environment Configs - -**[deployments/local](deployments/local)** - Local development: - -``` -deployments/local/ -├── docker-compose.yml # Full stack for local dev -├── .env.local -└── README.md -``` - -**[deployments/staging](deployments/staging)** - Staging environment: - -``` -deployments/staging/ -├── kubernetes/ # K8s manifests -│ ├── auth-service.yaml -│ ├── ingress.yaml -│ └── configmap.yaml -├── helm/ # Helm charts (optional) -└── .env.staging -``` - -**[deployments/production](deployments/production)** - Production environment: - -``` -deployments/production/ -├── kubernetes/ -├── helm/ -└── .env.production -``` - -### 7. CI/CD - GitHub Actions - -**[.github/workflows](.github/workflows)** - CI/CD pipelines: - -``` -.github/ -├── workflows/ -│ ├── ci-web.yml # Web app CI -│ ├── ci-mobile.yml # Mobile app CI -│ ├── ci-auth-service.yml # Auth service CI -│ ├── docker-build.yml # Docker build & push -│ ├── deploy-staging.yml # Staging deployment -│ ├── deploy-production.yml # Production deployment -│ └── pr-checks.yml # PR validation -└── actions/ # Reusable actions - ├── setup-node/ - └── docker-build/ -``` - -CI/CD flow: - -```mermaid -graph LR - PR[Pull Request] --> Lint[Lint & Format] - Lint --> Test[Unit Tests] - Test --> Build[Build] - Build --> Docker[Docker Build] - Docker --> Push[Push to Registry] - Push --> Deploy[Deploy to Staging] - Deploy --> E2E[E2E Tests] -``` - -Example workflow structure: - -```yaml -# .github/workflows/ci-auth-service.yml -name: Auth Service CI -on: - push: - paths: - - 'services/auth-service/**' - pull_request: - paths: - - 'services/auth-service/**' -``` - -### 8. Scripts - Automation - -**[scripts](scripts)** - Helper scripts: - -``` -scripts/ -├── setup/ -│ ├── init-project.sh # Initial project setup -│ └── install-deps.sh # Install all dependencies -├── dev/ -│ ├── start-all.sh # Start all services -│ ├── start-service.sh # Start specific service -│ └── logs.sh # View service logs -├── db/ -│ ├── migrate.sh # Run migrations -│ ├── seed.sh # Seed databases -│ └── backup.sh # Backup databases -├── build/ -│ ├── build-all.sh # Build all services -│ └── build-service.sh # Build specific service -├── deploy/ -│ ├── deploy-staging.sh -│ └── deploy-prod.sh -└── utils/ - ├── create-service.sh # Generate new service from template - └── cleanup.sh # Cleanup temp files -``` - -### 9. Documentation - -**[docs](docs)** - System documentation: - -``` -docs/ -├── architecture/ -│ ├── system-design.md -│ ├── service-communication.md -│ ├── data-flow.md -│ └── diagrams/ -│ ├── system-architecture.png -│ └── auth-flow.png -├── api/ -│ ├── openapi/ -│ │ └── auth-service.yaml -│ └── postman/ -├── guides/ -│ ├── getting-started.md -│ ├── development.md -│ ├── deployment.md -│ └── troubleshooting.md -├── runbooks/ -│ ├── incident-response.md -│ └── rollback-procedure.md -└── onboarding/ - └── new-developer-guide.md -``` - -### 10. Root Configuration Files - -**Root level configs**: - -- `.gitignore` - Git ignore rules -- `.dockerignore` - Docker ignore rules -- `package.json` - Workspace configuration (npm/pnpm/yarn workspaces) -- `pnpm-workspace.yaml` - PNPM workspace config -- `turbo.json` - Turborepo configuration (optional) -- `README.md` - Project overview -- `CONTRIBUTING.md` - Contribution guidelines -- `LICENSE` - License file - -## Nguyên tắc thiết kế chính - -### Separation of Concerns - -- **Apps**: Presentation layer (UI/UX) -- **Services**: Business logic (độc lập, scalable) -- **Packages**: Shared utilities (DRY principle) -- **Infra**: Infrastructure setup (IaC) -- **Deployments**: Environment configs (12-factor app) - -### Service Independence - -- Mỗi service có database riêng (Database per service pattern) -- Mỗi service có Dockerfile riêng -- Mỗi service có CI/CD pipeline riêng -- Services giao tiếp qua HTTP/gRPC hoặc message queue - -### Shared Packages Strategy - -```typescript -// Import từ shared packages -import { logger } from '@goodgo/logger' -import { User } from '@goodgo/types' -import { createHttpClient } from '@goodgo/http-client' -``` - -### Environment Management - -- Không commit secrets vào Git -- Sử dụng `.env.example` làm template -- Production secrets qua CI/CD secrets hoặc vault - -### CI/CD Strategy - -- Path-based triggers (chỉ build service thay đổi) -- Parallel builds cho các services độc lập -- Automated testing trước khi merge -- Automated deployment sau khi merge - -## Implementation Steps (High-level) - -Khi bắt đầu thực hiện, các bước chính sẽ là: - -1. **Setup Root Structure** - Tạo folders gốc và config files -2. **Setup Packages** - Tạo shared libraries trước -3. **Setup Auth Service** - Backend service đầu tiên -4. **Setup Infrastructure** - Traefik + Databases + Observability -5. **Setup Frontend** - Web app với Next.js -6. **Setup Mobile** - React Native app -7. **Setup CI/CD** - GitHub Actions workflows -8. **Setup Deployments** - Docker Compose + K8s configs -9. **Documentation** - README và guides -10. **Testing** - Verify toàn bộ hệ thống - -## Tech Stack Summary - -**Frontend:** - -- Web: Next.js 14+ (App Router), TypeScript, Tailwind CSS -- Mobile: React Native, TypeScript -- State: Zustand -- HTTP: Axios (wrapped trong shared package) - -**Backend:** - -- Auth Service: Node.js + TypeScript + Express/NestJS -- Database: PostgreSQL (Prisma ORM) -- Cache: Redis -- Future services: Mixed (Node.js + Python support) - -**Infrastructure:** - -- Reverse Proxy: Traefik -- Containers: Docker + Docker Compose -- Orchestration: Kubernetes (production) -- Monitoring: Prometheus + Grafana + Loki -- Tracing: OpenTelemetry - -**DevOps:** - -- CI/CD: GitHub Actions -- Registry: Docker Hub / GitHub Container Registry -- Secrets: GitHub Secrets / HashiCorp Vault - -## Expected File Structure Size - -Sau khi hoàn thành, cấu trúc sẽ có: - -- ~150-200 files -- ~50-70 configuration files -- ~20-30 Docker/compose files -- ~10-15 GitHub Actions workflows -- Full documentation suite - -## Monorepo Tooling Strategy - -### PNPM Workspaces (Khuyến nghị) - -**pnpm-workspace.yaml**: - -```yaml -packages: - - 'apps/*' - - 'services/*' - - 'packages/*' -``` - -**Root package.json**: - -```json -{ - "name": "@goodgo/monorepo", - "private": true, - "workspaces": [ - "apps/*", - "services/*", - "packages/*" - ], - "scripts": { - "dev": "pnpm --parallel -r dev", - "build": "pnpm -r build", - "test": "pnpm -r test", - "lint": "pnpm -r lint" - }, - "devDependencies": { - "typescript": "^5.3.0", - "prettier": "^3.1.0", - "eslint": "^8.56.0" - } -} -``` - -### Turborepo (Optional - Để tăng tốc build) - -**turbo.json**: - -```json -{ - "$schema": "https://turbo.build/schema.json", - "pipeline": { - "build": { - "dependsOn": ["^build"], - "outputs": ["dist/**", ".next/**"] - }, - "test": { - "dependsOn": ["build"], - "outputs": [] - }, - "lint": { - "outputs": [] - }, - "dev": { - "cache": false - } - } -} -``` - -## Security Best Practices - -### 1. Authentication & Authorization - -- JWT với refresh token rotation -- Rate limiting trên Traefik -- RBAC (Role-Based Access Control) -- API key management cho service-to-service - -### 2. Network Security - -```yaml -# Traefik middleware example -http: - middlewares: - secure-headers: - headers: - sslRedirect: true - stsSeconds: 31536000 - contentTypeNosniff: true - browserXssFilter: true - frameDeny: true - - rate-limit: - rateLimit: - average: 100 - burst: 50 -``` - -### 3. Secrets Management - -- Không commit `.env` files -- Sử dụng GitHub Secrets cho CI/CD -- Kubernetes Secrets cho production -- HashiCorp Vault cho enterprise (optional) - -### 4. Database Security - -- Connection pooling -- Prepared statements (Prisma tự động) -- Encryption at rest -- Regular backups - -## Performance Optimization - -### 1. Caching Strategy - -```typescript -// Redis caching layers -- API Response Cache (TTL: 5-60s) -- Session Cache (TTL: 24h) -- Database Query Cache (TTL: varies) -``` - -### 2. Database Optimization - -- Proper indexing -- Connection pooling -- Read replicas (future) -- Query optimization với Prisma - -### 3. API Gateway Optimization - -- Request compression (gzip) -- Response caching -- Load balancing -- Circuit breaker pattern - -## Monitoring & Alerting - -### Metrics to Track - -**Service Health**: - -- Uptime -- Response time (p50, p95, p99) -- Error rate -- Request rate - -**Infrastructure**: - -- CPU usage -- Memory usage -- Disk I/O -- Network I/O - -**Business Metrics**: - -- Active users -- API usage -- Feature adoption - -### Grafana Dashboards - -1. **System Overview Dashboard** - - - All services health - - Traffic overview - - Error rates - - Response times - -2. **Auth Service Dashboard** - - - Login attempts - - Token generation rate - - Failed authentications - - Active sessions - -3. **Database Dashboard** - - - Query performance - - Connection pool usage - - Slow queries - - Database size - -### Alerting Rules - -```yaml -# Prometheus alerting example -groups: - - name: service_alerts - rules: - - alert: HighErrorRate - expr: rate(http_requests_total{status=~"5.."}[5m]) > 0.05 - for: 5m - labels: - severity: critical - annotations: - summary: "High error rate detected" - - - alert: ServiceDown - expr: up == 0 - for: 1m - labels: - severity: critical - annotations: - summary: "Service is down" -``` - -## Testing Strategy - -### 1. Unit Tests - -- Coverage target: 80%+ -- Jest cho Node.js services -- React Testing Library cho frontend - -### 2. Integration Tests - -- API endpoint testing -- Database integration tests -- Service-to-service communication - -### 3. E2E Tests - -- Playwright/Cypress cho web -- Detox cho mobile -- Critical user flows - -### 4. Load Testing - -- K6 hoặc Artillery -- Performance benchmarks -- Stress testing scenarios - -## Database Design Principles - -### Auth Service Schema Example - -```prisma -// prisma/schema.prisma -generator client { - provider = "prisma-client-js" -} - -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} - -model User { - id String @id @default(uuid()) - email String @unique - passwordHash String - role Role @default(USER) - isActive Boolean @default(true) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - sessions Session[] - refreshTokens RefreshToken[] - - @@index([email]) - @@map("users") -} - -model Session { - id String @id @default(uuid()) - userId String - token String @unique - expiresAt DateTime - createdAt DateTime @default(now()) - - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - - @@index([userId]) - @@index([token]) - @@map("sessions") -} - -model RefreshToken { - id String @id @default(uuid()) - userId String - token String @unique - expiresAt DateTime - createdAt DateTime @default(now()) - - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - - @@index([userId]) - @@index([token]) - @@map("refresh_tokens") -} - -enum Role { - USER - ADMIN - SUPER_ADMIN -} -``` - -## API Design Standards - -### RESTful Endpoints Convention - -``` -Auth Service: -POST /api/v1/auth/register - Register new user -POST /api/v1/auth/login - Login user -POST /api/v1/auth/logout - Logout user -POST /api/v1/auth/refresh - Refresh access token -GET /api/v1/auth/me - Get current user -PUT /api/v1/auth/password - Change password -POST /api/v1/auth/forgot - Forgot password -POST /api/v1/auth/reset - Reset password - -User Management: -GET /api/v1/users - List users (admin) -GET /api/v1/users/:id - Get user by ID -PUT /api/v1/users/:id - Update user -DELETE /api/v1/users/:id - Delete user - -Health Check: -GET /health - Health check -GET /health/ready - Readiness probe -GET /health/live - Liveness probe -``` - -### Response Format Standard - -```typescript -// Success Response -{ - "success": true, - "data": { /* payload */ }, - "message": "Operation successful", - "timestamp": "2024-01-01T00:00:00.000Z" -} - -// Error Response -{ - "success": false, - "error": { - "code": "AUTH_001", - "message": "Invalid credentials", - "details": {} - }, - "timestamp": "2024-01-01T00:00:00.000Z" -} - -// Pagination Response -{ - "success": true, - "data": [ /* items */ ], - "pagination": { - "page": 1, - "limit": 20, - "total": 100, - "totalPages": 5 - }, - "timestamp": "2024-01-01T00:00:00.000Z" -} -``` - -## Environment Variables Template - -### Auth Service .env.example - -```bash -# Server Configuration -NODE_ENV=development -PORT=5001 -API_VERSION=v1 - -# Database -DATABASE_URL=postgresql://user:password@localhost:5432/auth_db?schema=public - -# Redis -REDIS_HOST=localhost -REDIS_PORT=6379 -REDIS_PASSWORD= - -# JWT Configuration -JWT_SECRET=your-super-secret-jwt-key-change-in-production -JWT_EXPIRES_IN=15m -JWT_REFRESH_SECRET=your-super-secret-refresh-key -JWT_REFRESH_EXPIRES_IN=7d - -# CORS -CORS_ORIGIN=http://localhost:3000,http://localhost:3001 - -# Logging -LOG_LEVEL=debug - -# External Services -EMAIL_SERVICE_URL=http://notification-service:5003 -EMAIL_FROM=noreply@goodgo.vn - -# Monitoring -PROMETHEUS_PORT=9090 -TRACING_ENABLED=true -JAEGER_ENDPOINT=http://jaeger:14268/api/traces -``` - -## Development Workflow - -### 1. Branch Strategy (Git Flow) - -``` -main (production) - └── develop (staging) - ├── feature/auth-login - ├── feature/user-profile - ├── bugfix/token-refresh - └── hotfix/security-patch -``` - -### 2. Commit Convention (Conventional Commits) - -```bash -feat: add login endpoint -fix: resolve token expiration issue -docs: update API documentation -refactor: restructure auth module -test: add unit tests for auth service -chore: update dependencies -ci: add GitHub Actions workflow -perf: optimize database queries -``` - -### 3. PR Process - -1. Create feature branch từ `develop` -2. Implement changes với tests -3. Run linter và tests locally -4. Push và create PR -5. CI/CD auto run checks -6. Code review -7. Merge vào `develop` (auto deploy staging) -8. QA testing trên staging -9. Merge vào `main` (manual deploy production) - -### 4. Local Development Commands - -```bash -# Install dependencies -pnpm install - -# Start all services -pnpm dev - -# Start specific service -pnpm --filter @goodgo/auth-service dev - -# Run tests -pnpm test - -# Run linter -pnpm lint - -# Build all -pnpm build - -# Database migrations -cd services/auth-service -pnpm prisma migrate dev - -# Seed database -pnpm prisma db seed -``` - -## Docker Best Practices - -### Multi-stage Build Example - -```dockerfile -# services/auth-service/Dockerfile -FROM node:20-alpine AS base -RUN apk add --no-cache libc6-compat -WORKDIR /app - -# Dependencies stage -FROM base AS deps -COPY package.json pnpm-lock.yaml ./ -RUN corepack enable pnpm && pnpm install --frozen-lockfile - -# Builder stage -FROM base AS builder -COPY --from=deps /app/node_modules ./node_modules -COPY . . -RUN pnpm prisma generate -RUN pnpm build - -# Production stage -FROM base AS runner -ENV NODE_ENV=production -RUN addgroup --system --gid 1001 nodejs -RUN adduser --system --uid 1001 microservice -USER microservice - -COPY --from=builder --chown=microservice:nodejs /app/dist ./dist -COPY --from=builder --chown=microservice:nodejs /app/node_modules ./node_modules -COPY --from=builder --chown=microservice:nodejs /app/package.json ./ - -EXPOSE 5001 -CMD ["node", "dist/main.js"] -``` - -### Docker Compose for Local Development - -```yaml -# deployments/local/docker-compose.yml -version: '3.8' - -services: - postgres: - image: postgres:16-alpine - environment: - POSTGRES_USER: devuser - POSTGRES_PASSWORD: devpass - POSTGRES_DB: auth_db - ports: - - "5432:5432" - volumes: - - postgres_data:/var/lib/postgresql/data - healthcheck: - test: ["CMD-SHELL", "pg_isready -U devuser"] - interval: 5s - timeout: 5s - retries: 5 - - redis: - image: redis:7-alpine - ports: - - "6379:6379" - volumes: - - redis_data:/data - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 5s - timeout: 3s - retries: 5 - - auth-service: - build: - context: ../../services/auth-service - dockerfile: Dockerfile - environment: - - DATABASE_URL=postgresql://devuser:devpass@postgres:5432/auth_db - - REDIS_HOST=redis - - NODE_ENV=development - ports: - - "5001:5001" - depends_on: - postgres: - condition: service_healthy - redis: - condition: service_healthy - volumes: - - ../../services/auth-service:/app - - /app/node_modules - - traefik: - image: traefik:v2.10 - command: - - "--api.insecure=true" - - "--providers.docker=true" - - "--entrypoints.web.address=:80" - ports: - - "80:80" - - "8080:8080" - volumes: - - /var/run/docker.sock:/var/run/docker.sock:ro - - ../../infra/traefik:/etc/traefik - -volumes: - postgres_data: - redis_data: -``` - -## Migration & Rollback Strategy - -### Database Migration - -```bash -# Create migration -pnpm prisma migrate dev --name add_user_table - -# Apply migrations (production) -pnpm prisma migrate deploy - -# Rollback (manual) -# Prisma không support auto rollback -# Cần tạo migration mới để reverse changes -``` - -### Service Rollback - -```bash -# Kubernetes rollback -kubectl rollout undo deployment/auth-service - -# Docker Compose rollback -docker-compose up -d --build auth-service:previous-tag - -# GitHub Actions manual rollback -# Re-run previous successful deployment workflow -``` - -## Scalability Considerations - -### Horizontal Scaling - -```yaml -# Kubernetes HPA example -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: auth-service-hpa -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: auth-service - minReplicas: 2 - maxReplicas: 10 - metrics: - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: 70 - - type: Resource - resource: - name: memory - target: - type: Utilization - averageUtilization: 80 -``` - -### Database Scaling - -- Read replicas cho read-heavy workloads -- Connection pooling (PgBouncer) -- Caching layer (Redis) -- Sharding (future consideration) - -### Caching Strategy - -```typescript -// Redis caching wrapper -import { Redis } from 'ioredis'; - -export class CacheService { - private redis: Redis; - - async get(key: string): Promise { - const data = await this.redis.get(key); - return data ? JSON.parse(data) : null; - } - - async set(key: string, value: any, ttl: number = 3600): Promise { - await this.redis.setex(key, ttl, JSON.stringify(value)); - } - - async del(key: string): Promise { - await this.redis.del(key); - } -} -``` - -## Cost Optimization - -### Development Environment - -- Use Docker Compose (free) -- Single VPS cho staging (~$10-20/month) -- Free tier databases (Neon, Supabase) - -### Production Environment - -- Kubernetes cluster (GKE/EKS) ~$50-100/month -- Managed databases ~$30-50/month -- CDN (Cloudflare) - Free tier -- Monitoring (Grafana Cloud) - Free tier -- Total estimate: $100-200/month initial - -## Next Steps - -Sau khi approve plan này, implementation sẽ bắt đầu với: - -1. **Phase 1: Foundation (Week 1)** - - - Tạo root structure và workspace config - - Setup shared packages với PNPM workspaces - - Configure ESLint, Prettier, TypeScript - -2. **Phase 2: Core Service (Week 2-3)** - - - Bootstrap Auth Service với full features - - Database setup với Prisma - - Unit & integration tests - -3. **Phase 3: Infrastructure (Week 3-4)** - - - Setup Traefik với routing rules - - Configure Prometheus, Grafana, Loki - - Docker Compose cho local dev - -4. **Phase 4: Frontend (Week 4-5)** - - - Create Next.js web app - - Create React Native mobile app - - API integration với auth service - -5. **Phase 5: CI/CD (Week 5-6)** - - - GitHub Actions workflows - - Docker build & push automation - - Deployment automation - -6. **Phase 6: Documentation (Week 6)** - - - API documentation (OpenAPI) - - Development guides - - Deployment runbooks - -**Total Timeline**: 6-8 weeks cho MVP đầy đủ chức năng \ No newline at end of file diff --git a/.cursor/plans/event-driven_architecture_skill_f267a3f0.plan.md b/.cursor/plans/event-driven_architecture_skill_f267a3f0.plan.md deleted file mode 100644 index 066174be..00000000 --- a/.cursor/plans/event-driven_architecture_skill_f267a3f0.plan.md +++ /dev/null @@ -1,405 +0,0 @@ ---- -name: Event-Driven Architecture Skill -overview: Tạo skill documentation chi tiết cho Event-Driven Architecture với Apache Kafka, bao gồm patterns cho event publishing/consuming, schema versioning, tích hợp Traefik để expose events qua HTTP (SSE/WebSocket), error handling, observability, và testing patterns phù hợp với GoodGo platform standards. -todos: - - id: create-skill-file - content: Tạo file .cursor/skills/event-driven-architecture/SKILL.md với structure cơ bản (header, When to Use, Core Concepts) - status: completed - - id: kafka-setup-section - content: Viết section Kafka Setup & Configuration (infrastructure, client config, connection management) - status: completed - - id: publishing-patterns - content: Viết Event Publishing Patterns section (Publisher class, outbox pattern, best practices) - status: completed - - id: consuming-patterns - content: Viết Event Consuming Patterns section (Consumer class, DLQ, processing strategies) - status: completed - - id: schema-versioning - content: Viết Schema Versioning section (Schema Registry, Avro, evolution strategies) - status: completed - - id: traefik-integration - content: Viết Traefik Integration section (SSE endpoints, WebSocket, routing config) - status: completed - - id: error-resilience - content: Viết Error Handling & Resilience section (error patterns, retries, DLQ, replay) - status: completed - - id: observability - content: Viết Observability section (logging events, metrics, tracing) - status: completed - - id: testing-patterns - content: Viết Testing Patterns section (unit, integration, E2E với test containers) - status: completed - - id: best-practices-examples - content: Viết Best Practices section và Complete Examples (end-to-end flows) - status: completed - - id: review-integration - content: Review và ensure consistency với existing skills, add references, final polish - status: completed ---- - -# Event-Driven Architecture Skill Implementation Plan - -## Overview - -Tạo comprehensive skill documentation cho Event-Driven Architecture patterns sử dụng Apache Kafka làm message broker. Skill này sẽ cover event publishing, consuming, schema versioning, integration với Traefik (SSE/WebSocket), error handling, observability, và testing patterns theo chuẩn GoodGo. - -## Architecture Context - -**Tech Stack:** - -- **Message Broker**: Apache Kafka (high-throughput, streaming) -- **API Gateway**: Traefik (existing) - expose events qua HTTP/SSE/WebSocket -- **Schema Registry**: Confluent Schema Registry (Avro schemas) -- **Services**: Node.js/TypeScript microservices với Express -- **Libraries**: kafkajs (Node.js Kafka client), @goodgo/logger, @goodgo/tracing - -**Traefik Integration:** - -- Traefik vẫn giữ vai trò API Gateway cho synchronous HTTP/REST -- Thêm support expose event streams qua HTTP endpoints (Server-Sent Events / WebSocket) -- Services publish events vào Kafka, Traefik routes SSE/WebSocket requests tới event streaming endpoints - -## Files to Create/Update - -### Primary File - -- `.cursor/skills/event-driven-architecture/SKILL.md` - Main skill documentation (new) - -### Potential Updates (if needed) - -- `.cursor/skills/project-rules/SKILL.md` - Update infrastructure section to include Kafka -- `docs/en/architecture/service-communication.md` - Add event-driven communication section -- `docs/vi/architecture/service-communication.md` - Add event-driven communication section - -## Detailed Implementation Plan - -### Phase 1: Skill File Structure - -Tạo file `.cursor/skills/event-driven-architecture/SKILL.md` với structure: - -1. **Header Metadata** - - - name: event-driven-architecture - - description: Event-driven architecture patterns với Kafka - -2. **When to Use This Skill** section - - - Khi nào nên dùng event-driven patterns - - Use cases: async processing, decoupling services, event sourcing, CQRS - -3. **Core Concepts** - - - Event-driven vs request-response - - Kafka fundamentals (topics, partitions, consumer groups) - - Event schema versioning - - Traefik integration for event streaming - -### Phase 2: Kafka Setup & Configuration - -**Topics Covered:** - -- Kafka infrastructure setup (docker-compose, Kubernetes) -- KafkaJS client configuration -- Connection management và pooling -- Environment variables (KAFKA_BROKERS, KAFKA_CLIENT_ID, etc.) - -**Code Examples:** - -```typescript -// Kafka client setup -// Producer configuration -// Consumer configuration -// Connection error handling -``` - -### Phase 3: Event Publishing Patterns - -**Topics:** - -- Event structure và naming conventions -- Publisher service pattern -- Transactional publishing (outbox pattern) -- Idempotency keys -- Event correlation IDs -- Publishing best practices - -**Patterns:** - -- Simple event publisher -- Transactional publisher với outbox pattern -- Batch publishing -- Error handling và retries - -**Code Examples:** - -```typescript -// EventPublisher class -// Publishing events from services -// Outbox pattern implementation -// Event metadata (correlationId, traceId, timestamp) -``` - -### Phase 4: Event Consuming Patterns - -**Topics:** - -- Consumer service patterns -- Consumer groups và partition assignment -- Processing strategies (at-least-once, exactly-once) -- Commit strategies -- Dead letter queue (DLQ) pattern -- Consumer error handling - -**Patterns:** - -- Simple consumer -- Batch consumer -- Transactional consumer -- DLQ handling -- Retry patterns với exponential backoff - -**Code Examples:** - -```typescript -// EventConsumer class -// Consumer group management -// Message processing với error handling -// DLQ implementation -``` - -### Phase 5: Schema Versioning & Registry - -**Topics:** - -- Schema Registry setup (Confluent) -- Avro schema definitions -- Schema evolution (backward/forward compatible) -- Schema versioning strategy -- Schema validation - -**Code Examples:** - -```typescript -// Schema definitions -// Schema registry integration -// Schema evolution examples -// Validation patterns -``` - -### Phase 6: Traefik Integration (SSE/WebSocket) - -**Topics:** - -- Exposing events qua HTTP endpoints -- Server-Sent Events (SSE) pattern -- WebSocket support (optional) -- Traefik routing configuration -- Authentication/authorization cho event streams -- Rate limiting cho event streams - -**Patterns:** - -- SSE endpoint implementation -- Event filtering và subscription -- Connection management -- Traefik labels configuration - -**Code Examples:** - -```typescript -// SSE endpoint implementation -// Event stream service -// Traefik routing config -// Client subscription patterns -``` - -### Phase 7: Error Handling & Resilience - -**Topics:** - -- Event publishing failures -- Consumer error handling -- Retry strategies -- Circuit breaker cho Kafka operations -- Dead letter queue management -- Event replay patterns - -**Integration với existing skills:** - -- Reuse resilience-patterns (circuit breaker, retry) -- Reuse error-handling-patterns (custom errors) - -**Code Examples:** - -```typescript -// Error handling trong publisher -// Error handling trong consumer -// DLQ processing -// Event replay service -``` - -### Phase 8: Observability - -**Topics:** - -- Logging events (structured logging) -- Metrics (events published/consumed, lag, throughput) -- Distributed tracing với OpenTelemetry -- Health checks cho Kafka connectivity -- Monitoring consumer lag - -**Integration:** - -- Use @goodgo/logger -- Use @goodgo/tracing -- Prometheus metrics - -**Code Examples:** - -```typescript -// Event logging -// Metrics collection -// Tracing events -// Health check endpoints -``` - -### Phase 9: Testing Patterns - -**Topics:** - -- Unit testing publishers/consumers -- Integration testing với Kafka -- Test containers cho local testing -- Mocking Kafka trong tests -- E2E event flow testing - -**Code Examples:** - -```typescript -// Unit test examples -// Integration test setup -// Test containers usage -// Mocking strategies -``` - -### Phase 10: Best Practices & Patterns - -**Topics:** - -- Event naming conventions (`domain.action.version`) -- Topic naming (`domain.entity.action`) -- Partition key selection -- Event ordering guarantees -- Event size limits -- Performance optimization -- Common anti-patterns to avoid - -**Examples:** - -- Complete event flow example -- Service integration examples -- Real-world use cases - -### Phase 11: Documentation Examples - -**Complete Examples:** - -1. UserCreated event flow (Auth Service → Notification Service) -2. OrderPlaced event với multiple consumers -3. SSE endpoint với filtering -4. Outbox pattern implementation -5. Event replay scenario - -**Integration Examples:** - -- Service publishing events -- Service consuming events -- Traefik routing SSE endpoints -- Error recovery flows - -## Skill File Structure (Detailed Outline) - -```markdown ---- -name: event-driven-architecture -description: Event-driven architecture patterns with Apache Kafka for GoodGo microservices. Use when implementing async communication, event publishing/consuming, event sourcing, CQRS, or integrating event streams with HTTP endpoints. ---- - -# Event-Driven Architecture Patterns - -## When to Use This Skill -[Use cases và scenarios] - -## Core Concepts -[Event-driven fundamentals, Kafka basics, Traefik integration] - -## Kafka Setup & Configuration -[Infrastructure, client setup, configuration] - -## Event Publishing Patterns -[Publisher patterns, outbox pattern, best practices] - -## Event Consuming Patterns -[Consumer patterns, DLQ, processing strategies] - -## Schema Versioning -[Schema Registry, Avro, evolution strategies] - -## Traefik Integration (SSE/WebSocket) -[Exposing events via HTTP, SSE endpoints, routing] - -## Error Handling & Resilience -[Error patterns, retries, DLQ, replay] - -## Observability -[Logging, metrics, tracing events] - -## Testing Patterns -[Unit, integration, E2E testing] - -## Best Practices -[Naming conventions, patterns, anti-patterns] - -## Complete Examples -[End-to-end examples] - -## Resources -[Links to related skills, docs] -``` - -## Key Design Decisions - -1. **Kafka over RabbitMQ**: User selected Kafka for high-throughput and streaming capabilities -2. **Traefik Integration**: Expose events via SSE/WebSocket through Traefik, keeping Traefik as API Gateway -3. **Schema Registry**: Use Confluent Schema Registry với Avro for schema versioning -4. **Outbox Pattern**: Include outbox pattern for transactional event publishing -5. **Consistency với existing skills**: Reuse patterns từ resilience-patterns, error-handling-patterns, observability-monitoring - -## Dependencies & Integration Points - -**Existing Skills to Reference:** - -- `resilience-patterns` - Circuit breaker, retry patterns -- `error-handling-patterns` - Error classes và handling -- `observability-monitoring` - Logging, metrics, tracing -- `middleware-patterns` - SSE endpoint middleware -- `project-rules` - Coding standards, naming conventions - -**Infrastructure:** - -- Kafka cluster setup (docker-compose, K8s) -- Schema Registry setup -- Traefik configuration updates - -## Acceptance Criteria - -- [ ] Skill file created với comprehensive coverage -- [ ] All code examples are working và follow GoodGo patterns -- [ ] Bilingual comments (EN/VI) trong code examples -- [ ] Integration examples với Traefik SSE/WebSocket -- [ ] Error handling patterns documented -- [ ] Observability patterns documented -- [ ] Testing patterns documented -- [ ] References to related skills -- [ ] Complete end-to-end examples -- [ ] Consistent với existing skill format và style \ No newline at end of file diff --git a/.cursor/plans/fix_template_structure_870b6de9.plan.md b/.cursor/plans/fix_template_structure_870b6de9.plan.md deleted file mode 100644 index faa2512d..00000000 --- a/.cursor/plans/fix_template_structure_870b6de9.plan.md +++ /dev/null @@ -1,270 +0,0 @@ ---- -name: Fix Template Structure -overview: Restructure services/_template to align with microservices platform architecture by removing duplicate Docker/Traefik configs and refactoring ARCHITECTURE.md to focus on single service context with platform integration. -todos: - - id: delete-docker-compose - content: Delete docker-compose.yml and docker-compose.prod.yml from services/_template/ - status: completed - - id: delete-traefik-config - content: Delete services/_template/traefik/ directory - status: completed - - id: refactor-architecture-md - content: "Refactor ARCHITECTURE.md with clear sections: Single Service Architecture, Platform Integration, Deployment Context" - status: completed - - id: update-readme-deployment - content: Update README.md to remove Docker Development option and add Platform Integration section - status: completed - - id: update-readme-traefik - content: Update README.md Traefik references to point to infra/traefik/ and explain Docker labels - status: completed ---- - -# Fix Template Structure for Microservices Platform - -## Problem Summary - -The `services/_template` currently contains configurations that conflict with the platform-level setup: - -1. Docker Compose files that duplicate `deployments/local/docker-compose.yml` functionality -2. Traefik configuration that duplicates `infra/traefik/` global config -3. ARCHITECTURE.md that describes multi-service architecture instead of single service template - -## Proposed Changes - -### 1. Remove Docker Compose Files - -**Files to delete:** - -- [`services/_template/docker-compose.yml`](services/_template/docker-compose.yml) - Full environment setup (conflicts with deployments/local/) -- [`services/_template/docker-compose.prod.yml`](services/_template/docker-compose.prod.yml) - Production overrides (should be in deployments/) - -**File to keep:** - -- [`services/_template/docker-compose.test.yml`](services/_template/docker-compose.test.yml) - Isolated test environment (useful for CI/CD) - -**Rationale:** - -- Template services should be deployed via `deployments/local/docker-compose.yml` -- Individual services don't need their own compose files for orchestration -- Test compose file is legitimate for isolated testing - -### 2. Remove Duplicate Traefik Configuration - -**Directory to delete:** - -- `services/_template/traefik/` - Contains duplicate traefik.yml and dynamic.yml - -**Rationale:** - -- Traefik is a platform-level API Gateway managed at `infra/traefik/` -- Service discovery happens via Docker labels in `deployments/local/docker-compose.yml` -- Services don't configure Traefik directly; they register via labels - -**Example of correct pattern:** - -```yaml -# In deployments/local/docker-compose.yml -services: - my-service: - labels: - - "traefik.enable=true" - - "traefik.http.routers.my-service.rule=PathPrefix(`/api/v1/my-service`)" - - "traefik.http.services.my-service.loadbalancer.server.port=5000" -``` - -### 3. Refactor ARCHITECTURE.md - -**Current issues:** - -- Shows multi-service architecture (Auth, User, Product, Order, Payment) -- Mixes single service internals with platform-level concerns -- Unclear context about what the template represents - -**New structure:** - -```markdown -# Service Template Architecture - -## Part 1: Single Service Architecture (Internal) -- Component layers: Controller → Service → Repository -- Middleware chain: Correlation → Auth → Validation → Error → Logger → Metrics -- Data flow within one service -- Internal dependencies: Database, Redis, Jaeger client - -## Part 2: Platform Integration (External) -- How this service fits in the microservices platform -- Integration with Traefik API Gateway (via Docker labels) -- Shared infrastructure: Redis, PostgreSQL, Observability stack -- Service discovery and registration -- Inter-service communication patterns - -## Part 3: Deployment Context -- Reference to deployments/local/docker-compose.yml -- How to add this service to the platform -- Environment variables and configuration -``` - -**Diagrams to update:** - -1. **Internal Service Architecture** - Focus on single service layers -```mermaid -graph TD - Request[HTTP Request] --> Traefik[Traefik Gateway] - Traefik -->|Routes to Service| Middleware[Middleware Chain] - - subgraph SingleService[Single Service Boundary] - Middleware --> Correlation[Correlation ID] - Correlation --> Auth[Authentication] - Auth --> Validation[Validation] - Validation --> Router[Router] - Router --> Controller[Controller] - Controller --> Service[Service Layer] - Service --> Repository[Repository] - Repository --> Database[(PostgreSQL)] - Service --> Cache[(Redis)] - end - - Service -.->|Metrics| Prometheus[Prometheus] - Service -.->|Traces| Jaeger[Jaeger] -``` - -2. **Platform Integration** - Show how service fits in ecosystem -```mermaid -graph TD - Client[Client] --> Traefik[Traefik API Gateway] - - subgraph Platform[Microservices Platform] - Traefik --> AuthService[Auth Service] - Traefik --> YourService[Your Service from Template] - Traefik --> OtherService[Other Services] - - YourService --> SharedDB[(Shared PostgreSQL)] - YourService --> SharedRedis[(Shared Redis)] - - AuthService -.->|JWT Validation| YourService - end - - subgraph Observability[Observability Stack] - Prometheus[Prometheus] - Grafana[Grafana] - Jaeger[Jaeger] - Loki[Loki] - end - - YourService -.->|Metrics| Prometheus - YourService -.->|Traces| Jaeger - YourService -.->|Logs| Loki -``` - - -### 4. Update README.md References - -**Changes needed in [`services/_template/README.md`](services/_template/README.md):** - -1. Remove "Option 2: Docker Development" section (lines 73-91) - - - This references the deleted docker-compose.yml - - Replace with reference to platform deployment - -2. Update "Getting Started" section: - - - Point to `deployments/local/docker-compose.yml` for full platform - - Explain how to add this service to the platform - - Keep local development instructions (without docker-compose) - -3. Remove "Docker Compose Files" section (lines 472-476) - - - Only docker-compose.test.yml remains - -4. Update "Traefik API Gateway" section (lines 494+) - - - Remove references to local traefik/ directory - - Point to `infra/traefik/` for configuration - - Explain Docker labels for service registration - -**New section to add:** - -````markdown -## Adding This Service to the Platform - -### 1. Add to deployments/local/docker-compose.yml - -```yaml -services: - your-service: - build: - context: ../.. - dockerfile: services/your-service/Dockerfile - container_name: your-service-local - environment: - - NODE_ENV=development - - PORT=5002 - - DATABASE_URL=${DATABASE_URL} - - REDIS_HOST=redis - - JWT_SECRET=${JWT_SECRET} - depends_on: - redis: - condition: service_healthy - networks: - - microservices-network - labels: - - "traefik.enable=true" - - "traefik.http.routers.your-service.rule=PathPrefix(`/api/v1/your-service`)" - - "traefik.http.services.your-service.loadbalancer.server.port=5002" -```` - -### 2. Start the Platform - -```bash -cd deployments/local -docker-compose up -d -``` - -### 3. Access Your Service - -- API: http://localhost/api/v1/your-service -- Health: http://localhost/api/v1/your-service/health -- Docs: http://localhost/api/v1/your-service/api-docs - -``` - -## Implementation Steps - -1. Delete `services/_template/docker-compose.yml` -2. Delete `services/_template/docker-compose.prod.yml` -3. Delete `services/_template/traefik/` directory -4. Refactor `services/_template/ARCHITECTURE.md`: - - - Add clear section headers for Single Service vs Platform Integration - - Update diagrams to show correct context - - Add deployment context section - -5. Update `services/_template/README.md`: - - - Remove Docker Development option - - Remove Docker Compose Files section - - Update Traefik references - - Add "Adding This Service to the Platform" section - -6. Keep `services/_template/docker-compose.test.yml` for isolated testing - -## Files Affected - -- Delete: `services/_template/docker-compose.yml` -- Delete: `services/_template/docker-compose.prod.yml` -- Delete: `services/_template/traefik/traefik.yml` -- Delete: `services/_template/traefik/dynamic.yml` -- Modify: `services/_template/ARCHITECTURE.md` -- Modify: `services/_template/README.md` -- Keep: `services/_template/docker-compose.test.yml` -- Keep: `services/_template/Dockerfile` - -## Expected Outcome - -After these changes: - -1. Template structure clearly represents a single microservice -2. No confusion about deployment - services are added to `deployments/local/docker-compose.yml` -3. Traefik configuration is centralized at `infra/traefik/` -4. ARCHITECTURE.md clearly separates internal service architecture from platform integration -5. Developers understand how to use the template in the microservices platform context \ No newline at end of file diff --git a/.cursor/plans/iam_service_audit_plan_d8aad26f.plan.md b/.cursor/plans/iam_service_audit_plan_d8aad26f.plan.md deleted file mode 100644 index 053a8090..00000000 --- a/.cursor/plans/iam_service_audit_plan_d8aad26f.plan.md +++ /dev/null @@ -1,905 +0,0 @@ ---- -name: IAM Service Audit Plan -overview: "Kế hoạch kiểm tra toàn diện cho IAM Service bao gồm: logic nghiệp vụ, quy trình build, bảo mật, và triển khai môi trường dev/staging/production. Plan được chia thành 6 phases: Pre-deployment Audit, Security Fixes, Local Environment, Staging Deployment, Production Deployment, và Post-deployment." -todos: - - id: audit-auth-1 - content: "Review Authentication Module - Registration Flow: Check email validation, password hashing with bcrypt cost 12, user profile creation in services/iam-service/src/modules/auth/auth.service.ts" - status: completed - - id: audit-auth-2 - content: "Review Authentication Module - Login Flow: Check password verification, JWT generation (access + refresh), session creation, MFA integration in services/iam-service/src/modules/auth/auth.service.ts" - status: completed - - id: audit-auth-3 - content: "Review Authentication Module - Token Refresh: Check token family tracking, refresh token rotation, replay attack detection in services/iam-service/src/modules/token/jwt.service.ts" - status: completed - - id: audit-auth-4 - content: "Review Authentication Module - Password Change: Check refresh token revocation, audit logging in services/iam-service/src/modules/auth/change-password.service.ts" - status: completed - - id: audit-rbac-1 - content: "Review RBAC Module - Permission Resolution: Check hierarchy (Direct user → Role → Group → Policy) in services/iam-service/src/modules/rbac/rbac.service.ts" - status: completed - - id: audit-rbac-2 - content: "Review RBAC Module - Role Assignment: Check expiration handling in services/iam-service/src/modules/rbac/rbac.service.ts" - status: completed - - id: audit-rbac-3 - content: "Review RBAC Module - Policy Engine: Check JSON Logic implementation in services/iam-service/src/modules/rbac/policy.engine.ts" - status: completed - - id: audit-rbac-4 - content: "Review RBAC Module - Permission Caching: Verify 5 min TTL and cache invalidation in services/iam-service/src/core/cache/cache.service.ts" - status: completed - - id: audit-identity-1 - content: "Review Identity Module - User Management: Check CRUD operations, bulk import/export in services/iam-service/src/modules/identity/user/user.service.ts" - status: completed - - id: audit-identity-2 - content: "Review Identity Module - Profile Management: Check custom fields, avatar upload/delete in services/iam-service/src/modules/identity/profile/profile.service.ts" - status: completed - - id: audit-identity-3 - content: "Review Identity Module - Verification: Check email/phone/document verification flows in services/iam-service/src/modules/identity/verification/verification.service.ts" - status: completed - - id: audit-identity-4 - content: "Review Identity Module - Organizations: Check multi-tenant support, hierarchical structure in services/iam-service/src/modules/identity/organization/organization.service.ts" - status: completed - - id: audit-identity-5 - content: "Review Identity Module - Groups: Check member management, group-based permissions in services/iam-service/src/modules/identity/group/group.service.ts" - status: completed - - id: audit-access-1 - content: "Review Access Module - Access Requests: Check workflow, approval chains, JIT access in services/iam-service/src/modules/access/request/request.service.ts" - status: completed - - id: audit-access-2 - content: "Review Access Module - Access Reviews: Check certification campaigns, automated cleanup in services/iam-service/src/modules/access/review/review.service.ts" - status: completed - - id: audit-access-3 - content: "Review Access Module - Access Analytics: Check usage tracking, risk identification in services/iam-service/src/modules/access/analytics/analytics.service.ts" - status: completed - - id: audit-mfa-1 - content: "Review MFA Module - TOTP: Check TOTP implementation using speakeasy library in services/iam-service/src/modules/mfa/mfa.service.ts" - status: completed - - id: audit-mfa-2 - content: "Review MFA Module - QR Code: Check QR code generation in services/iam-service/src/modules/mfa/mfa.service.ts" - status: completed - - id: audit-mfa-3 - content: "Review MFA Module - WebAuthn: Check WebAuthn support in services/iam-service/src/modules/mfa/mfa.service.ts" - status: completed - - id: audit-mfa-4 - content: "Review MFA Module - Multiple Devices: Check multiple devices per user support in services/iam-service/src/modules/mfa/mfa.service.ts" - status: completed - - id: audit-mfa-5 - content: "Review MFA Module - Recovery Flow: Verify MFA recovery flow exists (NOTE: Currently missing, needs review)" - status: completed - - id: audit-social-1 - content: "Review Social Authentication Module: Check Google/Facebook/GitHub OAuth flows, account linking, token refresh in services/iam-service/src/modules/social/social.service.ts" - status: completed - - id: audit-oidc-1 - content: "Review OIDC Provider Module: Check discovery endpoint, authorization code flow, token exchange, JWKS endpoint in services/iam-service/src/modules/oidc/oidc-provider.service.ts" - status: completed - - id: audit-session-1 - content: "Review Session Management Module: Check device fingerprinting, session expiration, revocation, activity tracking in services/iam-service/src/modules/session/session.service.ts" - status: completed - - id: audit-governance-1 - content: "Review Governance Module: Check compliance reporting (GDPR, SOC2, ISO27001), policy management, risk scoring in services/iam-service/src/modules/governance/" - status: completed - - id: audit-cache-1 - content: "Review Cache Service: Check multi-layer caching (L1: Memory, L2: Redis, L3: DB), cache warming, invalidation in services/iam-service/src/core/cache/cache.service.ts" - status: completed - - id: audit-events-1 - content: "Review Event Sourcing: Check audit logging for all security events, 7-year retention in services/iam-service/src/core/events/" - status: completed - - id: audit-build-1 - content: "Run TypeScript typecheck: cd services/iam-service && pnpm typecheck - Verify no TypeScript errors" - status: completed - - id: audit-build-2 - content: "Run TypeScript build: cd services/iam-service && pnpm build - Verify build succeeds, check for unused variables/imports" - status: completed - - id: audit-build-3 - content: "Verify Type Safety: Check type safety for Prisma models, verify path aliases (@/*) working correctly" - status: completed - - id: audit-lint-1 - content: "Run ESLint: cd services/iam-service && pnpm lint - Verify coding standards compliance" - status: completed - - id: audit-lint-2 - content: "Check Code Quality: Verify no console.log in production code, proper error handling, no security anti-patterns" - status: completed - - id: audit-prisma-1 - content: "Generate Prisma Client: cd services/iam-service && pnpm prisma:generate - Verify generation succeeds" - status: completed - - id: audit-prisma-2 - content: "Validate Prisma Schema: Verify schema syntax valid, all relations properly defined, indexes optimized, migration files consistent" - status: completed - - id: audit-test-1 - content: "Run Unit Tests: cd services/iam-service && pnpm test:unit - Verify all unit tests pass" - status: completed - - id: audit-test-2 - content: "Run E2E Tests: cd services/iam-service && pnpm test:e2e - Verify all E2E tests pass" - status: completed - - id: audit-test-3 - content: "Generate Test Coverage: cd services/iam-service && pnpm test:coverage - Verify coverage >= 70% (branches, functions, lines, statements)" - status: completed - - id: audit-docker-1 - content: "Build Docker Image: docker build -t iam-service:test -f services/iam-service/Dockerfile . - Verify multi-stage build succeeds" - status: completed - - id: audit-docker-2 - content: "Verify Docker Image: Check image size <500MB, non-root user configured, health check functional" - status: completed - - id: security-mfa-1 - content: "CRITICAL: Create Encryption Service - Create services/iam-service/src/core/security/encryption.service.ts with encrypt/decrypt functions using crypto module" - status: completed - - id: security-mfa-2 - content: "CRITICAL: Update Schema for MFA Encryption - Update prisma/schema.prisma to support encrypted MFA secret fields (add encrypted field or use existing secret field with encryption layer)" - status: completed - - id: security-mfa-3 - content: "CRITICAL: Update MFA Service - Update services/iam-service/src/modules/mfa/mfa.service.ts to encrypt MFA secrets before saving and decrypt when reading" - status: completed - - id: security-refresh-1 - content: "CRITICAL: Hash Refresh Tokens - Update services/iam-service/src/modules/token/jwt.service.ts to hash refresh tokens (SHA-256) before storing in database" - status: completed - - id: security-refresh-2 - content: "CRITICAL: Update Refresh Token Validation - Update refresh token validation logic in jwt.service.ts to compare hashes instead of plaintext tokens" - status: completed - - id: security-jwt-1 - content: "CRITICAL: Block Default JWT Secrets - Update services/iam-service/src/config/jwt.config.ts to throw error if default secrets are used when NODE_ENV === 'production'" - status: completed - - id: security-input-1 - content: "MEDIUM: Install DOMPurify: cd services/iam-service && pnpm add dompurify @types/dompurify" - status: completed - - id: security-input-2 - content: "MEDIUM: Update Input Sanitization - Update services/iam-service/src/utils/helpers.ts sanitizeInput function to use DOMPurify instead of simple < > removal" - status: completed - - id: security-password-1 - content: "MEDIUM: Add Password Complexity Schema - Update services/iam-service/src/modules/auth/auth.dto.ts RegisterDto to enforce: uppercase, lowercase, numbers, symbols (minimum 8 characters)" - status: completed - - id: security-password-2 - content: "MEDIUM: Update Change Password Schema - Update services/iam-service/src/modules/auth/auth.dto.ts ChangePasswordDto to enforce same password complexity rules" - status: completed - - id: security-fingerprint-1 - content: "MEDIUM: Install FingerprintJS: cd services/iam-service && pnpm add @fingerprintjs/fingerprintjs" - status: completed - - id: security-fingerprint-2 - content: "MEDIUM: Update Device Fingerprinting - Update services/iam-service/src/modules/token/cookie.service.ts to use @fingerprintjs/fingerprintjs library instead of basic User-Agent + IP hash" - status: skipped - - id: security-lockout-1 - content: "MEDIUM: Add Lockout Fields to Schema - Update prisma/schema.prisma User model to add failedLoginAttempts (Int, default 0) and lockedUntil (DateTime?) fields" - status: completed - - id: security-lockout-2 - content: "MEDIUM: Create Account Lockout Service - Create services/iam-service/src/modules/auth/account-lockout.service.ts with lockout logic and exponential backoff" - status: completed - - id: security-lockout-3 - content: "MEDIUM: Update Auth Service for Lockout - Update services/iam-service/src/modules/auth/auth.service.ts to track failed attempts and check lockout status before login" - status: completed - - id: security-lockout-4 - content: "MEDIUM: Create Lockout Migration - Create Prisma migration for failedLoginAttempts and lockedUntil fields" - status: completed - - id: security-audit-1 - content: "LOW: Run npm audit: cd services/iam-service && npm audit - Review vulnerabilities" - status: completed - - id: security-audit-2 - content: "LOW: Fix npm vulnerabilities: cd services/iam-service && npm audit fix - Apply fixes for vulnerabilities" - status: completed - - id: security-cors-1 - content: "LOW: Review CORS Configuration - Check services/iam-service/src/main.ts CORS settings, verify necessity of credentials enabled" - status: pending - - id: security-social-1 - content: "LOW: Review Social Token Storage - Check services/iam-service/prisma/schema.prisma SocialAccount model, consider encryption for accessToken and refreshToken fields" - status: pending - - id: security-backup-1 - content: "LOW: Design MFA Backup Codes - Design backup codes generation and storage strategy for MFA recovery scenarios" - status: pending - - id: local-env-1 - content: "Copy Environment File: cp deployments/local/env.local.example deployments/local/.env.local" - status: completed - - id: local-env-2 - content: "Update DATABASE_URL: Set DATABASE_URL in deployments/local/.env.local to Neon PostgreSQL connection string" - status: completed - - id: local-env-3 - content: "Update REDIS_URL: Set REDIS_URL in deployments/local/.env.local to redis://localhost:6379" - status: completed - - id: local-env-4 - content: "Generate JWT Secrets: Generate new JWT_SECRET, JWT_REFRESH_SECRET, JWT_ID_SECRET (NOT defaults) and update deployments/local/.env.local" - status: completed - - id: local-env-5 - content: "Update Social Auth Credentials: Set Google/Facebook/GitHub OAuth credentials in deployments/local/.env.local" - status: skipped - - id: local-docker-1 - content: "Start Docker Compose: cd deployments/local && docker-compose up -d" - status: completed - - id: local-docker-2 - content: "Verify Docker Services: Check Traefik, IAM Service, Redis, PostgreSQL containers are running successfully" - status: completed - - id: local-migrate-1 - content: "Run Prisma Migrate: cd services/iam-service && pnpm prisma:migrate - Verify migrations apply successfully" - status: completed - - id: local-migrate-2 - content: "Run Prisma Seed: cd services/iam-service && pnpm prisma:seed - Verify seed data is created" - status: completed - - id: local-verify-1 - content: "Test Traefik Dashboard: Open http://localhost:8080 and verify Traefik dashboard loads" - status: completed - - id: local-verify-2 - content: "Test IAM Service: Open http://localhost:5001 and verify service is accessible" - status: completed - - id: local-verify-3 - content: "Test API Gateway: Test http://localhost/api/v1/auth endpoint" - status: completed - - id: local-verify-4 - content: "Test Redis: Verify Redis connection on localhost:6379" - status: completed - - id: local-health-1 - content: "Test Liveness Endpoint: curl http://localhost:5001/health/live - Verify returns 200 OK" - status: completed - - id: local-health-2 - content: "Test Readiness Endpoint: curl http://localhost:5001/health/ready - Verify returns 200 OK (includes DB check)" - status: completed - - id: local-health-3 - content: "Test Metrics Endpoint: curl http://localhost:5001/metrics - Verify Prometheus metrics are returned" - status: completed - - id: local-test-1 - content: "Test Registration Flow: Register new user via API, verify email validation, password hashing, profile creation" - status: completed - - id: local-test-2 - content: "Test Login Flow: Login with registered user, verify JWT tokens, session creation" - status: completed - - id: local-test-3 - content: "Test Logout Flow: Logout user, verify session revocation" - status: skipped - - id: local-test-4 - content: "Test Authorization: Test RBAC/ABAC permissions with different user roles" - status: skipped - - id: local-test-5 - content: "Test MFA: Test TOTP setup, QR code generation, WebAuthn if implemented" - status: skipped - - id: local-test-6 - content: "Test Social Login: Test Google/Facebook/GitHub OAuth flows" - status: skipped - - id: local-test-7 - content: "Review Logs and Metrics: Check application logs and Prometheus metrics for errors" - status: completed - - id: staging-k8s-1 - content: "Create Staging Namespace: kubectl create namespace staging" - status: skipped - - id: staging-k8s-2 - content: "Create Staging Secrets: kubectl create secret generic iam-service-secrets --from-literal=database-url='...' --from-literal=jwt-secret='...' --from-literal=jwt-refresh-secret='...' -n staging" - status: skipped - - id: staging-k8s-3 - content: "Apply Staging ConfigMap: kubectl apply -f deployments/staging/kubernetes/iam-service-configmap.yaml" - status: skipped - - id: staging-k8s-4 - content: "Deploy Staging Service: kubectl apply -f deployments/staging/kubernetes/iam-service.yaml" - status: skipped - - id: staging-k8s-5 - content: "Apply Staging Ingress: kubectl apply -f deployments/staging/kubernetes/ingress.yaml" - status: skipped - - id: staging-migrate-1 - content: "Run Staging Migrations: DATABASE_URL='postgresql://...' pnpm prisma:deploy - Verify migrations apply successfully" - status: skipped - - id: staging-verify-1 - content: "Check Staging Pods: kubectl get pods -n staging - Verify pods are running" - status: skipped - - id: staging-verify-2 - content: "Check Staging Logs: kubectl logs -f deployment/iam-service -n staging - Review logs for errors" - status: skipped - - id: staging-verify-3 - content: "Describe Staging Pod: kubectl describe pod -n staging - Verify pod status and events" - status: skipped - - id: staging-test-1 - content: "Run Staging Smoke Tests: Execute basic API endpoint tests (health, auth endpoints)" - status: skipped - - id: staging-test-2 - content: "Run Performance Tests: Execute performance tests on staging environment" - status: skipped - - id: staging-test-3 - content: "Run Load Tests: Execute load tests on staging environment" - status: skipped - - id: staging-test-4 - content: "Monitor Staging Logs: Monitor logs for errors during testing period" - status: skipped - - id: staging-test-5 - content: "Verify Staging Health Endpoints: Test /health/live and /health/ready endpoints on staging" - status: skipped - - id: prod-check-1 - content: "Pre-production: Verify security audit passed - Review all security fixes are implemented" - status: skipped - - id: prod-check-2 - content: "Pre-production: Verify staging tests passed - Confirm all staging tests are successful" - status: skipped - - id: prod-check-3 - content: "Pre-production: Backup Database - Create database backup before production deployment" - status: skipped - - id: prod-check-4 - content: "Pre-production: Generate Production Secrets - Generate STRONG NON-DEFAULT JWT secrets for production" - status: skipped - - id: prod-check-5 - content: "Pre-production: Verify Critical Security Fixes - Confirm all CRITICAL security fixes are implemented and tested" - status: skipped - - id: prod-k8s-1 - content: "Create Production Namespace: kubectl create namespace production" - status: skipped - - id: prod-k8s-2 - content: "Create Production Secrets: kubectl create secret generic iam-service-secrets --from-literal=database-url='...' --from-literal=jwt-secret='STRONG_SECRET' --from-literal=jwt-refresh-secret='STRONG_SECRET' --from-literal=jwt-id-secret='STRONG_SECRET' -n production" - status: skipped - - id: prod-k8s-3 - content: "Apply Production ConfigMap: kubectl apply -f deployments/production/kubernetes/iam-service-configmap.yaml" - status: skipped - - id: prod-k8s-4 - content: "Deploy Production Service: kubectl apply -f deployments/production/kubernetes/iam-service.yaml" - status: skipped - - id: prod-k8s-5 - content: "Deploy Production HPA: kubectl apply -f deployments/production/kubernetes/hpa.yaml" - status: skipped - - id: prod-k8s-6 - content: "Apply Production Ingress: kubectl apply -f deployments/production/kubernetes/ingress.yaml" - status: skipped - - id: prod-migrate-1 - content: "Run Production Migrations: DATABASE_URL='postgresql://...' pnpm prisma:deploy (safe deployment mode) - Verify migrations apply successfully" - status: skipped - - id: prod-monitor-1 - content: "Monitor Production Rollout: kubectl rollout status deployment/iam-service -n production - Verify deployment succeeds" - status: skipped - - id: prod-monitor-2 - content: "Check Production HPA: kubectl get hpa -n production - Verify HPA is configured correctly" - status: skipped - - id: prod-security-1 - content: "Production Security: Verify secrets NOT using defaults - Check all JWT secrets are strong and non-default" - status: skipped - - id: prod-security-2 - content: "Production Security: Verify TLS/SSL certificates configured - Check certificates are valid and configured" - status: skipped - - id: prod-security-3 - content: "Production Security: Verify network policies applied - Check Kubernetes network policies are in place" - status: skipped - - id: prod-security-4 - content: "Production Security: Verify pod security policies enabled - Check pod security policies are configured" - status: skipped - - id: prod-security-5 - content: "Production Security: Verify resource quotas set - Check resource quotas are configured for namespace" - status: skipped - - id: prod-security-6 - content: "Production Security: Verify RBAC configured - Check Kubernetes RBAC is properly configured" - status: skipped - - id: prod-security-7 - content: "Production Security: Verify monitoring alerts configured - Check Prometheus alerts are set up" - status: skipped - - id: prod-security-8 - content: "Production Security: Verify backup strategy in place - Confirm database backup strategy is implemented" - status: skipped - - id: post-monitor-1 - content: "Monitor Error Rates: Check error rates in monitoring dashboard, verify errors are within acceptable range" - status: skipped - - id: post-monitor-2 - content: "Monitor Response Times: Check API response times, verify performance metrics are acceptable" - status: skipped - - id: post-monitor-3 - content: "Check Security Events: Review audit logs for security events, verify no suspicious activities" - status: skipped - - id: post-monitor-4 - content: "Review Audit Logs: Review comprehensive audit logs for any anomalies" - status: skipped - - id: post-monitor-5 - content: "Verify Autoscaling: Monitor HPA scaling based on CPU/memory metrics, verify autoscaling works correctly" - status: skipped - - id: post-test-1 - content: "Test Failover Scenarios: Test pod failures, verify service remains available" - status: skipped - - id: post-test-2 - content: "Run Comprehensive Smoke Tests: Execute full smoke test suite on production" - status: skipped - - id: post-test-3 - content: "Verify Health Endpoints: Test /health/live and /health/ready endpoints on production" - status: skipped - - id: post-test-4 - content: "Test Authentication Flows: Test register, login, logout flows on production" - status: skipped - - id: post-test-5 - content: "Test Authorization Flows: Test RBAC/ABAC authorization on production" - status: skipped - - id: post-doc-1 - content: "Document Known Issues: Create document listing any known issues or limitations" - status: skipped - - id: post-doc-2 - content: "Create Operations Runbook: Create runbook with operational procedures, troubleshooting guides" - status: skipped - - id: post-doc-3 - content: "Update Deployment Procedures: Update deployment documentation with lessons learned" - status: skipped - - id: post-doc-4 - content: "Document Rollback Procedures: Document step-by-step rollback procedures for production" - status: skipped ---- - -# IAM Service Audit Plan - -## Tổng Quan (Overview) - -Kế hoạch kiểm tra toàn diện cho IAM Service với 6 phases chính: - -1. **Pre-deployment Audit**: Review logic nghiệp vụ, build, linting, testing -2. **Security Fixes (CRITICAL)**: Fix các lỗ hổng bảo mật nghiêm trọng -3. **Local Environment**: Setup và test môi trường local -4. **Staging Deployment**: Deploy và verify trên staging -5. **Production Deployment**: Deploy production với zero-downtime -6. **Post-deployment**: Monitor và validate sau deploy - ---- - -## Phase 1: Pre-deployment Audit - -### 1.1 Business Logic Review (10 Modules) - -**Authentication Module** (`services/iam-service/src/modules/auth/`) - -- Review registration flow: email validation, password hashing (bcrypt cost 12), user profile creation -- Review login flow: password verification, JWT generation (access + refresh), session creation, MFA integration -- Review token refresh: token family tracking, refresh token rotation, replay attack detection -- Review password change: refresh token revocation, audit logging - -**Authorization/RBAC Module** (`services/iam-service/src/modules/rbac/`) - -- Review permission resolution hierarchy: Direct user → Role → Group → Policy (ABAC) -- Review role assignment with expiration -- Review policy engine (JSON Logic) -- Validate permission caching (5 min TTL) và cache invalidation - -**Identity Management** (`services/iam-service/src/modules/identity/`) - -- User Management: CRUD operations, bulk import/export -- Profile Management: Custom fields, avatar upload/delete -- Verification: Email/phone/document verification flows -- Organizations: Multi-tenant support, hierarchical structure -- Groups: Member management, group-based permissions - -**Access Management** (`services/iam-service/src/modules/access/`) - -- Access Requests: Workflow, approval chains, JIT access -- Access Reviews: Certification campaigns, automated cleanup -- Access Analytics: Usage tracking, risk identification - -**Multi-Factor Authentication** (`services/iam-service/src/modules/mfa/`) - -- TOTP implementation (speakeasy library) -- QR code generation -- WebAuthn support -- Multiple devices per user -- MFA recovery flow (REVIEW REQUIRED - currently missing) - -**Social Authentication** (`services/iam-service/src/modules/social/`) - -- Google/Facebook/GitHub OAuth flows -- Account linking logic -- Token refresh for social providers -- Email verification bypass for verified social accounts - -**OIDC Provider** (`services/iam-service/src/modules/oidc/`) - -- Discovery endpoint -- Authorization code flow -- Token exchange -- JWKS endpoint - -**Session Management** (`services/iam-service/src/modules/session/`) - -- Device fingerprinting -- Session expiration -- Session revocation (single/all) -- Activity tracking - -**Governance & Compliance** (`services/iam-service/src/modules/governance/`) - -- Compliance reporting (GDPR, SOC2, ISO27001) -- Policy management và versioning -- Risk scoring (0-100) -- Audit reporting - -**Cache và Event Sourcing** (`services/iam-service/src/core/cache/`, `services/iam-service/src/core/events/`) - -- Multi-layer caching (L1: Memory, L2: Redis, L3: DB) -- Cache warming và invalidation -- Audit logging tất cả security events -- Event sourcing với 7-year retention - -### 1.2 Build & Error Checking - -**TypeScript Compilation** - -```bash -cd services/iam-service -pnpm typecheck # Type checking -pnpm build # Full build -``` - -- Verify: No TypeScript errors, no unused variables/imports, type safety for Prisma models, path aliases (@/*) working - -**Linting & Code Quality** - -```bash -pnpm lint -``` - -- Verify: Coding standards compliance, no console.log in production code, proper error handling, no security anti-patterns - -**Database Schema** - -```bash -pnpm prisma:generate # Generate Prisma client -pnpm prisma:validate # Validate schema (if available) -``` - -- Verify: Schema syntax valid, all relations properly defined, indexes optimized, migration files consistent - -**Testing** - -```bash -pnpm test:unit # Unit tests -pnpm test:e2e # E2E tests -pnpm test:coverage # Coverage report -``` - -- Target: Coverage >= 70% (branches, functions, lines, statements), all critical paths tested - -**Docker Build** - -```bash -docker build -t iam-service:test -f services/iam-service/Dockerfile . -``` - -- Verify: Multi-stage build successful, image size <500MB, non-root user configured, health check functional - ---- - -## Phase 2: Security Fixes (CRITICAL - Must Complete Before Production) - -### 2.1 CRITICAL Vulnerabilities (HIGH PRIORITY) - -**🔴 CRITICAL: MFA Secrets in Plaintext** - -- **Location**: `services/iam-service/prisma/schema.prisma` (lines 23, 234) -- **Issue**: `MFADevice.secret` và `User.mfaSecret` stored unencrypted -- **Fix**: Implement field-level encryption using crypto module (encrypt before save, decrypt on read) -- **Files to modify**: - - `prisma/schema.prisma` - Add encrypted field support - - Create `services/iam-service/src/core/security/encryption.service.ts` for encryption/decryption - - Update `services/iam-service/src/modules/mfa/mfa.service.ts` to use encryption - -**🔴 CRITICAL: Refresh Tokens in Plaintext** - -- **Location**: `services/iam-service/prisma/schema.prisma` (line 177) -- **Issue**: `RefreshToken.token` stored as plaintext -- **Fix**: Store hashed tokens (SHA-256), compare hash during validation -- **Files to modify**: - - Update `services/iam-service/src/modules/token/jwt.service.ts` to hash refresh tokens before storing - - Update refresh token validation logic - -**🔴 CRITICAL: Default JWT Secrets** - -- **Location**: `services/iam-service/src/config/jwt.config.ts` (lines 7, 11, 15) -- **Issue**: Default secrets not blocked in production -- **Fix**: Add production check that throws error if defaults are used -- **Files to modify**: - - `services/iam-service/src/config/jwt.config.ts` - Add production validation - -### 2.2 Medium Severity Issues - -**🟡 Weak Input Sanitization** - -- **Location**: `services/iam-service/src/utils/helpers.ts` (line 39) -- **Current**: Only removes `<` and `>` -- **Fix**: Use DOMPurify or proper HTML entity encoding - -**🟡 No Password Complexity Rules** - -- **Location**: `services/iam-service/src/modules/auth/auth.dto.ts` (line 9) -- **Current**: Only minimum 8 characters -- **Fix**: Enforce uppercase, lowercase, numbers, symbols - -**🟡 Simple Device Fingerprinting** - -- **Location**: `services/iam-service/src/modules/token/cookie.service.ts` (lines 117-126) -- **Current**: Basic User-Agent + IP hash -- **Fix**: Use @fingerprintjs/fingerprintjs library - -**🟡 Missing Account Lockout** - -- **Issue**: No protection after N failed login attempts -- **Fix**: Implement exponential backoff + account lockout -- **Files to create/modify**: - - Create `services/iam-service/src/modules/auth/account-lockout.service.ts` - - Update `services/iam-service/src/modules/auth/auth.service.ts` to track failed attempts - - Add `failedLoginAttempts` và `lockedUntil` fields to User model - -### 2.3 Low Severity Issues - -- No password history tracking -- CORS credentials enabled (review necessity) -- Social tokens in plaintext (consider encryption) -- No MFA backup codes -- Missing password breach checking (HaveIBeenPwned integration) - -### 2.4 OWASP Top 10 Review - -- A01: Broken Access Control - ✅ Well implemented via RBAC/ABAC -- A02: Cryptographic Failures - ❌ See vulnerabilities above -- A03: Injection - ✅ Protected by Prisma parameterized queries -- A04: Insecure Design - Review zero-trust implementation -- A05: Security Misconfiguration - Review Helmet.js settings -- A06: Vulnerable Components - Run `npm audit` -- A07: Auth Failures - ❌ Missing account lockout -- A08: Data Integrity Failures - Review JWT signature validation -- A09: Logging Failures - ✅ Comprehensive audit logging -- A10: SSRF - Review external API calls - ---- - -## Phase 3: Local Environment Setup - -### 3.1 Docker Compose Setup - -**Environment Configuration** - -- Copy `deployments/local/env.local.example` to `deployments/local/.env.local` -- Update environment variables: - - `DATABASE_URL` (Neon PostgreSQL) - - `REDIS_URL` - - `JWT_SECRET` (generate new, NOT default) - - `JWT_REFRESH_SECRET` (generate new) - - `JWT_ID_SECRET` (generate new) - - Social auth credentials - -**Start Services** - -```bash -cd deployments/local -docker-compose up -d -``` - -**Database Migrations** - -```bash -cd services/iam-service -pnpm prisma:migrate -pnpm prisma:seed -``` - -**Verify Services** - -- Traefik Dashboard: http://localhost:8080 -- IAM Service: http://localhost:5001 -- API Gateway: http://localhost/api/v1/auth -- Redis: localhost:6379 - -**Health Checks** - -```bash -curl http://localhost:5001/health/live # Liveness -curl http://localhost:5001/health/ready # Readiness (includes DB) -curl http://localhost:5001/metrics # Prometheus metrics -``` - -### 3.2 Functional Testing - -- Test authentication flows (register, login, logout) -- Test authorization (RBAC/ABAC) -- Test MFA (TOTP, WebAuthn) -- Test social login (Google, Facebook, GitHub) -- Review logs and metrics - ---- - -## Phase 4: Staging Deployment - -### 4.1 Kubernetes Setup - -**Prerequisites** - -- Kubernetes cluster configured -- kubectl installed và configured -- Docker images pushed to registry - -**Create Namespace** - -```bash -kubectl create namespace staging -``` - -**Create Secrets** - -```bash -kubectl create secret generic iam-service-secrets \ - --from-literal=database-url="postgresql://..." \ - --from-literal=jwt-secret="..." \ - --from-literal=jwt-refresh-secret="..." \ - -n staging -``` - -**Apply ConfigMap** - -```bash -kubectl apply -f deployments/staging/kubernetes/iam-service-configmap.yaml -``` - -**Deploy Service** - -```bash -kubectl apply -f deployments/staging/kubernetes/iam-service.yaml -``` - -**Apply Ingress** - -```bash -kubectl apply -f deployments/staging/kubernetes/ingress.yaml -``` - -**Run Migrations** - -```bash -DATABASE_URL="postgresql://..." pnpm prisma:deploy -``` - -**Verify Deployment** - -```bash -kubectl get pods -n staging -kubectl logs -f deployment/iam-service -n staging -kubectl describe pod -n staging -``` - -### 4.2 Configuration - -- Replicas: 2 -- Resources: Requests (256Mi memory, 250m CPU), Limits (512Mi memory, 500m CPU) -- Probes: Liveness (/health/live, 30s delay), Readiness (/health/ready, 10s delay) - -### 4.3 Testing - -- Smoke tests -- Performance testing -- Load testing -- Monitor logs for errors - ---- - -## Phase 5: Production Deployment - -### 5.1 Pre-deployment Checklist - -- Security audit passed -- Staging tests passed -- Backup database -- Configure production secrets (NON-DEFAULT VALUES) - -### 5.2 Kubernetes Setup - -**Create Namespace** - -```bash -kubectl create namespace production -``` - -**Create Secrets** - -```bash -kubectl create secret generic iam-service-secrets \ - --from-literal=database-url="postgresql://..." \ - --from-literal=jwt-secret="STRONG_PRODUCTION_SECRET" \ - --from-literal=jwt-refresh-secret="STRONG_PRODUCTION_REFRESH_SECRET" \ - --from-literal=jwt-id-secret="STRONG_PRODUCTION_ID_SECRET" \ - -n production -``` - -**Apply Production ConfigMap** - -```bash -kubectl apply -f deployments/production/kubernetes/iam-service-configmap.yaml -``` - -**Deploy with HPA** - -```bash -kubectl apply -f deployments/production/kubernetes/iam-service.yaml -kubectl apply -f deployments/production/kubernetes/hpa.yaml -``` - -**Apply Production Ingress** - -```bash -kubectl apply -f deployments/production/kubernetes/ingress.yaml -``` - -**Run Migrations (Safe Deployment)** - -```bash -DATABASE_URL="postgresql://..." pnpm prisma:deploy -``` - -**Monitor Rollout** - -```bash -kubectl rollout status deployment/iam-service -n production -kubectl get hpa -n production -``` - -### 5.3 Production Configuration - -- Replicas: 3 (min) → 10 (max) via HPA -- Resources: Requests (512Mi memory, 500m CPU), Limits (1Gi memory, 1000m CPU) -- Autoscaling: CPU target 70%, Memory target 80% -- Environment: `NODE_ENV=production`, `LOG_LEVEL=warn`, `TRACING_ENABLED=true` - -### 5.4 Security Checklist - -- ✅ Secrets NOT using defaults -- ✅ TLS/SSL certificates configured -- ✅ Network policies applied -- ✅ Pod security policies enabled -- ✅ Resource quotas set -- ✅ RBAC configured -- ✅ Monitoring alerts configured -- ✅ Backup strategy in place - ---- - -## Phase 6: Post-deployment - -### 6.1 Monitoring - -- Monitor error rates -- Monitor response times -- Check for security events -- Review audit logs -- Verify autoscaling works - -### 6.2 Testing - -- Test failover scenarios -- Run comprehensive smoke tests -- Verify health endpoints - -### 6.3 Documentation - -- Document known issues -- Create runbook for operations -- Update deployment procedures - ---- - -## Critical Files to Review/Modify - -### Security Fixes Required - -- `services/iam-service/prisma/schema.prisma` - Add encryption for sensitive fields -- `services/iam-service/src/config/jwt.config.ts` - Block defaults in production -- `services/iam-service/src/modules/auth/auth.dto.ts` - Password complexity -- `services/iam-service/src/modules/auth/auth.service.ts` - Account lockout -- `services/iam-service/src/utils/helpers.ts` - Input sanitization -- `services/iam-service/src/modules/token/cookie.service.ts` - Device fingerprinting - -### Deployment Configs - -- `deployments/local/docker-compose.yml` -- `deployments/staging/kubernetes/iam-service.yaml` -- `deployments/production/kubernetes/iam-service.yaml` -- `deployments/production/kubernetes/hpa.yaml` - ---- - -## Conclusion - -### Strengths - -- ✅ Clean architecture với separation of concerns -- ✅ Comprehensive business logic (10 modules) -- ✅ Multi-layered security (RBAC + ABAC + Zero-Trust) -- ✅ Excellent audit logging -- ✅ Production-ready deployment configs -- ✅ CI/CD automation -- ✅ Horizontal scaling support - -### Critical Issues to Address - -- ❌ Encrypt sensitive data at rest (MFA secrets, refresh tokens) -- ❌ Block default JWT secrets in production -- ❌ Implement account lockout -- ❌ Improve password policies -- ❌ Enhanced input sanitization - -### Recommendations - -- **Immediate**: Fix all HIGH severity security issues before production -- **Short-term**: Implement MEDIUM severity fixes within 2 weeks -- **Long-term**: Enhance with ML-based risk analysis, passwordless auth -- **Continuous**: Regular security audits, penetration testing, dependency updates \ No newline at end of file diff --git a/.cursor/plans/iam_service_migration_plan_fc0d64b3.plan.md b/.cursor/plans/iam_service_migration_plan_fc0d64b3.plan.md deleted file mode 100644 index 47d55073..00000000 --- a/.cursor/plans/iam_service_migration_plan_fc0d64b3.plan.md +++ /dev/null @@ -1,1390 +0,0 @@ ---- -name: IAM Service Migration Plan -overview: Kế hoạch chi tiết để chuyển đổi auth-service thành IAM service với các module mở rộng cho Identity Management, Access Management và Governance -todos: - - id: phase1-rename - content: "Phase 1: Rename service directory and update package.json, environment variables, main.ts, and deployment configs" - status: completed - - id: phase1-docs - content: "Phase 1: Update README.md, ARCHITECTURE files, and create IAM_PROPOSAL.md" - status: completed - - id: phase1-deploy - content: "Phase 1: Update docker-compose.yml and Kubernetes configs for iam-service" - status: completed - - id: phase2-schema - content: "Phase 2: Add Identity Management models (Organization, Group, UserProfile, IdentityVerification) to Prisma schema" - status: completed - - id: phase2-schema-access - content: "Phase 2: Add Access Management models (AccessRequest, AccessReview, AccessReviewItem) to Prisma schema" - status: completed - - id: phase2-schema-governance - content: "Phase 2: Add Governance models (ComplianceReport, PolicyTemplate, RiskScore) to Prisma schema" - status: completed - - id: phase2-migration - content: "Phase 2: Create and run Prisma migration, update seed script, generate Prisma client" - status: completed - - id: phase3-repositories - content: "Phase 3: Create repositories for Organization, Group, UserProfile, IdentityVerification, AccessRequest, AccessReview" - status: completed - - id: phase3-dtos - content: "Phase 3: Create DTOs (Zod schemas) for Identity, Access, and Governance modules" - status: completed - - id: phase4-user-lifecycle - content: "Phase 4: Implement User Lifecycle Management (service, controller, module) with CRUD, bulk operations, deactivation" - status: completed - - id: phase4-profile - content: "Phase 4: Implement Profile Management (service, controller, module) with avatar upload support" - status: completed - - id: phase4-verification - content: "Phase 4: Implement Identity Verification (service, controller, module) for email, phone, document verification" - status: completed - - id: phase4-org-group - content: "Phase 4: Implement Organization & Group Management (services, controllers, modules) with hierarchy support" - status: completed - - id: phase5-access-request - content: "Phase 5: Implement Access Request & Approval system (service, controller, module) with workflow support" - status: completed - - id: phase5-access-review - content: "Phase 5: Implement Access Review & Certification system (service, controller, module) with periodic reviews" - status: completed - - id: phase5-access-analytics - content: "Phase 5: Implement Access Analytics (service, controller, module) with usage stats and risk analysis" - status: completed - - id: phase6-compliance - content: "Phase 6: Implement Compliance Reporting (service, controller, module) with GDPR, SOC2, ISO27001 support" - status: completed - - id: phase6-policy - content: "Phase 6: Implement Policy Governance (service, controller, module) with versioning and templates" - status: completed - - id: phase6-risk - content: "Phase 6: Implement Risk Management (service, controller, module) with risk scoring and analysis" - status: completed - - id: phase6-reporting - content: "Phase 6: Implement Reporting Dashboard (service, controller, module) with access summary and security events" - status: completed - - id: phase7-routes - content: "Phase 7: Update routes/index.ts to integrate all new Identity, Access, and Governance endpoints while maintaining backward compatibility" - status: completed - - id: phase8-unit-tests - content: "Phase 8: Write unit tests for all repositories, services, and controllers" - status: pending - - id: phase8-integration-tests - content: "Phase 8: Write E2E tests for Identity, Access, and Governance workflows" - status: pending - - id: phase9-swagger - content: "Phase 9: Update Swagger/OpenAPI documentation with all new endpoints and schemas" - status: pending - - id: phase9-docs - content: "Phase 9: Update README, ARCHITECTURE docs, and create MIGRATION_GUIDE.md" - status: completed - - id: phase10-deploy - content: "Phase 10: Deploy to staging, run tests, then deploy to production with monitoring" - status: pending ---- - -# Kế Hoạch Chuyển Đổi Auth Service → IAM Service - -## Tổng Quan - -Plan này mô tả chi tiết các bước để chuyển đổi `auth-service` hiện tại thành `iam-service` với các tính năng mở rộng về Identity Management, Access Management, và Governance & Compliance. - -## Phạm Vi - -- **Rename service**: auth-service → iam-service -- **Database schema**: Thêm các models mới cho Identity, Access Management, Governance -- **Modules mới**: Identity, Access, Governance modules -- **Backward compatibility**: Giữ nguyên các API endpoints hiện tại -- **Deployment**: Update docker-compose, Kubernetes configs - ---- - -## Phase 1: Foundation & Renaming (Week 1) - -### 1.1 Service Rename - -**Tasks:** - -1. Rename service directory - - - `services/auth-service` → `services/iam-service` - -2. Update `package.json` - - - File: `services/iam-service/package.json` - - Change `name`: `"@goodgo/auth-service"` → `"@goodgo/iam-service"` - - Change `description`: Update to "Enterprise IAM (Identity and Access Management) Service" - -3. Update environment variables - - - File: `services/iam-service/.env.example` - - Change `SERVICE_NAME=auth-service` → `SERVICE_NAME=iam-service` - - Keep all other variables unchanged for backward compatibility - -4. Update `main.ts` - - - File: `services/iam-service/src/main.ts` - - Update service name in tracing initialization: `'auth-service'` → `'iam-service'` - -5. Update Dockerfile (if exists) - - - File: `services/iam-service/Dockerfile` - - Update any hardcoded service names - -### 1.2 Update Documentation Files - -**Tasks:** - -1. Update README.md - - - File: `services/iam-service/README.md` - - Change title: "Auth Service" → "IAM Service" - - Update description to include IAM scope - - Add migration notes section - -2. Update ARCHITECTURE files - - - Files: `services/iam-service/ARCHITECTURE.vi.md`, `ARCHITECTURE.en.md` - - Update service name references - - Add new IAM architecture sections (placeholder for now) - -3. Create IAM_PROPOSAL.md - - - File: `services/iam-service/IAM_PROPOSAL.md` - - Document IAM architecture proposal - - Include module structure and database schema changes - -### 1.3 Update Deployment Configurations - -**Tasks:** - -1. Update docker-compose.yml - - - File: `deployments/local/docker-compose.yml` - - Rename service: `auth-service` → `iam-service` - - Update container_name: `auth-service-local` → `iam-service-local` - - Update SERVICE_NAME env var - - Update Traefik labels: - - Router rule: Add `/api/v1/identity/*`, `/api/v1/access/*`, `/api/v1/governance/*` - - Keep existing `/api/v1/auth/*` routes for backward compatibility - -2. Update Kubernetes configs - - - Files: - - `deployments/staging/kubernetes/auth-service.yaml` → `iam-service.yaml` - - `deployments/production/kubernetes/auth-service.yaml` → `iam-service.yaml` - - Update all metadata names - - Update image name: `goodgo/auth-service` → `goodgo/iam-service` - - Update service names in ingress configs - -3. Update environment example files - - - Files: - - `deployments/local/env.local.example` - - `deployments/staging/env.staging.example` - - `deployments/production/env.production.example` - - Add new IAM-specific environment variables (with defaults) - ---- - -## Phase 2: Database Schema Extension (Week 2) - -### 2.1 Prisma Schema Extension - -**File**: `services/iam-service/prisma/schema.prisma` - -**Tasks:** - -1. **Add Identity Management Models** -```prisma -// Organization model -model Organization { - id String @id @default(cuid()) - name String - domain String? @unique - parentId String? - settings Json? - isActive Boolean @default(true) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - users User[] - groups Group[] - policies Policy[] - parent Organization? @relation("OrganizationHierarchy", fields: [parentId], references: [id]) - children Organization[] @relation("OrganizationHierarchy") - - @@index([domain]) - @@map("organizations") -} - -// Group model -model Group { - id String @id @default(cuid()) - name String - organizationId String? - description String? - isActive Boolean @default(true) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - organization Organization? @relation(fields: [organizationId], references: [id]) - members GroupMember[] - permissions GroupPermission[] - - @@unique([organizationId, name]) - @@index([organizationId]) - @@map("groups") -} - -// GroupMember model -model GroupMember { - id String @id @default(cuid()) - userId String - groupId String - role String @default("member") // member, admin - joinedAt DateTime @default(now()) - expiresAt DateTime? - - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) - - @@unique([userId, groupId]) - @@index([userId]) - @@index([groupId]) - @@map("group_members") -} - -// GroupPermission model -model GroupPermission { - id String @id @default(cuid()) - groupId String - permissionId String - createdAt DateTime @default(now()) - - group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) - permission Permission @relation(fields: [permissionId], references: [id], onDelete: Cascade) - - @@unique([groupId, permissionId]) - @@index([groupId]) - @@map("group_permissions") -} - -// UserProfile model -model UserProfile { - id String @id @default(cuid()) - userId String @unique - firstName String? - lastName String? - phone String? - phoneVerified Boolean @default(false) - avatarUrl String? - customFields Json? // Extended attributes - preferences Json? // User preferences - metadata Json? // Additional metadata - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - - @@index([phone]) - @@map("user_profiles") -} - -// IdentityVerification model -model IdentityVerification { - id String @id @default(cuid()) - userId String - type VerificationType - status VerificationStatus @default(PENDING) - method String? - token String? @unique // OTP token, verification code - verifiedAt DateTime? - expiresAt DateTime? - metadata Json? // Verification details - createdAt DateTime @default(now()) - - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - - @@index([userId, type]) - @@index([token]) - @@index([status]) - @@map("identity_verifications") -} - -enum VerificationType { - EMAIL - PHONE - DOCUMENT - BIOMETRIC -} - -enum VerificationStatus { - PENDING - VERIFIED - REJECTED - EXPIRED -} -``` - -2. **Add Access Management Models** -```prisma -// AccessRequest model -model AccessRequest { - id String @id @default(cuid()) - userId String - resource String - action String - reason String? - status RequestStatus @default(PENDING) - requestedAt DateTime @default(now()) - reviewedAt DateTime? - reviewedBy String? - expiresAt DateTime? - metadata Json? - - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - approvers AccessRequestApprover[] - - @@index([userId]) - @@index([status]) - @@index([resource]) - @@map("access_requests") -} - -enum RequestStatus { - PENDING - APPROVED - REJECTED - EXPIRED - CANCELLED -} - -// AccessRequestApprover model -model AccessRequestApprover { - id String @id @default(cuid()) - requestId String - approverId String - status ApprovalStatus @default(PENDING) - comments String? - reviewedAt DateTime? - - request AccessRequest @relation(fields: [requestId], references: [id], onDelete: Cascade) - - @@unique([requestId, approverId]) - @@index([approverId]) - @@map("access_request_approvers") -} - -enum ApprovalStatus { - PENDING - APPROVED - REJECTED -} - -// AccessReview model -model AccessReview { - id String @id @default(cuid()) - name String - description String? - type ReviewType - status ReviewStatus @default(DRAFT) - startDate DateTime - endDate DateTime - createdBy String - createdAt DateTime @default(now()) - completedAt DateTime? - - items AccessReviewItem[] - - @@index([status]) - @@index([type]) - @@map("access_reviews") -} - -enum ReviewType { - PERIODIC - ADHOC - CERTIFICATION -} - -enum ReviewStatus { - DRAFT - ACTIVE - COMPLETED - CANCELLED -} - -// AccessReviewItem model -model AccessReviewItem { - id String @id @default(cuid()) - reviewId String - userId String - resource String - access Json // Current access details - status ReviewItemStatus @default(PENDING) - reviewedBy String? - reviewedAt DateTime? - comments String? - - review AccessReview @relation(fields: [reviewId], references: [id], onDelete: Cascade) - - @@index([reviewId]) - @@index([userId]) - @@index([status]) - @@map("access_review_items") -} - -enum ReviewItemStatus { - PENDING - APPROVED - REVOKED - NO_CHANGE -} -``` - -3. **Add Governance Models** -```prisma -// ComplianceReport model -model ComplianceReport { - id String @id @default(cuid()) - type ComplianceType - name String - periodStart DateTime - periodEnd DateTime - status ReportStatus @default(DRAFT) - data Json? - generatedAt DateTime? - generatedBy String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - @@index([type]) - @@index([status]) - @@map("compliance_reports") -} - -enum ComplianceType { - GDPR - SOC2 - ISO27001 - HIPAA - CUSTOM -} - -enum ReportStatus { - DRAFT - GENERATED - PUBLISHED - ARCHIVED -} - -// PolicyTemplate model -model PolicyTemplate { - id String @id @default(cuid()) - name String - category PolicyCategory - description String? - content Json // Policy template structure - version String @default("1.0.0") - isActive Boolean @default(true) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - @@index([category]) - @@index([isActive]) - @@map("policy_templates") -} - -enum PolicyCategory { - SECURITY - ACCESS - COMPLIANCE - DATA - PRIVACY -} - -// RiskScore model -model RiskScore { - id String @id @default(cuid()) - userId String - score Int // 0-100 - level RiskLevel - factors Json // Risk factors - calculatedAt DateTime @default(now()) - - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - - @@index([userId]) - @@index([score]) - @@index([level]) - @@map("risk_scores") -} - -enum RiskLevel { - LOW - MEDIUM - HIGH - CRITICAL -} -``` - -4. **Update Existing User Model** -```prisma -// Add to existing User model -model User { - // ... existing fields ... - - // New relations - organizationId String? - organization Organization? @relation(fields: [organizationId], references: [id]) - profile UserProfile? - verifications IdentityVerification[] - accessRequests AccessRequest[] - riskScores RiskScore[] - groupMembers GroupMember[] -} -``` - - -### 2.2 Create Migration - -**Tasks:** - -1. Generate Prisma migration - - - Command: `cd services/iam-service && pnpm prisma migrate dev --name add_iam_models` - - This will create migration file in `prisma/migrations/` - -2. Update seed script - - - File: `services/iam-service/prisma/seed.ts` - - Add seed data for new models (organizations, groups, etc.) - -3. Update Prisma Client - - - Command: `pnpm prisma:generate` - - Verify types are generated correctly - ---- - -## Phase 3: Core Infrastructure Extensions (Week 3) - -### 3.1 Repository Layer Extensions - -**Tasks:** - -1. **Create Organization Repository** - - - File: `services/iam-service/src/repositories/organization.repository.ts` - - Extend `BaseRepository` from `modules/common/repository.ts` - - Methods: - - `findById(id: string)` - - `findByDomain(domain: string)` - - `findChildren(parentId: string)` - - `create(data: CreateOrganizationInput)` - - `update(id: string, data: UpdateOrganizationInput)` - - `delete(id: string)` - -2. **Create Group Repository** - - - File: `services/iam-service/src/repositories/group.repository.ts` - - Methods: - - `findById(id: string)` - - `findByOrganization(organizationId: string)` - - `findUserGroups(userId: string)` - - `addMember(groupId: string, userId: string, role: string)` - - `removeMember(groupId: string, userId: string)` - - `getMembers(groupId: string)` - -3. **Create User Profile Repository** - - - File: `services/iam-service/src/repositories/user-profile.repository.ts` - - Methods: - - `findByUserId(userId: string)` - - `create(userId: string, data: CreateProfileInput)` - - `update(userId: string, data: UpdateProfileInput)` - - `updateAvatar(userId: string, avatarUrl: string)` - -4. **Create Identity Verification Repository** - - - File: `services/iam-service/src/repositories/identity-verification.repository.ts` - - Methods: - - `findByToken(token: string)` - - `findByUserAndType(userId: string, type: VerificationType)` - - `create(data: CreateVerificationInput)` - - `updateStatus(id: string, status: VerificationStatus)` - -5. **Create Access Request Repository** - - - File: `services/iam-service/src/repositories/access-request.repository.ts` - - Methods: - - `findById(id: string)` - - `findByUser(userId: string)` - - `findPendingByUser(userId: string)` - - `create(data: CreateAccessRequestInput)` - - `updateStatus(id: string, status: RequestStatus)` - -6. **Create Access Review Repository** - - - File: `services/iam-service/src/repositories/access-review.repository.ts` - - Methods: - - `findById(id: string)` - - `findActive()` - - `findByStatus(status: ReviewStatus)` - - `create(data: CreateAccessReviewInput)` - - `getItems(reviewId: string)` - -7. **Update Repository Index** - - - File: `services/iam-service/src/repositories/index.ts` - - Export all new repositories - -### 3.2 DTO Definitions - -**Tasks:** - -1. **Identity DTOs** - - - File: `services/iam-service/src/modules/identity/identity.dto.ts` - - Zod schemas: - - `CreateOrganizationDto` - - `UpdateOrganizationDto` - - `CreateGroupDto` - - `UpdateGroupDto` - - `CreateUserProfileDto` - - `UpdateUserProfileDto` - - `VerificationRequestDto` - - `VerifyCodeDto` - -2. **Access DTOs** - - - File: `services/iam-service/src/modules/access/access.dto.ts` - - Zod schemas: - - `CreateAccessRequestDto` - - `ApproveAccessRequestDto` - - `RejectAccessRequestDto` - - `CreateAccessReviewDto` - - `ReviewAccessItemDto` - -3. **Governance DTOs** - - - File: `services/iam-service/src/modules/governance/governance.dto.ts` - - Zod schemas: - - `GenerateComplianceReportDto` - - `CreatePolicyTemplateDto` - - `CalculateRiskScoreDto` - ---- - -## Phase 4: Identity Management Module (Week 4-5) - -### 4.1 User Lifecycle Management - -**Tasks:** - -1. **Create User Management Service** - - - File: `services/iam-service/src/modules/identity/user/user.service.ts` - - Extend existing `AuthService` functionality - - Add methods: - - `getUser(userId: string)` - - `updateUser(userId: string, data: UpdateUserInput)` - - `deleteUser(userId: string)` (soft delete) - - `deactivateUser(userId: string)` - - `reactivateUser(userId: string)` - - `bulkImportUsers(file: Buffer, organizationId?: string)` - - `bulkExportUsers(filters: UserFilters)` - - `searchUsers(query: string, filters: UserFilters)` - -2. **Create User Management Controller** - - - File: `services/iam-service/src/modules/identity/user/user.controller.ts` - - Endpoints: - - `GET /api/v1/identity/users` - - `GET /api/v1/identity/users/:id` - - `PUT /api/v1/identity/users/:id` - - `DELETE /api/v1/identity/users/:id` - - `POST /api/v1/identity/users/:id/deactivate` - - `POST /api/v1/identity/users/:id/reactivate` - - `POST /api/v1/identity/users/bulk-import` - - `GET /api/v1/identity/users/bulk-export` - -3. **Create User Module** - - - File: `services/iam-service/src/modules/identity/user/user.module.ts` - - Wire up dependencies - -4. **Create Index File** - - - File: `services/iam-service/src/modules/identity/user/index.ts` - -### 4.2 Profile Management - -**Tasks:** - -1. **Create Profile Service** - - - File: `services/iam-service/src/modules/identity/profile/profile.service.ts` - - Methods: - - `getProfile(userId: string)` - - `updateProfile(userId: string, data: UpdateProfileInput)` - - `uploadAvatar(userId: string, file: Buffer, mimetype: string)` - - `deleteAvatar(userId: string)` - - `updatePreferences(userId: string, preferences: Json)` - -2. **Create Profile Controller** - - - File: `services/iam-service/src/modules/identity/profile/profile.controller.ts` - - Endpoints: - - `GET /api/v1/identity/users/:id/profile` - - `PUT /api/v1/identity/users/:id/profile` - - `POST /api/v1/identity/users/:id/profile/avatar` - - `DELETE /api/v1/identity/users/:id/profile/avatar` - -3. **Create Profile Module** - - - File: `services/iam-service/src/modules/identity/profile/profile.module.ts` - -### 4.3 Identity Verification - -**Tasks:** - -1. **Create Verification Service** - - - File: `services/iam-service/src/modules/identity/verification/verification.service.ts` - - Methods: - - `requestEmailVerification(userId: string)` - - `verifyEmail(token: string)` - - `requestPhoneVerification(userId: string, phone: string)` - - `verifyPhone(token: string)` - - `requestDocumentVerification(userId: string, document: Buffer)` - - `getVerificationStatus(userId: string, type: VerificationType)` - -2. **Create Verification Controller** - - - File: `services/iam-service/src/modules/identity/verification/verification.controller.ts` - - Endpoints: - - `POST /api/v1/identity/verification/email/request` - - `POST /api/v1/identity/verification/email/verify` - - `POST /api/v1/identity/verification/phone/request` - - `POST /api/v1/identity/verification/phone/verify` - - `POST /api/v1/identity/verification/document/upload` - - `GET /api/v1/identity/verification/:id/status` - -3. **Create Verification Module** - - - File: `services/iam-service/src/modules/identity/verification/verification.module.ts` - -4. **Add Email/SMS Service Integration** - - - Create config: `services/iam-service/src/config/notification.config.ts` - - Integrate with email service (SMTP) and SMS service - -### 4.4 Organization & Group Management - -**Tasks:** - -1. **Create Organization Service** - - - File: `services/iam-service/src/modules/identity/organization/organization.service.ts` - - Methods: - - `create(data: CreateOrganizationInput)` - - `getById(id: string)` - - `getByDomain(domain: string)` - - `update(id: string, data: UpdateOrganizationInput)` - - `delete(id: string)` - - `getChildren(parentId: string)` - - `getUsers(organizationId: string)` - - `addUser(organizationId: string, userId: string)` - - `removeUser(organizationId: string, userId: string)` - -2. **Create Organization Controller** - - - File: `services/iam-service/src/modules/identity/organization/organization.controller.ts` - - Endpoints: - - `GET /api/v1/identity/organizations` - - `POST /api/v1/identity/organizations` - - `GET /api/v1/identity/organizations/:id` - - `PUT /api/v1/identity/organizations/:id` - - `DELETE /api/v1/identity/organizations/:id` - - `GET /api/v1/identity/organizations/:id/users` - -3. **Create Group Service** - - - File: `services/iam-service/src/modules/identity/group/group.service.ts` - - Methods: - - `create(organizationId: string, data: CreateGroupInput)` - - `getById(id: string)` - - `getByOrganization(organizationId: string)` - - `update(id: string, data: UpdateGroupInput)` - - `delete(id: string)` - - `addMember(groupId: string, userId: string, role: string)` - - `removeMember(groupId: string, userId: string)` - - `getMembers(groupId: string)` - - `assignPermission(groupId: string, permissionId: string)` - - `revokePermission(groupId: string, permissionId: string)` - -4. **Create Group Controller** - - - File: `services/iam-service/src/modules/identity/group/group.controller.ts` - - Endpoints: - - `GET /api/v1/identity/organizations/:id/groups` - - `POST /api/v1/identity/organizations/:id/groups` - - `GET /api/v1/identity/groups/:id` - - `PUT /api/v1/identity/groups/:id` - - `DELETE /api/v1/identity/groups/:id` - - `GET /api/v1/identity/groups/:id/members` - - `POST /api/v1/identity/groups/:id/members` - - `DELETE /api/v1/identity/groups/:id/members/:userId` - -5. **Create Modules** - - - Files: - - `services/iam-service/src/modules/identity/organization/organization.module.ts` - - `services/iam-service/src/modules/identity/group/group.module.ts` - -6. **Create Identity Module Index** - - - File: `services/iam-service/src/modules/identity/index.ts` - - Export all identity modules - ---- - -## Phase 5: Access Management Module (Week 6-7) - -### 5.1 Access Request & Approval - -**Tasks:** - -1. **Create Access Request Service** - - - File: `services/iam-service/src/modules/access/request/request.service.ts` - - Methods: - - `createRequest(userId: string, data: CreateAccessRequestInput)` - - `getRequest(id: string)` - - `getUserRequests(userId: string)` - - `approveRequest(requestId: string, approverId: string, comments?: string)` - - `rejectRequest(requestId: string, approverId: string, comments?: string)` - - `cancelRequest(requestId: string, userId: string)` - - `getPendingApprovals(approverId: string)` - -2. **Create Access Request Controller** - - - File: `services/iam-service/src/modules/access/request/request.controller.ts` - - Endpoints: - - `GET /api/v1/access/requests` - - `POST /api/v1/access/requests` - - `GET /api/v1/access/requests/:id` - - `PUT /api/v1/access/requests/:id/approve` - - `PUT /api/v1/access/requests/:id/reject` - - `DELETE /api/v1/access/requests/:id` - -3. **Create Access Request Module** - - - File: `services/iam-service/src/modules/access/request/request.module.ts` - -### 5.2 Access Review & Certification - -**Tasks:** - -1. **Create Access Review Service** - - - File: `services/iam-service/src/modules/access/review/review.service.ts` - - Methods: - - `createReview(data: CreateAccessReviewInput)` - - `getReview(id: string)` - - `startReview(id: string)` - - `completeReview(id: string)` - - `getReviewItems(reviewId: string)` - - `reviewItem(itemId: string, reviewerId: string, status: ReviewItemStatus, comments?: string)` - - `getUserReviewItems(userId: string, reviewId: string)` - - `generateReviewItems(reviewId: string)` // Auto-generate based on current access - -2. **Create Access Review Controller** - - - File: `services/iam-service/src/modules/access/review/review.controller.ts` - - Endpoints: - - `GET /api/v1/access/reviews` - - `POST /api/v1/access/reviews` - - `GET /api/v1/access/reviews/:id` - - `PUT /api/v1/access/reviews/:id` - - `POST /api/v1/access/reviews/:id/start` - - `POST /api/v1/access/reviews/:id/complete` - - `GET /api/v1/access/reviews/:id/items` - - `PUT /api/v1/access/reviews/:id/items/:itemId/review` - -3. **Create Access Review Module** - - - File: `services/iam-service/src/modules/access/review/review.module.ts` - -### 5.3 Access Analytics - -**Tasks:** - -1. **Create Access Analytics Service** - - - File: `services/iam-service/src/modules/access/analytics/analytics.service.ts` - - Methods: - - `getUsageStats(period: DateRange)` - - `getPermissionDistribution()` - - `getUserAccessSummary(userId: string)` - - `getRiskAnalysis(filters: RiskFilters)` - - `getAccessTrends(period: DateRange)` - -2. **Create Access Analytics Controller** - - - File: `services/iam-service/src/modules/access/analytics/analytics.controller.ts` - - Endpoints: - - `GET /api/v1/access/analytics/usage` - - `GET /api/v1/access/analytics/permissions` - - `GET /api/v1/access/analytics/users/:id/summary` - - `GET /api/v1/access/analytics/risks` - -3. **Create Access Analytics Module** - - - File: `services/iam-service/src/modules/access/analytics/analytics.module.ts` - -4. **Create Access Module Index** - - - File: `services/iam-service/src/modules/access/index.ts` - - Export all access modules - ---- - -## Phase 6: Governance Module (Week 8-9) - -### 6.1 Compliance Reporting - -**Tasks:** - -1. **Create Compliance Service** - - - File: `services/iam-service/src/modules/governance/compliance/compliance.service.ts` - - Methods: - - `generateReport(type: ComplianceType, periodStart: Date, periodEnd: Date)` - - `getReport(id: string)` - - `getReports(filters: ReportFilters)` - - `exportReport(id: string, format: 'pdf' | 'csv' | 'json')` - - `publishReport(id: string)` - - `getGDPRReport(userId: string)` - - `getSOC2Report(periodStart: Date, periodEnd: Date)` - -2. **Create Compliance Controller** - - - File: `services/iam-service/src/modules/governance/compliance/compliance.controller.ts` - - Endpoints: - - `GET /api/v1/governance/compliance/reports` - - `POST /api/v1/governance/compliance/reports/generate` - - `GET /api/v1/governance/compliance/reports/:id` - - `GET /api/v1/governance/compliance/reports/:id/export` - - `POST /api/v1/governance/compliance/reports/:id/publish` - -3. **Create Compliance Module** - - - File: `services/iam-service/src/modules/governance/compliance/compliance.module.ts` - -### 6.2 Policy Governance - -**Tasks:** - -1. **Create Policy Governance Service** - - - File: `services/iam-service/src/modules/governance/policy/policy-governance.service.ts` - - Extend existing `Policy` model from RBAC - - Methods: - - `createTemplate(data: CreatePolicyTemplateInput)` - - `getTemplates(category?: PolicyCategory)` - - `createPolicyFromTemplate(templateId: string, data: CreatePolicyInput)` - - `getPolicyVersions(policyId: string)` - - `rollbackPolicy(policyId: string, version: string)` - - `testPolicy(policyId: string, testData: Json)` - - `validatePolicy(policy: Policy)` - -2. **Create Policy Governance Controller** - - - File: `services/iam-service/src/modules/governance/policy/policy-governance.controller.ts` - - Endpoints: - - `GET /api/v1/governance/policies/templates` - - `POST /api/v1/governance/policies/templates` - - `GET /api/v1/governance/policies/:id/versions` - - `POST /api/v1/governance/policies/:id/test` - - `POST /api/v1/governance/policies/:id/rollback` - -3. **Create Policy Governance Module** - - - File: `services/iam-service/src/modules/governance/policy/policy-governance.module.ts` - -### 6.3 Risk Management - -**Tasks:** - -1. **Create Risk Service** - - - File: `services/iam-service/src/modules/governance/risk/risk.service.ts` - - Methods: - - `calculateRiskScore(userId: string)` - - `getRiskScore(userId: string)` - - `getRiskScores(filters: RiskFilters)` - - `getRiskFactors(userId: string)` - - `getHighRiskUsers(threshold: number)` - - `updateRiskScore(userId: string, factors: RiskFactors)` - -2. **Create Risk Controller** - - - File: `services/iam-service/src/modules/governance/risk/risk.controller.ts` - - Endpoints: - - `GET /api/v1/governance/risk/scores` - - `GET /api/v1/governance/risk/scores/:userId` - - `POST /api/v1/governance/risk/calculate` - - `GET /api/v1/governance/risk/dashboard` - -3. **Create Risk Module** - - - File: `services/iam-service/src/modules/governance/risk/risk.module.ts` - -### 6.4 Reporting Dashboard - -**Tasks:** - -1. **Create Reporting Service** - - - File: `services/iam-service/src/modules/governance/reporting/reporting.service.ts` - - Methods: - - `getAccessSummary(period: DateRange)` - - `getUserActivity(userId: string, period: DateRange)` - - `getSecurityEvents(period: DateRange, filters: EventFilters)` - - `getComplianceStatus()` - - `getRiskOverview()` - -2. **Create Reporting Controller** - - - File: `services/iam-service/src/modules/governance/reporting/reporting.controller.ts` - - Endpoints: - - `GET /api/v1/governance/reports/access-summary` - - `GET /api/v1/governance/reports/user-activity` - - `GET /api/v1/governance/reports/security-events` - - `GET /api/v1/governance/reports/compliance-status` - - `GET /api/v1/governance/reports/risk-overview` - -3. **Create Reporting Module** - - - File: `services/iam-service/src/modules/governance/reporting/reporting.module.ts` - -4. **Create Governance Module Index** - - - File: `services/iam-service/src/modules/governance/index.ts` - - Export all governance modules - ---- - -## Phase 7: Routes Integration (Week 10) - -### 7.1 Update Routes - -**File**: `services/iam-service/src/routes/index.ts` - -**Tasks:** - -1. **Add Identity Routes** - ```typescript - // Import identity controllers - import { userController } from '../modules/identity/user/user.controller'; - import { profileController } from '../modules/identity/profile/profile.controller'; - import { verificationController } from '../modules/identity/verification/verification.controller'; - import { organizationController } from '../modules/identity/organization/organization.controller'; - import { groupController } from '../modules/identity/group/group.controller'; - - // Add routes with authentication middleware - // User routes - router.get(`/api/${apiVersion}/identity/users`, authenticate(), userController.list.bind(userController)); - router.post(`/api/${apiVersion}/identity/users`, authenticate(), requirePermission('identity', 'create'), userController.create.bind(userController)); - // ... more user routes - - // Profile routes - router.get(`/api/${apiVersion}/identity/users/:id/profile`, authenticate(), profileController.get.bind(profileController)); - // ... more profile routes - - // Verification routes - router.post(`/api/${apiVersion}/identity/verification/email/request`, authenticate(), verificationController.requestEmail.bind(verificationController)); - // ... more verification routes - - // Organization routes - router.get(`/api/${apiVersion}/identity/organizations`, authenticate(), organizationController.list.bind(organizationController)); - // ... more organization routes - - // Group routes - router.get(`/api/${apiVersion}/identity/organizations/:id/groups`, authenticate(), groupController.list.bind(groupController)); - // ... more group routes - ``` - -2. **Add Access Routes** - ```typescript - // Import access controllers - import { accessRequestController } from '../modules/access/request/request.controller'; - import { accessReviewController } from '../modules/access/review/review.controller'; - import { accessAnalyticsController } from '../modules/access/analytics/analytics.controller'; - - // Access request routes - router.get(`/api/${apiVersion}/access/requests`, authenticate(), accessRequestController.list.bind(accessRequestController)); - // ... more access request routes - - // Access review routes - router.get(`/api/${apiVersion}/access/reviews`, authenticate(), accessReviewController.list.bind(accessReviewController)); - // ... more access review routes - - // Access analytics routes - router.get(`/api/${apiVersion}/access/analytics/usage`, authenticate(), accessAnalyticsController.usage.bind(accessAnalyticsController)); - // ... more analytics routes - ``` - -3. **Add Governance Routes** - ```typescript - // Import governance controllers - import { complianceController } from '../modules/governance/compliance/compliance.controller'; - import { policyGovernanceController } from '../modules/governance/policy/policy-governance.controller'; - import { riskController } from '../modules/governance/risk/risk.controller'; - import { reportingController } from '../modules/governance/reporting/reporting.controller'; - - // Compliance routes - router.get(`/api/${apiVersion}/governance/compliance/reports`, authenticate(), complianceController.list.bind(complianceController)); - // ... more compliance routes - - // Policy governance routes - router.get(`/api/${apiVersion}/governance/policies/templates`, authenticate(), policyGovernanceController.getTemplates.bind(policyGovernanceController)); - // ... more policy routes - - // Risk routes - router.get(`/api/${apiVersion}/governance/risk/scores`, authenticate(), riskController.list.bind(riskController)); - // ... more risk routes - - // Reporting routes - router.get(`/api/${apiVersion}/governance/reports/access-summary`, authenticate(), reportingController.accessSummary.bind(reportingController)); - // ... more reporting routes - ``` - -4. **Keep Backward Compatibility** - - - Keep all existing `/api/v1/auth/*` routes unchanged - - Keep all existing `/api/v1/rbac/*` routes unchanged - - Keep all existing `/api/v1/mfa/*` routes unchanged - - Keep all existing `/api/v1/sessions/*` routes unchanged - ---- - -## Phase 8: Testing (Week 11) - -### 8.1 Unit Tests - -**Tasks:** - -1. **Repository Tests** - - - Files: - - `services/iam-service/src/repositories/__tests__/organization.repository.test.ts` - - `services/iam-service/src/repositories/__tests__/group.repository.test.ts` - - `services/iam-service/src/repositories/__tests__/user-profile.repository.test.ts` - - `services/iam-service/src/repositories/__tests__/identity-verification.repository.test.ts` - - `services/iam-service/src/repositories/__tests__/access-request.repository.test.ts` - - `services/iam-service/src/repositories/__tests__/access-review.repository.test.ts` - -2. **Service Tests** - - - Files: - - `services/iam-service/src/modules/identity/**/__tests__/*.service.test.ts` - - `services/iam-service/src/modules/access/**/__tests__/*.service.test.ts` - - `services/iam-service/src/modules/governance/**/__tests__/*.service.test.ts` - -3. **Controller Tests** - - - Files: - - `services/iam-service/src/modules/identity/**/__tests__/*.controller.test.ts` - - `services/iam-service/src/modules/access/**/__tests__/*.controller.test.ts` - - `services/iam-service/src/modules/governance/**/__tests__/*.controller.test.ts` - -### 8.2 Integration Tests - -**Tasks:** - -1. **E2E Tests** - - - File: `services/iam-service/src/__tests__/identity.e2e.ts` - - Test user lifecycle workflows - - Test profile management - - Test identity verification flows - - Test organization & group management - - - File: `services/iam-service/src/__tests__/access.e2e.ts` - - Test access request/approval flows - - Test access review workflows - - Test access analytics - - - File: `services/iam-service/src/__tests__/governance.e2e.ts` - - Test compliance report generation - - Test policy governance - - Test risk scoring - -### 8.3 Update Test Setup - -**File**: `services/iam-service/src/__tests__/setupTests.ts` - -**Tasks:** - -- Update test database setup to include new models -- Update test fixtures for new entities -- Add test utilities for new modules - ---- - -## Phase 9: Documentation & API Docs (Week 12) - -### 9.1 Update OpenAPI/Swagger - -**File**: `services/iam-service/src/docs/swagger.ts` - -**Tasks:** - -1. Add Swagger tags for new modules: - - - `Identity` - - `Access` - - `Governance` - -2. Add API documentation for all new endpoints -3. Add request/response schemas -4. Add examples for each endpoint - -### 9.2 Update README - -**File**: `services/iam-service/README.md` - -**Tasks:** - -1. Update feature list with IAM capabilities -2. Add architecture overview -3. Add API endpoint documentation -4. Add migration guide from auth-service -5. Update setup instructions - -### 9.3 Update Architecture Docs - -**Files**: - -- `services/iam-service/ARCHITECTURE.vi.md` -- `services/iam-service/ARCHITECTURE.en.md` - -**Tasks:** - -1. Update service architecture diagrams -2. Add IAM module architecture -3. Add database schema documentation -4. Add API flow diagrams -5. Add deployment architecture - -### 9.4 Create Migration Guide - -**File**: `services/iam-service/MIGRATION_GUIDE.md` - -**Tasks:** - -1. Document steps to migrate from auth-service -2. Document breaking changes (if any) -3. Document backward compatibility notes -4. Document database migration steps -5. Document environment variable changes - ---- - -## Phase 10: Deployment & Rollout (Week 13) - -### 10.1 Final Deployment Updates - -**Tasks:** - -1. **Update Docker Image Build** - - - Ensure Dockerfile builds correctly - - Update image tags if needed - -2. **Update Environment Variables** - - - Review all environment variables - - Add new required variables for IAM features - - Update example files - -3. **Update Health Checks** - - - Verify health check endpoints work - - Add health checks for new dependencies (if any) - -### 10.2 Staging Deployment - -**Tasks:** - -1. Deploy to staging environment -2. Run smoke tests -3. Verify all endpoints work -4. Check backward compatibility -5. Run load tests - -### 10.3 Production Rollout - -**Tasks:** - -1. Create deployment plan -2. Deploy to production -3. Monitor metrics and logs -4. Verify backward compatibility -5. Gradual rollout if needed - ---- - -## Dependencies & Prerequisites - -### External Dependencies - -- Email service (SMTP) for email verification -- SMS service for phone verification -- File storage service for document/avatar uploads -- Object storage for file attachments - -### Internal Dependencies - -- All existing auth-service dependencies remain -- No breaking changes to existing APIs -- Database migrations are additive only - ---- - -## Risk Mitigation - -### Backward Compatibility - -- All existing `/api/v1/auth/*` routes remain functional -- Existing database schema is preserved -- Existing clients continue to work without changes - -### Rollback Plan - -- Keep auth-service as backup during migration -- Database migrations are reversible -- Can deploy both services simultaneously during transition - -### Testing Strategy - -- Comprehensive unit tests for all new modules -- Integration tests for workflows -- E2E tests for critical paths -- Load testing before production - ---- - -## Success Criteria - -1. ✅ Service renamed successfully -2. ✅ All new database models created and migrated -3. ✅ All new modules implemented and tested -4. ✅ All new API endpoints functional -5. ✅ Backward compatibility maintained -6. ✅ Documentation complete -7. ✅ Deployed to staging and verified -8. ✅ Production deployment successful \ No newline at end of file diff --git a/.cursor/plans/implement-user-pages_6e6b2c08.plan.md b/.cursor/plans/implement-user-pages_6e6b2c08.plan.md deleted file mode 100644 index f59e0a63..00000000 --- a/.cursor/plans/implement-user-pages_6e6b2c08.plan.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -name: implement-user-pages -overview: Implement responsive user-facing and admin pages wired to the users API, working on both desktop and mobile (native-like) layouts. -todos: - - id: create-users-api-helper - content: Create apps/web-client/src/lib/api/users.ts with typed methods for users API - status: completed - - id: create-users-store - content: Add apps/web-client/src/stores/users-store.ts and hooks to manage users state and actions - status: completed - - id: create-users-components - content: Add UsersTable, UserCard, UserForm components under src/features/shared/components/users/ - status: completed - - id: implement-admin-pages - content: "Add admin pages: apps/web-client/src/app/admin/users/page.tsx and apps/web-client/src/app/admin/users/[id]/page.tsx" - status: completed - - id: implement-profile-settings - content: "Add profile and settings pages: /profile and /settings wired to users-store/auth-store" - status: completed - - id: implement-auth-pages - content: Ensure login/register pages under /auth use auth-store and redirect to /dashboard on success - status: completed - - id: integrate-layouts - content: Wire pages to desktop layout (sidebar) and MobileLayout for mobile breakpoints - status: completed - - id: add-guards - content: Implement client-side auth guard and role-check helper for admin routes - status: completed - - id: add-tests - content: Add smoke/integration tests for auth flow and users pages - status: completed ---- - -# Plan: Implement User Pages (Desktop + Mobile) - -## Goal - -Implement a cohesive set of pages that use the users API for both self-service (profile) and admin CRUD, and that render well on desktop (sidebar/content) and mobile (native-style MobileLayout). - -## Scope - -- Public & auth pages: landing, login, register, forgot-password -- Authenticated user pages: dashboard (chat), profile, settings -- Admin pages: users list, user detail, create/edit user, role management -- Mobile parity: same routes/components but rendered inside `MobileLayout`/`MobileBottomNav` for mobile sizes -- API integration: use existing http-client package and create users client helpers - -## Files I'll update / create (high-signal) - -- Pages - - `apps/web-client/src/app/page.tsx` (landing — already updated) - - `apps/web-client/src/app/auth/login/page.tsx` (login) - - `apps/web-client/src/app/auth/register/page.tsx` (register) - - `apps/web-client/src/app/dashboard/page.tsx` (user dashboard) - - `apps/web-client/src/app/profile/page.tsx` (profile self-service) - - `apps/web-client/src/app/settings/page.tsx` (settings) - - `apps/web-client/src/app/admin/users/page.tsx` (admin users list) - - `apps/web-client/src/app/admin/users/[id]/page.tsx` (admin user detail/edit) - -- Components & layout - - `apps/web-client/src/features/shared/components/users/UserCard.tsx` - - `apps/web-client/src/features/shared/components/users/UserForm.tsx` - - `apps/web-client/src/features/shared/components/users/UsersTable.tsx` - - `apps/web-client/src/features/shared/components/layout/desktop-layout/desktop-layout.tsx` (ensure sidebar + content) - - reuse `MobileLayout`, `MobileBottomNav` for mobile - -- State & API - - `apps/web-client/src/stores/users-store.ts` (zustand or existing store pattern used by `auth-store.ts`) - - `packages/http-client/src/index.ts` or new helper `apps/web-client/src/lib/api/users.ts` for typed users API calls - -- Auth & guards - - `apps/web-client/src/features/shared/middleware/auth-guard.tsx` (client-side guard/wrapper) - - add role-check helper for admin routes - -- Tests & docs - - `apps/web-client/src/features/shared/components/layout/mobile-layout/mobile-app-demo.tsx` (demo already added) - - Add basic integration tests under `apps/web-client/src/__tests__/` for users pages - -## Implementation steps (high level) - -1. API client helpers (users) - - - Create `apps/web-client/src/lib/api/users.ts` with typed methods: `getUsers`, `getUser`, `createUser`, `updateUser`, `deleteUser`. - - Use existing http-client package where appropriate. - -2. Users store & hooks - - - Implement `users-store.ts` with methods that call the API helpers and manage loading/error state. - - Expose hooks: `useUsersStore` with `fetchUsers`, `fetchUser`, `createUser`, `updateUser`, `deleteUser`. - -3. Desktop layouts & components - - - Ensure `desktop-layout.tsx` (sidebar + content) exists and supports admin sections. - - Create `UsersTable`, `UserCard`, and `UserForm` components. - - Implement `apps/web-client/src/app/admin/users/page.tsx` to use `UsersTable` and `useUsersStore`. - - Implement `apps/web-client/src/app/admin/users/[id]/page.tsx `to show `UserCard` + `UserForm`. - -4. Auth pages & routing - - - Provide login/register pages that call `auth-store` actions; upon login redirect to `/dashboard`. - - Protect admin pages with a client-side guard that checks `auth-store.user.role`. - -5. Profile & settings - - - Implement `/profile` to fetch and update current user (self-service) via `users-store` or `auth-store` methods. - - Settings to manage preferences (theme, language) integrated with existing providers. - -6. Mobile parity - - - For all pages, ensure responsive variants use `MobileLayout` when viewport small. - - For admin pages, provide compact mobile UI or hide complex operations (offer an «Open on desktop» hint) while allowing read/update on mobile where feasible. - -7. UX polish - - - Loading and empty states - - Error handling following project error patterns - - Accessible controls (keyboard, focus) - -8. Tests - - - Add smoke/integration tests for user list, user detail, login flow. - -## Minimal example: users API helper (proposed) - -```javascript -// apps/web-client/src/lib/api/users.ts -import { http } from '@goodgo/http-client'; - -export async function getUsers(params = {}) { - return await http.get('/api/users', { params }); -} - -export async function getUser(id) { - return await http.get(`/api/users/${id}`); -} - -export async function createUser(payload) { - return await http.post('/api/users', payload); -} - -export async function updateUser(id, payload) { - return await http.put(`/api/users/${id}`, payload); -} - -export async function deleteUser(id) { - return await http.delete(`/api/users/${id}`); -} -``` - -## Todos (implementation tasks) - -- create-users-api-helper: Create `apps/web-client/src/lib/api/users.ts` with typed methods -- create-users-store: Implement `apps/web-client/src/stores/users-store.ts` and hooks -- create-users-components: Implement `UsersTable`, `UserCard`, `UserForm` -- implement-admin-pages: Add `apps/web-client/src/app/admin/users/page.tsx` and `[id]/page.tsx` -- implement-profile-settings: Add `/profile` and `/settings` pages -- implement-auth-pages: Ensure `login` and `register` pages integrate with `auth-store` -- integrate-layouts: Wire pages to `desktop-layout` and `MobileLayout` responsive behavior -- add-guards: Implement client-side `auth-guard` and role checks for admin -- add-tests: Add basic tests for login, users list, user detail - -## Timeline (estimates) - -- API helpers + store: 1-2 days -- Core components + admin pages: 2-3 days -- Auth/profile/settings: 1-2 days -- Mobile adjustments & polish: 1-2 days -- Tests + QA: 1-2 days - -## Notes / assumptions - -- Users API endpoints follow REST conventions (`/api/users`). If the real API URL differs, I'll adapt the helpers. -- Uses existing `auth-store` for JWT/session; token injection handled by `http-client`. -- Admin UI assumes role-based field `user.role` is present. - -If you confirm this plan I will create the detailed implementation plan (file-by-file edits and the exact code snippets) and then proceed to implement. If you want any changes to scope (e.g., exclude admin CRUD for now, or prioritise mobile-first UX), tell me which items to adjust. \ No newline at end of file diff --git a/.cursor/plans/modern_ai_chat_ui_design_40dbd41e.plan.md b/.cursor/plans/modern_ai_chat_ui_design_40dbd41e.plan.md deleted file mode 100644 index edaebbeb..00000000 --- a/.cursor/plans/modern_ai_chat_ui_design_40dbd41e.plan.md +++ /dev/null @@ -1,1142 +0,0 @@ ---- -name: Modern AI Chat UI Design -overview: "Comprehensive UI/UX design plan for modern AI chat interfaces with two web applications: Web Client (user-facing chat interface) and Web Admin (admin dashboard). Includes complete design system, component library, responsive design, accessibility, and implementation phases with 60+ granular todos for multi-agent parallel development." -todos: - - id: design-system-1 - content: "[Agent 1] Initialize Tailwind CSS 4 in web-client with custom configuration" - status: completed - - id: design-system-2 - content: "[Agent 1] Create CSS variables file (src/styles/theme.css) with all color, typography, spacing, and animation tokens" - status: completed - - id: design-system-3 - content: "[Agent 2] Build Button component (src/components/ui/button.tsx) with variants (primary, secondary, ghost, danger) and sizes (xs, sm, md, lg, xl)" - status: completed - - id: design-system-4 - content: "[Agent 2] Build Input component (src/components/ui/input.tsx) with validation states (default, focus, error, success, disabled)" - status: completed - - id: design-system-5 - content: "[Agent 3] Build Card component (src/components/ui/card.tsx) with subcomponents (CardHeader, CardTitle, CardDescription, CardContent, CardFooter)" - status: completed - - id: design-system-6 - content: "[Agent 3] Build Modal/Dialog component (src/components/ui/dialog.tsx) using Radix UI with overlay and content animations" - status: completed - - id: design-system-7 - content: "[Agent 3] Build Avatar component (src/components/ui/avatar.tsx) with sizes (xs, sm, md, lg, xl) and status indicators" - status: completed - - id: design-system-8 - content: "[Agent 4] Setup theme switching system (dark/light mode) with Context API and localStorage persistence" - status: completed - - id: design-system-9 - content: "[Agent 4] Initialize Storybook for component documentation and visual testing" - status: completed - - id: auth-1 - content: "[Agent 1] Create Login page (src/app/(auth)/login/page.tsx) with email/password inputs, validation, and error handling" - status: completed - - id: auth-2 - content: "[Agent 1] Create Register page (src/app/(auth)/register/page.tsx) with password strength indicator and form validation" - status: completed - - id: auth-3 - content: "[Agent 2] Implement Forgot Password flow (src/app/(auth)/forgot-password/page.tsx) with email input and reset link" - status: completed - - id: auth-4 - content: "[Agent 3] Integrate OAuth with Google (src/lib/auth/oauth.ts) using NextAuth or similar library" - status: completed - - id: auth-5 - content: "[Agent 4] Create auth store (src/stores/auth-store.ts) with Zustand for managing authentication state" - status: completed - - id: chat-1 - content: "[Agent 1] Build Chat layout component (src/components/chat/chat-layout.tsx) with sidebar, main area, and optional right panel" - status: completed - - id: chat-2 - content: "[Agent 1] Build MessageBubble component (src/components/chat/message-bubble.tsx) with user/AI variants and message actions" - status: completed - - id: chat-3 - content: "[Agent 2] Build ChatInput component (src/components/chat/chat-input.tsx) with auto-resize textarea and send button" - status: completed - - id: chat-4 - content: "[Agent 2] Build TypingIndicator component (src/components/chat/typing-indicator.tsx) with pulsing dots animation" - status: completed - - id: chat-5 - content: "[Agent 3] Build ConversationSidebar component (src/components/chat/conversation-sidebar.tsx) with search and conversation list" - status: completed - - id: chat-6 - content: "[Agent 3] Implement message actions menu (copy, edit, delete, regenerate, like/dislike, share) on message hover" - status: completed - - id: chat-7 - content: "[Agent 4] Integrate WebSocket client (src/lib/websocket.ts) for real-time messaging with reconnection logic" - status: completed - - id: chat-8 - content: "[Agent 4] Create chat store (src/stores/chat-store.ts) with Zustand for managing messages and conversation state" - status: completed - - id: settings-1 - content: "[Agent 1] Create User Profile page (src/app/(dashboard)/settings/profile/page.tsx) with avatar upload and profile fields" - status: completed - - id: settings-2 - content: "[Agent 1] Create Settings layout (src/app/(dashboard)/settings/layout.tsx) with tab navigation (Profile, Preferences, Security, etc.)" - status: completed - - id: settings-3 - content: "[Agent 2] Implement Preferences tab (src/app/(dashboard)/settings/preferences/page.tsx) with language, theme, chat settings, and accessibility options" - status: completed - - id: settings-4 - content: "[Agent 3] Implement Security tab (src/app/(dashboard)/settings/security/page.tsx) with password change, 2FA setup (QR code), and active sessions" - status: completed - - id: settings-5 - content: "[Agent 4] Implement API Keys management page (src/app/(dashboard)/settings/api-keys/page.tsx) for developers" - status: completed - - id: admin-1 - content: "[Agent 1] Create Admin Dashboard layout (apps/web-admin/src/app/(dashboard)/layout.tsx) with sidebar navigation" - status: completed - - id: admin-2 - content: "[Agent 1] Build AnalyticsCard component (apps/web-admin/src/components/admin/analytics-card.tsx) with metric, chart, progress, and comparison variants" - status: completed - - id: admin-3 - content: "[Agent 1] Create Dashboard overview page (apps/web-admin/src/app/(dashboard)/dashboard/page.tsx) with metrics row and charts" - status: completed - - id: admin-4 - content: "[Agent 2] Integrate Recharts and create UserGrowthChart component (apps/web-admin/src/components/admin/charts/user-growth-chart.tsx)" - status: completed - - id: admin-5 - content: "[Agent 3] Create RevenueChart component (apps/web-admin/src/components/admin/charts/revenue-chart.tsx) as Area Chart" - status: completed - - id: admin-6 - content: "[Agent 4] Build RecentActivityTable component (apps/web-admin/src/components/admin/recent-activity-table.tsx) with pagination" - status: completed - - id: admin-7 - content: "[Agent 1] Create UserManagement page (apps/web-admin/src/app/(dashboard)/users/page.tsx) with search and filters" - status: completed - - id: admin-8 - content: "[Agent 1] Build DataTable component (apps/web-admin/src/components/admin/data-table.tsx) with sorting, filtering, pagination, and bulk actions" - status: completed - - id: admin-9 - content: "[Agent 2] Create UserDetailsModal component (apps/web-admin/src/components/admin/user-details-modal.tsx) with profile, activity timeline, and message history" - status: completed - - id: admin-10 - content: "[Agent 3] Implement bulk actions for users (activate, deactivate, delete) with confirmation dialogs" - status: completed - - id: admin-11 - content: "[Agent 1] Create SystemSettings page (apps/web-admin/src/app/(dashboard)/settings/page.tsx) with tabs (General, Email, Security, API, Advanced)" - status: completed - - id: admin-12 - content: "[Agent 1] Build GeneralSettings form (apps/web-admin/src/components/admin/settings/general-settings.tsx) with site name, logo, language, timezone, maintenance mode" - status: completed - - id: admin-13 - content: "[Agent 2] Build EmailSettings form (apps/web-admin/src/components/admin/settings/email-settings.tsx) with SMTP configuration, email templates, and test email function" - status: completed - - id: admin-14 - content: "[Agent 3] Build SecuritySettings form (apps/web-admin/src/components/admin/settings/security-settings.tsx) with password policy, session timeout, IP whitelist/blacklist, rate limiting, CORS" - status: completed - - id: responsive-1 - content: "[Agent 1] Mobile responsive for web-client: Hide sidebar by default, full-width messages, sticky header/input, swipe gestures" - status: completed - - id: responsive-2 - content: "[Agent 2] Mobile responsive for web-admin: Collapsible sidebar, stacked metric cards, horizontal scroll tables, touch-friendly buttons (44px min)" - status: completed - - id: responsive-3 - content: "[Agent 2] Tablet optimizations: Two-column layout, show sidebar (toggleable), medium-width messages (60%), side-by-side charts" - status: completed - - id: responsive-4 - content: "[Agent 2] Touch-friendly interactions: 44px minimum touch targets, 8px spacing between, active state feedback, swipe gestures (left/right, pull down, long press)" - status: completed - - id: accessibility-1 - content: "[Agent 3] Keyboard navigation: Focus indicators (2px solid outline), logical tab order, custom shortcuts (Ctrl+K for search, Ctrl+N for new chat, etc.)" - status: completed - - id: accessibility-2 - content: "[Agent 3] ARIA labels and semantic HTML: Proper HTML5 elements (header, nav, main, aside, footer), descriptive aria-labels for all interactive elements, form validation with aria-invalid and aria-describedby" - status: completed - - id: accessibility-3 - content: "[Agent 4] Screen reader support: Live regions for announcements (role=\"status\" aria-live=\"polite\"), proper labels for all inputs, skip to main content link" - status: completed - - id: accessibility-4 - content: "[Agent 4] WCAG 2.1 AA compliance verification: Color contrast testing (4.5:1 for normal text, 3:1 for large text), font size minimum 16px, zoom support up to 200%, alternative text for all images" - status: completed - - id: performance-1 - content: "[Agent 1] Code splitting implementation: Route-based splitting with React.lazy, component-based splitting for heavy components (charts, modals), dynamic imports" - status: completed - - id: performance-2 - content: "[Agent 2] Image optimization: Next.js Image component with WebP/AVIF formats, responsive images (srcset), blur placeholder, lazy loading" - status: completed - - id: performance-3 - content: "[Agent 1] Lazy loading: Components (React.lazy), images (loading=\"lazy\"), routes (dynamic imports), heavy libraries (charts, animations)" - status: completed - - id: performance-4 - content: "[Agent 3] Caching strategy: Browser caching for static assets (1 year), API response caching with React Query, service worker for offline support, session storage for user data" - status: completed - - id: performance-5 - content: "[Agent 4] Lighthouse optimization: Target scores (Performance 90+, Accessibility 95+, Best Practices 95+, SEO 100), Core Web Vitals (LCP < 2.5s, FID < 100ms, CLS < 0.1)" - status: completed - - id: testing-1 - content: "[Agent 1] Unit tests for UI components: Jest + React Testing Library, test Button, Input, Card, Dialog, Avatar components with all variants and states" - status: completed - - id: testing-2 - content: "[Agent 2] Unit tests for hooks and stores: Test useChat, useAuth, useTheme hooks, test Zustand stores (auth-store, chat-store, theme-store)" - status: completed - - id: testing-3 - content: "[Agent 3] E2E tests for critical flows: Login/Register flow, Chat message sending, Settings updates, Admin user management (using Playwright or Cypress)" - status: completed - - id: testing-4 - content: "[Agent 4] Cross-browser testing: Test on Chrome, Firefox, Safari, Edge, verify responsive layouts, check for visual regressions" - status: completed - - id: testing-5 - content: "[Agent 4] Performance testing: Lighthouse CI, WebPageTest, monitor Core Web Vitals, test on slow 3G connection" - status: completed - - id: testing-6 - content: "[Agent 5] Bug fixes and polish: Fix animation issues, improve micro-interactions, handle edge cases, optimize bundle size, final UI polish" - status: completed ---- - -# Modern AI Chat UI Design - Implementation Plan - -## Tổng quan kiến trúc UI - -Dự án sẽ có 2 ứng dụng web chính với design language thống nhất: - -### Web Client (User-facing) - -- **Mục đích**: Chat interface cho end users tương tác với AI -- **Design inspiration**: x.ai Grok, OpenAI ChatGPT -- **Key features**: - - Minimalistic và intuitive - - Dark mode as default với light mode option - - Real-time chat với typing indicators - - Message history và conversation management - - Multi-modal input (text, voice future) - -### Web Admin (Admin-facing) - -- **Mục đích**: Dashboard quản lý users, analytics, system settings -- **Design inspiration**: Modern admin dashboards với AI-powered insights -- **Key features**: - - Analytics dashboard với charts/graphs - - User management với advanced filtering - - System monitoring và health checks - - Content moderation tools - - Configuration management - -## I. Design System Foundation - -### 1.1 Color Palette - -#### Dark Mode (Primary Theme) - -**Background Colors:** - -- `--bg-primary: #0A0A0A` - Main background - Almost black -- `--bg-secondary: #121212` - Card/Panel background - Dark grey -- `--bg-tertiary: #1A1A1A` - Hover states -- `--bg-elevated: #242424` - Elevated surfaces (modals, dropdowns) - -**Text Colors (WCAG Compliant):** - -- `--text-primary: #FAFAFA` - Primary text - Off-white (4.5:1 contrast) -- `--text-secondary: #E0E0E0` - Secondary text - Light grey -- `--text-tertiary: #A0A0A0` - Tertiary/disabled text -- `--text-inverse: #1A1A1A` - Text on light backgrounds - -**Brand/Accent Colors:** - -- `--accent-primary: #3B82F6` - Primary blue - CTAs, links -- `--accent-secondary: #8B5CF6` - Purple - Highlights -- `--accent-success: #10B981` - Green - Success states -- `--accent-warning: #F59E0B` - Amber - Warnings -- `--accent-error: #EF4444` - Red - Errors -- `--accent-info: #06B6D4` - Cyan - Info - -**Chat Specific Colors:** - -- `--chat-user-bubble: #2563EB` - User message - Deep blue -- `--chat-ai-bubble: #374151` - AI message - Dark grey -- `--chat-user-text: #FFFFFF` - White text on blue -- `--chat-ai-text: #F3F4F6` - Light text on grey -- `--chat-timestamp: #9CA3AF` - Timestamp grey -- `--chat-divider: #1F2937` - Divider between messages - -**Border Colors:** - -- `--border-primary: #2A2A2A` - Default borders -- `--border-secondary: #3A3A3A` - Hover borders -- `--border-focus: #3B82F6` - Focus state - Blue - -#### Light Mode (Secondary Theme) - -- `--bg-primary-light: #FFFFFF` -- `--bg-secondary-light: #F9FAFB` -- `--bg-tertiary-light: #F3F4F6` -- `--text-primary-light: #111827` -- `--text-secondary-light: #4B5563` -- `--border-primary-light: #E5E7EB` - -### 1.2 Typography - -**Font Stack:** - -```css ---font-sans: - -apple-system, - BlinkMacSystemFont, - "SF Pro Display", - "Segoe UI", - Roboto, - "Helvetica Neue", - Arial, - sans-serif; - ---font-mono: - "SF Mono", - Consolas, - "Liberation Mono", - Menlo, - monospace; -``` - -**Type Scale:** - -- `--text-6xl: 3.75rem / 1` - 60px - Hero titles -- `--text-5xl: 3rem / 1` - 48px - Page titles -- `--text-4xl: 2.25rem / 1.1` - 36px - Section headers -- `--text-3xl: 1.875rem / 1.2` - 30px - Card headers -- `--text-2xl: 1.5rem / 1.3` - 24px - Large body -- `--text-xl: 1.25rem / 1.4` - 20px - Emphasized text -- `--text-lg: 1.125rem / 1.5` - 18px - Large body -- `--text-base: 1rem / 1.5` - 16px - Default body -- `--text-sm: 0.875rem / 1.5` - 14px - Small text -- `--text-xs: 0.75rem / 1.5` - 12px - Captions - -**Font Weights:** - -- `--font-light: 300` - Light text -- `--font-normal: 400` - Body text -- `--font-medium: 500` - Emphasized -- `--font-semibold: 600` - Headings -- `--font-bold: 700` - Strong emphasis - -### 1.3 Spacing & Layout - -**Base Unit: 4px (0.25rem)** - -**Spacing Scale:** - -- `--space-0: 0` - 0px -- `--space-1: 0.25rem` - 4px -- `--space-2: 0.5rem` - 8px -- `--space-3: 0.75rem` - 12px -- `--space-4: 1rem` - 16px -- `--space-5: 1.25rem` - 20px -- `--space-6: 1.5rem` - 24px -- `--space-8: 2rem` - 32px -- `--space-10: 2.5rem` - 40px -- `--space-12: 3rem` - 48px -- `--space-16: 4rem` - 64px -- `--space-20: 5rem` - 80px - -**Container Widths:** - -- `--container-sm: 640px` - Small devices -- `--container-md: 768px` - Medium devices -- `--container-lg: 1024px` - Large devices -- `--container-xl: 1280px` - Extra large -- `--container-2xl: 1536px` - 2X large -- `--chat-max-width: 768px` - Max width for chat messages -- `--sidebar-width: 280px` - Conversation history sidebar - -**Border Radius:** - -- `--radius-sm: 0.25rem` - 4px - Small elements -- `--radius-md: 0.5rem` - 8px - Buttons, inputs -- `--radius-lg: 0.75rem` - 12px - Cards -- `--radius-xl: 1rem` - 16px - Large cards -- `--radius-2xl: 1.5rem` - 24px - Modals -- `--radius-full: 9999px` - Full round - Avatars, pills - -**Shadows (Dark Mode Optimized):** - -- `--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.5)` -- `--shadow-md: 0 4px 6px rgba(0, 0, 0, 0.5)` -- `--shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.6)` -- `--shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.7)` -- `--shadow-glow: 0 0 20px rgba(59, 130, 246, 0.3)` - Blue glow for focus - -### 1.4 Grid System - -**Responsive Breakpoints:** - -- `--screen-sm: 640px` - Mobile landscape -- `--screen-md: 768px` - Tablet -- `--screen-lg: 1024px` - Desktop -- `--screen-xl: 1280px` - Large desktop -- `--screen-2xl: 1536px` - Extra large desktop - -**Layout Patterns:** - -- Single Column (Mobile): < 768px - Full width content -- Two Column (Tablet): 768px - 1024px - Sidebar + Main -- Three Column (Desktop): > 1024px - Sidebar + Main + Panel - -### 1.5 Animation & Transitions - -**Timing Functions:** - -- `--ease-in: cubic-bezier(0.4, 0, 1, 1)` -- `--ease-out: cubic-bezier(0, 0, 0.2, 1)` -- `--ease-in-out: cubic-bezier(0.4, 0, 0.2, 1)` -- `--ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1)` - -**Duration:** - -- `--duration-fast: 150ms` - Hover effects -- `--duration-normal: 250ms` - Default transitions -- `--duration-slow: 350ms` - Complex animations -- `--duration-slower: 500ms` - Page transitions - -**Micro-interactions:** - -- Button hover: Subtle scale (1.02) + brightness -- Card hover: Lift effect (translateY -2px) + shadow -- Input focus: Glow effect (box-shadow) + border color -- Message send: Slide up + fade in -- Typing indicator: Pulsing dots animation - -## II. Component Library - -### 2.1 Core Components (Radix UI based) - -#### Button Component - -**Variants:** primary, secondary, ghost, danger - -**Sizes:** xs (28px), sm (32px), md (40px default), lg (48px), xl (56px) - -**States:** Default, Hover, Active, Focus, Disabled, Loading - -**Implementation:** [apps/web-client/src/components/ui/button.tsx] - -#### Input Fields - -**Types:** Text Input, Textarea, Select, Multi-select, Date Picker, Search - -**States:** Default, Focus (blue border + glow), Error, Success, Disabled - -**Implementation:** [apps/web-client/src/components/ui/input.tsx] - -#### Card Component - -**Variants:** Default, Interactive (hover), Bordered - -**Structure:** CardHeader, CardTitle, CardDescription, CardContent, CardFooter - -**Implementation:** [apps/web-client/src/components/ui/card.tsx] - -#### Modal/Dialog - -**Structure:** DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter - -**Animation:** Overlay fade in, Content scale + fade - -**Implementation:** [apps/web-client/src/components/ui/dialog.tsx] - -#### Avatar Component - -**Sizes:** xs (24px), sm (32px), md (40px default), lg (48px), xl (64px) - -**States:** Image loaded, Fallback (initials), Loading (skeleton), Status indicator - -**Implementation:** [apps/web-client/src/components/ui/avatar.tsx] - -### 2.2 Chat-Specific Components - -#### Message Bubble - -**Structure:** User message (right aligned, blue), AI message (left aligned, grey) - -**Features:** Message header (author, time), Message text, Message actions on hover - -**Animation:** Slide up + fade in - -**Implementation:** [apps/web-client/src/components/chat/message-bubble.tsx] - -#### Typing Indicator - -**Animation:** Pulsing dots with staggered delays - -**Implementation:** [apps/web-client/src/components/chat/typing-indicator.tsx] - -#### Chat Input - -**Features:** Auto-resize textarea, Attach file button, Send button, Keyboard shortcuts (Enter to send, Shift+Enter for new line) - -**Implementation:** [apps/web-client/src/components/chat/chat-input.tsx] - -#### Conversation Sidebar - -**Features:** New Chat button, Search conversations, Conversation list (scrollable), User profile (sticky bottom) - -**Implementation:** [apps/web-client/src/components/chat/conversation-sidebar.tsx] - -### 2.3 Admin Components - -#### Data Table - -**Features:** Column sorting, Global search, Column filters, Pagination, Row selection, Bulk actions, Export to CSV/Excel, Column visibility toggle - -**Implementation:** [apps/web-admin/src/components/admin/data-table.tsx] - -#### Analytics Card - -**Variants:** Metric card (single value), Chart card (with graph), Progress card (with progress bar), Comparison card (multiple metrics) - -**Implementation:** [apps/web-admin/src/components/admin/analytics-card.tsx] - -#### Charts - -**Library:** Recharts or Tremor - -**Types:** Line Chart, Bar Chart, Pie/Donut Chart, Area Chart, Heatmap - -**Implementation:** [apps/web-admin/src/components/admin/charts/] - -## III. Web Client - Detailed Screens - -### 3.1 Authentication Pages - -#### Login Page - -**Layout:** Centered card (max-width: 400px), Logo, Email input, Password input (show/hide toggle), Remember me checkbox, Forgot password link, Primary button "Sign in", OAuth buttons (Google), Sign up link - -**Validation:** Real-time email format validation, Error messages below inputs, Loading state on button - -**Implementation:** [apps/web-client/src/app/(auth)/login/page.tsx] - -#### Register Page - -**Additional Fields:** Full Name, Confirm Password, Terms & Conditions checkbox, Password strength meter - -**Password Strength Levels:** Weak (0-25% red), Fair (26-50% orange), Good (51-75% yellow), Strong (76-100% green) - -**Implementation:** [apps/web-client/src/app/(auth)/register/page.tsx] - -#### Forgot Password Page - -**Flow:** Enter email → Send reset link → Check email → Click link → Enter new password → Confirm → Success → Redirect to login - -**Implementation:** [apps/web-client/src/app/(auth)/forgot-password/page.tsx] - -### 3.2 Main Chat Interface - -**Layout (Desktop):** - -- Left Sidebar (280px): New Chat button, Search conversations, Conversation list, User profile -- Main Chat Area (flex-1, max 768px centered): Header, Messages container (scrollable), Typing indicator, Input area (sticky bottom) -- Right Panel (320px, optional, collapsible): Conversation settings, Participants, Shared files, Quick actions - -**Message Types:** - -1. Text Message - Plain text with markdown support, Code blocks with syntax highlighting, Links with preview cards -2. System Message - Centered, grey text, Used for timestamps, status updates -3. Error Message - Red border, error icon, Retry button -4. Loading Message - Skeleton or typing indicator, Shown while AI is generating - -**Message Actions (on hover):** Copy message, Edit (user messages only), Delete (user messages only), Regenerate (AI messages), Like/Dislike (feedback), Share - -**Implementation:** - -- Layout: [apps/web-client/src/components/chat/chat-layout.tsx] -- Messages: [apps/web-client/src/app/(dashboard)/chat/page.tsx] - -### 3.3 User Settings - -**Navigation Tabs:** Profile, Preferences, Security, Notifications, Billing (if applicable), API Keys (for developers) - -**Profile Tab:** Avatar Upload, Full Name, Email (verified status), Username, Bio, Save Changes button - -**Implementation:** [apps/web-client/src/app/(dashboard)/settings/profile/page.tsx] - -**Preferences Tab:** Language selection, Theme (Dark/Light/Auto), Chat settings (Auto-scroll, Show timestamps, Message grouping, Font size), Accessibility (High contrast mode, Screen reader optimizations) - -**Implementation:** [apps/web-client/src/app/(dashboard)/settings/preferences/page.tsx] - -**Security Tab:** Change password, Two-factor authentication (2FA) with QR code, Active sessions (List of devices, Revoke access), Delete account (danger zone) - -**Implementation:** [apps/web-client/src/app/(dashboard)/settings/security/page.tsx] - -## IV. Web Admin - Detailed Screens - -### 4.1 Dashboard (Overview) - -**Layout:** - -- Header: Dashboard title, User menu, Settings -- Sidebar: Dashboard, Users, Analytics, Messages, Settings, Admin section, Logout -- Main Content: - - Metrics Row: Total Users, Messages, Active Users, Revenue (with percentage change and sparkline) - - Charts Row: User Growth Chart (Line Chart), Revenue Chart (Area Chart), Message Activity Heatmap - - Recent Activity Table: User avatar + name, Action performed, Timestamp (relative), Status badge, Quick actions - -**Implementation:** [apps/web-admin/src/app/(dashboard)/dashboard/page.tsx] - -### 4.2 User Management - -**Features:** User list with search/filter, User details modal, Bulk actions (activate, deactivate, delete), User roles management, Activity logs - -**User List Table:** Avatar, Name, Email, Role, Status columns, Search bar, Filter dropdown, Export button, Pagination - -**Filters:** Role (Admin, User, Moderator), Status (Active, Inactive, Banned), Date range, Sort by (Name, Email, Date, Activity) - -**User Details Modal:** Profile information, Activity timeline, Message history, Edit user button, Deactivate/Delete buttons - -**Implementation:** - -- Page: [apps/web-admin/src/app/(dashboard)/users/page.tsx] -- Modal: [apps/web-admin/src/components/admin/user-details-modal.tsx] - -### 4.3 Analytics - -**Tabs:** Overview, Users, Messages, Performance, Custom Reports - -**Overview Tab:** Key metrics summary, Trends visualization, Comparison charts (day/week/month/year), Export to PDF/CSV - -**Users Tab:** User acquisition funnel, Retention chart, Cohort analysis, Geographic distribution map, Device/browser breakdown - -**Messages Tab:** Total messages sent, Average messages per user, Peak activity times, Popular topics/keywords, Sentiment analysis - -**Performance Tab:** API response times, Error rates, Uptime statistics, Server resources (CPU, Memory, Disk) - -**Implementation:** [apps/web-admin/src/app/(dashboard)/analytics/page.tsx] - -### 4.4 System Settings - -**Categories:** General, Email, Security, API, Advanced - -**General Settings:** Site name, Site logo, Default language, Timezone, Maintenance mode toggle - -**Email Settings:** SMTP configuration, Email templates, Test email function - -**Security Settings:** Password policy, Session timeout, IP whitelist/blacklist, Rate limiting, CORS settings - -**API Settings:** API keys management, Webhooks configuration, Rate limits, Documentation link - -**Implementation:** [apps/web-admin/src/app/(dashboard)/settings/page.tsx] - -## V. Responsive Design - -### 5.1 Breakpoints Strategy - -**Mobile First Approach:** - -- Mobile (default): < 640px -- Tablet: @media (min-width: 768px) -- Desktop: @media (min-width: 1024px) -- Large Desktop: @media (min-width: 1280px) - -### 5.2 Mobile Layout (< 768px) - -**Web Client Mobile:** - -- Hide sidebar by default (hamburger menu) -- Full-width messages -- Sticky header + input -- Swipe gestures (back, delete) -- Bottom tab navigation (optional) - -**Web Admin Mobile:** - -- Collapsible sidebar -- Stacked metric cards -- Horizontal scroll for tables -- Simplified charts -- Touch-friendly buttons (min 44px) - -### 5.3 Tablet Layout (768px - 1024px) - -**Two-column layout:** - -- Show sidebar (toggleable) -- Medium-width messages (60%) -- Side-by-side charts (admin) - -### 5.4 Touch Interactions - -**Touch Targets:** Minimum size: 44x44px (iOS HIG), Spacing between: 8px minimum, Active state feedback (scale down on press) - -**Gestures:** Swipe left (Delete), Swipe right (Archive/mark as read), Pull down (Refresh), Long press (Context menu) - -## VI. Accessibility (WCAG 2.1 AA) - -### 6.1 Color Contrast - -**Requirements:** - -- Normal text (< 18px): 4.5:1 minimum -- Large text (≥ 18px): 3:1 minimum -- UI components: 3:1 minimum - -**Testing Tools:** WebAIM Contrast Checker, Chrome DevTools Accessibility tab, WAVE browser extension - -### 6.2 Keyboard Navigation - -**Focus Indicators:** 2px solid outline with offset - -**Tab Order:** Skip to main content link → Header navigation → Main content → Sidebar → Footer - -**Keyboard Shortcuts:** - -- `Tab`: Next element -- `Shift + Tab`: Previous element -- `Enter`: Activate button/link -- `Space`: Toggle checkbox/select -- `Escape`: Close modal/dropdown -- `Arrow keys`: Navigate lists/menus - -**Custom Shortcuts (Chat):** - -- `Ctrl/Cmd + K`: Open search -- `Ctrl/Cmd + N`: New conversation -- `Ctrl/Cmd + /`: Show shortcuts help -- `Alt + ↑/↓`: Navigate conversations - -### 6.3 Screen Reader Support - -**Semantic HTML:** Use proper HTML5 elements (header, nav, main, aside, footer) - -**ARIA Labels:** All interactive elements have descriptive labels, Form validation with aria-invalid and aria-describedby - -**Live Regions:** Announcements for new messages with role="status" aria-live="polite" - -### 6.4 Visual Accessibility - -**Font Size:** Minimum base: 16px, User can zoom up to 200% without breaking layout - -**Text Spacing:** Line height: 1.5 minimum, Paragraph spacing: 2x font size - -**Focus Management:** Trap focus in modals, Return focus after modal close, Skip to main content link - -**Alternative Text:** All images have alt text, Decorative images: alt="", Avatar images: Descriptive alt text - -## VII. Performance Optimization - -### 7.1 Loading Strategy - -**Critical Rendering Path:** - -1. Inline critical CSS (above fold) -2. Defer non-critical CSS -3. Async load JavaScript -4. Lazy load images - -**Code Splitting:** Route-based splitting, Component-based splitting for heavy components - -**Image Optimization:** Next.js Image component (automatic optimization), WebP format with fallback, Responsive images (srcset), Lazy loading, Blur placeholder - -### 7.2 Perceived Performance - -**Skeleton Screens:** Show content structure while loading - -**Optimistic UI:** Show immediate feedback before API response, Update UI immediately on action, Revert if API call fails - -**Loading States:** Button loading (spinner inside), Page loading (full-screen or top bar), Partial loading (specific sections) - -### 7.3 Caching - -**Browser Caching:** Static assets: 1 year, API responses: Vary by endpoint, User data: Session storage - -**Service Worker:** Cache static assets, Offline support (basic), Background sync for messages - -## VIII. Tech Stack Implementation - -### 8.1 Frontend Stack - -**Core:** - -- Next.js 14+ (App Router) -- TypeScript 5+ -- React 18+ - -**Styling:** - -- Tailwind CSS 4 -- CSS Variables (theme tokens) -- clsx / cn utility (conditional classes) - -**UI Components:** - -- Radix UI (unstyled primitives) -- Lucide React (icons) -- Framer Motion (animations) - -**State Management:** - -- Zustand (global state) -- React Query (server state) -- Context API (theme, auth) - -**Forms:** - -- React Hook Form -- Zod (validation) - -**Charts:** - -- Recharts or Tremor - -**Utilities:** - -- date-fns (date formatting) -- clsx (conditional classes) -- nanoid (unique IDs) - -### 8.2 Project Structure - -``` -apps/web-client/ -├── public/ -│ ├── fonts/ -│ ├── images/ -│ └── icons/ -├── src/ -│ ├── app/ # Next.js App Router -│ │ ├── (auth)/ -│ │ │ ├── login/ -│ │ │ └── register/ -│ │ ├── (dashboard)/ -│ │ │ ├── chat/ -│ │ │ └── settings/ -│ │ ├── layout.tsx -│ │ └── page.tsx -│ ├── components/ -│ │ ├── ui/ # Base components -│ │ │ ├── button.tsx -│ │ │ ├── input.tsx -│ │ │ ├── card.tsx -│ │ │ └── ... -│ │ ├── chat/ # Chat components -│ │ │ ├── message-bubble.tsx -│ │ │ ├── chat-input.tsx -│ │ │ └── typing-indicator.tsx -│ │ ├── layouts/ -│ │ │ ├── header.tsx -│ │ │ ├── sidebar.tsx -│ │ │ └── footer.tsx -│ │ └── features/ -│ ├── hooks/ -│ │ ├── use-chat.ts -│ │ ├── use-auth.ts -│ │ └── use-theme.ts -│ ├── lib/ -│ │ ├── api.ts -│ │ ├── utils.ts -│ │ └── constants.ts -│ ├── stores/ -│ │ ├── auth-store.ts -│ │ ├── chat-store.ts -│ │ └── theme-store.ts -│ ├── styles/ -│ │ ├── globals.css -│ │ └── theme.css -│ └── types/ -│ ├── api.ts -│ └── models.ts -├── .env.local -├── next.config.js -├── tailwind.config.js -├── tsconfig.json -└── package.json -``` - -### 8.3 Component Example - -**Button Component Implementation:** - -- File: [apps/web-client/src/components/ui/button.tsx] -- Uses: class-variance-authority for variants, Radix UI Slot for composition, cn utility for conditional classes -- Variants: primary, secondary, ghost, danger -- Sizes: xs, sm, md, lg, xl -- States: loading state with spinner, disabled state - -## IX. Implementation Phases - -### Phase 1: Design System Setup (Week 1) - -**Todos:** design-system-1 through design-system-9 - -- Initialize Tailwind CSS 4 configuration in web-client and web-admin -- Create CSS variables file with theme tokens -- Build base UI components (Button, Input, Card, Dialog, Avatar) -- Setup theme switching system (dark/light mode) -- Initialize Storybook for component documentation - -**Parallel Work:** - -- Agent 1: Tailwind setup + CSS variables -- Agent 2: Button + Input components -- Agent 3: Card + Dialog + Avatar components -- Agent 4: Theme system + Storybook setup - -### Phase 2: Web Client - Authentication (Week 2) - -**Todos:** auth-1 through auth-5 - -- Login page with form validation -- Register page with password strength indicator -- Forgot password flow -- OAuth integration (Google) -- Auth state management with Zustand - -**Parallel Work:** - -- Agent 1: Login + Register pages -- Agent 2: Forgot password flow -- Agent 3: OAuth integration -- Agent 4: Auth store implementation - -### Phase 3: Web Client - Chat Interface (Week 3-4) - -**Todos:** chat-1 through chat-8 - -- Chat layout structure (sidebar + main + optional panel) -- Message bubble components (user + AI) -- Chat input with auto-resize -- Typing indicator with animation -- Conversation sidebar with search -- Message actions menu (copy, edit, delete, regenerate) -- WebSocket integration for real-time messaging -- Chat store with Zustand - -**Parallel Work:** - -- Agent 1: Chat layout + Message bubbles -- Agent 2: Chat input + Typing indicator -- Agent 3: Conversation sidebar + Message actions -- Agent 4: WebSocket client + Chat store - -### Phase 4: Web Client - Settings & Profile (Week 5) - -**Todos:** settings-1 through settings-5 - -- User profile page with avatar upload -- Settings layout with tabs -- Preferences tab (language, theme, chat settings, accessibility) -- Security tab (change password, 2FA with QR code, active sessions) -- API keys management page - -**Parallel Work:** - -- Agent 1: Profile page + Settings layout -- Agent 2: Preferences tab -- Agent 3: Security tab -- Agent 4: API keys management - -### Phase 5: Web Admin - Dashboard (Week 6-7) - -**Todos:** admin-1 through admin-6 - -- Admin dashboard layout with sidebar -- Analytics card component (metric, chart, progress, comparison variants) -- Dashboard overview page with metrics -- User growth chart (Line Chart with Recharts) -- Revenue chart (Area Chart) -- Recent activity table with pagination - -**Parallel Work:** - -- Agent 1: Dashboard layout + Analytics cards -- Agent 2: User growth chart -- Agent 3: Revenue chart -- Agent 4: Recent activity table - -### Phase 6: Web Admin - User Management (Week 8) - -**Todos:** admin-7 through admin-10 - -- User management page with search and filters -- DataTable component (sorting, filtering, pagination, bulk actions) -- User details modal (profile, activity timeline, message history) -- Bulk actions implementation (activate, deactivate, delete) - -**Parallel Work:** - -- Agent 1: User management page + DataTable -- Agent 2: User details modal -- Agent 3: Bulk actions implementation - -### Phase 7: Web Admin - System Settings (Week 9) - -**Todos:** admin-11 through admin-14 - -- System settings page with tabs (General, Email, Security, API, Advanced) -- General settings form (site name, logo, language, timezone, maintenance mode) -- Email settings form (SMTP configuration, email templates, test email) -- Security settings form (password policy, session timeout, IP whitelist/blacklist, rate limiting, CORS) - -**Parallel Work:** - -- Agent 1: Settings page + General settings -- Agent 2: Email settings -- Agent 3: Security settings - -### Phase 8: Responsive & Accessibility (Week 10) - -**Todos:** responsive-1 through responsive-4, accessibility-1 through accessibility-4 - -- Mobile responsive layouts for web-client (hide sidebar, full-width messages, sticky header/input) -- Mobile responsive layouts for web-admin (collapsible sidebar, stacked metrics, horizontal scroll tables) -- Tablet optimizations (two-column layout, medium-width messages) -- Touch-friendly interactions (44px minimum touch targets, swipe gestures) -- Keyboard navigation (focus indicators, tab order, custom shortcuts) -- ARIA labels and semantic HTML -- Screen reader support (live regions, proper labels) -- WCAG 2.1 AA compliance verification - -**Parallel Work:** - -- Agent 1: Mobile responsive (web-client) -- Agent 2: Mobile responsive (web-admin) + Tablet -- Agent 3: Accessibility (keyboard + ARIA) -- Agent 4: Screen reader + WCAG testing - -### Phase 9: Performance & Optimization (Week 11) - -**Todos:** performance-1 through performance-5 - -- Code splitting (route-based and component-based) -- Image optimization (Next.js Image component, WebP format, responsive images, lazy loading) -- Lazy loading (components, images, routes) -- Caching strategy (browser caching, service worker, API response caching) -- Lighthouse optimization (target: Performance 90+, Accessibility 95+, Best Practices 95+, SEO 100) - -**Parallel Work:** - -- Agent 1: Code splitting + Lazy loading -- Agent 2: Image optimization -- Agent 3: Caching strategy -- Agent 4: Lighthouse optimization - -### Phase 10: Testing & Polish (Week 12) - -**Todos:** testing-1 through testing-6 - -- Unit tests for UI components (Jest + React Testing Library) -- Unit tests for hooks and stores -- E2E tests for critical flows (Playwright or Cypress) -- Cross-browser testing (Chrome, Firefox, Safari, Edge) -- Performance testing (Lighthouse, WebPageTest) -- Bug fixes and polish (animations, micro-interactions, edge cases) - -**Parallel Work:** - -- Agent 1: Component unit tests -- Agent 2: Hooks/stores unit tests -- Agent 3: E2E tests -- Agent 4: Cross-browser + Performance testing -- Agent 5: Bug fixes and polish - -## X. Design Resources & References - -### 10.1 Inspiration Sources - -- x.ai Grok UI - Minimalistic, intuitive chat interface -- OpenAI ChatGPT - Industry-standard AI chat -- Claude.ai - Clean, professional design -- Vercel AI Chat - Modern chat SDK examples -- Linear App - Beautiful dark mode UI - -### 10.2 Design Tools - -- Figma: UI design and prototyping -- Storybook: Component development and documentation -- Chromatic: Visual regression testing -- Tailwind UI: Premium component examples -- Shadcn UI: High-quality component library - -### 10.3 Color Tools - -- Coolors: Color palette generation -- Contrast Checker: WCAG compliance -- ColorBox: Dark mode palette creation -- Palettte: Color scheme explorer - -### 10.4 Typography Resources - -- Fontsource: Self-hosted fonts -- Modern Font Stacks: System font combinations -- Type Scale: Typography scale generator - -### 10.5 Icon Libraries - -- Lucide React: Modern icon set (recommended) -- Heroicons: Tailwind's icon library -- Phosphor Icons: Flexible icon family -- Feather Icons: Minimalist icons - -## XI. Common Patterns & Best Practices - -### 11.1 Component Patterns - -- Compound Components (Card with CardHeader, CardContent, etc.) -- Render Props (DataTable with custom row rendering) -- Controlled Components (Input with value/onChange) - -### 11.2 State Management Patterns - -- Zustand Store for global state (auth, chat, theme) -- React Query for server state (API data, caching) -- Context API for theme and auth context - -### 11.3 API Integration Pattern - -- React Query hooks (useQuery, useMutation) -- Query invalidation on mutations -- Optimistic updates for better UX - -### 11.4 Error Handling - -- Error Boundary for component error catching -- Toast notifications for user feedback (using sonner or similar) -- Form validation with Zod schemas - -## XII. Deployment Considerations - -### 12.1 Build Optimization - -**Next.js Config:** - -- Image optimization with WebP/AVIF formats -- Remove console.log in production -- CSS optimization -- Environment-specific configurations - -### 12.2 Environment Variables - -- Development: NEXT_PUBLIC_API_URL=http://localhost:5001/api/v1 -- Production: NEXT_PUBLIC_API_URL=https://api.goodgo.vn/api/v1 -- WebSocket URLs for real-time features - -### 12.3 Performance Metrics - -**Target Lighthouse Scores:** - -- Performance: 90+ -- Accessibility: 95+ -- Best Practices: 95+ -- SEO: 100 - -**Core Web Vitals:** - -- LCP (Largest Contentful Paint): < 2.5s -- FID (First Input Delay): < 100ms -- CLS (Cumulative Layout Shift): < 0.1 - -## Research Sources - -- xAI UI & Management Console -- Grok UI Figma Community -- OpenAI Apps SDK UI -- OpenAI UI Guidelines -- 16 Chat UI Design Patterns -- UI/UX Design Trends 2026 -- Modern Web Experience Design - ---- - -**Document Version:** 1.0 - -**Last Updated:** 2026-01-02 - -**Status:** Ready for Implementation \ No newline at end of file diff --git a/.cursor/plans/service-template-improvements_98f188ff.plan.md b/.cursor/plans/service-template-improvements_98f188ff.plan.md deleted file mode 100644 index e0f57cf8..00000000 --- a/.cursor/plans/service-template-improvements_98f188ff.plan.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -name: service-template-improvements -overview: "Make the service template production-ready: add testing, env management, DB scaffolding, auth, validation, docs and CI." -todos: [] ---- - -# Improve Service Template (services/_template) - -## Goal - -Make `services/_template` production-ready and developer-friendly by adding testing infra, environment templates/validation, database scaffolding, auth & RBAC, request validation, API docs, standardized error handling, repository pattern, and CI. Changes should preserve existing structure and follow GoodGo project rules. - -## High-level steps - -1. Testing & CI - - - Add `jest.config.ts`, `setupTests.ts`, and example unit/integration tests for `FeatureService` and `HealthController`. - - Add `supertest` based E2E test for `/health` and `/api/v1/features`. - - Update `package.json` scripts to run tests and coverage. - - Files: `services/_template/package.json`, add `jest.config.ts` at repo root of template, tests under `services/_template/src/__tests__/`. - -2. Environment & Local Dev - - - Add `.env.example` and `.env.local.example` with all required vars (PORT, NODE_ENV, DATABASE_URL, REDIS_URL, JAEGER_ENDPOINT, TRACING_ENABLED, SERVICE_NAME, API_VERSION). - - Enhance `src/config/app.config.ts` to accept `.env.local` overrides and document each var in `README.md`. - - Files: `services/_template/.env.example`, `services/_template/.env.local.example`, `services/_template/src/config/app.config.ts`, `services/_template/README.md`. - -3. Prisma & Database - - - Add `prisma/schema.prisma` example with a `Feature` model, and `prisma/seed.ts` placeholder. - - Add migration/dev workflow to README and `package.json` scripts (`prisma:generate`, `prisma:migrate`, `prisma:seed`). - - Files: `services/_template/prisma/schema.prisma`, `services/_template/prisma/seed.ts`, `services/_template/package.json` (scripts already partly present — document usage). - -4. Authentication & Authorization - - - Add auth middleware `src/middlewares/auth.middleware.ts` using `@goodgo/auth-sdk` and JWT guards. - - Add role-based decorator/utility and example protected route in `Feature` module. - - Files: `services/_template/src/middlewares/auth.middleware.ts`, update `services/_template/src/routes/index.ts` and `services/_template/src/modules/feature/feature.module.ts`. - -5. Request Validation & Sanitization - - - Add `validateDto` middleware that uses Zod DTOs (e.g., `createFeatureDtoSchema`) and integrates in `feature.module` routes. - - Sanitize input (simple trimming) helper. - - Files: `services/_template/src/middlewares/validation.middleware.ts`, update `src/modules/feature/feature.module.ts` to parse body. - -6. API Documentation (OpenAPI) - - - Add OpenAPI spec generator (e.g., `openapi-typescript` or `swagger-jsdoc`) and `/docs` route serving Swagger UI. - - Files: `services/_template/src/docs/openapi.ts`, `services/_template/src/routes/docs.ts`, update `README.md`. - -7. Error Handling & Standard Errors - - - Introduce custom error classes (`src/errors/http-error.ts`, `src/errors/not-found.ts`, `src/errors/bad-request.ts`) and an `error-code` enum. - - Ensure `error.middleware.ts` maps known errors to proper status codes and structured `ApiResponse`. - - Files: `services/_template/src/errors/*.ts`, update `src/middlewares/error.middleware.ts`. - -8. Repository Pattern & Transactions - - - Add `src/modules/common/repository.ts` scaffolding and update `FeatureService` to use repository and Prisma transactions for multi-step operations. - - Files: `services/_template/src/modules/common/repository.ts`, update `services/_template/src/modules/feature/feature.service.ts`. - -9. Observability Improvements - - - Ensure metrics registry reset in tests to avoid global state contamination. - - Add correlation id middleware and attach trace ids to logs. - - Files: `services/_template/src/middlewares/correlation.middleware.ts`, update `src/middlewares/logger.middleware.ts` and `src/main.ts` to add header mappings. - -10. Docker & Image Best Practices - - - Add `.dockerignore` and ensure `NODE_ENV` build-time handling. - - Make Docker build cache-friendly and document image tagging conventions in README. - - Files: `services/_template/.dockerignore`, `services/_template/Dockerfile` (reviewed changes only documented). - -11. Documentation & Examples - - - Update `README.md` with examples: local dev, running tests, generating Prisma client, environment explanation, and how to create a new service from template. - - Add code comment examples showing bilingual comment pattern where new modules are introduced. - -## Implementation details & snippets - -- Example: Add DTO validation middleware and usage: -```typescript -// services/_template/src/middlewares/validation.middleware.ts -import { Request, Response, NextFunction } from 'express'; -import { AnyZodObject } from 'zod'; - -export const validateDto = (schema: AnyZodObject) => (req: Request, res: Response, next: NextFunction) => { - try { - req.body = schema.parse(req.body); - return next(); - } catch (err: any) { - return res.status(400).json({ success: false, error: { code: 'VALIDATION_ERROR', message: err.message } }); - } -}; -``` - -- Example: Custom HTTP error mapping in `error.middleware.ts` — convert `HttpError` to proper status and code. - -- Tests: Add `src/__tests__/health.e2e.ts` using `supertest` to assert readiness/liveness and metrics endpoint. - -## Todos (for tracking) - -- setup-tests: Add Jest config, test utilities, and example tests. -- add-dotenv-examples: Add `.env.example` and `.env.local.example` and document envs in README. -- prisma-scaffold: Add `prisma/schema.prisma` and `prisma/seed.ts` with Feature model. -- auth-middleware: Implement auth middleware & RBAC utilities and protect example route. -- validation-middleware: Implement Zod validation middleware and apply to feature routes. -- openapi: Add OpenAPI generation and Swagger UI route. -- errors: Implement custom error classes and improve `error.middleware` mapping. -- repository-pattern: Add repository scaffolding and update FeatureService. -- observability: Add correlation id middleware and test-safe prom-client usage. -- docker-ci: Add .dockerignore and document Docker improvements in README. -- docs: Update README and ARCHITECTURE.md with new instructions. - -Each todo will contain detailed substeps when started. - -## Time estimates (rough) - -- High priority set (tests, env, prisma, validation, auth): 2–4 days -- Medium (openapi, errors, repo pattern): 1–2 days -- Low (docker polish, extra docs): 0.5–1 day - -## Next step - -If you approve, I will generate a concrete implementation plan and break the top-priority todos into file-level patches. If you prefer a different priority (e.g., focus on Auth first), tell me which to prioritize. \ No newline at end of file diff --git a/.cursor/plans/ui_design_modern_ai_chat.md b/.cursor/plans/ui_design_modern_ai_chat.md deleted file mode 100644 index 71f11bcf..00000000 --- a/.cursor/plans/ui_design_modern_ai_chat.md +++ /dev/null @@ -1,2506 +0,0 @@ -# Plan: Modern AI Chat UI Design - -## Tổng quan kiến trúc UI - -Dự án sẽ có 2 ứng dụng web chính với design language thống nhất: - -### Web Client (User-facing) - -- **Mục đích**: Chat interface cho end users tương tác với AI -- **Design inspiration**: x.ai Grok, OpenAI ChatGPT -- **Key features**: - - Minimalistic và intuitive - - Dark mode as default với light mode option - - Real-time chat với typing indicators - - Message history và conversation management - - Multi-modal input (text, voice future) - -### Web Admin (Admin-facing) - -- **Mục đích**: Dashboard quản lý users, analytics, system settings -- **Design inspiration**: Modern admin dashboards với AI-powered insights -- **Key features**: - - Analytics dashboard với charts/graphs - - User management với advanced filtering - - System monitoring và health checks - - Content moderation tools - - Configuration management -```mermaid -graph TB - subgraph Design System - Colors[Color Palette
Dark + Light Mode] - Typo[Typography
System Fonts] - Comp[Components
Radix UI] - Icons[Icons
Lucide React] - end - - subgraph Web Client - Auth1[Authentication] - Chat[Chat Interface] - History[Conversation History] - Settings1[User Settings] - end - - subgraph Web Admin - Dashboard[Analytics Dashboard] - Users[User Management] - Monitor[System Monitoring] - Settings2[Admin Settings] - end - - Colors --> Web Client - Colors --> Web Admin - Typo --> Web Client - Typo --> Web Admin - Comp --> Web Client - Comp --> Web Admin - Icons --> Web Client - Icons --> Web Admin -``` - - -## I. Design System Foundation - -### 1.1 Color Palette - -#### Dark Mode (Primary Theme) - -Dựa trên research, dark mode giảm eye strain 67% và là xu hướng chính cho AI chat interfaces. - -**Background Colors:** - -```css ---bg-primary: #0A0A0A /* Main background - Almost black */ ---bg-secondary: #121212 /* Card/Panel background - Dark grey (better depth) */ ---bg-tertiary: #1A1A1A /* Hover states */ ---bg-elevated: #242424 /* Elevated surfaces (modals, dropdowns) */ -``` - -**Text Colors (WCAG Compliant):** - -```css ---text-primary: #FAFAFA /* Primary text - Off-white (4.5:1 contrast) */ ---text-secondary: #E0E0E0 /* Secondary text - Light grey */ ---text-tertiary: #A0A0A0 /* Tertiary/disabled text */ ---text-inverse: #1A1A1A /* Text on light backgrounds */ -``` - -**Brand/Accent Colors:** - -```css ---accent-primary: #3B82F6 /* Primary blue - CTAs, links */ ---accent-secondary: #8B5CF6 /* Purple - Highlights */ ---accent-success: #10B981 /* Green - Success states */ ---accent-warning: #F59E0B /* Amber - Warnings */ ---accent-error: #EF4444 /* Red - Errors */ ---accent-info: #06B6D4 /* Cyan - Info */ -``` - -**Chat Specific Colors:** - -```css ---chat-user-bubble: #2563EB /* User message - Deep blue */ ---chat-ai-bubble: #374151 /* AI message - Dark grey */ ---chat-user-text: #FFFFFF /* White text on blue */ ---chat-ai-text: #F3F4F6 /* Light text on grey */ ---chat-timestamp: #9CA3AF /* Timestamp grey */ ---chat-divider: #1F2937 /* Divider between messages */ -``` - -**Border Colors:** - -```css ---border-primary: #2A2A2A /* Default borders */ ---border-secondary: #3A3A3A /* Hover borders */ ---border-focus: #3B82F6 /* Focus state - Blue */ -``` - -#### Light Mode (Secondary Theme) - -```css -/* Light mode variants */ ---bg-primary-light: #FFFFFF ---bg-secondary-light: #F9FAFB ---bg-tertiary-light: #F3F4F6 ---text-primary-light: #111827 ---text-secondary-light: #4B5563 ---border-primary-light: #E5E7EB -``` - -**Semantic Color Usage:** - -- Primary blue (#3B82F6): CTAs, primary buttons, active states -- Purple (#8B5CF6): Premium features, AI-related highlights -- Success green (#10B981): Confirmations, success messages -- Warning amber (#F59E0B): Warnings, caution states -- Error red (#EF4444): Errors, destructive actions - -### 1.2 Typography - -Theo OpenAI guidelines, sử dụng **system fonts** để ensure readability và accessibility. - -**Font Stack:** - -```css ---font-sans: - -apple-system, - BlinkMacSystemFont, - "SF Pro Display", /* iOS/macOS */ - "Segoe UI", /* Windows */ - Roboto, /* Android */ - "Helvetica Neue", - Arial, - sans-serif; - ---font-mono: - "SF Mono", - Consolas, - "Liberation Mono", - Menlo, - monospace; -``` - -**Type Scale (Tailwind-based):** - -```css -/* Display - Headers */ ---text-6xl: 3.75rem / 1 /* 60px - Hero titles */ ---text-5xl: 3rem / 1 /* 48px - Page titles */ ---text-4xl: 2.25rem / 1.1 /* 36px - Section headers */ ---text-3xl: 1.875rem / 1.2 /* 30px - Card headers */ - -/* Body */ ---text-2xl: 1.5rem / 1.3 /* 24px - Large body */ ---text-xl: 1.25rem / 1.4 /* 20px - Emphasized text */ ---text-lg: 1.125rem / 1.5 /* 18px - Large body */ ---text-base: 1rem / 1.5 /* 16px - Default body */ ---text-sm: 0.875rem / 1.5 /* 14px - Small text */ ---text-xs: 0.75rem / 1.5 /* 12px - Captions */ -``` - -**Font Weights:** - -```css ---font-light: 300 /* Light text */ ---font-normal: 400 /* Body text */ ---font-medium: 500 /* Emphasized */ ---font-semibold: 600 /* Headings */ ---font-bold: 700 /* Strong emphasis */ -``` - -**Chat Typography:** - -- Message text: 16px (text-base), regular weight -- Timestamps: 12px (text-xs), light weight -- User names: 14px (text-sm), medium weight -- System messages: 14px (text-sm), italic - -### 1.3 Spacing & Layout - -**Base Unit: 4px (0.25rem)** - -**Spacing Scale:** - -```css ---space-0: 0 /* 0px */ ---space-1: 0.25rem /* 4px */ ---space-2: 0.5rem /* 8px */ ---space-3: 0.75rem /* 12px */ ---space-4: 1rem /* 16px */ ---space-5: 1.25rem /* 20px */ ---space-6: 1.5rem /* 24px */ ---space-8: 2rem /* 32px */ ---space-10: 2.5rem /* 40px */ ---space-12: 3rem /* 48px */ ---space-16: 4rem /* 64px */ ---space-20: 5rem /* 80px */ -``` - -**Container Widths:** - -```css ---container-sm: 640px /* Small devices */ ---container-md: 768px /* Medium devices */ ---container-lg: 1024px /* Large devices */ ---container-xl: 1280px /* Extra large */ ---container-2xl: 1536px /* 2X large */ - -/* Chat specific */ ---chat-max-width: 768px /* Max width for chat messages */ ---sidebar-width: 280px /* Conversation history sidebar */ -``` - -**Border Radius:** - -```css ---radius-sm: 0.25rem /* 4px - Small elements */ ---radius-md: 0.5rem /* 8px - Buttons, inputs */ ---radius-lg: 0.75rem /* 12px - Cards */ ---radius-xl: 1rem /* 16px - Large cards */ ---radius-2xl: 1.5rem /* 24px - Modals */ ---radius-full: 9999px /* Full round - Avatars, pills */ -``` - -**Shadows (Dark Mode Optimized):** - -```css ---shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.5); ---shadow-md: 0 4px 6px rgba(0, 0, 0, 0.5); ---shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.6); ---shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.7); ---shadow-glow: 0 0 20px rgba(59, 130, 246, 0.3); /* Blue glow for focus */ -``` - -### 1.4 Grid System - -**Responsive Breakpoints:** - -```css ---screen-sm: 640px /* Mobile landscape */ ---screen-md: 768px /* Tablet */ ---screen-lg: 1024px /* Desktop */ ---screen-xl: 1280px /* Large desktop */ ---screen-2xl: 1536px /* Extra large desktop */ -``` - -**Layout Patterns:** - -- **Single Column (Mobile)**: < 768px - Full width content -- **Two Column (Tablet)**: 768px - 1024px - Sidebar + Main -- **Three Column (Desktop)**: > 1024px - Sidebar + Main + Panel - -### 1.5 Animation & Transitions - -**Timing Functions:** - -```css ---ease-in: cubic-bezier(0.4, 0, 1, 1); ---ease-out: cubic-bezier(0, 0, 0.2, 1); ---ease-in-out: cubic-bezier(0.4, 0, 0.2, 1); ---ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1); -``` - -**Duration:** - -```css ---duration-fast: 150ms /* Hover effects */ ---duration-normal: 250ms /* Default transitions */ ---duration-slow: 350ms /* Complex animations */ ---duration-slower: 500ms /* Page transitions */ -``` - -**Common Transitions:** - -```css -/* Smooth hover */ -transition: all var(--duration-fast) var(--ease-out); - -/* Button press */ -transition: transform var(--duration-fast) var(--ease-in-out); - -/* Modal open */ -transition: opacity var(--duration-normal) var(--ease-in-out), - transform var(--duration-normal) var(--ease-spring); -``` - -**Micro-interactions (2026 Trend):** - -- Button hover: Subtle scale (1.02) + brightness -- Card hover: Lift effect (translateY -2px) + shadow -- Input focus: Glow effect (box-shadow) + border color -- Message send: Slide up + fade in -- Typing indicator: Pulsing dots animation - -## II. Component Library - -### 2.1 Core Components (Radix UI based) - -#### Button - -**Variants:** - -```typescript -// Primary - Main CTAs - - -// Secondary - Less emphasis - - -// Ghost - Minimal - - -// Danger - Destructive actions - -``` - -**Sizes:** - -- `xs`: 28px height, 12px text, 12px padding -- `sm`: 32px height, 14px text, 16px padding -- `md`: 40px height, 16px text, 20px padding (default) -- `lg`: 48px height, 18px text, 24px padding -- `xl`: 56px height, 20px text, 28px padding - -**States:** - -- Default: Normal appearance -- Hover: Brightness 110%, slight scale (1.02) -- Active: Brightness 90%, scale (0.98) -- Focus: Blue glow shadow -- Disabled: Opacity 50%, cursor not-allowed -- Loading: Spinner icon, disabled state - -**Implementation:** - -```css -/* Primary Button */ -.btn-primary { - background: var(--accent-primary); - color: white; - border-radius: var(--radius-md); - padding: var(--space-3) var(--space-5); - font-weight: var(--font-medium); - transition: all var(--duration-fast) var(--ease-out); -} - -.btn-primary:hover { - filter: brightness(1.1); - transform: scale(1.02); -} - -.btn-primary:focus-visible { - outline: none; - box-shadow: var(--shadow-glow); -} -``` - -#### Input Fields - -**Types:** - -- Text Input -- Textarea -- Select -- Multi-select -- Date Picker -- Search (with icon) - -**Structure:** - -```tsx -
- - - We'll never share your email -
-``` - -**Styles:** - -```css -.input { - background: var(--bg-secondary); - border: 1px solid var(--border-primary); - color: var(--text-primary); - border-radius: var(--radius-md); - padding: var(--space-3) var(--space-4); - font-size: var(--text-base); - transition: all var(--duration-fast) var(--ease-out); -} - -.input:focus { - border-color: var(--accent-primary); - box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); - outline: none; -} - -.input::placeholder { - color: var(--text-tertiary); -} - -.input-hint { - color: var(--text-tertiary); - font-size: var(--text-sm); - margin-top: var(--space-1); -} -``` - -**States:** - -- Default -- Focus (blue border + glow) -- Error (red border + error message) -- Success (green border + checkmark) -- Disabled (grey + cursor not-allowed) - -#### Card - -**Variants:** - -```tsx -// Default Card - - - Card Title - Card description - - - Content goes here - - - Footer actions - - - -// Interactive Card (hover effect) - - ... - - -// Bordered Card - - ... - -``` - -**Styles:** - -```css -.card { - background: var(--bg-secondary); - border-radius: var(--radius-lg); - padding: var(--space-6); - transition: all var(--duration-normal) var(--ease-out); -} - -.card.hover:hover { - transform: translateY(-2px); - box-shadow: var(--shadow-lg); -} - -.card-header { - margin-bottom: var(--space-4); -} - -.card-title { - font-size: var(--text-xl); - font-weight: var(--font-semibold); - color: var(--text-primary); -} - -.card-description { - font-size: var(--text-sm); - color: var(--text-secondary); - margin-top: var(--space-1); -} -``` - -#### Modal/Dialog - -**Structure:** - -```tsx - - - - - - - Dialog Title - - Dialog description text - - -
- {/* Content */} -
- - - - -
-
-``` - -**Animation:** - -```css -/* Overlay fade in */ -@keyframes overlay-fade { - from { opacity: 0; } - to { opacity: 1; } -} - -/* Content scale + fade */ -@keyframes content-show { - from { - opacity: 0; - transform: translate(-50%, -48%) scale(0.96); - } - to { - opacity: 1; - transform: translate(-50%, -50%) scale(1); - } -} - -.dialog-overlay { - background: rgba(0, 0, 0, 0.6); - backdrop-filter: blur(8px); - animation: overlay-fade var(--duration-normal) var(--ease-out); -} - -.dialog-content { - background: var(--bg-elevated); - border-radius: var(--radius-2xl); - box-shadow: var(--shadow-xl); - animation: content-show var(--duration-normal) var(--ease-spring); -} -``` - -#### Avatar - -**Sizes:** - -- `xs`: 24px -- `sm`: 32px -- `md`: 40px (default) -- `lg`: 48px -- `xl`: 64px - -**States:** - -- Image loaded -- Fallback (initials) -- Loading (skeleton) -- Status indicator (online/offline/away) -```tsx - - - JD - -``` - - -### 2.2 Chat-Specific Components - -#### Message Bubble - -**Structure:** - -```tsx -
-
- You - 2:30 PM -
-
-

Hello, how can I help you?

-
-
- -
- -
-
- AI Assistant - 2:31 PM -
-
-

I can help you with...

-
-
-
-``` - -**Styles:** - -```css -/* User Message (Right aligned, blue) */ -.message.user { - display: flex; - flex-direction: column; - align-items: flex-end; - margin-bottom: var(--space-4); -} - -.message.user .message-bubble { - background: var(--chat-user-bubble); - color: var(--chat-user-text); - border-radius: var(--radius-lg) var(--radius-lg) var(--radius-sm) var(--radius-lg); - padding: var(--space-3) var(--space-4); - max-width: 70%; - word-wrap: break-word; -} - -/* AI Message (Left aligned, grey) */ -.message.ai { - display: flex; - gap: var(--space-3); - margin-bottom: var(--space-4); -} - -.message.ai .message-bubble { - background: var(--chat-ai-bubble); - color: var(--chat-ai-text); - border-radius: var(--radius-lg) var(--radius-lg) var(--radius-lg) var(--radius-sm); - padding: var(--space-3) var(--space-4); - max-width: 70%; -} - -/* Message Header */ -.message-header { - display: flex; - align-items: center; - gap: var(--space-2); - margin-bottom: var(--space-1); -} - -.message-author { - font-size: var(--text-sm); - font-weight: var(--font-medium); - color: var(--text-secondary); -} - -.message-time { - font-size: var(--text-xs); - color: var(--chat-timestamp); -} -``` - -**Message Animations:** - -```css -/* Slide up + fade in */ -@keyframes message-in { - from { - opacity: 0; - transform: translateY(10px); - } - to { - opacity: 1; - transform: translateY(0); - } -} - -.message { - animation: message-in var(--duration-normal) var(--ease-out); -} -``` - -#### Typing Indicator - -```tsx -
-
-
-
-
-``` -```css -.typing-indicator { - display: flex; - gap: 4px; - padding: var(--space-3); -} - -.typing-dot { - width: 8px; - height: 8px; - border-radius: 50%; - background: var(--text-tertiary); - animation: typing 1.4s infinite; -} - -.typing-dot:nth-child(2) { - animation-delay: 0.2s; -} - -.typing-dot:nth-child(3) { - animation-delay: 0.4s; -} - -@keyframes typing { - 0%, 60%, 100% { - opacity: 0.3; - transform: scale(0.8); - } - 30% { - opacity: 1; - transform: scale(1); - } -} -``` - -#### Chat Input - -```tsx -
-
- - -