@kya-os/checkpoint-nextjs 1.2.0 → 1.7.0

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 (44) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/dist/composed-policy.d.mts +108 -0
  3. package/dist/composed-policy.d.ts +108 -0
  4. package/dist/composed-policy.js +91 -0
  5. package/dist/composed-policy.mjs +85 -0
  6. package/dist/config-_nfPN3E3.d.mts +205 -0
  7. package/dist/config-kxFihzR_.d.ts +205 -0
  8. package/dist/create-middleware.js +0 -2
  9. package/dist/create-middleware.mjs +0 -2
  10. package/dist/edge-runtime-loader.js +3 -1
  11. package/dist/edge-runtime-loader.mjs +3 -1
  12. package/dist/edge-wasm-middleware.d.mts +6 -6
  13. package/dist/edge-wasm-middleware.d.ts +6 -6
  14. package/dist/index.d.mts +6 -14
  15. package/dist/index.d.ts +6 -14
  16. package/dist/index.js +160 -8
  17. package/dist/index.mjs +161 -9
  18. package/dist/middleware-edge.d.mts +7 -3
  19. package/dist/middleware-edge.d.ts +7 -3
  20. package/dist/middleware-edge.js +157 -3
  21. package/dist/middleware-edge.mjs +154 -3
  22. package/dist/middleware-node.d.mts +39 -116
  23. package/dist/middleware-node.d.ts +39 -116
  24. package/dist/middleware-node.js +164 -3
  25. package/dist/middleware-node.mjs +161 -4
  26. package/dist/middleware.d.mts +10 -1
  27. package/dist/middleware.d.ts +10 -1
  28. package/dist/middleware.js +6 -0
  29. package/dist/middleware.mjs +6 -1
  30. package/dist/nodejs-wasm-loader.d.mts +3 -4
  31. package/dist/nodejs-wasm-loader.d.ts +3 -4
  32. package/dist/nodejs-wasm-loader.js +1 -1
  33. package/dist/nodejs-wasm-loader.mjs +1 -1
  34. package/dist/signature-verifier.js +2 -2
  35. package/dist/signature-verifier.mjs +2 -2
  36. package/dist/wasm-setup.js +1 -1
  37. package/dist/wasm-setup.mjs +1 -1
  38. package/package.json +4 -9
  39. package/dist/.tsbuildinfo +0 -1
  40. package/dist/wasm-middleware.d.mts +0 -98
  41. package/dist/wasm-middleware.d.ts +0 -98
  42. package/dist/wasm-middleware.js +0 -125
  43. package/dist/wasm-middleware.mjs +0 -121
  44. package/templates/middleware-wasm-100.ts +0 -161
