BSV authentication and payment middleware for Cloudflare Workers. Rust compiled to WASM.
Port of auth-express-middleware and payment-express-middleware for the Cloudflare Workers runtime. Implements BRC-103/104 mutual identity auth and BRC-29 direct payments, with session and payment state persisted in Cloudflare KV. Error codes, HTTP statuses, and header names match the Express versions.
process_auth/process_auth_with_storage- BRC-103/104 mutual identity handshake, session verification, certificate exchange, and per-request replay protection (eachx-bsv-auth-nonceis single-use per session). Returns the authenticated identity key, a reusable session handle, and the raw request body. Every authentication refusal is a 401 response from the middleware itself (0.4.1), with CORS, unsigned; anErris a fault (storage, the server's key, the transport).process_payment_with_storage- BRC-29 payment verification. Emits402 Payment Requiredwith derivation prefix, acceptsx-bsv-paymentheader, reads output 0 of the payment and refuses it (400 ERR_INVALID_PAYMENT, the quote kept) unless it pays this server's BRC-29 derived key at least the price (0.3.8; 400 since 0.4.0), internalizes via a remote wallet storage endpoint, gates on the wallet'sacceptedflag, and enforces single-use derivation prefixes.satoshis_paidis the amount read from the output. The prefix binds its first txid permanently (M14).sign_json_response- signs outbound JSON responses so BRC-103/104 clients (e.g.AuthFetch) can verify server identity and message integrity. Equivalent to Express'sres.jsonhijacking, but explicit.WorkerStorageClient- WASM-compatible RPC client for a wallet storage server (e.g.storage.babbage.systems), used by the payment middleware and optional refund flows.- Optional
refundfeature - BRC-41 refund transaction builder for partial-refund scenarios (e.g. AI agents that pre-charge and refund on failure). Not present in the Express reference. verify_brc29_payment/verify_brc29_payment_output(0.3.6) - checks, before anything is internalized, that a BRC-29 payment output pays this server's derived key at least the quoted amount inside a structurally complete BEEF, with merkle roots checked against a header service you run (required: no service, no verdict;verify_brc29_payment_structural_onlyis the named opt-out without SPV). For callers with their own payment flow; the stock middleware runsverify_brc29_payment_outputitself (0.3.8).- Optional
d1-claimsfeature -D1PrefixStoreis the exact payment prefix backend.payment_prefix_gate/release_payment_prefixsupport custom doors; the separate nonce-named helpers are for idempotency keys only.
Since 0.4.0 the rules live in a runtime-free crate, bsv-middleware-core (this repository,
core/), and this crate is the Cloudflare Workers adapter over it:
the core (bsv-middleware-core, no runtime) |
this crate (bsv-middleware-cloudflare, Workers) |
|---|---|
BRC-103 message build and verify over a SessionBinding (sign, verify against the SESSION's identity, the handshake replies, response signing) |
reading a worker::Request into those messages, the session records, the replay guard, the HTTP answers, CORS |
BRC-29 derivation, the output check, the streaming reader's validity and spends (bsv-rs 0.4.0, the scripts run), the proof's presence and the SPV decision, answered in six words (PaymentVerdict: Verified, Underpaid, WrongScript, NoHeaderService, RootMismatch, Unverifiable { reason }) |
verify_brc29_payment and friends with their 0.3 signatures, PaymentVerifyError, and accept_verdict, the one visible match from the words to it |
the HeaderService trait (no URL type in the core; None fails closed) |
UrlHeaderService: Workers fetch to a ChainTracks-compatible base URL behind the 0.3.6 configuration gate |
the PaymentNonceStore and ClaimStore traits |
KV, Durable Object and D1 implementations (SessionNonceStore, D1ClaimStore) |
| the session lane's rules, the refund key derivation and the template signer, the context types | the lane's door and store, issue_refund over the storage client |
Every 0.3 public item keeps its name, path and signature (re-exported from the core where the type moved);
adopters upgrade by bumping the version. The core is reachable as bsv_middleware_cloudflare::core for code that
wants the words or the traits directly.
Workers are request-scoped and have no in-process memory, so a direct port of the Express middleware isn't possible. Adaptations:
- Sessions in Cloudflare KV (
KvSessionStorage) - configurable TTL, keyed by session nonce plus an identity index for lookups. - Payments in Cloudflare KV (
KvPaymentStorage) - duplicate-txid detection, unspent tracking, derivation prefix lifecycle. - No
res.jsonhijacking - Workers can't intercept response construction. Callsign_json_response(&body, status, &[], &session)explicitly before returning. - Remote wallet instead of local wallet object - Workers can't host a
WalletInterface, soWorkerStorageClientspeaks JSON-RPC to a storage server over HTTP, authenticated by BRC-103/104. - Async everywhere - KV reads, HTTP calls, and auth verification are all
async, matching the Workers runtime.
Error codes, HTTP statuses, and all x-bsv-auth-* / x-bsv-payment-* header names are identical to the Express versions. Clients that talk to Express middleware will talk to this middleware unchanged.
bsv-middleware-cloudflare = "0.7.9"
# Runtime-free hosts:
bsv-middleware-core = "0.4.8"Both crates require bsv-rs 0.8.15 or later in 0.8.x (caret). Work limits are optional, default None. Every script a
payment runs is held to a per-stack memory budget of DEFAULT_STACK_MEMORY_LIMIT (1,000,000 bytes; bsv-rs advisory
GHSA-7vx5-cf5p-5c48's ceiling for a 128 MB isolate is 8,000,000, a sixteenth of its memory, and a Worker holds the request
and its own state beside the verifier; an ordinary payment's scripts hold well under a kilobyte of stack); a host that
needs another figure names it with verify_brc29_payment_budgeted_with_memory_limit
or verify_brc29_payment_source_with_memory_limit.
A script this host declines memory for under the budget is not judged: the budget is this host's memory bound, not
a rule of the chain, and the answer is no verdict on the payment. The core's reason is UnverifiableReason::MemoryNotJudged
(the unproven transaction whose script was running, which is the payment itself or one of its ancestors, and its input,
from the payer's own bytes; the resource, Stack, AltStack or ElementSize; the budget in force at the door). bsv-rs runs the
scripts of a transaction only when it carries no merkle path of its own, so a transaction with its proof is never named.
response_class() answers it 422 ERR_PAYMENT_MEMORY (PaymentVerifyError::is_memory_decline()), with the JSON body of
PaymentVerifyError::memory_decline_body():
{"code":"ERR_PAYMENT_MEMORY","description":"Not judged: this host declined memory for the script of input 1 of transaction <txid>, an unproven transaction in this payment's BEEF (the payment itself or one of its ancestors). This host's memory bound is 1000000 bytes per stack: a bound of this host, not a rule of the chain, and no verdict on the payment. Present this payment again once transaction <txid> has its proof, or pay with other coins.","resource":"Stack","budget":1000000,"txid":"<txid>","input":1}The two ways out for the payer, the free one first: present the same payment again once that transaction has its proof
(when it is the payment itself, once the payment is mined), or pay with other coins. It is never a 5xx and never served.
The adapter's doors return the decline as PaymentVerifyError::Unverifiable; response_class() gives
(422, ERR_PAYMENT_MEMORY) and memory_decline_body() the body, so a host that answers with those two answers 422 with
the body by itself. A host that maps PaymentVerifyError to a response with its own match answers this decline with
whatever its catch-all arm answers until it adds one arm on is_memory_decline() BEFORE that catch-all:
match &err {
// ... the host's arms before its catch-all (a 503 for `is_server_side()`, ...) ...
e if e.is_memory_decline() => (422, e.memory_decline_body().unwrap()),
PaymentVerifyError::Unverifiable { .. } => /* the host's catch-all */,
// ...
}Each door logs one line per such decline, for a host
to count them: payment.not_judged code=ERR_PAYMENT_MEMORY resource=<resource> txid=<txid> input=<input> payer=<the sender's public identity key>. The reference verifier runs under no such ceiling and names no budget here.
A decline under a work limit names the resource and input as payer-side Unverifiable (SpendRefused),
400 ERR_PAYMENT_INVALID in the adapter, as a script that judges false is. A lone hashed leaf at a nonzero offset is refused by the
SDK's MerklePath, with a payer-side refusal naming the offset. See the migration.
Every verifying door reads at most DEFAULT_PAYMENT_BYTES_LIMIT bytes of a payment (614,400, 600 KiB: the BEEF or
transaction as bytes, whatever encoding carried it) and refuses a longer one before it parses or verifies any of
it, before anything is claimed or handed to a wallet. A Worker's isolate is memory-limited, and a door bounds what it
reads. A door that takes a slice compares the slice's length before any reader
is built. A door that takes a source counts the bytes as it pulls them and pulls no further once it holds one byte
past the figure; no reader sees a byte past it. The multipart transport's source (PaymentPart::transaction()) is the
payment part alone: it is counted, and the request's other parts keep whatever the host allows. split_multipart_payment
checks the base64 of the whole payment part, so a malformed encoding is the payer's 400 ERR_MALFORMED_PAYMENT at any
figure a host names. The header door
(process_payment_with_storage) counts the payment from its base64's length before decoding it. The cap is on the
payment's part only.
The reference's payment middleware (bsv-blockchain/ts-stack 57c5f13, packages/middleware/payment-express-middleware) names a figure for a payment carried in the body, 4 MiB of payment JSON by default (src/index.ts:368), refuses a larger part with 413 and the code ERR_MALFORMED_PAYMENT, and leaves a header-carried payment's size to the HTTP server. The status here matches the reference's (413). The code differs on purpose: ERR_PAYMENT_SIZE, because the payment is not judged, so it is not malformed. The default here is lower than the reference's. An ordinary payment is about a kilobyte (in 727 real payments the median was 1.2 KB and the largest 434 KB), and a host that must read a larger payment names its figure. The figure is provisional: it is read again at each bsv-rs pin of this crate and raised to the door's natural figure when a pin allows it.
The core's reason is UnverifiableReason::SizeNotJudged { size, budget } (size where the door knows it: a slice's
length; absent at a source door). response_class() answers it 413 ERR_PAYMENT_SIZE
(PaymentVerifyError::is_size_decline()), with the JSON body of PaymentVerifyError::size_decline_body():
{"code":"ERR_PAYMENT_SIZE","description":"Not judged: this payment is 614401 bytes, and this host reads at most 614400 bytes of a payment: a bound of this host, not a rule of the chain, and no verdict on the payment. Pay with other coins. If this payment's size is unconfirmed ancestry, it will be smaller after the next block.","budget":614400,"size":614401}Where the size is not known the body has no size and the description reads "Not judged: this payment is more than
614400 bytes, the most this host reads of a payment: ...", the rest the same. It is never a 5xx and never served. The
adapter's own doors and response_class() answer it by themselves. A host that maps PaymentVerifyError to a response
with its own match adds one arm on is_size_decline() BEFORE its catch-all, beside the memory arm:
match &err {
// ... the host's arms before its catch-all (a 503 for `is_server_side()`, ...) ...
e if e.is_memory_decline() => (422, e.memory_decline_body().unwrap()),
e if e.is_size_decline() => (413, e.size_decline_body().unwrap()),
PaymentVerifyError::Unverifiable { .. } => /* the host's catch-all */,
// ...
}Each door logs one line per such decline, for a host to count them: payment.not_judged code=ERR_PAYMENT_SIZE resource=Size size=<bytes or none> budget=<bytes> payer=<the sender's public identity key>. A host that needs another
figure names it with verify_brc29_payment_budgeted_with_limits (a slice) or verify_brc29_payment_source_with_limits
(a source), each the _with_memory_limit function with a last payment_bytes_limit: Option<usize>; None means the
default.
A request body larger than this host reads: 413; 503 while it holds as many as it reads at once; 408 when it does not arrive in time
The auth layer reads a request's body before it authenticates the caller (the BRC-104 signature covers the body), at
three places: a general message (process_auth*), the handshake (/.well-known/auth) and the session lane
(process_auth_lane*). At each it runs one bounded reader, in this order, before any session is looked up or written
and before any signature is verified:
- The declared length. A
Content-Lengthovermax_request_body_bytesis refused with nothing read. This is the only use of the declared length: it charges nothing to the total and reserves nothing. - The read, charged as it arrives. The body is read from the request's stream as it arrives. Each chunk is
charged to the isolate's count (below) before it is kept, into one buffer that grows with what has arrived and
never has room for more than
max_request_body_bytes+ 1 bytes. Once the buffer holds one byte past the figure no further chunk is pulled and the body is refused (413). A chunk that would take the count pastmax_held_body_bytesends the read (503), and everything the body had charged is given back. That buffer is thebodyhanded to the host. - The deadline. The whole read, not each chunk, has
body_deadlineto complete. A body that has not arrived in full by then is not read further (408), and everything it had charged is given back.
The figures are this host's, held in one BodyBounds value. The defaults apply by themselves; to name its own
figures a host calls the _with_body_bounds twin of the entry point it already calls:
// The defaults (8 MiB, 32 MiB and 30 seconds) apply by themselves:
let auth = process_auth(req, &env, &auth_options).await?;
// A host's own figures: the same call through its `_with_body_bounds` twin.
let bounds = BodyBounds::default()
.with_max_request_body_bytes(12 * 1024 * 1024) // the most of one request's body
.with_max_held_body_bytes(48 * 1024 * 1024) // the most held at once in this isolate
.with_body_deadline(std::time::Duration::from_secs(20)); // the longest a body's read runs
let auth = process_auth_with_body_bounds(req, &env, &auth_options, bounds).await?;Each entry point has a twin that takes the same arguments and a last bounds: BodyBounds:
process_auth_with_body_bounds, process_auth_do_with_body_bounds, process_auth_with_storage_with_body_bounds,
process_auth_lane_with_body_bounds and process_auth_lane_with_storage_with_body_bounds. The entry points without
the suffix apply BodyBounds::default().
| Figure | Default | Why |
|---|---|---|
max_request_body_bytes |
DEFAULT_MAX_REQUEST_BODY_BYTES, 8,388,608 (8 MiB) |
the reference's figure |
max_held_body_bytes |
DEFAULT_MAX_HELD_BODY_BYTES, 33,554,432 (32 MiB): four bodies at the default bound |
one total for the isolate, smaller than the reference's (below) |
body_deadline |
DEFAULT_BODY_DEADLINE, 30 seconds |
the reference's figure |
The layer keeps one count per isolate of the request-body bytes it holds at this moment, every request it is reading
counted together. A host names a total at least its bound on one request, or a body at the bound is never read. A
body is counted from its first byte until the layer hands it to the host (the body of AuthResult::Authenticated or
LaneAuthResult::Laned, from then on the host's) or drops it, on every path: an answer, a refusal, a fault, a request
that goes away while it is read. The total bounds the bodies this layer is holding while their callers are not yet
authenticated; it does not bound the bodies that authenticated requests' handlers are still holding, because a body
is given back to the count when it is handed to the host, and a host bounds those by its own work. The total is one
figure for the isolate and does not tell a known caller from an unknown one: the layer holds no session in the isolate
(sessions live in the host's store), and telling them apart would cost a storage round trip before every read. The
deadline runs on the Worker's timer (worker::Delay, setTimeout).
The answers are the layer's own, unsigned (no caller is authenticated yet), with the CORS headers:
| Refusal | Status | Code |
|---|---|---|
a declared length over max_request_body_bytes (nothing read) |
413 | ERR_AUTH_BODY_TOO_LARGE |
a body that reaches one byte past max_request_body_bytes as it is read |
413 | ERR_AUTH_BODY_TOO_LARGE |
a chunk that would take the isolate's count past max_held_body_bytes |
503, Retry-After: 2 |
ERR_AUTH_BODIES_FULL |
a body that has not arrived in full within body_deadline |
408 | ERR_AUTH_BODY_TIMEOUT |
{"code":"ERR_AUTH_BODY_TOO_LARGE","description":"This request's body is 8388609 bytes, and this host reads at most 8388608 bytes of a request: a bound of this host.","budget":8388608,"size":8388609}
{"code":"ERR_AUTH_BODY_TOO_LARGE","description":"This request's body is more than 8388608 bytes, the most this host reads of a request: a bound of this host.","budget":8388608}
{"code":"ERR_AUTH_BODIES_FULL","description":"This host is holding as many request bodies as it reads at once; send the request again shortly: a bound of this host, not a fault of the request."}
{"code":"ERR_AUTH_BODY_TIMEOUT","description":"This request's body did not arrive within 30 seconds, the longest this host waits for one: a bound of this host."}Each refusal logs one line, for a host to count them: auth.body_refused code=ERR_AUTH_BODY_TOO_LARGE size=<bytes or none> budget=<bytes>, auth.body_refused code=ERR_AUTH_BODIES_FULL held=<bytes> total=<bytes> (the isolate's count
when the chunk was refused) or auth.body_refused code=ERR_AUTH_BODY_TIMEOUT held=<bytes> waited=<ms> (the bytes of
that body that had arrived). A Content-Length that is not decimal digits is read as no declared length. A request
with no auth headers is not read by the layer (it answers 401, or passes the request through under
allow_unauthenticated), so the bounds do not apply to it. CloudflareTransport::extract_auth_message and
extract_auth_message_digest read through the same reader at the defaults; a body refused there is
Err(AuthCloudflareError::TransportError(..)) carrying the description. The core's body_bound module holds the
figures, the count (BodyLedger), the buffer (BoundedBody) and the refusal (BodyRefusal), re-exported at this
crate's root.
The reference's auth middleware (bsv-blockchain/ts-stack 57c5f13, packages/middleware/auth-express-middleware)
names 8 MiB for one request (DEFAULT_MAX_REQUEST_BYTES, src/index.ts:52) and, when it collects the raw body in the
layer, refuses a declared length over it before reading and stops at it while reading, both 413
(src/rawRequestBody.ts:50-51, :87); it counts each chunk as it arrives against a total across the bodies it is
collecting, 64 MiB (rawRequestBody.ts:19), answered 503 (:88-90); and it gives the read 30 seconds
(index.ts:2213), answered 408 (rawRequestBody.ts:101). The bound on one request, the deadline, the counting as a
body arrives and the three statuses match the reference's. The total differs in figure, because a Worker's isolate
is memory-limited and serves several requests at once. Other differences: the reference collects the raw body in the
layer only when the host sets captureRawBody (index.ts:149, :2209-2220), and this layer always does; the
reference answers one code, ERR_AUTH_BODY, with Connection: close and no Retry-After (index.ts:2252-2258),
and this layer answers three codes, with budget and size on a 413 and Retry-After on the 503; the reference gives
a body's count back when the response finishes or closes (rawRequestBody.ts:55-64), and this layer when it hands
the body to the host; the reference's total is not a setting (its constructor's default, index.ts:2211-2215), and
here it is; the reference also refuses a malformed Content-Length (400, rawRequestBody.ts:41-49), a non-identity
Content-Encoding (415, :35-40), a body that differs from its declared length (400, :94) and captures past a
count of pending ones (503, :34), and this layer adds none of those answers.
Core callers add work_limit: None to verify_brc29_payment and
verify_brc29_payment_verified. verify_brc29_payment_stream takes an
AsyncByteSource; SliceSource is the bounded-chunk slice wrapper.
Implement HeaderService::mining_tip for finality and coinbase maturity.
Missing context is a server-side MiningContextUnavailable, never a guessed verdict.
The adapter keeps its existing verify signatures with no budget. Read
payment_work_limit(&env)? once and pass it to verify_brc29_payment_budgeted
or verify_brc29_payment_source. PAYMENT_WORK_LIMIT is optional: absent or
blank means no bound, a positive decimal u64 bounds each unproven input,
and 0 or a non-number is BadWorkLimit, 500 ERR_SERVER_MISCONFIGURED.
The fleet uses 1000000 units per input; a one-input P2PKH witness needs 490.
A resource decline is payer-side, 400 ERR_PAYMENT_INVALID, with the quote kept.
The bound is per input, not per request. The Worker's configured CPU cap bounds
total request work (Paid defaults to 30 seconds); this release adds no request clock.
After authentication, use split_multipart_payment(&req, body) and feed
payment.transaction() to the source verifier with payment.prefix() and
payment.suffix(). The original multipart body moves into PaymentPart;
only the handler payload is copied out, and base64 decodes in 3 KB chunks.
The x402 helper switches above 8,192 bytes of payment JSON, when multipart
is advertised. It sends an x-bsv-payment JSON part and an optional binary
body part. This is the helper's threshold, replacing the design's approximate
16 KB. The old prepare_multipart_payment remains available, deprecated.
BRC-104 authenticates the entire body before payment verification; its digest
path holds one body copy. Signed refusal payloads keep their existing shape.
UrlHeaderService uses /findChainTipHeaderHex, /getChain, and up to ten
/findHeaderHexForBlockHash?hash=... lookups to compute the tip's median time
past from its ancestry. Mainnet and testnet activation heights follow the SV
node's chain parameters. No candidate block time is guessed before CSV:
pre-CSV time locks decline without explicit context from a custom service.
The door reads at most DEFAULT_PAYMENT_BYTES_LIMIT bytes of a payment. The release witness
core/tests/stream_memory.rs (ignored by default) runs the SDK's streaming reader alone over BEEF bodies of 16, 64 and
128 MB, and expects the door to answer each of them 413 at the default.
use bsv_middleware_cloudflare::{
process_auth, sign_json_response,
middleware::auth::{AuthMiddlewareOptions, AuthResult, handle_cors_preflight},
};
use worker::*;
#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: Context) -> Result<Response> {
if req.method() == Method::Options {
return handle_cors_preflight();
}
let opts = AuthMiddlewareOptions {
server_private_key: env.secret("SERVER_PRIVATE_KEY")?.to_string(),
allow_unauthenticated: false,
session_ttl_seconds: 3600,
..Default::default()
};
let (auth, req, session, _body) = match process_auth(req, &env, &opts).await
.map_err(|e| Error::from(e.to_string()))?
{
AuthResult::Authenticated { context, request, session, body } => (context, request, session, body),
AuthResult::Response(resp) => return Ok(resp),
};
let body = serde_json::json!({ "identity": auth.identity_key });
match session {
Some(ref s) => sign_json_response(&body, 200, &[], s)
.map_err(|e| Error::from(e.to_string())),
None => Response::from_json(&body),
}
}See examples/basic_server.rs for auth + payment together.
# wrangler.toml
[[kv_namespaces]]
binding = "AUTH_SESSIONS"
id = "<your-kv-id>"
[[kv_namespaces]]
binding = "PAYMENTS" # only needed if you use the payment middleware
id = "<your-kv-id>"Secret: wrangler secret put SERVER_PRIVATE_KEY (64-char hex secp256k1 private key).
| Feature | Default | Pulls in |
|---|---|---|
refund |
off | bsv-middleware-core/refund (ripemd) - enables refund::issue_refund for BRC-41 partial refunds |
d1-claims |
off | worker/d1 - enables exact payment-prefix bindings and idempotency claims on D1 |
All error codes, HTTP statuses, and header names match the Express versions:
| Concern | Express | Rust |
|---|---|---|
| Auth error codes | UNAUTHORIZED, ERR_INVALID_AUTH, ERR_SESSION_NOT_FOUND |
identical |
| Payment error codes | ERR_PAYMENT_REQUIRED, ERR_MALFORMED_PAYMENT, ERR_INVALID_DERIVATION_PREFIX, ERR_PAYMENT_FAILED |
identical |
| Headers | x-bsv-auth-*, x-bsv-payment-* |
identical |
| HTTP statuses | 400 / 401 / 402 / 500 | claim-store faults: 503 ERR_PAYMENT_UNAVAILABLE, retryable: true, Retry-After: 5, quote and prefix kept; plus 503 ERR_HEADER_SERVICE_UNAVAILABLE when the header service cannot answer (the quote kept); a payment that cannot be verified for the payer's reason (invalid BEEF, a refused spend, no proof) is 400 ERR_INVALID_PAYMENT with the quote kept (0.5.0); every authentication refusal is a 401 AuthResult::Response (0.4.1), never an Err |
Known divergences (architectural, not bugs):
- Response signing is explicit. Callers invoke
sign_json_responserather than relying onres.jsoninterception. - Pluggable storage via
SessionStorage. Express lets you swapSessionManager; here the equivalent seam isSessionStoragefor auth andPaymentPrefixStorefor payments. UseD1PrefixStorefor exact payment enforcement;KvPrefixStorehas the G3 consistency window. - No injectable logger. Use
console_log!/console_error!from theworkercrate at call sites if needed. - Payment internalizes via HTTP to a wallet storage server, not a local
WalletInterface. Required for Workers (no local wallet possible). - No SPV on the middleware's own path.
process_payment_with_storagechecks output 0's script and amount and nothing else about the transaction: no merkle proof is checked against a block header there. Whether the payment is real and confirmable is left to the wallet storage server'sinternalizeAction, which this crate does not verify. Runverify_brc29_payment(through a header service) before it when a proof must be checked.
Deliberate hardening divergences (the reference is weaker here; security audit findings #30/#44):
- Auth replay protection. The TS stack (
@bsv/sdkPeer.processGeneralMessage) never records consumed per-request nonces, so a byte-identical signed request replays successfully there for the whole session TTL. This crate consumes each(session nonce, x-bsv-auth-nonce)pair and rejects duplicates with401 ERR_REPLAYED_REQUEST. Seemiddleware::authdocs for the exact residual window under eventually-consistent KV. - Every authentication refusal is a 401 answer (0.4.1). The reference answers
401 UNAUTHORIZEDonly when no auth headers are present; a general message its SDK refuses (another identity's key over the session, a bad signature, a session that never completed its handshake) is swallowed by thePeerand never answered. Here each of those is401 ERR_INVALID_AUTH(ERR_SESSION_NOT_FOUNDfor an unknown session), fromprocess_auth*as anAuthResult::Responsewith CORS, soAuthFetch-class clients re-handshake; anErrfromprocess_auth*is a fault (storage, the server's key, the transport), the host's 500. acceptedgate.payment-express-middlewarecallsnext()even whenwallet.internalizeActionreturnsaccepted: false. Here a rejected payment returns402with a fresh challenge and never reaches the handler.- The paying output's script.
payment-express-middleware2.1.9 reads output 0's satoshis and refuses below the price with400 ERR_INVALID_PAYMENT, and leaves the script to its wallet's signer. Here the storage server is not a signer, so output 0 must also pay this server's BRC-29 derived key; a short or misdirected payment gets the reference's400 ERR_INVALID_PAYMENTwith the quote kept (no fresh challenge, the prefix not consumed), before the storage is called (0.3.8 answered 402 with a fresh challenge; 400 since 0.4.0). - M14 payment derivation prefixes. Each prefix binds its first subject txid forever before any wallet call. Another txid is refused with 400
ERR_INVALID_DERIVATION_PREFIX, no fresh challenge, no internalize or refund. The same txid is refused while held or served; an internalize error releases only its own attempt for an identical retry. Wallet rejection keeps the binding held.process_paymentwas removed in 0.7.0.
Known production consumers using BRC-103/104 auth + dynamic pricing + optional refund:
bsv-messagebox-cloudflare- BSV peer-to-peer messaging service (upcoming public release)- Various agents (image gen, LLM inference) that pre-charge and refund on upstream failure
Dual-licensed under MIT or Apache-2.0 at your option. See LICENSE-MIT and LICENSE-APACHE.
One BRC-103/104 handshake per origin, then a LANE: process_auth_lane(req, &env, &options, "AUTH_SESSION_STORE")
serves calls that carry x-low-session (the lane id), x-low-session-identity, x-low-session-n (the client's
counter) and x-low-session-mac (HMAC-SHA256(K, n ‖ "METHOD path?query" ‖ 0x00 ‖ sha256(body))) with ZERO wallet
calls and one Durable Object round trip, and answers LaneAuthResult::Laned { context, request, body, lane };
everything else is LaneAuthResult::Reference(AuthResult) or LaneAuthResult::Offered { auth, offer }, the unchanged
reference outcome. The client's FIRST BRC-104-signed general message carrying the explicit ask (x-low-lane-ask) on a
server with options.session_lane = Some(..) is answered Offered: the server attaches the offer to that message's
SIGNED reply as the x-bsv-lane-offer header (base64 JSON {id, expiresAt, salt, ask}, a header a reference client
ignores, exposed cross-origin); the unsigned handshake never mints. Both sides derive
K = HMAC-SHA256(salt, label ‖ id ‖ clientMessageNonce ‖ serverSessionNonce) from that message's own x-bsv-auth-nonce
and the server's session nonce. Seal a laned answer with
seal_lane_response(&value, status, &lane) (x-low-session-n, x-low-session-mac, no-store). Refusals are
401 {status:"error", code:"ERR_SESSION_REFUSED", reason} (unknown-session / expired / replay / bad-mac /
malformed; 503 lane-unavailable when the store cannot be asked). The KV backend keeps no lanes (never offers
one, answers a laned call 503 lane-unsupported). The pure rules live in middleware::session_lane; the MAC
vectors are tests/fixtures/session_lane.vectors.json (emitted by the module's own test, sha256-pinned; a client
pins the same bytes). Designed for the relay adopter: its lane, generalized to HTTP-only servers.
verify_brc29_payment(server_key, sender_identity_key, derivation_prefix, derivation_suffix, &tx_bytes, output_index, required_satoshis, header_url)
proves, before any wallet call, that the payment pays this server correctly and is real and confirmable.
verify_brc29_payment_verified(..) (0.5.0) answers the same with the subject's txid beside the amount
(VerifiedPayment { satoshis, txid }), so a host records the payment without parsing the BEEF a second time.
The payment's bytes. A payment of at most DEFAULT_PAYMENT_BYTES_LIMIT bytes is read once through the streaming
reader of bsv-rs 0.5 (0.5.0 at least), one element in hand, and a refusal of the bytes names the offset and the
reader's kind; a longer one is not judged, 413 ERR_PAYMENT_SIZE (above). This crate carries no count bound.
The check runs, in order:
- Configuration:
header_urlmust name a header service (below), elseNoHeaderServicebefore the bytes are read. - The bytes (the core's reader,
bsv_middleware_core): the BEEF is valid (V1, V2 or Atomic) and the scripts run: every unproven transaction's inputs name earlier transactions and spend them (each unlocking script is executed against the parent output the BEEF carries; no transaction creates value); an Atomic subject is the tip of its ancestry. Invalid bytes areUnverifiablewithInvalidBeef { offset, kind, .. }, a refused spendSpendRefused { txid, input, .. }, at the soonest fault in stream order. 0.4.x checked the structure alone. - Script + amount (
verify_brc29_payment_outputruns this alone, offline): the subject's output's locking script equals the P2PKH script of the BRC-29 key derived from (server identity, sender identity, prefix, suffix) viaexpected_brc29_locking_script, and carries at leastrequired_satoshis. One byte-compare rejects underpayment, zero-sat outputs, outputs paying any other key, a transaction built for another quote nonce, and a transaction built for another server. - A proof is present: no BUMP, or an ancestry that reaches no proof, is
UnverifiablewithNoProof { txid }(the transaction whose proof is absent). A transaction with no input is invalid bytes, refused by the reader in check 2 asInvalidBeef { kind: "NoInputs", .. }at its leading byte (bsv-rs 0.4.1; 0.4.0's reader read it as valid with no root and this check refused it). The payer's side either way (ruled 2026-10-09): the server never fetches a missing proof; the payer sends a proven BEEF. - SPV: each distinct merkle root, lowest height first, is checked against block headers from a
ChainTracks-compatible service (
GET {header_url}/findHeaderHexForHeight?height=N). Fail-closed both ways: a root the service cannot answer for (outage, timeout, HTTP error, height not yet indexed) isUnverifiablewithHeaderLookupFailed { height, .. }(the server's own condition: 503-class, the quote kept, the client retries the same payment), and a root that differs from the header isRootMismatch(a fraud signal). 0.3.x accepted the first case with a logged warning; 0.4.0 fails closed, by the project's ruling of 2026-10-08: an unchecked root is not evidence.
Warning: a header service URL is required. The crate ships no header service and never skips SPV silently. Pass the base URL of your own ChainTracks-compatible service as
header_url(for example a ChainTracks deployment you run).None,Some(""), theDEFAULT_CHAINTRACKS_URL.invalidplaceholder (in any case, with or without a trailing slash or dot), any other.invalidhost, a value without anhttp(s)://scheme, or a value whose host the gate cannot classify as a real hostname (userinfo, percent-encoding, backslashes, whitespace, non-ASCII, a non-numeric port) is refused withPaymentVerifyError::NoHeaderServicebefore any other check: fail-closed, never a silent skip. The host is normalised before the placeholder comparison, so no spelling of the placeholder reaches DNS and surfaces as a lookup error instead of as the misconfiguration it is. Adopters with no header service opt out of SPV by name withverify_brc29_payment_structural_only(..)(the reader's structure with no script run, the output, the proof's presence; no root check).
Every PaymentVerifyError means reject without internalizing, no refund owed. PaymentVerifyError::is_server_side()
is the one predicate the table needs.
PaymentVerifyError |
status | code | the quote |
|---|---|---|---|
NoHeaderService |
500 | ERR_SERVER_MISCONFIGURED |
fix the deployment |
KeyDerivation (the server's key) |
500 | the host's own | fix the deployment |
Unverifiable { reason }, is_server_side() (HeaderLookupFailed) |
503 | ERR_HEADER_SERVICE_UNAVAILABLE |
kept: retry the SAME payment once the service answers |
Unverifiable { reason }, is_size_decline() (SizeNotJudged: longer than this host reads of a payment, not judged) |
413 | ERR_PAYMENT_SIZE, body size_decline_body() |
kept: pay with other coins |
Unverifiable { reason }, is_memory_decline() (MemoryNotJudged: this host declined memory for a script, not judged) |
422 | ERR_PAYMENT_MEMORY, body memory_decline_body() |
kept: present it again once that transaction has its proof, or pay with other coins |
Unverifiable { reason }, the payer's (InvalidBeef, SpendRefused including work declines naming the input, NoProof, OutputMissing, NoTransaction, MalformedTransaction, the sender's KeyDerivation) |
400 | ERR_PAYMENT_INVALID |
kept: send another payment |
Underpaid, WrongScript, RootMismatch |
400 | ERR_PAYMENT_INVALID |
kept |
Ok(satoshis) |
serve |
header_url |
result |
|---|---|
None, Some(""), whitespace only |
Err(NoHeaderService) |
the .invalid placeholder (trailing slash or dot or not, any case), any .invalid host, no http(s):// scheme |
Err(NoHeaderService) |
userinfo, %, \, whitespace, control or non-ASCII characters, a non-numeric port, a label that is not a hostname |
Err(NoHeaderService) |
| service unreachable, HTTP error, unparseable answer, height not indexed | Err(Unverifiable { reason: HeaderLookupFailed { height, .. } }), warning logged (fail-closed; 503-class at the host, the quote kept) |
| the header at that height carries a different root | Err(RootMismatch) (fail-closed) |
| the header carries the proof's root | Ok(satoshis) |
A host whose match on PaymentVerifyError has a _ arm compiles unchanged on 0.5.0 but answers that arm's 400 for a
header outage; add the 503 arm by is_server_side(). The 0.3 variants BadTransaction, MissingOutput and
BadBeef are gone (0.5.0): a payer's bytes are an Unverifiable reason now, and a _ arm takes them.
The check itself is the core's (bsv-middleware-core) and answers in six words; accept_verdict is this crate's one
visible match from them to the table above (Verified is the only Ok(satoshis); every other word is the same-named
Err, Unverifiable included). Callers that want the words themselves use verify_brc29_payment_verdict with any
HeaderService (UrlHeaderService::resolve(header_url) is the gated URL one); none of the words but Verified may
be served on. The named opt-out verify_brc29_payment_structural_only is the one function that answers Ok with
roots unchecked, because its caller asked for exactly that by name.
With d1-claims, pass &D1PrefixStore(&db) to
process_payment_with_storage{,_signed} in place of session storage. Custom doors
call payment_prefix_gate(env, prefix, txid, agent, FaultPosture::Closed) after
verification and before the wallet, then sign any PrefixGate::Refuse body.
SameTransaction / legacy Unknown return 409 ERR_PAYMENT_REPLAYED;
OtherTransaction returns 400 ERR_PAYMENT_INVALID. A closed fault returns 503
ERR_PAYMENT_UNAVAILABLE, retryable: true, with the quote and prefix kept,
no fresh challenge, and Retry-After: 5. Pass FaultPosture::Closed at every
host and pass Refuse { status, body, headers } through sign_json_response.
FaultPosture::Open is deprecated by the owner's ruling of 2026-10-19;
it returns Fault for one compatibility release only. The stock payment path
returns the same 503 on a PaymentPrefixStore fault.
| Claim-store failure | Status | Code | Retry |
|---|---|---|---|
Store fault, missing CLAIMS, or invalid txid shape (fleet Closed); stock store fault |
503 | ERR_PAYMENT_UNAVAILABLE |
retryable: true, Retry-After: 5; same payment, quote and prefix kept |
No refusal body includes either transaction's txid. release_payment_prefix
retains the binding. claim_payment_nonce / release_payment_nonce and
D1ClaimStore are only for idempotency keys, such as refund-once keys.
For existing tables, run PAYMENT_CLAIMS_MIGRATION ONCE before deploying 0.7.0:
ALTER TABLE payment_claims ADD COLUMN txid TEXT;
ALTER TABLE payment_claims ADD COLUMN released INTEGER NOT NULL DEFAULT 0;New tables use PAYMENT_CLAIMS_SCHEMA. Never expire payment-prefix rows.
KvPrefixStore(&session_storage) keeps the legacy key namespace and legacy 1
records closed. A payment-prefix claim must be one indivisible step against the
backend: a compare-and-set, an upsert under a unique key read back in the same
transaction, or a single-threaded actor. KV has no compare-and-swap: a
KvPrefixStore claim is a read of the prefix's key, then a write of the txid,
and a write at one edge reaches the others after about 60 seconds.
D1PrefixStore (feature d1-claims) is the store whose claim is one statement.
A DO auth backend does not change the payment backend; select D1 separately.
bsv-middleware-cloudflare = { version = "0.7.9", features = ["d1-claims"] }- KV (default) -
process_auth(req, &env, &options): sessions and the per-request nonce replay guard in theAUTH_SESSIONSKV namespace (a read, and a read + write, per authenticated request). - Durable Objects (0.3.3, opt-in) -
process_auth_do(req, &env, &options, "AUTH_SESSION_STORE"): oneAuthSessionStoreobject per session nonce holds the session record and the consumed nonces, so a request costs two same-colo object round trips and no KV write; KV stays the cold path (the identity → session index written at the handshake, a KV-minted session migrated on first sight, the BRC-29 payment nonce scope). Bind the class and add a migration:
[[durable_objects.bindings]]
name = "AUTH_SESSION_STORE"
class_name = "AuthSessionStore"
[[migrations]]
tag = "vN-auth-session-store"
new_classes = ["AuthSessionStore"]and export the class from the worker crate: pub use bsv_middleware_cloudflare::AuthSessionStore;. Any other store implements SessionStorage and goes through process_auth_with_storage.
Tags core-v* and v* publish bsv-middleware-core and bsv-middleware-cloudflare through crates.io trusted publishing (.github/workflows/release.yml); the trusted-publishing entries exist on crates.io for both crates (verified 2026-10-10: both tag shapes authenticate). Releases go out by the tags, core-v* first, then v* once the core version is on crates.io (the adapter's package step resolves the core from crates.io alone).
Run cargo fmt --all -- --check, cargo clippy --workspace --all-targets --all-features -- -D warnings, and cargo clippy -p bsv-middleware-cloudflare --target wasm32-unknown-unknown --all-features -- -D warnings.
Build docs with RUSTDOCFLAGS="-D warnings" cargo doc --workspace --all-features --no-deps.
Install cargo-deny with cargo install cargo-deny --locked --version 0.19.0, then run cargo deny --manifest-path core/Cargo.toml check and cargo deny --manifest-path Cargo.toml check.
tools/ci/secrets_scan.sh origin/main scans tracked files and the branch and working diffs for the estate's secret shapes, reporting paths only. Public test keys require a reviewed digest exception only if a shape matches; none are currently excluded.
The six existing CI contexts stay required. After merge, the captain adds deny and secrets to main's required contexts.