Skip to content
130 changes: 120 additions & 10 deletions crates/openhuman-core/src/modules/wallet_host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ pub(super) enum X402Route {
/// module has already reserved the amount against its own budget before
/// asking; the host re-checks the per-request cap as a second line.
AutomationApproved,
/// A direct `openhuman.x402_fetch` RPC holds a one-shot permit for this
/// URL and the amount is within both its cap and the per-request budget.
RpcPermitApproved,
/// The originating WebChat turn: ask the user with a forced approval.
PromptWebChat,
/// Refused, with the reason handed back to the module.
Expand Down Expand Up @@ -138,6 +141,113 @@ pub(super) fn x402_route(
}
}

/// How a direct-RPC x402 permit was used by the module's authorization callback.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum X402RpcPermitOutcome {
/// No authorization callback matched the permit.
Unused,
/// The payment was within the caller's cap and the per-request budget.
Approved,
/// The permit matched but the payment was refused, with the reason.
Refused(&'static str),
}

#[derive(Debug)]
struct X402RpcPermitEntry {
url: String,
max_amount_atomic: u64,
outcome: Option<X402RpcPermitOutcome>,
}

static X402_RPC_PERMITS: OnceLock<Mutex<HashMap<u64, X402RpcPermitEntry>>> = OnceLock::new();
static X402_RPC_PERMIT_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

fn x402_rpc_permits() -> &'static Mutex<HashMap<u64, X402RpcPermitEntry>> {
X402_RPC_PERMITS.get_or_init(|| Mutex::new(HashMap::new()))
}

/// One-shot x402 authorization for a direct `openhuman.x402_fetch` RPC call,
/// correlated by the exact URL the module reports in its callback and bounded
/// by the caller's `maxAmountAtomic`. Removed when dropped.
pub(super) struct X402RpcPermit(u64);

impl X402RpcPermit {
pub(super) fn new(url: &str, max_amount_atomic: u64) -> Self {
let id = X402_RPC_PERMIT_IDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if let Ok(mut permits) = x402_rpc_permits().lock() {
permits.insert(
id,
X402RpcPermitEntry {
url: url.to_owned(),
max_amount_atomic,
outcome: None,
},
);
}
Self(id)
}

/// Retire the permit and report what the authorization callback decided.
pub(super) fn finish(self) -> X402RpcPermitOutcome {
x402_rpc_permits()
.lock()
.ok()
.and_then(|mut permits| permits.remove(&self.0))
.and_then(|entry| entry.outcome)
.unwrap_or(X402RpcPermitOutcome::Unused)
}
}

impl Drop for X402RpcPermit {
fn drop(&mut self) {
if let Ok(mut permits) = x402_rpc_permits().lock() {
permits.remove(&self.0);
}
}
}

/// Consume an active, unused direct-RPC permit for `request.url` and decide
/// the payment against its cap and `per_request_max_atomic` (the module
/// budget's second line, as for automation). `None` when no permit matches,
/// so the caller falls through to [`x402_route`] unchanged.
pub(super) fn x402_rpc_permit_route(
request: &AuthorizeX402PaymentRequest,
per_request_max_atomic: u64,
) -> Option<X402Route> {
let mut permits = x402_rpc_permits().lock().ok()?;
let entry = permits
.values_mut()
.find(|entry| entry.outcome.is_none() && entry.url == request.url)?;
let refusal = if request.amount_atomic > entry.max_amount_atomic {
Some("x402 payment exceeds the caller's maxAmountAtomic")
} else if request.amount_atomic > per_request_max_atomic {
Some("x402 payment exceeds the per-request budget")
} else {
None
};
let (outcome, route) = match refusal {
Some(reason) => (
X402RpcPermitOutcome::Refused(reason),
X402Route::Refused(reason),
),
None => (X402RpcPermitOutcome::Approved, X402Route::RpcPermitApproved),
};
entry.outcome = Some(outcome);
Some(route)
}

/// Keep a direct-RPC x402 permit alive only while `future` (the module's
/// payment preparation) runs, and report how it was used.
pub(crate) async fn with_x402_rpc_permit<F: Future>(
url: &str,
max_amount_atomic: u64,
future: F,
) -> (F::Output, X402RpcPermitOutcome) {
let permit = X402RpcPermit::new(url, max_amount_atomic);
let output = future.await;
(output, permit.finish())
}

fn x402_approval_facts(request: &AuthorizeX402PaymentRequest) -> serde_json::Value {
serde_json::json!({
"url": request.url,
Expand Down Expand Up @@ -490,27 +600,27 @@ impl WalletHost {
}))
}

/// x402 authorization: a WebChat turn asks its user with a forced approval
/// (the guarded HTTP request path), trusted automation is approved within
/// the per-request budget ([`x402_route`]), and any other origin fails
/// closed.
/// x402 authorization: a direct `x402_fetch` RPC holding a permit for this
/// URL is approved within its cap and the per-request budget
/// ([`x402_rpc_permit_route`]); otherwise a WebChat turn asks its user with
/// a forced approval (the guarded HTTP request path), trusted automation is
/// approved within the per-request budget ([`x402_route`]), and any other
/// origin fails closed.
async fn authorize_x402_payment(
&self,
request: AuthorizeX402PaymentRequest,
) -> tinybus::Result<HostResponse> {
let origin = crate::core::runtime::DispatchCtx::ambient_turn().turn_origin();
let route = x402_route(
&request,
origin.as_ref(),
super::x402_service::per_request_max_atomic(),
);
let per_request_max_atomic = super::x402_service::per_request_max_atomic();
let route = x402_rpc_permit_route(&request, per_request_max_atomic)
.unwrap_or_else(|| x402_route(&request, origin.as_ref(), per_request_max_atomic));
tracing::debug!(
origin = origin.as_ref().map(|o| o.class()).unwrap_or_else(|| "none".into()),
route = ?route,
"[modules:wallet] x402 authorization"
);
let (approved, reason) = match route {
X402Route::AutomationApproved => (true, None),
X402Route::AutomationApproved | X402Route::RpcPermitApproved => (true, None),
X402Route::PromptWebChat => {
let approved = match crate::security::approval::ApprovalGate::try_global() {
Some(gate) => matches!(
Expand Down
95 changes: 93 additions & 2 deletions crates/openhuman-core/src/modules/wallet_host_tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use super::{
consume_approval, native_approval_matches_request, validate_module_endpoint_url,
web3_approval_matches_request, x402_approval_facts, x402_request_owner_matches, x402_route,
ApprovalKind, ApprovalPermit, X402Route,
web3_approval_matches_request, with_x402_rpc_permit, x402_approval_facts,
x402_request_owner_matches, x402_route, x402_rpc_permit_route, ApprovalKind, ApprovalPermit,
X402Route, X402RpcPermit, X402RpcPermitOutcome,
};
use tinywallet_bus::wire::{
AuthorizeNativeWalletExecutionRequest, AuthorizeWeb3ExecutionRequest,
Expand Down Expand Up @@ -605,3 +606,93 @@ fn x402_from_scheduled_actions_cron_is_budgeted_and_plain_cron_is_refused() {
X402Route::Refused(_)
));
}

fn x402_request_for(url: &str, amount_atomic: u64) -> AuthorizeX402PaymentRequest {
AuthorizeX402PaymentRequest {
url: url.into(),
..x402_request(amount_atomic, None)
}
}

#[test]
fn x402_rpc_permit_approves_a_payment_within_the_caller_cap() {
let url = "https://rpc-permit.example/within-cap";
let permit = X402RpcPermit::new(url, 500);
assert_eq!(
x402_rpc_permit_route(&x402_request_for(url, 500), 1_000),
Some(X402Route::RpcPermitApproved)
);
assert_eq!(permit.finish(), X402RpcPermitOutcome::Approved);
}

#[test]
fn x402_rpc_permit_refuses_a_payment_over_the_caller_cap() {
let url = "https://rpc-permit.example/over-cap";
let permit = X402RpcPermit::new(url, 500);
assert!(matches!(
x402_rpc_permit_route(&x402_request_for(url, 501), u64::MAX),
Some(X402Route::Refused(_))
));
assert!(matches!(permit.finish(), X402RpcPermitOutcome::Refused(_)));
}

#[test]
fn x402_rpc_permit_refuses_a_payment_over_the_per_request_budget() {
let url = "https://rpc-permit.example/over-budget";
let permit = X402RpcPermit::new(url, 1_000);
assert!(matches!(
x402_rpc_permit_route(&x402_request_for(url, 500), 499),
Some(X402Route::Refused(_))
));
assert!(matches!(permit.finish(), X402RpcPermitOutcome::Refused(_)));
}

#[test]
fn x402_without_a_matching_rpc_permit_keeps_the_existing_refusal() {
let permitted = "https://rpc-permit.example/permitted";
let other = "https://rpc-permit.example/other";
let permit = X402RpcPermit::new(permitted, u64::MAX);
// A permit for one URL never authorizes another; routing falls through.
assert_eq!(
x402_rpc_permit_route(&x402_request_for(other, 1), u64::MAX),
None
);
assert!(matches!(
x402_route(&x402_request_for(other, 1), None, u64::MAX),
X402Route::Refused(_)
));
assert_eq!(permit.finish(), X402RpcPermitOutcome::Unused);
// No permit at all: nothing is approved for a plain RPC caller.
assert_eq!(
x402_rpc_permit_route(&x402_request_for(permitted, 1), u64::MAX),
None
);
}

#[test]
fn x402_rpc_permit_is_consumed_by_the_first_authorization() {
let url = "https://rpc-permit.example/consumed-once";
let permit = X402RpcPermit::new(url, 10);
assert_eq!(
x402_rpc_permit_route(&x402_request_for(url, 1), 10),
Some(X402Route::RpcPermitApproved)
);
assert_eq!(x402_rpc_permit_route(&x402_request_for(url, 1), 10), None);
assert_eq!(permit.finish(), X402RpcPermitOutcome::Approved);
}

#[tokio::test]
async fn x402_rpc_permit_is_active_only_while_its_future_runs() {
let url = "https://rpc-permit.example/scoped";
let (route, outcome) = with_x402_rpc_permit(url, 10, async {
x402_rpc_permit_route(&x402_request_for(url, 10), 10)
})
.await;
assert_eq!(route, Some(X402Route::RpcPermitApproved));
assert_eq!(outcome, X402RpcPermitOutcome::Approved);
assert_eq!(x402_rpc_permit_route(&x402_request_for(url, 1), 10), None);

let ((), unused) = with_x402_rpc_permit(url, 10, async {}).await;
assert_eq!(unused, X402RpcPermitOutcome::Unused);
assert_eq!(x402_rpc_permit_route(&x402_request_for(url, 1), 10), None);
}
85 changes: 75 additions & 10 deletions crates/openhuman-core/src/modules/x402_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ use crate::config::Config;

use super::wallet::{self, WalletCallError};

pub(crate) use super::wallet_host::X402RpcPermitOutcome;

/// Prepare and sign a 402 challenge inside TinyWallet. Both supported rails'
/// secret material is sent only through the attested confidential call; the
/// module parses the challenge and selects the matching chain.
Expand All @@ -28,16 +30,72 @@ pub(crate) async fn prepare_payment(
payment_required: String,
owner: Option<tinywallet_bus::wire::QuoteOwner>,
) -> Result<(X402ServiceHandle, X402PreparePaymentResponse), WalletCallError> {
prepare(ctx, config, url, payment_required, owner, None)
.await
.0
}

/// [`prepare_payment`] for a direct `openhuman.x402_fetch` RPC caller, which
/// has no turn to approve through. The host's authorization callback approves
/// this payment only while a one-shot permit for `url` is active, and only
/// within `max_amount_atomic` and the per-request budget. The permit is
/// installed while the service lock is held, so it can only be matched by this
/// preparation. Returns how the permit was used so a refusal is recognisable.
pub(crate) async fn prepare_capped_payment(
ctx: &DispatchCtx,
config: &Config,
url: String,
payment_required: String,
max_amount_atomic: u64,
) -> (
Result<(X402ServiceHandle, X402PreparePaymentResponse), WalletCallError>,
X402RpcPermitOutcome,
) {
prepare(
ctx,
config,
url,
payment_required,
None,
Some(max_amount_atomic),
)
.await
}

async fn prepare(
ctx: &DispatchCtx,
config: &Config,
url: String,
payment_required: String,
owner: Option<tinywallet_bus::wire::QuoteOwner>,
rpc_cap: Option<u64>,
) -> (
Result<(X402ServiceHandle, X402PreparePaymentResponse), WalletCallError>,
X402RpcPermitOutcome,
) {
let mut active = service().lock().await;
ensure_service(ctx, config, &mut active).await?;
let service_handle = active
.as_ref()
.ok_or_else(|| WalletCallError::Failed("x402 service is unavailable".into()))?
.handle
.clone();
if let Err(error) = ensure_service(ctx, config, &mut active).await {
return (Err(error), X402RpcPermitOutcome::Unused);
}
let Some(service_handle) = active.as_ref().map(|current| current.handle.clone()) else {
return (
Err(WalletCallError::Failed(
"x402 service is unavailable".into(),
)),
X402RpcPermitOutcome::Unused,
);
};

let evm = signing_secret(ctx, config, crate::web3::wallet::WalletChain::Evm).await?;
let solana = signing_secret(ctx, config, crate::web3::wallet::WalletChain::Solana).await?;
let secrets = async {
let evm = signing_secret(ctx, config, crate::web3::wallet::WalletChain::Evm).await?;
let solana = signing_secret(ctx, config, crate::web3::wallet::WalletChain::Solana).await?;
Ok::<_, WalletCallError>((evm, solana))
};
let (evm, solana) = match secrets.await {
Ok(secrets) => secrets,
Err(error) => return (Err(error), X402RpcPermitOutcome::Unused),
};
let permit_url = url.clone();
let mut request = X402PreparePaymentRequest {
service: service_handle.clone(),
url,
Expand All @@ -46,12 +104,19 @@ pub(crate) async fn prepare_payment(
secret: evm,
additional_secrets: vec![solana],
};
let response = wallet::call_confidential(config, methods::X402_PREPARE_PAYMENT, &request).await;
let call = wallet::call_confidential(config, methods::X402_PREPARE_PAYMENT, &request);
let (response, outcome) = match rpc_cap {
Some(max_amount_atomic) => {
super::wallet_host::with_x402_rpc_permit(&permit_url, max_amount_atomic, call).await
}
None => (call.await, X402RpcPermitOutcome::Unused),
};
request.secret.mnemonic.zeroize();
for secret in &mut request.additional_secrets {
secret.mnemonic.zeroize();
}
Ok((service_handle, response?))
drop(active);
(response.map(|response| (service_handle, response)), outcome)
}

/// Record the retry result through the same module-owned payment ledger.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ Capability {
domain: "x402",
category: CapabilityCategory::Workflows,
description: "Automatic HTTP 402 payment handling for machine-payable APIs via the x402 protocol. When an API returns 402 Payment Required, the agent pays with USDC on Solana using the local wallet and retries. Budget enforcement with per-request, daily, and monthly caps; automated turns (background jobs, approval-free workflows) pay within the budget without a prompt.",
how_to: "Use x402.* RPC methods (get_summary, list_payments, update_budget) to manage spending. Payments happen automatically when the http_request tool encounters a 402 with a PAYMENT-REQUIRED header.",
how_to: "Use x402.* RPC methods (get_summary, list_payments, update_budget) to manage spending. Payments happen automatically when the http_request tool encounters a 402 with a PAYMENT-REQUIRED header; a local caller can make one paid HTTPS request with x402.fetch and an explicit maxAmountAtomic cap.",
status: CapabilityStatus::Beta,
privacy: LOCAL_CREDENTIALS,
},
Expand Down
Loading
Loading