@@ -1,98 +0,0 @@
1
- import { NextRequest, NextResponse } from 'next/server';
2
-
3
- /**
4
- * WASM-enabled middleware for Next.js with Checkpoint.
5
- *
6
- * **Deprecation notice (AgentDetector-Deletion-1):**
7
- * `createWasmAgentShieldMiddleware` is deprecated as of this patch and
8
- * slated for removal in the next minor. It internally constructs a
9
- * legacy `AgentDetector` and never actually uses the WASM instance for
10
- * detection (the `wasmInstance` arg only bumps confidence by 15%).
11
- * Stage 1 detection now lives in the Rust `kya-os-engine` (PDM-1
12
- * #2560). Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs`
13
- * — engine-backed, runs the orchestrator including envelope
14
- * verification.
15
- */
16
-
17
- /** @internal — test-only reset for the one-shot warn latch. */
18
- declare function __resetCreateWasmAgentShieldWarningForTests(): void;
19
- interface WasmDetectionResult {
20
- isAgent: boolean;
21
- isAiCrawler?: boolean;
22
- confidence: number;
23
- agent?: string | undefined;
24
- verificationMethod: 'signature' | 'pattern' | 'none';
25
- riskLevel: 'low' | 'medium' | 'high';
26
- timestamp: string;
27
- }
28
- interface AgentShieldConfig {
29
- onAgentDetected?: (result: WasmDetectionResult) => void | Promise<void>;
30
- blockOnHighConfidence?: boolean;
31
- confidenceThreshold?: number;
32
- skipPaths?: string[];
33
- blockedResponse?: {
34
- status?: number;
35
- message?: string;
36
- headers?: Record<string, string>;
37
- };
38
- }
39
- /**
40
- * @deprecated Wraps the legacy `AgentDetector` class. Will be removed
41
- * in the next minor (AgentDetector-Deletion-2). Migrate to
42
- * `withCheckpoint` from `@kya-os/checkpoint-nextjs` — engine-backed,
43
- * runs the orchestrator including envelope verification.
44
- *
45
- * Create a WASM-enabled Checkpoint middleware (**pattern-detection only**).
46
- *
47
- * **This factory runs UA/header pattern matching only.** It does NOT
48
- * verify MCP-I signed envelopes — no JWS verification, no DID
49
- * resolution, no orchestrator stages. Use it when your only enforcement
50
- * concern is "is this request from a known bot pattern."
51
- *
52
- * **For envelope verification, use {@link withCheckpoint} instead** —
53
- * exported from `@kya-os/checkpoint-nextjs` (Node runtime) or
54
- * `@kya-os/checkpoint-nextjs/edge` (Edge runtime). `withCheckpoint`
55
- * routes every request through the kya-os-engine via WASM and supports
56
- * both `_meta.proof.jws` body envelopes (default) and the legacy
57
- * `KYA-Delegation` header form (opt-in via `legacyEnvelopeFallback`).
58
- * See SDK-Envelope-Plumbing-1 (#2594) for the migration context.
59
- *
60
- * @example pattern-only (this factory)
61
- * ```typescript
62
- * import wasmModule from '@kya-os/checkpoint/wasm?module';
63
- * import { createCheckpointWasmMiddleware } from '@kya-os/checkpoint-nextjs';
64
- *
65
- * const wasmInstance = await WebAssembly.instantiate(wasmModule);
66
- * export const middleware = createCheckpointWasmMiddleware({
67
- * wasmInstance,
68
- * confidenceThreshold: 80,
69
- * });
70
- * ```
71
- *
72
- * @example envelope verification (use `withCheckpoint` instead)
73
- * ```typescript
74
- * import { withCheckpoint } from '@kya-os/checkpoint-nextjs';
75
- *
76
- * export default withCheckpoint({
77
- * tenantHost: 'acme.checkpoint.example',
78
- * legacyEnvelopeFallback: true, // accept `KYA-Delegation` header form
79
- * // drainJsonBody defaults to true; spec-form `_meta.proof.jws` works out of the box
80
- * });
81
- * ```
82
- */
83
- declare function createWasmAgentShieldMiddleware(config: AgentShieldConfig & {
84
- wasmInstance?: WebAssembly.Instance;
85
- }): (request: NextRequest) => Promise<NextResponse<unknown>>;
86
- /**
87
- * Helper to load and instantiate WASM module
88
- * This should be called at the top of your middleware.ts file
89
- *
90
- * @example
91
- * ```typescript
92
- * import wasmModule from '@kya-os/checkpoint/wasm?module';
93
- * const wasmInstance = await instantiateWasm(wasmModule);
94
- * ```
95
- */
96
- declare function instantiateWasm(wasmModule: WebAssembly.Module): Promise<WebAssembly.Instance>;
97
-
98
- export { type AgentShieldConfig, type WasmDetectionResult, __resetCreateWasmAgentShieldWarningForTests, createWasmAgentShieldMiddleware, instantiateWasm };
@@ -1,125 +0,0 @@
1
- 'use strict';
2
-
3
- var server = require('next/server');
4
- var checkpoint = require('@kya-os/checkpoint');
5
-
6
- // src/wasm-middleware.ts
7
-
8
- // src/local-detection-gate.ts
9
- function isDetectedAgentForLocalGate(result) {
10
- return result.isAgent === true;
11
- }
12
- function evaluateLocalDetectionGate(result, config) {
13
- if (!isDetectedAgentForLocalGate(result)) {
14
- return { action: "allow", shouldNotify: false };
15
- }
16
- if ((result.confidence ?? 0) >= config.confidenceThreshold) {
17
- return { action: config.defaultAction, shouldNotify: true };
18
- }
19
- return { action: "allow", shouldNotify: false };
20
- }
21
-
22
- // src/wasm-middleware.ts
23
- var _createWasmAgentShieldWarned = false;
24
- function warnCreateWasmAgentShieldDeprecated() {
25
- if (_createWasmAgentShieldWarned) return;
26
- _createWasmAgentShieldWarned = true;
27
- if (typeof process !== "undefined" && process.env?.NODE_ENV === "production") return;
28
- console.warn(
29
- "[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."
30
- );
31
- }
32
- function __resetCreateWasmAgentShieldWarningForTests() {
33
- _createWasmAgentShieldWarned = false;
34
- }
35
- function createWasmAgentShieldMiddleware(config) {
36
- warnCreateWasmAgentShieldDeprecated();
37
- const {
38
- onAgentDetected,
39
- blockOnHighConfidence = false,
40
- confidenceThreshold = 80,
41
- // Updated to 0-100 scale (was 0.8)
42
- skipPaths = [],
43
- blockedResponse = {
44
- status: 403,
45
- message: "Access denied: AI agent detected",
46
- headers: { "Content-Type": "application/json" }
47
- },
48
- wasmInstance
49
- } = config;
50
- return async function middleware(request) {
51
- const path = request.nextUrl.pathname;
52
- if (skipPaths.some((skip) => path.startsWith(skip))) {
53
- return server.NextResponse.next();
54
- }
55
- try {
56
- const detector = new checkpoint.AgentDetector();
57
- const hasWasm = !!wasmInstance;
58
- const metadata = {
59
- userAgent: request.headers.get("user-agent") || void 0,
60
- ipAddress: request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || void 0,
61
- headers: Object.fromEntries(request.headers.entries()),
62
- timestamp: /* @__PURE__ */ new Date()
63
- };
64
- const result = await detector.analyze(metadata);
65
- const enhancedResult = {
66
- isAgent: result.isAgent,
67
- isAiCrawler: result.isAiCrawler,
68
- confidence: hasWasm && result.confidence > 85 ? Math.min(result.confidence * 1.15, 100) : result.confidence,
69
- agent: result.detectedAgent?.name || void 0,
70
- verificationMethod: hasWasm && result.confidence > 85 ? "signature" : "pattern",
71
- // Updated to 0-100 scale
72
- riskLevel: result.confidence > 90 ? "high" : result.confidence > 70 ? "medium" : "low",
73
- // Updated to 0-100 scale (was 0.7)
74
- timestamp: result.timestamp instanceof Date ? result.timestamp.toISOString() : new Date(result.timestamp).toISOString()
75
- };
76
- const decision = evaluateLocalDetectionGate(enhancedResult, {
77
- confidenceThreshold,
78
- defaultAction: blockOnHighConfidence ? "block" : "allow"
79
- });
80
- if (onAgentDetected && isDetectedAgentForLocalGate(enhancedResult)) {
81
- await onAgentDetected(enhancedResult);
82
- }
83
- if (decision.action === "block") {
84
- return server.NextResponse.json(
85
- {
86
- error: blockedResponse.message,
87
- agent: enhancedResult.agent,
88
- confidence: Math.round(enhancedResult.confidence)
89
- },
90
- {
91
- status: blockedResponse.status || 403,
92
- headers: blockedResponse.headers || {}
93
- }
94
- );
95
- }
96
- const response = server.NextResponse.next();
97
- if (enhancedResult.isAgent) {
98
- response.headers.set("X-Agent-Detected", enhancedResult.agent || "unknown");
99
- response.headers.set(
100
- "X-Agent-Confidence",
101
- String(Math.round(enhancedResult.confidence * 100))
102
- );
103
- response.headers.set("X-Agent-Verification", enhancedResult.verificationMethod);
104
- }
105
- return response;
106
- } catch (error) {
107
- console.error("AgentShield middleware error:", error);
108
- return server.NextResponse.next();
109
- }
110
- };
111
- }
112
- async function instantiateWasm(wasmModule) {
113
- try {
114
- const instance = await WebAssembly.instantiate(wasmModule);
115
- console.log("\u2705 AgentShield: WASM module loaded for cryptographic verification");
116
- return instance;
117
- } catch (error) {
118
- console.warn("\u26A0\uFE0F AgentShield: Failed to instantiate WASM module", error);
119
- throw error;
120
- }
121
- }
122
-
123
- exports.__resetCreateWasmAgentShieldWarningForTests = __resetCreateWasmAgentShieldWarningForTests;
124
- exports.createWasmAgentShieldMiddleware = createWasmAgentShieldMiddleware;
125
- exports.instantiateWasm = instantiateWasm;
@@ -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
- */