backend-ultimate

πŸ”₯ ULTIMATE BACKEND MASTERY - 25+ YEARS EXPERT LEVEL

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "backend-ultimate" with this command: npx skills add shajar5110/hackathon-ii-phase-3/shajar5110-hackathon-ii-phase-3-backend-ultimate

πŸ”₯ ULTIMATE BACKEND MASTERY - 25+ YEARS EXPERT LEVEL

Enterprise-grade backend architecture with genius-level optimization, comprehensive security hardening, advanced architectural patterns, and complete coverage across all frameworks, databases, and deployment strategies.

TABLE OF CONTENTS

  • Core Architecture Decision Trees

  • Route Protection & Middleware (PERFECTION)

  • Authentication Systems (ALL METHODS)

  • Authorization & RBAC

  • API Design (REST, GraphQL, WebSockets, gRPC)

  • Database Patterns & ORM

  • Caching Strategies

  • Message Queues & Async Jobs

  • Security Hardening (COMPREHENSIVE)

  • Performance Optimization

  • Microservices & Advanced Patterns

  • Monitoring, Logging, Tracing

  • Testing (Unit, Integration, E2E, Load, Security)

  • Deployment (Docker, Kubernetes, CI/CD)

  • Real-World Implementations

PART 1: CORE ARCHITECTURE & DECISION TREES

Backend Technology Decision Matrix

Need to build a backend?

STEP 1: Choose Primary Framework β”œβ”€ Need high performance + async? β†’ FastAPI (Python) β”œβ”€ Need full JavaScript ecosystem? β†’ Express/Node.js β”œβ”€ Need type safety + performance? β†’ Node.js with TypeScript β”œβ”€ Need full-stack with backend? β†’ Next.js API routes └─ Need extreme performance + concurrency? β†’ Go/Rust

STEP 2: Choose Database(s) β”œβ”€ Relational data + complex queries? β†’ PostgreSQL β”œβ”€ Document storage + flexibility? β†’ MongoDB β”œβ”€ Cache layer + sessions? β†’ Redis β”œβ”€ Full-text search? β†’ Elasticsearch β”œβ”€ Time-series data? β†’ TimescaleDB/InfluxDB └─ All of above β†’ Use what fits each use case

STEP 3: Choose API Style β”œβ”€ Simple CRUD operations? β†’ REST β”œβ”€ Complex data requirements? β†’ GraphQL β”œβ”€ Real-time features needed? β†’ WebSockets β”œβ”€ Internal services? β†’ gRPC └─ Combination? β†’ Use all, not monolithic

STEP 4: Choose Architectural Pattern β”œβ”€ Starting small? β†’ Monolith (with modular structure) β”œβ”€ Need scaling? β†’ Microservices β”œβ”€ Heavy background work? β†’ Event-driven β”œβ”€ Complex business logic? β†’ DDD (Domain-Driven Design) └─ Combination? β†’ Hybrid approach

STEP 5: Choose Deployment β”œβ”€ Single server? β†’ Docker + systemd β”œβ”€ Multiple servers? β†’ Docker + Docker Compose β”œβ”€ Enterprise scale? β†’ Kubernetes β”œβ”€ Serverless? β†’ AWS Lambda / Google Cloud Functions └─ Cloud native? β†’ Managed services (RDS, ElastiCache, etc.)

Project Structure - Next-Generation Backend

