Skip to content

Configuration Options

Azizul Hakim edited this page Nov 2, 2024 · 6 revisions

The nestjs-xsecurity module provides extensive configuration options through the XSecurityConfig interface. This document details all available configuration options and their usage.

Configuration Interface

interface XSecurityConfig {
  // Enable/disable middleware
  enabled?: boolean;

  // Your secret key for token validation
  secret?: string;

  // Rate limiting settings
  rateLimit?: {
    enabled?: boolean;      // Default: true
    maxAttempts?: number;    // Default: 5
    decayMinutes?: number;   // Default: 1
    cleanupInterval?: number; // Default: 5
    storeLimit: number;     // Default: 10000
  };

  // Token configuration
  token?: {
    headerName?: string;     // Default: 'X-SECURITY-TOKEN'
    expirySeconds?: number;  // Default: 10 (10 seconds)
  };

  // Paths to exclude from security checks
  exclude?: Array<string | RegExp>;

  // Custom error messages
  errorMessages?: {
    rateLimitExceeded?: string;
    invalidToken?: string;
  };
}

Configuration Sections

Global Options

Option Type Default Description
enabled boolean true Master switch to enable/disable the security middleware
secret string undefined Secret key for token signing. If not provided, will use environment variable
exclude Array<string | RegExp> undefined Routes to exclude from XSecurity middleware

Rate Limiting Options (RateLimitConfig)

Option Type Default Description
enabled boolean true twitch to on/off rate limiting
maxAttempts number 5 Maximum number of failed attempts before rate limiting
decayMinutes number 1 Time in minutes before rate limit reset
cleanupInterval number 5 Cleanup interval in minutes for rate limit store
storeLimit number 10000 Maximum number of entries in rate limit store

Token Options (TokenConfig)

Option Type Default Description
headerName string 'X-SECURITY-TOKEN' Name of the header to look for the security token
expirySeconds number 10 Token expiry time in seconds

Environment Variable Options (EnvironmentConfig)

Option Type Default Description
enabled string 'XSECURITY_ENABLED' Environment variable name for enabling/disabling the middleware
secret string 'XSECURITY_SECRET' Environment variable name for the security secret

Error Messages

Option Type Default Description
rateLimitExceeded string 'Too many requests. Please try again later.' Custom message for rate limit exceeded errors
invalidToken string 'Invalid XSECURITY token' Custom message for invalid token errors

Usage Examples

Basic Configuration

import { XSecurityModule } from 'nestjs-xsecurity';

@Module({
  imports: [
    XSecurityModule.register({
      enabled: true,
      token: {
        headerName: 'Custom-Security-Token',
        expirySeconds: 10  // 10 seconds token validity
      }
    })
  ]
})
export class AppModule {}

Advanced Configuration with Route Exclusion

import { XSecurityModule } from 'nestjs-xsecurity';

@Module({
  imports: [
    XSecurityModule.register({
      enabled: true,
      secret: process.env.MY_SECRET_KEY,
      exclude: [
        '/health',
        '/public/*',
        /^\/api\/v1\/public\/.*/
      ],
      rateLimit: {
        maxAttempts: 3,
        decayMinutes: 5,
        cleanupInterval: 10
      },
      token: {
        headerName: 'Custom-Security-Token',
        expirySeconds: 10  // 10 seconds
      },
      environment: {
        enabled: 'CUSTOM_SECURITY_ENABLED',
        secret: 'CUSTOM_SECURITY_SECRET'
      },
      errorMessages: {
        rateLimitExceeded: 'Access blocked due to too many failed attempts',
        invalidToken: 'Security token verification failed'
      }
    })
  ]
})
export class AppModule {}

Route Exclusion Patterns

The exclude option supports both string paths and RegExp patterns:

exclude: [
  // Simple string paths
  '/health',
  '/metrics',
  '/public/*',
  
  // Regular expressions
  /^\/api\/v1\/public\/.*/,
  /^\/docs\/.*$/,
  
  // Wildcard paths
  '/assets/*',
  '/static/*'
]

Important Notes

  1. Token Expiry: The default token expiry is set to 10 seconds, which is intentionally short-lived for security purposes. Adjust this value based on your specific security requirements, but it's recommended to keep it as short as possible.

  2. Rate Limiting: The rate limit store keeps track of failed attempts and automatically cleans up based on the cleanupInterval setting to prevent memory leaks.

  3. Secret Key: You can provide the secret either through configuration (secret option) or environment variables. If both are provided, the configuration value takes precedence.

  4. Route Exclusion: The exclude option allows you to bypass the security middleware for specific routes, which is useful for public endpoints or health checks.

Clone this wiki locally