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