r402-http 0.13.0

HTTP transport layer for the x402 payment protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! Axum middleware for enforcing [x402](https://www.x402.org) payments on protected routes.
//!
//! This middleware validates incoming payment headers using a configured x402 facilitator,
//! verifies the payment, executes the request, and settles valid payments after successful
//! execution. If the handler returns an error (4xx/5xx), settlement is skipped.
//!
//! Returns a `402 Payment Required` response if the request lacks a valid payment.
//!
//! ## Settlement Modes
//!
//! - **[`SettlementMode::Sequential`]** (default): verify → execute → settle.
//!   Safer — settlement only runs after the handler succeeds.
//! - **[`SettlementMode::Concurrent`]**: verify → (settle ∥ execute) → await settle.
//!   Lower latency — overlaps settlement with handler execution.
//! - **[`SettlementMode::Background`]**: verify → spawn settle → execute → return.
//!   Fire-and-forget — ideal for streaming responses.
//!
//! ## Configuration Notes
//!
//! - **[`X402Middleware::with_price_tag`]** sets the assets and amounts accepted for payment (static pricing).
//! - **[`X402Middleware::with_dynamic_price`]** sets a callback for dynamic pricing based on request context.
//! - **[`X402Middleware::with_base_url`]** sets the base URL for computing full resource URLs.
//!   If not set, defaults to `http://localhost/` (avoid in production).
//! - **[`X402LayerBuilder::with_settlement_mode`]** selects sequential or concurrent settlement.
//! - **[`X402LayerBuilder::with_description`]** is optional but helps the payer understand what is being paid for.
//! - **[`X402LayerBuilder::with_mime_type`]** sets the MIME type of the protected resource (default: `application/json`).
//! - **[`X402LayerBuilder::with_resource`]** explicitly sets the full URI of the protected resource.
//!

use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;

use axum_core::extract::Request;
use axum_core::response::Response;
use http::{HeaderMap, Uri};
use r402::facilitator::Facilitator;
use r402::proto::v2;
use tower::util::BoxCloneSyncService;
use tower::{Layer, Service};
use url::Url;

use super::facilitator::FacilitatorClient;
use super::paygate::{Paygate, ResourceTemplate};
use super::pricing::{DynamicPriceTags, PriceTagSource, StaticPriceTags};

/// Controls when on-chain settlement executes relative to the inner service.
///
/// # Variants
///
/// - **Sequential** (default): verify → execute → settle.  Settlement only
///   runs after the handler returns a successful response.  This is the
///   safest option — no settlement occurs on handler errors.
///
/// - **Concurrent**: verify → (settle ∥ execute) → await settle.  Settlement
///   is spawned immediately after verification and runs in parallel with the
///   handler, reducing total request latency by one facilitator RTT.
///   On handler error the settlement task is detached (fire-and-forget).
///
/// - **Background**: verify → spawn settle (fire-and-forget) → execute → return.
///   Settlement runs entirely in the background — the response is returned to
///   the client immediately after the handler completes, without waiting for
///   settlement.  Ideal for **streaming** responses (e.g. SSE / LLM token
///   streams) where the client should start receiving data as soon as possible.
///   **Trade-off:** the `Payment-Response` header is not attached since settlement
///   may still be in progress when the response is sent.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum SettlementMode {
    /// Settlement runs **after** the handler completes.
    #[default]
    Sequential,
    /// Settlement runs **concurrently** with the handler; response waits for settlement.
    Concurrent,
    /// Settlement is fire-and-forget; response is returned immediately.
    Background,
}

/// The main X402 middleware instance for enforcing x402 payments on routes.
///
/// Create a single instance per application and use it to build payment layers
/// for protected routes.
pub struct X402Middleware<F> {
    facilitator: F,
    base_url: Option<Url>,
}

impl<F: Clone> Clone for X402Middleware<F> {
    fn clone(&self) -> Self {
        Self {
            facilitator: self.facilitator.clone(),
            base_url: self.base_url.clone(),
        }
    }
}

impl<F: std::fmt::Debug> std::fmt::Debug for X402Middleware<F> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("X402Middleware")
            .field("facilitator", &self.facilitator)
            .field("base_url", &self.base_url)
            .finish()
    }
}

