Get the FREE Ultimate OpenClaw Setup Guide →

api-security-hardening

Scanned
npx machina-cli add skill secondsky/claude-skills/api-security-hardening --openclaw
Files (1)
SKILL.md
2.4 KB

API Security Hardening

Protect REST APIs against common vulnerabilities with multiple security layers.

Security Middleware Stack (Express)

const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');

app.use(helmet());
app.use(mongoSanitize());
app.use(xss());

app.use('/api/', rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100
}));

app.use('/api/auth/', rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 5
}));

Input Validation

const { body, validationResult } = require('express-validator');

app.post('/users',
  body('email').isEmail().normalizeEmail(),
  body('password').isLength({ min: 8 }).matches(/[A-Z]/).matches(/[0-9]/),
  body('name').trim().escape().isLength({ max: 100 }),
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    // Process request
  }
);

Security Headers

app.use((req, res, next) => {
  res.setHeader('Content-Security-Policy', "default-src 'self'");
  res.setHeader('X-Frame-Options', 'DENY');
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
  res.setHeader('X-XSS-Protection', '1; mode=block');
  next();
});

Security Checklist

  • HTTPS everywhere
  • Authentication on all protected routes
  • Input validation and sanitization
  • Rate limiting enabled
  • Security headers configured
  • CORS restricted to allowed origins
  • No stack traces in production errors
  • Audit logging enabled
  • Dependencies regularly updated

Additional Implementations

See references/python-nginx.md for:

  • Python FastAPI security middleware
  • Pydantic input validation with password rules
  • Nginx SSL/TLS and security headers configuration
  • HTTP Parameter Pollution prevention

Never Do

  • Trust user input without validation
  • Return detailed errors in production
  • Store secrets in code
  • Use GET for state-changing operations
  • Disable security for convenience

Source

git clone https://github.com/secondsky/claude-skills/blob/main/plugins/api-security-hardening/skills/api-security-hardening/SKILL.mdView on GitHub

Overview

Provides a layered security approach for REST APIs using an Express middleware stack. It combines authentication on protected routes, rate limiting, input validation and sanitization, and security headers to support defense-in-depth and security audits.

How This Skill Works

Core components include helmet for headers, express-rate-limit for request throttling, express-mongo-sanitize and xss-clean for input cleansing, and express-validator for strict input validation. A dedicated security header middleware sets CSP, X-Frame-Options, HSTS, and other headers, while a Security Checklist guides production readiness.

When to Use It

  • Deploying a production REST API that handles user data and protected routes
  • Carrying out security audits or compliance checks requiring defense-in-depth
  • Defending against injection, XSS, and parameter pollution vulnerabilities
  • Enforcing rate limits on API and stricter limits on auth endpoints to prevent abuse
  • Fixing CORS misconfigurations and ensuring no detailed errors leak in production

Quick Start

  1. Step 1: Install and import security libraries (helmet, express-rate-limit, express-mongo-sanitize, xss-clean, express-validator) and wire into your Express app
  2. Step 2: Apply the middleware stack to /api routes and configure per-route rate limits (e.g., 100/15m on /api and 5/15m on /api/auth)
  3. Step 3: Add express-validator rules for endpoints (email, password, name) and set security headers in a middleware; run tests and review the security checklist

Best Practices

  • Use a layered middleware stack (helmet, express-mongo-sanitize, and xss-clean) for all API routes
  • Enforce per-route rate limits, with stricter limits on /api/auth (e.g., 100/15m and 5/15m respectively)
  • Validate and sanitize all inputs with express-validator, including email normalization and password rules
  • Set robust security headers: CSP, X-Frame-Options, X-Content-Type-Options, HSTS, X-XSS-Protection
  • Maintain a security checklist and keep dependencies updated; restrict error details in production and enable audit logging

Example Use Cases

  • A fintech Node.js Express API protecting customer data with auth, rate limiting, and input validation
  • A SaaS product API with admin endpoints and per-route security controls
  • A public REST API handling user-generated content with server-side input sanitization
  • An internal microservice gateway implementing defense-in-depth and strict CORS rules
  • A security audit scenario verifying no sensitive errors are exposed and dependencies are current

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers