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

@chdlabs/b402

v1.0.0

Published

Official Node.js SDK for HTTP 402 Micropayments with Post-Quantum Cryptography (NIST FIPS 204 ML-DSA-44)

Readme

@chdlabs/b402 - Node.js SDK for HTTP 402 Micropayments

The official Node.js SDK for the b402 HTTP 402 Micropayment Platform. Protect your SaaS endpoints with pay-per-call pricing using NIST FIPS 204 Post-Quantum Cryptography (ML-DSA-44), or consume paid APIs with automatic 402 payment negotiation.

npm version License: MIT Node.js: >=24.0.0


Installation

npm install @chdlabs/b402

Requirement: Requires Node.js >= 24.0.0 for native NIST FIPS 204 ML-DSA-44 post-quantum lattice signature verification.


Understanding serviceId & Supported URNs

In the b402 micropayment protocol, serviceId is the unique identifier representing the target provider service:

  • Canonical Address: urn:b402:<slug> (e.g. urn:b402:quoteoftheday, urn:b402:ztrust-verify).
  • Provider Role: The provider registers their service in the Provider Center, copies their canonical serviceId, and passes it to B402PaymentRequired({ serviceId }).
  • 402 Challenge: When an unauthenticated client calls a protected endpoint, B402PaymentRequired challenges the caller with WWW-Authenticate: B402 serviceId="..." and a JSON challenge containing serviceId, fee, currency, and ledgerUrl.
  • Consumer Role: The consumer client (B402Client or manual script) reads challenge.serviceId and submits { callerId, serviceId, amount } to the Central Ledger /pay endpoint to settle the micropayment.

Supported URN Formats & When to Use

Both B402PaymentRequired and the Central Ledger support multiple URN schemes for maximum flexibility, domain trust verification, and machine pipeline stability:

| URN Format | Example | When to Use | | :--- | :--- | :--- | | Canonical Slug URN | urn:b402:<slug>(e.g. urn:b402:quoteoftheday, urn:b402:saas-ai-data) | Standard (Recommended): Use this for human readability, catalog discovery, and frontend code snippets. This is the primary format returned by the Provider Center. | | Domain URN | urn:b402:domain:<domain>(e.g. urn:b402:domain:ztrust.eu) | Autonomous Discovery & Web Trust: Use when calling or configuring a provider by its DNS-verified internet domain name without needing to know an internal platform slug. The ledger verifies cryptographic domain ownership via DNS TXT record (_b402-challenge.domain.com). | | Service UUID URN | urn:b402:srv:<uuid>(e.g. urn:b402:srv:a1b2c3d4-e5f6-...) | Machine Pipelines & Immutability: Use in Terraform, automated deployment scripts, or backend-to-backend meshes when referencing an immutable database primary key that won't break if the slug is renamed in the dashboard. |

Automatic Normalization: Both B402PaymentRequired and the Central Ledger automatically normalize all URN formats (as well as bare slugs or UUIDs) via regex ^urn:b402:(srv:|domain:)?, ensuring seamless interoperability without manual string manipulation.


1. SaaS Provider Usage (Protecting Endpoints)

Use B402PaymentRequired as standard Express or Connect middleware on routes you want to monetize.

import express from 'express';
import { B402PaymentRequired } from '@chdlabs/b402';

const app = express();
app.use(express.json());

// Protect endpoint with a €0.0050 micropayment fee
app.post('/api/summarize', B402PaymentRequired({
    serviceId: 'urn:b402:quoteoftheday', // Canonical service URN
    fee: 0.0050,
    currency: 'EUR'
}), (req, res) => {
    // Cryptographically verified payment claims are attached to req.b402Payment
    res.json({
        success: true,
        data: 'Here is your premium summarized payload.',
        payer: req.b402Payment.sub,
        serviceId: req.b402Payment.serviceId,
        amount: req.b402Payment.amount
    });
});

app.listen(8000, () => console.log('Monetized API running on port 8000'));

Dynamic Pricing (e.g. LLM Per-Token Pricing)

B402PaymentRequired supports dynamic fee resolver functions where pricing scales with compute:

app.post('/v1/generate', B402PaymentRequired({
    serviceId: 'urn:b402:llm-inference',
    fee: (req) => {
        const tokens = Number(req.body?.tokens) || 100;
        return tokens * 0.0001; // €0.0001 per token
    }
}), (req, res) => { /* ... */ });

2. SaaS Consumer Usage (Calling Paid Endpoints)

Use B402Client as a drop-in replacement for standard fetch. It automatically traps HTTP 402 Payment Required responses, validates the quote against your configured budget cap (maxFee), settles the fractional fee via the Central Ledger using your API key, and retries the request with the signed NIST FIPS 204 ML-DSA-44 Bearer token.

import { B402Client } from '@chdlabs/b402';

const client = new B402Client({
    apiKey: process.env.B402_API_KEY, // Autonomous API Key (starts with b402_live_)
    maxFee: 0.05 // Budget protection: aborts if provider demands > €0.05
});

// Call any 402-enabled API seamlessly
async function run() {
    const response = await client.fetch('https://api.ztrust.eu/api/quoteoftheday', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query: 'Get quote of the day' })
    });

    const data = await response.json();
    console.log('Result:', data);
}

run().catch(console.error);

3. Low-Level Token Verification

If you are implementing custom middleware or verifying tokens outside of B402PaymentRequired:

import { verifyPqcToken } from '@chdlabs/b402';

try {
    const payload = verifyPqcToken(tokenString, publicKey);
    console.log('Verified PQC Payment:', payload);
    // payload: { iss, sub, aud, serviceId, amount, currency, jti, iat, exp }
} catch (err) {
    console.error('PQC Token Verification Failed:', err.message);
}

Running the End-to-End Demos

The package includes runnable standalone demos in examples/ demonstrating both sides of the micropayment flow:

1. Start the Monetized Service (monetize.js)

In the first terminal, launch the monetized service:

node examples/monetize.js

This starts an Express API endpoint at http://127.0.0.1:8091/api/ai-data protected by B402PaymentRequired alongside a local mock ledger on port 8090.

2. Run the Consumer

In a second terminal, execute the consumer:

node examples/consumer.js

The consumer initializes B402Client, requests the monetized endpoint, traps the HTTP 402 challenge, automatically settles the micropayment with the ledger, and retries with the post-quantum Bearer token to receive the 200 OK response.


Architecture & Post-Quantum Security

  • Algorithm: NIST FIPS 204 Module-Lattice Digital Signature Algorithm (ML-DSA-44).
  • Single-Use Replay Protection: Each token includes a unique jti cryptographic nonce.
  • Unified Parameter: serviceId is the single canonical identifier for the provider address across all requests, challenges, tokens, and ledger entries.
  • Budget Protection: Consumers enforce maxFee safeguards to prevent unexpected charges.
  • Double-Entry Settlement: Atomic balance transfers recorded in compliant financial journals.

License

MIT © CHD Labs UG — https://ztrust.eu