@dupecom/botcha-verify

中文文档
0.2.0发布于 2026/02/16MITTypeScriptES Module近 30 天下载 8292

Server-side verification middleware for BOTCHA JWT tokens

原始使用文档
文档目录19 节
  1. Installation
  2. Features
  3. Usage
  4. JWKS Verification (Recommended)
  5. Legacy: Shared Secret Verification
  6. Express Middleware
  7. Hono Middleware
  8. API
  9. verifyBotchaToken(token, options, clientIp?)
  10. BotchaVerifyOptions
  11. BotchaTokenPayload
  12. Token Validation
  13. Migration from Shared Secret to JWKS
  14. Custom Error Handling
  15. Token Revocation
  16. Client IP Extraction
  17. Security Notes
  18. License
  19. Links

@dupecom/botcha-verify

Server-side verification middleware for BOTCHA JWT tokens.

Installation

npm install @dupecom/botcha-verify
# or
yarn add @dupecom/botcha-verify
# or
bun add @dupecom/botcha-verify

Features

  • JWKS verification (ES256) — no shared secret needed, keys rotate automatically
  • HS256 shared-secret verification (legacy, still supported)
  • Automatic expiry checking
  • Audience claim validation
  • Issuer validation (botcha.ai) in JWKS mode
  • Client IP binding support
  • Token revocation checking (optional)
  • Express & Hono middleware
  • TypeScript support with full type definitions
  • Custom error handlers

Usage

The recommended approach fetches BOTCHA's public key from the JWKS endpoint. No shared secret to manage — key rotation is handled automatically.

import { verifyBotchaToken } from '@dupecom/botcha-verify';

const result = await verifyBotchaToken(token, {
  jwksUrl: 'https://botcha.ai/.well-known/jwks',
  audience: 'https://api.example.com',
});

if (result.valid) {
  console.log('Token valid! Challenge:', result.payload.sub);
  console.log('Solve time:', result.payload.solveTime, 'ms');
} else {
  console.error('Token invalid:', result.error);
}

Legacy: Shared Secret Verification

Still supported for existing integrations using HS256 tokens.

import { verifyBotchaToken } from '@dupecom/botcha-verify';

const result = await verifyBotchaToken(token, {
  secret: process.env.BOTCHA_SECRET!,
  audience: 'https://api.example.com',
  requireIp: true,
});

Express Middleware

import express from 'express';
import { botchaVerify } from '@dupecom/botcha-verify/express';

const app = express();

// RECOMMENDED: JWKS verification
app.use('/api', botchaVerify({
  jwksUrl: 'https://botcha.ai/.well-known/jwks',
  audience: 'https://api.example.com',
}));

// LEGACY: Shared secret
app.use('/api', botchaVerify({
  secret: process.env.BOTCHA_SECRET!,
  audience: 'https://api.example.com',
  requireIp: true,
}));

app.get('/api/protected', (req, res) => {
  console.log('Challenge ID:', req.botcha?.sub);
  console.log('Solve time:', req.botcha?.solveTime);
  res.json({ message: 'Success' });
});

Hono Middleware

import { Hono } from 'hono';
import { botchaVerify } from '@dupecom/botcha-verify/hono';
import type { BotchaTokenPayload } from '@dupecom/botcha-verify';

const app = new Hono<{ Variables: { botcha: BotchaTokenPayload } }>();

// RECOMMENDED: JWKS verification
app.use('/api/*', botchaVerify({
  jwksUrl: 'https://botcha.ai/.well-known/jwks',
  audience: 'https://api.example.com',
}));

// LEGACY: Shared secret
app.use('/api/*', botchaVerify({
  secret: env.BOTCHA_SECRET,
  audience: 'https://api.example.com',
  requireIp: true,
}));

app.get('/api/protected', (c) => {
  const botcha = c.get('botcha');
  console.log('Challenge ID:', botcha.sub);
  console.log('Solve time:', botcha.solveTime);
  return c.json({ message: 'Success' });
});

API

verifyBotchaToken(token, options, clientIp?)

Verify a BOTCHA JWT token.

Parameters:

  • token (string): JWT token to verify
  • options (BotchaVerifyOptions): Verification options (at least one of secret or jwksUrl required)
  • clientIp (string, optional): Client IP for validation

Returns: Promise<VerificationResult>

interface VerificationResult {
  valid: boolean;
  payload?: BotchaTokenPayload;
  error?: string;
}

BotchaVerifyOptions

interface BotchaVerifyOptions {
  // JWKS URL for ES256 verification (recommended)
  jwksUrl?: string;

