| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
use anyhow::{Context, Result}; |
| 6 |
use http_body_util::{BodyExt, Full}; |
| 7 |
use hyper::body::Bytes; |
| 8 |
use spectra_core::keys::KeyPair; |
| 9 |
use spectra_core::proof::Proof; |
| 10 |
use std::path::{Path, PathBuf}; |
| 11 |
|
| 12 |
|
| 13 |
#[derive(Debug)] |
| 14 |
pub struct Response { |
| 15 |
pub status: u16, |
| 16 |
pub headers: Vec<(String, String)>, |
| 17 |
pub body: Vec<u8>, |
| 18 |
} |
| 19 |
|
| 20 |
impl Response { |
| 21 |
pub fn json(&self) -> Result<serde_json::Value> { |
| 22 |
serde_json::from_slice(&self.body).with_context(|| format!("not JSON: {}", String::from_utf8_lossy(&self.body))) |
| 23 |
} |
| 24 |
pub fn header(&self, name: &str) -> Option<&str> { |
| 25 |
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
#[derive(Clone)] |
| 32 |
pub enum Endpoint { |
| 33 |
Unix(PathBuf), |
| 34 |
Tls { addr: String, config: std::sync::Arc<rustls::ClientConfig> }, |
| 35 |
} |
| 36 |
|
| 37 |
impl Endpoint { |
| 38 |
|
| 39 |
pub fn tls(url: &str, pin: [u8; 32]) -> Result<Endpoint> { |
| 40 |
Ok(Endpoint::Tls { addr: host_port(url)?, config: crate::tls::Pinned::new(Some(pin)).client_config()? }) |
| 41 |
} |
| 42 |
|
| 43 |
pub fn describe(&self) -> String { |
| 44 |
match self { |
| 45 |
Endpoint::Unix(p) => p.display().to_string(), |
| 46 |
Endpoint::Tls { addr, .. } => format!("https://{addr}"), |
| 47 |
} |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
pub fn host_port(url: &str) -> Result<String> { |
| 53 |
let rest = url.strip_prefix("https://").with_context(|| format!("{url} is not an https:// URL"))?; |
| 54 |
let hp = rest.split('/').next().unwrap_or(""); |
| 55 |
if hp.is_empty() { |
| 56 |
anyhow::bail!("{url} names no host"); |
| 57 |
} |
| 58 |
|
| 59 |
let has_port = if hp.starts_with('[') { hp.contains("]:") } else { hp.contains(':') }; |
| 60 |
Ok(if has_port { hp.to_string() } else { format!("{hp}:7350") }) |
| 61 |
} |
| 62 |
|
| 63 |
trait Io: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send {} |
| 64 |
impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send> Io for T {} |
| 65 |
|
| 66 |
pub struct Client { |
| 67 |
endpoint: Endpoint, |
| 68 |
signer: Option<KeyPair>, |
| 69 |
} |
| 70 |
|
| 71 |
impl Client { |
| 72 |
pub fn new(socket: &Path, signer: Option<KeyPair>) -> Client { |
| 73 |
Client { endpoint: Endpoint::Unix(socket.to_path_buf()), signer } |
| 74 |
} |
| 75 |
|
| 76 |
pub fn at(endpoint: Endpoint, signer: Option<KeyPair>) -> Client { |
| 77 |
Client { endpoint, signer } |
| 78 |
} |
| 79 |
|
| 80 |
pub fn endpoint(&self) -> &Endpoint { |
| 81 |
&self.endpoint |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
pub fn signer(&self) -> Option<&KeyPair> { |
| 86 |
self.signer.as_ref() |
| 87 |
} |
| 88 |
|
| 89 |
async fn io(&self) -> Result<Box<dyn Io>> { |
| 90 |
Ok(match &self.endpoint { |
| 91 |
Endpoint::Unix(socket) => Box::new( |
| 92 |
tokio::net::UnixStream::connect(socket) |
| 93 |
.await |
| 94 |
.with_context(|| format!("connecting to {} (is `spectra serve` running?)", socket.display()))?, |
| 95 |
), |
| 96 |
Endpoint::Tls { addr, config } => Box::new(crate::tls::connect(addr, config.clone()).await?), |
| 97 |
}) |
| 98 |
} |
| 99 |
|
| 100 |
|
| 101 |
pub async fn reachable(&self) -> bool { |
| 102 |
self.io().await.is_ok() |
| 103 |
} |
| 104 |
|
| 105 |
|
| 106 |
pub async fn alive(socket: &Path) -> bool { |
| 107 |
tokio::net::UnixStream::connect(socket).await.is_ok() |
| 108 |
} |
| 109 |
|
| 110 |
|
| 111 |
pub async fn send(&self, method: &str, path: &str, headers: &[(&str, String)], body: Vec<u8>) -> Result<Response> { |
| 112 |
let stream = self.io().await?; |
| 113 |
let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?; |
| 114 |
tokio::spawn(async move { |
| 115 |
let _ = conn.await; |
| 116 |
}); |
| 117 |
|
| 118 |
|
| 119 |
let mut req = hyper::Request::builder().method(method).uri(path).header("host", "spectra").header("connection", "close"); |
| 120 |
|
| 121 |
if !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-type")) { |
| 122 |
req = req.header("content-type", "application/json"); |
| 123 |
} |
| 124 |
for (k, v) in headers { |
| 125 |
req = req.header(*k, v); |
| 126 |
} |
| 127 |
if let Some(pair) = &self.signer { |
| 128 |
for (k, v) in sign_headers(pair, &format!("{method} {path}"), &body) { |
| 129 |
req = req.header(k, v); |
| 130 |
} |
| 131 |
} |
| 132 |
let resp = sender.send_request(req.body(Full::new(Bytes::from(body)))?).await?; |
| 133 |
let status = resp.status().as_u16(); |
| 134 |
let headers = resp.headers().iter().map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())).collect(); |
| 135 |
let body = resp.into_body().collect().await?.to_bytes().to_vec(); |
| 136 |
Ok(Response { status, headers, body }) |
| 137 |
} |
| 138 |
|
| 139 |
|
| 140 |
pub async fn mcp(&self, version: &str, request: &serde_json::Value) -> Result<Response> { |
| 141 |
let method = request.get("method").and_then(|m| m.as_str()).unwrap_or("").to_string(); |
| 142 |
let mut headers = vec![ |
| 143 |
("accept", "application/json, text/event-stream".to_string()), |
| 144 |
("mcp-protocol-version", version.to_string()), |
| 145 |
("mcp-method", method.clone()), |
| 146 |
]; |
| 147 |
if let Some(name) = request.pointer("/params/name").or_else(|| request.pointer("/params/uri")).and_then(|n| n.as_str()) { |
| 148 |
headers.push(("mcp-name", name.to_string())); |
| 149 |
} |
| 150 |
self.send("POST", "/mcp", &headers, serde_json::to_vec(request)?).await |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
impl Client { |
| 155 |
|
| 156 |
|
| 157 |
pub async fn forward(&self, req: hyper::Request<Full<Bytes>>) -> Result<hyper::Response<hyper::body::Incoming>> { |
| 158 |
let stream = self.io().await?; |
| 159 |
let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?; |
| 160 |
tokio::spawn(async move { |
| 161 |
let _ = conn.await; |
| 162 |
}); |
| 163 |
Ok(sender.send_request(req).await?) |
| 164 |
} |
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
pub async fn stream(&self, path: &str, mut line: impl FnMut(&str) -> bool) -> Result<u16> { |
| 169 |
let stream = self.io().await?; |
| 170 |
let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?; |
| 171 |
tokio::spawn(async move { |
| 172 |
let _ = conn.await; |
| 173 |
}); |
| 174 |
let mut req = hyper::Request::builder().method("GET").uri(path).header("host", "spectra").header("connection", "close"); |
| 175 |
if let Some(pair) = &self.signer { |
| 176 |
for (k, v) in sign_headers(pair, &format!("GET {path}"), b"") { |
| 177 |
req = req.header(k, v); |
| 178 |
} |
| 179 |
} |
| 180 |
let resp = sender.send_request(req.body(Full::new(Bytes::new()))?).await?; |
| 181 |
let status = resp.status().as_u16(); |
| 182 |
let mut body = resp.into_body(); |
| 183 |
let mut buf = String::new(); |
| 184 |
while let Some(frame) = body.frame().await { |
| 185 |
if let Ok(data) = frame?.into_data() { |
| 186 |
buf.push_str(&String::from_utf8_lossy(&data)); |
| 187 |
while let Some(i) = buf.find('\n') { |
| 188 |
let l: String = buf.drain(..=i).collect(); |
| 189 |
if !line(l.trim_end()) { |
| 190 |
return Ok(status); |
| 191 |
} |
| 192 |
} |
| 193 |
} |
| 194 |
} |
| 195 |
Ok(status) |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
|
| 200 |
pub fn sign_headers(pair: &KeyPair, method_path: &str, body: &[u8]) -> Vec<(&'static str, String)> { |
| 201 |
let p = Proof::sign(pair, method_path, body); |
| 202 |
vec![ |
| 203 |
("spectra-key", p.sig.key.to_hex()), |
| 204 |
("spectra-time", p.time_ms.to_string()), |
| 205 |
("spectra-nonce", hex::encode(p.nonce)), |
| 206 |
("spectra-signature", hex::encode(spectra_core::cbor::encode(&p.sig.to_value()))), |
| 207 |
] |
| 208 |
} |
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
pub fn rpc_result(r: &Response) -> Result<serde_json::Value> { |
| 213 |
let is_sse = r.header("content-type").is_some_and(|c| c.starts_with("text/event-stream")); |
| 214 |
if !is_sse { |
| 215 |
return r.json(); |
| 216 |
} |
| 217 |
let text = String::from_utf8_lossy(&r.body); |
| 218 |
let last = text |
| 219 |
.lines() |
| 220 |
.rev() |
| 221 |
.filter_map(|l| l.strip_prefix("data:")) |
| 222 |
.map(str::trim) |
| 223 |
.find(|l| !l.is_empty()) |
| 224 |
.context("an SSE response with no data")?; |
| 225 |
Ok(serde_json::from_str(last)?) |
| 226 |
} |