Skip to content

mindfiredigital/nextjs-fortress

Next.js Fortress

npm version License: MIT PRs Welcome

Universal security validation framework for Next.js applications

Protect your Next.js apps against CVE-2025-55182, injection attacks, encoding bypasses, and other critical vulnerabilities with a production-ready, zero-configuration security layer.


Repository Structure

This is a monorepo containing:

nextjs-fortress/
├── packages/
│   └── nextjs-fortress/     # Core security framework package
│       ├── src/
│       │   ├── validators/  # Security validators
│       │   ├── wrappers/    # API route & server action wrappers
│       │   ├── middleware.ts
│       │   └── cli/         # CLI tool
│       └── tests/           # Comprehensive test suite
│
└── examples/
    └── demoApp/             # Interactive demo application
        ├── app/             # Next.js app directory
        ├── components/      # Demo UI components
        ├── lib/             # Attack definitions & testing
        └── fortress.config.ts

Quick Start

Demo Video

Watch the NextJS Fortress Demo

Installation

npm i @mindfiredigital/nextjs-fortress

CLI Setup

The fastest way to add fortress to your existing Next.js project:

npx fortress init

This automatically:

  • ✅ Creates fortress.config.ts with production-ready defaults
  • ✅ Sets up middleware.ts with security validation
  • ✅ Generates .env.example with configuration options
  • ✅ Creates an example protected API route

Note: If you already have a middleware.ts file, the CLI will skip creation and you'll need to integrate manually (see below).


Complete Setup Guide

1. Create Configuration

Create fortress.config.ts in your project root:

import { FortressConfig } from '@mindfiredigital/nextjs-fortress'

export const fortressConfig: FortressConfig = {
  enabled: true,
  mode: 'production',
  
  logging: {
    enabled: true,
    level: 'warn',
    destination: 'console',
  },

  modules: {
    deserialization: {
      enabled: true,
      maxDepth: 10,
      detectCircular: true,
    },
    injection: {
      enabled: true,
      checks: ['sql', 'command', 'xss', 'codeInjection'],
    },
    encoding: {
      enabled: true,
      blockNonUTF8: true,
      detectBOM: true,
    },
    csrf: {
      enabled: true,
      cookieName: '_csrf',
      tokenSecret: process.env.CSRF_SECRET || 'your-secret-key',
    },
    rateLimit: {
      enabled: true,
      byIP: { requests: 100, window: 60000 },
    },
    content: {
      enabled: true,
      maxPayloadSize: 1024 * 1024, // 1MB
    },
    securityHeaders: {
      enabled: true,
    },
  },

  whitelist: {
    paths: ['/_next', '/favicon.ico', '/api/health'],
    ips: [],
  },

  onSecurityEvent: async (event) => {
    console.log('🚨 Security Event:', {
      type: event.type,
      severity: event.severity,
      message: event.message,
      ip: event.request.ip,
    })
  },
}

Middleware Integration

Option 1: New Project (No Existing Middleware)

If you don't have a middleware.ts file, create one:

import { createFortressMiddleware } from '@mindfiredigital/nextjs-fortress'
import { fortressConfig } from './fortress.config'

export const middleware = createFortressMiddleware(fortressConfig)

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}

Option 2: Existing Middleware (Simple Integration)

If you already have middleware, wrap your existing logic with Fortress:

Before (Your existing middleware):

import { NextRequest, NextResponse } from 'next/server'

// This is exactly what is happening inside the "custom logic" part
export async function middleware(request: NextRequest) {
  const response = NextResponse.next()
  response.headers.set('x-custom', 'value')
  return response
}

export const config = {
  matcher: ['/api/:path*'],
}

After (With Fortress protection):

import { createFortressMiddleware } from '@mindfiredigital/nextjs-fortress'
import { fortressConfig } from './fortress.config'
import { NextRequest, NextResponse } from 'next/server'

// Option 1: Simple
// export const middleware = createFortressMiddleware(fortressConfig)

// Option 2: With custom logic - NO TYPE ERRORS
async function myMiddleware(request: NextRequest) {
  const response = NextResponse.next()
  response.headers.set('x-custom', 'value')
  return response
}

export const middleware = createFortressMiddleware(fortressConfig, myMiddleware)

Option 3: Middleware implementation in custom allowed paths

import { createSelectiveFortressMiddleware } from 'nextjs-fortress'
import { fortressConfig } from './fortress.config'
import { NextRequest, NextResponse } from 'next/server'

// Your existing custom middleware logic
async function myMiddleware(request: NextRequest) {
  const response = NextResponse.next()
  response.headers.set('x-custom', 'value')
  response.headers.set('x-app-version', '1.0.0')
  return response
}