backend/ β”œβ”€β”€ src/ β”‚ β”œβ”€β”€ core/ // Core infrastructure β”‚ β”‚ β”œβ”€β”€ config.ts // Configuration management β”‚ β”‚ β”œβ”€β”€ env.ts // Environment validation (Zod) β”‚ β”‚ β”œβ”€β”€ database.ts // Database connections β”‚ β”‚ └── cache.ts // Cache setup (Redis) β”‚ β”‚ β”‚ β”œβ”€β”€ middleware/ // Global middleware (PERFECTION) β”‚ β”‚ β”œβ”€β”€ authentication.ts // JWT/session verification β”‚ β”‚ β”œβ”€β”€ authorization.ts // RBAC enforcement β”‚ β”‚ β”œβ”€β”€ validation.ts // Input validation (Zod) β”‚ β”‚ β”œβ”€β”€ error-handling.ts // Centralized errors β”‚ β”‚ β”œβ”€β”€ logging.ts // Request logging β”‚ β”‚ β”œβ”€β”€ rate-limiting.ts // DDoS protection β”‚ β”‚ β”œβ”€β”€ cors.ts // CORS handling β”‚ β”‚ β”œβ”€β”€ helmet.ts // Security headers β”‚ β”‚ β”œβ”€β”€ request-id.ts // Correlation IDs β”‚ β”‚ └── compression.ts // Response compression β”‚ β”‚ β”‚ β”œβ”€β”€ routes/ // API endpoints (PROTECTED) β”‚ β”‚ β”œβ”€β”€ auth.routes.ts // Authentication endpoints β”‚ β”‚ β”œβ”€β”€ user.routes.ts // User endpoints β”‚ β”‚ β”œβ”€β”€ products.routes.ts // Product endpoints β”‚ β”‚ β”œβ”€β”€ orders.routes.ts // Order endpoints β”‚ β”‚ └── admin.routes.ts // Admin endpoints (admin only) β”‚ β”‚ β”‚ β”œβ”€β”€ controllers/ // Business logic β”‚ β”‚ β”œβ”€β”€ auth.controller.ts β”‚ β”‚ β”œβ”€β”€ user.controller.ts β”‚ β”‚ β”œβ”€β”€ product.controller.ts β”‚ β”‚ └── order.controller.ts β”‚ β”‚ β”‚ β”œβ”€β”€ services/ // Core services β”‚ β”‚ β”œβ”€β”€ auth.service.ts // Auth logic β”‚ β”‚ β”œβ”€β”€ user.service.ts β”‚ β”‚ β”œβ”€β”€ product.service.ts β”‚ β”‚ β”œβ”€β”€ order.service.ts β”‚ β”‚ β”œβ”€β”€ email.service.ts // Email sending β”‚ β”‚ β”œβ”€β”€ payment.service.ts // Payment processing β”‚ β”‚ └── notification.service.ts // Notifications β”‚ β”‚ β”‚ β”œβ”€β”€ models/ // Database models β”‚ β”‚ β”œβ”€β”€ user.model.ts β”‚ β”‚ β”œβ”€β”€ product.model.ts β”‚ β”‚ β”œβ”€β”€ order.model.ts β”‚ β”‚ └── schema.ts // Validation schemas β”‚ β”‚ β”‚ β”œβ”€β”€ repositories/ // Data access layer β”‚ β”‚ β”œβ”€β”€ user.repository.ts β”‚ β”‚ β”œβ”€β”€ product.repository.ts β”‚ β”‚ └── order.repository.ts β”‚ β”‚ β”‚ β”œβ”€β”€ guards/ // Route protection (PERFECTION) β”‚ β”‚ β”œβ”€β”€ auth.guard.ts // Is authenticated? β”‚ β”‚ β”œβ”€β”€ role.guard.ts // Has role? β”‚ β”‚ β”œβ”€β”€ permission.guard.ts // Has permission? β”‚ β”‚ └── rate-limit.guard.ts // Rate limit check? β”‚ β”‚ β”‚ β”œβ”€β”€ pipes/ // Data transformation β”‚ β”‚ β”œβ”€β”€ validation.pipe.ts β”‚ β”‚ └── parse-int.pipe.ts β”‚ β”‚ β”‚ β”œβ”€β”€ interceptors/ // Request/response handling β”‚ β”‚ β”œβ”€β”€ logging.interceptor.ts β”‚ β”‚ β”œβ”€β”€ transform.interceptor.ts β”‚ β”‚ └── error.interceptor.ts β”‚ β”‚ β”‚ β”œβ”€β”€ decorators/ // Custom decorators β”‚ β”‚ β”œβ”€β”€ @Auth() β”‚ β”‚ β”œβ”€β”€ @Role('admin') β”‚ β”‚ β”œβ”€β”€ @Permission('create:user') β”‚ β”‚ └── @RateLimit(5, '1m') β”‚ β”‚ β”‚ β”œβ”€β”€ utils/ β”‚ β”‚ β”œβ”€β”€ security.ts // Encryption, hashing β”‚ β”‚ β”œβ”€β”€ validation.ts // Input validation β”‚ β”‚ β”œβ”€β”€ jwt.ts // JWT utilities β”‚ β”‚ β”œβ”€β”€ pagination.ts // Pagination helpers β”‚ β”‚ └── error-handling.ts // Error utilities β”‚ β”‚ β”‚ β”œβ”€β”€ queue/ // Background jobs β”‚ β”‚ β”œβ”€β”€ jobs/ β”‚ β”‚ β”‚ β”œβ”€β”€ send-email.job.ts β”‚ β”‚ β”‚ β”œβ”€β”€ process-payment.job.ts β”‚ β”‚ β”‚ └── generate-report.job.ts β”‚ β”‚ └── queue.ts // Queue setup β”‚ β”‚ β”‚ β”œβ”€β”€ events/ // Event-driven architecture β”‚ β”‚ β”œβ”€β”€ user.events.ts β”‚ β”‚ β”œβ”€β”€ order.events.ts β”‚ β”‚ └── event-bus.ts β”‚ β”‚ β”‚ β”œβ”€β”€ types/ // TypeScript types β”‚ β”‚ β”œβ”€β”€ auth.types.ts β”‚ β”‚ β”œβ”€β”€ user.types.ts β”‚ β”‚ β”œβ”€β”€ api.types.ts β”‚ β”‚ └── database.types.ts β”‚ β”‚ β”‚ └── main.ts // Entry point β”‚ β”œβ”€β”€ tests/ β”‚ β”œβ”€β”€ unit/ β”‚ β”œβ”€β”€ integration/ β”‚ β”œβ”€β”€ e2e/ β”‚ └── load/ β”‚ β”œβ”€β”€ docker/ β”‚ β”œβ”€β”€ Dockerfile β”‚ └── docker-compose.yml β”‚ β”œβ”€β”€ kubernetes/ β”‚ β”œβ”€β”€ deployment.yaml β”‚ β”œβ”€β”€ service.yaml β”‚ └── ingress.yaml β”‚ β”œβ”€β”€ .env.example β”œβ”€β”€ .env.local // gitignored β”œβ”€β”€ docker-compose.yml β”œβ”€β”€ .dockerignore β”œβ”€β”€ .eslintrc.json β”œβ”€β”€ .prettierrc.json β”œβ”€β”€ tsconfig.json β”œβ”€β”€ jest.config.js β”œβ”€β”€ package.json └── README.md

PART 2: ROUTE PROTECTION & MIDDLEWARE (PERFECTION)

2.1 Authentication Middleware

// src/middleware/authentication.ts import { NextFunction, Request, Response } from 'express'; import jwt from 'jsonwebtoken'; import { UnauthorizedError } from '@/utils/error-handling';

/**

  • Express authentication middleware

  • Verifies JWT token and attaches user to request

  • PERFECTION: Handles all edge cases */ export function authenticationMiddleware() { return (req: Request, res: Response, next: NextFunction) => { try { // Extract token from multiple sources let token = extractToken(req);

         if (!token) {
             throw new UnauthorizedError('No token provided');
         }
    
         // Verify token signature and expiration
         const decoded = jwt.verify(token, process.env.JWT_SECRET!);
    
         // Check if token is blacklisted (revoked)
         if (isTokenBlacklisted(decoded.jti)) {
             throw new UnauthorizedError('Token has been revoked');
         }
    
         // Attach user to request for later use
         (req as any).user = {
             id: decoded.sub,
             email: decoded.email,
             role: decoded.role,
             permissions: decoded.permissions,
             sessionId: decoded.jti,
         };
    
         // Store token expiration for refresh logic
         (req as any).tokenExp = decoded.exp;
    
         next();
     } catch (error) {
         if (error instanceof jwt.TokenExpiredError) {
             res.status(401).json({ error: 'Token expired' });
         } else if (error instanceof jwt.JsonWebTokenError) {
             res.status(401).json({ error: 'Invalid token' });
         } else {
             next(error);
         }
     }
    

    }; }

/**

  • Extract token from Authorization header, cookies, or query */ function extractToken(req: Request): string | null { // 1. Check Authorization header (Bearer token) const authHeader = req.headers.authorization; if (authHeader?.startsWith('Bearer ')) { return authHeader.slice(7); }

    // 2. Check HTTP-only cookie if (req.cookies?.accessToken) { return req.cookies.accessToken; }

    // 3. Check custom header if (req.headers['x-access-token']) { return req.headers['x-access-token'] as string; }

    // 4. Don't extract from query string (XSS vulnerability) // if (req.query?.token) { ... } // NEVER DO THIS

    return null; }

