Security Guide

XyPriss includes 12 built-in security middleware modules to protect your applications.

Built-in Security Middleware

  1. Helmet - Security headers (CSP, X-Frame-Options, HSTS)
  2. CORS - Cross-origin resource sharing protection
  3. Rate Limiting - Request throttling and abuse prevention
  4. CSRF - Cross-site request forgery protection
  5. Compression - Response compression with security
  6. HPP - HTTP parameter pollution protection
  7. Mongo Sanitize - NoSQL injection protection
  8. XSS - Cross-site scripting protection
  9. Morgan - Request logging for security monitoring
  10. Slow Down - Progressive delay protection
  11. Express Brute - Brute force attack protection
  12. Validator - Input validation and sanitization

Basic Security Setup

import { createServer } from "xypriss";

const server = createServer({
    security: {
        enabled: true,
        csrf: { enabled: true },
        rateLimit: { 
            max: 100, 
            windowMs: 15 * 60 * 1000 
        }
    }
});

CSRF Protection

XyPriss uses the csrf-csrf library for robust CSRF protection:

const server = createServer();

// Configure CSRF protection
server.middleware().csrf({
    getSecret: () => process.env.CSRF_SECRET || "default-secret",
    cookieName: "__Host-csrf-token",
    cookieOptions: {
        httpOnly: true,
        sameSite: "strict",
        secure: process.env.NODE_ENV === "production"
    }
});

Rate Limiting

Basic Rate Limiting

server.middleware().rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100, // Limit each IP to 100 requests per windowMs
    message: "Too many requests from this IP"
});

Progressive Slow Down

server.middleware().slowDown({
    windowMs: 15 * 60 * 1000,
    delayAfter: 10, // Allow 10 requests without delay
    delayMs: 500, // Add 500ms delay per request
    maxDelayMs: 5000 // Maximum delay of 5 seconds
});

Authentication

JWT Authentication Example

import jwt from "jsonwebtoken";
import { Hash } from "xypriss-security";

const JWT_SECRET = process.env.JWT_SECRET;

// Login endpoint
server.post("/auth/login", async (req, res) => {
    const { username, password } = req.body;
    
    // Verify user
    const user = await verifyUser(username, password);
    
    if (!user) {
        return res.status(401).json({ error: "Invalid credentials" });
    }
    
    // Generate JWT token
    const token = jwt.sign(
        { userId: user.id, username: user.username },
        JWT_SECRET,
        { expiresIn: "1h" }
    );
    
    res.json({ token });
});

// Authentication middleware
function authenticateToken(req, res, next) {
    const token = req.headers["authorization"]?.split(" ")[1];
    
    if (!token) {
        return res.status(401).json({ error: "Access token required" });
    }
    
    jwt.verify(token, JWT_SECRET, (err, user) => {
        if (err) {
            return res.status(403).json({ error: "Invalid token" });
        }
        req.user = user;
        next();
    });
}

// Protected route
server.get("/api/protected", authenticateToken, (req, res) => {
    res.json({ message: "Protected data", user: req.user });
});

Input Validation

XSS Protection

server.middleware().xss({
    whiteList: {
        a: ["href"],
        b: [],
        i: [],
        strong: [],
        em: []
    }
});

MongoDB Injection Protection

server.middleware().mongoSanitize({
    replaceWith: "_"
});

HTTP Parameter Pollution

server.middleware().hpp({
    whitelist: ["tags", "categories"]
});

Security Headers

server.middleware().helmet({
    contentSecurityPolicy: {
        directives: {
            defaultSrc: ["'self'"],
            styleSrc: ["'self'", "'unsafe-inline'"],
            scriptSrc: ["'self'"],
            imgSrc: ["'self'", "data:", "https:"]
        }
    },
    hsts: {
        maxAge: 31536000,
        includeSubDomains: true,
        preload: true
    }
});

Security Best Practices

  • Use HTTPS in production
  • Implement proper authentication
  • Hash passwords with strong algorithms (Argon2ID)
  • Validate and sanitize all inputs
  • Use security headers (Helmet)
  • Implement rate limiting
  • Log security events
  • Keep dependencies updated
  • Use environment variables for secrets
  • Implement proper error handling
  • Monitor for suspicious activity
  • Regular security audits