@kya-os/checkpoint-nextjs 1.2.0 → 1.7.1

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/EDGE_RUNTIME_WASM_SETUP.md +1 -1
  3. package/bin/setup-edge-wasm.js +1 -1
  4. package/dist/api-middleware.d.mts +9 -1
  5. package/dist/api-middleware.d.ts +9 -1
  6. package/dist/api-middleware.js +14 -4
  7. package/dist/api-middleware.mjs +15 -5
  8. package/dist/composed-policy.d.mts +115 -0
  9. package/dist/composed-policy.d.ts +115 -0
  10. package/dist/composed-policy.js +102 -0
  11. package/dist/composed-policy.mjs +96 -0
  12. package/dist/config-DAwIA4DB.d.mts +214 -0
  13. package/dist/config-DyU4l5er.d.ts +214 -0
  14. package/dist/create-middleware.js +0 -2
  15. package/dist/create-middleware.mjs +0 -2
  16. package/dist/edge-runtime-loader.js +3 -1
  17. package/dist/edge-runtime-loader.mjs +3 -1
  18. package/dist/edge-wasm-middleware.d.mts +6 -6
  19. package/dist/edge-wasm-middleware.d.ts +6 -6
  20. package/dist/index.d.mts +6 -14
  21. package/dist/index.d.ts +6 -14
  22. package/dist/index.js +191 -13
  23. package/dist/index.mjs +192 -14
  24. package/dist/middleware-edge.d.mts +7 -3
  25. package/dist/middleware-edge.d.ts +7 -3
  26. package/dist/middleware-edge.js +174 -4
  27. package/dist/middleware-edge.mjs +171 -4
  28. package/dist/middleware-node.d.mts +39 -116
  29. package/dist/middleware-node.d.ts +39 -116
  30. package/dist/middleware-node.js +181 -4
  31. package/dist/middleware-node.mjs +178 -5
  32. package/dist/middleware.d.mts +10 -1
  33. package/dist/middleware.d.ts +10 -1
  34. package/dist/middleware.js +6 -0
  35. package/dist/middleware.mjs +6 -1
  36. package/dist/nodejs-wasm-loader.d.mts +3 -4
  37. package/dist/nodejs-wasm-loader.d.ts +3 -4
  38. package/dist/nodejs-wasm-loader.js +1 -1
  39. package/dist/nodejs-wasm-loader.mjs +1 -1
  40. package/dist/wasm-setup.js +1 -1
  41. package/dist/wasm-setup.mjs +1 -1
  42. package/package.json +4 -9
  43. package/dist/.tsbuildinfo +0 -1
  44. package/dist/signature-verifier.d.mts +0 -33
  45. package/dist/signature-verifier.d.ts +0 -33
  46. package/dist/signature-verifier.js +0 -384
  47. package/dist/signature-verifier.mjs +0 -360
  48. package/dist/wasm-middleware.d.mts +0 -98
  49. package/dist/wasm-middleware.d.ts +0 -98
  50. package/dist/wasm-middleware.js +0 -125
  51. package/dist/wasm-middleware.mjs +0 -121
  52. package/templates/middleware-wasm-100.ts +0 -161