/**

  • Check if token is in blacklist (revoked) */ function isTokenBlacklisted(jti: string): boolean { // In production: Check Redis or database // For now: Simple in-memory cache return cache.exists(blacklist:${jti}); }

2.2 Authorization Middleware (RBAC)

// src/middleware/authorization.ts import { NextFunction, Request, Response } from 'express'; import { ForbiddenError } from '@/utils/error-handling';

/**

  • Role-based access control middleware

  • PERFECTION: Enforces roles at route level */ export function requireRole(...allowedRoles: string[]) { return (req: Request, res: Response, next: NextFunction) => { const user = (req as any).user;

     if (!user) {
         res.status(401).json({ error: 'Unauthorized' });
         return;
     }
    
     if (!allowedRoles.includes(user.role)) {
         // Log unauthorized attempt
         logSecurityEvent({
             type: 'unauthorized_access',
             userId: user.id,
             requiredRole: allowedRoles,
             userRole: user.role,
             endpoint: req.path,
             method: req.method,
         });
    
         throw new ForbiddenError(
             `This endpoint requires one of roles: ${allowedRoles.join(', ')}`
         );
     }
    
     next();
    

    }; }

/**

  • Permission-based access control

  • PERFECTION: Fine-grained permissions */ export function requirePermission(...permissions: string[]) { return (req: Request, res: Response, next: NextFunction) => { const user = (req as any).user;

     if (!user) {
         res.status(401).json({ error: 'Unauthorized' });
         return;
     }
    
     // Check if user has at least one required permission
     const hasPermission = permissions.some((perm) =>
         user.permissions?.includes(perm)
     );
    
     if (!hasPermission) {
         logSecurityEvent({
             type: 'insufficient_permissions',
             userId: user.id,
             requiredPermissions: permissions,
             userPermissions: user.permissions,
             endpoint: req.path,
         });
    
         throw new ForbiddenError(
             `This endpoint requires one of permissions: ${permissions.join(', ')}`
         );
     }
    
     next();
    

    }; }

/**

  • Resource-based access control

  • PERFECTION: Check ownership */ export function canAccessResource( resourceOwnerField: string = 'userId' ) { return async (req: Request, res: Response, next: NextFunction) => { const user = (req as any).user; const resourceId = req.params.id;

     if (!user) {
         res.status(401).json({ error: 'Unauthorized' });
         return;
     }
    
     // Fetch resource
     const resource = await db.query(
         `SELECT * FROM resources WHERE id = $1`,
         [resourceId]
     );
    
     if (!resource) {
         res.status(404).json({ error: 'Resource not found' });
         return;
     }
    
     // Check ownership
     if (resource[resourceOwnerField] !== user.id && user.role !== 'admin') {
         logSecurityEvent({
             type: 'resource_access_denied',
             userId: user.id,
             resourceId,
             ownerId: resource[resourceOwnerField],
         });
    
         throw new ForbiddenError('You do not have access to this resource');
     }
    
     // Attach resource for later use
     (req as any).resource = resource;
    
     next();
    

    }; }

2.3 Route-Level Protection (Express Example)

// src/routes/protected.routes.ts import { Router } from 'express'; import { authenticationMiddleware } from '@/middleware/authentication'; import { requireRole, requirePermission } from '@/middleware/authorization'; import { validateInput } from '@/middleware/validation'; import { rateLimitGuard } from '@/middleware/rate-limiting'; import { userController } from '@/controllers/user.controller'; import { createUserSchema, updateUserSchema } from '@/models/user.model';

const router = Router();

/**

  • Public endpoints (no protection) */ router.post('/auth/login', userController.login); router.post('/auth/register', userController.register);

/**

  • Protected endpoints (authentication required) */ router.use(authenticationMiddleware());

// Get current user profile router.get( '/users/me', userController.getCurrentUser );

// Update own profile router.patch( '/users/me', validateInput(updateUserSchema), userController.updateProfile );

/**

  • Admin-only endpoints (role required) */ router.use(requireRole('admin'));

// List all users (admin only) router.get( '/users', userController.listUsers );

// Delete user (admin only) router.delete( '/users/:id', userController.deleteUser );

/**

  • Permission-based endpoints */ router.post( '/users', requirePermission('create:user'), validateInput(createUserSchema), userController.createUser );

/**

  • Rate-limited endpoints */ router.post( '/exports/generate', rateLimitGuard({ maxRequests: 5, windowMs: 60000 }), // 5 per minute userController.generateExport );

export const protectedRoutes = router;

2.4 FastAPI Route Protection (Python)

src/middleware/authentication.py

from fastapi import Depends, HTTPException, status, Request from fastapi.security import HTTPBearer, HTTPAuthCredentials import jwt from typing import Optional, Dict, Any

security = HTTPBearer()

class User: def init( self, id: str, email: str, role: str, permissions: list[str], ): self.id = id self.email = email self.role = role self.permissions = permissions

async def get_current_user( credentials: HTTPAuthCredentials = Depends(security), ) -> User: """ Verify JWT token and return current user PERFECTION: Complete authentication """ token = credentials.credentials

try:
    # Verify token signature
    payload = jwt.decode(
        token,
        os.getenv("JWT_SECRET"),
        algorithms=["HS256"],
        options={
            "verify_signature": True,
            "verify_exp": True,
            "verify_aud": False,
        },
    )

    user_id: str = payload.get("sub")
    if user_id is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token",
        )

    # Check if token is blacklisted
    if cache.exists(f"blacklist:{payload.get('jti')}"):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Token has been revoked",
        )

    user = User(
        id=payload.get("sub"),
        email=payload.get("email"),
        role=payload.get("role"),
        permissions=payload.get("permissions", []),
    )

    return user

