@kya-os/agentshield-nextjs 0.1.21 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,151 @@
1
+ /**
2
+ * AgentShield Middleware Template with WASM (95-100% Confidence)
3
+ *
4
+ * This template provides full cryptographic verification for AI agents
5
+ * following Next.js official documentation for WebAssembly in Edge Runtime.
6
+ *
7
+ * Installation:
8
+ * 1. Copy this file to your project root as `middleware.ts`
9
+ * 2. Install packages: npm install @kya-os/agentshield @kya-os/agentshield-nextjs
10
+ * 3. Deploy to Vercel for Edge Runtime support
11
+ */
12
+
13
+ import { NextResponse } from 'next/server';
14
+ import type { NextRequest } from 'next/server';
15
+
16
+ // CRITICAL: Import WASM module with ?module suffix for Edge Runtime
17
+ // This MUST be at the top of the file, before any other AgentShield imports
18
+ import wasmModule from '@kya-os/agentshield/wasm?module';
19
+
20
+ // Now import the middleware creator
21
+ import { createWasmAgentShieldMiddleware, instantiateWasm } from '@kya-os/agentshield-nextjs/wasm-middleware';
22
+
23
+ // Initialize WASM module once at startup
24
+ let wasmInstancePromise: Promise<WebAssembly.Instance> | null = null;
25
+
26
+ async function getWasmInstance() {
27
+ if (!wasmInstancePromise) {
28
+ wasmInstancePromise = instantiateWasm(wasmModule);
29
+ }
30
+ return wasmInstancePromise;
31
+ }
32
+
33
+ export async function middleware(request: NextRequest) {
34
+ try {
35
+ // Get or create WASM instance
36
+ const wasmInstance = await getWasmInstance();
37
+
38
+ // Create middleware with WASM support
39
+ const agentShieldMiddleware = createWasmAgentShieldMiddleware({
40
+ wasmInstance,
41
+
42
+ // Skip authentication and static assets
43
+ skipPaths: ['/api/auth', '/_next', '/favicon.ico', '/public'],
44
+
45
+ // What to do when agent is detected
46
+ onAgentDetected: async (result) => {
47
+ // With WASM: 95-100% confidence for cryptographically verified agents
48
+ console.log(`🤖 AI Agent detected:`, {
49
+ agent: result.agent,
50
+ confidence: `${Math.round(result.confidence * 100)}%`,
51
+ verification: result.verificationMethod, // 'signature' with WASM, 'pattern' without
52
+ risk: result.riskLevel,
53
+ timestamp: result.timestamp
54
+ });
55
+
56
+ // You can add custom logic here:
57
+ // - Log to analytics
58
+ // - Send alerts
59
+ // - Apply rate limiting
60
+ // - etc.
61
+ },
62
+
63
+ // Set to true to block AI agents
64
+ blockOnHighConfidence: false, // Change to true to block agents
65
+
66
+ // Minimum confidence to trigger blocking (0.8 = 80%)
67
+ confidenceThreshold: 0.8,
68
+
69
+ // Custom response when blocking
70
+ blockedResponse: {
71
+ status: 403,
72
+ message: 'AI agent access restricted',
73
+ headers: {
74
+ 'Content-Type': 'application/json',
75
+ 'X-Blocked-Reason': 'ai-agent-detected'
76
+ }
77
+ }
78
+ });
79
+
80
+ // Run AgentShield detection
81
+ const response = await agentShieldMiddleware(request);
82
+
83
+ // Add security headers to all responses
84
+ response.headers.set('X-Frame-Options', 'DENY');
85
+ response.headers.set('X-Content-Type-Options', 'nosniff');
86
+ response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
87
+
88
+ return response;
89
+
90
+ } catch (error) {
91
+ // If WASM fails to load, fall back to pattern detection (85% confidence)
92
+ console.warn('⚠️ WASM initialization failed, using pattern detection:', error);
93
+
94
+ // You could use the regular middleware here as fallback
95
+ // For now, just continue
96
+ return NextResponse.next();
97
+ }
98
+ }
99
+
100
+ // Configure which paths the middleware runs on
101
+ export const config = {
102
+ matcher: [
103
+ /*
104
+ * Match all request paths except for the ones starting with:
105
+ * - _next/static (static files)
106
+ * - _next/image (image optimization files)
107
+ * - favicon.ico (favicon file)
108
+ * - public folder
109
+ */
110
+ {
111
+ source: '/((?!_next/static|_next/image|favicon.ico|public).*)',
112
+ missing: [
113
+ { type: 'header', key: 'next-router-prefetch' },
114
+ { type: 'header', key: 'purpose', value: 'prefetch' },
115
+ ],
116
+ },
117
+ ],
118
+ };
119
+
120
+ /**
121
+ * TypeScript Support
122
+ *
123
+ * Add this to a `types/wasm.d.ts` file in your project:
124
+ *
125
+ * declare module '@kya-os/agentshield/wasm?module' {
126
+ * const value: WebAssembly.Module;
127
+ * export default value;
128
+ * }
129
+ */
130
+
131
+ /**
132
+ * What You'll See in Logs:
133
+ *
134
+ * With WASM (95-100% confidence):
135
+ * 🤖 AI Agent detected: {
136
+ * agent: 'ChatGPT-User',
137
+ * confidence: '100%',
138
+ * verification: 'signature', // Cryptographically verified!
139
+ * risk: 'high',
140
+ * timestamp: '2024-01-01T00:00:00.000Z'
141
+ * }
142
+ *
143
+ * Without WASM (85% confidence):
144
+ * 🤖 AI Agent detected: {
145
+ * agent: 'ChatGPT-User',
146
+ * confidence: '85%',
147
+ * verification: 'pattern', // Pattern matching only
148
+ * risk: 'medium',
149
+ * timestamp: '2024-01-01T00:00:00.000Z'
150
+ * }
151
+ */