export const middleware = createSelectiveFortressMiddleware(
  fortressConfig,
  {
    // Routes that MUST be protected by Fortress
    protectedPaths: [
      '/api/test',           // Your test endpoint
      '/api/admin/*',        // All admin routes
      '/api/secure/*',       // All secure routes
    ],
    
    // Routes that should NEVER be protected
    excludedPaths: [
      '/api/public/*',       // Public endpoints
      '/api/health',         // Health check
    ],
    
    // Your custom middleware runs on ALL routes
    customMiddleware: myMiddleware
  }
)

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}

Core Security Features

1. Deserialization Protection (CVE-2025-55182)

Blocks prototype pollution and constructor injection attacks.

// ❌ Automatically Blocked
{
  "__proto__": { "isAdmin": true },
  "constructor": { "prototype": { "hacked": true } }
}

// ✅ Allowed
{
  "username": "john_doe",
  "email": "john@example.com"
}

2. Injection Detection

Protects against SQL, Command, XSS, and Code injection.

Type Example Blocked
SQL admin' UNION SELECT password--
XSS <script>alert('XSS')</script>
Command ; cat /etc/passwd
Code eval('malicious')

3. Encoding Bypass Protection (Ghost Mode)

Prevents WAF bypass using alternative encodings like UTF-16LE.

// ❌ Blocked - UTF-16LE detected
Content-Type: application/json; charset=utf-16le

// ❌ Blocked - BOM detected (FF FE)
[0xFF, 0xFE, 0x48, 0x00]

// ✅ Allowed - Standard UTF-8
Content-Type: application/json; charset=utf-8

4. CSRF Protection

Token-based cross-site request forgery prevention.

5. Rate Limiting

IP and session-based request throttling.

6. Content Validation

Payload size limits and content type checking.

7. Security Headers

Automatic security header configuration.


Demo Application

Interactive Security Testing Interface

The demo app provides a hands-on interface to test all security protections with 15+ pre-configured attack vectors.

Running the Demo

git clone https://github.com/mindfiredigital/nextjs-fortress.git
cd examples/demoApp
pnpm install
pnpm dev

Open http://localhost:3000 to access the demo.

Demo Features

Visual Testing Interface

  • Attack Categories: Filter by Deserialization, Injection, Encoding, General
  • 15+ Attack Vectors: Real-world exploit payloads
  • Payload Inspection: View exact attack payloads
  • Real-time Results: Instant validation feedback
  • Test History: Track all tested attacks

Attack Vectors Included

Deserialization Attacks:

  • ✅ Prototype Pollution (CVE-2025-55182)
  • ✅ Constructor Injection
  • ✅ Deep Nesting Bypass

SQL Injection:

  • ✅ UNION-based injection
  • ✅ Boolean-based blind injection
  • ✅ Time-based blind injection

Cross-Site Scripting (XSS):

  • ✅ Script tag injection
  • ✅ Event handler exploitation
  • ✅ Iframe injection

Command Injection:

  • ✅ Shell command execution
  • ✅ Command substitution (backticks)
  • ✅ Pipe commands

Encoding Bypasses:

  • ✅ UTF-16LE encoding (Ghost Mode)

General:

  • ✅ Rate limit stress testing
  • ✅ Valid request validation

Demo UI Components

// Live testing interface
<FortressDemo />

// Features:
- Category filtering (4 categories)
- Attack selection (15+ vectors)
- Payload inspection panel
- Test execution button
- Real-time result display
- Test history tracking
- Severity indicators
- Confidence scores

Demo Architecture

demoApp/
├── app/
│   ├── page.tsx              # Main demo page
│   └── api/test/route.ts     # Protected test endpoint
├── components/
│   └── fortress/
│       └── FortressDemo.tsx  # Interactive UI
├── lib/
│   ├── constants/
│   │   ├── attacks.ts        # Attack definitions
│   │   └── categories.ts     # Attack categories
│   ├── hooks/
│   │   └── useAttackTesting.ts  # Testing logic
│   ├── services/
│   │   └── attackService.ts  # Attack simulation
│   └── utils/
│       └── attackHelpers.ts  # Helper functions
└── types/
    └── index.ts              # TypeScript definitions

Testing Flow

  1. Select Category → Filter attacks by type
  2. Choose Attack → Select from 15+ vectors
  3. Inspect Payload → Review the malicious payload
  4. Test Firewall → Click to simulate the attack
  5. View Results → See if blocked and why
  6. Check History → Review all previous tests

Example Attack Test

// User selects: Prototype Pollution
{
  "__proto__": { "isAdmin": true },
  "constructor": { "prototype": { "hacked": true } }
}

// Result:
{
  blocked: true,
  message: "🛡️ Blocked by Fortress",
  details: {
    rule: "dangerous_key",
    pattern: "__proto__",
    confidence: 100%,
    timestamp: "2025-12-23T10:30:00Z"
  },
  responseStatus: 403
}