except jwt.ExpiredSignatureError:
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Token expired",
    )
except jwt.InvalidTokenError:
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid token",
    )

def require_role(*allowed_roles: str): """Check if user has required role""" async def check_role(user: User = Depends(get_current_user)) -> User: if user.role not in allowed_roles: log_security_event({ "type": "unauthorized_access", "user_id": user.id, "required_role": allowed_roles, "user_role": user.role, }) raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Required role: {', '.join(allowed_roles)}", ) return user return check_role

def require_permission(*permissions: str): """Check if user has required permission""" async def check_permission( user: User = Depends(get_current_user), ) -> User: if not any(perm in user.permissions for perm in permissions): log_security_event({ "type": "insufficient_permissions", "user_id": user.id, "required_permissions": permissions, "user_permissions": user.permissions, }) raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Required permission: {', '.join(permissions)}", ) return user return check_permission

src/routes/users.py

from fastapi import APIRouter, Depends from src.middleware.authentication import ( get_current_user, require_role, require_permission, User, )

router = APIRouter()

Public endpoint

@router.post("/auth/login") async def login(credentials: LoginRequest): # Login logic pass

Protected endpoint (authentication required)

@router.get("/users/me") async def get_current_user_profile( user: User = Depends(get_current_user), ): return {"id": user.id, "email": user.email}

Admin-only endpoint

@router.get("/users") async def list_users( user: User = Depends(require_role("admin")), ): return {"users": [...]}

Permission-based endpoint

@router.post("/users") async def create_user( user_data: UserCreate, user: User = Depends(require_permission("create:user")), ): return {"id": "...", "email": user_data.email}

Resource ownership check

@router.get("/orders/{order_id}") async def get_order( order_id: str, current_user: User = Depends(get_current_user), ): order = await db.get_order(order_id)

# Check ownership or admin
if order.user_id != current_user.id and current_user.role != "admin":
    raise HTTPException(
        status_code=status.HTTP_403_FORBIDDEN,
        detail="You do not have access to this resource",
    )

return order

2.5 Global Middleware Chain (Express)

// src/main.ts import express from 'express'; import helmet from 'helmet'; import cors from 'cors'; import compression from 'compression'; import cookieParser from 'cookie-parser'; import rateLimit from 'express-rate-limit';

const app = express();

/**

  • Security middleware (PERFECTION) */ // Helmet: Set security headers app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'"], styleSrc: ["'self'", "'unsafe-inline'"], imgSrc: ["'self'", "data:", "https:"], }, }, hsts: { maxAge: 31536000, // 1 year includeSubDomains: true, preload: true, }, frameguard: { action: 'deny' }, noSniff: true, xssFilter: true, }));

// CORS: Control cross-origin requests app.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(','), credentials: true, optionsSuccessStatus: 200, }));

// Rate limiting: Prevent abuse const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // Limit each IP to 100 requests per windowMs message: 'Too many requests from this IP', standardHeaders: true, // Return rate limit info in headers skip: (req) => req.path === '/health', // Skip health checks }); app.use(limiter);

/**

  • Body parsing middleware */ app.use(express.json({ limit: '10mb' })); app.use(express.urlencoded({ limit: '10mb', extended: true })); app.use(cookieParser());

/**

  • Compression middleware */ app.use(compression());

/**

  • Request logging middleware */ app.use(loggingMiddleware());

/**

  • Custom middleware (PERFECTION) */ // Request ID for tracing app.use(requestIdMiddleware());

// Input validation globally app.use(globalValidationMiddleware());

// Error handling (must be last) app.use(errorHandlingMiddleware());

/**

  • Routes */ app.use('/api/auth', authRoutes); app.use('/api/users', userRoutes); app.use('/api/products', productRoutes); app.use('/api/orders', orderRoutes);

/**

  • 404 handler */ app.use((req, res) => { res.status(404).json({ error: 'Not found' }); });

