@kya-os/checkpoint-nextjs 1.7.1 → 1.9.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.
- package/CHANGELOG.md +30 -0
- package/EDGE_RUNTIME_WASM_SETUP.md +11 -11
- package/README.md +144 -251
- package/bin/setup-edge-wasm.js +9 -1
- package/dist/adapt.js +9 -6
- package/dist/adapt.mjs +9 -6
- package/dist/api-client.d.mts +9 -0
- package/dist/api-client.d.ts +9 -0
- package/dist/api-middleware.d.mts +5 -3
- package/dist/api-middleware.d.ts +5 -3
- package/dist/api-middleware.js +19 -32
- package/dist/api-middleware.mjs +20 -33
- package/dist/composed-policy.js +1 -0
- package/dist/composed-policy.mjs +2 -1
- package/dist/{config-DAwIA4DB.d.mts → config-CleTeeoW.d.mts} +32 -13
- package/dist/{config-DyU4l5er.d.ts → config-XMOIkxFN.d.ts} +32 -13
- package/dist/create-middleware.d.mts +1 -1
- package/dist/create-middleware.d.ts +1 -1
- package/dist/edge/index.d.mts +3 -1
- package/dist/edge/index.d.ts +3 -1
- package/dist/edge/index.js +5 -16
- package/dist/edge/index.mjs +5 -16
- package/dist/edge-runtime-loader.d.mts +3 -1
- package/dist/edge-runtime-loader.d.ts +3 -1
- package/dist/edge-runtime-loader.js +4 -16
- package/dist/edge-runtime-loader.mjs +5 -17
- package/dist/edge-wasm-middleware.d.mts +1 -1
- package/dist/edge-wasm-middleware.d.ts +1 -1
- package/dist/edge-wasm-middleware.js +1 -1
- package/dist/edge-wasm-middleware.mjs +1 -1
- package/dist/index.d.mts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +126 -85
- package/dist/index.mjs +128 -87
- package/dist/middleware-bundler.d.mts +13 -0
- package/dist/middleware-bundler.d.ts +13 -0
- package/dist/middleware-bundler.js +354 -0
- package/dist/middleware-bundler.mjs +352 -0
- package/dist/middleware-edge.d.mts +4 -40
- package/dist/middleware-edge.d.ts +4 -40
- package/dist/middleware-edge.js +148 -100
- package/dist/middleware-edge.mjs +151 -103
- package/dist/middleware-node.d.mts +15 -51
- package/dist/middleware-node.d.ts +15 -51
- package/dist/middleware-node.js +99 -56
- package/dist/middleware-node.mjs +102 -55
- package/dist/middleware.d.mts +1 -1
- package/dist/middleware.d.ts +1 -1
- package/dist/policy.js +6 -1
- package/dist/policy.mjs +6 -1
- package/dist/session-tracker.js +2 -0
- package/dist/session-tracker.mjs +2 -0
- package/dist/translate.d.mts +7 -4
- package/dist/translate.d.ts +7 -4
- package/dist/translate.js +9 -8
- package/dist/translate.mjs +9 -8
- package/dist/{types-D9RQvPNy.d.mts → types-Chgi5TFC.d.mts} +2 -2
- package/dist/{types-D9RQvPNy.d.ts → types-Chgi5TFC.d.ts} +2 -2
- package/package.json +17 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# @kya-os/checkpoint-nextjs
|
|
2
2
|
|
|
3
|
+
## 1.9.0
|
|
4
|
+
|
|
5
|
+
- Add the `@kya-os/checkpoint-nextjs/bundler` entry for applications that bundle the WASM runtime, including the first-party browser integrity lab.
|
|
6
|
+
- Next.js middleware, API middleware, edge helpers, and translators now use the
|
|
7
|
+
shared bounded IP normalizer (#4794).
|
|
8
|
+
- Added explicit clientIpPolicy configuration. The default is direct peer-only;
|
|
9
|
+
Vercel and trusted-proxy forwarding require an explicit profile.
|
|
10
|
+
- Authenticated server-to-server body addresses are normalized only after the
|
|
11
|
+
caller has passed the endpoint authentication boundary.
|
|
12
|
+
|
|
13
|
+
## 1.8.0 — fetcher-200 envelope active by default (#3530)
|
|
14
|
+
|
|
15
|
+
**Minor — behaviour change.** The body-readable HTTP 200 challenge envelope
|
|
16
|
+
(draft-kya-http-02 §8.1, fetcher-200) is now the **default**: `delegationChallengeMode`
|
|
17
|
+
defaults to `'negotiated'` (was `'spec-401'`) across the node, edge, and API
|
|
18
|
+
middlewares. A detected interactive `ai_agent` (or a non-empty `KYA-Accept-Challenge`
|
|
19
|
+
request header) now receives the body-readable **200** so fetchers that drop 4xx
|
|
20
|
+
bodies (e.g. Claude-User WebFetch) can read the `consent_uri`; capable / discovery
|
|
21
|
+
clients still get the spec **401**. The body is byte-identical across both —
|
|
22
|
+
selection is a cooperative-UX bridge, **NOT** an access control. Set
|
|
23
|
+
`delegationChallengeMode: 'spec-401'` to opt out. Matches the gateway worker
|
|
24
|
+
(#3431); fleet rollout #3530.
|
|
25
|
+
|
|
26
|
+
## 1.7.1 — engine: rfc9421 verifier fix (#3474)
|
|
27
|
+
|
|
28
|
+
**Patch.** Republished so the rebuilt bundle picks up the RFC-9421 verifier fix
|
|
29
|
+
from `@kya-os/checkpoint-wasm-runtime@1.8.1` (engine #3474 — adds `ecdsa-p256`
|
|
30
|
+
alongside `ed25519` in the §2.3 accept-set). No API change. (Resyncs the
|
|
31
|
+
committed version to the value published via the workflow `version` input.)
|
|
32
|
+
|
|
3
33
|
## 1.6.0 — Self-report SDK identity + runtime (version-gating)
|
|
4
34
|
|
|
5
35
|
**Minor release — additive + a fix.** `withCheckpoint`'s detection reporter now
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Checkpoint WASM Setup for Next.js Edge Runtime
|
|
2
2
|
|
|
3
3
|
## The Challenge
|
|
4
4
|
|
|
@@ -16,7 +16,7 @@ process that copies the necessary files to your Next.js project.
|
|
|
16
16
|
|
|
17
17
|
## Quick Start
|
|
18
18
|
|
|
19
|
-
### Step 1: Install
|
|
19
|
+
### Step 1: Install Checkpoint
|
|
20
20
|
|
|
21
21
|
```bash
|
|
22
22
|
npm install @kya-os/checkpoint-nextjs
|
|
@@ -27,7 +27,7 @@ pnpm add @kya-os/checkpoint-nextjs
|
|
|
27
27
|
### Step 2: Run Setup Script
|
|
28
28
|
|
|
29
29
|
```bash
|
|
30
|
-
npx
|
|
30
|
+
npx checkpoint-setup-edge
|
|
31
31
|
```
|
|
32
32
|
|
|
33
33
|
This will:
|
|
@@ -90,16 +90,16 @@ cp node_modules/@kya-os/checkpoint-nextjs/dist/wasm/agentshield_wasm_bg.wasm ./w
|
|
|
90
90
|
|
|
91
91
|
### 2. Create TypeScript Definitions
|
|
92
92
|
|
|
93
|
-
Create `wasm/
|
|
93
|
+
Create `wasm/checkpoint.d.ts`:
|
|
94
94
|
|
|
95
95
|
```typescript
|
|
96
|
-
// wasm/
|
|
96
|
+
// wasm/checkpoint.d.ts
|
|
97
97
|
declare module '*.wasm?module' {
|
|
98
98
|
const wasmModule: WebAssembly.Module;
|
|
99
99
|
export default wasmModule;
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
-
export interface
|
|
102
|
+
export interface CheckpointWasm {
|
|
103
103
|
detect_agent(metadata: string): string;
|
|
104
104
|
get_version(): string;
|
|
105
105
|
Memory: WebAssembly.Memory;
|
|
@@ -108,10 +108,10 @@ export interface AgentShieldWasm {
|
|
|
108
108
|
|
|
109
109
|
### 3. Create Edge Loader
|
|
110
110
|
|
|
111
|
-
Create `lib/
|
|
111
|
+
Create `lib/checkpoint-edge.ts`:
|
|
112
112
|
|
|
113
113
|
```typescript
|
|
114
|
-
// lib/
|
|
114
|
+
// lib/checkpoint-edge.ts
|
|
115
115
|
import type { NextRequest } from 'next/server';
|
|
116
116
|
import type { EdgeRuntimeDetectionDetail } from '@kya-os/checkpoint-nextjs/edge-runtime-loader';
|
|
117
117
|
import wasmModule from '../wasm/agentshield_wasm_bg.wasm?module';
|
|
@@ -182,7 +182,7 @@ export function createAgentShieldMiddleware(options: {
|
|
|
182
182
|
try {
|
|
183
183
|
await initWasm();
|
|
184
184
|
initialized = true;
|
|
185
|
-
console.log('✅
|
|
185
|
+
console.log('✅ Checkpoint WASM initialized in Edge Runtime');
|
|
186
186
|
} catch (error) {
|
|
187
187
|
console.warn('⚠️ WASM initialization failed, falling back to pattern detection:', error);
|
|
188
188
|
initialized = true;
|
|
@@ -338,5 +338,5 @@ ensures:
|
|
|
338
338
|
## Support
|
|
339
339
|
|
|
340
340
|
- GitHub Issues:
|
|
341
|
-
[github.com/
|
|
342
|
-
- Documentation: [
|
|
341
|
+
[github.com/Know-That-Ai/checkpoint/issues](https://github.com/Know-That-Ai/checkpoint/issues)
|
|
342
|
+
- Documentation: [checkpoint.ai/docs](https://checkpoint.ai/docs)
|
package/README.md
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
# @kya-os/checkpoint-nextjs
|
|
2
2
|
|
|
3
|
-
Next.js middleware
|
|
3
|
+
Next.js middleware for Checkpoint AI agent detection and enforcement.
|
|
4
4
|
|
|
5
5
|
## Features
|
|
6
6
|
|
|
7
7
|
- 🚀 **Next.js Middleware**: Edge-compatible middleware for all routes
|
|
8
|
-
-
|
|
9
|
-
- 🎯 **Flexible Actions**: Block, redirect,
|
|
8
|
+
- 🧩 **Two Deployment Shapes**: In-process WASM engine or SaaS gateway
|
|
9
|
+
- 🎯 **Flexible Actions**: Block, redirect, or challenge detected agents
|
|
10
10
|
- 🛡️ **Edge Runtime**: Optimized for Vercel Edge Functions
|
|
11
|
-
- 📊 **
|
|
11
|
+
- 📊 **Dashboard Reporting**: Detections land in your Checkpoint dashboard
|
|
12
12
|
|
|
13
13
|
## Two deployment shapes
|
|
14
14
|
|
|
@@ -52,21 +52,29 @@ npm install @kya-os/checkpoint-nextjs
|
|
|
52
52
|
|
|
53
53
|
## Quick Start
|
|
54
54
|
|
|
55
|
+
## Client-IP trust policy
|
|
56
|
+
|
|
57
|
+
Client-IP resolution defaults to the direct framework or socket peer. For a
|
|
58
|
+
Next.js deployment behind Vercel, select the Vercel profile explicitly:
|
|
59
|
+
|
|
60
|
+
withCheckpoint({
|
|
61
|
+
tenantHost: 'your.tenant.example',
|
|
62
|
+
clientIpPolicy: { platform: 'vercel' },
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
Forwarding headers are normalized and are not trusted by the middleware
|
|
66
|
+
without a matching deployment profile. See the client-IP resolution runbook
|
|
67
|
+
for the profile matrix and proxy-chain guidance.
|
|
68
|
+
|
|
55
69
|
### Middleware Setup
|
|
56
70
|
|
|
57
71
|
Create `middleware.js` (or `middleware.ts`) in your project root:
|
|
58
72
|
|
|
59
73
|
```javascript
|
|
60
|
-
import {
|
|
61
|
-
|
|
62
|
-
export default agentShield({
|
|
63
|
-
onAgentDetected: 'block',
|
|
64
|
-
confidenceThreshold: 0.8,
|
|
74
|
+
import { withCheckpointApi } from '@kya-os/checkpoint-nextjs';
|
|
65
75
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
enabled: true, // Track continued sessions from AI agents
|
|
69
|
-
},
|
|
76
|
+
export default withCheckpointApi({
|
|
77
|
+
apiKey: process.env.CHECKPOINT_API_KEY,
|
|
70
78
|
});
|
|
71
79
|
|
|
72
80
|
export const config = {
|
|
@@ -74,91 +82,81 @@ export const config = {
|
|
|
74
82
|
};
|
|
75
83
|
```
|
|
76
84
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
> and slated for removal in the next minor. It wraps the legacy TS
|
|
81
|
-
> `AgentDetector` class; Stage 1 detection now lives in the Rust
|
|
82
|
-
> `kya-os-engine` (PDM-1 #2560). Migrate to server-side detection via
|
|
83
|
-
> `withCheckpoint` from `@kya-os/checkpoint-nextjs`, or consume
|
|
84
|
-
> `KNOWN_AGENT_PATTERNS` directly from `@kya-os/checkpoint-shared` if
|
|
85
|
-
> you genuinely need client-side pattern matching. `useDetectionMonitor`
|
|
86
|
-
> stays — it doesn't depend on `AgentDetector`.
|
|
85
|
+
Enforcement happens in the middleware, before your pages and route handlers
|
|
86
|
+
run: blocked or challenged requests never reach your code. Tune what gets
|
|
87
|
+
blocked in your Checkpoint dashboard policy.
|
|
87
88
|
|
|
88
|
-
|
|
89
|
-
'use client';
|
|
90
|
-
|
|
91
|
-
import { useAgentDetection } from '@kya-os/checkpoint-nextjs';
|
|
89
|
+
### Client-Side Detection
|
|
92
90
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
if (result.isAgent) {
|
|
101
|
-
alert('Agent detected!');
|
|
102
|
-
}
|
|
103
|
-
};
|
|
104
|
-
|
|
105
|
-
return (
|
|
106
|
-
<div>
|
|
107
|
-
<button onClick={handleCheck} disabled={isDetecting}>
|
|
108
|
-
{isDetecting ? 'Checking...' : 'Check for Agents'}
|
|
109
|
-
</button>
|
|
110
|
-
|
|
111
|
-
{lastResult && (
|
|
112
|
-
<div>
|
|
113
|
-
<p>Is Agent: {lastResult.isAgent ? 'Yes' : 'No'}</p>
|
|
114
|
-
<p>Confidence: {(lastResult.confidence * 100).toFixed(1)}%</p>
|
|
115
|
-
</div>
|
|
116
|
-
)}
|
|
117
|
-
</div>
|
|
118
|
-
);
|
|
119
|
-
}
|
|
120
|
-
```
|
|
91
|
+
This package is server-side middleware; it does not ship client-side React
|
|
92
|
+
hooks. (The legacy `useAgentDetection` hook was removed along with the
|
|
93
|
+
`AgentDetector` class it wrapped.) For client-side detection, such as
|
|
94
|
+
conditionally rendering content or tracking agent visits from the browser,
|
|
95
|
+
use the [JavaScript Beacon](https://kya.vouched.id/docs/detect/beacon) or the
|
|
96
|
+
[Marketing Pixel](https://kya.vouched.id/docs/detect/pixel) alongside the
|
|
97
|
+
middleware.
|
|
121
98
|
|
|
122
99
|
## Middleware Configuration
|
|
123
100
|
|
|
101
|
+
The SaaS-gateway shape (`withCheckpointApi`) accepts:
|
|
102
|
+
|
|
124
103
|
```javascript
|
|
125
|
-
import {
|
|
104
|
+
import { withCheckpointApi } from '@kya-os/checkpoint-nextjs';
|
|
126
105
|
|
|
127
|
-
export default
|
|
128
|
-
//
|
|
129
|
-
|
|
130
|
-
enablePatternMatching: true,
|
|
131
|
-
enableBehaviorAnalysis: true,
|
|
106
|
+
export default withCheckpointApi({
|
|
107
|
+
// API key (or set the CHECKPOINT_API_KEY env var)
|
|
108
|
+
apiKey: process.env.CHECKPOINT_API_KEY,
|
|
132
109
|
|
|
133
|
-
// Action when agent
|
|
134
|
-
|
|
110
|
+
// Action when an agent should be blocked: 'block' | 'redirect' | 'challenge'
|
|
111
|
+
// Default: uses the policy from your dashboard
|
|
112
|
+
onBlock: 'block',
|
|
135
113
|
|
|
136
|
-
//
|
|
137
|
-
|
|
114
|
+
// Target when onBlock is 'redirect'
|
|
115
|
+
redirectUrl: '/blocked',
|
|
116
|
+
|
|
117
|
+
// Skip enforcement for paths (glob patterns)
|
|
118
|
+
skipPaths: ['/api/webhooks', '/health'],
|
|
138
119
|
|
|
139
|
-
// Custom
|
|
120
|
+
// Custom blocked response
|
|
140
121
|
blockedResponse: {
|
|
141
122
|
status: 403,
|
|
142
123
|
message: 'Access denied',
|
|
143
124
|
},
|
|
144
|
-
redirectUrl: '/blocked',
|
|
145
|
-
rewriteUrl: '/blocked',
|
|
146
125
|
|
|
147
|
-
//
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
126
|
+
// Edge detection: lower latency, catches non-JS clients. Default: true
|
|
127
|
+
useEdge: true,
|
|
128
|
+
|
|
129
|
+
// Request timeout in ms. Default: 5000
|
|
130
|
+
timeout: 5000,
|
|
131
|
+
|
|
132
|
+
// Fail open (allow) on API errors. Default: true
|
|
133
|
+
failOpen: true,
|
|
134
|
+
|
|
135
|
+
// Observability callback when an agent is detected
|
|
136
|
+
onAgentDetected: async (request, decision) => {
|
|
137
|
+
console.log('Agent detected:', decision.reason);
|
|
151
138
|
},
|
|
139
|
+
|
|
140
|
+
// Enable debug logging
|
|
141
|
+
debug: false,
|
|
152
142
|
});
|
|
153
143
|
```
|
|
154
144
|
|
|
145
|
+
The local-engine shape (`withCheckpoint`) takes a `CheckpointConfig` instead:
|
|
146
|
+
`tenantHost` (required), plus optional `enforcementMode` (`'enforce'` |
|
|
147
|
+
`'observe'`), `apiKey` (enables dashboard reporting), `projectId` (enforces
|
|
148
|
+
your deployed dashboard policy in-process), and more. See the
|
|
149
|
+
[middleware docs](https://kya.vouched.id/docs/enforce/middleware) for the
|
|
150
|
+
full option tables for both shapes.
|
|
151
|
+
|
|
155
152
|
## Actions
|
|
156
153
|
|
|
157
154
|
### Block Agents
|
|
158
155
|
|
|
159
156
|
```javascript
|
|
160
|
-
export default
|
|
161
|
-
|
|
157
|
+
export default withCheckpointApi({
|
|
158
|
+
apiKey: process.env.CHECKPOINT_API_KEY,
|
|
159
|
+
onBlock: 'block',
|
|
162
160
|
blockedResponse: {
|
|
163
161
|
status: 403,
|
|
164
162
|
message: 'Automated access not allowed',
|
|
@@ -173,125 +171,52 @@ export default agentShield({
|
|
|
173
171
|
### Redirect Agents
|
|
174
172
|
|
|
175
173
|
```javascript
|
|
176
|
-
export default
|
|
177
|
-
|
|
174
|
+
export default withCheckpointApi({
|
|
175
|
+
apiKey: process.env.CHECKPOINT_API_KEY,
|
|
176
|
+
onBlock: 'redirect',
|
|
178
177
|
redirectUrl: '/blocked',
|
|
179
|
-
confidenceThreshold: 0.8,
|
|
180
178
|
});
|
|
181
179
|
```
|
|
182
180
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
onAgentDetected: 'rewrite',
|
|
188
|
-
rewriteUrl: '/bot-content',
|
|
189
|
-
confidenceThreshold: 0.6,
|
|
190
|
-
});
|
|
191
|
-
```
|
|
181
|
+
By default a redirect verdict is delivered as an HTTP 401 "instruct"
|
|
182
|
+
envelope with a link header pointing the agent at the redirect URL, which
|
|
183
|
+
LLM fetchers surface as a clickable link. Set `redirectMode: 'http'` for a
|
|
184
|
+
legacy 302 response (only useful when your traffic is real browsers).
|
|
192
185
|
|
|
193
186
|
### Custom Logic
|
|
194
187
|
|
|
188
|
+
`customBlockedResponse` runs when the verdict is a block; whatever it
|
|
189
|
+
returns becomes the response:
|
|
190
|
+
|
|
195
191
|
```javascript
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
192
|
+
import { NextResponse } from 'next/server';
|
|
193
|
+
|
|
194
|
+
export default withCheckpointApi({
|
|
195
|
+
apiKey: process.env.CHECKPOINT_API_KEY,
|
|
196
|
+
customBlockedResponse: async (request, decision) => {
|
|
197
|
+
if (decision.confidence > 0.9) {
|
|
198
|
+
// High confidence: hard block
|
|
200
199
|
return NextResponse.json({ error: 'Blocked' }, { status: 403 });
|
|
201
|
-
} else if (result.confidence > 0.5) {
|
|
202
|
-
// Medium confidence - redirect to captcha
|
|
203
|
-
return NextResponse.redirect(new URL('/verify', request.url));
|
|
204
200
|
}
|
|
205
|
-
//
|
|
201
|
+
// Lower confidence: send to a verification page instead
|
|
202
|
+
return NextResponse.redirect(new URL('/verify', request.url));
|
|
206
203
|
},
|
|
207
204
|
});
|
|
208
205
|
```
|
|
209
206
|
|
|
210
|
-
## React Hooks
|
|
211
|
-
|
|
212
|
-
### useAgentDetection
|
|
213
|
-
|
|
214
|
-
> ⚠️ **Deprecated** — see banner above. Will be removed in the next
|
|
215
|
-
> minor. Migrate to `withCheckpoint` (server-side) or direct
|
|
216
|
-
> `KNOWN_AGENT_PATTERNS` consumption (client-side pattern matching).
|
|
217
|
-
|
|
218
|
-
Client-side agent detection:
|
|
219
|
-
|
|
220
|
-
```javascript
|
|
221
|
-
import { useAgentDetection } from '@kya-os/checkpoint-nextjs';
|
|
222
|
-
|
|
223
|
-
function SecurityComponent() {
|
|
224
|
-
const { detect, isDetecting, lastResult, detector } = useAgentDetection({
|
|
225
|
-
confidenceThreshold: 0.7,
|
|
226
|
-
});
|
|
227
|
-
|
|
228
|
-
useEffect(() => {
|
|
229
|
-
// Auto-detect on component mount
|
|
230
|
-
detect();
|
|
231
|
-
}, [detect]);
|
|
232
|
-
|
|
233
|
-
return (
|
|
234
|
-
<div>
|
|
235
|
-
{lastResult?.isAgent && (
|
|
236
|
-
<div className="alert">Agent detected with {lastResult.confidence} confidence</div>
|
|
237
|
-
)}
|
|
238
|
-
</div>
|
|
239
|
-
);
|
|
240
|
-
}
|
|
241
|
-
```
|
|
242
|
-
|
|
243
|
-
### useDetectionMonitor
|
|
244
|
-
|
|
245
|
-
Monitor and track detection events:
|
|
246
|
-
|
|
247
|
-
```javascript
|
|
248
|
-
import { useDetectionMonitor } from '@kya-os/checkpoint-nextjs';
|
|
249
|
-
|
|
250
|
-
function AnalyticsDashboard() {
|
|
251
|
-
const { detectionHistory, getStats, clearHistory } = useDetectionMonitor((context) => {
|
|
252
|
-
// Handle each detection
|
|
253
|
-
console.log('Detection event:', context);
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
const stats = getStats();
|
|
257
|
-
|
|
258
|
-
return (
|
|
259
|
-
<div>
|
|
260
|
-
<h2>Detection Statistics</h2>
|
|
261
|
-
<p>Total Requests: {stats.total}</p>
|
|
262
|
-
<p>Agents Detected: {stats.detected}</p>
|
|
263
|
-
<p>Detection Rate: {(stats.detectionRate * 100).toFixed(1)}%</p>
|
|
264
|
-
<p>Average Confidence: {(stats.avgConfidence * 100).toFixed(1)}%</p>
|
|
265
|
-
|
|
266
|
-
<button onClick={clearHistory}>Clear History</button>
|
|
267
|
-
</div>
|
|
268
|
-
);
|
|
269
|
-
}
|
|
270
|
-
```
|
|
271
|
-
|
|
272
207
|
## API Routes Integration
|
|
273
208
|
|
|
274
|
-
|
|
209
|
+
API routes matched by the `matcher` are protected by the middleware itself:
|
|
210
|
+
a request that your policy blocks is answered with the verdict (403,
|
|
211
|
+
redirect, or challenge) before your route handlers execute. Handlers need no
|
|
212
|
+
detection code of their own:
|
|
275
213
|
|
|
276
214
|
```javascript
|
|
277
|
-
//
|
|
278
|
-
import {
|
|
279
|
-
|
|
280
|
-
const detector = new AgentDetector();
|
|
281
|
-
|
|
282
|
-
export async function GET(request) {
|
|
283
|
-
const context = {
|
|
284
|
-
userAgent: request.headers.get('user-agent'),
|
|
285
|
-
ip: request.ip,
|
|
286
|
-
headers: Object.fromEntries(request.headers.entries()),
|
|
287
|
-
};
|
|
288
|
-
|
|
289
|
-
const result = await detector.analyze(context);
|
|
290
|
-
|
|
291
|
-
if (result.isAgent && result.confidence > 0.7) {
|
|
292
|
-
return NextResponse.json({ error: 'Automated access detected' }, { status: 403 });
|
|
293
|
-
}
|
|
215
|
+
// app/api/protected/route.js
|
|
216
|
+
import { NextResponse } from 'next/server';
|
|
294
217
|
|
|
218
|
+
export async function GET() {
|
|
219
|
+
// Only requests your policy allows ever reach this point.
|
|
295
220
|
return NextResponse.json({ data: 'Protected content' });
|
|
296
221
|
}
|
|
297
222
|
```
|
|
@@ -300,67 +225,21 @@ export async function GET(request) {
|
|
|
300
225
|
|
|
301
226
|
### Path-Specific Configuration
|
|
302
227
|
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
import { AgentDetector } from '@kya-os/checkpoint';
|
|
306
|
-
|
|
307
|
-
const detector = new AgentDetector();
|
|
308
|
-
|
|
309
|
-
export async function middleware(request: NextRequest) {
|
|
310
|
-
const { pathname } = request.nextUrl;
|
|
311
|
-
|
|
312
|
-
// Different thresholds for different paths
|
|
313
|
-
let threshold = 0.7;
|
|
314
|
-
if (pathname.startsWith('/api/')) {
|
|
315
|
-
threshold = 0.5; // More sensitive for API
|
|
316
|
-
} else if (pathname.startsWith('/admin/')) {
|
|
317
|
-
threshold = 0.9; // Less sensitive for admin (humans expected)
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
const context = {
|
|
321
|
-
userAgent: request.headers.get('user-agent') ?? undefined,
|
|
322
|
-
ip: request.ip,
|
|
323
|
-
headers: Object.fromEntries(request.headers.entries()),
|
|
324
|
-
url: request.url,
|
|
325
|
-
};
|
|
326
|
-
|
|
327
|
-
const result = await detector.analyze(context);
|
|
328
|
-
|
|
329
|
-
if (result.isAgent && result.confidence >= threshold) {
|
|
330
|
-
return NextResponse.json(
|
|
331
|
-
{ error: 'Access denied' },
|
|
332
|
-
{ status: 403 }
|
|
333
|
-
);
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
return NextResponse.next();
|
|
337
|
-
}
|
|
338
|
-
```
|
|
339
|
-
|
|
340
|
-
### Server Components
|
|
341
|
-
|
|
342
|
-
Use detection results in Server Components:
|
|
228
|
+
Use `includePaths` and `skipPaths` (glob patterns) to scope enforcement
|
|
229
|
+
without touching the `matcher`:
|
|
343
230
|
|
|
344
231
|
```javascript
|
|
345
|
-
|
|
346
|
-
import { headers } from 'next/headers';
|
|
347
|
-
import { AgentDetector } from '@kya-os/checkpoint';
|
|
348
|
-
|
|
349
|
-
export default async function Dashboard() {
|
|
350
|
-
const headersList = headers();
|
|
351
|
-
const detector = new AgentDetector();
|
|
232
|
+
import { withCheckpointApi } from '@kya-os/checkpoint-nextjs';
|
|
352
233
|
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
headers: Object.fromEntries(headersList.entries()),
|
|
356
|
-
});
|
|
234
|
+
export default withCheckpointApi({
|
|
235
|
+
apiKey: process.env.CHECKPOINT_API_KEY,
|
|
357
236
|
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
}
|
|
237
|
+
// Only enforce on these paths (overrides dashboard policy)
|
|
238
|
+
includePaths: ['/api/*', '/admin/*'],
|
|
361
239
|
|
|
362
|
-
|
|
363
|
-
|
|
240
|
+
// Never enforce on webhooks or health checks
|
|
241
|
+
skipPaths: ['/api/webhooks', '/health'],
|
|
242
|
+
});
|
|
364
243
|
```
|
|
365
244
|
|
|
366
245
|
## TypeScript Support
|
|
@@ -368,19 +247,22 @@ export default async function Dashboard() {
|
|
|
368
247
|
Full TypeScript support with proper types:
|
|
369
248
|
|
|
370
249
|
```typescript
|
|
371
|
-
import { NextRequest } from 'next/server';
|
|
372
|
-
import {
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
250
|
+
import type { NextRequest } from 'next/server';
|
|
251
|
+
import {
|
|
252
|
+
withCheckpointApi,
|
|
253
|
+
type CheckpointApiMiddlewareConfig,
|
|
254
|
+
type EnforcementDecision,
|
|
255
|
+
} from '@kya-os/checkpoint-nextjs';
|
|
256
|
+
|
|
257
|
+
const config: CheckpointApiMiddlewareConfig = {
|
|
258
|
+
onBlock: 'block',
|
|
259
|
+
onAgentDetected: async (request: NextRequest, decision: EnforcementDecision) => {
|
|
378
260
|
// Fully typed parameters
|
|
379
|
-
console.log(
|
|
261
|
+
console.log(decision.confidence);
|
|
380
262
|
},
|
|
381
263
|
};
|
|
382
264
|
|
|
383
|
-
export default
|
|
265
|
+
export default withCheckpointApi(config);
|
|
384
266
|
```
|
|
385
267
|
|
|
386
268
|
## Examples
|
|
@@ -389,10 +271,12 @@ export default agentShield(config);
|
|
|
389
271
|
|
|
390
272
|
```javascript
|
|
391
273
|
// Protect product pages from scrapers
|
|
392
|
-
|
|
393
|
-
|
|
274
|
+
import { withCheckpointApi } from '@kya-os/checkpoint-nextjs';
|
|
275
|
+
|
|
276
|
+
export default withCheckpointApi({
|
|
277
|
+
apiKey: process.env.CHECKPOINT_API_KEY,
|
|
278
|
+
onBlock: 'redirect',
|
|
394
279
|
redirectUrl: '/captcha',
|
|
395
|
-
confidenceThreshold: 0.6,
|
|
396
280
|
skipPaths: ['/api/webhooks', '/health'],
|
|
397
281
|
});
|
|
398
282
|
|
|
@@ -404,20 +288,24 @@ export const config = {
|
|
|
404
288
|
### Content Publishing
|
|
405
289
|
|
|
406
290
|
```javascript
|
|
407
|
-
// Allow search engines, block other
|
|
408
|
-
|
|
409
|
-
|
|
291
|
+
// Allow search engines through, block other agents
|
|
292
|
+
import { NextResponse } from 'next/server';
|
|
293
|
+
import { withCheckpointApi } from '@kya-os/checkpoint-nextjs';
|
|
294
|
+
|
|
295
|
+
export default withCheckpointApi({
|
|
296
|
+
apiKey: process.env.CHECKPOINT_API_KEY,
|
|
297
|
+
customBlockedResponse: async (request, decision) => {
|
|
410
298
|
const userAgent = request.headers.get('user-agent') || '';
|
|
411
299
|
|
|
412
|
-
//
|
|
300
|
+
// Let known search engines continue even when the policy blocks
|
|
413
301
|
if (/googlebot|bingbot|slurp/i.test(userAgent)) {
|
|
414
|
-
return;
|
|
302
|
+
return NextResponse.next();
|
|
415
303
|
}
|
|
416
304
|
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
305
|
+
return NextResponse.json(
|
|
306
|
+
{ error: 'Bot access restricted', reason: decision.reason },
|
|
307
|
+
{ status: 403 }
|
|
308
|
+
);
|
|
421
309
|
},
|
|
422
310
|
});
|
|
423
311
|
```
|
|
@@ -425,3 +313,8 @@ export default agentShield({
|
|
|
425
313
|
## License
|
|
426
314
|
|
|
427
315
|
MIT OR Apache-2.0
|
|
316
|
+
|
|
317
|
+
## Browser integrity
|
|
318
|
+
|
|
319
|
+
For opt-in classification, signed posture and scoped consent step-up, see the
|
|
320
|
+
[browser integrity rollout runbook](../../docs/runbooks/browser-integrity.md).
|
package/bin/setup-edge-wasm.js
CHANGED
|
@@ -139,6 +139,8 @@ export type EdgeWasmDetectionDetail =
|
|
|
139
139
|
|
|
140
140
|
import type { NextRequest } from 'next/server';
|
|
141
141
|
import type { EdgeRuntimeDetectionDetail } from '@kya-os/checkpoint-nextjs/edge-runtime-loader';
|
|
142
|
+
import type { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';
|
|
143
|
+
import { resolveClientIp } from '@kya-os/checkpoint-shared/browser';
|
|
142
144
|
import wasmModule from '../wasm/agentshield_wasm_bg.wasm?module';
|
|
143
145
|
|
|
144
146
|
type EdgeWasmDetectionDetail = EdgeRuntimeDetectionDetail;
|
|
@@ -199,6 +201,7 @@ function writeString(str: string): [number, number] {
|
|
|
199
201
|
|
|
200
202
|
export interface AgentShieldOptions {
|
|
201
203
|
enableWasm?: boolean;
|
|
204
|
+
clientIpPolicy?: ClientIpTrustPolicy;
|
|
202
205
|
onAgentDetected?: (result: EdgeWasmDetectionDetail) => void;
|
|
203
206
|
blockAgents?: boolean;
|
|
204
207
|
allowedAgents?: string[];
|
|
@@ -231,7 +234,12 @@ export function createAgentShieldMiddleware(options: AgentShieldOptions = {}) {
|
|
|
231
234
|
async detect(request: NextRequest): Promise<EdgeWasmDetectionDetail> {
|
|
232
235
|
const metadata = {
|
|
233
236
|
userAgent: request.headers.get('user-agent') || '',
|
|
234
|
-
ipAddress:
|
|
237
|
+
ipAddress:
|
|
238
|
+
resolveClientIp({
|
|
239
|
+
headers: request.headers,
|
|
240
|
+
frameworkAddress: request.ip,
|
|
241
|
+
policy: options.clientIpPolicy ?? { platform: 'direct' },
|
|
242
|
+
}).ip || '',
|
|
235
243
|
headers: Object.fromEntries(request.headers.entries()),
|
|
236
244
|
};
|
|
237
245
|
|