Skip to main content

bsv_wallet_cli/server/
mod.rs

1pub mod audit;
2pub mod broadcast_follow_up;
3pub mod handlers;
4pub mod post_word;
5pub mod types;
6
7use anyhow::Result;
8use axum::extract::{DefaultBodyLimit, Request};
9use axum::http::{HeaderMap, StatusCode};
10use axum::middleware::{self, Next};
11use axum::response::{IntoResponse, Response};
12use axum::routing::{get, post};
13use axum::{Json, Router};
14use bsv_wallet_toolbox::{Chain, Services, StorageSqlx, Wallet};
15use serde_json::json;
16use std::net::SocketAddr;
17use std::sync::Arc;
18use tower_http::cors::CorsLayer;
19use tower_http::trace::TraceLayer;
20
21use handlers::WalletState;
22
23/// Lock that serializes spending operations (createAction).
24/// Non-spending endpoints (encrypt, getPublicKey, listOutputs, etc.) are unaffected.
25///
26/// Why: With limited UTXOs, concurrent createAction calls race on SQLite's write lock
27/// and the loser gets SQLITE_BUSY_SNAPSHOT instead of waiting for the winner's change
28/// output. This lock queues them so each spending request sees the previous one's change.
29pub type SpendingLock = Arc<tokio::sync::Mutex<()>>;
30
31/// TLS configuration (cert + key paths).
32#[derive(Clone)]
33#[allow(dead_code)]
34pub struct TlsConfig {
35    pub cert_path: String,
36    pub key_path: String,
37}
38
39/// Server configuration (auth, TLS, etc.)
40#[derive(Clone)]
41pub struct ServerConfig {
42    /// Optional bearer token. When set, all requests must include
43    /// `Authorization: Bearer <token>`. When None, auth is disabled.
44    pub auth_token: Option<String>,
45    /// Optional TLS config. Requires `--features tls` at build time.
46    pub tls: Option<TlsConfig>,
47    /// Network the served wallet is on. Drives post-broadcast verification
48    /// (which ARC / WoC endpoints to probe). Defaults to `Main`.
49    pub chain: Chain,
50    /// Address to bind (default `127.0.0.1`). Set `BIND_ADDR=0.0.0.0` for the
51    /// tunnel/public-webhook case (`POST /arc-callback` behind cloudflared /
52    /// tailscale funnel / direct TLS).
53    pub bind_addr: std::net::IpAddr,
54    /// Per-wallet ARC/Arcade callback token. When set, `POST /arc-callback`
55    /// is enabled, authenticated by THIS token (`Authorization: Bearer` or
56    /// `X-CallbackToken`) and EXEMPT from the wallet bearer auth above.
57    pub callback_token: Option<String>,
58}
59
60impl Default for ServerConfig {
61    fn default() -> Self {
62        Self {
63            auth_token: None,
64            tls: None,
65            chain: Chain::Main,
66            bind_addr: std::net::IpAddr::from([127, 0, 0, 1]),
67            callback_token: None,
68        }
69    }
70}
71
72/// The address to bind: `BIND_ADDR` when it parses, else `127.0.0.1`. Read
73/// by every served command and by the bind guard, so the two agree.
74pub fn bind_addr_from_env() -> std::net::IpAddr {
75    std::env::var("BIND_ADDR")
76        .ok()
77        .and_then(|v| v.parse().ok())
78        .unwrap_or_else(|| std::net::IpAddr::from([127, 0, 0, 1]))
79}
80
81/// The bind guard (0.7.1). With no bearer token a served wallet answers any
82/// caller that can reach it, and its two BEEF doors take a body of any size
83/// (0.7.0), so an address beyond loopback needs a token or the operator's
84/// explicit `allow_no_token`. An empty token counts as none. Loopback is
85/// unchanged. Run at startup, before the wallet is opened or a socket bound.
86pub fn refuse_open_bind(
87    bind_addr: std::net::IpAddr,
88    auth_token: Option<&str>,
89    allow_no_token: bool,
90) -> Result<()> {
91    let has_token = auth_token.is_some_and(|t| !t.is_empty());
92    if has_token || allow_no_token || bind_addr.to_canonical().is_loopback() {
93        return Ok(());
94    }
95    anyhow::bail!(
96        "refusing to bind {bind_addr}: no bearer token is configured, and a wallet served \
97         beyond loopback without one answers anyone who can reach it. Set AUTH_TOKEN, or pass \
98         --allow-no-token to bind it open deliberately."
99    )
100}
101
102/// [`refuse_open_bind`] on the environment the served commands read
103/// (`BIND_ADDR`, `AUTH_TOKEN`).
104pub fn refuse_open_bind_from_env(allow_no_token: bool) -> Result<()> {
105    let token = std::env::var("AUTH_TOKEN").ok();
106    refuse_open_bind(bind_addr_from_env(), token.as_deref(), allow_no_token)
107}
108
109/// Auth middleware — checks Bearer token if configured.
110async fn auth_middleware(headers: HeaderMap, request: Request, next: Next) -> Response {
111    // /arc-callback is EXEMPT from wallet bearer auth: it is authenticated by
112    // the per-wallet callback token inside its own handler (ARC/Arcade call it
113    // with `Authorization: Bearer <callback-token>`, not the wallet token).
114    if request.uri().path() == "/arc-callback" {
115        return next.run(request).await;
116    }
117
118    // Extract config from request extensions
119    let token = request
120        .extensions()
121        .get::<ServerConfig>()
122        .and_then(|c| c.auth_token.clone());
123
124    if let Some(expected) = token {
125        let provided = headers
126            .get("authorization")
127            .and_then(|v| v.to_str().ok())
128            .and_then(|v| v.strip_prefix("Bearer "));
129
130        match provided {
131            Some(t) if t == expected => {}
132            _ => {
133                return (
134                    StatusCode::UNAUTHORIZED,
135                    Json(json!({"code": "UNAUTHORIZED", "message": "Invalid or missing bearer token"})),
136                )
137                    .into_response();
138            }
139        }
140    }
141
142    next.run(request).await
143}
144
145/// Build the axum Router with all 28 WalletInterface endpoints.
146pub fn make_router(wallet: WalletState, config: ServerConfig) -> Router {
147    let cors = CorsLayer::very_permissive();
148    let cfg = config.clone();
149    let spending_lock: SpendingLock = Arc::new(tokio::sync::Mutex::new(()));
150    // Post-broadcast verifier — lets `/createAction` fail loudly when ARC
151    // silently dropped an immediate broadcast (e.g. 465 fee-too-low on a deep
152    // unconfirmed BEEF) instead of returning a phantom txid.
153    let verifier = crate::broadcast_verify::BroadcastVerifier::from_env(config.chain);
154
155    Router::new()
156        // Existing 5 endpoints
157        // Status endpoints accept BOTH GET and POST: @bsv/sdk's HTTPWalletJSON substrate
158        // POSTs every method (incl. these), while curl/CLI clients GET them. Supporting
159        // both makes the server wire-compatible with browser WalletClient connections.
160        .route(
161            "/isAuthenticated",
162            get(handlers::is_authenticated).post(handlers::is_authenticated),
163        )
164        .route("/getPublicKey", post(handlers::get_public_key))
165        // PERMISSION AUDIT (not BRC-100): what a wallet with a human behind it
166        // would have prompted for. See `audit.rs` — this daemon grants everything
167        // silently, which is what makes it headless AND blind.
168        .route("/permission-audit", get(permission_audit))
169        .route("/permission-audit/reset", post(permission_audit_reset))
170        .route("/createSignature", post(handlers::create_signature))
171        // The two doors that carry a caller's BEEF (`inputBEEF`, `tx`): no
172        // body cap, a valid BEEF is never refused for its size (see
173        // `BEEF_DOORS`).
174        .route(
175            "/createAction",
176            post(handlers::create_action).layer(DefaultBodyLimit::disable()),
177        )
178        .route(
179            "/internalizeAction",
180            post(handlers::internalize_action).layer(DefaultBodyLimit::disable()),
181        )
182        // Batch 1: Status (GET + POST for HTTPWalletJSON compat)
183        .route(
184            "/getHeight",
185            get(handlers::get_height).post(handlers::get_height),
186        )
187        .route(
188            "/getNetwork",
189            get(handlers::get_network).post(handlers::get_network),
190        )
191        .route(
192            "/getVersion",
193            get(handlers::get_version).post(handlers::get_version),
194        )
195        .route(
196            "/waitForAuthentication",
197            get(handlers::wait_for_authentication).post(handlers::wait_for_authentication),
198        )
199        // Batch 2: Header
200        .route("/getHeaderForHeight", post(handlers::get_header_for_height))
201        // Batch 3: Crypto
202        .route("/verifySignature", post(handlers::verify_signature))
203        .route("/encrypt", post(handlers::encrypt))
204        .route("/decrypt", post(handlers::decrypt))
205        .route("/createHmac", post(handlers::create_hmac))
206        .route("/verifyHmac", post(handlers::verify_hmac))
207        // Batch 4: Transaction workflow
208        .route("/signAction", post(handlers::sign_action))
209        .route("/abortAction", post(handlers::abort_action))
210        .route("/listActions", post(handlers::list_actions))
211        .route("/listOutputs", post(handlers::list_outputs))
212        .route("/relinquishOutput", post(handlers::relinquish_output))
213        // Batch 5: Certificates
214        .route("/acquireCertificate", post(handlers::acquire_certificate))
215        .route("/listCertificates", post(handlers::list_certificates))
216        .route("/proveCertificate", post(handlers::prove_certificate))
217        .route(
218            "/relinquishCertificate",
219            post(handlers::relinquish_certificate),
220        )
221        // Batch 6: Discovery + Key linkage
222        .route(
223            "/discoverByIdentityKey",
224            post(handlers::discover_by_identity_key),
225        )
226        .route(
227            "/discoverByAttributes",
228            post(handlers::discover_by_attributes),
229        )
230        .route(
231            "/revealCounterpartyKeyLinkage",
232            post(handlers::reveal_counterparty_key_linkage),
233        )
234        .route(
235            "/revealSpecificKeyLinkage",
236            post(handlers::reveal_specific_key_linkage),
237        )
238        // ARC/Arcade proof-delivery webhook (callback-token auth, exempt from
239        // wallet bearer auth — see auth_middleware).
240        .route("/arc-callback", post(arc_callback))
241        // The last layer added runs first: body limit, trace, the
242        // extensions, then auth BEFORE the body is read (an uncapped BEEF
243        // door is open only to the wallet's own caller), then the body.
244        .layer(cors)
245        .layer(middleware::from_fn(lenient_json_body))
246        .layer(middleware::from_fn(auth_middleware))
247        .layer(axum::Extension(cfg))
248        .layer(axum::Extension(spending_lock))
249        .layer(axum::Extension(verifier))
250        .layer(TraceLayer::new_for_http())
251        .layer(DefaultBodyLimit::max(BODY_CAP))
252        .with_state(wallet)
253}
254
255/// `POST /arc-callback` — ARC/Arcade status webhook receiving push status
256/// updates and (on MINED) the merkle path, straight into wallet storage.
257///
258/// Authenticated by the per-wallet callback token: ARC-convention
259/// `Authorization: Bearer <callback-token>` or an `X-CallbackToken` header
260/// (both accepted — broadcaster implementations vary). Returns 404 when no
261/// callback token is configured (route effectively disabled).
262async fn arc_callback(
263    axum::extract::State(wallet): axum::extract::State<WalletState>,
264    request: Request,
265) -> Response {
266    let expected = request
267        .extensions()
268        .get::<ServerConfig>()
269        .and_then(|c| c.callback_token.clone());
270    let Some(expected) = expected else {
271        return (
272            StatusCode::NOT_FOUND,
273            Json(json!({"code": "CALLBACK_DISABLED", "message": "no callback token configured"})),
274        )
275            .into_response();
276    };
277
278    let headers = request.headers().clone();
279    let provided = headers
280        .get("authorization")
281        .and_then(|v| v.to_str().ok())
282        .and_then(|v| v.strip_prefix("Bearer "))
283        .map(str::to_string)
284        .or_else(|| {
285            headers
286                .get("x-callbacktoken")
287                .and_then(|v| v.to_str().ok())
288                .map(str::to_string)
289        });
290
291    if provided.as_deref() != Some(expected.as_str()) {
292        // Arcade authenticates its webhook POSTs as `Authorization: Bearer
293        // <X-CallbackToken>` — a 401 here means a token mismatch and Arcade
294        // will burn its (~10) retries, then permanently drop the submission.
295        tracing::warn!(
296            has_authorization = headers.contains_key("authorization"),
297            has_x_callbacktoken = headers.contains_key("x-callbacktoken"),
298            "arc-callback: rejected POST with invalid/missing callback token"
299        );
300        return (
301            StatusCode::UNAUTHORIZED,
302            Json(json!({"code": "UNAUTHORIZED", "message": "invalid or missing callback token"})),
303        )
304            .into_response();
305    }
306
307    let bytes = match axum::body::to_bytes(request.into_body(), 1_000_000).await {
308        Ok(b) => b,
309        Err(_) => {
310            return (
311                StatusCode::PAYLOAD_TOO_LARGE,
312                Json(json!({"code": "TOO_LARGE", "message": "payload too large"})),
313            )
314                .into_response();
315        }
316    };
317    let payload: serde_json::Value = match serde_json::from_slice(&bytes) {
318        Ok(v) => v,
319        Err(e) => {
320            return (
321                StatusCode::BAD_REQUEST,
322                Json(json!({"code": "BAD_JSON", "message": e.to_string()})),
323            )
324                .into_response();
325        }
326    };
327
328    match crate::arc_ingest::ingest_arc_payload(wallet.storage(), &payload).await {
329        Ok(action) => (
330            StatusCode::OK,
331            Json(json!({"ok": true, "action": format!("{:?}", action)})),
332        )
333            .into_response(),
334        Err(e) => (
335            StatusCode::BAD_REQUEST,
336            Json(json!({"code": "BAD_PAYLOAD", "message": e.to_string()})),
337        )
338            .into_response(),
339    }
340}
341
342/// Browser wallets accept JSON whose strings carry lone UTF-16 surrogate escapes
343/// (`"\ud83d"` without its pair); serde does not, so a page whose keyID or data
344/// happened to contain one got `400 Failed to parse the request body as JSON:
345/// keyID: lone leading surrogate` from this wallet while MetaNet Desktop served
346/// the same call (beta soak, 2026-09-02, two logins lost). A browser's encoder
347/// turns such a code unit into U+FFFD when it hashes the string, so the same
348/// substitution here yields the same bytes the JS wallet would derive from.
349pub fn sanitize_lone_surrogates(input: &[u8]) -> std::borrow::Cow<'_, [u8]> {
350    if !input.windows(2).any(|w| w == b"\\u") {
351        return std::borrow::Cow::Borrowed(input);
352    }
353    let hex4 = |b: &[u8]| -> Option<u32> {
354        if b.len() < 4 {
355            return None;
356        }
357        std::str::from_utf8(&b[..4])
358            .ok()
359            .and_then(|h| u32::from_str_radix(h, 16).ok())
360    };
361    let mut out = Vec::with_capacity(input.len());
362    let mut i = 0;
363    let mut changed = false;
364    while i < input.len() {
365        if input[i] == b'\\' && i + 1 < input.len() && input[i + 1] == b'u' {
366            if let Some(cu) = hex4(&input[i + 2..]) {
367                let is_lead = (0xD800..=0xDBFF).contains(&cu);
368                let is_trail = (0xDC00..=0xDFFF).contains(&cu);
369                if is_lead {
370                    let next = &input[i + 6..];
371                    let paired = next.len() >= 6
372                        && next[0] == b'\\'
373                        && next[1] == b'u'
374                        && hex4(&next[2..]).is_some_and(|t| (0xDC00..=0xDFFF).contains(&t));
375                    if paired {
376                        out.extend_from_slice(&input[i..i + 12]);
377                        i += 12;
378                        continue;
379                    }
380                    out.extend_from_slice(b"\\ufffd");
381                    changed = true;
382                    i += 6;
383                    continue;
384                }
385                if is_trail {
386                    out.extend_from_slice(b"\\ufffd");
387                    changed = true;
388                    i += 6;
389                    continue;
390                }
391                out.extend_from_slice(&input[i..i + 6]);
392                i += 6;
393                continue;
394            }
395        }
396        out.push(input[i]);
397        i += 1;
398    }
399    if changed {
400        std::borrow::Cow::Owned(out)
401    } else {
402        std::borrow::Cow::Borrowed(input)
403    }
404}
405
406/// The routes whose JSON body carries a caller's BEEF. Their body is read
407/// whole with no cap: the BRC-100 JSON wire carries the BEEF as one array, so
408/// the body is held in memory (linear in the BEEF, about four bytes of body
409/// per byte of BEEF) and the BEEF is then judged by the toolbox's streaming
410/// reader for invalid bytes only. Every other route keeps
411/// [`BODY_CAP`].
412const BEEF_DOORS: [&str; 2] = ["/createAction", "/internalizeAction"];
413
414/// The body cap of the routes that carry no BEEF.
415const BODY_CAP: usize = 50 * 1024 * 1024;
416
417/// Rewrite lone surrogate escapes in JSON request bodies before the `Json`
418/// extractors see them (see [`sanitize_lone_surrogates`]).
419async fn lenient_json_body(request: Request, next: Next) -> Response {
420    let is_json = request
421        .headers()
422        .get(axum::http::header::CONTENT_TYPE)
423        .and_then(|v| v.to_str().ok())
424        .is_some_and(|ct| ct.to_ascii_lowercase().contains("json"));
425    if !is_json {
426        return next.run(request).await;
427    }
428    let (parts, body) = request.into_parts();
429    let cap = if BEEF_DOORS.contains(&parts.uri.path()) {
430        usize::MAX
431    } else {
432        BODY_CAP
433    };
434    let bytes = match axum::body::to_bytes(body, cap).await {
435        Ok(b) => b,
436        Err(_) => {
437            return (
438                StatusCode::PAYLOAD_TOO_LARGE,
439                Json(json!({"code": "TOO_LARGE", "message": "payload too large"})),
440            )
441                .into_response();
442        }
443    };
444    let body = match sanitize_lone_surrogates(&bytes) {
445        std::borrow::Cow::Borrowed(_) => axum::body::Body::from(bytes),
446        std::borrow::Cow::Owned(fixed) => {
447            tracing::warn!(
448                path = %parts.uri.path(),
449                "json body carried a lone UTF-16 surrogate escape; substituted U+FFFD"
450            );
451            axum::body::Body::from(fixed)
452        }
453    };
454    next.run(Request::from_parts(parts, body)).await
455}
456
457pub async fn run(wallet: WalletState, port: u16, config: ServerConfig) -> Result<()> {
458    let tls = config.tls.clone();
459    let bind_addr = config.bind_addr;
460    let app = make_router(wallet, config);
461    let addr = SocketAddr::from((bind_addr, port));
462
463    #[cfg(feature = "tls")]
464    if let Some(tls_cfg) = tls {
465        use axum_server::tls_rustls::RustlsConfig;
466        let rustls = RustlsConfig::from_pem_file(&tls_cfg.cert_path, &tls_cfg.key_path).await?;
467        tracing::info!("HTTPS server listening on {addr}");
468        eprintln!("HTTPS server listening on {addr}");
469        axum_server::bind_rustls(addr, rustls)
470            .serve(app.into_make_service())
471            .await?;
472        return Ok(());
473    }
474
475    #[cfg(not(feature = "tls"))]
476    if tls.is_some() {
477        anyhow::bail!("TLS requested but binary was built without `--features tls`");
478    }
479
480    tracing::info!("HTTP server listening on {addr}");
481    eprintln!("HTTP server listening on {addr}");
482
483    let listener = tokio::net::TcpListener::bind(addr).await?;
484    axum::serve(listener, app)
485        .with_graceful_shutdown(shutdown_signal())
486        .await?;
487
488    Ok(())
489}
490
491pub fn make_wallet_state(wallet: Wallet<StorageSqlx, Services>) -> WalletState {
492    Arc::new(wallet)
493}
494
495/// Build a `WalletState` from an existing `Arc<Wallet>`.
496///
497/// Use this when the caller is already holding an `Arc<Wallet>` and wants the
498/// HTTP server to share the *same* wallet instance — same identity key, same
499/// balance, same UTXO set. Avoids opening a second `Wallet` handle against
500/// the same SQLite DB (which would work via busy_timeout but adds write
501/// contention and a second instance of any in-memory caches).
502#[allow(dead_code)] // public API for external callers; not used inside this binary
503pub fn make_wallet_state_from_arc(wallet: Arc<Wallet<StorageSqlx, Services>>) -> WalletState {
504    wallet
505}
506
507async fn shutdown_signal() {
508    tokio::signal::ctrl_c()
509        .await
510        .expect("failed to listen for ctrl-c");
511    eprintln!("\nShutting down...");
512}
513
514/// GET /permission-audit — every permissioned request since start or reset.
515async fn permission_audit() -> Json<serde_json::Value> {
516    let entries = audit::snapshot();
517    Json(json!({ "count": entries.len(), "entries": entries }))
518}
519
520/// POST /permission-audit/reset — call immediately before the flow you measure.
521async fn permission_audit_reset() -> Json<serde_json::Value> {
522    audit::reset();
523    Json(json!({ "ok": true }))
524}
525
526#[cfg(test)]
527mod lenient_json_tests {
528    use super::sanitize_lone_surrogates;
529
530    #[test]
531    fn lone_lead_and_lone_trail_become_fffd_and_pairs_survive() {
532        let lead = br#"{"keyID":"ab \ud83d cd"}"#;
533        assert_eq!(
534            &*sanitize_lone_surrogates(lead),
535            br#"{"keyID":"ab \ufffd cd"}"#
536        );
537        let trail = br#"{"keyID":"\udc00"}"#;
538        assert_eq!(&*sanitize_lone_surrogates(trail), br#"{"keyID":"\ufffd"}"#);
539        let pair = br#"{"keyID":"\ud83d\ude00"}"#;
540        assert!(matches!(
541            sanitize_lone_surrogates(pair),
542            std::borrow::Cow::Borrowed(_)
543        ));
544        let plain = br#"{"keyID":"plain \\u0041"}"#;
545        assert!(matches!(
546            sanitize_lone_surrogates(plain),
547            std::borrow::Cow::Borrowed(_)
548        ));
549        let fixed = sanitize_lone_surrogates(lead);
550        let v: serde_json::Value = serde_json::from_slice(&fixed).unwrap();
551        assert_eq!(v["keyID"], "ab \u{fffd} cd");
552    }
553}
554
555#[cfg(test)]
556mod bind_guard_tests {
557    use super::refuse_open_bind;
558    use std::net::IpAddr;
559
560    fn ip(s: &str) -> IpAddr {
561        s.parse().unwrap()
562    }
563
564    #[test]
565    fn beyond_loopback_needs_a_token_or_the_flag() {
566        for open in ["0.0.0.0", "::", "192.168.1.10", "10.0.0.1"] {
567            let err = refuse_open_bind(ip(open), None, false).unwrap_err();
568            assert!(
569                err.to_string().contains("--allow-no-token"),
570                "{open}: {err}"
571            );
572            assert!(
573                refuse_open_bind(ip(open), Some(""), false).is_err(),
574                "{open}"
575            );
576            assert!(
577                refuse_open_bind(ip(open), Some("t"), false).is_ok(),
578                "{open}"
579            );
580            assert!(refuse_open_bind(ip(open), None, true).is_ok(), "{open}");
581        }
582    }
583
584    #[test]
585    fn loopback_is_unchanged() {
586        for lo in ["127.0.0.1", "127.0.0.2", "::1", "::ffff:127.0.0.1"] {
587            assert!(refuse_open_bind(ip(lo), None, false).is_ok(), "{lo}");
588        }
589    }
590}