@autonomy/x402-bot-auth v0.1.0

Cryptographic Bot Auth
for Solana X402 Agents

RFC 9421 HTTP Message Signatures with Ed25519 โ€” seamlessly integrating Cloudflare's Web Bot Auth with the X402 payment protocol on Solana.

5 Bot Tiers
Ed25519 Signatures
RFC 9421 Compliant
4 Frameworks
x402-bot-auth

How It Works

End-to-end bot verification flow from agent to origin, through Cloudflare's edge network.

๐Ÿค–

X402 Agent

Solana Wallet

  • Signs requests with Ed25519 (RFC 9421)
  • Includes X402 payment signature
  • Auto-pays for API access
๐Ÿ›ก๏ธ

Cloudflare Edge

Bot Protection

  • Verify Web Bot Auth signature
  • Assign bot score (1-99)
  • Classify traffic tier
โš™๏ธ

X402 Middleware

Express / NestJS / Fastify

  • Check bot tier from CF headers
  • Verify X402 payment on Solana
  • Enforce tier-based access policy
โœ…

Response

Payment Validated

  • On-chain verification complete
  • Bot tier-appropriate data
  • Rate limits applied

Bot Tiers

Traffic is classified into tiers based on Cloudflare bot scores and Web Bot Auth signatures.

๐Ÿ†

Verified Bot

N/A 1000/min

Cloudflare-verified bots registered via Web Bot Auth or IP validation. Full unrestricted access.

Full Access
๐Ÿ”‘

Signed Agent

N/A 500/min

Self-hosted agents using Web Bot Auth with Ed25519 signatures. High trust, user-controlled.

Full Access
๐Ÿ‘ค

Human

30-99 100/min

Traffic classified as likely human by Cloudflare's ML and heuristic detection engines.

Full Access
โš ๏ธ

Likely Automated

2-29 10/min

Suspicious traffic patterns detected. Restricted access with heavy rate limiting.

Restricted
๐Ÿšซ

Automated

1 Blocked

Definitively automated traffic. Unverified bots blocked from all endpoints by default.

Blocked

@autonomy/x402-bot-auth

Full-featured TypeScript package for both client and server-side bot verification.

๐Ÿ” keys.ts

Ed25519KeyManager

Key generation, JWK conversion, thumbprint calculation (RFC 7638), and JWKS directory hosting.

generateKeyPair() importFromPem() importFromBase64() calculateThumbprint() createKeyDirectory() createKeyDirectoryHandler()
๐Ÿ“ก client.ts

BotAuthSigner

RFC 9421 HTTP Message Signatures for outgoing requests. Signs with Ed25519 covering @authority + signature-agent.

sign(url, method) fromPem() fromBase64() testSignature() shouldSign()
๐Ÿ›ก๏ธ server.ts

CloudflareBotMiddleware

Express/Hono middleware that parses Cloudflare headers, classifies traffic into tiers, and enforces access policies.

middleware() requireTier() requireMinScore() parseBotInfo() requireTierWithPayment()
โ˜๏ธ cloudflare.ts

CloudflareWorkerBotHandler

Edge-native Worker handler for key directory hosting, bot analytics via GraphQL API, and score-based routing.

handleRequest() createWorkerExport() handleKeyDirectory() handleBotAnalytics()
๐Ÿ“ฆ Package Structure
@autonomy/x402-bot-auth
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ index.ts       โ†’ Constants, types, tier definitions
โ”‚   โ”œโ”€โ”€ keys.ts        โ†’ Ed25519 key gen, JWK, thumbprints
โ”‚   โ”œโ”€โ”€ client.ts      โ†’ BotAuthSigner, BotVerifiedX402Client
โ”‚   โ”œโ”€โ”€ server.ts      โ†’ CloudflareBotMiddleware, BotVerificationGuard
โ”‚   โ””โ”€โ”€ cloudflare.ts  โ†’ CloudflareWorkerBotHandler
โ”œโ”€โ”€ exports:
โ”‚   โ”œโ”€โ”€ "."            โ†’ ./dist/index.js
โ”‚   โ”œโ”€โ”€ "./client"     โ†’ ./dist/client.js
โ”‚   โ”œโ”€โ”€ "./server"     โ†’ ./dist/server.js
โ”‚   โ”œโ”€โ”€ "./keys"       โ†’ ./dist/keys.js
โ”‚   โ””โ”€โ”€ "./cloudflare" โ†’ ./dist/cloudflare.js
โ””โ”€โ”€ deps: @noble/ed25519, @autonomy/x402-core

Production-Ready Examples

Five complete examples demonstrating x402 payment protocol on Solana with Cloudflare Bot Verification.

01
Beginner

Basic API

The minimum viable x402 setup. Adds micropayments ($0.001/req) to an Express API with just a few lines of code.

Express No Bot Auth
GET /api/free โ†’ Free GET /api/paid โ†’ $0.001
02
Advanced

Solex Betting

AI-powered betting platform with full Cloudflare bot verification. Tier-based access to betting endpoints.

Express โœ“ Bot Auth
03
Intermediate

Weather API

Tiered pricing ($0.001โ€“$0.01) with bot-aware access control. Demonstrates all 5 bot tiers in action.