impl<F> X402Middleware<F> {
    /// Creates a middleware instance from any facilitator implementation.
    ///
    /// Use this when you already have a configured facilitator (e.g. one
    /// with custom timeouts, caching, or a non-default HTTP client).
    #[must_use]
    pub const fn from_facilitator(facilitator: F) -> Self {
        Self {
            facilitator,
            base_url: None,
        }
    }

    /// Returns a reference to the underlying facilitator.
    pub const fn facilitator(&self) -> &F {
        &self.facilitator
    }
}

impl X402Middleware<Arc<FacilitatorClient>> {
    /// Creates a new middleware instance with a default facilitator URL.
    ///
    /// # Panics
    ///
    /// Panics if the facilitator URL is invalid.
    #[must_use]
    #[allow(
        clippy::expect_used,
        reason = "constructor panics on invalid URL by design"
    )]
    pub fn new(url: &str) -> Self {
        let facilitator = FacilitatorClient::try_from(url).expect("Invalid facilitator URL");
        Self {
            facilitator: Arc::new(facilitator),
            base_url: None,
        }
    }

    /// Creates a new middleware instance with a facilitator URL.
    ///
    /// # Errors
    ///
    /// Returns an error if the URL is invalid.
    pub fn try_new(url: &str) -> Result<Self, Box<dyn std::error::Error>> {
        let facilitator = FacilitatorClient::try_from(url)?;
        Ok(Self {
            facilitator: Arc::new(facilitator),
            base_url: None,
        })
    }

    /// Returns the configured facilitator URL.
    #[must_use]
    pub fn facilitator_url(&self) -> &Url {
        self.facilitator.base_url()
    }

    /// Sets the TTL for caching the facilitator's supported response.
    ///
    /// Default is 10 minutes. Use [`FacilitatorClient::without_supported_cache()`]
    /// to disable caching entirely.
    #[must_use]
    pub fn with_supported_cache_ttl(&self, ttl: Duration) -> Self {
        let inner = Arc::unwrap_or_clone(Arc::clone(&self.facilitator));
        let facilitator = Arc::new(inner.with_supported_cache_ttl(ttl));
        Self {
            facilitator,
            base_url: self.base_url.clone(),
        }
    }

    /// Sets a per-request timeout for all facilitator HTTP calls (verify, settle, supported).
    ///
    /// Without this, the underlying `reqwest::Client` uses no timeout by default,
    /// which can cause requests to hang indefinitely if the facilitator is slow
    /// or unreachable, eventually triggering OS-level TCP timeouts (typically 2–5 minutes).
    ///
    /// A reasonable production value is 30 seconds.
    #[must_use]
    pub fn with_facilitator_timeout(&self, timeout: Duration) -> Self {
        let inner = Arc::unwrap_or_clone(Arc::clone(&self.facilitator));
        let facilitator = Arc::new(inner.with_timeout(timeout));
        Self {
            facilitator,
            base_url: self.base_url.clone(),
        }
    }
}

impl TryFrom<&str> for X402Middleware<Arc<FacilitatorClient>> {
    type Error = Box<dyn std::error::Error>;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::try_new(value)
    }
}

impl TryFrom<String> for X402Middleware<Arc<FacilitatorClient>> {
    type Error = Box<dyn std::error::Error>;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::try_new(&value)
    }
}

impl<F> X402Middleware<F>
where
    F: Clone,
{
    /// Sets the base URL used to construct resource URLs dynamically.
    ///
    /// If [`X402LayerBuilder::with_resource`] is not called, this base URL is combined with
    /// each request's path/query to compute the resource. If not set, defaults to `http://localhost/`.
    ///
    /// In production, prefer calling `with_resource` or setting a precise `base_url`.
    #[must_use]
    pub fn with_base_url(&self, base_url: Url) -> Self {
        let mut this = self.clone();
        this.base_url = Some(base_url);
        this
    }
}

impl<TFacilitator> X402Middleware<TFacilitator>
where
    TFacilitator: Clone,
{
    /// Sets the price tag for the protected route.
    ///
    /// Creates a layer builder that can be further configured with additional
    /// price tags and resource information.
    #[must_use]
    pub fn with_price_tag(
        &self,
        price_tag: v2::PriceTag,
    ) -> X402LayerBuilder<StaticPriceTags, TFacilitator> {
        X402LayerBuilder {
            facilitator: self.facilitator.clone(),
            price_source: StaticPriceTags::new(vec![price_tag]),
            base_url: self.base_url.clone().map(Arc::new),
            resource: Arc::new(ResourceTemplate::default()),
            settlement_mode: SettlementMode::default(),
        }
    }

    /// Sets multiple price tags for the protected route.
    ///
    /// Convenience method for services that accept several payment options
    /// (e.g. multiple tokens / networks).  Returns an empty-bypass builder
    /// when the list is empty — the middleware will pass requests through
    /// without payment enforcement.
    #[must_use]
    pub fn with_price_tags(
        &self,
        price_tags: Vec<v2::PriceTag>,
    ) -> X402LayerBuilder<StaticPriceTags, TFacilitator> {
        X402LayerBuilder {
            facilitator: self.facilitator.clone(),
            price_source: StaticPriceTags::new(price_tags),
            base_url: self.base_url.clone().map(Arc::new),
            resource: Arc::new(ResourceTemplate::default()),
            settlement_mode: SettlementMode::default(),
        }
    }

    /// Sets a dynamic price source for the protected route.
    ///
    /// The `callback` receives request headers, URI, and base URL, and returns
    /// a vector of V2 price tags.
    #[must_use]
    pub fn with_dynamic_price<F, Fut>(
        &self,
        callback: F,
    ) -> X402LayerBuilder<DynamicPriceTags, TFacilitator>
    where
        F: Fn(&HeaderMap, &Uri, Option<&Url>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Vec<v2::PriceTag>> + Send + 'static,
    {
        X402LayerBuilder {
            facilitator: self.facilitator.clone(),
            price_source: DynamicPriceTags::new(callback),
            base_url: self.base_url.clone().map(Arc::new),
            resource: Arc::new(ResourceTemplate::default()),
            settlement_mode: SettlementMode::default(),
        }
    }
}

/// Builder for configuring the X402 middleware layer.
///
/// Generic over `TSource` which implements [`PriceTagSource`] to support
/// both static and dynamic pricing strategies.
#[derive(Clone)]
#[allow(
    missing_debug_implementations,
    reason = "generic types may not impl Debug"
)]
pub struct X402LayerBuilder<TSource, TFacilitator> {
    facilitator: TFacilitator,
    base_url: Option<Arc<Url>>,
    price_source: TSource,
    resource: Arc<ResourceTemplate>,
    settlement_mode: SettlementMode,
}

impl<TFacilitator> X402LayerBuilder<StaticPriceTags, TFacilitator> {
    /// Adds another payment option.
    ///
    /// Allows specifying multiple accepted payment methods (e.g., different networks).
    ///
    /// Note: This method is only available for static price tag sources.
    #[must_use]
    pub fn with_price_tag(mut self, price_tag: v2::PriceTag) -> Self {
        self.price_source = self.price_source.with_price_tag(price_tag);
        self
    }
}

#[allow(
    missing_debug_implementations,
    reason = "generic types may not impl Debug"
)]
impl<TSource, TFacilitator> X402LayerBuilder<TSource, TFacilitator> {
    /// Sets a description of what the payment grants access to.
    ///
    /// This is included in 402 responses to inform clients what they're paying for.
    #[must_use]
    pub fn with_description(mut self, description: String) -> Self {
        let mut new_resource = (*self.resource).clone();
        new_resource.description = description;
        self.resource = Arc::new(new_resource);
        self
    }

    /// Sets the MIME type of the protected resource.
    ///
    /// Defaults to `application/json` if not specified.
    #[must_use]
    pub fn with_mime_type(mut self, mime: String) -> Self {
        let mut new_resource = (*self.resource).clone();
        new_resource.mime_type = mime;
        self.resource = Arc::new(new_resource);
        self
    }