Complete Attack Protection Matrix

Attack Type Severity Protected Demo Included
Prototype Pollution (CVE-2025-55182) 🔴 Critical
Constructor Injection 🔴 Critical
Deep Nesting 🟠 High
SQL UNION Injection 🔴 Critical
SQL Boolean Injection 🔴 Critical
SQL Time-based Injection 🟠 High
XSS Script Tag 🟠 High
XSS Event Handler 🟠 High
XSS Iframe 🟠 High
Command Injection (Shell) 🔴 Critical
Command Injection (Backticks) 🔴 Critical
Code Injection (eval) 🔴 Critical
UTF-16LE Bypass (Ghost Mode) 🔴 Critical
Rate Limit Abuse 🟡 Medium
CSRF Attacks 🟠 High -

Configuration Reference

Module Configuration

Deserialization

deserialization: {
  enabled: true,
  native: false,              // Use native addon (future)
  maxDepth: 10,              // Max object nesting
  detectCircular: true,       // Detect circular refs
  blockList?: string[],       // Custom blocked keys
  dangerousPatterns?: string[] // Custom patterns
}

Injection

injection: {
  enabled: true,
  checks: ['sql', 'command', 'xss', 'codeInjection'],
  customPatterns?: RegExp[]   // Additional patterns
}

Encoding

encoding: {
  enabled: true,
  blockNonUTF8: true,         // Block non-UTF-8
  detectBOM: true,            // Detect byte order marks
  allowedEncodings?: string[] // Encoding whitelist
}

CSRF

csrf: {
  enabled: true,
  tokenSecret: string,        // Token generation secret
  cookieName: '_csrf',
  headerName: 'X-CSRF-Token',
  tokenLength: 32,
  expiryMs: 86400000         // 24 hours
}

Rate Limiting

rateLimit: {
  enabled: true,
  byIP: { requests: 100, window: 60000 },
  bySession: { requests: 50, window: 60000 },
  endpoints?: {              // Per-endpoint limits
    '/api/auth': { requests: 5, window: 300000 }
  },
  whitelist?: string[],      // Whitelisted IPs
  backoff?: {                // Exponential backoff
    enabled: true,
    multiplier: 2,
    maxDelay: 3600000
  }
}

Testing

Running Package Tests

cd packages/nextjs-fortress
pnpm test                 # Run all tests

Running Demo Tests

cd examples/demoApp
pnpm dev             # Start demo
# Visit http://localhost:3000
# Test attacks interactively

Example Test

import { createDeserializationValidator } from 'nextjs-fortress'

describe('CVE-2025-55182 Protection', () => {
  const validator = createDeserializationValidator({
    enabled: true,
    maxDepth: 10,
    detectCircular: true,
  })

  test('blocks prototype pollution', () => {
    const payload = JSON.parse(
      '{"__proto__": {"isAdmin": true}}'
    )
    const result = validator.validate(payload)
    
    expect(result.valid).toBe(false)
    expect(result.severity).toBe('critical')
  })
})

API Reference

Core Functions

// Middleware
createFortressMiddleware(config: FortressConfig)

// API Route Protection
createWithFortress(config: FortressConfig)
withFortress(handler, options?)

// Server Action Protection
createSecureServerAction(config: FortressConfig)
secureServerAction(action, options?)

// Validators
createDeserializationValidator(config)
createInjectionValidator(config)
createEncodingValidator(config)
createCSRFValidator(config)
createAdvancedRateLimiter(config, storage?)

// Utilities
createSecurityEvent(params)
FortressLogger(config)

Exported Types

export type {
  FortressConfig,
  SecurityEvent,
  ValidationResult,
  SecuritySeverity,
  SecurityThreatType,
  SecurityAction,
  DeserializationConfig,
  InjectionConfig,
  EncodingConfig,
  CSRFConfig,
  RateLimitConfig,
  ContentConfig,
  SecurityHeadersConfig,
  LoggingConfig,
  SecureRouteOptions,
  SecureActionOptions,
}

Development

Setup Development Environment

# Clone repository
git clone https://github.com/mindfiredigital/nextjs-fortress.git
cd nextjs-fortress

# Install dependencies
pnpm install

# Build package
cd packages/nextjs-fortress
pnpm build

# Run tests
pnpm test

# Start demo
cd ../../examples/demoApp
pnpm run dev

Support & Resources


Acknowledgments

Built to protect against:

  • CVE-2025-55182 (Prototype Pollution in Next.js)
  • OWASP Top 10 vulnerabilities
  • Ghost Mode encoding bypass
  • Modern web attack vectors

Special thanks to the security research community for vulnerability disclosures and best practices.


Learn More


Made with ❤️ by the Mindfire Digital LLP

Keep your Next.js apps secure 🛡️