Express โœ“ Bot Auth
/weather/free โ†’ All traffic /weather/basic โ†’ Humans + bots /weather/premium โ†’ Humans only /weather/automation โ†’ Bots only
04
Intermediate

NestJS API

Enterprise microservice pattern with BotVerificationGuard and decorators for clean, modular bot checks.

NestJS โœ“ Bot Auth
05
Intermediate

Fastify API

High-performance implementation supporting 70k+ req/s. Fastify hooks for bot verification at maximum speed.

Fastify โœ“ Bot Auth

Get Started in 5 Steps

From key generation to production deployment โ€” the complete setup for Cloudflare Web Bot Auth.

1

Generate Ed25519 Keys

Create a new key pair for signing HTTP requests per RFC 9421.

TypeScript
import { Ed25519KeyManager } from '@autonomy/x402-bot-auth/keys';

const keyPair = await Ed25519KeyManager.generateKeyPair();
console.log('Thumbprint:', keyPair.thumbprint);
console.log('Public JWK:', JSON.stringify(keyPair.jwk));

// Save private key securely
fs.writeFileSync('private-key.pem', keyPair.privatePem, { mode: 0o600 });
2

Host Key Directory

Serve your JWKS at /.well-known/http-message-signatures-directory over HTTPS.

TypeScript
app.get(
  '/.well-known/http-message-signatures-directory',
  Ed25519KeyManager.createKeyDirectoryHandler([keyPair.jwk])
);

// Response:
// Content-Type: application/http-message-signatures-directory+json
// { "keys": [{ "kty": "OKP", "crv": "Ed25519", "x": "..." }] }
3

Register with Cloudflare

Submit your bot for verification through Cloudflare's dashboard.

Dashboard โ†’ Manage Account โ†’ Configurations โ†’ Bot Submission Form
Set Verification Method to "Request Signature"
Enter your key directory URL
Select category (AI Assistant, Webhooks, Security, etc.)
Submit โ€” verification takes 24-48 hours
4

Sign Requests (Client)

Attach RFC 9421 signatures to every outgoing HTTP request.

TypeScript
import { BotAuthSigner } from '@autonomy/x402-bot-auth/client';

const signer = BotAuthSigner.fromPem(
  fs.readFileSync('./private-key.pem', 'utf-8'),
  'https://your-domain.com/.well-known/http-message-signatures-directory'
);

const headers = signer.sign('https://api.example.com/data', 'GET');
const response = await fetch('https://api.example.com/data', { headers });
5

Verify on Server

Add bot-tier enforcement to your X402 payment endpoints.

TypeScript
import { CloudflareBotMiddleware, BOT_TIERS } from '@autonomy/x402-bot-auth';

const bot = new CloudflareBotMiddleware({
  allowVerifiedBots: true,
  allowSignedAgents: true,
});

app.use(bot.middleware());

app.get('/api/premium',
  x402.requirePayment(0.01),
  bot.requireMinScore(30),
  handler
);

Cloudflare Headers & Protection

Complete reference for Cloudflare bot management headers and protection tier capabilities.

Cloudflare Headers

Header Description Tier Required
cf-bot-score1-99 bot likelihoodEnterprise
cf-verified-bot"true" if Cloudflare-verifiedPro+
cf-bot-managedDetection resultPro+
cf-bot-tagsClassification tagsEnterprise
cf-ja3-hashTLS fingerprint hashEnterprise
cf-ja4JA4 TLS fingerprintEnterprise
cf-connecting-ipClient IPAll plans
cf-ipcountryCountry codeAll plans

Protection Tiers

Feature Free Pro Enterprise
Basic Blockingโœ“โœ“โœ“
Bot Analyticsโœ—BasicFull
Granular Scoresโœ—Groupings1-99
Verified BotsBasicโœ“โœ“
Custom Rulesโœ—โœ“โœ“
JA3/JA4โœ—โœ—โœ“
Bot Tagsโœ—โœ—โœ“

Troubleshooting

Missing Signature-Agent

Ensure header value is enclosed in double quotes and is an HTTPS URL.

Timestamp Expired

Use expirySeconds: 60 or less. Sync system clock via NTP.

Key Mismatch

Verify keyid matches the JWK thumbprint calculated per RFC 7638.

Non-ASCII Values

Only sign ASCII headers. Use @query not @query-params.

401 from Test Endpoint

Key is registered but signature base is wrong. Check the signing algorithm.

400 from Test Endpoint

Header format error. Check the Signature-Input syntax carefully.

Anatomy of a Web Bot Auth Signature

Three headers are required on every authenticated request.

Signature-Agent

Points to the JWKS key directory URL. Cloudflare fetches this to retrieve your public key.

"https://your-domain.com/.well-known/http-message-signatures-directory"

Signature-Input

Defines covered components and signature parameters per RFC 9421.

sig1=("@authority" "signature-agent");created=1735689600;keyid="<thumbprint>";alg="ed25519";expires=1735693200;nonce="<random>";tag="web-bot-auth"
@authority Target domain created Unix timestamp keyid JWK Thumbprint alg ed25519 expires โ‰ค60s recommended nonce Replay protection tag web-bot-auth

Signature

The Ed25519 signature over the signature base string, base64-encoded.

sig1=:<base64-ed25519-signature>: