@chdlabs/b402
v1.0.0
Published
Official Node.js SDK for HTTP 402 Micropayments with Post-Quantum Cryptography (NIST FIPS 204 ML-DSA-44)
Maintainers
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.
Installation
npm install @chdlabs/b402Requirement: 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 toB402PaymentRequired({ serviceId }). - 402 Challenge: When an unauthenticated client calls a protected endpoint,
B402PaymentRequiredchallenges the caller withWWW-Authenticate: B402 serviceId="..."and a JSON challenge containingserviceId,fee,currency, andledgerUrl. - Consumer Role: The consumer client (
B402Clientor manual script) readschallenge.serviceIdand submits{ callerId, serviceId, amount }to the Central Ledger/payendpoint 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
B402PaymentRequiredand 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.jsThis 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.jsThe 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
jticryptographic nonce. - Unified Parameter:
serviceIdis the single canonical identifier for the provider address across all requests, challenges, tokens, and ledger entries. - Budget Protection: Consumers enforce
maxFeesafeguards to prevent unexpected charges. - Double-Entry Settlement: Atomic balance transfers recorded in compliant financial journals.
License
MIT © CHD Labs UG — https://ztrust.eu