    /// Sets the full URL of the protected resource.
    ///
    /// When set, this URL is used directly instead of constructing it from the base URL
    /// and request URI. This is the preferred approach in production.
    #[must_use]
    #[allow(
        clippy::needless_pass_by_value,
        reason = "Url consumed via to_string()"
    )]
    pub fn with_resource(mut self, resource: Url) -> Self {
        let mut new_resource = (*self.resource).clone();
        new_resource.url = Some(resource.to_string());
        self.resource = Arc::new(new_resource);
        self
    }

    /// Sets the settlement mode.
    ///
    /// - [`SettlementMode::Sequential`] (default): verify → execute → settle.
    /// - [`SettlementMode::Concurrent`]: verify → (settle ∥ execute) → await settle.
    /// - [`SettlementMode::Background`]: verify → spawn settle → execute → return.
    ///
    /// Concurrent mode reduces total latency by overlapping settlement with
    /// handler execution. Background mode is ideal for streaming responses
    /// where the client should receive data immediately (settlement errors
    /// are logged but do not propagate).
    #[must_use]
    pub const fn with_settlement_mode(mut self, mode: SettlementMode) -> Self {
        self.settlement_mode = mode;
        self
    }
}

impl<S, TSource, TFacilitator> Layer<S> for X402LayerBuilder<TSource, TFacilitator>
where
    S: Service<Request, Response = Response, Error = Infallible> + Clone + Send + Sync + 'static,
    S::Future: Send + 'static,
    TFacilitator: Facilitator + Clone,
    TSource: PriceTagSource,
{
    type Service = X402MiddlewareService<TSource, TFacilitator>;

    fn layer(&self, inner: S) -> Self::Service {
        X402MiddlewareService {
            facilitator: self.facilitator.clone(),
            base_url: self.base_url.clone(),
            price_source: self.price_source.clone(),
            resource: Arc::clone(&self.resource),
            settlement_mode: self.settlement_mode,
            inner: BoxCloneSyncService::new(inner),
        }
    }
}

/// Axum service that enforces x402 payments on incoming requests.
///
/// Generic over `TSource` which implements [`PriceTagSource`] to support
/// both static and dynamic pricing strategies.
#[derive(Clone)]
#[allow(
    missing_debug_implementations,
    reason = "BoxCloneSyncService does not impl Debug"
)]
pub struct X402MiddlewareService<TSource, TFacilitator> {
    /// Payment facilitator (local or remote)
    facilitator: TFacilitator,
    /// Base URL for constructing resource URLs
    base_url: Option<Arc<Url>>,
    /// Price tag source - can be static or dynamic
    price_source: TSource,
    /// Resource information
    resource: Arc<ResourceTemplate>,
    /// Settlement strategy (sequential, concurrent, or background)
    settlement_mode: SettlementMode,
    /// The inner Axum service being wrapped
    inner: BoxCloneSyncService<Request, Response, Infallible>,
}

impl<TSource, TFacilitator> Service<Request> for X402MiddlewareService<TSource, TFacilitator>
where
    TSource: PriceTagSource,
    TFacilitator: Facilitator + Clone + Send + Sync + 'static,
{
    type Response = Response;
    type Error = Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>;

    /// Delegates readiness polling to the wrapped inner service.
    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    /// Intercepts the request, injects payment enforcement logic, and forwards to the wrapped service.
    fn call(&mut self, req: Request) -> Self::Future {
        let price_source = self.price_source.clone();
        let facilitator = self.facilitator.clone();
        let base_url = self.base_url.clone();
        let resource_builder = Arc::clone(&self.resource);
        let settlement_mode = self.settlement_mode;
        let mut inner = self.inner.clone();

        Box::pin(async move {
            // Resolve price tags from the source
            let accepts = price_source
                .resolve(req.headers(), req.uri(), base_url.as_deref())
                .await;

            // If no price tags are configured, bypass payment enforcement
            if accepts.is_empty() {
                return inner.call(req).await;
            }

            let resource = resource_builder.resolve(base_url.as_deref(), &req);

            let mut gate = Paygate::builder(facilitator)
                .accepts(accepts)
                .resource(resource)
                .build();
            gate.enrich_accepts().await;

            let result = match settlement_mode {
                SettlementMode::Sequential => gate.handle_request(inner, req).await,
                SettlementMode::Concurrent => gate.handle_request_concurrent(inner, req).await,
                SettlementMode::Background => gate.handle_request_background(inner, req).await,
            };
            Ok(result.unwrap_or_else(|err| gate.error_response(err)))
        })
    }
}