app.listen(process.env.PORT || 3000);

PART 3: AUTHENTICATION SYSTEMS (ALL METHODS)

3.1 JWT Implementation (Production-Grade)

// src/utils/jwt.ts import jwt from 'jsonwebtoken'; import { randomBytes } from 'crypto';

/**

  • Generate JWT with all security features

  • PERFECTION: Rotation, expiration, blacklisting */ export function generateJWT( userId: string, email: string, role: string, permissions: string[], expiresIn: string = '15m' ): { token: string; expiresAt: number } { const now = Math.floor(Date.now() / 1000); const jti = randomBytes(16).toString('hex');

    const payload = { sub: userId, email, role, permissions, jti, iat: now, exp: now + getExpirationSeconds(expiresIn), nbf: now, aud: 'api', iss: 'auth-service', };

    const token = jwt.sign(payload, process.env.JWT_SECRET!, { algorithm: 'HS256', });

    return { token, expiresAt: payload.exp * 1000, }; }

/**

  • Verify JWT with complete security checks */ export function verifyJWT(token: string): any { try { return jwt.verify(token, process.env.JWT_SECRET!, { algorithms: ['HS256'], audience: 'api', issuer: 'auth-service', }); } catch (error) { if (error instanceof jwt.TokenExpiredError) { throw new Error('Token expired'); } throw new Error('Invalid token'); } }

/**

  • Refresh token pair (access + refresh) */ export function generateTokenPair( userId: string, email: string, role: string, permissions: string[] ) { const accessToken = generateJWT(userId, email, role, permissions, '15m'); const refreshToken = generateJWT(userId, email, role, permissions, '7d');

    return { accessToken, refreshToken }; }

/**

  • Revoke token (add to blacklist) */ export async function revokeToken(jti: string): Promise<void> { await cache.setex(blacklist:${jti}, 86400, '1'); }

function getExpirationSeconds(expiresIn: string): number { const units: Record<string, number> = { s: 1, m: 60, h: 3600, d: 86400, }; const match = expiresIn.match(/^(\d+)([smhd])$/); if (!match) return 900; return parseInt(match[1]) * units[match[2]]; }

3.2 Multi-Factor Authentication

// src/services/mfa.service.ts import speakeasy from 'speakeasy'; import QRCode from 'qrcode';

export async function generateMFASecret(email: string) { const secret = speakeasy.generateSecret({ name: MyApp (${email}), issuer: 'MyApp', length: 32, });

const qrCode = await QRCode.toDataURL(secret.otpauth_url);

return {
    secret: secret.base32,
    qrCode,
};

}

export function verifyMFAToken(secret: string, token: string): boolean { return speakeasy.totp.verify({ secret, encoding: 'base32', token, window: 2, }); }

export async function enableMFA( userId: string, secret: string, mfaToken: string ): Promise<void> { if (!verifyMFAToken(secret, mfaToken)) { throw new Error('Invalid MFA token'); }

await db.user.update({
    where: { id: userId },
    data: {
        mfaEnabled: true,
        mfaSecret: secret,
    },
});

}

3.3 OAuth2 (Google)

// src/services/oauth.service.ts import { google } from 'googleapis';

const oauth2Client = new google.auth.OAuth2( process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET, process.env.GOOGLE_REDIRECT_URI );

export function getGoogleAuthURL(): string { return oauth2Client.generateAuthUrl({ access_type: 'offline', scope: [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ], state: generateRandomState(), }); }

export async function exchangeCodeForTokens(code: string) { try { const { tokens } = await oauth2Client.getToken(code); const ticket = await oauth2Client.verifyIdToken({ idToken: tokens.id_token, audience: process.env.GOOGLE_CLIENT_ID, });

    const payload = ticket.getPayload();

    return {
        email: payload.email,
        name: payload.name,
        picture: payload.picture,
        googleId: payload.sub,
    };
} catch (error) {
    throw new Error('OAuth authentication failed');
}

}

PART 4: AUTHORIZATION & RBAC

4.1 Permission Management

// src/services/permission.service.ts

export async function userHasPermission( userId: string, requiredPermission: string ): Promise<boolean> { const user = await db.user.findUnique({ where: { id: userId }, include: { role: { include: { permissions: true } } }, });

if (user?.role?.name === 'admin') {
    return true;
}

const hasRolePermission = user?.role?.permissions.some(
    (p) => p.name === requiredPermission
);

if (hasRolePermission) {
    return true;
}

const hasUserPermission = await db.userPermission.findFirst({
    where: {
        userId,
        permission: { name: requiredPermission },
        OR: [
            { expiresAt: null },
            { expiresAt: { gt: new Date() } },
        ],
    },
});

return !!hasUserPermission;

}

