1use std::sync::Arc;
10use std::time::{Duration, Instant};
11
12use axum::{
13 extract::{Query, State},
14 http::{header, StatusCode},
15 response::{Html, IntoResponse, Response},
16 Form, Json,
17};
18use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
19use rand::RngCore;
20use serde::Deserialize;
21
22use super::challenge;
23use super::state::{DeviceCodeStatus, OAuthState, PendingDeviceCode};
24
25pub(crate) use challenge::html_escape;
27
28const DEVICE_CODE_TTL_SECS: u64 = 600;
30
31const DEFAULT_POLL_INTERVAL: u64 = 5;
33
34#[derive(Debug, Deserialize)]
36pub struct DeviceAuthRequest {
37 pub client_id: String,
38 #[serde(default)]
39 pub scope: Option<String>,
40 #[serde(default)]
41 pub resource: Option<String>,
42}
43
44#[derive(Debug, Deserialize)]
46pub struct VerifyQuery {
47 #[serde(default)]
48 pub user_code: Option<String>,
49}
50
51#[derive(Debug, Deserialize)]
53pub struct VerifyForm {
54 pub user_code: String,
55 pub username: String,
56 pub signature: String,
57}
58
59#[allow(clippy::redundant_closure_for_method_calls)] pub async fn device_authorize(
62 State(state): State<Arc<OAuthState>>,
63 Form(params): Form<DeviceAuthRequest>,
64) -> Response {
65 let client = if params.client_id.starts_with("https://") {
69 match super::registration::resolve_cimd_client(&state, ¶ms.client_id).await {
70 Ok(c) => c,
71 Err(e) => {
72 tracing::warn!(client_id = %params.client_id, error = %e, "device: CIMD resolution failed");
73 return device_error(
74 StatusCode::BAD_REQUEST,
75 "invalid_client",
76 "Unknown client_id. Register first via POST /oauth/register",
77 );
78 }
79 }
80 } else {
81 match state.clients.read().await.get(¶ms.client_id) {
82 Some(c) => c.clone(),
83 None => {
84 return device_error(
85 StatusCode::BAD_REQUEST,
86 "invalid_client",
87 "Unknown client_id. Register first via POST /oauth/register",
88 );
89 }
90 }
91 };
92
93 let mut device_code_bytes = [0u8; 32];
95 rand::rngs::OsRng.fill_bytes(&mut device_code_bytes);
96 let device_code = URL_SAFE_NO_PAD.encode(device_code_bytes);
97
98 let user_code = generate_user_code();
100
101 let mut nonce_bytes = [0u8; 32];
103 rand::rngs::OsRng.fill_bytes(&mut nonce_bytes);
104 let nonce = URL_SAFE_NO_PAD.encode(nonce_bytes);
105
106 let scopes: Vec<String> = {
107 let requested: Vec<String> = params
111 .scope
112 .as_deref()
113 .unwrap_or(&state.default_scopes.join(" "))
114 .split_whitespace()
115 .map(std::borrow::ToOwned::to_owned)
116 .collect();
117 let client_declared = client.declared_scopes();
118 let require_atproto = super::state::atproto_profile_active(&requested);
119 if require_atproto {
126 return device_error(
127 StatusCode::BAD_REQUEST,
128 "invalid_scope",
129 "The atproto profile has no device authorization grant; use PAR + authorization code",
130 );
131 }
132 match super::state::validate_requested_scopes(
133 &requested,
134 &state.server_supported_scopes(),
135 if client_declared.is_empty() {
136 None
137 } else {
138 Some(&client_declared)
139 },
140 require_atproto,
141 ) {
142 Ok(g) => g,
143 Err(_) => {
144 return device_error(
145 StatusCode::BAD_REQUEST,
146 "invalid_scope",
147 "Requested scope is not supported or not declared by the client",
148 );
149 }
150 }
151 };
152
153 let resource = params.resource.filter(|s| !s.is_empty());
154
155 let now = Instant::now();
156 let pending = PendingDeviceCode {
157 device_code: device_code.clone(),
158 user_code: user_code.clone(),
159 client_id: params.client_id,
160 scopes,
161 resource,
162 status: DeviceCodeStatus::Pending,
163 created_at: now,
164 expires_at: now + Duration::from_secs(DEVICE_CODE_TTL_SECS),
165 interval: DEFAULT_POLL_INTERVAL,
166 last_polled: None,
167 nonce,
168 approved_by: None,
169 verifying_key: None,
170 };
171
172 {
174 let mut device_codes = state.pending_device_codes.write().await;
175 device_codes.insert(device_code.clone(), pending);
176 }
177 {
178 let mut user_code_map = state.device_code_by_user_code.write().await;
179 user_code_map.insert(user_code.clone(), device_code.clone());
180 }
181
182 let formatted_code = format_user_code(&user_code);
183 let verification_uri = format!("{}/oauth/device/verify", state.issuer_url);
184 let verification_uri_complete = format!(
185 "{}/oauth/device/verify?user_code={}",
186 state.issuer_url, formatted_code
187 );
188
189 (
190 StatusCode::OK,
191 [
192 (header::CACHE_CONTROL, "no-store"),
193 (header::PRAGMA, "no-cache"),
194 ],
195 Json(serde_json::json!({
196 "device_code": device_code,
197 "user_code": formatted_code,
198 "verification_uri": verification_uri,
199 "verification_uri_complete": verification_uri_complete,
200 "expires_in": DEVICE_CODE_TTL_SECS,
201 "interval": DEFAULT_POLL_INTERVAL,
202 })),
203 )
204 .into_response()
205}
206
207pub async fn verify_get(
209 State(state): State<Arc<OAuthState>>,
210 Query(query): Query<VerifyQuery>,
211) -> Response {
212 let prefilled_code = query.user_code.as_deref().unwrap_or("").trim();
213
214 if prefilled_code.is_empty() {
215 let html = render_entry_page(&state.issuer_url, None);
217 return Html(html).into_response();
218 }
219
220 let normalized = prefilled_code.replace('-', "").to_uppercase();
222
223 let device_code = {
225 let user_code_map = state.device_code_by_user_code.read().await;
226 user_code_map.get(&normalized).cloned()
227 };
228
229 let device_code = match device_code {
230 Some(dc) => dc,
231 None => {
232 let html = render_entry_page(
233 &state.issuer_url,
234 Some("Invalid or expired code. Please check your device and try again."),
235 );
236 return Html(html).into_response();
237 }
238 };
239
240 let nonce = {
241 let device_codes = state.pending_device_codes.read().await;
242 match device_codes.get(&device_code) {
243 Some(pending) if pending.is_expired() => {
244 let html = render_entry_page(
245 &state.issuer_url,
246 Some("This code has expired. Please request a new one from your device."),
247 );
248 return Html(html).into_response();
249 }
250 Some(pending) => pending.nonce.clone(),
251 None => {
252 let html = render_entry_page(
253 &state.issuer_url,
254 Some("Invalid or expired code. Please try again."),
255 );
256 return Html(html).into_response();
257 }
258 }
259 };
260
261 let html = render_verify_page(prefilled_code, &nonce, None);
262 Html(html).into_response()
263}
264
265pub async fn verify_post(
271 State(state): State<Arc<OAuthState>>,
272 headers: axum::http::HeaderMap,
273 Form(form): Form<VerifyForm>,
274) -> Response {
275 let json_client = wants_json(&headers);
276
277 let normalized = form.user_code.replace('-', "").to_uppercase();
279
280 let device_code = {
282 let user_code_map = state.device_code_by_user_code.read().await;
283 user_code_map.get(&normalized).cloned()
284 };
285
286 let device_code = match device_code {
287 Some(dc) => dc,
288 None => {
289 return verify_err(
290 json_client,
291 &form.user_code,
292 "",
293 "Invalid or expired code. Please try again.",
294 );
295 }
296 };
297
298 let nonce = {
300 let device_codes = state.pending_device_codes.read().await;
301 match device_codes.get(&device_code) {
302 Some(pending) if pending.is_expired() => {
303 return verify_err(
304 json_client,
305 &form.user_code,
306 "",
307 "This code has expired. Please request a new one.",
308 );
309 }
310 Some(pending) if pending.status != DeviceCodeStatus::Pending => {
311 return verify_err(
312 json_client,
313 &form.user_code,
314 "",
315 "This code has already been used.",
316 );
317 }
318 Some(pending) => pending.nonce.clone(),
319 None => {
320 return verify_err(
321 json_client,
322 &form.user_code,
323 "",
324 "Invalid or expired code. Please try again.",
325 );
326 }
327 }
328 };
329
330 let challenge_str = format!("{}:{}:{}", form.username, normalized, nonce);
333
334 let user_store = match state.user_store_reader() {
336 Some(store) => store,
337 None => {
338 return verify_err(
339 json_client,
340 &form.user_code,
341 &nonce,
342 "User credential store not configured on this server.",
343 );
344 }
345 };
346
347 let verifying_key = match challenge::verify_ed25519_response(
349 user_store.as_ref(),
350 &form.username,
351 &challenge_str,
352 &form.signature,
353 )
354 .await
355 {
356 Ok(vk) => vk,
357 Err(e) => {
358 if matches!(e, challenge::ChallengeError::UserStoreError(_)) {
359 tracing::error!(username = %form.username, "UserStore lookup error during device verify");
360 }
361 return verify_err(json_client, &form.user_code, &nonce, e.message());
362 }
363 };
364
365 let result = {
367 let mut device_codes = state.pending_device_codes.write().await;
368 match device_codes.get_mut(&device_code) {
369 Some(pending) if pending.is_expired() => {
370 let user_code_inner = pending.user_code.clone();
371 device_codes.remove(&device_code);
372 let mut user_code_map = state.device_code_by_user_code.write().await;
373 user_code_map.remove(&user_code_inner);
374 Err("This code has expired. Please request a new one.")
375 }
376 Some(pending) if pending.status != DeviceCodeStatus::Pending => {
377 Err("This code has already been used.")
378 }
379 Some(pending) => {
380 pending.status = DeviceCodeStatus::Approved;
381 pending.last_polled = None;
382 pending.approved_by = Some(form.username.clone());
383 pending.verifying_key = Some(verifying_key);
384 Ok(())
385 }
386 None => Err("Invalid or expired code. Please try again."),
387 }
388 };
389
390 match result {
391 Ok(()) => {
392 if json_client {
393 (
394 StatusCode::OK,
395 Json(serde_json::json!({"status": "approved", "username": form.username})),
396 )
397 .into_response()
398 } else {
399 Html(render_result_page(true, &form.username)).into_response()
400 }
401 }
402 Err(msg) => verify_err(json_client, &form.user_code, &nonce, msg),
403 }
404}
405
406fn wants_json(headers: &axum::http::HeaderMap) -> bool {
408 headers
409 .get(axum::http::header::ACCEPT)
410 .and_then(|v| v.to_str().ok())
411 .map(|s| s.contains("application/json"))
412 .unwrap_or(false)
413}
414
415fn verify_err(json_client: bool, user_code: &str, nonce: &str, msg: &str) -> Response {
417 if json_client {
418 (
419 StatusCode::BAD_REQUEST,
420 Json(serde_json::json!({"error": "verification_failed", "error_description": msg})),
421 )
422 .into_response()
423 } else {
424 Html(render_verify_page(user_code, nonce, Some(msg))).into_response()
425 }
426}
427
428pub async fn device_nonce(
433 State(state): State<Arc<OAuthState>>,
434 Query(query): Query<VerifyQuery>,
435) -> Response {
436 let user_code = match query.user_code.as_deref() {
437 Some(c) if !c.is_empty() => c.replace('-', "").to_uppercase(),
438 _ => {
439 return (
440 StatusCode::BAD_REQUEST,
441 Json(serde_json::json!({"error": "user_code query param required"})),
442 )
443 .into_response();
444 }
445 };
446
447 let device_code = {
448 let user_code_map = state.device_code_by_user_code.read().await;
449 user_code_map.get(&user_code).cloned()
450 };
451
452 let device_code = match device_code {
453 Some(dc) => dc,
454 None => {
455 return (
456 StatusCode::NOT_FOUND,
457 Json(serde_json::json!({"error": "unknown_code", "error_description": "user_code not found or expired"})),
458 )
459 .into_response();
460 }
461 };
462
463 let device_codes = state.pending_device_codes.read().await;
464 match device_codes.get(&device_code) {
465 Some(pending) if pending.is_expired() => (
466 StatusCode::GONE,
467 Json(serde_json::json!({"error": "expired_token", "error_description": "Device code has expired"})),
468 )
469 .into_response(),
470 Some(pending) => (
471 StatusCode::OK,
472 [
473 (header::CACHE_CONTROL, "no-store"),
474 (header::PRAGMA, "no-cache"),
475 ],
476 Json(serde_json::json!({
477 "user_code": user_code,
478 "nonce": pending.nonce,
479 })),
480 )
481 .into_response(),
482 None => (
483 StatusCode::NOT_FOUND,
484 Json(serde_json::json!({"error": "unknown_code", "error_description": "user_code not found"})),
485 )
486 .into_response(),
487 }
488}
489
490fn generate_user_code() -> String {
493 const CHARSET: &[u8] = b"ABCDEFGHJKMNPQRSTVWXYZ23456789";
494 let mut code = String::with_capacity(8);
495 for _ in 0..8 {
496 let mut byte = [0u8; 1];
497 loop {
498 rand::rngs::OsRng.fill_bytes(&mut byte);
499 let idx = byte[0] as usize;
500 if idx < (256 / CHARSET.len()) * CHARSET.len() {
501 code.push(CHARSET[idx % CHARSET.len()] as char);
502 break;
503 }
504 }
505 }
506 code
507}
508
509fn format_user_code(code: &str) -> String {
511 if code.len() == 8 {
512 format!("{}-{}", &code[..4], &code[4..])
513 } else {
514 code.to_owned()
515 }
516}
517
518fn device_error(status: StatusCode, error: &str, description: &str) -> Response {
519 (
520 status,
521 [
522 (header::CACHE_CONTROL, "no-store"),
523 (header::PRAGMA, "no-cache"),
524 ],
525 Json(serde_json::json!({
526 "error": error,
527 "error_description": description,
528 })),
529 )
530 .into_response()
531}
532
533fn render_entry_page(issuer_url: &str, error: Option<&str>) -> String {
535 let error_html = match error {
536 Some(msg) => format!(r#"<div class="error">{}</div>"#, html_escape(msg)),
537 None => String::new(),
538 };
539 format!(
540 r#"<!DOCTYPE html>
541<html lang="en">
542<head>
543<meta charset="utf-8">
544<meta name="viewport" content="width=device-width, initial-scale=1">
545<title>Device Verification — hyprstream</title>
546<style>
547 body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
548 max-width: 480px; margin: 60px auto; padding: 0 20px; color: #1a1a1a; background: #fafafa; }}
549 .card {{ background: #fff; border-radius: 12px; padding: 32px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }}
550 h1 {{ font-size: 1.4rem; margin: 0 0 8px; }}
551 p {{ color: #555; line-height: 1.5; }}
552 .code-input {{ width: 100%; padding: 14px; font-size: 1.4rem; font-family: monospace;
553 text-align: center; letter-spacing: 4px; text-transform: uppercase;
554 border: 2px solid #ddd; border-radius: 8px; box-sizing: border-box; margin: 16px 0; }}
555 .code-input:focus {{ border-color: #0066cc; outline: none; }}
556 .error {{ background: #fff0f0; color: #cc0000; border-radius: 8px; padding: 12px 16px;
557 margin: 12px 0; font-size: 0.9rem; }}
558 button {{ width: 100%; padding: 12px; border: none; border-radius: 8px; font-size: 1rem;
559 cursor: pointer; font-weight: 500; background: #0066cc; color: #fff; margin-top: 8px; }}
560 button:hover {{ background: #0052a3; }}
561</style>
562</head>
563<body>
564<div class="card">
565 <h1>Device Verification</h1>
566 <p>Enter the code displayed on your device to proceed to authorization.</p>
567 {error_html}
568 <form method="get" action="{action_url}/oauth/device/verify">
569 <input type="text" name="user_code" class="code-input"
570 placeholder="XXXX-XXXX" maxlength="9" autocomplete="off" autofocus>
571 <button type="submit">Continue</button>
572 </form>
573</div>
574</body>
575</html>"#,
576 error_html = error_html,
577 action_url = html_escape(issuer_url),
578 )
579}
580
581pub(crate) fn render_verify_page(user_code: &str, nonce: &str, error: Option<&str>) -> String {
583 let error_html = match error {
584 Some(msg) => format!(r#"<div class="error">{}</div>"#, html_escape(msg)),
585 None => String::new(),
586 };
587 let challenge_display = format!(
589 "{{username}}:{}:{}",
590 user_code.replace('-', "").to_uppercase(),
591 nonce
592 );
593
594 format!(
595 r#"<!DOCTYPE html>
596<html lang="en">
597<head>
598<meta charset="utf-8">
599<meta name="viewport" content="width=device-width, initial-scale=1">
600<title>Authorize Device — hyprstream</title>
601<style>
602 body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
603 max-width: 560px; margin: 60px auto; padding: 0 20px; color: #1a1a1a; background: #fafafa; }}
604 .card {{ background: #fff; border-radius: 12px; padding: 32px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }}
605 h1 {{ font-size: 1.4rem; margin: 0 0 8px; }}
606 p {{ color: #555; line-height: 1.5; }}
607 code {{ background: #f0f0f0; padding: 2px 6px; border-radius: 4px; font-size: 0.9em; word-break: break-all; }}
608 .challenge-box {{ background: #f8f8f8; border: 1px solid #ddd; border-radius: 8px;
609 padding: 12px; margin: 12px 0; font-family: monospace; font-size: 0.85em;
610 word-break: break-all; }}
611 .error {{ background: #fff0f0; color: #cc0000; border-radius: 8px; padding: 12px 16px;
612 margin: 12px 0; font-size: 0.9rem; }}
613 label {{ display: block; margin-top: 16px; color: #333; font-size: 0.9rem; font-weight: 500; }}
614 input[type=text] {{ width: 100%; padding: 10px; font-size: 0.9rem; border: 2px solid #ddd;
615 border-radius: 8px; box-sizing: border-box; margin-top: 4px; }}
616 input[type=text]:focus {{ border-color: #0066cc; outline: none; }}
617 button {{ width: 100%; padding: 12px; border: none; border-radius: 8px; font-size: 1rem;
618 cursor: pointer; font-weight: 500; background: #0066cc; color: #fff; margin-top: 24px; }}
619 button:hover {{ background: #0052a3; }}
620 .step {{ background: #f0f6ff; border-left: 3px solid #0066cc; padding: 10px 14px;
621 margin: 12px 0; border-radius: 0 6px 6px 0; font-size: 0.88rem; color: #333; }}
622</style>
623</head>
624<body>
625<div class="card">
626 <h1>Authorize Device</h1>
627 <p>Code: <code>{user_code_esc}</code></p>
628 {error_html}
629 <div class="step">
630 <strong>Step 1:</strong> Run on your workstation:<br/>
631 <code>hyprstream sign-challenge {user_code_esc}</code><br/>
632 This signs the challenge with your Ed25519 key and prints the base64 signature.
633 </div>
634 <p>Challenge string (for reference):</p>
635 <div class="challenge-box">{challenge_display_esc}</div>
636 <form method="post" action="/oauth/device/verify">
637 <input type="hidden" name="user_code" value="{user_code_esc}"/>
638 <label>Username:
639 <input type="text" name="username" required autocomplete="username" autofocus/>
640 </label>
641 <label>Signature (base64, 88 chars):
642 <input type="text" name="signature" required size="88" autocomplete="off"
643 placeholder="base64-encoded Ed25519 signature"/>
644 </label>
645 <button type="submit">Authorize Device</button>
646 </form>
647</div>
648</body>
649</html>"#,
650 user_code_esc = html_escape(user_code),
651 error_html = error_html,
652 challenge_display_esc = html_escape(&challenge_display),
653 )
654}
655
656fn render_result_page(approved: bool, username: &str) -> String {
658 let (title, message, color) = if approved {
659 (
660 "Device Authorized",
661 format!(
662 "Device authorized for user <strong>{}</strong>. You can close this window and return to your device.",
663 html_escape(username)
664 ),
665 "#0a8a0a",
666 )
667 } else {
668 (
669 "Access Denied",
670 "Access was denied for this device. You can close this window.".to_owned(),
671 "#cc0000",
672 )
673 };
674
675 format!(
676 r#"<!DOCTYPE html>
677<html lang="en">
678<head>
679<meta charset="utf-8">
680<meta name="viewport" content="width=device-width, initial-scale=1">
681<title>{title} — hyprstream</title>
682<style>
683 body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
684 max-width: 480px; margin: 60px auto; padding: 0 20px; color: #1a1a1a; background: #fafafa; }}
685 .card {{ background: #fff; border-radius: 12px; padding: 32px; box-shadow: 0 2px 8px rgba(0,0,0,0.08);
686 text-align: center; }}
687 h1 {{ font-size: 1.4rem; margin: 0 0 16px; color: {color}; }}
688 p {{ color: #555; line-height: 1.5; }}
689</style>
690</head>
691<body>
692<div class="card">
693 <h1>{title}</h1>
694 <p>{message}</p>
695</div>
696</body>
697</html>"#,
698 title = title,
699 message = message,
700 color = color,
701 )
702}
703
704#[cfg(test)]
705mod tests {
706 use super::*;
707 use ed25519_dalek::{Signer, SigningKey};
708
709 #[test]
710 fn test_render_verify_page_contains_nonce() {
711 let nonce = "abc123XYZ_nonce_value_here_for_test";
712 let html = render_verify_page("ABCD-EFGH", nonce, None);
713 assert!(html.contains(nonce), "rendered page must contain the nonce");
714 assert!(
715 html.contains("ABCDEFGH"),
716 "rendered page must contain normalized user_code in challenge"
717 );
718 assert!(
719 html.contains("Authorize Device"),
720 "page must have the heading"
721 );
722 }
723
724 #[test]
725 fn test_render_verify_page_shows_error() {
726 let html = render_verify_page("ABCD-EFGH", "somenonce", Some("Invalid signature"));
727 assert!(
728 html.contains("Invalid signature"),
729 "error message must appear in page"
730 );
731 }
732
733 #[test]
734 fn test_challenge_string_format() {
735 let username = "alice";
737 let user_code = "ABCDEFGH";
738 let nonce = "testnonce42";
739 let challenge = format!("{}:{}:{}", username, user_code, nonce);
740 assert_eq!(challenge, "alice:ABCDEFGH:testnonce42");
741 }
742
743 #[test]
744 fn test_ed25519_signature_verification_roundtrip() {
745 let signing_key = SigningKey::generate(&mut rand::thread_rng());
747 let verifying_key = signing_key.verifying_key();
748
749 let username = "alice";
750 let user_code = "ABCDEFGH";
751 let nonce = "randomnonce12345678";
752 let challenge = format!("{}:{}:{}", username, user_code, nonce);
753
754 let signature = signing_key.sign(challenge.as_bytes());
756
757 assert!(
759 verifying_key
760 .verify_strict(challenge.as_bytes(), &signature)
761 .is_ok(),
762 "signature must verify successfully"
763 );
764
765 let tampered = format!("mallory:{}:{}", user_code, nonce);
767 assert!(
768 verifying_key
769 .verify_strict(tampered.as_bytes(), &signature)
770 .is_err(),
771 "signature must NOT verify for tampered challenge"
772 );
773 }
774
775 #[test]
776 fn test_html_escape() {
777 assert_eq!(
778 html_escape("<script>alert('xss')</script>"),
779 "<script>alert('xss')</script>"
780 );
781 assert_eq!(html_escape("a & b"), "a & b");
782 assert_eq!(html_escape(r#"say "hi""#), "say "hi"");
783 }
784
785 #[test]
786 fn test_nonce_is_43_chars() {
787 let mut nonce_bytes = [0u8; 32];
789 rand::thread_rng().fill_bytes(&mut nonce_bytes);
790 let nonce = URL_SAFE_NO_PAD.encode(nonce_bytes);
791 assert_eq!(nonce.len(), 43, "nonce must be 43 base64url chars");
792 }
793}