@kya-os/agentshield-nextjs
Version:
Next.js middleware for AgentShield AI agent detection
68 lines (64 loc) • 2.34 kB
text/typescript
import { NextRequest, NextResponse } from 'next/server';
/**
* Edge Runtime Compatible WASM Middleware for AgentShield
*
* This module provides WASM-based AI agent detection with 95-100% confidence
* in Next.js Edge Runtime and Vercel Edge Functions.
*
* IMPORTANT: WebAssembly.instantiate(module) IS supported in Edge Runtime
* when using a pre-compiled module imported with ?module suffix.
*/
interface EdgeWasmDetectionResult {
isAgent: boolean;
confidence: number;
agent?: string;
verificationMethod: 'signature' | 'pattern' | 'wasm';
riskLevel: 'low' | 'medium' | 'high';
timestamp: string;
reasons?: string[];
}
interface EdgeAgentShieldConfig {
onAgentDetected?: (result: EdgeWasmDetectionResult) => void | Promise<void>;
blockOnHighConfidence?: boolean;
/**
* Confidence threshold for blocking (0.0-1.0 scale).
* Detection confidence above this threshold will be blocked if blockOnHighConfidence is true.
* @default 0.9 (90% confidence)
* @example
* confidenceThreshold: 0.9 // Block if >= 90% confident
* confidenceThreshold: 0.7 // Block if >= 70% confident
*/
confidenceThreshold?: number;
skipPaths?: string[];
blockedResponse?: {
status?: number;
message?: string;
headers?: Record<string, string>;
};
}
/**
* Initialize WASM module with proper imports for Edge Runtime
*/
declare function initializeEdgeWasm(wasmModule: WebAssembly.Module): Promise<void>;
/**
* Create Edge Runtime compatible WASM middleware
*
* @example
* ```typescript
* // middleware.ts
* import wasmModule from '@kya-os/agentshield/wasm?module';
* import { createEdgeWasmMiddleware } from '@kya-os/agentshield-nextjs/edge-wasm-middleware';
*
* export const middleware = createEdgeWasmMiddleware({
* wasmModule,
* onAgentDetected: (result) => {
* // Note: result.confidence is 0.0-1.0 scale
* console.log(`AI Agent: ${result.agent} (${Math.round(result.confidence * 100)}% confidence)`);
* }
* });
* ```
*/
declare function createEdgeWasmMiddleware(config: EdgeAgentShieldConfig & {
wasmModule: WebAssembly.Module;
}): (request: NextRequest) => Promise<NextResponse<unknown>>;
export { type EdgeAgentShieldConfig, type EdgeWasmDetectionResult, createEdgeWasmMiddleware, initializeEdgeWasm };