export async function grantTemporaryPermission( userId: string, permissionName: string, expiresIn: number ): Promise<void> { const permission = await db.permission.findUnique({ where: { name: permissionName }, });

if (!permission) {
    throw new Error('Permission not found');
}

await db.userPermission.create({
    data: {
        userId,
        permissionId: permission.id,
        expiresAt: new Date(Date.now() + expiresIn),
    },
});

}

export async function revokePermission( userId: string, permissionName: string ): Promise<void> { await db.userPermission.deleteMany({ where: { userId, permission: { name: permissionName }, }, }); }

4.2 Audit Logging

// src/services/audit.service.ts

export async function auditLog( userId: string, action: string, resource: string, resourceId: string, changes?: Record<string, any>, ipAddress?: string, userAgent?: string ): Promise<void> { await db.auditLog.create({ data: { userId, action, resource, resourceId, changes, ipAddress, userAgent, timestamp: new Date(), }, }); }

export async function getAuditTrail( resource: string, resourceId: string, limit: number = 50 ): Promise<any[]> { return db.auditLog.findMany({ where: { resource, resourceId }, orderBy: { timestamp: 'desc' }, take: limit, }); }

PART 5: API DESIGN PATTERNS

5.1 RESTful API

// src/controllers/product.controller.ts

export async function listProducts(req: Request, res: Response) { const { page = 1, limit = 20, category, sort = 'createdAt' } = req.query;

const where = category ? { category } : {};

const [products, total] = await Promise.all([
    db.product.findMany({
        where,
        skip: (parseInt(page as string) - 1) * parseInt(limit as string),
        take: parseInt(limit as string),
        orderBy: { [sort as string]: 'desc' },
    }),
    db.product.count({ where }),
]);

res.json({
    data: products,
    pagination: {
        page: parseInt(page as string),
        limit: parseInt(limit as string),
        total,
        pages: Math.ceil(total / parseInt(limit as string)),
    },
});

}

export async function createProduct(req: Request, res: Response) { const { name, price, description, stock } = req.body;

if (!name || !price) {
    return res.status(400).json({ error: 'Missing required fields' });
}

const product = await db.product.create({
    data: {
        name,
        price: parseFloat(price),
        description,
        stock: parseInt(stock) || 0,
    },
});

await auditLog(
    (req as any).user.id,
    'CREATE',
    'product',
    product.id,
    product,
    req.ip
);

res.status(201).json({ data: product });

}

export async function updateProduct(req: Request, res: Response) { const { id } = req.params; const updates = req.body;

const product = await db.product.update({
    where: { id },
    data: updates,
});

await auditLog(
    (req as any).user.id,
    'UPDATE',
    'product',
    id,
    updates,
    req.ip
);

res.json({ data: product });

}

export async function deleteProduct(req: Request, res: Response) { const { id } = req.params;

await db.product.delete({
    where: { id },
});

await auditLog(
    (req as any).user.id,
    'DELETE',
    'product',
    id,
    null,
    req.ip
);

res.json({ message: 'Product deleted' });

}

5.2 WebSockets Real-Time

// src/services/websocket.service.ts import { WebSocketServer } from 'ws'; import { verifyJWT } from './jwt.service';

export function setupWebSocketServer(server: any) { const wss = new WebSocketServer({ server });

wss.on('connection', (ws, req) => {
    const token = extractTokenFromURL(req.url);
    let userId: string;

    try {
        const decoded = verifyJWT(token);
        userId = decoded.sub;
    } catch {
        ws.close(1008, 'Unauthorized');
        return;
    }

    (ws as any).userId = userId;

    ws.on('message', async (data) => {
        try {
            const message = JSON.parse(data.toString());

            switch (message.type) {
                case 'subscribe':
                    subscribeToChannel(ws, message.channel);
                    break;
                case 'publish':
                    publishToChannel(message.channel, message.payload);
                    break;
                case 'ping':
                    ws.send(JSON.stringify({ type: 'pong' }));
                    break;
            }
        } catch (error) {
            ws.send(JSON.stringify({
                type: 'error',
                message: 'Invalid message',
            }));
        }
    });

    ws.on('close', () => {
        unsubscribeAll(ws);
    });
});

return wss;

}

