From dafdf757af0475ebfd46f62e14f72a6a6cfdbc72 Mon Sep 17 00:00:00 2001 From: lollerfirst <43107113+lollerfirst@users.noreply.github.com> Date: Thu, 10 Apr 2025 14:47:35 +0200 Subject: [PATCH] CORS Headers in Responses (#719) * access control headers for CORS request from in-browser wallets * cargo fmt * handle preflight requests --- crates/cdk-axum/src/lib.rs | 45 +++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/crates/cdk-axum/src/lib.rs b/crates/cdk-axum/src/lib.rs index 34c1e91e..f7e2d432 100644 --- a/crates/cdk-axum/src/lib.rs +++ b/crates/cdk-axum/src/lib.rs @@ -9,6 +9,8 @@ use std::sync::Arc; use anyhow::Result; #[cfg(feature = "auth")] use auth::create_auth_router; +use axum::middleware::from_fn; +use axum::response::Response; use axum::routing::{get, post}; use axum::Router; use cache::HttpCache; @@ -137,6 +139,45 @@ pub async fn create_mint_router(mint: Arc) -> Result { create_mint_router_with_custom_cache(mint, Default::default()).await } +async fn cors_middleware( + req: axum::http::Request, + next: axum::middleware::Next, +) -> Response { + // Handle preflight requests + if req.method() == axum::http::Method::OPTIONS { + let mut response = Response::new("".into()); + response + .headers_mut() + .insert("Access-Control-Allow-Origin", "*".parse().unwrap()); + response.headers_mut().insert( + "Access-Control-Allow-Methods", + "GET, POST, OPTIONS".parse().unwrap(), + ); + response.headers_mut().insert( + "Access-Control-Allow-Headers", + "Content-Type".parse().unwrap(), + ); + return response; + } + + // Call the next handler + let mut response = next.run(req).await; + + response + .headers_mut() + .insert("Access-Control-Allow-Origin", "*".parse().unwrap()); + response.headers_mut().insert( + "Access-Control-Allow-Methods", + "GET, POST, OPTIONS".parse().unwrap(), + ); + response.headers_mut().insert( + "Access-Control-Allow-Headers", + "Content-Type".parse().unwrap(), + ); + + response +} + /// Create mint [`Router`] with required endpoints for cashu mint with a custom /// backend for cache pub async fn create_mint_router_with_custom_cache( @@ -170,7 +211,9 @@ pub async fn create_mint_router_with_custom_cache( .route("/info", get(get_mint_info)) .route("/restore", post(post_restore)); - let mint_router = Router::new().nest("/v1", v1_router); + let mint_router = Router::new() + .nest("/v1", v1_router) + .layer(from_fn(cors_middleware)); #[cfg(feature = "auth")] let mint_router = {