From b1b32a1112402bf05bac27c4cdbf0358f2478d6e Mon Sep 17 00:00:00 2001 From: Mayank Date: Mon, 24 Aug 2026 12:54:01 +0530 Subject: [PATCH 1/2] refactor: implement domain-driven auth module with ports and adapters and remove obsolete documentation files --- API_DOCUMENTATION.md | 764 ---------------------------- CONFIGURATION.md | 679 ------------------------ DEPLOYMENT.md | 759 --------------------------- DEVELOPMENT.md | 509 ------------------ Dockerfile | 68 +-- QUICK_START.md | 86 ---- issues/001-auth-domain-deepening.md | 177 +++++++ 7 files changed, 211 insertions(+), 2831 deletions(-) delete mode 100644 API_DOCUMENTATION.md delete mode 100644 CONFIGURATION.md delete mode 100644 DEPLOYMENT.md delete mode 100644 DEVELOPMENT.md delete mode 100644 QUICK_START.md create mode 100644 issues/001-auth-domain-deepening.md diff --git a/API_DOCUMENTATION.md b/API_DOCUMENTATION.md deleted file mode 100644 index 53fa51f..0000000 --- a/API_DOCUMENTATION.md +++ /dev/null @@ -1,764 +0,0 @@ -# Auth Service API Documentation - -A production-ready Node.js/TypeScript authentication service built with Express.js, PostgreSQL, and Drizzle ORM. - -## ๐Ÿš€ Features - -- **JWT Authentication** with refresh tokens -- **OAuth Support** (Google & GitHub) -- **Email Verification** with Resend -- **Password Reset** functionality -- **Rate Limiting** for security -- **Input Validation** with Zod schemas -- **Security Headers** via Helmet -- **Health Monitoring** endpoints -- **TypeScript** for type safety -- **PostgreSQL** with Drizzle ORM - -## ๐Ÿ“‹ Table of Contents - -- [Installation](#installation) -- [Environment Variables](#environment-variables) -- [Database Setup](#database-setup) -- [API Endpoints](#api-endpoints) -- [Authentication](#authentication) -- [Security Features](#security-features) -- [Health Checks](#health-checkes) -- [Error Handling](#error-handling) -- [Rate Limiting](#rate-limiting) -- [Development](#development) -- [Deployment](#deployment) - -## ๐Ÿ›  Installation - -### Prerequisites -- Node.js 18+ -- PostgreSQL database -- pnpm package manager - -### Setup - -1. **Clone the repository** -```bash -git clone -cd auth-service -``` - -2. **Install dependencies** -```bash -pnpm install -``` - -3. **Configure environment variables** -```bash -cp .env.example .env -# Edit .env with your configuration -``` - -4. **Setup database** -```bash -# Run database migrations -pnpm db:migrate - -# (Optional) Seed database with test data -pnpm db:seed -``` - -5. **Start the service** -```bash -# Development -pnpm dev - -# Production -pnpm build -pnpm start -``` - -## โš™๏ธ Environment Variables - -Create a `.env` file with the following variables: - -```env -# Application -NODE_ENV=development -PORT=4000 -ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001 - -# Database -DATABASE_URL=postgresql://username:password@host:port/database - -# JWT Tokens -ACCESS_TOKEN_SECRET=your-super-secret-access-token-min-32-chars -REFRESH_TOKEN_SECRET=your-super-secret-refresh-token-min-32-chars - -# Email Service (Resend) -RESEND_API_KEY=re_your_api_key -RESEND_FROM_EMAIL=noreply@yourdomain.com - -# Session -EXPRESS_SESSION_SECRET=your-session-secret-min-32-chars - -# OAuth -GOOGLE_CLIENT_ID=your_google_client_id -GOOGLE_CLIENT_SECRET=your_google_client_secret - -GITHUB_CLIENT_ID=your_github_client_id -GITHUB_CLIENT_SECRET=your_github_client_secret - -# Redirect URLs -CLIENT_SSO_REDIRECT_URL=http://localhost:3000/auth/callback -FORGOT_PASSWORD_REDIRECT_URL=http://localhost:3000/reset-password -``` - -## ๐Ÿ—„ Database Setup - -### PostgreSQL with Neon (Recommended) - -1. **Create Neon account** at [neon.tech](https://neon.tech) -2. **Create database** and get connection string -3. **Add DATABASE_URL** to your `.env` file - -### Local PostgreSQL - -```bash -# Create database -createdb auth_service - -# Run migrations -pnpm db:migrate -``` - -### Database Schema - -The service uses the following main tables: - -- **users** - User accounts and profiles -- **user_sessions** - Active user sessions -- **email_verifications** - Email verification tokens - -## ๐ŸŒ API Endpoints - -### Base URL -``` -http://localhost:4000/api/v1 -``` - -### Health Check Endpoints - -#### Get Full Health Check -```http -GET /healthcheck -``` - -**Response:** -```json -{ - "statusCode": 200, - "success": true, - "message": "Health Check Passed", - "data": { - "status": "OK", - "timestamp": "2025-12-26T07:58:30.173Z", - "uptime": 13.367850478, - "server": "running", - "database": "connected", - "environment": "development" - } -} -``` - -#### Get Simple Health Check -```http -GET /healthcheck/simple -``` - -**Response:** -```json -{ - "statusCode": 200, - "success": true, - "message": "Server Health Check Passed", - "data": { - "status": "OK", - "timestamp": "2025-12-26T07:58:30.419Z", - "uptime": 13.613790279, - "server": "running", - "environment": "development" - } -} -``` - -### Authentication Endpoints - -#### Register User -```http -POST /users/register -``` - -**Request Body:** -```json -{ - "username": "johndoe", - "email": "john@example.com", - "password": "SecurePass123!", - "fullName": "John Doe" -} -``` - -**Response:** -```json -{ - "statusCode": 201, - "success": true, - "message": "Users registered successfully and verification email has been sent on your email.", - "data": { - "user": { - "id": "uuid", - "email": "john@example.com", - "username": "johndoe", - "fullName": "John Doe", - "isEmailVerified": false, - "isActive": true, - "role": "user", - "createdAt": "2025-12-26T07:58:31.868Z" - } - } -} -``` - -#### Login User -```http -POST /users/login -``` - -**Request Body:** -```json -{ - "username": "johndoe", - "password": "SecurePass123!" -} -``` - -**Response:** -```json -{ - "statusCode": 200, - "success": true, - "message": "User logged in successfully", - "data": { - "user": { - "id": "uuid", - "email": "john@example.com", - "username": "johndoe", - "fullName": "John Doe", - "isEmailVerified": true, - "isActive": true, - "role": "user" - }, - "accessToken": "jwt_access_token", - "refreshToken": "jwt_refresh_token" - } -} -``` - -#### Refresh Access Token -```http -POST /users/refresh-token -``` - -**Request Body:** -```json -{ - "refreshToken": "jwt_refresh_token" -} -``` - -**Response:** -```json -{ - "statusCode": 200, - "success": true, - "message": "Access token refreshed successfully", - "data": { - "accessToken": "new_jwt_access_token" - } -} -``` - -#### Logout User -```http -POST /users/logout -``` - -**Headers:** -```http -Authorization: Bearer -``` - -**Response:** -```json -{ - "statusCode": 200, - "success": true, - "message": "User logged out successfully", - "data": {} -} -``` - -#### Forgot Password -```http -POST /users/forgot-password -``` - -**Request Body:** -```json -{ - "email": "john@example.com" -} -``` - -**Response:** -```json -{ - "statusCode": 200, - "success": true, - "message": "Password reset email sent successfully", - "data": {} -} -``` - -#### Reset Password -```http -POST /users/reset-password -``` - -**Request Body:** -```json -{ - "resetToken": "reset_token_from_email", - "newPassword": "NewSecurePass123!" -} -``` - -**Response:** -```json -{ - "statusCode": 200, - "success": true, - "message": "Password reset successfully", - "data": {} -} -``` - -#### Verify Email -```http -POST /users/verify-email -``` - -**Request Body:** -```json -{ - "verificationToken": "token_from_email" -} -``` - -**Response:** -```json -{ - "statusCode": 200, - "success": true, - "message": "Email verified successfully", - "data": {} -} -``` - -### OAuth Endpoints - -#### Google OAuth -```http -GET /users/auth/google -``` - -#### Google OAuth Callback -```http -GET /users/auth/google/callback -``` - -#### GitHub OAuth -```http -GET /users/auth/github -``` - -#### GitHub OAuth Callback -```http -GET /users/auth/github/callback -``` - -## ๐Ÿ” Authentication - -### JWT Token Structure - -**Access Token:** -- **Expiration:** 15 minutes -- **Usage:** API requests -- **Header:** `Authorization: Bearer ` - -**Refresh Token:** -- **Expiration:** 7 days -- **Usage:** Get new access tokens -- **Storage:** HTTP-only cookies - -### Token Refresh Flow - -1. **Client** sends refresh token to `/users/refresh-token` -2. **Server** validates refresh token -3. **Server** generates new access token -4. **Client** uses new access token for API calls - -### Protected Routes - -Add the `Authorization` header to access protected routes: - -```http -Authorization: Bearer -``` - -## ๐Ÿ›ก Security Features - -### Rate Limiting - -- **Auth Endpoints:** 5 requests per 15 minutes -- **Other Endpoints:** No rate limiting -- **Headers:** `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset` - -### Security Headers - -Implemented via Helmet.js: - -- **Content Security Policy:** Strict CSP configuration -- **HSTS:** HTTP Strict Transport Security -- **X-Frame-Options:** `SAMEORIGIN` -- **X-Content-Type-Options:** `nosniff` -- **Referrer Policy:** `no-referrer` - -### Input Validation - -All inputs are validated using Zod schemas: - -- **Email:** Valid email format -- **Password:** 8+ chars, uppercase, lowercase, number, special character -- **Username:** 3+ characters, alphanumeric -- **Full Name:** Required, non-empty - -### Password Security - -- **Hashing:** bcrypt with 12 salt rounds -- **Storage:** Only hashed passwords stored -- **Validation:** Strong password requirements - -## ๐Ÿฅ Health Checks - -### Monitoring Endpoints - -| Endpoint | Purpose | Database Dependency | -|----------|---------|---------------------| -| `/healthcheck` | Full system health | โœ… Required | -| `/healthcheck/simple` | Server health only | โŒ Not required | - -### Health Check Response - -**Healthy Response (200):** -```json -{ - "status": "OK", - "timestamp": "2025-12-26T07:58:30.173Z", - "uptime": 13.367850478, - "server": "running", - "database": "connected", - "environment": "development" -} -``` - -**Degraded Response (503):** -```json -{ - "status": "DEGRADED", - "timestamp": "2025-12-26T07:58:30.173Z", - "uptime": 13.367850478, - "server": "running", - "database": "disconnected", - "environment": "development" -} -``` - -## โš  Error Handling - -### Standard Error Response - -```json -{ - "statusCode": 400, - "success": false, - "message": "Error description", - "errors": [ - { - "field": "email", - "message": "Invalid email format" - } - ] -} -``` - -### Common HTTP Status Codes - -| Status | Description | Example | -|--------|-------------|---------| -| 200 | Success | Login successful | -| 201 | Created | User registered | -| 400 | Bad Request | Invalid input | -| 401 | Unauthorized | Invalid token | -| 403 | Forbidden | Access denied | -| 404 | Not Found | Endpoint not found | -| 429 | Too Many Requests | Rate limit exceeded | -| 500 | Server Error | Internal error | -| 503 | Service Unavailable | Database disconnected | - -### Validation Errors - -```json -{ - "statusCode": 400, - "success": false, - "message": "Validation failed", - "errors": [ - { - "field": "email", - "message": "Invalid email format" - }, - { - "field": "password", - "message": "Password must be at least 8 characters long" - } - ] -} -``` - -## ๐Ÿšฆ Rate Limiting - -### Configuration - -- **Window:** 15 minutes -- **Limit:** 5 requests per IP -- **Endpoints:** All authentication endpoints -- **Headers:** Rate limit information included - -### Rate Limit Headers - -```http -RateLimit-Limit: 5 -RateLimit-Remaining: 3 -RateLimit-Reset: 900 -RateLimit-Policy: 5;w=900 -``` - -### Rate Limit Exceeded Response - -```json -{ - "statusCode": 429, - "success": false, - "message": "Too many authentication attempts, please try again later." -} -``` - -## ๐Ÿ›  Development - -### Available Scripts - -```bash -# Start development server -pnpm dev - -# Build for production -pnpm build - -# Start production server -pnpm start - -# Run database migrations -pnpm db:migrate - -# Generate new migration -pnpm db:generate - -# Push schema changes -pnpm db:push - -# Drop database -pnpm db:drop - -# Run tests -pnpm test - -# Run linting -pnpm lint - -# Type checking -pnpm typecheck -``` - -### Database Commands - -```bash -# Create new migration -pnpm drizzle-kit generate - -# Run migrations -pnpm drizzle-kit migrate - -# View database -pnpm drizzle-kit studio -``` - -### Project Structure - -``` -src/ -โ”œโ”€โ”€ config/ # Configuration files -โ”œโ”€โ”€ controllers/ # Route controllers -โ”œโ”€โ”€ db/ # Database schema -โ”œโ”€โ”€ lib/ # External libraries -โ”œโ”€โ”€ logger/ # Logging configuration -โ”œโ”€โ”€ middlewares/ # Express middlewares -โ”œโ”€โ”€ passport/ # OAuth strategies -โ”œโ”€โ”€ routes/ # API routes -โ”œโ”€โ”€ types/ # TypeScript types -โ”œโ”€โ”€ utils/ # Utility functions -โ”œโ”€โ”€ validators/ # Input validation schemas -โ”œโ”€โ”€ app.ts # Express app configuration -โ””โ”€โ”€ server.ts # Server entry point -``` - -## ๐Ÿš€ Deployment - -### Production Setup - -1. **Environment Configuration** -```bash -NODE_ENV=production -PORT=4000 -``` - -2. **Database Setup** -```bash -# Run migrations -pnpm db:migrate -``` - -3. **Build Application** -```bash -pnpm build -``` - -4. **Start Server** -```bash -pnpm start -``` - -### Docker Deployment - -```dockerfile -FROM node:18-alpine - -WORKDIR /app - -COPY package*.json ./ -RUN pnpm install --prod - -COPY . . -RUN pnpm build - -EXPOSE 4000 - -CMD ["pnpm", "start"] -``` - -### Environment-Specific Configurations - -**Development:** -- Detailed error messages -- Development database -- Relaxed security headers -- Debug logging - -**Production:** -- Generic error messages -- Production database -- Strict security headers -- Error logging only - -## ๐Ÿ“ API Examples - -### Registration Example - -```bash -curl -X POST http://localhost:4000/api/v1/users/register \ - -H "Content-Type: application/json" \ - -d '{ - "username": "johndoe", - "email": "john@example.com", - "password": "SecurePass123!", - "fullName": "John Doe" - }' -``` - -### Login Example - -```bash -curl -X POST http://localhost:4000/api/v1/users/login \ - -H "Content-Type: application/json" \ - -d '{ - "username": "johndoe", - "password": "SecurePass123!" - }' -``` - -### Protected Route Example - -```bash -curl -X GET http://localhost:4000/api/v1/users/profile \ - -H "Authorization: Bearer " -``` - -## ๐Ÿค Contributing - -1. Fork the repository -2. Create a feature branch -3. Make your changes -4. Add tests if applicable -5. Submit a pull request - -## ๐Ÿ“„ License - -This project is licensed under the MIT License - see the LICENSE file for details. - -## ๐Ÿ†˜ Support - -For support and questions: - -- Create an issue in the repository -- Check the documentation -- Review the API examples - -## ๐Ÿ”— Related Services - -- **Frontend Application:** Your client application -- **Email Service:** Resend for transactional emails -- **Database:** PostgreSQL (Neon recommended) -- **OAuth Providers:** Google & GitHub - ---- - -**Version:** 1.0.0 -**Last Updated:** 2025-12-26 -**Author:** Auth Service Team \ No newline at end of file diff --git a/CONFIGURATION.md b/CONFIGURATION.md deleted file mode 100644 index 2e2211d..0000000 --- a/CONFIGURATION.md +++ /dev/null @@ -1,679 +0,0 @@ -# Configuration Guide - -Complete guide for configuring the Auth Service in different environments. - -## โš™๏ธ Environment Configuration - -### Environment Variables Overview - -The Auth Service uses environment variables for configuration across different environments (development, staging, production). - -### Required Variables - -| Variable | Description | Example | Required | -|----------|-------------|---------|----------| -| `DATABASE_URL` | PostgreSQL connection string | `postgresql://user:pass@host:5432/db` | โœ… | -| `ACCESS_TOKEN_SECRET` | JWT access token secret (32+ chars) | `super-secret-access-token-key` | โœ… | -| `REFRESH_TOKEN_SECRET` | JWT refresh token secret (32+ chars) | `super-secret-refresh-token-key` | โœ… | -| `RESEND_API_KEY` | Resend email service API key | `re_your_api_key_here` | โœ… | -| `RESEND_FROM_EMAIL` | From email for transactional emails | `noreply@yourdomain.com` | โœ… | -| `EXPRESS_SESSION_SECRET` | Express session secret (32+ chars) | `session-secret-key-here` | โœ… | - -### Optional Variables - -| Variable | Description | Default | Example | -|----------|-------------|---------|---------| -| `NODE_ENV` | Environment mode | `development` | `production` | -| `PORT` | Server port | `4000` | `8080` | -| `ALLOWED_ORIGINS` | CORS allowed origins | `http://localhost:3000` | `https://app.domain.com` | -| `GOOGLE_CLIENT_ID` | Google OAuth client ID | - | `your-google-client-id` | -| `GOOGLE_CLIENT_SECRET` | Google OAuth client secret | - | `your-google-client-secret` | -| `GITHUB_CLIENT_ID` | GitHub OAuth client ID | - | `your-github-client-id` | -| `GITHUB_CLIENT_SECRET` | GitHub OAuth client secret | - | `your-github-client-secret` | -| `CLIENT_SSO_REDIRECT_URL` | OAuth callback URL | - | `https://app.domain.com/auth/callback` | -| `FORGOT_PASSWORD_REDIRECT_URL` | Password reset redirect URL | - | `https://app.domain.com/reset-password` | - -## ๐Ÿ—„ Database Configuration - -### PostgreSQL Connection String Format - -```bash -# Standard format -postgresql://username:password@host:port/database - -# With SSL and connection pooling -postgresql://user:pass@host:5432/db?sslmode=require&connection_limit=20 - -# Neon PostgreSQL example -postgresql://neondb_owner:npg_xxx@ep-xxx.us-east-1.aws.neon.tech/neondb?sslmode=require -``` - -### Database Connection Options - -```typescript -// src/config/db.ts -const pool = new Pool({ - connectionString: env.DATABASE_URL, - max: 20, // Maximum connections - idleTimeoutMillis: 30000, // Idle timeout - connectionTimeoutMillis: 10000, // Connection timeout - ssl: { - rejectUnauthorized: false // For cloud databases - }, - application_name: "auth-service" -}); -``` - -### Database Schema Configuration - -```typescript -// src/db/schema/user.ts -import { pgTable, text, timestamp, boolean, uuid, enum as pgEnum } from 'drizzle-orm/pg-core'; - -// Enums -export const loginTypeEnum = pgEnum('login_type', ['email_password', 'google', 'github']); -export const roleEnum = pgEnum('role', ['admin', 'user']); - -// Users table -export const User = pgTable("users", { - id: uuid("id").defaultRandom().primaryKey(), - email: text("email").notNull().unique(), - username: text("username").notNull().unique(), - password: text("password"), - fullName: text("full_name").notNull(), - loginType: loginTypeEnum("login_type").default("email_password"), - providerId: text("provider_id"), - profilePicture: text("profile_picture"), - isEmailVerified: boolean("is_email_verified").default(false), - isActive: boolean("is_active").default(true), - role: roleEnum("role").default("user"), - refreshToken: text("refresh_token"), - forgotPasswordToken: text("forgot_password_token"), - forgotPasswordTokenExpiresAt: timestamp("forgot_password_token_expires_at"), - emailVerificationToken: text("email_verification_token"), - emailVerificationExpiry: timestamp("email_verification_expiry"), - lastLoginAt: timestamp("last_login_at"), - createdAt: timestamp("created_at").defaultNow(), - updatedAt: timestamp("updated_at").defaultNow() -}, (table) => ({ - // Indexes for performance - emailIdx: index("email_idx").on(table.email), - usernameIdx: index("username_idx").on(table.username), - activeUserIdx: index("active_user_idx").on(table.isActive).where(eq(table.isActive, true)) -})); -``` - -## ๐Ÿ” Security Configuration - -### JWT Token Configuration - -```typescript -// src/utils/token.ts -import jwt from 'jsonwebtoken'; - -// Access token configuration -const accessTokenConfig = { - secret: process.env.ACCESS_TOKEN_SECRET!, - expiresIn: '15m', - algorithm: 'HS256' as const -}; - -// Refresh token configuration -const refreshTokenConfig = { - secret: process.env.REFRESH_TOKEN_SECRET!, - expiresIn: '7d', - algorithm: 'HS256' as const -}; - -// Generate tokens -export const generateTokens = (userId: string) => { - const accessToken = jwt.sign( - { sub: userId, type: 'access' }, - accessTokenConfig.secret, - { expiresIn: accessTokenConfig.expiresIn, algorithm: accessTokenConfig.algorithm } - ); - - const refreshToken = jwt.sign( - { sub: userId, type: 'refresh' }, - refreshTokenConfig.secret, - { expiresIn: refreshTokenConfig.expiresIn, algorithm: refreshTokenConfig.algorithm } - ); - - return { accessToken, refreshToken }; -}; -``` - -### Password Security Configuration - -```typescript -// src/utils/password.ts -import bcrypt from 'bcrypt'; - -// Password hashing configuration -const saltRounds = 12; - -export const hashPassword = async (password: string): Promise => { - return await bcrypt.hash(password, saltRounds); -}; - -export const verifyPassword = async (password: string, hash: string): Promise => { - return await bcrypt.compare(password, hash); -}; -``` - -### Security Headers Configuration - -```typescript -// src/app.ts -import helmet from 'helmet'; - -// Production security headers -const securityConfig = { - contentSecurityPolicy: { - directives: { - defaultSrc: ["'self'"], - styleSrc: ["'self'", "'unsafe-inline'"], - scriptSrc: ["'self'"], - imgSrc: ["'self'", "data:", "https:"], - connectSrc: ["'self'"], - fontSrc: ["'self'"], - objectSrc: ["'none'"], - mediaSrc: ["'self'"], - frameSrc: ["'none'"], - }, - }, - hsts: { - maxAge: 31536000, - includeSubDomains: true, - preload: true - } -}; - -app.use(helmet(securityConfig)); -``` - -### CORS Configuration - -```typescript -// src/app.ts -import cors from 'cors'; - -const corsConfig = { - origin: process.env.ALLOWED_ORIGINS?.split(',') || ["http://localhost:3000"], - credentials: true, - methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], - allowedHeaders: ["Content-Type", "Authorization"], - optionsSuccessStatus: 200 -}; - -app.use(cors(corsConfig)); -``` - -### Rate Limiting Configuration - -```typescript -// src/app.ts -import rateLimit from 'express-rate-limit'; - -// Auth endpoints rate limiting -const authLimiter = rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 5, // 5 requests per window - message: "Too many authentication attempts, please try again later.", - standardHeaders: true, - legacyHeaders: false, - skipSuccessfulRequests: false, - skipFailedRequests: false -}); - -// Apply to auth routes -app.use("/api/v1/users", authLimiter); -``` - -## ๐Ÿ“ง Email Configuration - -### Resend Email Service - -```typescript -// src/utils/mail.ts -import { Resend } from 'resend'; - -const resend = new Resend(process.env.RESEND_API_KEY); - -// Email configuration -const emailConfig = { - from: process.env.RESEND_FROM_EMAIL!, - replyTo: process.env.RESEND_REPLY_TO_EMAIL || process.env.RESEND_FROM_EMAIL -}; - -// Send email function -export const sendEmail = async (to: string, subject: string, html: string) => { - try { - const { data, error } = await resend.emails.send({ - from: emailConfig.from, - to: [to], - subject, - html - }); - - if (error) { - throw new Error(`Email send failed: ${error.message}`); - } - - return data; - } catch (error) { - console.error('Email service error:', error); - throw error; - } -}; -``` - -### Email Templates Configuration - -```typescript -// src/templates/email.ts -export const emailTemplates = { - verification: (token: string, userName: string) => ({ - subject: 'Verify Your Email Address', - html: ` -

