r402-core 0.15.0

Core types, traits, and wire formats 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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! Lifecycle hooks for facilitator verify / settle operations.
//!
//! A [`HookedFacilitator`] wraps any [`Facilitator`] and runs registered
//! [`FacilitatorHooks`] at three lifecycle points:
//!
//! 1. **Before** — inspect or abort the operation.
//! 2. **After** — observe a successful result.
//! 3. **On failure** — observe or recover from an error.
//!
//! Hook methods use AFIT for zero-cost static dispatch when the hook type is
//! statically known. For heterogeneous lists (e.g. a registry collecting
//! multiple hook implementations) use the [`DynFacilitatorHooks`] erasure.

use std::fmt::{self, Debug, Formatter};
use std::future::Future;
use std::pin::Pin;

use crate::error::FacilitatorError;
use crate::facilitator::{BoxFuture, Facilitator};
use crate::wire::{
    SettleRequest, SettleResponse, SupportedResponse, VerifyRequest, VerifyResponse,
};

/// Decision returned by "before" hooks to control whether the operation
/// proceeds.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum HookDecision {
    /// Continue execution normally.
    Continue,
    /// Abort with a structured reason + message.
    Abort {
        /// Machine-readable reason for aborting.
        reason: String,
        /// Human-readable description.
        message: String,
    },
}

/// Outcome returned by "on failure" hooks, indicating whether recovery
/// happened.
#[derive(Debug)]
#[non_exhaustive]
pub enum FailureRecovery<T> {
    /// No recovery — propagate the original error.
    Propagate,
    /// The hook produced a substitute success result.
    Recovered(T),
}

/// Context passed to verify-related hooks.
#[derive(Clone)]
#[non_exhaustive]
pub struct VerifyContext {
    /// The incoming verify request.
    pub request: VerifyRequest,
}

impl Debug for VerifyContext {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("VerifyContext").finish_non_exhaustive()
    }
}

/// Context passed to settle-related hooks.
#[derive(Clone)]
#[non_exhaustive]
pub struct SettleContext {
    /// The incoming settle request.
    pub request: SettleRequest,
}

impl Debug for SettleContext {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("SettleContext").finish_non_exhaustive()
    }
}

/// Lifecycle hooks for facilitator verify and settle operations.
///
/// All methods default to a no-op — implementers override only what they
/// need. The trait uses AFIT for static dispatch; see
/// [`DynFacilitatorHooks`] for the object-safe erasure.
pub trait FacilitatorHooks: Send + Sync {
    /// Runs before every `verify` call.
    fn before_verify<'a>(
        &'a self,
        _ctx: &'a VerifyContext,
    ) -> impl Future<Output = HookDecision> + Send + 'a {
        async { HookDecision::Continue }
    }

    /// Runs after every successful `verify` call.
    fn after_verify<'a>(
        &'a self,
        _ctx: &'a VerifyContext,
        _response: &'a VerifyResponse,
    ) -> impl Future<Output = ()> + Send + 'a {
        async {}
    }

    /// Runs when a `verify` call returns an error.
    fn on_verify_failure<'a>(
        &'a self,
        _ctx: &'a VerifyContext,
        _error: &'a FacilitatorError,
    ) -> impl Future<Output = FailureRecovery<VerifyResponse>> + Send + 'a {
        async { FailureRecovery::Propagate }
    }

    /// Runs before every `settle` call.
    fn before_settle<'a>(
        &'a self,
        _ctx: &'a SettleContext,
    ) -> impl Future<Output = HookDecision> + Send + 'a {
        async { HookDecision::Continue }
    }

    /// Runs after every successful `settle` call.
    fn after_settle<'a>(
        &'a self,
        _ctx: &'a SettleContext,
        _response: &'a SettleResponse,
    ) -> impl Future<Output = ()> + Send + 'a {
        async {}
    }

    /// Runs when a `settle` call returns an error.
    fn on_settle_failure<'a>(
        &'a self,
        _ctx: &'a SettleContext,
        _error: &'a FacilitatorError,
    ) -> impl Future<Output = FailureRecovery<SettleResponse>> + Send + 'a {
        async { FailureRecovery::Propagate }
    }
}

/// Object-safe erasure of [`FacilitatorHooks`].
pub trait DynFacilitatorHooks: Send + Sync {
    /// See [`FacilitatorHooks::before_verify`].
    fn before_verify<'a>(
        &'a self,
        ctx: &'a VerifyContext,
    ) -> Pin<Box<dyn Future<Output = HookDecision> + Send + 'a>>;

    /// See [`FacilitatorHooks::after_verify`].
    fn after_verify<'a>(
        &'a self,
        ctx: &'a VerifyContext,
        response: &'a VerifyResponse,
    ) -> BoxFuture<'a, ()>;

    /// See [`FacilitatorHooks::on_verify_failure`].
    fn on_verify_failure<'a>(
        &'a self,
        ctx: &'a VerifyContext,
        error: &'a FacilitatorError,
    ) -> BoxFuture<'a, FailureRecovery<VerifyResponse>>;

    /// See [`FacilitatorHooks::before_settle`].
    fn before_settle<'a>(&'a self, ctx: &'a SettleContext) -> BoxFuture<'a, HookDecision>;

    /// See [`FacilitatorHooks::after_settle`].
    fn after_settle<'a>(
        &'a self,
        ctx: &'a SettleContext,
        response: &'a SettleResponse,
    ) -> BoxFuture<'a, ()>;

    /// See [`FacilitatorHooks::on_settle_failure`].
    fn on_settle_failure<'a>(
        &'a self,
        ctx: &'a SettleContext,
        error: &'a FacilitatorError,
    ) -> BoxFuture<'a, FailureRecovery<SettleResponse>>;
}

impl<T: FacilitatorHooks + ?Sized> DynFacilitatorHooks for T {
    fn before_verify<'a>(&'a self, ctx: &'a VerifyContext) -> BoxFuture<'a, HookDecision> {
        Box::pin(<Self as FacilitatorHooks>::before_verify(self, ctx))
    }

    fn after_verify<'a>(
        &'a self,
        ctx: &'a VerifyContext,
        response: &'a VerifyResponse,
    ) -> BoxFuture<'a, ()> {
        Box::pin(<Self as FacilitatorHooks>::after_verify(
            self, ctx, response,
        ))
    }

    fn on_verify_failure<'a>(
        &'a self,
        ctx: &'a VerifyContext,
        error: &'a FacilitatorError,
    ) -> BoxFuture<'a, FailureRecovery<VerifyResponse>> {
        Box::pin(<Self as FacilitatorHooks>::on_verify_failure(
            self, ctx, error,
        ))
    }

    fn before_settle<'a>(&'a self, ctx: &'a SettleContext) -> BoxFuture<'a, HookDecision> {
        Box::pin(<Self as FacilitatorHooks>::before_settle(self, ctx))
    }

    fn after_settle<'a>(
        &'a self,
        ctx: &'a SettleContext,
        response: &'a SettleResponse,
    ) -> BoxFuture<'a, ()> {
        Box::pin(<Self as FacilitatorHooks>::after_settle(
            self, ctx, response,
        ))
    }

    fn on_settle_failure<'a>(
        &'a self,
        ctx: &'a SettleContext,
        error: &'a FacilitatorError,
    ) -> BoxFuture<'a, FailureRecovery<SettleResponse>> {
        Box::pin(<Self as FacilitatorHooks>::on_settle_failure(
            self, ctx, error,
        ))
    }
}

/// Facilitator decorator that runs registered hooks around verify and settle.
///
/// Hook invocation order:
///
/// - **Before** hooks run in registration order; first `Abort` wins.
/// - **After** hooks run in registration order; errors are silently dropped.
/// - **On-failure** hooks run in registration order; first `Recovered` wins.
pub struct HookedFacilitator<F> {
    inner: F,
    hooks: Vec<Box<dyn DynFacilitatorHooks>>,
}

impl<F: Debug> Debug for HookedFacilitator<F> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("HookedFacilitator")
            .field("inner", &self.inner)
            .field("hooks", &format_args!("[{} hooks]", self.hooks.len()))
            .finish()
    }
}

impl<F> HookedFacilitator<F> {
    /// Wraps `inner` with an empty hook list.
    pub const fn new(inner: F) -> Self {
        Self {
            inner,
            hooks: Vec::new(),
        }
    }

