npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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/verifier

Quick 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:

  1. Proof Structure Validation: Validates JWS format and required metadata fields
  2. Timestamp Validation: Checks timestamp against configurable clock skew tolerance
  3. Audience Validation: Ensures proof audience matches request audience
  4. Signature Verification: Verifies Ed25519 signature using DID document public key
  5. 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 identifier
  • X-Agent-KeyId: Key identifier used for signing
  • X-Agent-Session: Session identifier
  • X-Agent-Confidence: Always "verified" for successful verification
  • X-Agent-Registry: URL to agent's registry page for traceability
  • X-Agent-Verified-At: Unix timestamp of verification
  • X-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 proof
  • XMCP_I_EHANDSHAKE: Handshake validation failed (timestamp/audience)
  • XMCP_I_ENOIDENTITY: No proof found in request
  • XMCP_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:revoked

Contributing

This package is part of the XMCP-I ecosystem. See the main repository for contribution guidelines.

License

MIT