1use std::io::{Read, Write};
33use std::net::{TcpListener, TcpStream};
34#[cfg(any(
35 target_os = "android",
36 target_os = "windows",
37 target_os = "linux",
38 target_env = "ohos"
39))]
40use std::sync::{Arc, Mutex};
41use std::time::{Duration, Instant};
42
43use crate::AuthError;
44
45#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct SessionOptions {
48 pub ephemeral: bool,
52 pub timeout: Duration,
56 pub completion_page: Option<String>,
59}
60
61impl Default for SessionOptions {
62 fn default() -> Self {
63 SessionOptions {
64 ephemeral: false,
65 timeout: Duration::from_secs(300),
66 completion_page: None,
67 }
68 }
69}
70
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub struct SessionCapabilities {
74 pub support: day_bridge::Support,
76 pub https_callback: bool,
79 pub ephemeral: bool,
81 pub scheme_callback: bool,
83 pub loopback: bool,
85}
86
87pub fn capabilities() -> SessionCapabilities {
89 let apple = cfg!(any(target_os = "ios", target_os = "macos"));
90 let desktop = cfg!(any(
91 target_os = "windows",
92 all(target_os = "linux", not(target_env = "ohos"))
93 ));
94 let web = cfg!(target_arch = "wasm32");
95 let support = if cfg!(any(
96 target_os = "ios",
97 target_os = "macos",
98 target_os = "android",
99 target_os = "windows",
100 target_os = "linux",
101 target_env = "ohos",
102 target_arch = "wasm32"
103 )) {
104 day_bridge::Support::Native
105 } else {
106 day_bridge::Support::Unsupported
107 };
108 SessionCapabilities {
109 support,
110 https_callback: apple || web,
111 ephemeral: apple,
112 scheme_callback: !web,
113 loopback: desktop || apple,
114 }
115}
116
117pub fn open(
131 url: &str,
132 callback_prefix: &str,
133 options: &SessionOptions,
134) -> impl std::future::Future<Output = Result<String, AuthError>> + Send {
135 let (tx, rx) = day_async::oneshot();
136 start(
137 url,
138 callback_prefix,
139 options,
140 Box::new(move |answer| tx.send(answer)),
141 );
142 let expected = callback_prefix.to_string();
143 async move {
144 let received = rx.await.unwrap_or(Err(AuthError::Cancelled))?;
145 if !crate::urls::callback_matches(&expected, &received) {
146 return Err(AuthError::InvalidRequest(
147 "authentication callback endpoint mismatch".into(),
148 ));
149 }
150 Ok(received)
151 }
152}
153
154pub fn page_url() -> Option<String> {
157 if cfg!(target_arch = "wasm32") {
158 crate::native::page_url()
159 .ok()
160 .filter(|u| u.starts_with("https://") || u.starts_with("http://"))
161 } else {
162 None
163 }
164}
165
166pub fn cancel() {
168 imp::cancel();
169}
170
171type OnDone = Box<dyn FnOnce(Result<String, AuthError>) + Send>;
172
173fn start(url: &str, callback_prefix: &str, options: &SessionOptions, on_done: OnDone) {
174 if crate::urls::parse(callback_prefix).is_err() {
175 on_done(Err(AuthError::InvalidRequest(
176 "the callback must be an absolute URL".into(),
177 )));
178 return;
179 }
180 if !crate::provider::is_trusted_url(url) {
181 on_done(Err(AuthError::InvalidRequest(
182 "the sign-in URL must be https (or loopback for a local provider)".into(),
183 )));
184 return;
185 }
186 imp::start(url, callback_prefix, options, on_done);
187}
188
189#[cfg(any(
191 target_os = "android",
192 target_os = "windows",
193 target_os = "linux",
194 target_env = "ohos"
195))]
196fn once(cb: OnDone) -> Arc<dyn Fn(Result<String, AuthError>) + Send + Sync> {
197 let cell = Mutex::new(Some(cb));
198 Arc::new(move |answer| {
199 let taken = match cell.lock() {
200 Ok(mut g) => g.take(),
201 Err(poisoned) => poisoned.into_inner().take(),
202 };
203 if let Some(cb) = taken {
204 cb(answer);
205 }
206 })
207}
208
209#[cfg(any(
216 target_os = "android",
217 target_os = "windows",
218 target_os = "linux",
219 target_env = "ohos"
220))]
221thread_local! {
222 static WATCH: std::cell::RefCell<Option<day_reactive::Scope>> = const { std::cell::RefCell::new(None) };
223}
224
225#[cfg(any(
230 target_os = "android",
231 target_os = "windows",
232 target_os = "linux",
233 target_env = "ohos"
234))]
235fn watch_rail(prefix: String, deliver: Arc<dyn Fn(Result<String, AuthError>) + Send + Sync>) {
236 unwatch_rail();
237 let scope = day_reactive::Scope::child();
238 scope.enter(|| {
239 day_core::on_open_url(move |url| {
240 if crate::urls::callback_matches(&prefix, url) {
241 deliver(Ok(url.to_string()));
242 unwatch_rail();
243 true
244 } else {
245 false
246 }
247 });
248 });
249 WATCH.with(|w| *w.borrow_mut() = Some(scope));
250}
251
252#[cfg(any(
254 target_os = "android",
255 target_os = "windows",
256 target_os = "linux",
257 target_env = "ohos"
258))]
259fn unwatch_rail() {
260 let taken = WATCH.with(|w| w.borrow_mut().take());
261 if let Some(scope) = taken {
262 scope.dispose();
263 }
264}
265
266pub struct Loopback {
272 listener: TcpListener,
273 redirect_uri: String,
274}
275
276impl Loopback {
277 pub fn bind(port: u16, path: &str) -> Result<Loopback, AuthError> {
284 let listener = TcpListener::bind(("127.0.0.1", port))
285 .map_err(|e| AuthError::Platform(format!("loopback listener: {e}")))?;
286 let bound = listener
287 .local_addr()
288 .map_err(|e| AuthError::Platform(format!("loopback listener: {e}")))?;
289 let path = if path.is_empty() { "/callback" } else { path };
290 let path = if path.starts_with('/') {
291 path.to_string()
292 } else {
293 format!("/{path}")
294 };
295 Ok(Loopback {
296 listener,
297 redirect_uri: format!("http://127.0.0.1:{}{}", bound.port(), path),
298 })
299 }
300
301 pub fn redirect_uri(&self) -> &str {
303 &self.redirect_uri
304 }
305
306 pub fn wait(
314 self,
315 options: &SessionOptions,
316 ) -> impl std::future::Future<Output = Result<String, AuthError>> + Send {
317 let (tx, rx) = day_async::oneshot();
318 let timeout = options.timeout;
319 let page = options
320 .completion_page
321 .clone()
322 .unwrap_or_else(|| DEFAULT_COMPLETION_PAGE.to_string());
323 let spawned = std::thread::Builder::new()
324 .name("day-auth-loopback".into())
325 .spawn(move || tx.send(self.serve(timeout, &page)));
326 let started = spawned.is_ok();
327 async move {
328 if !started {
329 return Err(AuthError::Platform(
330 "could not start the loopback thread".into(),
331 ));
332 }
333 rx.await.unwrap_or(Err(AuthError::Cancelled))
334 }
335 }
336
337 fn serve(self, timeout: Duration, page: &str) -> Result<String, AuthError> {
338 let deadline = Instant::now() + timeout;
339 self.listener
340 .set_nonblocking(true)
341 .map_err(|e| AuthError::Platform(format!("loopback listener: {e}")))?;
342 let path = self
343 .redirect_uri
344 .splitn(4, '/')
345 .nth(3)
346 .map_or_else(|| "/".to_string(), |p| format!("/{p}"));
347 loop {
348 match self.listener.accept() {
349 Ok((stream, _)) => {
350 let _ = stream.set_nonblocking(false);
351 let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
352 if let Some(url) = self.answer(stream, &path, page) {
353 return Ok(url);
354 }
355 }
356 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
357 if Instant::now() >= deadline {
358 return Err(AuthError::Timeout);
359 }
360 std::thread::sleep(Duration::from_millis(50));
361 }
362 Err(e) => return Err(AuthError::Platform(format!("loopback listener: {e}"))),
363 }
364 }
365 }
366
367 fn answer(&self, mut stream: TcpStream, path: &str, page: &str) -> Option<String> {
369 let mut buf = Vec::with_capacity(4096);
370 let mut chunk = [0u8; 1024];
371 loop {
372 match stream.read(&mut chunk) {
373 Ok(0) | Err(_) => break,
374 Ok(n) => {
375 buf.extend_from_slice(&chunk[..n]);
376 if buf.windows(4).any(|w| w == b"\r\n\r\n") || buf.len() > 64 * 1024 {
377 break;
378 }
379 }
380 }
381 }
382 let head = String::from_utf8_lossy(&buf);
383 let request_line = head.lines().next().unwrap_or("");
384 let mut parts = request_line.split(' ');
385 let (Some(method), Some(target)) = (parts.next(), parts.next()) else {
386 let _ = respond(&mut stream, 400, "text/plain", "bad request");
387 return None;
388 };
389 let target_path = target.split('?').next().unwrap_or("");
390 if method != "GET" || target_path != path {
391 let _ = respond(&mut stream, 404, "text/plain", "not found");
392 return None;
393 }
394 let _ = respond(&mut stream, 200, "text/html; charset=utf-8", page);
395 let base = self.redirect_uri.trim_end_matches(path);
396 Some(format!("{base}{target}"))
397 }
398}
399
400fn respond(
401 stream: &mut TcpStream,
402 status: u16,
403 content_type: &str,
404 body: &str,
405) -> std::io::Result<()> {
406 let reason = match status {
407 200 => "OK",
408 400 => "Bad Request",
409 404 => "Not Found",
410 _ => "",
411 };
412 write!(
413 stream,
414 "HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n",
415 body.len()
416 )?;
417 stream.write_all(body.as_bytes())?;
418 stream.flush()
419}
420
421const DEFAULT_COMPLETION_PAGE: &str = "<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>Signed in</title><style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#f4f5f7;color:#1f2933}main{text-align:center;padding:2rem}h1{font-size:1.4rem;margin:0 0 .5rem}p{margin:0;color:#52606d}</style></head><body><main><h1>Signed in</h1><p>You can close this window and return to the app.</p></main></body></html>";
423
424#[cfg(any(target_os = "ios", target_os = "macos"))]
431mod imp {
432 use super::*;
433 use crate::native::{close_session, open_session_native_async};
434
435 pub fn start(url: &str, callback_prefix: &str, options: &SessionOptions, on_done: OnDone) {
436 let scheme = callback_prefix.split(':').next().unwrap_or("").to_string();
437 let _ = open_session_native_async(
438 url,
439 &scheme,
440 callback_prefix,
441 options.ephemeral,
442 move |answer| on_done(super::read_answer(answer)),
443 );
444 }
445
446 pub fn cancel() {
447 let _ = close_session();
448 }
449}
450
451#[cfg(target_os = "android")]
455mod imp {
456 use super::*;
457 use crate::native::{close_session, open_session_native_async};
458
459 pub fn start(url: &str, callback_prefix: &str, options: &SessionOptions, on_done: OnDone) {
460 let deliver = once(on_done);
461 watch_rail(callback_prefix.to_string(), deliver.clone());
462 let scheme = callback_prefix.split(':').next().unwrap_or("").to_string();
463 let resumed = deliver.clone();
464 let _ = open_session_native_async(
465 url,
466 &scheme,
467 callback_prefix,
468 options.ephemeral,
469 move |answer| match answer {
470 Ok(_) => {
473 let resumed = resumed.clone();
474 let _ = std::thread::Builder::new()
475 .name("day-auth-resume".into())
476 .spawn(move || {
477 std::thread::sleep(Duration::from_millis(700));
478 resumed(Err(AuthError::Cancelled));
479 });
480 }
481 Err(e) => resumed(Err(AuthError::from(e))),
482 },
483 );
484 }
485
486 pub fn cancel() {
487 let _ = close_session();
488 }
489}
490
491#[cfg(target_arch = "wasm32")]
494mod imp {
495 use super::*;
496 use crate::native::{close_session, open_session_native_async};
497
498 pub fn start(url: &str, callback_prefix: &str, options: &SessionOptions, on_done: OnDone) {
499 let _ =
500 open_session_native_async(url, "", callback_prefix, options.ephemeral, move |answer| {
501 on_done(super::read_answer(answer));
502 });
503 }
504
505 pub fn cancel() {
506 let _ = close_session();
507 }
508}
509
510#[cfg(not(any(
514 target_os = "ios",
515 target_os = "macos",
516 target_os = "android",
517 target_arch = "wasm32"
518)))]
519mod imp {
520 use super::*;
521
522 type Deliver = Arc<dyn Fn(Result<String, AuthError>) + Send + Sync>;
523 static ACTIVE: Mutex<Option<Deliver>> = Mutex::new(None);
524
525 pub fn start(url: &str, callback_prefix: &str, _options: &SessionOptions, on_done: OnDone) {
526 let deliver = once(on_done);
527 watch_rail(callback_prefix.to_string(), deliver.clone());
528 if let Ok(mut slot) = ACTIVE.lock() {
529 *slot = Some(deliver);
530 }
531 day_core::open_url(url);
532 }
533
534 pub fn cancel() {
535 let taken = ACTIVE.lock().ok().and_then(|mut s| s.take());
536 if let Some(deliver) = taken {
537 deliver(Err(AuthError::Cancelled));
538 }
539 }
540}
541
542#[cfg(any(target_os = "ios", target_os = "macos", target_arch = "wasm32"))]
544fn read_answer(answer: Result<String, day_bridge::Error>) -> Result<String, AuthError> {
545 match answer {
546 Ok(text) if text == "cancelled" => Err(AuthError::Cancelled),
547 Ok(text) if text == "unsupported" => Err(AuthError::Unsupported),
548 Ok(text) if text.starts_with("error:") => Err(AuthError::Platform(text[6..].to_string())),
549 Ok(url) if url.contains(':') => Ok(url),
550 Ok(other) => Err(AuthError::Platform(format!(
551 "unexpected session answer {other:?}"
552 ))),
553 Err(e) => Err(AuthError::from(e)),
554 }
555}
556
557#[cfg(test)]
558mod tests {
559 use super::*;
560
561 #[test]
562 fn capabilities_answer_for_this_host() {
563 let caps = capabilities();
564 if cfg!(any(
565 target_os = "macos",
566 target_os = "linux",
567 target_os = "windows"
568 )) {
569 assert_eq!(caps.support, day_bridge::Support::Native);
570 assert!(caps.loopback);
571 }
572 }
573
574 #[test]
575 fn loopback_binds_builds_the_redirect_and_returns_the_request_url() {
576 let loopback = Loopback::bind(0, "/callback").expect("bind");
577 let redirect = loopback.redirect_uri().to_string();
578 assert!(redirect.starts_with("http://127.0.0.1:"));
579 assert!(redirect.ends_with("/callback"));
580 let options = SessionOptions {
581 timeout: Duration::from_secs(5),
582 ..SessionOptions::default()
583 };
584 let (tx, rx) = std::sync::mpsc::channel();
585 let server = std::thread::spawn(move || {
586 let answer = loopback.serve(options.timeout, "done");
587 let _ = tx.send(answer);
588 });
589 let port: u16 = redirect
591 .trim_start_matches("http://127.0.0.1:")
592 .split('/')
593 .next()
594 .and_then(|p| p.parse().ok())
595 .expect("port");
596 let mut other = TcpStream::connect(("127.0.0.1", port)).expect("connect");
597 other
598 .write_all(b"GET /favicon.ico HTTP/1.1\r\nHost: x\r\n\r\n")
599 .expect("write");
600 let mut reply = String::new();
601 let _ = other.read_to_string(&mut reply);
602 assert!(reply.starts_with("HTTP/1.1 404"));
603 let mut browser = TcpStream::connect(("127.0.0.1", port)).expect("connect");
604 browser
605 .write_all(b"GET /callback?code=abc&state=xyz HTTP/1.1\r\nHost: x\r\n\r\n")
606 .expect("write");
607 let mut reply = String::new();
608 let _ = browser.read_to_string(&mut reply);
609 assert!(reply.starts_with("HTTP/1.1 200"));
610 assert!(reply.ends_with("done"));
611 let answer = rx.recv().expect("answer");
612 assert_eq!(answer, Ok(format!("{redirect}?code=abc&state=xyz")));
613 server.join().expect("join");
614 }
615
616 #[test]
617 fn loopback_times_out_without_a_request() {
618 let loopback = Loopback::bind(0, "cb").expect("bind");
619 assert!(loopback.redirect_uri().ends_with("/cb"));
620 assert_eq!(
621 loopback.serve(Duration::from_millis(120), "done"),
622 Err(AuthError::Timeout)
623 );
624 }
625
626 #[test]
627 fn open_rejects_unusable_arguments_through_the_callback() {
628 let (tx, rx) = std::sync::mpsc::channel();
629 start(
630 "https://x",
631 "",
632 &SessionOptions::default(),
633 Box::new(move |a| {
634 let _ = tx.send(a);
635 }),
636 );
637 std::assert_matches!(rx.recv(), Ok(Err(AuthError::InvalidRequest(_))));
638 let (tx, rx) = std::sync::mpsc::channel();
639 start(
640 "ftp://x",
641 "myapp://cb",
642 &SessionOptions::default(),
643 Box::new(move |a| {
644 let _ = tx.send(a);
645 }),
646 );
647 std::assert_matches!(rx.recv(), Ok(Err(AuthError::InvalidRequest(_))));
648 }
649}