@kya-os/checkpoint-nextjs 1.1.4 → 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 (43) hide show
  1. package/CHANGELOG.md +190 -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 +162 -9
  17. package/dist/index.mjs +163 -10
  18. package/dist/middleware-edge.d.mts +7 -3
  19. package/dist/middleware-edge.d.ts +7 -3
  20. package/dist/middleware-edge.js +159 -4
  21. package/dist/middleware-edge.mjs +156 -4
  22. package/dist/middleware-node.d.mts +39 -101
  23. package/dist/middleware-node.d.ts +39 -101
  24. package/dist/middleware-node.js +166 -4
  25. package/dist/middleware-node.mjs +163 -5
  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 +8 -11
  39. package/dist/wasm-middleware.d.mts +0 -98
  40. package/dist/wasm-middleware.d.ts +0 -98
  41. package/dist/wasm-middleware.js +0 -125
  42. package/dist/wasm-middleware.mjs +0 -121
  43. package/templates/middleware-wasm-100.ts +0 -161
@@ -1,10 +1,9 @@
1
1
  /**
2
2
  * @deprecated Phase-D.9a — legacy Node.js WASM loader for the retired
3
3
  * `agentshield-wasm` Rust crate. This file used `fs.readFileSync` to
4
- * locate + load the legacy detector's WASM binary into the
5
- * `@kya-os/checkpoint` `AgentDetector` class via `setWasmModule`. Both
6
- * the WASM crate (Phase-D.9a/D.9b) and the AgentDetector class
7
- * (AgentDetector-Deletion-2, next minor) are slated for deletion.
4
+ * locate + load the legacy detector's WASM binary into the legacy
5
+ * detection class. Both the WASM crate (Phase-D.9a/D.9b) and the
6
+ * detection class (removed in AgentDetector-Deletion-2) are retired.
8
7
  *
9
8
  * Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` — it
10
9
  * loads the canonical `kya-os-engine` WASM automatically via
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // src/nodejs-wasm-loader.ts
4
- var MIGRATION_ERROR = "`@kya-os/checkpoint-nextjs`'s `loadWasmNodejs` / `isNodejsRuntime` / `getWasmModule` / `isWasmInitialized` were deprecated in Phase-D.9a (legacy `agentshield-wasm` Rust crate retirement). The legacy `AgentDetector` class they fed is slated for deletion in AgentDetector-Deletion-2 (next minor). Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` \u2014 engine-backed via the Rust `kya-os-engine` crate, with automatic WASM loading via `@kya-os/checkpoint-wasm-runtime`. See packages/checkpoint-nextjs/README.md for the canonical recipe.";
4
+ var MIGRATION_ERROR = "`@kya-os/checkpoint-nextjs`'s `loadWasmNodejs` / `isNodejsRuntime` / `getWasmModule` / `isWasmInitialized` were deprecated in Phase-D.9a (legacy `agentshield-wasm` Rust crate retirement). The legacy detection class they fed was removed in AgentDetector-Deletion-2. Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` \u2014 engine-backed via the Rust `kya-os-engine` crate, with automatic WASM loading via `@kya-os/checkpoint-wasm-runtime`. See packages/checkpoint-nextjs/README.md for the canonical recipe.";
5
5
  var _nodejsWasmWarned = false;
6
6
  function warnNodejsWasmDeprecated() {
7
7
  if (_nodejsWasmWarned) return;
@@ -1,5 +1,5 @@
1
1
  // src/nodejs-wasm-loader.ts
2
- var MIGRATION_ERROR = "`@kya-os/checkpoint-nextjs`'s `loadWasmNodejs` / `isNodejsRuntime` / `getWasmModule` / `isWasmInitialized` were deprecated in Phase-D.9a (legacy `agentshield-wasm` Rust crate retirement). The legacy `AgentDetector` class they fed is slated for deletion in AgentDetector-Deletion-2 (next minor). Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` \u2014 engine-backed via the Rust `kya-os-engine` crate, with automatic WASM loading via `@kya-os/checkpoint-wasm-runtime`. See packages/checkpoint-nextjs/README.md for the canonical recipe.";
2
+ var MIGRATION_ERROR = "`@kya-os/checkpoint-nextjs`'s `loadWasmNodejs` / `isNodejsRuntime` / `getWasmModule` / `isWasmInitialized` were deprecated in Phase-D.9a (legacy `agentshield-wasm` Rust crate retirement). The legacy detection class they fed was removed in AgentDetector-Deletion-2. Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` \u2014 engine-backed via the Rust `kya-os-engine` crate, with automatic WASM loading via `@kya-os/checkpoint-wasm-runtime`. See packages/checkpoint-nextjs/README.md for the canonical recipe.";
3
3
  var _nodejsWasmWarned = false;
4
4
  function warnNodejsWasmDeprecated() {
5
5
  if (_nodejsWasmWarned) return;
@@ -34,8 +34,8 @@ var KNOWN_KEYS = {
34
34
  publicKey: "7F_3jDlxaquwh291MiACkcS3Opq88NksyHiakzS-Y1g",
35
35
  validFrom: 1735689600,
36
36
  // Jan 1, 2025 (nbf from OpenAI)
37
- validUntil: 1769029093
38
- // Jan 21, 2026 (exp from OpenAI)
37
+ validUntil: 1780362143
38
+ // Jun 1, 2026 (exp from OpenAI live directory 2026-05-25)
39
39
  }
40
40
  ]
41
41
  };
@@ -12,8 +12,8 @@ var KNOWN_KEYS = {
12
12
  publicKey: "7F_3jDlxaquwh291MiACkcS3Opq88NksyHiakzS-Y1g",
13
13
  validFrom: 1735689600,
14
14
  // Jan 1, 2025 (nbf from OpenAI)
15
- validUntil: 1769029093
16
- // Jan 21, 2026 (exp from OpenAI)
15
+ validUntil: 1780362143
16
+ // Jun 1, 2026 (exp from OpenAI live directory 2026-05-25)
17
17
  }
18
18
  ]
19
19
  };
@@ -53,7 +53,7 @@ function isWasmInitialized() {
53
53
  var MIGRATION_ERROR, _nodejsWasmWarned;
54
54
  var init_nodejs_wasm_loader = __esm({
55
55
  "src/nodejs-wasm-loader.ts"() {
56
- MIGRATION_ERROR = "`@kya-os/checkpoint-nextjs`'s `loadWasmNodejs` / `isNodejsRuntime` / `getWasmModule` / `isWasmInitialized` were deprecated in Phase-D.9a (legacy `agentshield-wasm` Rust crate retirement). The legacy `AgentDetector` class they fed is slated for deletion in AgentDetector-Deletion-2 (next minor). Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` \u2014 engine-backed via the Rust `kya-os-engine` crate, with automatic WASM loading via `@kya-os/checkpoint-wasm-runtime`. See packages/checkpoint-nextjs/README.md for the canonical recipe.";
56
+ MIGRATION_ERROR = "`@kya-os/checkpoint-nextjs`'s `loadWasmNodejs` / `isNodejsRuntime` / `getWasmModule` / `isWasmInitialized` were deprecated in Phase-D.9a (legacy `agentshield-wasm` Rust crate retirement). The legacy detection class they fed was removed in AgentDetector-Deletion-2. Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` \u2014 engine-backed via the Rust `kya-os-engine` crate, with automatic WASM loading via `@kya-os/checkpoint-wasm-runtime`. See packages/checkpoint-nextjs/README.md for the canonical recipe.";
57
57
  _nodejsWasmWarned = false;
58
58
  }
59
59
  });
@@ -51,7 +51,7 @@ function isWasmInitialized() {
51
51
  var MIGRATION_ERROR, _nodejsWasmWarned;
52
52
  var init_nodejs_wasm_loader = __esm({
53
53
  "src/nodejs-wasm-loader.ts"() {
54
- MIGRATION_ERROR = "`@kya-os/checkpoint-nextjs`'s `loadWasmNodejs` / `isNodejsRuntime` / `getWasmModule` / `isWasmInitialized` were deprecated in Phase-D.9a (legacy `agentshield-wasm` Rust crate retirement). The legacy `AgentDetector` class they fed is slated for deletion in AgentDetector-Deletion-2 (next minor). Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` \u2014 engine-backed via the Rust `kya-os-engine` crate, with automatic WASM loading via `@kya-os/checkpoint-wasm-runtime`. See packages/checkpoint-nextjs/README.md for the canonical recipe.";
54
+ MIGRATION_ERROR = "`@kya-os/checkpoint-nextjs`'s `loadWasmNodejs` / `isNodejsRuntime` / `getWasmModule` / `isWasmInitialized` were deprecated in Phase-D.9a (legacy `agentshield-wasm` Rust crate retirement). The legacy detection class they fed was removed in AgentDetector-Deletion-2. Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` \u2014 engine-backed via the Rust `kya-os-engine` crate, with automatic WASM loading via `@kya-os/checkpoint-wasm-runtime`. See packages/checkpoint-nextjs/README.md for the canonical recipe.";
55
55
  _nodejsWasmWarned = false;
56
56
  }
57
57
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kya-os/checkpoint-nextjs",
3
- "version": "1.1.4",
3
+ "version": "1.7.0",
4
4
  "description": "Checkpoint Next.js middleware for AI agent detection (formerly @kya-os/agentshield-nextjs)",
5
5
  "keywords": [
6
6
  "nextjs",
@@ -62,11 +62,6 @@
62
62
  "import": "./dist/wasm-setup.mjs",
63
63
  "require": "./dist/wasm-setup.js"
64
64
  },
65
- "./wasm-middleware": {
66
- "types": "./dist/wasm-middleware.d.ts",
67
- "import": "./dist/wasm-middleware.mjs",
68
- "require": "./dist/wasm-middleware.js"
69
- },
70
65
  "./edge-wasm-middleware": {
71
66
  "types": "./dist/edge-wasm-middleware.d.ts",
72
67
  "import": "./dist/edge-wasm-middleware.mjs",
@@ -115,12 +110,14 @@
115
110
  "rimraf": "^5.0.5",
116
111
  "tsup": "^8.0.2",
117
112
  "typescript": "^5.4.2",
113
+ "vite-plugin-top-level-await": "^1.6.0",
114
+ "vite-plugin-wasm": "^3.6.0",
118
115
  "vitest": "^1.3.1"
119
116
  },
120
117
  "peerDependencies": {
118
+ "@upstash/redis": ">=1.0.0",
121
119
  "next": ">=13.0.0",
122
- "react": ">=18.0.0",
123
- "@upstash/redis": ">=1.0.0"
120
+ "react": ">=18.0.0"
124
121
  },
125
122
  "peerDependenciesMeta": {
126
123
  "@upstash/redis": {
@@ -134,9 +131,9 @@
134
131
  "dependencies": {
135
132
  "@noble/ed25519": "^2.2.3",
136
133
  "@noble/hashes": "^2.0.1",
137
- "@kya-os/checkpoint": "1.0.1",
138
- "@kya-os/checkpoint-shared": "1.1.0",
139
- "@kya-os/checkpoint-wasm-runtime": "^1.2.0"
134
+ "@kya-os/checkpoint": "1.2.0",
135
+ "@kya-os/checkpoint-shared": "1.2.0",
136
+ "@kya-os/checkpoint-wasm-runtime": "^1.8.0"
140
137
  },
141
138
  "scripts": {
142
139
  "build": "tsup",
@@ -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,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 };