@kya-os/verifier
v1.4.11
Published
Isomorphic verifier middleware for XMCP-I proof validation
Readme
@kya-os/verifier
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.
Features
- Isomorphic Core: Works in both Cloudflare Workers and Express environments
- Ed25519 Signature Verification: Cryptographically secure proof validation using detached JWS
- DID Document Resolution: Automatic resolution and caching of DID documents
- KTA Delegation Checking: Integration with Know-That-AI for delegation verification
- Comprehensive Error Handling: Structured errors with detailed remediation guidance
- Production-Ready Performance: Built-in caching and optimization for edge deployment
- Security-First Design: Comprehensive validation and audit logging
Installation
npm install @kya-os/verifierQuick Start
Cloudflare Worker
import { verifyWorker, applyVerificationToResponse } from "@kya-os/verifier";
export default {
async fetch(request: Request): Promise<Response> {
const result = await verifyWorker(request, {
ktaBaseUrl: "https://knowthat.ai",
enableDelegationCheck: true,
});
if (!result.success) {
return applyVerificationToResponse(result);
}
// Agent is verified - process request
console.log("Verified agent:", result.agentContext?.did);
const response = await handleVerifiedRequest(request, result.agentContext);
return applyVerificationToResponse(result, response);
},
};Express
import express from "express";
import {
verifyExpress,
isAuthenticated,
getAgentContext,
} from "@kya-os/verifier";
const app = express();
// Apply verifier middleware
app.use(
verifyExpress({
ktaBaseUrl: "https://knowthat.ai",
enableDelegationCheck: true,
})
);
app.post("/api/tools/call", (req, res) => {
if (!isAuthenticated(req)) {
return res.status(401).json({ error: "Not authenticated" });
}
const agent = getAgentContext(req);
console.log("Verified agent:", agent?.did);
// Handle tool call with verified agent context
res.json({ success: true, agent: agent?.did });
});API Reference
Core Verifier
VerifierCore
The isomorphic core that handles proof verification logic.
import { VerifierCore } from "@kya-os/verifier";
const verifier = new VerifierCore({
ktaBaseUrl: "https://knowthat.ai",
enableDelegationCheck: true,
clockSkewTolerance: 120, // seconds
sessionTimeout: 1800, // seconds
allowMockData: false, // for testing only
});
const result = await verifier.verify({
proof: detachedProof,
audience: "example.com",
timestamp: Math.floor(Date.now() / 1000),
});Configuration Options
ktaBaseUrl: KTA base URL for delegation checking (default: "https://knowthat.ai")enableDelegationCheck: Enable delegation verification (default: true)clockSkewTolerance: Clock skew tolerance in seconds (default: 120)sessionTimeout: Session timeout in seconds (default: 1800)allowMockData: Allow mock data for testing (default: false)didCacheTtl: DID document cache TTL in seconds (default: 300)delegationCacheTtl: Delegation cache TTL in seconds (default: 60)
Cloudflare Worker Integration
verifyWorker(request, config?)
Verifies a Worker request and returns verification result.
const result = await verifyWorker(request, {
ktaBaseUrl: "https://knowthat.ai",
});
if (result.success) {
// Access result.headers and result.agentContext
} else {
// Handle result.error
}applyVerificationToResponse(result, response?)
Applies verification result to a Response object.
// Return error response
if (!result.success) {
return applyVerificationToResponse(result);
}
// Apply headers to existing response
const response = new Response("OK");
return applyVerificationToResponse(result, response);Express Integration
verifyExpress(config?)
Express middleware for proof verification.
app.use(
verifyExpress({
ktaBaseUrl: "https://knowthat.ai",
enableDelegationCheck: true,
})
);Helper Functions
// Check if request is authenticated
if (isAuthenticated(req)) {
// Request has verified agent
}
// Get agent context
const agent = getAgentContext(req);
if (agent) {
console.log("Agent DID:", agent.did);
console.log("Agent scopes:", agent.scopes);
}Verification Process
The verifier performs comprehensive validation in the following order:
- Proof Structure Validation: Validates JWS format and required metadata fields
- Timestamp Validation: Checks timestamp against configurable clock skew tolerance
- Audience Validation: Ensures proof audience matches request audience
- Signature Verification: Verifies Ed25519 signature using DID document public key
- Delegation Checking: Validates delegation status via KTA (if enabled and present)
Headers Injected
On successful verification, the following headers are injected:
X-Agent-DID: Agent's decentralized identifierX-Agent-KeyId: Key identifier used for signingX-Agent-Session: Session identifierX-Agent-Confidence: Always "verified" for successful verificationX-Agent-Registry: URL to agent's registry page for traceabilityX-Agent-Verified-At: Unix timestamp of verificationX-Agent-Scopes: Comma-separated list of scopes (if present)X-Agent-Delegation-Ref: Delegation reference (if present)
Error Handling
The verifier returns structured errors with detailed information:
{
success: false,
error: {
code: "XMCP_I_EBADPROOF",
message: "Invalid proof: malformed requestHash",
httpStatus: 400,
details: {
reason: "requestHash must be in format 'sha256:<64-char-hex>'",
expected: "sha256:[a-f0-9]{64}",
received: "invalid-hash",
remediation: "Check proof generation and hash format"
}
}
}Error Codes
XMCP_I_EBADPROOF: Invalid or malformed proofXMCP_I_EHANDSHAKE: Handshake validation failed (timestamp/audience)XMCP_I_ENOIDENTITY: No proof found in requestXMCP_I_EVERIFY: Unexpected verification error
Security Considerations
- Clock Synchronization: Ensure server clocks are synchronized (NTP recommended)
- HTTPS Only: Always use HTTPS in production to protect proof transmission
- Cache Security: DID documents and delegation status are cached with appropriate TTLs
- Error Information: Error messages provide debugging information without leaking sensitive data
- Audit Logging: All verification attempts are logged for security monitoring
Performance
- Caching: DID documents and delegation responses are cached to reduce network calls
- Edge Optimization: Designed for edge deployment with minimal cold start overhead
- Timeout Handling: Network requests have appropriate timeouts to prevent hanging
- Memory Management: Automatic cache cleanup prevents memory leaks
Testing
The package includes comprehensive test coverage and supports mock data for testing:
const verifier = new VerifierCore({
allowMockData: true, // Enables mock DIDs and delegations
});
// Mock DIDs: did:test:*
// Mock delegations: mock:active, mock:revokedContributing
This package is part of the XMCP-I ecosystem. See the main repository for contribution guidelines.
License
MIT