@@ -1,121 +0,0 @@
1
- import { NextResponse } from 'next/server';
2
- import { AgentDetector } from '@kya-os/checkpoint';
3
-
4
- // src/wasm-middleware.ts
5
-
6
- // src/local-detection-gate.ts
7
- function isDetectedAgentForLocalGate(result) {
8
- return result.isAgent === true;
9
- }
10
- function evaluateLocalDetectionGate(result, config) {
11
- if (!isDetectedAgentForLocalGate(result)) {
12
- return { action: "allow", shouldNotify: false };
13
- }
14
- if ((result.confidence ?? 0) >= config.confidenceThreshold) {
15
- return { action: config.defaultAction, shouldNotify: true };
16
- }
17
- return { action: "allow", shouldNotify: false };
18
- }
19
-
20
- // src/wasm-middleware.ts
21
- var _createWasmAgentShieldWarned = false;
22
- function warnCreateWasmAgentShieldDeprecated() {
23
- if (_createWasmAgentShieldWarned) return;
24
- _createWasmAgentShieldWarned = true;
25
- if (typeof process !== "undefined" && process.env?.NODE_ENV === "production") return;
26
- console.warn(
27
- "[Checkpoint] createWasmAgentShieldMiddleware is deprecated and will be removed in the next minor. It wraps the legacy AgentDetector class; Stage 1 detection now lives in the Rust kya-os-engine (PDM-1). Migrate to `withCheckpoint` from @kya-os/checkpoint-nextjs \u2014 engine-backed and runs envelope verification. See packages/checkpoint-nextjs/CHANGELOG.md for the recipe."
28
- );
29
- }
30
- function __resetCreateWasmAgentShieldWarningForTests() {
31
- _createWasmAgentShieldWarned = false;
32
- }
33
- function createWasmAgentShieldMiddleware(config) {
34
- warnCreateWasmAgentShieldDeprecated();
35
- const {
36
- onAgentDetected,
37
- blockOnHighConfidence = false,
38
- confidenceThreshold = 80,
39
- // Updated to 0-100 scale (was 0.8)
40
- skipPaths = [],
41
- blockedResponse = {
42
- status: 403,
43
- message: "Access denied: AI agent detected",
44
- headers: { "Content-Type": "application/json" }
45
- },
46
- wasmInstance
47
- } = config;
48
- return async function middleware(request) {
49
- const path = request.nextUrl.pathname;
50
- if (skipPaths.some((skip) => path.startsWith(skip))) {
51
- return NextResponse.next();
52
- }
53
- try {
54
- const detector = new AgentDetector();
55
- const hasWasm = !!wasmInstance;
56
- const metadata = {
57
- userAgent: request.headers.get("user-agent") || void 0,
58
- ipAddress: request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || void 0,
59
- headers: Object.fromEntries(request.headers.entries()),
60
- timestamp: /* @__PURE__ */ new Date()
61
- };
62
- const result = await detector.analyze(metadata);
63
- const enhancedResult = {
64
- isAgent: result.isAgent,
65
- isAiCrawler: result.isAiCrawler,
66
- confidence: hasWasm && result.confidence > 85 ? Math.min(result.confidence * 1.15, 100) : result.confidence,
67
- agent: result.detectedAgent?.name || void 0,
68
- verificationMethod: hasWasm && result.confidence > 85 ? "signature" : "pattern",
69
- // Updated to 0-100 scale
70
- riskLevel: result.confidence > 90 ? "high" : result.confidence > 70 ? "medium" : "low",
71
- // Updated to 0-100 scale (was 0.7)
72
- timestamp: result.timestamp instanceof Date ? result.timestamp.toISOString() : new Date(result.timestamp).toISOString()
73
- };
74
- const decision = evaluateLocalDetectionGate(enhancedResult, {
75
- confidenceThreshold,
76
- defaultAction: blockOnHighConfidence ? "block" : "allow"
77
- });
78
- if (onAgentDetected && isDetectedAgentForLocalGate(enhancedResult)) {
79
- await onAgentDetected(enhancedResult);
80
- }
81
- if (decision.action === "block") {
82
- return NextResponse.json(
83
- {
84
- error: blockedResponse.message,
85
- agent: enhancedResult.agent,
86
- confidence: Math.round(enhancedResult.confidence)
87
- },
88
- {
89
- status: blockedResponse.status || 403,
90
- headers: blockedResponse.headers || {}
91
- }
92
- );
93
- }
94
- const response = NextResponse.next();
95
- if (enhancedResult.isAgent) {
96
- response.headers.set("X-Agent-Detected", enhancedResult.agent || "unknown");
97
- response.headers.set(
98
- "X-Agent-Confidence",
99
- String(Math.round(enhancedResult.confidence * 100))
100
- );
101
- response.headers.set("X-Agent-Verification", enhancedResult.verificationMethod);
102
- }
103
- return response;
104
- } catch (error) {
105
- console.error("AgentShield middleware error:", error);
106
- return NextResponse.next();
107
- }
108
- };
109
- }
110
- async function instantiateWasm(wasmModule) {
111
- try {
112
- const instance = await WebAssembly.instantiate(wasmModule);
113
- console.log("\u2705 AgentShield: WASM module loaded for cryptographic verification");
114
- return instance;
115
- } catch (error) {
116
- console.warn("\u26A0\uFE0F AgentShield: Failed to instantiate WASM module", error);
117
- throw error;
118
- }
119
- }
120
-
121
- export { __resetCreateWasmAgentShieldWarningForTests, createWasmAgentShieldMiddleware, instantiateWasm };
@@ -1,161 +0,0 @@
1
- /**
2
- * Checkpoint Middleware Template — Legacy WASM Factory
3
- *
4
- * ⚠️ **DEPRECATED TEMPLATE (AgentDetector-Deletion-1):** this template
5
- * uses `createWasmAgentShieldMiddleware`, which is deprecated and
6
- * will be removed in the next minor. For new projects, use
7
- * `withCheckpoint` instead — it's engine-backed (PDM-1 #2560), runs
8
- * MCP-I envelope verification, and is the canonical Phase-D
9
- * replacement. See the `withCheckpoint` recipe in
10
- * `packages/checkpoint-nextjs/README.md`.
11
- *
12
- * This template stays in-tree for one release as a migration reference;
13
- * the deprecated factory still works (with a dev-only console.warn).
14
- *
15
- * Installation:
16
- * 1. Copy this file to your project root as `middleware.ts`
17
- * 2. Install packages: npm install @kya-os/checkpoint @kya-os/checkpoint-nextjs
18
- * 3. Deploy to Vercel for Edge Runtime support
19
- */
20
-
21
- import { NextResponse } from 'next/server';
22
- import type { NextRequest } from 'next/server';
23
-
24
- // CRITICAL: Import WASM module with ?module suffix for Edge Runtime
25
- // This MUST be at the top of the file, before any other AgentShield imports
26
- import wasmModule from '@kya-os/checkpoint/wasm?module';
27
-
28
- // Now import the middleware creator
29
- import {
30
- createWasmAgentShieldMiddleware,
31
- instantiateWasm,
32
- } from '@kya-os/checkpoint-nextjs/wasm-middleware';
33
-
34
- // Initialize WASM module once at startup
35
- let wasmInstancePromise: Promise<WebAssembly.Instance> | null = null;
36
-
37
- async function getWasmInstance() {
38
- if (!wasmInstancePromise) {
39
- wasmInstancePromise = instantiateWasm(wasmModule);
40
- }
41
- return wasmInstancePromise;
42
- }
43
-
44
- export async function middleware(request: NextRequest) {
45
- try {
46
- // Get or create WASM instance
47
- const wasmInstance = await getWasmInstance();
48
-
49
- // Create middleware with WASM support
50
- const agentShieldMiddleware = createWasmAgentShieldMiddleware({
51
- wasmInstance,
52
-
53
- // Skip authentication and static assets
54
- skipPaths: ['/api/auth', '/_next', '/favicon.ico', '/public'],
55
-
56
- // What to do when agent is detected
57
- onAgentDetected: async (result) => {
58
- // With WASM: 95-100% confidence for cryptographically verified agents
59
- console.log(`🤖 AI Agent detected:`, {
60
- agent: result.agent,
61
- confidence: `${Math.round(result.confidence * 100)}%`,
62
- verification: result.verificationMethod, // 'signature' with WASM, 'pattern' without
63
- risk: result.riskLevel,
64
- timestamp: result.timestamp,
65
- });
66
-
67
- // You can add custom logic here:
68
- // - Log to analytics
69
- // - Send alerts
70
- // - Apply rate limiting
71
- // - etc.
72
- },
73
-
74
- // Set to true to block AI agents
75
- blockOnHighConfidence: false, // Change to true to block agents
76
-
77
- // Minimum confidence to trigger blocking (0.8 = 80%)
78
- confidenceThreshold: 0.8,
79
-
80
- // Custom response when blocking
81
- blockedResponse: {
82
- status: 403,
83
- message: 'AI agent access restricted',
84
- headers: {
85
- 'Content-Type': 'application/json',
86
- 'X-Blocked-Reason': 'ai-agent-detected',
87
- },
88
- },
89
- });
90
-
91
- // Run AgentShield detection
92
- const response = await agentShieldMiddleware(request);
93
-
94
- // Add security headers to all responses
95
- response.headers.set('X-Frame-Options', 'DENY');
96
- response.headers.set('X-Content-Type-Options', 'nosniff');
97
- response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
98
-
99
- return response;
100
- } catch (error) {
101
- // If WASM fails to load, fall back to pattern detection (85% confidence)
102
- console.warn('⚠️ WASM initialization failed, using pattern detection:', error);
103
-
104
- // You could use the regular middleware here as fallback
105
- // For now, just continue
106
- return NextResponse.next();
107
- }
108
- }
109
-
110
- // Configure which paths the middleware runs on
111
- export const config = {
112
- matcher: [
113
- /*
114
- * Match all request paths except for the ones starting with:
115
- * - _next/static (static files)
116
- * - _next/image (image optimization files)
117
- * - favicon.ico (favicon file)
118
- * - public folder
119
- */
120
- {
121
- source: '/((?!_next/static|_next/image|favicon.ico|public).*)',
122
- missing: [
123
- { type: 'header', key: 'next-router-prefetch' },
124
- { type: 'header', key: 'purpose', value: 'prefetch' },
125
- ],
126
- },
127
- ],
128
- };
129
-
130
- /**
131
- * TypeScript Support
132
- *
133
- * Add this to a `types/wasm.d.ts` file in your project:
134
- *
135
- * declare module '@kya-os/checkpoint/wasm?module' {
136
- * const value: WebAssembly.Module;
137
- * export default value;
138
- * }
139
- */
140
-
141
- /**
142
- * What You'll See in Logs:
143
- *
144
- * With WASM (95-100% confidence):
145
- * 🤖 AI Agent detected: {
146
- * agent: 'ChatGPT-User',
147
- * confidence: '100%',
148
- * verification: 'signature', // Cryptographically verified!
149
- * risk: 'high',
150
- * timestamp: '2024-01-01T00:00:00.000Z'
151
- * }
152
- *
153
- * Without WASM (85% confidence):
154
- * 🤖 AI Agent detected: {
155
- * agent: 'ChatGPT-User',
156
- * confidence: '85%',
157
- * verification: 'pattern', // Pattern matching only
158
- * risk: 'medium',
159
- * timestamp: '2024-01-01T00:00:00.000Z'
160
- * }
161
- */