1use std::net::{IpAddr, Ipv4Addr, SocketAddr};
35
36use anyhow::{anyhow, bail, Context, Result};
37use base64::Engine as _;
38use serde_json::{json, Value};
39
40use crate::did_key::MULTICODEC_ED25519_PUB;
41use crate::transport::{EndpointType, QuicServerAuth, TransportConfig};
42
43const MULTIHASH_SHA2_256: [u8; 2] = [0x12, 0x20];
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct DecodedEntry {
49 pub config: TransportConfig,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct BrowserQuicReach {
56 pub quic_url: String,
58 pub cert_hash: String,
60}
61
62fn multibase_encode(prefix: &[u8], payload: &[u8]) -> String {
65 let mut buf = Vec::with_capacity(prefix.len() + payload.len());
66 buf.extend_from_slice(prefix);
67 buf.extend_from_slice(payload);
68 format!("z{}", bs58::encode(buf).into_string())
69}
70
71fn multibase_decode_32(s: &str, prefix: [u8; 2], what: &str) -> Result<[u8; 32]> {
73 let b58 = s
74 .strip_prefix('z')
75 .ok_or_else(|| anyhow!("{what}: expected multibase base58btc ('z' prefix)"))?;
76 let bytes = bs58::decode(b58)
77 .into_vec()
78 .map_err(|e| anyhow!("{what}: invalid base58: {e}"))?;
79 if bytes.len() != prefix.len() + 32 {
80 bail!(
81 "{what}: expected {} bytes, got {}",
82 prefix.len() + 32,
83 bytes.len()
84 );
85 }
86 if bytes[..2] != prefix[..] {
87 bail!("{what}: wrong multiformats prefix");
88 }
89 let mut out = [0u8; 32];
90 out.copy_from_slice(&bytes[2..]);
91 Ok(out)
92}
93
94pub fn encode_iroh(node_id: &[u8; 32], relays: &[String], accept: &[&str]) -> Value {
99 json!({
100 "nodeId": multibase_encode(&MULTICODEC_ED25519_PUB, node_id),
101 "relays": relays,
102 "accept": accept,
103 })
104}
105
106pub fn encode_quic(uri: &str, auth: &QuicServerAuth, accept: &[&str]) -> Value {
108 let cert_hashes: Vec<String> = auth
109 .accept_cert_hashes()
110 .iter()
111 .map(|h| multibase_encode(&MULTIHASH_SHA2_256, h))
112 .collect();
113 json!({
114 "uri": uri,
115 "webpki": auth.require_web_pki(),
116 "certHashes": cert_hashes,
117 "accept": accept,
118 })
119}
120
121pub fn decode_service_entry(entry: &Value) -> Result<DecodedEntry> {
127 let ty = entry
128 .get("type")
129 .and_then(Value::as_str)
130 .ok_or_else(|| anyhow!("service entry missing string `type`"))?;
131 let svc = entry
132 .get("serviceEndpoint")
133 .ok_or_else(|| anyhow!("service entry missing `serviceEndpoint`"))?;
134 match ty {
135 "IrohTransport" => decode_iroh(svc),
136 "QuicTransport" => decode_quic(svc),
137 other => bail!("unsupported transport service type: {other}"),
138 }
139}
140
141pub fn decode_browser_quic_reach(entry: &Value) -> Result<BrowserQuicReach> {
148 let decoded = decode_service_entry(entry)?;
149 let EndpointType::Quic { auth, .. } = &decoded.config.endpoint else {
150 bail!("browser QUIC reach requires a QuicTransport service entry");
151 };
152 let [cert_hash] = auth.accept_cert_hashes() else {
153 bail!("browser QUIC reach requires exactly one live certificate hash");
154 };
155 let quic_url = entry
156 .get("serviceEndpoint")
157 .and_then(|endpoint| endpoint.get("uri"))
158 .and_then(Value::as_str)
159 .ok_or_else(|| anyhow!("quic: missing `uri`"))?
160 .to_owned();
161 Ok(BrowserQuicReach {
162 quic_url,
163 cert_hash: base64::engine::general_purpose::STANDARD.encode(cert_hash),
164 })
165}
166
167fn decode_iroh(svc: &Value) -> Result<DecodedEntry> {
168 let node_id = multibase_decode_32(
169 svc.get("nodeId")
170 .and_then(Value::as_str)
171 .ok_or_else(|| anyhow!("iroh: missing `nodeId`"))?,
172 MULTICODEC_ED25519_PUB,
173 "iroh nodeId",
174 )?;
175 let relays: Vec<String> = svc
176 .get("relays")
177 .and_then(Value::as_array)
178 .map(|a| {
179 a.iter()
180 .filter_map(|v| v.as_str().map(str::to_owned))
181 .collect()
182 })
183 .unwrap_or_default();
184 let relay_url = relays.into_iter().next();
187 Ok(DecodedEntry {
188 config: TransportConfig::iroh(node_id, Vec::new(), relay_url),
189 })
190}
191
192fn decode_quic(svc: &Value) -> Result<DecodedEntry> {
193 let uri = svc
194 .get("uri")
195 .and_then(Value::as_str)
196 .ok_or_else(|| anyhow!("quic: missing `uri`"))?;
197 let (host, port) = parse_https_authority(uri)?;
198 let require_web_pki = svc.get("webpki").and_then(Value::as_bool).unwrap_or(true);
200 let cert_hashes: Vec<[u8; 32]> = svc
201 .get("certHashes")
202 .and_then(Value::as_array)
203 .map(|a| -> Result<Vec<[u8; 32]>> {
204 a.iter()
205 .map(|v| {
206 let s = v
207 .as_str()
208 .ok_or_else(|| anyhow!("quic certHashes: non-string entry"))?;
209 multibase_decode_32(s, MULTIHASH_SHA2_256, "quic certHash")
210 })
211 .collect()
212 })
213 .transpose()?
214 .unwrap_or_default();
215
216 let auth = match (require_web_pki, cert_hashes.is_empty()) {
217 (true, true) => QuicServerAuth::web_pki(),
218 (false, false) => QuicServerAuth::pinned(cert_hashes)?,
219 (true, false) => QuicServerAuth::web_pki_pinned(cert_hashes)?,
220 (false, true) => bail!("quic entry has no auth (webpki=false and no certHashes)"),
221 };
222
223 let addr: SocketAddr = match host.parse::<IpAddr>() {
227 Ok(ip) => SocketAddr::new(ip, port),
228 Err(_) => SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), port),
229 };
230 Ok(DecodedEntry {
231 config: TransportConfig::quic_with_auth(addr, host, auth),
232 })
233}
234
235fn parse_https_authority(uri: &str) -> Result<(String, u16)> {
238 let url = url::Url::parse(uri).with_context(|| format!("quic uri parse: {uri}"))?;
239 let host = url
240 .host_str()
241 .ok_or_else(|| anyhow!("quic uri has no host: {uri}"))?
242 .to_owned();
243 let port = url.port().unwrap_or(443);
244 Ok((host, port))
245}
246
247#[cfg(test)]
248#[allow(clippy::unwrap_used, clippy::expect_used)]
249mod tests {
250 use super::*;
251 use crate::transport::EndpointType;
252
253 #[test]
254 fn iroh_round_trip() {
255 let node_id = [7u8; 32];
256 let relays = vec!["https://relay.example".to_owned()];
257 let entry = json!({
258 "id": "did:web:ex#iroh",
259 "type": "IrohTransport",
260 "serviceEndpoint": encode_iroh(&node_id, &relays, &["hyprstream-rpc/1", "moql"]),
261 });
262 let decoded = decode_service_entry(&entry).unwrap();
263 match &decoded.config.endpoint {
264 EndpointType::Iroh {
265 node_id: n,
266 relay_url,
267 direct_addrs,
268 } => {
269 assert_eq!(*n, node_id);
270 assert_eq!(relay_url.as_deref(), Some("https://relay.example"));
271 assert!(direct_addrs.is_empty());
272 }
273 other => panic!("expected Iroh, got {other:?}"),
274 }
275 }
276
277 #[test]
278 fn quic_pinned_round_trip() {
279 let auth = QuicServerAuth::pinned(vec![[1u8; 32], [2u8; 32]]).unwrap();
280 let entry = json!({
281 "type": "QuicTransport",
282 "serviceEndpoint": encode_quic("https://10.0.0.1:4433", &auth, &["hyprstream-rpc/1"]),
283 });
284 let decoded = decode_service_entry(&entry).unwrap();
285 match &decoded.config.endpoint {
286 EndpointType::Quic {
287 addr,
288 server_name,
289 auth: a,
290 } => {
291 assert_eq!(addr.to_string(), "10.0.0.1:4433");
292 assert_eq!(server_name, "10.0.0.1");
293 assert!(!a.require_web_pki());
294 assert_eq!(a.accept_cert_hashes(), &[[1u8; 32], [2u8; 32]]);
295 }
296 other => panic!("expected Quic, got {other:?}"),
297 }
298 }
299
300 #[test]
301 fn browser_quic_projection_uses_the_live_pin() {
302 let auth = QuicServerAuth::pinned(vec![[3u8; 32]]).unwrap();
303 let entry = json!({
304 "type": "QuicTransport",
305 "serviceEndpoint": encode_quic(
306 "https://pds.example:4433/wt",
307 &auth,
308 &["hyprstream-rpc/1"],
309 ),
310 });
311
312 let browser = decode_browser_quic_reach(&entry).unwrap();
313 assert_eq!(browser.quic_url, "https://pds.example:4433/wt");
314 assert_eq!(
315 browser.cert_hash,
316 base64::engine::general_purpose::STANDARD.encode([3u8; 32])
317 );
318 }
319
320 #[test]
321 fn browser_quic_projection_rejects_rotation_overlap_ambiguity() {
322 let auth = QuicServerAuth::pinned(vec![[3u8; 32], [4u8; 32]]).unwrap();
323 let entry = json!({
324 "type": "QuicTransport",
325 "serviceEndpoint": encode_quic(
326 "https://pds.example:4433/wt",
327 &auth,
328 &["hyprstream-rpc/1"],
329 ),
330 });
331
332 let error = decode_browser_quic_reach(&entry).unwrap_err();
333 assert!(error.to_string().contains("exactly one"), "{error:#}");
334 }
335
336 #[test]
337 fn quic_webpki_default_and_hostname_placeholder() {
338 let entry = json!({
340 "type": "QuicTransport",
341 "serviceEndpoint": { "uri": "https://host.example:8443", "accept": ["hyprstream-rpc/1"] },
342 });
343 let decoded = decode_service_entry(&entry).unwrap();
344 match &decoded.config.endpoint {
345 EndpointType::Quic {
346 addr,
347 server_name,
348 auth,
349 } => {
350 assert!(auth.require_web_pki());
351 assert!(auth.accept_cert_hashes().is_empty());
352 assert_eq!(server_name, "host.example");
353 assert_eq!(addr.port(), 8443);
354 assert!(addr.ip().is_unspecified(), "hostname ⇒ placeholder IP");
355 }
356 other => panic!("expected Quic, got {other:?}"),
357 }
358 }
359
360 #[test]
361 fn quic_web_pki_pinned() {
362 let entry = json!({
363 "type": "QuicTransport",
364 "serviceEndpoint": {
365 "uri": "https://host.example:4433",
366 "webpki": true,
367 "certHashes": [multibase_encode(&MULTIHASH_SHA2_256, &[9u8; 32])],
368 },
369 });
370 let decoded = decode_service_entry(&entry).unwrap();
371 if let EndpointType::Quic { auth, .. } = &decoded.config.endpoint {
372 assert!(auth.require_web_pki());
373 assert_eq!(auth.accept_cert_hashes(), &[[9u8; 32]]);
374 } else {
375 panic!("expected Quic");
376 }
377 }
378
379 #[test]
380 fn rejects_no_auth_and_unknown_type() {
381 let bad = json!({
383 "type": "QuicTransport",
384 "serviceEndpoint": { "uri": "https://10.0.0.1:4433", "webpki": false },
385 });
386 assert!(decode_service_entry(&bad).is_err());
387
388 let unknown = json!({ "type": "OnionTransport", "serviceEndpoint": {} });
389 assert!(decode_service_entry(&unknown).is_err());
390 }
391
392 #[test]
393 fn rejects_malformed_multibase() {
394 let entry = json!({
396 "type": "IrohTransport",
397 "serviceEndpoint": { "nodeId": multibase_encode(&MULTIHASH_SHA2_256, &[0u8; 32]), "relays": [] },
398 });
399 assert!(decode_service_entry(&entry).is_err());
400 }
401}