Welcome ${userName}!

-

Thank you for registering. Please verify your email address by clicking the link below:

- Verify Email -

This link will expire in 24 hours.

- ` - }), - - passwordReset: (token: string, userName: string) => ({ - subject: 'Reset Your Password', - html: ` -

Hello ${userName}!

-

You requested to reset your password. Click the link below to reset it:

- Reset Password -

This link will expire in 1 hour.

-

If you didn't request this, please ignore this email.

- ` - }) -}; -``` - -## ๐ŸŒ OAuth Configuration - -### Google OAuth Setup - -1. **Create Google Cloud Project** - - Go to [Google Cloud Console](https://console.cloud.google.com/) - - Create new project or select existing one - - Enable Google+ API - -2. **Create OAuth Credentials** - - Go to "Credentials" โ†’ "Create Credentials" โ†’ "OAuth 2.0 Client IDs" - - Select "Web application" - - Add authorized redirect URI: `https://yourdomain.com/api/v1/users/auth/google/callback` - -3. **Environment Variables** -```env -GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com -GOOGLE_CLIENT_SECRET=your-google-client-secret -``` - -### GitHub OAuth Setup - -1. **Create GitHub OAuth App** - - Go to GitHub Settings โ†’ Developer settings โ†’ OAuth Apps - - Click "New OAuth App" - - Fill in application details - - Set callback URL: `https://yourdomain.com/api/v1/users/auth/github/callback` - -2. **Environment Variables** -```env -GITHUB_CLIENT_ID=your-github-client-id -GITHUB_CLIENT_SECRET=your-github-client-secret -``` - -### Passport.js Configuration - -```typescript -// src/passport/google.strategy.ts -import passport from 'passport'; -import { Strategy as GoogleStrategy } from 'passport-google-oauth20'; - -passport.use(new GoogleStrategy({ - clientID: process.env.GOOGLE_CLIENT_ID!, - clientSecret: process.env.GOOGLE_CLIENT_SECRET!, - callbackURL: "/api/v1/users/auth/google/callback", - scope: ['profile', 'email'] -}, async (accessToken, refreshToken, profile, done) => { - try { - // Handle OAuth user creation/login - let user = await findUserByProviderId('google', profile.id); - - if (!user) { - user = await createOAuthUser({ - providerId: profile.id, - email: profile.emails[0].value, - username: profile.displayName, - fullName: profile.displayName, - loginType: 'google', - profilePicture: profile.photos[0].value - }); - } - - return done(null, user); - } catch (error) { - return done(error, null); - } -})); -``` - -## ๐Ÿ“Š Logging Configuration - -### Winston Logger Configuration - -```typescript -// src/logger/winston.logger.ts -import winston from 'winston'; - -const logFormat = winston.format.combine( - winston.format.timestamp(), - winston.format.errors({ stack: true }), - winston.format.json() -); - -const logger = winston.createLogger({ - level: process.env.LOG_LEVEL || 'info', - format: logFormat, - defaultMeta: { service: 'auth-service' }, - transports: [ - // Error logs - new winston.transports.File({ - filename: 'logs/error.log', - level: 'error', - maxsize: 5242880, // 5MB - maxFiles: 5 - }), - - // Combined logs - new winston.transports.File({ - filename: 'logs/combined.log', - maxsize: 5242880, // 5MB - maxFiles: 5 - }) - ] -}); - -// Console logging for development -if (process.env.NODE_ENV !== 'production') { - logger.add(new winston.transports.Console({ - format: winston.format.simple() - })); -} - -export default logger; -``` - -### Morgan HTTP Logger Configuration - -```typescript -// src/logger/morgan.logger.ts -import morgan from 'morgan'; -import winston from './winston.logger'; - -const stream = { - write: (message: string) => { - winston.info(message.trim()); - } -}; - -const morganMiddleware = morgan( - ':method :url :status :res[content-length] - :response-time ms', - { stream } -); - -export default morganMiddleware; -``` - -## ๐Ÿ” Environment-Specific Configurations - -### Development Configuration - -```env -# .env.development -NODE_ENV=development -PORT=4000 -LOG_LEVEL=debug - -# Database (local) -DATABASE_URL=postgresql://postgres:password@localhost:5432/auth_service_dev - -# JWT (development secrets) -ACCESS_TOKEN_SECRET=dev-access-token-secret-key -REFRESH_TOKEN_SECRET=dev-refresh-token-secret-key - -# Email (development - can use test service) -RESEND_API_KEY=re_test_api_key -RESEND_FROM_EMAIL=dev@localhost - -# CORS (development origins) -ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001 - -# Session -EXPRESS_SESSION_SECRET=dev-session-secret-key - -# OAuth (development - can use test apps) -GOOGLE_CLIENT_ID=dev-google-client-id -GOOGLE_CLIENT_SECRET=dev-google-client-secret -``` - -### Staging Configuration - -```env -# .env.staging -NODE_ENV=staging -PORT=4000 -LOG_LEVEL=info - -# Database (staging) -DATABASE_URL=postgresql://user:pass@staging-db.host:5432/auth_service_staging - -# JWT (staging secrets) -ACCESS_TOKEN_SECRET=staging-access-token-secret-key-32-chars -REFRESH_TOKEN_SECRET=staging-refresh-token-secret-key-32-chars - -# Email (staging) -RESEND_API_KEY=re_staging_api_key -RESEND_FROM_EMAIL=noreply@staging.yourdomain.com - -# CORS (staging domains) -ALLOWED_ORIGINS=https://staging.yourdomain.com,https://app-staging.yourdomain.com - -# Session -EXPRESS_SESSION_SECRET=staging-session-secret-key-32-chars - -# OAuth (staging) -GOOGLE_CLIENT_ID=staging-google-client-id -GOOGLE_CLIENT_SECRET=staging-google-client-secret -``` - -### Production Configuration - -```env -# .env.production -NODE_ENV=production -PORT=4000 -LOG_LEVEL=warn - -# Database (production with connection pooling) -DATABASE_URL=postgresql://user:pass@prod-db.host:5432/auth_service_prod?connection_limit=20&pool_timeout=10 - -# JWT (production secrets - use strong randomly generated keys) -ACCESS_TOKEN_SECRET=prod-super-strong-access-token-secret-64-chars-minimum -REFRESH_TOKEN_SECRET=prod-super-strong-refresh-token-secret-64-chars-minimum - -# Email (production) -RESEND_API_KEY=re_production_api_key -RESEND_FROM_EMAIL=noreply@yourdomain.com - -# CORS (production domains only) -ALLOWED_ORIGINS=https://yourdomain.com,https://app.yourdomain.com - -# Session -EXPRESS_SESSION_SECRET=prod-super-strong-session-secret-64-chars-minimum - -# OAuth (production) -GOOGLE_CLIENT_ID=prod-google-client-id -GOOGLE_CLIENT_SECRET=prod-google-client-secret - -# Optional: Monitoring -POSTHOG_API_KEY=prod-posthog-api-key -POSTHOG_HOST=https://api.posthog.com - -# Optional: Redis for caching -REDIS_URL=redis://user:pass@redis-host:6379 -``` - -## ๐Ÿงช Testing Configuration - -### Test Environment Variables - -```env -# .env.test -NODE_ENV=test -PORT=4001 -LOG_LEVEL=error - -# Database (test) -DATABASE_URL=postgresql://postgres:password@localhost:5432/auth_service_test - -# JWT (test secrets) -ACCESS_TOKEN_SECRET=test-access-token-secret-key -REFRESH_TOKEN_SECRET=test-refresh-token-secret-key - -# Email (test - mock or use test service) -RESEND_API_KEY=re_test_api_key -RESEND_FROM_EMAIL=test@localhost - -# CORS (test) -ALLOWED_ORIGINS=http://localhost:3000 - -# Session -EXPRESS_SESSION_SECRET=test-session-secret-key -``` - -### Jest Configuration - -```json -// jest.config.json -{ - "preset": "ts-jest", - "testEnvironment": "node", - "roots": ["/src", "/tests"], - "testMatch": ["**/__tests__/**/*.ts", "**/?(*.)+(spec|test).ts"], - "transform": { - "^.+\\.ts$": "ts-jest" - }, - "collectCoverageFrom": [ - "src/**/*.ts", - "!src/**/*.d.ts", - "!src/server.ts" - ], - "coverageDirectory": "coverage", - "coverageReporters": ["text", "lcov", "html"], - "setupFilesAfterEnv": ["/tests/setup.ts"] -} -``` - -## ๐Ÿ”ง Configuration Validation - -### Environment Variable Validation - -```typescript -// src/config/env.ts -import { z } from 'zod'; -import 'dotenv/config'; - -const envSchema = z.object({ - // Application - NODE_ENV: z.enum(['development', 'production', 'test']).default('development'), - PORT: z.coerce.number().default(4000), - ALLOWED_ORIGINS: z.string().optional(), - - // Database - DATABASE_URL: z.string().min(1, "DATABASE_URL is required"), - - // JWT - ACCESS_TOKEN_SECRET: z.string().min(32, "ACCESS_TOKEN_SECRET must be at least 32 characters"), - REFRESH_TOKEN_SECRET: z.string().min(32, "REFRESH_TOKEN_SECRET must be at least 32 characters"), - - // Email - RESEND_API_KEY: z.string().min(1, "RESEND_API_KEY is required"), - RESEND_FROM_EMAIL: z.string().email("RESEND_FROM_EMAIL must be a valid email"), - - // Session - EXPRESS_SESSION_SECRET: z.string().min(32, "EXPRESS_SESSION_SECRET must be at least 32 characters"), - - // OAuth (optional) - GOOGLE_CLIENT_ID: z.string().optional(), - GOOGLE_CLIENT_SECRET: z.string().optional(), - GITHUB_CLIENT_ID: z.string().optional(), - GITHUB_CLIENT_SECRET: z.string().optional(), - - // Redirect URLs - CLIENT_SSO_REDIRECT_URL: z.string().url().optional(), - FORGOT_PASSWORD_REDIRECT_URL: z.string().url().optional() -}); - -// Validate environment variables -export const env = envSchema.parse(process.env); - -// Export validated config -export default env; -``` - -### Configuration Health Check - -```typescript -// src/utils/config-health.ts -export const checkConfiguration = () => { - const issues: string[] = []; - - // Check required variables - const requiredVars = [ - 'DATABASE_URL', - 'ACCESS_TOKEN_SECRET', - 'REFRESH_TOKEN_SECRET', - 'RESEND_API_KEY', - 'RESEND_FROM_EMAIL', - 'EXPRESS_SESSION_SECRET' - ]; - - requiredVars.forEach(varName => { - if (!process.env[varName]) { - issues.push(`Missing required environment variable: ${varName}`); - } - }); - - // Check secret lengths - const secretVars = ['ACCESS_TOKEN_SECRET', 'REFRESH_TOKEN_SECRET', 'EXPRESS_SESSION_SECRET']; - secretVars.forEach(varName => { - const secret = process.env[varName]; - if (secret && secret.length < 32) { - issues.push(`${varName} must be at least 32 characters long`); - } - }); - - // Check email format - const email = process.env.RESEND_FROM_EMAIL; - if (email && !email.includes('@')) { - issues.push('RESEND_FROM_EMAIL must be a valid email address'); - } - - return { - healthy: issues.length === 0, - issues - }; -}; -``` - ---- - -**๐ŸŽฏ Your Auth Service is now properly configured!** \ No newline at end of file diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md deleted file mode 100644 index 73eab38..0000000 --- a/DEPLOYMENT.md +++ /dev/null @@ -1,759 +0,0 @@ -# Deployment Guide - -Complete guide for deploying the Auth Service to production environments. - -## ๐Ÿš€ Production Deployment Options - -### 1. Docker Deployment (Recommended) - -#### Dockerfile -```dockerfile -# Multi-stage build for optimization -FROM node:18-alpine AS builder - -WORKDIR /app - -# Install dependencies -COPY package*.json ./ -COPY pnpm-lock.yaml ./ -RUN npm install -g pnpm -RUN pnpm install --frozen-lockfile - -# Copy source code -COPY . . - -# Build application -RUN pnpm build - -# Production stage -FROM node:18-alpine AS production - -WORKDIR /app - -# Install only production dependencies -COPY package*.json ./ -COPY pnpm-lock.yaml ./ -RUN npm install -g pnpm -RUN pnpm install --prod --frozen-lockfile - -# Copy built application -COPY --from=builder /app/dist ./dist -COPY --from=builder /app/drizzle ./drizzle - -# Create non-root user -RUN addgroup -g 1001 -S nodejs -RUN adduser -S nodejs -u 1001 - -# Change ownership -RUN chown -R nodejs:nodejs /app -USER nodejs - -# Expose port -EXPOSE 4000 - -# Health check -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD curl -f http://localhost:4000/api/v1/healthcheck/simple || exit 1 - -# Start application -CMD ["node", "dist/server.js"] -``` - -#### Docker Compose -```yaml -version: '3.8' - -services: - auth-service: - build: . - ports: - - "4000:4000" - environment: - - NODE_ENV=production - - DATABASE_URL=${DATABASE_URL} - - ACCESS_TOKEN_SECRET=${ACCESS_TOKEN_SECRET} - - REFRESH_TOKEN_SECRET=${REFRESH_TOKEN_SECRET} - - RESEND_API_KEY=${RESEND_API_KEY} - - RESEND_FROM_EMAIL=${RESEND_FROM_EMAIL} - - EXPRESS_SESSION_SECRET=${EXPRESS_SESSION_SECRET} - restart: unless-stopped - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:4000/api/v1/healthcheck/simple"] - interval: 30s - timeout: 10s - retries: 3 - start_period: 40s - - # Optional: PostgreSQL for local development - postgres: - image: postgres:15-alpine - environment: - - POSTGRES_DB=auth_service - - POSTGRES_USER=auth_user - - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - ports: - - "5432:5432" - volumes: - - postgres_data:/var/lib/postgresql/data - restart: unless-stopped - -volumes: - postgres_data: -``` - -#### Deployment Commands -```bash -# Build and run with Docker Compose -docker-compose up -d - -# View logs -docker-compose logs -f auth-service - -# Scale the service -docker-compose up -d --scale auth-service=3 -``` - -### 2. Cloud Platform Deployment - -#### Heroku -```bash -# Install Heroku CLI -# Login to Heroku -heroku login - -# Create app -heroku create your-auth-service - -# Set environment variables -heroku config:set NODE_ENV=production -heroku config:set DATABASE_URL=your_database_url -heroku config:set ACCESS_TOKEN_SECRET=your_access_token_secret -heroku config:set REFRESH_TOKEN_SECRET=your_refresh_token_secret -heroku config:set RESEND_API_KEY=your_resend_api_key -heroku config:set RESEND_FROM_EMAIL=noreply@yourdomain.com -heroku config:set EXPRESS_SESSION_SECRET=your_session_secret - -# Deploy -git push heroku main - -# Open app -heroku open -``` - -#### Vercel -```json -// vercel.json -{ - "version": 2, - "builds": [ - { - "src": "dist/server.js", - "use": "@vercel/node" - } - ], - "routes": [ - { - "src": "/(.*)", - "dest": "dist/server.js" - } - ], - "env": { - "NODE_ENV": "production" - } -} -``` - -#### AWS ECS -```json -// task-definition.json -{ - "family": "auth-service", - "networkMode": "awsvpc", - "requiresCompatibilities": ["FARGATE"], - "cpu": "256", - "memory": "512", - "executionRoleArn": "arn:aws:iam::account:role/ecsTaskExecutionRole", - "containerDefinitions": [ - { - "name": "auth-service", - "image": "your-account.dkr.ecr.region.amazonaws.com/auth-service:latest", - "portMappings": [ - { - "containerPort": 4000, - "protocol": "tcp" - } - ], - "environment": [ - { - "name": "NODE_ENV", - "value": "production" - } - ], - "secrets": [ - { - "name": "DATABASE_URL", - "valueFrom": "arn:aws:secretsmanager:region:account:secret:auth-service/db-url" - } - ], - "logConfiguration": { - "logDriver": "awslogs", - "options": { - "awslogs-group": "/ecs/auth-service", - "awslogs-region": "us-east-1", - "awslogs-stream-prefix": "ecs" - } - }, - "healthCheck": { - "command": ["CMD-SHELL", "curl -f http://localhost:4000/api/v1/healthcheck/simple || exit 1"], - "interval": 30, - "timeout": 5, - "retries": 3, - "startPeriod": 60 - } - } - ] -} -``` - -### 3. Traditional Server Deployment - -#### System Requirements -- **OS**: Ubuntu 20.04+ / CentOS 8+ / Amazon Linux 2 -- **CPU**: 1+ cores -- **Memory**: 2GB+ RAM -- **Storage**: 20GB+ SSD -- **Node.js**: 18.x LTS - -#### Deployment Script -```bash -#!/bin/bash -# deploy.sh - -set -e - -echo "๐Ÿš€ Starting Auth Service Deployment..." - -# Update system -sudo apt update && sudo apt upgrade -y - -# Install Node.js -curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - -sudo apt-get install -y nodejs - -# Install pnpm -npm install -g pnpm - -# Create application user -sudo useradd -m -s /bin/bash authservice -sudo usermod -aG sudo authservice - -# Create application directory -sudo mkdir -p /opt/auth-service -sudo chown authservice:authservice /opt/auth-service - -# Switch to application user -sudo -u authservice bash << 'EOF' - -# Navigate to app directory -cd /opt/auth-service - -# Clone repository (or copy files) -git clone . - -# Install dependencies -pnpm install --prod - -# Build application -pnpm build - -# Run database migrations -pnpm db:migrate - -# Create systemd service -sudo tee /etc/systemd/system/auth-service.service > /dev/null << EOL -[Unit] -Description=Auth Service -After=network.target - -[Service] -Type=simple -User=authservice -WorkingDirectory=/opt/auth-service -Environment=NODE_ENV=production -EnvironmentFile=/opt/auth-service/.env -ExecStart=/usr/bin/node dist/server.js -Restart=always -RestartSec=10 - -[Install] -WantedBy=multi-user.target -EOL - -# Enable and start service -sudo systemctl daemon-reload -sudo systemctl enable auth-service -sudo systemctl start auth-service - -echo "โœ… Auth Service deployed successfully!" -echo "๐ŸŒ Service is running at: http://localhost:4000" -echo "๐Ÿ“Š Health check: http://localhost:4000/api/v1/healthcheck" - -EOF -``` - -## ๐Ÿ”ง Production Configuration - -### Environment Variables -```env -# Production Environment -NODE_ENV=production -PORT=4000 - -# Database (Use connection pooling) -DATABASE_URL=postgresql://user:pass@host:5432/db?connection_limit=20&pool_timeout=10 - -# JWT Secrets (Use strong, randomly generated secrets) -ACCESS_TOKEN_SECRET=your-super-strong-access-token-secret-64-chars-minimum -REFRESH_TOKEN_SECRET=your-super-strong-refresh-token-secret-64-chars-minimum - -# Email Service -RESEND_API_KEY=re_production_api_key -RESEND_FROM_EMAIL=noreply@yourdomain.com - -# Session Security -EXPRESS_SESSION_SECRET=your-super-strong-session-secret-64-chars-minimum - -# CORS (Configure your frontend domains) -ALLOWED_ORIGINS=https://yourdomain.com,https://app.yourdomain.com - -# OAuth (if using) -GOOGLE_CLIENT_ID=your_google_client_id -GOOGLE_CLIENT_SECRET=your_google_client_secret -GITHUB_CLIENT_ID=your_github_client_id -GITHUB_CLIENT_SECRET=your_github_client_secret - -# Redirect URLs (HTTPS in production) -CLIENT_SSO_REDIRECT_URL=https://yourdomain.com/auth/callback -FORGOT_PASSWORD_REDIRECT_URL=https://yourdomain.com/reset-password - -# Optional: Monitoring -POSTHOG_API_KEY=your_posthog_api_key -POSTHOG_HOST=https://api.posthog.com - -# Optional: Redis for caching -REDIS_URL=redis://user:pass@host:6379 -``` - -### Nginx Configuration -```nginx -# /etc/nginx/sites-available/auth-service -server { - listen 80; - server_name yourdomain.com www.yourdomain.com; - - # Redirect to HTTPS - return 301 https://$server_name$request_uri; -} - -server { - listen 443 ssl http2; - server_name yourdomain.com www.yourdomain.com; - - # SSL Configuration - ssl_certificate /path/to/your/certificate.crt; - ssl_certificate_key /path/to/your/private.key; - ssl_protocols TLSv1.2 TLSv1.3; - ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384; - ssl_prefer_server_ciphers off; - - # Security Headers - add_header X-Frame-Options "SAMEORIGIN" always; - add_header X-XSS-Protection "1; mode=block" always; - add_header X-Content-Type-Options "nosniff" always; - add_header Referrer-Policy "no-referrer-when-downgrade" always; - add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always; - add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; - - # Rate Limiting - limit_req_zone $binary_remote_addr zone=auth:10m rate=5r/m; - - location / { - proxy_pass http://localhost:4000; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection 'upgrade'; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache_bypass $http_upgrade; - - # Apply rate limiting to auth endpoints - location /api/v1/users/ { - limit_req zone=auth burst=10 nodelay; - } - } - - # Health check endpoint (no rate limiting) - location /api/v1/healthcheck { - proxy_pass http://localhost:4000; - access_log off; - } -} -``` - -## ๐Ÿ“Š Monitoring & Logging - -### Application Monitoring -```typescript -// src/monitoring/metrics.ts -import { createPrometheusMetrics } from 'prom-client'; - -const metrics = { - httpRequestsTotal: new createPrometheusMetrics.Counter({ - name: 'http_requests_total', - help: 'Total number of HTTP requests', - labelNames: ['method', 'route', 'status_code'] - }), - - httpRequestDuration: new createPrometheusMetrics.Histogram({ - name: 'http_request_duration_seconds', - help: 'Duration of HTTP requests in seconds', - labelNames: ['method', 'route'], - buckets: [0.1, 0.5, 1, 2, 5] - }), - - activeConnections: new createPrometheusMetrics.Gauge({ - name: 'active_connections', - help: 'Number of active database connections' - }), - - userRegistrations: new createPrometheusMetrics.Counter({ - name: 'user_registrations_total', - help: 'Total number of user registrations' - }) -}; - -export { metrics }; -``` - -### Health Check Enhancements -```typescript -// src/controllers/healthcheck.controller.ts -const detailedHealthCheck = asyncHandler(async (req: Request, res: Response) => { - const healthData = { - status: "OK", - timestamp: new Date().toISOString(), - uptime: process.uptime(), - server: "running", - database: "connected", - environment: process.env.NODE_ENV, - version: process.env.npm_package_version, - memory: { - used: Math.round(process.memoryUsage().heapUsed / 1024 / 1024), - total: Math.round(process.memoryUsage().heapTotal / 1024 / 1024) - }, - connections: { - active: pool.totalCount - pool.idleCount, - idle: pool.idleCount, - total: pool.totalCount - } - }; - - // Add metrics endpoint - if (req.query.metrics === 'true') { - healthData.metrics = await getMetrics(); - } - - return res.status(200).json(new ApiResponse(200, healthData, "Health Check Passed")); -}); -``` - -### Log Management -```typescript -// src/logger/production.logger.ts -import winston from 'winston'; -import 'winston-daily-rotate-file'; - -const logger = winston.createLogger({ - level: 'info', - format: winston.format.combine( - winston.format.timestamp(), - winston.format.errors({ stack: true }), - winston.format.json() - ), - defaultMeta: { service: 'auth-service' }, - transports: [ - // Error logs - new winston.transports.DailyRotateFile({ - filename: 'logs/error-%DATE%.log', - datePattern: 'YYYY-MM-DD', - level: 'error', - maxSize: '20m', - maxFiles: '14d' - }), - - // Combined logs - new winston.transports.DailyRotateFile({ - filename: 'logs/combined-%DATE%.log', - datePattern: 'YYYY-MM-DD', - maxSize: '20m', - maxFiles: '14d' - }), - - // Console logging for container environments - new winston.transports.Console({ - format: winston.format.simple() - }) - ] -}); - -export default logger; -``` - -## ๐Ÿ”’ Security Hardening - -### SSL/TLS Configuration -```bash -# Generate SSL certificate with Let's Encrypt -sudo apt install certbot python3-certbot-nginx -sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com - -# Auto-renewal -sudo crontab -e -# Add: 0 12 * * * /usr/bin/certbot renew --quiet -``` - -### Firewall Configuration -```bash -# Configure UFW firewall -sudo ufw default deny incoming -sudo ufw default allow outgoing -sudo ufw allow ssh -sudo ufw allow 'Nginx Full' -sudo ufw enable -``` - -### Security Headers -```typescript -// Enhanced Helmet configuration -app.use(helmet({ - contentSecurityPolicy: { - directives: { - defaultSrc: ["'self'"], - styleSrc: ["'self'", "'unsafe-inline'"], - scriptSrc: ["'self'"], - imgSrc: ["'self'", "data:", "https:"], - connectSrc: ["'self'"], - fontSrc: ["'self'"], - objectSrc: ["'none'"], - mediaSrc: ["'self'"], - frameSrc: ["'none'"], - }, - }, - hsts: { - maxAge: 31536000, - includeSubDomains: true, - preload: true - } -})); -``` - -## ๐Ÿ”„ CI/CD Pipeline - -### GitHub Actions -```yaml -# .github/workflows/deploy.yml -name: Deploy Auth Service - -on: - push: - branches: [main] - pull_request: - branches: [main] - -jobs: - test: - runs-on: ubuntu-latest - - services: - postgres: - image: postgres:15 - env: - POSTGRES_PASSWORD: postgres - POSTGRES_DB: test_db - options: >- - --health-cmd pg_isready - --health-interval 10s - --health-timeout 5s - --health-retries 5 - ports: - - 5432:5432 - - steps: - - uses: actions/checkout@v3 - - - name: Setup Node.js - uses: actions/setup-node@v3 - with: - node-version: '18' - cache: 'npm' - - - name: Install pnpm - run: npm install -g pnpm - - - name: Install dependencies - run: pnpm install --frozen-lockfile - - - name: Run tests - run: pnpm test - env: - DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test_db - - - name: Run linting - run: pnpm lint - - - name: Type check - run: pnpm typecheck - - build-and-deploy: - needs: test - runs-on: ubuntu-latest - if: github.ref == 'refs/heads/main' - - steps: - - uses: actions/checkout@v3 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Login to Container Registry - uses: docker/login-action@v2 - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Build and push Docker image - uses: docker/build-push-action@v4 - with: - context: . - push: true - tags: | - ghcr.io/${{ github.repository }}:latest - ghcr.io/${{ github.repository }}:${{ github.sha }} - - - name: Deploy to production - run: | - # Your deployment commands here - echo "Deploying to production..." -``` - -## ๐Ÿ“ˆ Performance Optimization - -### Database Optimization -```sql --- Create indexes for performance -CREATE INDEX CONCURRENTLY idx_users_email ON users(email); -CREATE INDEX CONCURRENTLY idx_users_username ON users(username); -CREATE INDEX CONCURRENTLY idx_users_is_active ON users(is_active) WHERE is_active = true; - --- Analyze table statistics -ANALYZE users; -``` - -### Caching Strategy -```typescript -// Redis caching implementation -import Redis from 'ioredis'; - -const redis = new Redis({ - host: process.env.REDIS_HOST, - port: parseInt(process.env.REDIS_PORT || '6379'), - retryDelayOnFailover: 100, - maxRetriesPerRequest: 3 -}); - -// Cache user data -export const cacheUser = async (userId: string, userData: any, ttl = 3600) => { - await redis.setex(`user:${userId}`, ttl, JSON.stringify(userData)); -}; - -// Get cached user -export const getCachedUser = async (userId: string) => { - const cached = await redis.get(`user:${userId}`); - return cached ? JSON.parse(cached) : null; -}; -``` - -### Load Balancing -```nginx -# Upstream configuration for multiple instances -upstream auth_service { - least_conn; - server 127.0.0.1:4000 max_fails=3 fail_timeout=30s; - server 127.0.0.1:4001 max_fails=3 fail_timeout=30s; - server 127.0.0.1:4002 max_fails=3 fail_timeout=30s; -} - -server { - listen 443 ssl http2; - server_name yourdomain.com; - - location / { - proxy_pass http://auth_service; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - } -} -``` - -## ๐Ÿšจ Troubleshooting - -### Common Issues - -1. **Database Connection Timeout** -```bash -# Check database connectivity -psql $DATABASE_URL -c "SELECT 1;" - -# Increase connection timeout -export PGCONNECT_TIMEOUT=10 -``` - -2. **Memory Issues** -```bash -# Monitor memory usage -free -h -top -p $(pgrep -f "node.*server.js") - -# Increase Node.js memory limit -node --max-old-space-size=2048 dist/server.js -``` - -3. **Port Already in Use** -```bash -# Find process using port 4000 -sudo lsof -i :4000 - -# Kill process -sudo kill -9 -``` - -### Health Check Failures -```bash -# Check service status -sudo systemctl status auth-service - -# View logs -sudo journalctl -u auth-service -f - -# Test health endpoint -curl -f http://localhost:4000/api/v1/healthcheck/simple -``` - ---- - -**๐ŸŽ‰ Your Auth Service is now production-ready!** \ No newline at end of file diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md deleted file mode 100644 index 24e458c..0000000 --- a/DEVELOPMENT.md +++ /dev/null @@ -1,509 +0,0 @@ -# Development Guide - -Complete guide for developing and contributing to the Auth Service. - -## ๐Ÿ›  Development Setup - -### Prerequisites -- Node.js 18+ -- PostgreSQL database -- pnpm package manager -- Git - -### Local Development - -1. **Clone Repository** -```bash -git clone -cd auth-service -``` - -2. **Install Dependencies** -```bash -pnpm install -``` - -3. **Environment Configuration** -```bash -cp .env.example .env -# Edit .env with your development configuration -``` - -4. **Database Setup** -```bash -# Create development database -createdb auth_service_dev - -# Run migrations -pnpm db:migrate - -# (Optional) Seed with test data -pnpm db:seed -``` - -5. **Start Development Server** -```bash -pnpm dev -``` - -The server will start at `http://localhost:4000` with hot reload enabled. - -## ๐Ÿ“ Project Structure - -``` -auth-service/ -โ”œโ”€โ”€ src/ -โ”‚ โ”œโ”€โ”€ config/ # Configuration files -โ”‚ โ”‚ โ”œโ”€โ”€ db.ts # Database configuration -โ”‚ โ”‚ โ””โ”€โ”€ env.ts # Environment validation -โ”‚ โ”œโ”€โ”€ controllers/ # Route controllers -โ”‚ โ”‚ โ””โ”€โ”€ auth/ -โ”‚ โ”‚ โ””โ”€โ”€ user.controller.ts -โ”‚ โ”œโ”€โ”€ db/ # Database schema -โ”‚ โ”‚ โ”œโ”€โ”€ schema/ -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ index.ts -โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ user.ts -โ”‚ โ”‚ โ””โ”€โ”€ migrations/ # Database migrations -โ”‚ โ”œโ”€โ”€ lib/ # External libraries -โ”‚ โ”‚ โ””โ”€โ”€ posthog.ts -โ”‚ โ”œโ”€โ”€ logger/ # Logging configuration -โ”‚ โ”‚ โ”œโ”€โ”€ morgan.logger.ts -โ”‚ โ”‚ โ””โ”€โ”€ winston.logger.ts -โ”‚ โ”œโ”€โ”€ middlewares/ # Express middlewares -โ”‚ โ”‚ โ”œโ”€โ”€ auth.middleware.ts -โ”‚ โ”‚ โ”œโ”€โ”€ error.middleware.ts -โ”‚ โ”‚ โ””โ”€โ”€ validate.middleware.ts -โ”‚ โ”œโ”€โ”€ passport/ # OAuth strategies -โ”‚ โ”‚ โ””โ”€โ”€ index.ts -โ”‚ โ”œโ”€โ”€ routes/ # API routes -โ”‚ โ”‚ โ”œโ”€โ”€ auth/ -โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ user.routes.ts -โ”‚ โ”‚ โ””โ”€โ”€ healthcheck.routes.ts -โ”‚ โ”œโ”€โ”€ types/ # TypeScript types -โ”‚ โ”‚ โ””โ”€โ”€ express.d.ts -โ”‚ โ”œโ”€โ”€ utils/ # Utility functions -โ”‚ โ”‚ โ”œโ”€โ”€ ApiError.ts -โ”‚ โ”‚ โ”œโ”€โ”€ ApiResponse.ts -โ”‚ โ”‚ โ”œโ”€โ”€ asyncHandler.ts -โ”‚ โ”‚ โ”œโ”€โ”€ mail.ts -โ”‚ โ”‚ โ””โ”€โ”€ token.ts -โ”‚ โ”œโ”€โ”€ validators/ # Input validation schemas -โ”‚ โ”‚ โ””โ”€โ”€ auth.validator.ts -โ”‚ โ”œโ”€โ”€ app.ts # Express app configuration -โ”‚ โ””โ”€โ”€ server.ts # Server entry point -โ”œโ”€โ”€ drizzle/ # Drizzle ORM files -โ”œโ”€โ”€ docs/ # Documentation -โ”œโ”€โ”€ tests/ # Test files -โ”œโ”€โ”€ .env.example # Environment template -โ”œโ”€โ”€ package.json # Dependencies and scripts -โ”œโ”€โ”€ tsconfig.json # TypeScript configuration -โ”œโ”€โ”€ drizzle.config.ts # Drizzle configuration -โ””โ”€โ”€ README.md # Main documentation -``` - -## ๐Ÿงช Testing - -### Running Tests -```bash -# Run all tests -pnpm test - -# Run tests with coverage -pnpm test:coverage - -# Run tests in watch mode -pnpm test:watch - -# Run specific test file -pnpm test auth.test.ts -``` - -### Test Structure -``` -tests/ -โ”œโ”€โ”€ unit/ # Unit tests -โ”‚ โ”œโ”€โ”€ controllers/ -โ”‚ โ”œโ”€โ”€ utils/ -โ”‚ โ””โ”€โ”€ validators/ -โ”œโ”€โ”€ integration/ # Integration tests -โ”‚ โ”œโ”€โ”€ auth/ -โ”‚ โ””โ”€โ”€ database/ -โ””โ”€โ”€ e2e/ # End-to-end tests - โ””โ”€โ”€ api/ -``` - -### Writing Tests - -#### Unit Test Example -```typescript -// tests/unit/utils/token.test.ts -import { generateTokens } from '../../../src/utils/token'; - -describe('Token Utils', () => { - it('should generate access and refresh tokens', () => { - const userId = 'test-user-id'; - const tokens = generateTokens(userId); - - expect(tokens).toHaveProperty('accessToken'); - expect(tokens).toHaveProperty('refreshToken'); - expect(typeof tokens.accessToken).toBe('string'); - expect(typeof tokens.refreshToken).toBe('string'); - }); -}); -``` - -#### Integration Test Example -```typescript -// tests/integration/auth/register.test.ts -import request from 'supertest'; -import { app } from '../../../src/app'; - -describe('User Registration', () => { - it('should register a new user', async () => { - const userData = { - username: 'testuser', - email: 'test@example.com', - password: 'TestPass123!', - fullName: 'Test User' - }; - - const response = await request(app) - .post('/api/v1/users/register') - .send(userData) - .expect(201); - - expect(response.body.success).toBe(true); - expect(response.body.data.user.email).toBe(userData.email); - }); -}); -``` - -## ๐Ÿ”ง Available Scripts - -### Development Scripts -```bash -pnpm dev # Start development server with hot reload -pnpm build # Build for production -pnpm start # Start production server -pnpm lint # Run ESLint -pnpm lint:fix # Fix ESLint issues automatically -pnpm typecheck # Run TypeScript type checking -pnpm format # Format code with Prettier -``` - -### Database Scripts -```bash -pnpm db:migrate # Run database migrations -pnpm db:generate # Generate new migration -pnpm db:push # Push schema changes to database -pnpm db:drop # Drop database -pnpm db:studio # Open Drizzle Studio -pnpm db:seed # Seed database with test data -``` - -### Testing Scripts -```bash -pnpm test # Run all tests -pnpm test:unit # Run unit tests only -pnpm test:integration # Run integration tests only -pnpm test:e2e # Run end-to-end tests -pnpm test:coverage # Run tests with coverage report -pnpm test:watch # Run tests in watch mode -``` - -## ๐Ÿ—„ Database Development - -### Schema Changes - -1. **Modify Schema Files** -```typescript -// src/db/schema/user.ts -export const User = pgTable("users", { - // Add new fields here - newField: text("new_field").notNull().default("default_value"), -}); -``` - -2. **Generate Migration** -```bash -pnpm db:generate -``` - -3. **Apply Migration** -```bash -pnpm db:migrate -``` - -### Database Studio -```bash -pnpm db:studio -``` -Opens Drizzle Studio at `http://localhost:3000` for database management. - -### Seeding Data -```typescript -// scripts/seed.ts -import { db } from '../src/config/db'; -import { User } from '../src/db/schema'; - -async function seed() { - await db.insert(User).values([ - { - username: 'admin', - email: 'admin@example.com', - password: hashedPassword, - fullName: 'Admin User', - role: 'admin' - } - ]); -} - -seed().catch(console.error); -``` - -## ๐Ÿ” Debugging - -### VS Code Configuration - -Create `.vscode/launch.json`: -```json -{ - "version": "0.2.0", - "configurations": [ - { - "name": "Debug Auth Service", - "type": "node", - "request": "launch", - "program": "${workspaceFolder}/src/server.ts", - "outFiles": ["${workspaceFolder}/dist/**/*.js"], - "runtimeArgs": ["-r", "tsx/cjs"], - "env": { - "NODE_ENV": "development" - }, - "console": "integratedTerminal", - "internalConsoleOptions": "neverOpen" - } - ] -} -``` - -### Debugging Tips - -1. **Use Winston Logger** -```typescript -import logger from '../src/logger/winston.logger'; - -logger.info('User registered successfully', { userId }); -logger.error('Database connection failed', { error }); -``` - -2. **Database Query Debugging** -```typescript -// Enable query logging in development -const db = drizzle(pool, { - schema: Schema, - logger: true -}); -``` - -3. **Request Debugging** -```typescript -// Add request logging middleware -app.use((req, res, next) => { - console.log(`${req.method} ${req.path}`, req.body); - next(); -}); -``` - -## ๐Ÿ“ Code Style - -### ESLint Configuration -```json -{ - "extends": [ - "@typescript-eslint/recommended", - "prettier" - ], - "rules": { - "no-console": "warn", - "@typescript-eslint/no-unused-vars": "error" - } -} -``` - -### Prettier Configuration -```json -{ - "semi": true, - "trailingComma": "es5", - "singleQuote": true, - "printWidth": 80, - "tabWidth": 2 -} -``` - -### TypeScript Best Practices - -1. **Use Strict Types** -```typescript -// Good -interface User { - id: string; - email: string; - username: string; -} - -// Bad -interface User { - id: any; - email: any; - username: any; -} -``` - -2. **Error Handling** -```typescript -// Use asyncHandler for route handlers -const createUser = asyncHandler(async (req: Request, res: Response) => { - try { - const user = await userService.create(req.body); - res.status(201).json(new ApiResponse(201, user)); - } catch (error) { - throw new ApiError(400, "Failed to create user"); - } -}); -``` - -3. **Validation** -```typescript -// Use Zod for runtime validation -const userSchema = z.object({ - email: z.string().email(), - password: z.string().min(8), - username: z.string().min(3) -}); -``` - -## ๐Ÿ”„ Git Workflow - -### Branch Naming -- `feature/feature-name` - New features -- `bugfix/bug-description` - Bug fixes -- `hotfix/urgent-fix` - Critical fixes -- `docs/documentation-update` - Documentation updates - -### Commit Messages -``` -feat: add user registration endpoint -fix: resolve database connection timeout -docs: update API documentation -refactor: improve error handling -test: add unit tests for token utils -``` - -### Pull Request Template -```markdown -## Description -Brief description of changes - -## Type of Change -- [ ] Bug fix -- [ ] New feature -- [ ] Breaking change -- [ ] Documentation update - -## Testing -- [ ] Unit tests pass -- [ ] Integration tests pass -- [ ] Manual testing completed - -## Checklist -- [ ] Code follows style guidelines -- [ ] Self-review completed -- [ ] Documentation updated -``` - -## ๐Ÿš€ Performance Optimization - -### Database Optimization -```typescript -// Use indexes for frequently queried fields -export const User = pgTable("users", { - email: text("email").notNull().unique(), - username: text("username").notNull().unique(), - // Add indexes -}, (table) => ({ - emailIdx: index("email_idx").on(table.email), - usernameIdx: index("username_idx").on(table.username) -})); -``` - -### Caching Strategy -```typescript -// Implement Redis caching for frequently accessed data -import Redis from 'ioredis'; - -const redis = new Redis(process.env.REDIS_URL); - -// Cache user data -const cacheUser = async (userId: string, userData: any) => { - await redis.setex(`user:${userId}`, 3600, JSON.stringify(userData)); -}; -``` - -### Request Optimization -```typescript -// Use connection pooling -const pool = new Pool({ - max: 20, - idleTimeoutMillis: 30000, - connectionTimeoutMillis: 2000, -}); - -// Implement request batching -const batchUsers = async (userIds: string[]) => { - return await db.select().from(User).where(inArray(User.id, userIds)); -}; -``` - -## ๐Ÿ” Security Best Practices - -### Input Validation -```typescript -// Always validate user input -const validatedData = userSchema.parse(req.body); -``` - -### Error Handling -```typescript -// Don't expose sensitive information in errors -const handleError = (error: Error) => { - if (process.env.NODE_ENV === 'production') { - return new ApiError(500, "Internal server error"); - } - return new ApiError(500, error.message); -}; -``` - -### Authentication -```typescript -// Use secure cookie settings -app.use(cookieParser({ - httpOnly: true, - secure: process.env.NODE_ENV === 'production', - sameSite: 'strict' -})); -``` - -## ๐Ÿ“š Learning Resources - -- **Express.js**: https://expressjs.com/ -- **TypeScript**: https://www.typescriptlang.org/ -- **Drizzle ORM**: https://orm.drizzle.team/ -- **PostgreSQL**: https://www.postgresql.org/docs/ -- **JWT**: https://jwt.io/ -- **Zod**: https://zod.dev/ - ---- - -**Happy Coding! ๐ŸŽ‰** \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index f734b5d..07c5556 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,49 +1,49 @@ -# Multi-stage build for optimization -FROM node:18-alpine AS builder +# Stage 1: Dependencies + +FROM node:22-alpine AS deps WORKDIR /app -# Install dependencies -COPY package*.json ./ -COPY pnpm-lock.yaml ./ -RUN npm install -g pnpm -RUN pnpm install --frozen-lockfile +COPY package.json pnpm-lock.yaml ./ + +RUN corepack enable \ + && pnpm install --frozen-lockfile -# Copy source code -COPY . . -# Build application -RUN pnpm build -# Production stage -FROM node:18-alpine AS production +# Stage 2: Builder + +FROM node:22-alpine AS builder WORKDIR /app -# Install only production dependencies -COPY package*.json ./ -COPY pnpm-lock.yaml ./ -RUN npm install -g pnpm -RUN pnpm install --prod --frozen-lockfile +COPY --from=deps /app/node_modules ./node_modules +COPY package.json pnpm-lock.yaml ./ +COPY tsconfig*.json ./ +COPY src ./src -# Copy built application -COPY --from=builder /app/dist ./dist -COPY --from=builder /app/drizzle ./drizzle +RUN corepack enable \ + && pnpm build + + +# Stage 3: Production -# Create non-root user -RUN addgroup -g 1001 -S nodejs -RUN adduser -S nodejs -u 1001 +FROM node:22-alpine AS production -# Change ownership -RUN chown -R nodejs:nodejs /app -USER nodejs +WORKDIR /app + +ENV NODE_ENV=production + +COPY package.json pnpm-lock.yaml ./ + +# Install only production dependencies +RUN corepack enable \ + && pnpm install --prod --frozen-lockfile + +COPY --from=builder /app/dist ./dist -# Expose port -EXPOSE 4000 +USER node -# Health check -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD curl -f http://localhost:4000/api/v1/healthcheck/simple || exit 1 +EXPOSE 3000 -# Start application -CMD ["node", "dist/server.js"] \ No newline at end of file +CMD ["pnpm", "start"] \ No newline at end of file diff --git a/QUICK_START.md b/QUICK_START.md deleted file mode 100644 index 4efb782..0000000 --- a/QUICK_START.md +++ /dev/null @@ -1,86 +0,0 @@ -# Auth Service - Quick Start Guide - -Get your authentication service running in minutes with this quick start guide. - -## ๐Ÿš€ Prerequisites - -- Node.js 18+ -- PostgreSQL database (Neon recommended) -- pnpm package manager - -## โšก 5-Minute Setup - -### 1. Clone & Install -```bash -git clone -cd auth-service -pnpm install -``` - -### 2. Environment Setup -```bash -cp .env.example .env -``` - -Edit `.env` with minimum required variables: -```env -# Database (get from Neon or local PostgreSQL) -DATABASE_URL=postgresql://user:pass@host:5432/db - -# JWT Secrets (generate random 32+ character strings) -ACCESS_TOKEN_SECRET=your-super-secret-access-token-32-chars -REFRESH_TOKEN_SECRET=your-super-secret-refresh-token-32-chars - -# Email (get from Resend.com) -RESEND_API_KEY=re_your_api_key -RESEND_FROM_EMAIL=noreply@yourdomain.com - -# Session -EXPRESS_SESSION_SECRET=your-session-secret-32-chars -``` - -### 3. Database Setup -```bash -pnpm db:migrate -``` - -### 4. Start Service -```bash -pnpm dev -``` - -Service will be running at: `http://localhost:4000` - -## ๐Ÿงช Quick Test - -```bash -# Test health check -curl http://localhost:4000/api/v1/healthcheck - -# Test user registration -curl -X POST http://localhost:4000/api/v1/users/register \ - -H "Content-Type: application/json" \ - -d '{ - "username": "testuser", - "email": "test@example.com", - "password": "TestPass123!", - "fullName": "Test User" - }' -``` - -## ๐Ÿ“š Next Steps - -- **๐Ÿ“– Full Documentation**: [API_DOCUMENTATION.md](./API_DOCUMENTATION.md) -- **๐Ÿ›  Development Guide**: [DEVELOPMENT.md](./DEVELOPMENT.md) -- **๐Ÿš€ Deployment Guide**: [DEPLOYMENT.md](./DEPLOYMENT.md) -- **๐Ÿ”ง Configuration**: [CONFIGURATION.md](./CONFIGURATION.md) - -## ๐Ÿ†˜ Need Help? - -- Check the [troubleshooting section](./TROUBLESHOOTING.md) -- Review [common issues](./FAQ.md) -- Open an issue in the repository - ---- - -**Ready in 5 minutes! ๐ŸŽ‰** \ No newline at end of file diff --git a/issues/001-auth-domain-deepening.md b/issues/001-auth-domain-deepening.md new file mode 100644 index 0000000..c103ff9 --- /dev/null +++ b/issues/001-auth-domain-deepening.md @@ -0,0 +1,177 @@ +# RFC: Deepen Auth Domain โ€” Ergonomic Facade over Ports & Adapters + +## Problem + +**Shallow modules, tightly coupled, integration risk in the seams** โ€” `src/controllers/auth/auth.controller.ts:483` (7 handlers + `generateAccessAndRefreshToken:21` + `generateTemporaryToken:69`), `password.controller.ts:194` (3 handlers + duplicate `generateTemporaryToken:181`), `user.controller.ts:157` (3 handlers + phantom `utils/cache:11`), `admin.controller.ts:46`, plus `middlewares/auth.middleware.ts:10` (`verifyJWT`), `utils/token.ts:3` (`hashToken` unused), and `passport/index.ts:311` (Google/GitHub 85 LoC duplication, side-effect `import './passport/index'` in `app.ts:10`) are all shallow procedural handlers. Understanding one flow (`registerUser:88`) requires bouncing 6 files: `routes/auth/user.routes.ts:66` โ†’ `sanitize.middleware.ts:6` โ†’ `validators/auth.validator.ts:3` โ†’ `auth.controller.ts:88` โ†’ `utils/mail.ts:23` (`Resend`+`Mailgen`) โ†’ `lib/posthog.ts:3` plus `config/env.ts:52` vs 8 direct `process.env.*` bypasses (`mail.ts:5,15`, `posthog.ts:3` `!` assert, `app.ts:47`, `user.controller.ts:115`). + +Tightly-coupled seams where real bugs hide: +- `generateTemporaryToken` duplicated identically in `auth.controller.ts:69` and `password.controller.ts:181` (20m expiry hardcoded both); `hashToken` in `utils/token.ts:3` unused while `crypto.createHash('sha256')` is inlined 5ร— (`auth.controller.ts:72,271`, `password.controller.ts:84`). +- `refreshAccessToken:406` does `await db.update(User).set({refreshToken: newRefreshToken})` **without `.where()`** โ€” silently updates all rows; hidden between `auth.middleware.ts:21` JWT verify and controller. +- `user.controller.ts:23` `getCurrentUser` caches 1800s via `getCachedUser/cacheUser` but `updateUsername`/`uploadProfilePicture` never invalidate; phantom `src/utils/cache.ts` and `src/lib/redis.ts` missing from `src/` but alive in `dist/` (`dist/utils/cache.js:138`, `dist/lib/redis.js:58`), `server.ts:7` never calls `initRedis()`, `queues/queues.ts:3` `new Queue('emailQueue')` has no connection. +- 13 inline `posthog.capture` calls (`auth.controller.ts:133,199,248...`), `app.ts:47` CORS origin via `process.env.ALLOWED_ORIGINS`, `mail.ts:5` throws at import if `RESEND_API_KEY` missing โ€” all singletons constructed at module load, untestable without live PG+Redis+Resend+PostHog+S3. +- Routes god-file `routes/auth/user.routes.ts:136` multiplexes 4 controller modules, 5 sanitize chains, 7 Zod schemas, `verifyJWT`, `multer`, 2 `rateLimit` instances โ€” change any validator requires editing routes + controller + sanitize + validator. + +Result: **0 tests, no test infra** (`package.json` has no `test` script), every handler mixes `db.query` + `bcrypt` + `jwt` + `crypto` + `sendEmail` + `posthog` inline. Deep module needed to hide this complexity behind a small, testable boundary. + +## Proposed Interface + +**Hybrid A:** Public ergonomic facade (Agent 3) layered over ports & adapters internals (Agent 4). Hot path callers see trivial `register/login/authenticate/me + router`; internals use explicit ports + lifecycle. + +### Public surface โ€” `src/modules/auth/index.ts` + +```typescript +// Factory โ€” all options optional, defaults from env.ts single parse +export function createAuth(opts?: AuthOptions): Auth; + +export type AuthOptions = { + db?: DrizzleClient; // default: import {db} from '@/config/db' + cache?: CachePort; // default: IORedisCacheAdapter(env.REDIS_URL) fallback InMemory + mailer?: EmailPort; + analytics?: AnalyticsPort; + storage?: ObjectStoragePort; + config?: AuthConfig; // default: envSchema.parse(process.env) + jwt?: { accessSecret?: string; refreshSecret?: string; accessExpiry?: string; refreshExpiry?: string }; + baseUrl?: string; // for verification URLs, default req-derived or env.CLIENT_SSO_REDIRECT_URL +}; + +export interface Auth { + // 90% hot path โ€” 4 methods cover 70% usage + register(input: { email: string; username: string; password: string; origin?: string }): Promise<{ userId: string }>; + login(input: { email?: string; username?: string; password: string }): Promise<{ user: AuthenticatedUser; tokens: Tokens }>; + authenticate(token: string): Promise; + me(userId: string): Promise; // read-through cache 30m hidden + + readonly middleware: { authenticate: RequestHandler }; // drop-in for verifyJWT + readonly router: Router; // pre-wired: /register /login /refresh-token /verify-email/:token /logout /me + + // lifecycle โ€” fixes server.ts never calling initRedis / queue connection + init(): Promise; + close(): Promise; + + // rare flows โ€” explicit cost via extended, lazily loads S3/passport/multer + readonly extended: { + email: { verify(token: string): Promise<{ isEmailVerified: true }>; resend(userId: string, origin?: string): Promise }; + password: { forgot(email: string): Promise; reset(token: string, newPassword: string): Promise; change(userId: string, oldPassword: string, newPassword: string): Promise }; + profile: { updateUsername(userId: string, username: string): Promise<{ username: string }>; uploadAvatar(userId: string, file: { buffer: Buffer; mimetype: string; originalname: string }): Promise<{ profilePicture: string }> }; + tokens: { refresh(refreshToken: string): Promise }; + admin: { assignRole(actorId: string, targetUserId: string, role: 'admin'|'user'): Promise }; + oauth: { router: Router }; // /google, /github, callbacks โ€” hides passport + logout(userId: string): Promise; + }; +} + +// Example domain types +export type AuthenticatedUser = { id: string; email: string; username: string; role: 'admin'|'user'; profilePicture: string|null; isEmailVerified: boolean }; +export type Tokens = { accessToken: string; refreshToken: string }; +``` + +### Internal ports โ€” `src/modules/auth/ports.ts` (no concrete imports) + +```typescript +export interface UserRepository { findById(id:string):Promise; findByEmail(email:string):Promise; findUniqueByEmailOrUsername(email:string, username:string):Promise; findByVerificationToken(hashed:string):Promise; findByForgotToken(hashed:string):Promise; create(data:CreateUserInput):Promise; update(id:string,patch:Partial):Promise; } +export interface EmailPort { send(opts:{to:string;subject:string;html:string;text:string}):Promise<{id:string}>; } +export interface CachePort { get(k:string):Promise; setex(k:string,ttl:number,v:T):Promise; del(k:string):Promise; } +export interface ObjectStoragePort { upload(key:string,body:Buffer,ct:string):Promise<{url:string}>; delete(key:string):Promise; } +export interface AnalyticsPort { capture(e:{distinctId:string;event:string;properties?:object}):void; flush?():Promise; shutdown?():Promise; } +export interface TokenSigner { signAccessToken(p:JwtPayload):string; signRefreshToken(p:{userId:string}):string; verifyRefreshToken(t:string):{userId:string}; } +export interface Clock { now():Date; } +export interface PasswordHasher { hash(pw:string):Promise; compare(pw:string,hash:string):Promise; } +export type AuthConfig = { accessTokenSecret:string; refreshTokenSecret:string; accessTokenExpiry:string; refreshTokenExpiry:string; clientSsoRedirectUrl:string; forgotPasswordRedirectUrl:string; s3Bucket:string; s3Region:string; s3ProfilePicsPrefix:string }; +export type AuthPorts = { users:UserRepository; email:EmailPort; cache:CachePort; storage:ObjectStoragePort; analytics:AnalyticsPort; tokens:TokenSigner; hasher:PasswordHasher; clock:Clock }; +``` + +### Usage example โ€” before vs after + +**Before โ€” `routes/auth/user.routes.ts:66` today (8 imports, manual sanitize+validate+handler):** +```typescript +import { registerUser } from '../../controllers/auth/auth.controller'; +import { sanitizeRegistration } from '../../middlewares/sanitize.middleware'; +import { validate } from '../../middlewares/validate.middleware'; +import { registerSchema } from '../../validators/auth.validator'; +router.post('/register', sanitizeRegistration, validate(registerSchema), registerUser); +``` + +**After โ€” hot path trivial (no plumbing imports):** +```typescript +// src/app.ts / src/server.ts โ€” explicit bootstrap, single env parse +import { createAuth } from '@/modules/auth'; +import { env } from '@/config/env'; +export const auth = createAuth(); // or createAuth({ db, cache, mailer }) for tests +await auth.init(); +app.use('/api/v1/users', auth.router); // mounts register/login/verify-email/refresh/logout/me + middleware + +// Service-level (non-HTTP) โ€” e.g., queue job, script +await auth.register({ email:'a@b.com', username:'alice', password:'Str0ng!Pass1@' }); +const { user, tokens } = await auth.login({ email:'a@b.com', password:'Str0ng!Pass1@' }); +await auth.me(user.id); + +// Rare โ€” explicit via extended +await auth.extended.password.forgot('a@b.com'); +await auth.extended.profile.uploadAvatar(user.id, { buffer, mimetype:'image/png', originalname:'pic.png' }); +app.use('/api/v1/users', auth.extended.oauth.router); +``` + +### What complexity it hides internally +- **Token lifecycle:** Single canonical `hashToken` (`utils/token.ts:3`), `generateTemporaryToken` (randomBytes 32 โ†’ sha256 + 20m expiry) unified, fixes `refreshAccessToken:406` missing `where` โ€” rotation + reuse detection (`incoming !== stored โ†’ 401`) centralized in `TokenSigner` + `Clock` for deterministic expiry tests. +- **Validation+sanitization:** `registerSchema` + `sanitizeRegistration` run inside `register()` โ€” caller never imports `validate.ts:6` or `sanitize.middleware.ts:6`; throws typed `AuthError` mapped to `ApiError` at HTTP edge. +- **DB/Repository:** `UserRepository` owns all 15 cols of `db/schema/user.ts:11` + Drizzle operators (`eq,or,and,gt`) โ€” no caller touches Drizzle. +- **Cache/storage coherence:** `me()` read-through `getโ†’dbโ†’setex(1800)` hidden; `updateUsername`/`uploadProfilePicture` invalidate cache; S3 key `s3ProfilePicsPrefix + userId + sanitizedName + Date.now()` + old avatar GC + `image/*` + 5MB validation hidden in `S3StorageAdapter`. +- **Mail/analytics:** `Mailer` renders `Mailgen` inside adapter; `AnalyticsPort` centralizes 13 `posthog.capture` events to one enum, fire-and-forget with `flush` on `close()`. +- **OAuth:** `passport/index.ts:125,218` Google vs GitHub duplication (`sub` vs `node_id`, `picture` vs `avatar_url`) hidden behind `OAuthPort`; adding Apple = new adapter. +- **Env/lifecycle:** One `envSchema.parse` โ†’ `AuthConfig` value object; `init()` connects PG/Redis/S3, verifies bucket, warms queue; `close()` drains `pool.end()`, `redis.quit()`, `queue.close()`, `analytics.flush()`. + +## Dependency Strategy + +| Dependency | Category | Port | Production Adapter | Test Adapter | +|---|---|---|---|---| +| `crypto`/`bcrypt`/`jwt`/`hashToken` | **1. In-process** | None (merged) โ€” optional `Clock`/`Hasher`/`TokenSigner` ports for determinism/speed | Direct `node:crypto`, `bcrypt`, `jsonwebtoken` | `FakeHasher` (`hashed:${pw}`), `FakeTokenSigner` (sync), `Clock` fixed date, deterministic `IdGenerator` | +| Postgres + Drizzle (`config/db.ts:7` Pool) | **2. Local-substitutable** | `UserRepository` | `DrizzleUserRepository(pool: Pool)` โ€” `init()` does `SELECT 1`, `close()` calls `pool.end()` | PGlite (`@electric-sql/pglite` + `drizzle-orm/pglite`) for SQL fidelity, or `InMemoryUserRepository` (Map) for speed | +| Redis/Cache (`dist/lib/redis.js` + `dist/utils/cache.js`) | **2. Local-substitutable** | `CachePort` | `IORedisCacheAdapter(env.REDIS_URL)` โ€” throws if missing (fails fast vs current silent null) | `InMemoryCacheAdapter` โ€” `Map` respecting `ttlSec` via `Clock` | +| S3 (`utils/s3.ts:8`) | **2. Local-substitutable** | `ObjectStoragePort` | `S3StorageAdapter` | `InMemoryStorageAdapter` (Map) โ€” returns `memory://bucket/key` | +| BullMQ (`queues/queues.ts:3` bare `new Queue`) | **2. Local-substitutable** | `QueuePort` | `BullMQQueueAdapter(connection: IORedis)` | `InMemoryQueueAdapter` (array + immediate callback) | +| Resend+Mailgen (`utils/mail.ts:2`) | **4. True external (Mock)** | `EmailPort` | `ResendEmailAdapter` โ€” hides `mailGenerator.generate`, 3ร— retry with backoff | `InMemoryEmailAdapter` (`sent[]` + `assertSent`) or `vi.fn()` mock | +| PostHog (`lib/posthog.ts:3`) | **4. True external (Mock)** | `AnalyticsPort` | `PostHogAnalyticsAdapter` โ€” no-ops if `POSTHOG_API_KEY` undefined (fixes `!` crash) | `NoopAnalytics` or `vi.fn()` asserting `capture({event:'user_registered'})` | +| OAuth providers (`passport-*`) | **4. True external (Mock)** | `OAuthPort` (inside `AuthDomain`) | `PassportOAuthAdapter` โ€” registers strategies in `init()`, not at import time | `FakeOAuthAdapter` returning canned `User` | + +No **3. Remote but owned** dependencies today; if auth splits to RPC, add `UserServicePort` with `Http` vs `InMemory` adapters without changing domain. + +## Testing Strategy + +- **New boundary tests to write (at `Auth` / `AuthDomain` interface โ€” survive refactors, assert observable outcomes):** + - `register โ†’ verify โ†’ login โ†’ refresh โ†’ logout` happy path (assert `email.sent[0].to`, `users.findByEmail` exists, `analytics capture user_registered`, tokens returned, cookies set). + - Duplicate `register` with same email/username โ†’ `409 User exists` (covers `or(eq(email),eq(username))`). + - `verifyEmail` with expired token (advance `Clock` +20m) โ†’ `400 Token invalid or expired`; valid โ†’ `isEmailVerified:true` + token nulled. + - `login` via email vs username (both `loginSchema` paths), wrong password โ†’ `401 Invalid credentials`. + - `authenticate` valid/expired/missing โ†’ `401 Access token expired / Invalid token` (replaces `verifyJWT`). + - `refresh` rotation โ€” valid token rotates and invalidates old; reuse of old token โ†’ `401 expired or used`; regression for missing `where` bug (assert other users' `refreshToken` unchanged). + - `forgot โ†’ reset` โ€” full flow, same-password guard `400 New password cannot be same`, expired `forgotToken` expiry. + - `changeCurrentPassword` wrong oldPassword โ†’ `401`. + - `me()` read-through: first call misses cache โ†’ hits `UserRepository`, second hits `CachePort` (spy repo not called); TTL 1800 respected via `Clock`. + - `updateUsername` collision โ†’ `409`, `uploadProfilePicture` `text/csv` โ†’ `400 Invalid file type`, >5MB โ†’ `400`, valid `image/png` โ†’ storage upload + old avatar delete + DB update. + - OAuth `handleSocialLogin` new Google/Github user created `isEmailVerified:true`, existing email with `loginType=email_password` โ†’ `400 Please use that login method`. + - Lifecycle: `init()` without `REDIS_URL` throws, `close()` drains handles without leak. + +- **Old tests to delete (replace, don't layer):** + - Shallow per-handler mocks of `db.query.User.findFirst` in `auth.controller.ts:88` / `password.controller.ts:21`, `verifyJWT` isolated tests, `sanitizeRegistration` / `validate(registerSchema)` unit tests, `passport` strategy stubs of `db.select().from(User)`. All become redundant once boundary suite covers domain via ports. Keep only narrow adapter contract tests (e.g., `ResendEmailAdapter` retries once on 429, `S3StorageAdapter` key sanitization). + +- **Test environment needs:** + - PGlite (`@electric-sql/pglite` + `drizzle-orm/pglite`) or `InMemory*` adapters (50 LoC each in `src/modules/auth/adapters/__test__/`) โ€” no Docker. `InMemoryCacheAdapter` + `InMemoryStorageAdapter` + `InMemoryEmailAdapter` + `NoopAnalytics` + `FakeHasher` (avoids bcrypt 12-round cost). One suite still exercises real `bcrypt`/`jwt` for integration confidence. No live Resend/PostHog/S3/Redis required. CI runs `pnpm test` with zero `.env`. + +## Implementation Recommendations + +**What the module should own:** +- Auth invariants: password policy (Zod regex `/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/`), bcrypt cost 12, token hash+expiry (20m), `isEmailVerified`/`isActive` checks, `loginType` guard, refresh rotation + reuse detection, cache TTL 1800, S3 key sanitization, `lastLoginAt` update. Single `AuthError` union โ†’ `ApiError` mapping at edge. + +**What it should hide:** +- Vendor SDKs (`pg`, `ioredis`, `@aws-sdk/client-s3`, `resend`, `posthog-node`, `passport-*`, `mailgen`), retry/backoff, SQL dialect, cache JSON serialization, URL construction (`${protocol}://${host}/verify-email/...` behind `baseUrl`), queue transport, 13 `posthog.capture` call-sites, sanitization (`express-validator`). + +**What it should expose:** +- `createAuth(opts?) โ†’ Auth` (ergonomic public API) + `AuthError` + `AuthenticatedUser`/`Tokens`. `createAuthDomain(config, ports)` is internal. Controllers become 5-line HTTP translators: `const r = await auth.register(req.body); res.status(201).json(new ApiResponse(201,r,'...'))`. `passport` is not a global singleton. + +**How callers should migrate:** +1. **Phase 0 โ€” bootstrap:** Create `src/modules/auth/ports.ts`, `domain.ts`, `index.ts` (facade). Implement adapters wrapping current `dist/lib/redis.js`/`dist/utils/cache.js` code but with injected config. Add `src/bootstrap.ts` that parses `env.ts` once, creates adapters, `await auth.init()`, wires `makeApp(auth)`. Update `server.ts:7` to `await bootstrap()` before `listen`. Keep old code under feature flag. +2. **Phase 1 โ€” passport:** Change `src/app.ts:10` `import './passport/index'` side-effect โ†’ `auth.init()` registers strategies via `PassportOAuthAdapter`. Export `createPassportStrategies(ports)` called by domain. +3. **Phase 2 โ€” routes:** Replace `routes/auth/user.routes.ts:136` god-router with `auth.router` + `auth.extended.oauth.router` + `auth.middleware.authenticate`. Move `avatarLimiter`/`usernameUpdateLimiter` into `extended` adapters. Mount via `app.use('/api/v1/users', auth.router)`. +4. **Phase 3 โ€” controllers:** Migrate handlers one flow at a time behind flag; copy queries into `DrizzleUserRepository` (dedupe `generateTemporaryToken` + fix `406` missing `where`). Delete `src/controllers/auth/*` when boundary suite green. +5. **Phase 4 โ€” infra:** Delete phantom `dist/utils/cache.js`/`dist/lib/redis.js` sources moved to `src/modules/auth/adapters/`. Enforce via `eslint` `no-restricted-imports` banning `import {db} from '@/config/db'` etc. inside `src/modules/auth` except adapters. +6. **Phase 5 โ€” validation:** Consolidate `sanitize.middleware.ts:6` + `validators/auth.validator.ts:3` + `validate.middleware.ts:6` into domain-internal Zod validation (remove `express-validator`). From eaaf7eb4d8b2a59a91db927064059a74923c38f4 Mon Sep 17 00:00:00 2001 From: Mayank Date: Mon, 24 Aug 2026 13:14:33 +0530 Subject: [PATCH 2/2] refactor: deepen auth, validation, email, passport, routes, http modules - auth: createAuth domain over ports (UserRepository/Cache/Email/Storage/TokenHasher/Clock) with PGlite/InMemory adapters, fix refreshToken missing where, canonical hashToken - validation: merge sanitize+Zod+validate into single Zod pipeline (trim/lower/escape transforms), deprecate express-validator chains - email: deep BullMQ queue/worker with explicit IORedis, QueuedEmailAdapter (enqueue vs direct fallback), lifecycle in bootstrap - passport: factory createPassportStrategies deduplicates Google/GitHub via createOAuthVerify, inject UserRepository/hasher/analytics - routes: decompose god-router user.routes into auth/profile/admin/oauth focused modules, aggregator for compat - http: unify ApiError/ApiResponse/asyncHandler/errorHandler into lib/http deep module, helpers successResponse/createdResponse RFCs: issues/001-006 --- issues/002-validation-pipeline-deepening.md | 120 ++++++ issues/003-email-queue-deepening.md | 130 ++++++ issues/004-passport-factory-deepening.md | 149 +++++++ issues/005-route-composition-deepening.md | 125 ++++++ issues/006-http-semantics-deepening.md | 98 +++++ src/app.ts | 32 +- src/bootstrap.ts | 113 ++++++ src/controllers/auth/auth.controller.ts | 3 +- src/lib/http/asyncHandler.ts | 14 + src/lib/http/errorMiddleware.ts | 41 ++ src/lib/http/errors.ts | 21 + src/lib/http/index.ts | 13 + src/lib/http/response.ts | 32 ++ src/lib/posthog.ts | 26 +- src/lib/redis.ts | 32 ++ src/lib/validation/index.ts | 63 +++ src/middlewares/error.middleware.ts | 54 +-- src/middlewares/sanitize.middleware.ts | 102 ++--- src/middlewares/validate.middleware.ts | 52 ++- .../auth/adapters/drizzleUserRepository.ts | 77 ++++ .../auth/adapters/inMemoryUserRepository.ts | 90 ++++ .../auth/adapters/ioredisCacheAdapter.ts | 64 +++ src/modules/auth/adapters/jwtTokenSigner.ts | 47 +++ .../auth/adapters/memoryCacheAdapter.ts | 32 ++ .../auth/adapters/memoryEmailAdapter.ts | 16 + .../auth/adapters/memoryStorageAdapter.ts | 26 ++ .../auth/adapters/posthogAnalyticsAdapter.ts | 43 ++ .../auth/adapters/queuedEmailAdapter.ts | 26 ++ .../auth/adapters/resendEmailAdapter.ts | 41 ++ src/modules/auth/adapters/s3StorageAdapter.ts | 23 ++ src/modules/auth/domain.ts | 383 ++++++++++++++++++ src/modules/auth/errors.ts | 55 +++ src/modules/auth/index.ts | 256 ++++++++++++ src/modules/auth/passport/factory.ts | 205 ++++++++++ src/modules/auth/ports.ts | 93 +++++ src/modules/email/queue.ts | 64 +++ src/modules/email/types.ts | 9 + src/modules/email/worker.ts | 69 ++++ src/passport/index.ts | 343 ++-------------- src/queues/queues.ts | 10 +- src/queues/workers.ts | 17 +- src/routes/auth/admin.routes.ts | 16 + src/routes/auth/auth.routes.ts | 21 + src/routes/auth/oauth.routes.ts | 23 ++ src/routes/auth/profile.routes.ts | 41 ++ src/routes/auth/user.routes.ts | 147 +------ src/server.ts | 16 +- src/utils/ApiError.ts | 38 +- src/utils/ApiResponse.ts | 22 +- src/utils/asyncHandler.ts | 20 +- src/utils/cache.ts | 72 ++++ src/utils/mail.ts | 74 +--- src/utils/mailTemplates.ts | 23 ++ src/utils/token.ts | 10 + src/validators/auth.validator.ts | 103 +++-- 55 files changed, 3065 insertions(+), 770 deletions(-) create mode 100644 issues/002-validation-pipeline-deepening.md create mode 100644 issues/003-email-queue-deepening.md create mode 100644 issues/004-passport-factory-deepening.md create mode 100644 issues/005-route-composition-deepening.md create mode 100644 issues/006-http-semantics-deepening.md create mode 100644 src/bootstrap.ts create mode 100644 src/lib/http/asyncHandler.ts create mode 100644 src/lib/http/errorMiddleware.ts create mode 100644 src/lib/http/errors.ts create mode 100644 src/lib/http/index.ts create mode 100644 src/lib/http/response.ts create mode 100644 src/lib/redis.ts create mode 100644 src/lib/validation/index.ts create mode 100644 src/modules/auth/adapters/drizzleUserRepository.ts create mode 100644 src/modules/auth/adapters/inMemoryUserRepository.ts create mode 100644 src/modules/auth/adapters/ioredisCacheAdapter.ts create mode 100644 src/modules/auth/adapters/jwtTokenSigner.ts create mode 100644 src/modules/auth/adapters/memoryCacheAdapter.ts create mode 100644 src/modules/auth/adapters/memoryEmailAdapter.ts create mode 100644 src/modules/auth/adapters/memoryStorageAdapter.ts create mode 100644 src/modules/auth/adapters/posthogAnalyticsAdapter.ts create mode 100644 src/modules/auth/adapters/queuedEmailAdapter.ts create mode 100644 src/modules/auth/adapters/resendEmailAdapter.ts create mode 100644 src/modules/auth/adapters/s3StorageAdapter.ts create mode 100644 src/modules/auth/domain.ts create mode 100644 src/modules/auth/errors.ts create mode 100644 src/modules/auth/index.ts create mode 100644 src/modules/auth/passport/factory.ts create mode 100644 src/modules/auth/ports.ts create mode 100644 src/modules/email/queue.ts create mode 100644 src/modules/email/types.ts create mode 100644 src/modules/email/worker.ts create mode 100644 src/routes/auth/admin.routes.ts create mode 100644 src/routes/auth/auth.routes.ts create mode 100644 src/routes/auth/oauth.routes.ts create mode 100644 src/routes/auth/profile.routes.ts create mode 100644 src/utils/cache.ts create mode 100644 src/utils/mailTemplates.ts diff --git a/issues/002-validation-pipeline-deepening.md b/issues/002-validation-pipeline-deepening.md new file mode 100644 index 0000000..bc49494 --- /dev/null +++ b/issues/002-validation-pipeline-deepening.md @@ -0,0 +1,120 @@ +# RFC: Deepen Validation Pipeline โ€” Single Zod Module + +## Problem + +**Three shallow modules owning one concept** โ€” `middlewares/sanitize.middleware.ts:82` (5 `express-validator` chains), `validators/auth.validator.ts:85` (8 Zod schemas), `middlewares/validate.middleware.ts:33` (dual-library `validationResult` then `schema.parse`) are tightly coupled yet fragmented across files. To understand one flow (e.g., `POST /register` `routes/auth/user.routes.ts:60`) you bounce 3 files: `sanitizeRegistration` โ†’ `validate(registerSchema)` โ†’ `registerSchema` definition, plus the route wiring itself. `validate` conflates two libraries: first checks `express-validator` errors, then Zod `issues`, throwing unified `ApiError` but with two error shapes (`param/path` vs `path` join). + +Duplication: same rules encoded twice โ€” `username` `/^[a-zA-Z0-9_]+$/` and `min 3 max 50` in both `sanitize.middleware.ts:16` and `auth.validator.ts:5`, `password` 8-char + special-char regex in both, `email` `isEmail`/`normalizeEmail`/`trim`/`escape` in sanitize vs `z.string().email()` in Zod. `sanitizePasswordReset:63` validates `resetToken` (body field) while route uses `:resetToken` param โ€” drift. + +Shallow interfaces: each sanitize export is `body('email').isEmail().normalizeEmail().trim().escape()` โ€” one chain, one field, interface equals implementation. `validate` is 20 LoC wrapper around two libraries, not a domain. Every new endpoint requires editing 4 places (route + sanitize + validator + validate import) and remembering `sanitizeRegistration, validate(registerSchema)` order. + +Integration risk in seams: sanitize runs `escape()` (HTML-entity) before Zod sees value, changing length and potentially bypassing `min 3` after escape (`&` โ†’ `&`); Zod then re-validates without escape awareness. Handlers receive unsanitized `req.body` (original not parsed `result.data`), so they see unnormalized email (`TEST@Example.COM` vs `test@example.com`) unless they re-trim. + +## Proposed Interface + +**Deep module `src/lib/validation` โ€” single Zod pipeline hides sanitization, single `validate(schema)` factory.** + +### File topology (after) +- `src/lib/validation/index.ts:1` โ€” deep module, owns `validate` factory + helpers `escapeHtml`, `normalizeEmail` (previously scattered) +- `src/validators/auth.validator.ts:1` โ€” schemas own sanitization via Zod transforms (`.trim().toLowerCase().transform(escapeHtml).pipe(z.string().email())`) +- `src/middlewares/validate.middleware.ts:1` โ€” single Zod path, assigns sanitized `result.data` back to `req.body` (hides normalization from handlers), canonical error shape `ApiError(400, 'Validation failed', [{field,message}])` +- `src/middlewares/sanitize.middleware.ts:1` โ€” deprecated no-ops (logs warning, calls `next()`) for backward compat + +### Public surface + +```typescript +// src/middlewares/validate.middleware.ts / src/lib/validation/index.ts +export const validate = (schema: ZodType) => (req: Request, _res: Response, next: NextFunction) => { + const result = schema.safeParse(req.body); + if (!result.success) return next(new ApiError(400, 'Validation failed', + result.error.issues.map(i => ({ field: i.path.join('.'), message: i.message })))); + req.body = result.data; // sanitized (trimmed, lowercased, escaped) + next(); +}; + +// src/validators/auth.validator.ts โ€” schemas hide sanitization +export const registerSchema = z.object({ + email: z.string().trim().toLowerCase().transform(escapeHtml).pipe(z.string().email('Invalid email format')), + username: z.string().trim().transform(escapeHtml).pipe( + z.string().min(3).max(50).regex(/^[a-zA-Z0-9_]+$/, 'Username can only contain letters, numbers, and underscores') + ), + password: z.string().trim().pipe( + z.string().min(8).regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/, 'Password must contain ...') + ), +}); +// similarly: loginSchema, changePasswordSchema, forgotPasswordSchema, resetPasswordSchema, updateUsernameSchema +``` + +### Usage โ€” before vs after + +**Before `routes/auth/user.routes.ts:60` (3 imports, 2 middlewares):** +```typescript +import { sanitizeRegistration, sanitizeLogin } from '../../middlewares/sanitize.middleware'; +import { validate } from '../../middlewares/validate.middleware'; +import { registerSchema } from '../../validators/auth.validator'; +router.post('/register', sanitizeRegistration, validate(registerSchema), registerUser); +router.post('/login', sanitizeLogin, validate(loginSchema), loginUser); +router.put('/username', verifyJWT, usernameUpdateLimiter, sanitizeUsernameUpdate, validate(updateUsernameSchema), updateUsername); +router.post('/change-password', verifyJWT, sanitizePasswordChange, validate(changePasswordSchema), changeCurrentPassword); +``` + +**After (1 import, 1 middleware, sanitization hidden):** +```typescript +import { validate } from '../../middlewares/validate.middleware'; +// or import { validate } from '../../lib/validation'; +import { registerSchema, loginSchema, updateUsernameSchema, changePasswordSchema } from '../../validators/auth.validator'; +router.post('/register', validate(registerSchema), registerUser); +router.post('/login', validate(loginSchema), loginUser); +router.put('/username', verifyJWT, usernameUpdateLimiter, validate(updateUsernameSchema), updateUsername); +router.post('/change-password', verifyJWT, validate(changePasswordSchema), changeCurrentPassword); +``` + +Handlers receive sanitized `req.body` (e.g., `test@example.com` not ` TEST@Example.COM `) without knowing `trim`/`escape` exists. Route file shrinks `136 โ†’ 116 LoC` (`routes/auth/user.routes.ts:1`). + +### What it hides internally + +| Hidden | Previously in `sanitize.middleware.ts` | Now inside Zod schema via transform | +|---|---|---| +| `trim` | `.trim()` per field | `.trim()` (Zod built-in) | +| `normalizeEmail` (lowercase) | `.normalizeEmail()` | `.toLowerCase()` (Zod) | +| `escape` (XSS) | `.escape()` per field | `.transform(escapeHtml)` โ€” `&<>"'` โ†’ entities | +| Length/regex | `.isLength()`, `.matches()` | `.min()/.max()/.regex()` | +| Email validation | `.isEmail()` | `.pipe(z.string().email())` | + +`validate` no longer checks `validationResult(req)`; single `safeParse` + `req.body = result.data` hides sanitization assignment. + +## Dependency Strategy + +- **In-process**: Pure computation (Zod `z`), `escapeHtml`/`normalizeEmail` helpers merged directly into module. No I/O, no injection. +- **No external deps removed from interface:** `express-validator` remains in `package.json` for deprecated `sanitize.middleware.ts` no-ops but is no longer imported by hot path (`validate` + schemas). Remove in next major. + +## Testing Strategy + +- **New boundary tests to write (at `validate(schema)` interface โ€” survive refactors):** + - `registerSchema` โ€” ` TEST@Example.COM ` โ†’ `test@example.com` (trim+lower), `alice_123` โ†’ `alice_123`, `