    /// Registers a hook. Returns `self` so builder-style chaining works.
    #[must_use]
    pub fn with_hook(mut self, hook: impl FacilitatorHooks + 'static) -> Self {
        self.hooks.push(Box::new(hook));
        self
    }

    /// Registers a hook after construction.
    pub fn add_hook(&mut self, hook: impl FacilitatorHooks + 'static) {
        self.hooks.push(Box::new(hook));
    }

    /// Number of registered hooks.
    #[must_use]
    pub fn hook_count(&self) -> usize {
        self.hooks.len()
    }

    /// Returns a reference to the inner facilitator.
    #[must_use]
    pub const fn inner(&self) -> &F {
        &self.inner
    }
}

impl<F: Sync> HookedFacilitator<F> {
    async fn run_before_verify(&self, ctx: &VerifyContext) -> Result<(), FacilitatorError> {
        for hook in &self.hooks {
            if let HookDecision::Abort { reason, message } = hook.before_verify(ctx).await {
                return Err(FacilitatorError::Aborted { reason, message });
            }
        }
        Ok(())
    }

    async fn run_after_verify(&self, ctx: &VerifyContext, response: &VerifyResponse) {
        for hook in &self.hooks {
            hook.after_verify(ctx, response).await;
        }
    }

    async fn run_on_verify_failure(
        &self,
        ctx: &VerifyContext,
        error: &FacilitatorError,
    ) -> Option<VerifyResponse> {
        for hook in &self.hooks {
            if let FailureRecovery::Recovered(response) = hook.on_verify_failure(ctx, error).await {
                return Some(response);
            }
        }
        None
    }

    async fn run_before_settle(&self, ctx: &SettleContext) -> Result<(), FacilitatorError> {
        for hook in &self.hooks {
            if let HookDecision::Abort { reason, message } = hook.before_settle(ctx).await {
                return Err(FacilitatorError::Aborted { reason, message });
            }
        }
        Ok(())
    }

    async fn run_after_settle(&self, ctx: &SettleContext, response: &SettleResponse) {
        for hook in &self.hooks {
            hook.after_settle(ctx, response).await;
        }
    }

    async fn run_on_settle_failure(
        &self,
        ctx: &SettleContext,
        error: &FacilitatorError,
    ) -> Option<SettleResponse> {
        for hook in &self.hooks {
            if let FailureRecovery::Recovered(response) = hook.on_settle_failure(ctx, error).await {
                return Some(response);
            }
        }
        None
    }
}

impl<F: Facilitator + Sync> Facilitator for HookedFacilitator<F> {
    async fn verify(&self, request: VerifyRequest) -> Result<VerifyResponse, FacilitatorError> {
        let ctx = VerifyContext {
            request: request.clone(),
        };
        self.run_before_verify(&ctx).await?;
        match self.inner.verify(request).await {
            Ok(response) => {
                self.run_after_verify(&ctx, &response).await;
                Ok(response)
            }
            Err(error) => {
                let recovered = self.run_on_verify_failure(&ctx, &error).await;
                recovered.ok_or(error)
            }
        }
    }

    async fn settle(&self, request: SettleRequest) -> Result<SettleResponse, FacilitatorError> {
        let ctx = SettleContext {
            request: request.clone(),
        };
        self.run_before_settle(&ctx).await?;
        match self.inner.settle(request).await {
            Ok(response) => {
                self.run_after_settle(&ctx, &response).await;
                Ok(response)
            }
            Err(error) => {
                let recovered = self.run_on_settle_failure(&ctx, &error).await;
                recovered.ok_or(error)
            }
        }
    }

    async fn supported(&self) -> Result<SupportedResponse, FacilitatorError> {
        self.inner.supported().await
    }
}

