1use std::time::Duration;
10
11use anyhow::{Context, Result};
12use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
13use ed25519_dalek::{Signer as _, SigningKey};
14use serde::{Deserialize, Serialize};
15use tracing::info;
16use url::{Host, Url};
17
18use crate::{auth::identity_store, config::HyprConfig};
19
20const HOME_PDS_SECRET: &str = "pds-home.json";
21const DEVICE_CODE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
22const DEFAULT_PDS_SCOPE: &str = "pds:attach";
23
24#[derive(Clone, Serialize, Deserialize)]
29pub struct HomePdsAttachment {
30 pub pds_url: String,
31 pub issuer: String,
32 pub did: String,
33 pub client_id: String,
34 pub access_token: String,
35 pub refresh_token: String,
36 pub token_type: String,
37 pub scope: String,
38 pub expires_in: Option<i64>,
39}
40
41#[derive(Deserialize)]
42struct AuthorizationServerMetadata {
43 issuer: String,
44 registration_endpoint: String,
45 device_authorization_endpoint: String,
46 token_endpoint: String,
47}
48
49#[derive(Deserialize)]
50struct RegistrationResponse {
51 client_id: String,
52}
53
54#[derive(Deserialize)]
55struct DeviceAuthorizationResponse {
56 device_code: String,
57 user_code: String,
58 verification_uri: String,
59 #[serde(default)]
60 verification_uri_complete: Option<String>,
61 #[serde(default = "default_poll_interval")]
62 interval: u64,
63}
64
65#[derive(Deserialize)]
66struct TokenResponse {
67 access_token: String,
68 #[serde(default)]
69 refresh_token: Option<String>,
70 #[serde(default = "default_token_type")]
71 token_type: String,
72 #[serde(default)]
73 scope: String,
74 #[serde(default)]
75 expires_in: Option<i64>,
76}
77
78fn default_poll_interval() -> u64 {
79 5
80}
81fn default_token_type() -> String {
82 "DPoP".to_owned()
83}
84
85fn attachment_scope(scope: Option<&str>) -> String {
86 scope
87 .map(str::to_owned)
88 .unwrap_or_else(|| DEFAULT_PDS_SCOPE.to_owned())
89}
90
91pub async fn handle_pds_join(
97 config: &HyprConfig,
98 pds_url: &str,
99 scope: Option<&str>,
100) -> Result<()> {
101 let pds_url = canonical_pds_url(pds_url)?;
102 let secrets_dir = identity_store::credentials_dir_for_config(Some(config))?;
103 ensure_no_home_pds(&secrets_dir)?;
104
105 let root_key = identity_store::load_or_generate_node_signing_key(&secrets_dir)?;
106 let iroh_key = hyprstream_rpc::node_identity::derive_purpose_key(
110 &root_key,
111 "hyprstream-iroh-transport-v1",
112 );
113 let did = hyprstream_crypto::did_key::ed25519_to_did_key(iroh_key.verifying_key().as_bytes());
114
115 let client = reqwest::Client::builder()
116 .timeout(Duration::from_secs(30))
117 .build()
118 .context("building PDS OAuth client")?;
119
120 let metadata_url = endpoint_under_pds(&pds_url, ".well-known/oauth-authorization-server")?;
121 let metadata = client
122 .get(metadata_url)
123 .send()
124 .await
125 .context("fetching PDS OAuth authorization-server metadata")?
126 .error_for_status()
127 .context("PDS OAuth authorization-server metadata request failed")?
128 .json::<AuthorizationServerMetadata>()
129 .await
130 .context("PDS returned invalid OAuth authorization-server metadata")?;
131
132 let issuer = canonical_pds_url(&metadata.issuer)
133 .context("PDS OAuth metadata contains an invalid issuer")?;
134 if issuer != pds_url {
135 anyhow::bail!(
136 "PDS OAuth metadata issuer '{}' does not match requested PDS origin '{}'",
137 issuer,
138 pds_url
139 );
140 }
141 let registration_endpoint = pds_endpoint(
142 &metadata.registration_endpoint,
143 "registration_endpoint",
144 &pds_url,
145 )?;
146 let device_endpoint = pds_endpoint(
147 &metadata.device_authorization_endpoint,
148 "device_authorization_endpoint",
149 &pds_url,
150 )?;
151 let token_endpoint = pds_endpoint(&metadata.token_endpoint, "token_endpoint", &pds_url)?;
152
153 let registration = client
157 .post(registration_endpoint)
158 .json(&serde_json::json!({
159 "redirect_uris": ["http://127.0.0.1:0/pds-attach"],
160 "client_name": "HyprStream host PDS attachment",
161 "hyprstream_node_did": did.clone(),
162 "grant_types": [DEVICE_CODE_GRANT, "refresh_token"],
163 "token_endpoint_auth_method": "none"
164 }))
165 .send()
166 .await
167 .context("registering this host as an OAuth device client with the PDS")?
168 .error_for_status()
169 .context("PDS rejected OAuth device-client registration")?
170 .json::<RegistrationResponse>()
171 .await
172 .context("PDS returned an invalid OAuth client registration")?;
173
174 let requested_scope = attachment_scope(scope);
175 let device_form = vec![
176 ("client_id", registration.client_id.as_str()),
177 ("resource", pds_url.as_str()),
178 ("scope", requested_scope.as_str()),
179 ];
180 let device = client
181 .post(device_endpoint)
182 .form(&device_form)
183 .send()
184 .await
185 .context("starting PDS device authorization")?
186 .error_for_status()
187 .context("PDS rejected device authorization")?
188 .json::<DeviceAuthorizationResponse>()
189 .await
190 .context("PDS returned an invalid device authorization response")?;
191
192 #[allow(clippy::print_stdout)]
193 {
194 println!("Host DID: {did}");
195 println!("Open this URL and authorize this host:");
196 println!(
197 "{}",
198 device
199 .verification_uri_complete
200 .as_deref()
201 .unwrap_or(&device.verification_uri)
202 );
203 println!("User code: {}", device.user_code);
204 }
205 info!(host_did = %did, "PDS device authorization started");
206
207 let token = poll_device_token(
208 &client,
209 &token_endpoint,
210 ®istration.client_id,
211 &device.device_code,
212 device.interval.max(1),
213 &iroh_key,
214 )
215 .await?;
216 if !token.token_type.eq_ignore_ascii_case("DPoP") {
217 anyhow::bail!(
218 "PDS issued token_type '{}'; home-PDS credentials must be DPoP sender-constrained",
219 token.token_type
220 );
221 }
222 let refresh_token = token.refresh_token.context(
223 "PDS did not issue a refresh token; refusing to persist a non-renewable home-PDS attachment",
224 )?;
225
226 let attachment = HomePdsAttachment {
227 pds_url,
228 issuer,
229 did,
230 client_id: registration.client_id,
231 access_token: token.access_token,
232 refresh_token,
233 token_type: token.token_type,
234 scope: token.scope,
235 expires_in: token.expires_in,
236 };
237 let encoded = serde_json::to_vec(&attachment).context("serializing PDS attachment")?;
238 if !identity_store::write_secret_exclusive(&secrets_dir, HOME_PDS_SECRET, &encoded)? {
239 anyhow::bail!(
240 "this host was attached to a home PDS while authorization was in progress; refusing to replace it"
241 );
242 }
243
244 #[allow(clippy::print_stdout)]
245 {
246 println!(
247 "Attached this host ({}) to home PDS {}.",
248 attachment.did, attachment.pds_url
249 );
250 }
251 info!(
252 host_did = %attachment.did,
253 pds_url = %attachment.pds_url,
254 "Attached this host to its home PDS"
255 );
256 Ok(())
257}
258
259async fn poll_device_token(
260 client: &reqwest::Client,
261 token_endpoint: &Url,
262 client_id: &str,
263 device_code: &str,
264 mut interval: u64,
265 dpop_key: &SigningKey,
266) -> Result<TokenResponse> {
267 loop {
268 tokio::time::sleep(Duration::from_secs(interval)).await;
269 match exchange_device_code(
270 client,
271 token_endpoint,
272 client_id,
273 device_code,
274 dpop_key,
275 None,
276 )
277 .await?
278 {
279 DevicePoll::Token(token) => return Ok(token),
280 DevicePoll::Pending => continue,
281 DevicePoll::SlowDown => {
282 interval = interval.saturating_add(5);
283 continue;
284 }
285 }
286 }
287}
288
289enum DevicePoll {
290 Token(TokenResponse),
291 Pending,
292 SlowDown,
293}
294
295async fn exchange_device_code(
296 client: &reqwest::Client,
297 token_endpoint: &Url,
298 client_id: &str,
299 device_code: &str,
300 dpop_key: &SigningKey,
301 nonce: Option<&str>,
302) -> Result<DevicePoll> {
303 let mut nonce = nonce.map(str::to_owned);
304 loop {
305 let proof = dpop_proof(dpop_key, "POST", token_endpoint, nonce.as_deref())?;
306 let response = client
307 .post(token_endpoint.clone())
308 .header("DPoP", proof)
309 .form(&[
310 ("grant_type", DEVICE_CODE_GRANT),
311 ("client_id", client_id),
312 ("device_code", device_code),
313 ])
314 .send()
315 .await
316 .context("polling PDS OAuth token endpoint")?;
317
318 if response.status().is_success() {
319 return response
320 .json::<TokenResponse>()
321 .await
322 .context("PDS returned an invalid OAuth token response")
323 .map(DevicePoll::Token);
324 }
325
326 let dpop_nonce = response
327 .headers()
328 .get("DPoP-Nonce")
329 .and_then(|value| value.to_str().ok())
330 .map(str::to_owned);
331 let status = response.status();
332 let body: serde_json::Value = response.json().await.unwrap_or_default();
333 let error = body
334 .get("error")
335 .and_then(serde_json::Value::as_str)
336 .unwrap_or("unknown_error");
337 match error {
338 "authorization_pending" => return Ok(DevicePoll::Pending),
339 "slow_down" => return Ok(DevicePoll::SlowDown),
340 "use_dpop_nonce" => {
341 nonce = Some(
344 dpop_nonce.context("PDS requested DPoP nonce without sending DPoP-Nonce")?,
345 );
346 }
347 _ => anyhow::bail!(
348 "PDS device authorization failed ({status}): {}",
349 body.get("error_description")
350 .and_then(serde_json::Value::as_str)
351 .unwrap_or(error)
352 ),
353 }
354 }
355}
356
357fn dpop_proof(
358 key: &SigningKey,
359 method: &str,
360 endpoint: &Url,
361 nonce: Option<&str>,
362) -> Result<String> {
363 let htu = endpoint_without_query(endpoint)?;
364 let x = URL_SAFE_NO_PAD.encode(key.verifying_key().as_bytes());
365 let header = serde_json::json!({
366 "typ": "dpop+jwt",
367 "alg": "EdDSA",
368 "jwk": { "kty": "OKP", "crv": "Ed25519", "x": x },
369 });
370 let mut claims = serde_json::json!({
371 "jti": uuid::Uuid::new_v4().to_string(),
372 "htm": method,
373 "htu": htu,
374 "iat": chrono::Utc::now().timestamp(),
375 });
376 if let Some(nonce) = nonce {
377 claims["nonce"] = serde_json::Value::String(nonce.to_owned());
378 }
379 let header = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header)?);
380 let claims = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims)?);
381 let signed = format!("{header}.{claims}");
382 let signature = key.sign(signed.as_bytes());
383 Ok(format!(
384 "{signed}.{}",
385 URL_SAFE_NO_PAD.encode(signature.to_bytes())
386 ))
387}
388
389fn ensure_no_home_pds(secrets_dir: &std::path::Path) -> Result<()> {
390 if let Some(bytes) = identity_store::read_secret(secrets_dir, HOME_PDS_SECRET)? {
391 let attachment: HomePdsAttachment = serde_json::from_slice(&bytes).context(
392 "existing PDS attachment credential is corrupt; refusing to attach another home PDS",
393 )?;
394 anyhow::bail!(
395 "this host is already attached to home PDS '{}'; only one home PDS is allowed",
396 attachment.pds_url
397 );
398 }
399 Ok(())
400}
401
402fn is_loopback_host(url: &Url) -> bool {
403 match url.host() {
404 Some(Host::Domain("localhost")) => true,
405 Some(Host::Ipv4(ip)) => ip.is_loopback(),
406 Some(Host::Ipv6(ip)) => ip.is_loopback(),
407 _ => false,
408 }
409}
410
411fn canonical_pds_url(value: &str) -> Result<String> {
412 let mut url = Url::parse(value).context("PDS URL must be an absolute URL")?;
413 if url.query().is_some()
414 || url.fragment().is_some()
415 || !url.username().is_empty()
416 || url.password().is_some()
417 {
418 anyhow::bail!("PDS URL must not contain credentials, a query, or a fragment");
419 }
420 let is_loopback = is_loopback_host(&url);
421 if url.scheme() != "https" && !(url.scheme() == "http" && is_loopback) {
422 anyhow::bail!("PDS URL must use HTTPS (HTTP is allowed only for loopback development)");
423 }
424 if url.host_str().is_none() {
425 anyhow::bail!("PDS URL must include a host");
426 }
427 url.set_query(None);
428 url.set_fragment(None);
429 if url.path() != "/" {
430 anyhow::bail!("PDS URL must be an origin without a path");
431 }
432 Ok(url.as_str().trim_end_matches('/').to_owned())
433}
434
435fn endpoint_under_pds(pds_url: &str, path: &str) -> Result<Url> {
436 let base = Url::parse(&format!("{}/", pds_url.trim_end_matches('/')))?;
437 base.join(path).context("building PDS metadata endpoint")
438}
439
440fn pds_endpoint(value: &str, name: &str, pds_url: &str) -> Result<Url> {
441 let url = secure_endpoint(value, name)?;
442 let origin = canonical_pds_url(url.origin().ascii_serialization().as_str())?;
443 if origin != pds_url {
444 anyhow::bail!(
445 "PDS metadata {name} origin '{}' does not match requested PDS origin '{}'",
446 origin,
447 pds_url
448 );
449 }
450 Ok(url)
451}
452
453fn secure_endpoint(value: &str, name: &str) -> Result<Url> {
454 let url =
455 Url::parse(value).with_context(|| format!("PDS metadata {name} is not an absolute URL"))?;
456 let is_loopback = is_loopback_host(&url);
457 if url.scheme() != "https" && !(url.scheme() == "http" && is_loopback) {
458 anyhow::bail!("PDS metadata {name} must use HTTPS (or loopback HTTP)");
459 }
460 if url.query().is_some()
461 || url.fragment().is_some()
462 || !url.username().is_empty()
463 || url.password().is_some()
464 || url.host_str().is_none()
465 {
466 anyhow::bail!(
467 "PDS metadata {name} must be a complete endpoint URL without credentials, query, or fragment"
468 );
469 }
470 Ok(url)
471}
472
473fn endpoint_without_query(endpoint: &Url) -> Result<String> {
474 let mut endpoint = endpoint.clone();
475 endpoint.set_query(None);
476 endpoint.set_fragment(None);
477 if endpoint.cannot_be_a_base() {
478 anyhow::bail!("invalid OAuth endpoint for DPoP proof");
479 }
480 Ok(endpoint.as_str().trim_end_matches('/').to_owned())
481}
482
483#[cfg(test)]
484#[allow(clippy::unwrap_used)]
485mod tests {
486 use super::*;
487
488 #[test]
489 fn canonical_pds_requires_secure_origin() {
490 assert_eq!(
491 canonical_pds_url("https://PDS.example/").unwrap(),
492 "https://pds.example"
493 );
494 assert_eq!(
495 canonical_pds_url("http://127.0.0.1:6791/").unwrap(),
496 "http://127.0.0.1:6791"
497 );
498 assert!(canonical_pds_url("http://pds.example").is_err());
499 assert!(canonical_pds_url("https://pds.example/path").is_err());
500 assert!(canonical_pds_url("https://pds.example/?token=x").is_err());
501 assert!(secure_endpoint(
502 "https://user:secret@pds.example/oauth/token",
503 "token_endpoint",
504 )
505 .is_err());
506 assert_eq!(attachment_scope(None), DEFAULT_PDS_SCOPE);
507 }
508
509 #[test]
510 fn dpop_proof_is_bound_to_the_endpoint_and_key() {
511 let key = SigningKey::generate(&mut rand::rngs::OsRng);
512 let endpoint = Url::parse("https://pds.example/oauth/token?ignored=true").unwrap();
513 let proof = dpop_proof(&key, "POST", &endpoint, Some("nonce")).unwrap();
514 let verified = crate::services::oauth::dpop::verify_dpop_proof(
515 &proof,
516 "POST",
517 "https://pds.example/oauth/token",
518 None,
519 )
520 .unwrap();
521 assert_eq!(
522 verified.public_key_bytes(),
523 Some(*key.verifying_key().as_bytes())
524 );
525 assert_eq!(verified.nonce.as_deref(), Some("nonce"));
526 }
527
528 #[test]
529 fn existing_attachment_blocks_second_home() {
530 let dir = tempfile::tempdir().unwrap();
531 let attachment = HomePdsAttachment {
532 pds_url: "https://one.example".to_owned(),
533 issuer: "https://one.example".to_owned(),
534 did: "did:key:ztest".to_owned(),
535 client_id: "client".to_owned(),
536 access_token: "access".to_owned(),
537 refresh_token: "refresh".to_owned(),
538 token_type: "DPoP".to_owned(),
539 scope: String::new(),
540 expires_in: None,
541 };
542 identity_store::write_secret(
543 dir.path(),
544 HOME_PDS_SECRET,
545 &serde_json::to_vec(&attachment).unwrap(),
546 )
547 .unwrap();
548 let persisted: HomePdsAttachment = serde_json::from_slice(
549 &identity_store::read_secret(dir.path(), HOME_PDS_SECRET)
550 .unwrap()
551 .unwrap(),
552 )
553 .unwrap();
554 assert_eq!(persisted.pds_url, attachment.pds_url);
555 assert_eq!(persisted.did, attachment.did);
556 assert!(ensure_no_home_pds(dir.path()).is_err());
557 }
558}