  // Cache JWKS keys for this many seconds (default: 3600)
  jwksCacheTtl?: number;

  // JWT secret for HS256 verification (legacy)
  secret?: string;

  // At least one of `secret` or `jwksUrl` must be provided.
  // If both are provided, JWKS is tried first, falling back to secret.

  // Optional: Expected audience claim
  audience?: string;

  // Optional: Validate client IP claim
  requireIp?: boolean;

  // Optional: Custom error handler
  onError?: (error: string, context: VerificationContext) => void | Promise<void>;

  // Optional: Token revocation check
  checkRevocation?: (jti: string) => Promise<boolean>;
}

BotchaTokenPayload

interface BotchaTokenPayload {
  sub: string;        // Challenge ID
  iat: number;        // Issued at
  exp: number;        // Expires at
  jti: string;        // JWT ID
  type: 'botcha-verified';
  solveTime: number;  // Solve time in ms
  aud?: string;       // Optional audience
  client_ip?: string; // Optional client IP
}

Token Validation

The verifier checks:

  1. Signature: ES256 via JWKS (recommended) or HS256 via shared secret (legacy)
  2. Expiry: Token must not be expired
  3. Type: Token must be botcha-verified (not botcha-refresh)
  4. Issuer (JWKS mode): Token iss must be botcha.ai
  5. Audience (optional): Token aud must match expected audience
  6. Client IP (optional): Token client_ip must match request IP
  7. Revocation (optional): Token JTI must not be revoked

Migration from Shared Secret to JWKS

Replace secret with jwksUrl in your configuration. During the transition period you can provide both — JWKS is tried first with a fallback to the secret:

// Transition: both methods supported
app.use('/api', botchaVerify({
  jwksUrl: 'https://botcha.ai/.well-known/jwks',
  secret: process.env.BOTCHA_SECRET!, // fallback during migration
  audience: 'https://api.example.com',
}));

// After migration: JWKS only
app.use('/api', botchaVerify({
  jwksUrl: 'https://botcha.ai/.well-known/jwks',
  audience: 'https://api.example.com',
}));

Custom Error Handling

app.use('/api', botchaVerify({
  jwksUrl: 'https://botcha.ai/.well-known/jwks',
  onError: (error, context) => {
    console.error('Token verification failed:', error);
    console.error('Context:', context);
  },
}));

Token Revocation

Implement custom revocation checking:

import { verifyBotchaToken } from '@dupecom/botcha-verify';

const result = await verifyBotchaToken(token, {
  jwksUrl: 'https://botcha.ai/.well-known/jwks',
  checkRevocation: async (jti) => {
    const isRevoked = await db.revokedTokens.exists(jti);
    return isRevoked;
  },
});

Client IP Extraction

The middleware automatically extracts client IP from:

  • Cloudflare: CF-Connecting-IP header
  • Proxies: X-Forwarded-For header (first IP)
  • Load Balancers: X-Real-IP header
  • Direct: req.ip (Express) or fallback (Hono)

Security Notes

  • JWKS: Public keys are cached and rotated automatically by the jose library
  • Fail-open: Revocation checks fail-open if the check throws an error
  • IP validation: Only enabled if requireIp: true is set
  • Audience: Strongly recommended for multi-API deployments
  • Issuer: Automatically validated as botcha.ai in JWKS mode

License

MIT

版本与发布记录

@dupecom/botcha-verify 共发布 2 个版本,首次发布于 2026/02/15;过去 12 个月发布了 2 个版本。

版本发布日期距今
0.2.0latest2026/02/168 个月前
0.1.02026/02/158 个月前

关于 @dupecom/botcha-verify 的常见问题

@dupecom/botcha-verify 是什么?

Server-side verification middleware for BOTCHA JWT tokens

如何安装 @dupecom/botcha-verify?

在项目目录运行 npm install @dupecom/botcha-verify,或使用 pnpm add / yarn add / bun add。

@dupecom/botcha-verify 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dupecom/botcha-verify 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@dupecom/botcha-verify 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dupecom/botcha-verify 可以商用吗?

@dupecom/botcha-verify 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dupecom/botcha-verify 的下载量有多少?

根据 npm 官方下载统计,@dupecom/botcha-verify 在 2026/10/13 – 2026/11/11 这 30 天内被下载 8,292 次,日均约 276 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dupecom/botcha-verify 还在维护吗?

最新版本 0.2.0 发布于 2026/02/16(8 个月前);至今共发布 2 个版本,其中过去 12 个月发布了 2 个;首次发布于 2026/02/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。