//! The `playback` URI scheme: serves a call's cached mix //! ([`recorder_core::playback`]) to the main window, and to no other //! webview — the backend-login window shows a remote page, which must //! never read customer audio. //! //! The URL carries only the call id: `playback://localhost/` on Linux //! and macOS, `http://playback.localhost/` on Windows (what the UI's //! `convertFileSrc(id, 'playback')` builds). Range requests are answered //! so the player can seek without loading the whole file. use std::fs::File; use std::io::{self, ErrorKind, Read, Seek, SeekFrom}; use std::path::Path; use http_range::HttpRange; use recorder_core::model::CallId; use recorder_core::playback::cache_path; use tauri::http::header::{ ACCEPT_RANGES, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, CACHE_CONTROL, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE, RANGE, }; use tauri::http::{response, Method, Request, Response, StatusCode}; /// The scheme's name (see the module docs for its URLs). pub const SCHEME: &str = "playback"; /// The only webview the scheme answers. pub const PLAYER_WEBVIEW: &str = "main"; /// The most bytes one range response carries (like Tauri's asset protocol). const MAX_RANGE_LEN: u64 = 1024 * 1024; /// Answers `request` from webview `webview` with call ``'s mix in the /// playback directory `dir`: 403 for any webview but the main window, 404 /// for anything but a plain numeric id or a mix that is not there, 206 for /// a satisfiable range (at most [`MAX_RANGE_LEN`] bytes), 416 otherwise. pub fn respond(webview: &str, request: &Request>, dir: &Path) -> Response> { if webview != PLAYER_WEBVIEW { log::warn!("playback refused to webview {webview}"); return empty(StatusCode::FORBIDDEN); } let method = request.method(); if method != Method::GET && method != Method::HEAD { return empty(StatusCode::METHOD_NOT_ALLOWED); } let Some(id) = call_id(request.uri().path()) else { return empty(StatusCode::NOT_FOUND); }; let range = request .headers() .get(RANGE) .map(|value| value.to_str().unwrap_or_default()); match serve(&cache_path(dir, id), range, method == Method::HEAD) { Ok(response) => response, Err(e) if e.kind() == ErrorKind::NotFound => empty(StatusCode::NOT_FOUND), Err(e) => { log::error!("call {id}: could not serve the playback file: {e}"); empty(StatusCode::INTERNAL_SERVER_ERROR) } } } /// The answer while the app state is not set up yet (no window can play /// before it is, so this is never expected). pub fn unavailable() -> Response> { empty(StatusCode::SERVICE_UNAVAILABLE) } /// The call id of a request path: exactly `/`. fn call_id(path: &str) -> Option { let digits = path.strip_prefix('/')?; if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { return None; } digits.parse().ok() } fn serve(path: &Path, range: Option<&str>, head: bool) -> io::Result>> { let mut file = File::open(path)?; let len = file.metadata()?.len(); let builder = headers(); let Some(range) = range else { let mut body = Vec::new(); if !head { file.read_to_end(&mut body)?; } return Ok(build(builder.header(CONTENT_LENGTH, len), body)); }; // A media element asks for one range at a time; of several, the first. let Some(range) = HttpRange::parse(range, len) .ok() .and_then(|r| r.first().copied()) else { return Ok(build( builder .status(StatusCode::RANGE_NOT_SATISFIABLE) .header(CONTENT_RANGE, format!("bytes */{len}")), Vec::new(), )); }; let start = range.start; let count = range.length.min(MAX_RANGE_LEN); let mut body = Vec::new(); if !head { file.seek(SeekFrom::Start(start))?; file.take(count).read_to_end(&mut body)?; } Ok(build( builder .status(StatusCode::PARTIAL_CONTENT) .header( CONTENT_RANGE, format!("bytes {start}-{}/{len}", start + count - 1), ) .header(CONTENT_LENGTH, count), body, )) } /// Headers of every answer that carries the mix. Any origin may read it: /// only the main window's own page can reach the scheme at all (the /// webview check above), and on Linux it fetches the mix cross-origin. fn headers() -> response::Builder { Response::builder() .header(CONTENT_TYPE, "audio/wav") .header(CACHE_CONTROL, "no-store") .header(ACCEPT_RANGES, "bytes") .header(ACCESS_CONTROL_ALLOW_ORIGIN, "*") .header(ACCESS_CONTROL_EXPOSE_HEADERS, "content-range") } fn build(builder: response::Builder, body: Vec) -> Response> { builder .body(body) .unwrap_or_else(|_| empty(StatusCode::INTERNAL_SERVER_ERROR)) } fn empty(status: StatusCode) -> Response> { let mut response = Response::new(Vec::new()); *response.status_mut() = status; response .headers_mut() .insert(CACHE_CONTROL, "no-store".parse().unwrap()); response } #[cfg(test)] mod tests { use std::fs; use super::*; /// A playback directory with a 10-byte "mix" for call 7. fn dir() -> tempfile::TempDir { let dir = tempfile::tempdir().unwrap(); fs::write(cache_path(dir.path(), 7), b"0123456789").unwrap(); dir } fn get(uri: &str, range: Option<&str>) -> Request> { let mut builder = Request::builder().uri(uri); if let Some(range) = range { builder = builder.header(RANGE, range); } builder.body(Vec::new()).unwrap() } #[test] fn only_the_main_window_gets_the_mix() { let dir = dir(); let request = get("playback://localhost/7", None); for webview in ["backend-login", "prompt", "recorder", "", "Main"] { let response = respond(webview, &request, dir.path()); assert_eq!(response.status(), StatusCode::FORBIDDEN, "{webview}"); assert!(response.body().is_empty()); } let response = respond("main", &request, dir.path()); assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.body(), b"0123456789"); assert_eq!(response.headers()[CONTENT_TYPE], "audio/wav"); assert_eq!(response.headers()[CACHE_CONTROL], "no-store"); assert_eq!(response.headers()[CONTENT_LENGTH], "10"); } #[test] fn both_platform_url_forms_name_the_call() { let dir = dir(); for uri in ["playback://localhost/7", "http://playback.localhost/7"] { let response = respond("main", &get(uri, None), dir.path()); assert_eq!(response.status(), StatusCode::OK, "{uri}"); } } #[test] fn nothing_but_a_numeric_call_id_is_served() { let dir = dir(); fs::write(dir.path().join("secret.wav"), b"x").unwrap(); fs::write(dir.path().join("7.wav.part"), b"x").unwrap(); for path in [ "/", "/7.wav", "/secret", "/../7", "/%2e%2e%2f7", "/7/", "/7.wav.part", "/-7", "/+7", "/%EF%BC%97", "/99999999999999999999999", "/8", ] { let request = get(&format!("playback://localhost{path}"), None); let response = respond("main", &request, dir.path()); assert_eq!(response.status(), StatusCode::NOT_FOUND, "{path}"); } assert_eq!(call_id("/7"), Some(7)); assert_eq!(call_id("/0012"), Some(12)); } #[test] fn a_range_is_served_partially() { let dir = dir(); let response = respond( "main", &get("playback://localhost/7", Some("bytes=2-5")), dir.path(), ); assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT); assert_eq!(response.body(), b"2345"); assert_eq!(response.headers()[CONTENT_RANGE], "bytes 2-5/10"); assert_eq!(response.headers()[CONTENT_LENGTH], "4"); let open_ended = respond( "main", &get("playback://localhost/7", Some("bytes=8-")), dir.path(), ); assert_eq!(open_ended.body(), b"89"); assert_eq!(open_ended.headers()[CONTENT_RANGE], "bytes 8-9/10"); } #[test] fn a_range_beyond_the_end_is_not_satisfiable() { let dir = dir(); let response = respond( "main", &get("playback://localhost/7", Some("bytes=20-30")), dir.path(), ); assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE); assert_eq!(response.headers()[CONTENT_RANGE], "bytes */10"); assert!(response.body().is_empty()); } #[test] fn a_long_range_is_cut_to_the_maximum() { let dir = tempfile::tempdir().unwrap(); let len = MAX_RANGE_LEN as usize * 2 + 3; fs::write(cache_path(dir.path(), 1), vec![1u8; len]).unwrap(); let response = respond( "main", &get("playback://localhost/1", Some("bytes=1-")), dir.path(), ); assert_eq!(response.body().len(), MAX_RANGE_LEN as usize); assert_eq!( response.headers()[CONTENT_RANGE], format!("bytes 1-{}/{len}", MAX_RANGE_LEN).as_str() ); } #[test] fn head_has_no_body_and_other_methods_are_refused() { let dir = dir(); let head = Request::builder() .method(Method::HEAD) .uri("playback://localhost/7") .body(Vec::new()) .unwrap(); let response = respond("main", &head, dir.path()); assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.headers()[CONTENT_LENGTH], "10"); assert!(response.body().is_empty()); let post = Request::builder() .method(Method::POST) .uri("playback://localhost/7") .body(Vec::new()) .unwrap(); let response = respond("main", &post, dir.path()); assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED); } }