@kya-os/verifier 1.3.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/README.md ADDED
@@ -0,0 +1,265 @@
1
+ # @kya-os/verifier
2
+
3
+ Isomorphic verifier middleware for XMCP-I proof validation. This package provides the trust infrastructure for AI agent interactions by verifying agent identity, validating cryptographic proofs, and injecting trusted headers for downstream services.
4
+
5
+ ## Features
6
+
7
+ - **Isomorphic Core**: Works in both Cloudflare Workers and Express environments
8
+ - **Ed25519 Signature Verification**: Cryptographically secure proof validation using detached JWS
9
+ - **DID Document Resolution**: Automatic resolution and caching of DID documents
10
+ - **KTA Delegation Checking**: Integration with Know-That-AI for delegation verification
11
+ - **Comprehensive Error Handling**: Structured errors with detailed remediation guidance
12
+ - **Production-Ready Performance**: Built-in caching and optimization for edge deployment
13
+ - **Security-First Design**: Comprehensive validation and audit logging
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @kya-os/verifier
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ ### Cloudflare Worker
24
+
25
+ ```typescript
26
+ import { verifyWorker, applyVerificationToResponse } from "@kya-os/verifier";
27
+
28
+ export default {
29
+ async fetch(request: Request): Promise<Response> {
30
+ const result = await verifyWorker(request, {
31
+ ktaBaseUrl: "https://knowthat.ai",
32
+ enableDelegationCheck: true,
33
+ });
34
+
35
+ if (!result.success) {
36
+ return applyVerificationToResponse(result);
37
+ }
38
+
39
+ // Agent is verified - process request
40
+ console.log("Verified agent:", result.agentContext?.did);
41
+ const response = await handleVerifiedRequest(request, result.agentContext);
42
+ return applyVerificationToResponse(result, response);
43
+ },
44
+ };
45
+ ```
46
+
47
+ ### Express
48
+
49
+ ```typescript
50
+ import express from "express";
51
+ import {
52
+ verifyExpress,
53
+ isAuthenticated,
54
+ getAgentContext,
55
+ } from "@kya-os/verifier";
56
+
57
+ const app = express();
58
+
59
+ // Apply verifier middleware
60
+ app.use(
61
+ verifyExpress({
62
+ ktaBaseUrl: "https://knowthat.ai",
63
+ enableDelegationCheck: true,
64
+ })
65
+ );
66
+
67
+ app.post("/api/tools/call", (req, res) => {
68
+ if (!isAuthenticated(req)) {
69
+ return res.status(401).json({ error: "Not authenticated" });
70
+ }
71
+
72
+ const agent = getAgentContext(req);
73
+ console.log("Verified agent:", agent?.did);
74
+
75
+ // Handle tool call with verified agent context
76
+ res.json({ success: true, agent: agent?.did });
77
+ });
78
+ ```
79
+
80
+ ## API Reference
81
+
82
+ ### Core Verifier
83
+
84
+ #### `VerifierCore`
85
+
86
+ The isomorphic core that handles proof verification logic.
87
+
88
+ ```typescript
89
+ import { VerifierCore } from "@kya-os/verifier";
90
+
91
+ const verifier = new VerifierCore({
92
+ ktaBaseUrl: "https://knowthat.ai",
93
+ enableDelegationCheck: true,
94
+ clockSkewTolerance: 120, // seconds
95
+ sessionTimeout: 1800, // seconds
96
+ allowMockData: false, // for testing only
97
+ });
98
+
99
+ const result = await verifier.verify({
100
+ proof: detachedProof,
101
+ audience: "example.com",
102
+ timestamp: Math.floor(Date.now() / 1000),
103
+ });
104
+ ```
105
+
106
+ #### Configuration Options
107
+
108
+ - `ktaBaseUrl`: KTA base URL for delegation checking (default: "https://knowthat.ai")
109
+ - `enableDelegationCheck`: Enable delegation verification (default: true)
110
+ - `clockSkewTolerance`: Clock skew tolerance in seconds (default: 120)
111
+ - `sessionTimeout`: Session timeout in seconds (default: 1800)
112
+ - `allowMockData`: Allow mock data for testing (default: false)
113
+ - `didCacheTtl`: DID document cache TTL in seconds (default: 300)
114
+ - `delegationCacheTtl`: Delegation cache TTL in seconds (default: 60)
115
+
116
+ ### Cloudflare Worker Integration
117
+
118
+ #### `verifyWorker(request, config?)`
119
+
120
+ Verifies a Worker request and returns verification result.
121
+
122
+ ```typescript
123
+ const result = await verifyWorker(request, {
124
+ ktaBaseUrl: "https://knowthat.ai",
125
+ });
126
+
127
+ if (result.success) {
128
+ // Access result.headers and result.agentContext
129
+ } else {
130
+ // Handle result.error
131
+ }
132
+ ```
133
+
134
+ #### `applyVerificationToResponse(result, response?)`
135
+
136
+ Applies verification result to a Response object.
137
+
138
+ ```typescript
139
+ // Return error response
140
+ if (!result.success) {
141
+ return applyVerificationToResponse(result);
142
+ }
143
+
144
+ // Apply headers to existing response
145
+ const response = new Response("OK");
146
+ return applyVerificationToResponse(result, response);
147
+ ```
148
+
149
+ ### Express Integration
150
+
151
+ #### `verifyExpress(config?)`
152
+
153
+ Express middleware for proof verification.
154
+
155
+ ```typescript
156
+ app.use(
157
+ verifyExpress({
158
+ ktaBaseUrl: "https://knowthat.ai",
159
+ enableDelegationCheck: true,
160
+ })
161
+ );
162
+ ```
163
+
164
+ #### Helper Functions
165
+
166
+ ```typescript
167
+ // Check if request is authenticated
168
+ if (isAuthenticated(req)) {
169
+ // Request has verified agent
170
+ }
171
+
172
+ // Get agent context
173
+ const agent = getAgentContext(req);
174
+ if (agent) {
175
+ console.log("Agent DID:", agent.did);
176
+ console.log("Agent scopes:", agent.scopes);
177
+ }
178
+ ```
179
+
180
+ ## Verification Process
181
+
182
+ The verifier performs comprehensive validation in the following order:
183
+
184
+ 1. **Proof Structure Validation**: Validates JWS format and required metadata fields
185
+ 2. **Timestamp Validation**: Checks timestamp against configurable clock skew tolerance
186
+ 3. **Audience Validation**: Ensures proof audience matches request audience
187
+ 4. **Signature Verification**: Verifies Ed25519 signature using DID document public key
188
+ 5. **Delegation Checking**: Validates delegation status via KTA (if enabled and present)
189
+
190
+ ## Headers Injected
191
+
192
+ On successful verification, the following headers are injected:
193
+
194
+ - `X-Agent-DID`: Agent's decentralized identifier
195
+ - `X-Agent-KeyId`: Key identifier used for signing
196
+ - `X-Agent-Session`: Session identifier
197
+ - `X-Agent-Confidence`: Always "verified" for successful verification
198
+ - `X-Agent-Registry`: URL to agent's registry page for traceability
199
+ - `X-Agent-Verified-At`: Unix timestamp of verification
200
+ - `X-Agent-Scopes`: Comma-separated list of scopes (if present)
201
+ - `X-Agent-Delegation-Ref`: Delegation reference (if present)
202
+
203
+ ## Error Handling
204
+
205
+ The verifier returns structured errors with detailed information:
206
+
207
+ ```typescript
208
+ {
209
+ success: false,
210
+ error: {
211
+ code: "XMCP_I_EBADPROOF",
212
+ message: "Invalid proof: malformed requestHash",
213
+ httpStatus: 400,
214
+ details: {
215
+ reason: "requestHash must be in format 'sha256:<64-char-hex>'",
216
+ expected: "sha256:[a-f0-9]{64}",
217
+ received: "invalid-hash",
218
+ remediation: "Check proof generation and hash format"
219
+ }
220
+ }
221
+ }
222
+ ```
223
+
224
+ ### Error Codes
225
+
226
+ - `XMCP_I_EBADPROOF`: Invalid or malformed proof
227
+ - `XMCP_I_EHANDSHAKE`: Handshake validation failed (timestamp/audience)
228
+ - `XMCP_I_ENOIDENTITY`: No proof found in request
229
+ - `XMCP_I_EVERIFY`: Unexpected verification error
230
+
231
+ ## Security Considerations
232
+
233
+ - **Clock Synchronization**: Ensure server clocks are synchronized (NTP recommended)
234
+ - **HTTPS Only**: Always use HTTPS in production to protect proof transmission
235
+ - **Cache Security**: DID documents and delegation status are cached with appropriate TTLs
236
+ - **Error Information**: Error messages provide debugging information without leaking sensitive data
237
+ - **Audit Logging**: All verification attempts are logged for security monitoring
238
+
239
+ ## Performance
240
+
241
+ - **Caching**: DID documents and delegation responses are cached to reduce network calls
242
+ - **Edge Optimization**: Designed for edge deployment with minimal cold start overhead
243
+ - **Timeout Handling**: Network requests have appropriate timeouts to prevent hanging
244
+ - **Memory Management**: Automatic cache cleanup prevents memory leaks
245
+
246
+ ## Testing
247
+
248
+ The package includes comprehensive test coverage and supports mock data for testing:
249
+
250
+ ```typescript
251
+ const verifier = new VerifierCore({
252
+ allowMockData: true, // Enables mock DIDs and delegations
253
+ });
254
+
255
+ // Mock DIDs: did:test:*
256
+ // Mock delegations: mock:active, mock:revoked
257
+ ```
258
+
259
+ ## Contributing
260
+
261
+ This package is part of the XMCP-I ecosystem. See the main repository for contribution guidelines.
262
+
263
+ ## License
264
+
265
+ MIT
@@ -0,0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