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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@btx-tools/middleware-fastify

v1.1.0

Published

Fastify plugin for @btx-tools/challenges-sdk — drop-in BTX service-challenge admission gate

Readme

@btx-tools/middleware-fastify

Drop-in Fastify admission gate backed by BTX service challenges. Same flow + ergonomics as @btx-tools/middleware-express, tailored to Fastify's preHandler hook + reply API.

📖 API Reference — TypeDoc for all @btx-tools/* SDK packages.

New to BTX service challenges? This puts a chain-anchored proof-of-work checkpoint in front of a route — the caller spends a few seconds of verifiable compute instead of a CAPTCHA or a signup. Concept + issue → solve → redeem flow: see the core SDK README.

Prerequisites: you need a reachable BTX node (btxd) — non-mining for fast (~1–4 s) solves; there's no hosted endpoint, so you can't use this with zero BTX infrastructure. See core → Prerequisites.

End-to-end example: a runnable adopter example is in examples/02-express-gate (Express-based; the wiring shape is identical for Fastify — swap app.post(path, btxAdmission(...)) for fastify.post(path, { preHandler: btxAdmission(...) })). A Fastify-native parity example is queued for the SDK Phase 3.5 roadmap.

pnpm add @btx-tools/middleware-fastify @btx-tools/challenges-sdk fastify

Quickstart

import Fastify from 'fastify';
import { BtxChallengeClient } from '@btx-tools/challenges-sdk';
import { btxAdmission } from '@btx-tools/middleware-fastify';

const client = new BtxChallengeClient({
  rpcUrl: 'http://127.0.0.1:19334',
  rpcAuth: { user: 'rpcuser', pass: 'rpcpass' },
});

const fastify = Fastify();

fastify.post(
  '/v1/generate',
  {
    preHandler: btxAdmission({
      client,
      purpose: 'ai_inference_gate',
      resource: (req) => `model:${(req.body as any).model}|route:${req.url}`,
      subject: (req) => `tenant:${(req.body as any).tenant_id}`,
      issueParams: { target_solve_time_s: 1.0, expires_in_s: 60 },
      onError: (err, req) => req.log.error({ err }, 'btx admission error'),
    }),
  },
  async (request, reply) => {
    // request.btx?.result is populated with the redeem VerifyResult
    return { ok: true, generated: '...' };
  },
);

await fastify.listen({ port: 3000 });

How it works

Stateless echo-the-challenge flow:

  1. First request has no proof headers → middleware calls client.issue() → replies 402 Payment Required with X-BTX-Challenge header containing the challenge JSON + a body listing the headers the client should add on retry.
  2. Client solves the challenge (locally or via RPC) and retries with X-BTX-Challenge (echoed), X-BTX-Proof-Nonce, X-BTX-Proof-Digest.
  3. Middleware calls client.redeem() → if result.valid === true, sets request.btx = { result } and runs the route handler. Else replies 403.

No server-side challenge store; the client echoes the challenge back. Scales horizontally. Cons: the challenge JSON (~3-5 KB) lives in an HTTP header, so check your reverse proxy's large_client_header_buffers / equivalent.

API

btxAdmission(opts): preHandlerAsyncHookHandler

Returns a Fastify preHandler hook to attach per-route.

Options

| Field | Type | Notes | | ---------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | client | BtxChallengeClient | required. Construct once at boot. | | purpose | string \| (req) => string | required. Logical purpose label. | | resource | string \| (req) => string | required. Resource identifier. | | subject | string \| (req) => string | required. Subject identifier. | | issueParams | Partial<IssueParams> | optional. Extra params forwarded to client.issue(). | | onAdmit | (req, result) => void | optional. Fires on successful admission. | | onError | (err, req) => void | optional. Fires when client.issue() or client.redeem() throws, exactly once before the preHandler re-throws. Use for logging. Audit ref: D-1. | | isProofPresent | (req) => boolean | optional. Override the default headers[x-btx-challenge] && headers[x-btx-proof-nonce] && headers[x-btx-proof-digest] check. |

Header constants

| Constant | Value | | --------------------- | ---------------------- | | HEADER_CHALLENGE | 'x-btx-challenge' | | HEADER_CHALLENGE_ID | 'x-btx-challenge-id' | | HEADER_PROOF_NONCE | 'x-btx-proof-nonce' | | HEADER_PROOF_DIGEST | 'x-btx-proof-digest' |

(Fastify lowercases incoming header names, hence the lowercase form here. Outgoing reply.header() accepts any case.)

Error handling

When client.issue() or client.redeem() throws (e.g., btxd RPC down, network error), the middleware:

  1. Calls opts.onError(err, req) if provided
  2. Re-throws — Fastify's standard error-handling pipeline kicks in (default 500, or whatever your error handler returns)

For HTTPS / production deployments, terminate TLS at a reverse proxy (Caddy, nginx, Cloudflare) in front of btxd. Do NOT expose btxd's RPC port directly to the public internet.

CORS

The X-BTX-Challenge, X-BTX-Proof-Nonce, and X-BTX-Proof-Digest headers are custom, which triggers a CORS preflight for any browser-originated fetch. Configure @fastify/cors:

import cors from '@fastify/cors';
await fastify.register(cors, {
  origin: 'https://your-frontend.example',
  allowedHeaders: [
    'content-type',
    'x-btx-challenge',
    'x-btx-challenge-id',
    'x-btx-proof-nonce',
    'x-btx-proof-digest',
  ],
  exposedHeaders: [
    'x-btx-challenge', // so the browser can READ the 402's challenge header
  ],
});

Without exposedHeaders including x-btx-challenge, the browser sees the 402 status but cannot read the challenge JSON from the response header.

Requirements

  • Node.js ≥ 18.17
  • Fastify ^4.0.0 or ^5.0.0 (peer dep)
  • @btx-tools/challenges-sdk ^0.0.4 (peer dep)

License

MIT. See LICENSE.