function publishToChannel(channel: string, payload: any) { // Broadcast logic }

function subscribeToChannel(ws: any, channel: string) { if (!ws.channels) ws.channels = []; ws.channels.push(channel); }

function unsubscribeAll(ws: any) { if (ws.channels) { ws.channels = []; } }

function extractTokenFromURL(url: string): string { const match = url.match(/token=([^&]+)/); return match ? match[1] : ''; }

PART 6: ERROR HANDLING & LOGGING

6.1 Centralized Error Handler

// src/utils/error-handling.ts

export class AppError extends Error { constructor( public statusCode: number, message: string, public code?: string ) { super(message); Object.setPrototypeOf(this, AppError.prototype); } }

export class BadRequestError extends AppError { constructor(message: string) { super(400, message, 'BAD_REQUEST'); } }

export class UnauthorizedError extends AppError { constructor(message: string) { super(401, message, 'UNAUTHORIZED'); } }

export class ForbiddenError extends AppError { constructor(message: string) { super(403, message, 'FORBIDDEN'); } }

export class NotFoundError extends AppError { constructor(message: string) { super(404, message, 'NOT_FOUND'); } }

export function errorHandler( err: any, req: any, res: any, next: any ) { console.error('Error:', { message: err.message, stack: err.stack, url: req.originalUrl, method: req.method, ip: req.ip, });

if (err instanceof AppError) {
    return res.status(err.statusCode).json({
        error: {
            message: err.message,
            code: err.code,
        },
    });
}

res.status(500).json({
    error: {
        message: 'Internal server error',
        code: 'INTERNAL_ERROR',
    },
});

}

6.2 Logging System

// src/utils/logger.ts import winston from 'winston';

export const logger = winston.createLogger({ level: process.env.LOG_LEVEL || 'info', format: winston.format.json(), defaultMeta: { service: 'backend-api' }, transports: [ new winston.transports.File({ filename: 'logs/error.log', level: 'error', }), new winston.transports.File({ filename: 'logs/combined.log', }), ...(process.env.NODE_ENV !== 'production' ? [new winston.transports.Console({ format: winston.format.simple(), })] : []), ], });

export function loggingMiddleware(req: any, res: any, next: any) { const start = Date.now();

res.on('finish', () => {
    const duration = Date.now() - start;

    logger.info({
        method: req.method,
        url: req.originalUrl,
        status: res.statusCode,
        duration,
        ip: req.ip,
        userId: req.user?.id,
    });
});

next();

}

PART 7: ENVIRONMENT & ENTRY POINT

7.1 Type-Safe Configuration

// src/core/env.ts import { z } from 'zod';

const envSchema = z.object({ NODE_ENV: z.enum(['development', 'production', 'test']), PORT: z.coerce.number().default(3000), DATABASE_URL: z.string(), REDIS_URL: z.string(), JWT_SECRET: z.string().min(32), JWT_AUDIENCE: z.string(), JWT_ISSUER: z.string(), GOOGLE_CLIENT_ID: z.string(), GOOGLE_CLIENT_SECRET: z.string(), STRIPE_API_KEY: z.string(), ALLOWED_ORIGINS: z.string().transform(s => s.split(',')), LOG_LEVEL: z.enum(['error', 'warn', 'info', 'debug']).default('info'), });

export const env = envSchema.parse(process.env);

7.2 Application Entry Point

// src/main.ts import express from 'express'; import { env } from './core/env'; import { setupMiddleware } from './middleware'; import { setupRoutes } from './routes'; import { errorHandler } from './utils/error-handling';

const app = express();

setupMiddleware(app); setupRoutes(app); app.use(errorHandler);

const server = app.listen(env.PORT, () => { console.log(Server running on port ${env.PORT}); });

process.on('SIGTERM', () => { console.log('Shutting down gracefully'); server.close(() => { console.log('HTTP server closed'); process.exit(0); }); });

This completes PARTS 1-7 with CORE ARCHITECTURE, ROUTE PROTECTION, MIDDLEWARE, AUTHENTICATION, AUTHORIZATION, API DESIGN, and ERROR HANDLING in PERFECTION!

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

General

fastapi-full-stack

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

fullstack-developer

No summary provided by upstream source.

Repository SourceNeeds Review
General

Workspace Trash

Soft-delete protection for workspace files. Intercept file deletions and move them to a recoverable trash instead of permanent removal. Use when deleting, re...

Registry SourceRecently Updated
General

Deploy Public

Private-to-public repo sync. Copies everything except ai/ to the public mirror. Creates PR, merges, syncs releases.

Registry SourceRecently Updated