#[cfg(test)]
#[allow(
    clippy::excessive_nesting,
    reason = "mock facilitator impls inherently nest async fn bodies inside impl-in-fn"
)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;
    use crate::error_reason::ErrorReason;
    use crate::wire::Extensions;

    struct MockFacilitator {
        fail: bool,
    }

    impl MockFacilitator {
        fn ok() -> Self {
            Self { fail: false }
        }
        fn failing() -> Self {
            Self { fail: true }
        }
    }

    impl Facilitator for MockFacilitator {
        fn verify(
            &self,
            _request: VerifyRequest,
        ) -> impl Future<Output = Result<VerifyResponse, FacilitatorError>> + Send {
            let result = if self.fail {
                Err(FacilitatorError::Onchain("mock".into()))
            } else {
                Ok(VerifyResponse::valid("0xPAYER"))
            };
            std::future::ready(result)
        }

        fn settle(
            &self,
            _request: SettleRequest,
        ) -> impl Future<Output = Result<SettleResponse, FacilitatorError>> + Send {
            let result = if self.fail {
                Err(FacilitatorError::Onchain("mock".into()))
            } else {
                Ok(SettleResponse::Success {
                    payer: "0xPAYER".into(),
                    transaction: "0xTX".into(),
                    network: "eip155:1".into(),
                    amount: None,
                    extensions: Extensions::new(),
                })
            };
            std::future::ready(result)
        }

        fn supported(
            &self,
        ) -> impl Future<Output = Result<SupportedResponse, FacilitatorError>> + Send {
            std::future::ready(Ok(SupportedResponse::default()))
        }
    }

    struct AbortVerifyHook;
    impl FacilitatorHooks for AbortVerifyHook {
        fn before_verify<'a>(
            &'a self,
            _: &VerifyContext,
        ) -> impl Future<Output = HookDecision> + Send + 'a {
            std::future::ready(HookDecision::Abort {
                reason: "blocked".into(),
                message: "test".into(),
            })
        }
    }

    struct AbortSettleHook;
    impl FacilitatorHooks for AbortSettleHook {
        fn before_settle<'a>(
            &'a self,
            _: &SettleContext,
        ) -> impl Future<Output = HookDecision> + Send + 'a {
            std::future::ready(HookDecision::Abort {
                reason: "blocked".into(),
                message: "test".into(),
            })
        }
    }

    struct RecoverVerifyHook;
    impl FacilitatorHooks for RecoverVerifyHook {
        fn on_verify_failure<'a>(
            &'a self,
            _: &VerifyContext,
            _: &FacilitatorError,
        ) -> impl Future<Output = FailureRecovery<VerifyResponse>> + Send + 'a {
            std::future::ready(FailureRecovery::Recovered(VerifyResponse::valid("0xREC")))
        }
    }

    struct RecoverSettleHook;
    impl FacilitatorHooks for RecoverSettleHook {
        fn on_settle_failure<'a>(
            &'a self,
            _: &SettleContext,
            _: &FacilitatorError,
        ) -> impl Future<Output = FailureRecovery<SettleResponse>> + Send + 'a {
            std::future::ready(FailureRecovery::Recovered(SettleResponse::Success {
                payer: "0xREC".into(),
                transaction: "0xREC_TX".into(),
                network: "eip155:1".into(),
                amount: None,
                extensions: Extensions::new(),
            }))
        }
    }

    struct NoopHook;
    impl FacilitatorHooks for NoopHook {}

    struct SecondAbortHook(&'static AtomicUsize);
    impl FacilitatorHooks for SecondAbortHook {
        fn before_verify<'a>(
            &'a self,
            _: &VerifyContext,
        ) -> impl Future<Output = HookDecision> + Send + 'a {
            let _ = self.0.fetch_add(1, Ordering::Relaxed);
            std::future::ready(HookDecision::Abort {
                reason: "second".into(),
                message: String::new(),
            })
        }
    }

    fn dummy_verify() -> VerifyRequest {
        serde_json::json!({}).into()
    }
    fn dummy_settle() -> SettleRequest {
        serde_json::json!({}).into()
    }

    #[tokio::test]
    async fn verify_no_hooks_passes_through() {
        let hooked = HookedFacilitator::new(MockFacilitator::ok());
        assert_eq!(hooked.hook_count(), 0);
        let response = hooked.verify(dummy_verify()).await.unwrap();
        assert!(response.is_valid());
    }

    #[tokio::test]
    async fn verify_before_hook_aborts() {
        let hooked = HookedFacilitator::new(MockFacilitator::ok()).with_hook(AbortVerifyHook);
        let err = hooked.verify(dummy_verify()).await.unwrap_err();
        assert!(matches!(err, FacilitatorError::Aborted { reason, .. } if reason == "blocked"));
    }

    #[tokio::test]
    async fn verify_failure_hook_recovers() {
        let hooked =
            HookedFacilitator::new(MockFacilitator::failing()).with_hook(RecoverVerifyHook);
        assert!(hooked.verify(dummy_verify()).await.unwrap().is_valid());
    }

    #[tokio::test]
    async fn verify_failure_hook_propagates_by_default() {
        let hooked = HookedFacilitator::new(MockFacilitator::failing()).with_hook(NoopHook);
        assert!(hooked.verify(dummy_verify()).await.is_err());
    }

    #[tokio::test]
    async fn settle_before_hook_aborts() {
        let hooked = HookedFacilitator::new(MockFacilitator::ok()).with_hook(AbortSettleHook);
        let err = hooked.settle(dummy_settle()).await.unwrap_err();
        assert!(matches!(err, FacilitatorError::Aborted { reason, .. } if reason == "blocked"));
    }

    #[tokio::test]
    async fn settle_success_passes_through() {
        let hooked = HookedFacilitator::new(MockFacilitator::ok());
        assert!(hooked.settle(dummy_settle()).await.unwrap().is_success());
    }

    #[tokio::test]
    async fn settle_failure_hook_recovers() {
        let hooked =
            HookedFacilitator::new(MockFacilitator::failing()).with_hook(RecoverSettleHook);
        assert!(hooked.settle(dummy_settle()).await.unwrap().is_success());
    }

    #[tokio::test]
    async fn first_abort_wins_remaining_skipped() {
        static SECOND_CALLS: AtomicUsize = AtomicUsize::new(0);
        SECOND_CALLS.store(0, Ordering::Relaxed);
        let hooked = HookedFacilitator::new(MockFacilitator::ok())
            .with_hook(AbortVerifyHook)
            .with_hook(SecondAbortHook(&SECOND_CALLS));
        let err = hooked.verify(dummy_verify()).await.unwrap_err();
        assert!(matches!(err, FacilitatorError::Aborted { reason, .. } if reason == "blocked"));
        assert_eq!(SECOND_CALLS.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn add_hook_dynamic() {
        let mut hooked = HookedFacilitator::new(MockFacilitator::ok());
        assert_eq!(hooked.hook_count(), 0);
        hooked.add_hook(NoopHook);
        assert_eq!(hooked.hook_count(), 1);
        assert!(hooked.verify(dummy_verify()).await.unwrap().is_valid());
    }

    #[tokio::test]
    async fn supported_delegates_to_inner() {
        let hooked = HookedFacilitator::new(MockFacilitator::ok());
        let response = hooked.supported().await.unwrap();
        assert!(response.kinds.is_empty());
        assert!(response.signers.is_empty());
    }

    #[tokio::test]
    async fn verify_invalid_response_with_reason_round_trip() {
        struct Invalid;
        impl Facilitator for Invalid {
            fn verify(
                &self,
                _r: VerifyRequest,
            ) -> impl Future<Output = Result<VerifyResponse, FacilitatorError>> + Send {
                std::future::ready(Ok(VerifyResponse::invalid(
                    None,
                    ErrorReason::InvalidPayload,
                )))
            }
            fn settle(
                &self,
                _r: SettleRequest,
            ) -> impl Future<Output = Result<SettleResponse, FacilitatorError>> + Send {
                std::future::ready(Err(FacilitatorError::Onchain("unreachable".into())))
            }
            fn supported(
                &self,
            ) -> impl Future<Output = Result<SupportedResponse, FacilitatorError>> + Send
            {
                std::future::ready(Ok(SupportedResponse::default()))
            }
        }
        let hooked = HookedFacilitator::new(Invalid);
        let response = hooked.verify(dummy_verify()).await.unwrap();
        match response {
            VerifyResponse::Invalid { reason, .. } => {
                assert_eq!(reason, ErrorReason::InvalidPayload);
            }
            VerifyResponse::Valid { .. } => panic!("expected invalid"),
        }
    }
}