UNPKG

@kya-os/agentshield-nextjs

Version:

Next.js middleware for AgentShield AI agent detection

151 lines (130 loc) 4.72 kB
/** * AgentShield Middleware Template with WASM (95-100% Confidence) * * This template provides full cryptographic verification for AI agents * following Next.js official documentation for WebAssembly in Edge Runtime. * * Installation: * 1. Copy this file to your project root as `middleware.ts` * 2. Install packages: npm install @kya-os/agentshield @kya-os/agentshield-nextjs * 3. Deploy to Vercel for Edge Runtime support */ import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; // CRITICAL: Import WASM module with ?module suffix for Edge Runtime // This MUST be at the top of the file, before any other AgentShield imports import wasmModule from '@kya-os/agentshield/wasm?module'; // Now import the middleware creator import { createWasmAgentShieldMiddleware, instantiateWasm } from '@kya-os/agentshield-nextjs/wasm-middleware'; // Initialize WASM module once at startup let wasmInstancePromise: Promise<WebAssembly.Instance> | null = null; async function getWasmInstance() { if (!wasmInstancePromise) { wasmInstancePromise = instantiateWasm(wasmModule); } return wasmInstancePromise; } export async function middleware(request: NextRequest) { try { // Get or create WASM instance const wasmInstance = await getWasmInstance(); // Create middleware with WASM support const agentShieldMiddleware = createWasmAgentShieldMiddleware({ wasmInstance, // Skip authentication and static assets skipPaths: ['/api/auth', '/_next', '/favicon.ico', '/public'], // What to do when agent is detected onAgentDetected: async (result) => { // With WASM: 95-100% confidence for cryptographically verified agents console.log(`🤖 AI Agent detected:`, { agent: result.agent, confidence: `${Math.round(result.confidence * 100)}%`, verification: result.verificationMethod, // 'signature' with WASM, 'pattern' without risk: result.riskLevel, timestamp: result.timestamp }); // You can add custom logic here: // - Log to analytics // - Send alerts // - Apply rate limiting // - etc. }, // Set to true to block AI agents blockOnHighConfidence: false, // Change to true to block agents // Minimum confidence to trigger blocking (0.8 = 80%) confidenceThreshold: 0.8, // Custom response when blocking blockedResponse: { status: 403, message: 'AI agent access restricted', headers: { 'Content-Type': 'application/json', 'X-Blocked-Reason': 'ai-agent-detected' } } }); // Run AgentShield detection const response = await agentShieldMiddleware(request); // Add security headers to all responses response.headers.set('X-Frame-Options', 'DENY'); response.headers.set('X-Content-Type-Options', 'nosniff'); response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin'); return response; } catch (error) { // If WASM fails to load, fall back to pattern detection (85% confidence) console.warn('⚠️ WASM initialization failed, using pattern detection:', error); // You could use the regular middleware here as fallback // For now, just continue return NextResponse.next(); } } // Configure which paths the middleware runs on export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) * - public folder */ { source: '/((?!_next/static|_next/image|favicon.ico|public).*)', missing: [ { type: 'header', key: 'next-router-prefetch' }, { type: 'header', key: 'purpose', value: 'prefetch' }, ], }, ], }; /** * TypeScript Support * * Add this to a `types/wasm.d.ts` file in your project: * * declare module '@kya-os/agentshield/wasm?module' { * const value: WebAssembly.Module; * export default value; * } */ /** * What You'll See in Logs: * * With WASM (95-100% confidence): * 🤖 AI Agent detected: { * agent: 'ChatGPT-User', * confidence: '100%', * verification: 'signature', // Cryptographically verified! * risk: 'high', * timestamp: '2024-01-01T00:00:00.000Z' * } * * Without WASM (85% confidence): * 🤖 AI Agent detected: { * agent: 'ChatGPT-User', * confidence: '85%', * verification: 'pattern', // Pattern matching only * risk: 'medium', * timestamp: '2024-01-01T00:00:00.000Z' * } */