@kya-os/agentshield-nextjs 0.1.7

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.
package/README.md ADDED
@@ -0,0 +1,392 @@
1
+ # @kya-os/agentshield-nextjs
2
+
3
+ Next.js middleware and React hooks for AgentShield AI agent detection and protection.
4
+
5
+ ## Features
6
+
7
+ - 🚀 **Next.js Middleware**: Edge-compatible middleware for all routes
8
+ - ⚛️ **React Hooks**: Client-side detection and monitoring
9
+ - 🎯 **Flexible Actions**: Block, redirect, rewrite, or log detected agents
10
+ - 🛡️ **Edge Runtime**: Optimized for Vercel Edge Functions
11
+ - 📊 **Built-in Analytics**: Track detection patterns and statistics
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @kya-os/agentshield-nextjs
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ### Middleware Setup
22
+
23
+ Create `middleware.js` (or `middleware.ts`) in your project root:
24
+
25
+ ```javascript
26
+ import { agentShield } from '@kya-os/agentshield-nextjs';
27
+
28
+ export default agentShield({
29
+ onAgentDetected: 'block',
30
+ confidenceThreshold: 0.8,
31
+ });
32
+
33
+ export const config = {
34
+ matcher: [
35
+ '/((?!api|_next/static|_next/image|favicon.ico).*)',
36
+ ],
37
+ };
38
+ ```
39
+
40
+ ### React Hooks
41
+
42
+ ```javascript
43
+ 'use client';
44
+
45
+ import { useAgentDetection } from '@kya-os/agentshield-nextjs';
46
+
47
+ export default function SecurityMonitor() {
48
+ const { detect, isDetecting, lastResult } = useAgentDetection({
49
+ confidenceThreshold: 0.7,
50
+ });
51
+
52
+ const handleCheck = async () => {
53
+ const result = await detect();
54
+ if (result.isAgent) {
55
+ alert('Agent detected!');
56
+ }
57
+ };
58
+
59
+ return (
60
+ <div>
61
+ <button onClick={handleCheck} disabled={isDetecting}>
62
+ {isDetecting ? 'Checking...' : 'Check for Agents'}
63
+ </button>
64
+
65
+ {lastResult && (
66
+ <div>
67
+ <p>Is Agent: {lastResult.isAgent ? 'Yes' : 'No'}</p>
68
+ <p>Confidence: {(lastResult.confidence * 100).toFixed(1)}%</p>
69
+ </div>
70
+ )}
71
+ </div>
72
+ );
73
+ }
74
+ ```
75
+
76
+ ## Middleware Configuration
77
+
78
+ ```javascript
79
+ import { agentShield } from '@kya-os/agentshield-nextjs';
80
+
81
+ export default agentShield({
82
+ // Core detection options
83
+ confidenceThreshold: 0.7,
84
+ enablePatternMatching: true,
85
+ enableBehaviorAnalysis: true,
86
+
87
+ // Action when agent is detected
88
+ onAgentDetected: 'block', // 'block' | 'redirect' | 'rewrite' | 'allow' | 'log'
89
+
90
+ // Skip detection for paths
91
+ skipPaths: ['/api/webhooks', /^\/admin/],
92
+
93
+ // Custom responses
94
+ blockedResponse: {
95
+ status: 403,
96
+ message: 'Access denied',
97
+ },
98
+ redirectUrl: '/blocked',
99
+ rewriteUrl: '/blocked',
100
+
101
+ // Custom handler
102
+ onDetection: async (request, result) => {
103
+ console.log('Agent detected:', result);
104
+ // Return custom NextResponse or void
105
+ },
106
+ });
107
+ ```
108
+
109
+ ## Actions
110
+
111
+ ### Block Agents
112
+
113
+ ```javascript
114
+ export default agentShield({
115
+ onAgentDetected: 'block',
116
+ blockedResponse: {
117
+ status: 403,
118
+ message: 'Automated access not allowed',
119
+ headers: {
120
+ 'Content-Type': 'application/json',
121
+ 'X-Robots-Tag': 'noindex',
122
+ },
123
+ },
124
+ });
125
+ ```
126
+
127
+ ### Redirect Agents
128
+
129
+ ```javascript
130
+ export default agentShield({
131
+ onAgentDetected: 'redirect',
132
+ redirectUrl: '/blocked',
133
+ confidenceThreshold: 0.8,
134
+ });
135
+ ```
136
+
137
+ ### Rewrite Requests
138
+
139
+ ```javascript
140
+ export default agentShield({
141
+ onAgentDetected: 'rewrite',
142
+ rewriteUrl: '/bot-content',
143
+ confidenceThreshold: 0.6,
144
+ });
145
+ ```
146
+
147
+ ### Custom Logic
148
+
149
+ ```javascript
150
+ export default agentShield({
151
+ onDetection: async (request, result) => {
152
+ if (result.confidence > 0.9) {
153
+ // High confidence - block
154
+ return NextResponse.json(
155
+ { error: 'Blocked' },
156
+ { status: 403 }
157
+ );
158
+ } else if (result.confidence > 0.5) {
159
+ // Medium confidence - redirect to captcha
160
+ return NextResponse.redirect(
161
+ new URL('/verify', request.url)
162
+ );
163
+ }
164
+ // Low confidence - continue
165
+ },
166
+ });
167
+ ```
168
+
169
+ ## React Hooks
170
+
171
+ ### useAgentDetection
172
+
173
+ Client-side agent detection:
174
+
175
+ ```javascript
176
+ import { useAgentDetection } from '@kya-os/agentshield-nextjs';
177
+
178
+ function SecurityComponent() {
179
+ const { detect, isDetecting, lastResult, detector } = useAgentDetection({
180
+ confidenceThreshold: 0.7,
181
+ });
182
+
183
+ useEffect(() => {
184
+ // Auto-detect on component mount
185
+ detect();
186
+ }, [detect]);
187
+
188
+ return (
189
+ <div>
190
+ {lastResult?.isAgent && (
191
+ <div className="alert">
192
+ Agent detected with {lastResult.confidence} confidence
193
+ </div>
194
+ )}
195
+ </div>
196
+ );
197
+ }
198
+ ```
199
+
200
+ ### useDetectionMonitor
201
+
202
+ Monitor and track detection events:
203
+
204
+ ```javascript
205
+ import { useDetectionMonitor } from '@kya-os/agentshield-nextjs';
206
+
207
+ function AnalyticsDashboard() {
208
+ const { detectionHistory, getStats, clearHistory } = useDetectionMonitor(
209
+ (context) => {
210
+ // Handle each detection
211
+ console.log('Detection event:', context);
212
+ }
213
+ );
214
+
215
+ const stats = getStats();
216
+
217
+ return (
218
+ <div>
219
+ <h2>Detection Statistics</h2>
220
+ <p>Total Requests: {stats.total}</p>
221
+ <p>Agents Detected: {stats.detected}</p>
222
+ <p>Detection Rate: {(stats.detectionRate * 100).toFixed(1)}%</p>
223
+ <p>Average Confidence: {(stats.avgConfidence * 100).toFixed(1)}%</p>
224
+
225
+ <button onClick={clearHistory}>Clear History</button>
226
+ </div>
227
+ );
228
+ }
229
+ ```
230
+
231
+ ## API Routes Integration
232
+
233
+ Protect API routes with server-side detection:
234
+
235
+ ```javascript
236
+ // pages/api/protected.js or app/api/protected/route.js
237
+ import { AgentDetector } from '@kya-os/agentshield';
238
+
239
+ const detector = new AgentDetector();
240
+
241
+ export async function GET(request) {
242
+ const context = {
243
+ userAgent: request.headers.get('user-agent'),
244
+ ip: request.ip,
245
+ headers: Object.fromEntries(request.headers.entries()),
246
+ };
247
+
248
+ const result = await detector.analyze(context);
249
+
250
+ if (result.isAgent && result.confidence > 0.7) {
251
+ return NextResponse.json(
252
+ { error: 'Automated access detected' },
253
+ { status: 403 }
254
+ );
255
+ }
256
+
257
+ return NextResponse.json({ data: 'Protected content' });
258
+ }
259
+ ```
260
+
261
+ ## Advanced Usage
262
+
263
+ ### Path-Specific Configuration
264
+
265
+ ```javascript
266
+ import { NextRequest, NextResponse } from 'next/server';
267
+ import { AgentDetector } from '@kya-os/agentshield';
268
+
269
+ const detector = new AgentDetector();
270
+
271
+ export async function middleware(request: NextRequest) {
272
+ const { pathname } = request.nextUrl;
273
+
274
+ // Different thresholds for different paths
275
+ let threshold = 0.7;
276
+ if (pathname.startsWith('/api/')) {
277
+ threshold = 0.5; // More sensitive for API
278
+ } else if (pathname.startsWith('/admin/')) {
279
+ threshold = 0.9; // Less sensitive for admin (humans expected)
280
+ }
281
+
282
+ const context = {
283
+ userAgent: request.headers.get('user-agent') ?? undefined,
284
+ ip: request.ip,
285
+ headers: Object.fromEntries(request.headers.entries()),
286
+ url: request.url,
287
+ };
288
+
289
+ const result = await detector.analyze(context);
290
+
291
+ if (result.isAgent && result.confidence >= threshold) {
292
+ return NextResponse.json(
293
+ { error: 'Access denied' },
294
+ { status: 403 }
295
+ );
296
+ }
297
+
298
+ return NextResponse.next();
299
+ }
300
+ ```
301
+
302
+ ### Server Components
303
+
304
+ Use detection results in Server Components:
305
+
306
+ ```javascript
307
+ // app/dashboard/page.tsx
308
+ import { headers } from 'next/headers';
309
+ import { AgentDetector } from '@kya-os/agentshield';
310
+
311
+ export default async function Dashboard() {
312
+ const headersList = headers();
313
+ const detector = new AgentDetector();
314
+
315
+ const result = await detector.analyze({
316
+ userAgent: headersList.get('user-agent') ?? undefined,
317
+ headers: Object.fromEntries(headersList.entries()),
318
+ });
319
+
320
+ if (result.isAgent) {
321
+ return <div>Automated access detected</div>;
322
+ }
323
+
324
+ return <div>Welcome to the dashboard!</div>;
325
+ }
326
+ ```
327
+
328
+ ## TypeScript Support
329
+
330
+ Full TypeScript support with proper types:
331
+
332
+ ```typescript
333
+ import { NextRequest } from 'next/server';
334
+ import { agentShield, NextJSMiddlewareConfig } from '@kya-os/agentshield-nextjs';
335
+
336
+ const config: NextJSMiddlewareConfig = {
337
+ onAgentDetected: 'block',
338
+ confidenceThreshold: 0.8,
339
+ onDetection: async (request: NextRequest, result) => {
340
+ // Fully typed parameters
341
+ console.log(result.confidence);
342
+ },
343
+ };
344
+
345
+ export default agentShield(config);
346
+ ```
347
+
348
+ ## Examples
349
+
350
+ ### E-commerce Protection
351
+
352
+ ```javascript
353
+ // Protect product pages from scrapers
354
+ export default agentShield({
355
+ onAgentDetected: 'redirect',
356
+ redirectUrl: '/captcha',
357
+ confidenceThreshold: 0.6,
358
+ skipPaths: ['/api/webhooks', '/health'],
359
+ });
360
+
361
+ export const config = {
362
+ matcher: ['/products/:path*', '/search/:path*'],
363
+ };
364
+ ```
365
+
366
+ ### Content Publishing
367
+
368
+ ```javascript
369
+ // Allow search engines, block other bots
370
+ export default agentShield({
371
+ onDetection: async (request, result) => {
372
+ const userAgent = request.headers.get('user-agent') || '';
373
+
374
+ // Allow known search engines
375
+ if (/googlebot|bingbot|slurp/i.test(userAgent)) {
376
+ return; // Continue
377
+ }
378
+
379
+ // Block other agents
380
+ if (result.isAgent && result.confidence > 0.5) {
381
+ return NextResponse.json(
382
+ { error: 'Bot access restricted' },
383
+ { status: 403 }
384
+ );
385
+ }
386
+ },
387
+ });
388
+ ```
389
+
390
+ ## License
391
+
392
+ MIT OR Apache-2.0
@@ -0,0 +1,87 @@
1
+ import { D as DetectionContext } from './middleware-OvcbG6s2.mjs';
2
+ export { N as NextJSMiddlewareConfig, a as agentShield, c as createAgentShieldMiddleware } from './middleware-OvcbG6s2.mjs';
3
+ import { AgentShieldConfig, AgentDetector, DetectionResult } from '@kya-os/agentshield';
4
+ import 'next/server';
5
+
6
+ /**
7
+ * React hooks for AgentShield in Next.js applications
8
+ */
9
+
10
+ /**
11
+ * Hook for client-side agent detection
12
+ */
13
+ declare function useAgentDetection(config?: Partial<AgentShieldConfig>): {
14
+ detect: () => Promise<{
15
+ isAgent: boolean;
16
+ confidence: number;
17
+ reasons: string[];
18
+ timestamp: Date;
19
+ confidenceLevel?: "low" | "medium" | "high" | undefined;
20
+ metadata?: Record<string, unknown> | undefined;
21
+ detectedAgent?: {
22
+ type: string;
23
+ name: string;
24
+ } | undefined;
25
+ verificationMethod?: string | undefined;
26
+ riskLevel?: string | undefined;
27
+ forgeabilityRisk?: "low" | "medium" | "high" | undefined;
28
+ }>;
29
+ isDetecting: boolean;
30
+ lastResult: {
31
+ isAgent: boolean;
32
+ confidence: number;
33
+ reasons: string[];
34
+ timestamp: Date;
35
+ confidenceLevel?: "low" | "medium" | "high" | undefined;
36
+ metadata?: Record<string, unknown> | undefined;
37
+ detectedAgent?: {
38
+ type: string;
39
+ name: string;
40
+ } | undefined;
41
+ verificationMethod?: string | undefined;
42
+ riskLevel?: string | undefined;
43
+ forgeabilityRisk?: "low" | "medium" | "high" | undefined;
44
+ } | null;
45
+ detector: AgentDetector;
46
+ };
47
+ /**
48
+ * Hook for monitoring detection results
49
+ */
50
+ declare function useDetectionMonitor(onDetection?: (context: DetectionContext) => void): {
51
+ detectionHistory: {
52
+ isAgent: boolean;
53
+ confidence: number;
54
+ reasons: string[];
55
+ timestamp: Date;
56
+ confidenceLevel?: "low" | "medium" | "high" | undefined;
57
+ metadata?: Record<string, unknown> | undefined;
58
+ detectedAgent?: {
59
+ type: string;
60
+ name: string;
61
+ } | undefined;
62
+ verificationMethod?: string | undefined;
63
+ riskLevel?: string | undefined;
64
+ forgeabilityRisk?: "low" | "medium" | "high" | undefined;
65
+ }[];
66
+ addDetection: (result: DetectionResult, request?: any) => void;
67
+ clearHistory: () => void;
68
+ getStats: () => {
69
+ total: number;
70
+ detected: number;
71
+ avgConfidence: number;
72
+ detectionRate: number;
73
+ };
74
+ };
75
+
76
+ /**
77
+ * @fileoverview AgentShield Next.js Integration
78
+ * @version 0.1.0
79
+ * @license MIT OR Apache-2.0
80
+ */
81
+
82
+ /**
83
+ * Library version
84
+ */
85
+ declare const VERSION = "0.1.0";
86
+
87
+ export { DetectionContext, VERSION, useAgentDetection, useDetectionMonitor };
@@ -0,0 +1,87 @@
1
+ import { D as DetectionContext } from './middleware-OvcbG6s2.js';
2
+ export { N as NextJSMiddlewareConfig, a as agentShield, c as createAgentShieldMiddleware } from './middleware-OvcbG6s2.js';
3
+ import { AgentShieldConfig, AgentDetector, DetectionResult } from '@kya-os/agentshield';
4
+ import 'next/server';
5
+
6
+ /**
7
+ * React hooks for AgentShield in Next.js applications
8
+ */
9
+
10
+ /**
11
+ * Hook for client-side agent detection
12
+ */
13
+ declare function useAgentDetection(config?: Partial<AgentShieldConfig>): {
14
+ detect: () => Promise<{
15
+ isAgent: boolean;
16
+ confidence: number;
17
+ reasons: string[];
18
+ timestamp: Date;
19
+ confidenceLevel?: "low" | "medium" | "high" | undefined;
20
+ metadata?: Record<string, unknown> | undefined;
21
+ detectedAgent?: {
22
+ type: string;
23
+ name: string;
24
+ } | undefined;
25
+ verificationMethod?: string | undefined;
26
+ riskLevel?: string | undefined;
27
+ forgeabilityRisk?: "low" | "medium" | "high" | undefined;
28
+ }>;
29
+ isDetecting: boolean;
30
+ lastResult: {
31
+ isAgent: boolean;
32
+ confidence: number;
33
+ reasons: string[];
34
+ timestamp: Date;
35
+ confidenceLevel?: "low" | "medium" | "high" | undefined;
36
+ metadata?: Record<string, unknown> | undefined;
37
+ detectedAgent?: {
38
+ type: string;
39
+ name: string;
40
+ } | undefined;
41
+ verificationMethod?: string | undefined;
42
+ riskLevel?: string | undefined;
43
+ forgeabilityRisk?: "low" | "medium" | "high" | undefined;
44
+ } | null;
45
+ detector: AgentDetector;
46
+ };
47
+ /**
48
+ * Hook for monitoring detection results
49
+ */
50
+ declare function useDetectionMonitor(onDetection?: (context: DetectionContext) => void): {
51
+ detectionHistory: {
52
+ isAgent: boolean;
53
+ confidence: number;
54
+ reasons: string[];
55
+ timestamp: Date;
56
+ confidenceLevel?: "low" | "medium" | "high" | undefined;
57
+ metadata?: Record<string, unknown> | undefined;
58
+ detectedAgent?: {
59
+ type: string;
60
+ name: string;
61
+ } | undefined;
62
+ verificationMethod?: string | undefined;
63
+ riskLevel?: string | undefined;
64
+ forgeabilityRisk?: "low" | "medium" | "high" | undefined;
65
+ }[];
66
+ addDetection: (result: DetectionResult, request?: any) => void;
67
+ clearHistory: () => void;
68
+ getStats: () => {
69
+ total: number;
70
+ detected: number;
71
+ avgConfidence: number;
72
+ detectionRate: number;
73
+ };
74
+ };
75
+
76
+ /**
77
+ * @fileoverview AgentShield Next.js Integration
78
+ * @version 0.1.0
79
+ * @license MIT OR Apache-2.0
80
+ */
81
+
82
+ /**
83
+ * Library version
84
+ */
85
+ declare const VERSION = "0.1.0";
86
+
87
+ export { DetectionContext, VERSION, useAgentDetection, useDetectionMonitor };