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.
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
npm i @mindfiredigital/nextjs-fortressThe fastest way to add fortress to your existing Next.js project:
npx fortress initThis automatically:
- ✅ Creates
fortress.config.tswith production-ready defaults - ✅ Sets up
middleware.tswith security validation - ✅ Generates
.env.examplewith 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).
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,
})
},
}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).*)'],
}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)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).*)'],
}Blocks prototype pollution and constructor injection attacks.
// ❌ Automatically Blocked
{
"__proto__": { "isAdmin": true },
"constructor": { "prototype": { "hacked": true } }
}
// ✅ Allowed
{
"username": "john_doe",
"email": "john@example.com"
}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') |
✅ |
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-8Token-based cross-site request forgery prevention.
IP and session-based request throttling.
Payload size limits and content type checking.
Automatic security header configuration.
The demo app provides a hands-on interface to test all security protections with 15+ pre-configured attack vectors.
git clone https://github.com/mindfiredigital/nextjs-fortress.git
cd examples/demoApp
pnpm install
pnpm devOpen http://localhost:3000 to access the demo.
- 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
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
// 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 scoresdemoApp/
├── 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
- Select Category → Filter attacks by type
- Choose Attack → Select from 15+ vectors
- Inspect Payload → Review the malicious payload
- Test Firewall → Click to simulate the attack
- View Results → See if blocked and why
- Check History → Review all previous tests
// 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
}| 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 | ✅ | - |
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: {
enabled: true,
checks: ['sql', 'command', 'xss', 'codeInjection'],
customPatterns?: RegExp[] // Additional patterns
}encoding: {
enabled: true,
blockNonUTF8: true, // Block non-UTF-8
detectBOM: true, // Detect byte order marks
allowedEncodings?: string[] // Encoding whitelist
}csrf: {
enabled: true,
tokenSecret: string, // Token generation secret
cookieName: '_csrf',
headerName: 'X-CSRF-Token',
tokenLength: 32,
expiryMs: 86400000 // 24 hours
}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
}
}cd packages/nextjs-fortress
pnpm test # Run all testscd examples/demoApp
pnpm dev # Start demo
# Visit http://localhost:3000
# Test attacks interactivelyimport { 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')
})
})// 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)export type {
FortressConfig,
SecurityEvent,
ValidationResult,
SecuritySeverity,
SecurityThreatType,
SecurityAction,
DeserializationConfig,
InjectionConfig,
EncodingConfig,
CSRFConfig,
RateLimitConfig,
ContentConfig,
SecurityHeadersConfig,
LoggingConfig,
SecureRouteOptions,
SecureActionOptions,
}# 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- Documentation: Full Docs
- Issues: GitHub Issues
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.
Made with ❤️ by the Mindfire Digital LLP
Keep your Next.js apps secure 🛡️
