11use futures_util:: StreamExt ;
22use sha2:: { Digest , Sha256 } ;
33use tauri:: State ;
4+ use tokio_util:: sync:: CancellationToken ;
45
56use crate :: app_state:: AppState ;
67use crate :: commands:: clipboard:: with_clipboard;
78use crate :: commands:: export_util:: save_bytes_with_dialog;
8- use crate :: commands:: media:: { detect_and_validate_mime, mint_media_get_auth, sanitize_filename} ;
9+ use crate :: commands:: media:: { detect_and_validate_mime, mint_media_get_auth} ;
10+ use crate :: commands:: media_filename:: sanitize_filename;
911use crate :: commands:: {
1012 personas:: {
1113 parse_snapshot_payload_from_bytes, MAX_SNAPSHOT_JSON_BYTES , MAX_SNAPSHOT_PNG_BYTES ,
@@ -18,7 +20,7 @@ use crate::commands::{
1820use crate :: relay:: { classify_request_error, relay_api_base_url_with_override, relay_error_message} ;
1921
2022/// Maximum download size: 50 MiB. Prevents OOM from oversized responses.
21- const MAX_DOWNLOAD_BYTES : u64 = 50 * 1024 * 1024 ;
23+ pub ( super ) const MAX_DOWNLOAD_BYTES : u64 = 50 * 1024 * 1024 ;
2224
2325/// Download request timeout.
2426const DOWNLOAD_TIMEOUT : std:: time:: Duration = std:: time:: Duration :: from_secs ( 60 ) ;
@@ -29,7 +31,7 @@ const DOWNLOAD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60)
2931/// - URL scheme is `https` (or `http` for localhost dev)
3032/// - URL origin matches the relay base URL
3133/// - URL path matches `/media/{hash}.{ext}`
32- fn validate_download_url ( url : & str , relay_base : & str ) -> Result < ( ) , String > {
34+ pub ( super ) fn validate_download_url ( url : & str , relay_base : & str ) -> Result < ( ) , String > {
3335 let parsed = url:: Url :: parse ( url) . map_err ( |_| "invalid URL" . to_string ( ) ) ?;
3436 let base = url:: Url :: parse ( relay_base) . map_err ( |_| "invalid relay base URL" . to_string ( ) ) ?;
3537
@@ -139,32 +141,6 @@ pub async fn download_file(
139141 save_bytes_with_dialog ( & app, & filename, "All Files" , & extensions, & bytes) . await
140142}
141143
142- /// Fetch relay media bytes for the composer image editor.
143- ///
144- /// The editor composites the image onto a canvas and needs pixel access.
145- /// Handing the webview raw bytes over IPC (which it wraps in a same-origin
146- /// `blob:` URL) keeps the canvas un-tainted without involving CORS — and
147- /// therefore without any media-proxy header or origin-gate changes.
148- ///
149- /// Same SSRF validation, size cap, and content policy as the download
150- /// commands above.
151- ///
152- /// Returns `tauri::ipc::Response` so the bytes cross IPC as a raw buffer
153- /// instead of a JSON number array (which would be ~3x the size to
154- /// serialize and deserialize at the 50 MiB cap).
155- #[ tauri:: command]
156- pub async fn fetch_media_bytes (
157- url : String ,
158- state : State < ' _ , AppState > ,
159- ) -> Result < tauri:: ipc:: Response , String > {
160- let relay_base = relay_api_base_url_with_override ( & state) ;
161- validate_download_url ( & url, & relay_base) ?;
162-
163- let bytes = fetch_blob_bytes ( & url, & state) . await ?;
164- detect_and_validate_mime ( & bytes) ?;
165- Ok ( tauri:: ipc:: Response :: new ( bytes) )
166- }
167-
168144/// Copy an image from a relay media URL directly to the system clipboard.
169145///
170146/// Fetches the image, decodes it to RGBA8, and writes it to the clipboard via
@@ -255,7 +231,7 @@ pub async fn copy_text_to_clipboard(
255231/// HTTP client, enforcing the download size cap. The caller is responsible for
256232/// validating the URL origin and for any content-type checks on the result.
257233async fn fetch_blob_bytes ( url : & str , state : & State < ' _ , AppState > ) -> Result < Vec < u8 > , String > {
258- fetch_blob_bytes_with_cap ( url, state, MAX_DOWNLOAD_BYTES ) . await
234+ fetch_blob_bytes_with_cap ( url, state, MAX_DOWNLOAD_BYTES , None ) . await
259235}
260236
261237/// The command-facing error for a media-fetch response status, or `None` if
@@ -277,10 +253,11 @@ fn redirect_refusal_error(status: reqwest::StatusCode) -> Option<String> {
277253}
278254
279255/// Core streaming fetcher with a caller-supplied byte cap.
280- async fn fetch_blob_bytes_with_cap (
256+ pub ( super ) async fn fetch_blob_bytes_with_cap (
281257 url : & str ,
282258 state : & State < ' _ , AppState > ,
283259 cap : u64 ,
260+ cancellation : Option < & CancellationToken > ,
284261) -> Result < Vec < u8 > , String > {
285262 // Fetch bytes via the no-redirect media client (goes through the VPN tunnel).
286263 // A no-redirect client keeps the minted media auth token from being
@@ -296,7 +273,16 @@ async fn fetch_blob_bytes_with_cap(
296273 req = req. header ( "authorization" , auth) ;
297274 }
298275
299- let resp = req. send ( ) . await . map_err ( |e| classify_request_error ( & e) ) ?;
276+ let request = req. send ( ) ;
277+ let resp = if let Some ( cancellation) = cancellation {
278+ tokio:: select! {
279+ _ = cancellation. cancelled( ) => return Err ( "media fetch cancelled" . to_string( ) ) ,
280+ result = request => result,
281+ }
282+ } else {
283+ request. await
284+ }
285+ . map_err ( |e| classify_request_error ( & e) ) ?;
300286
301287 if let Some ( err) = redirect_refusal_error ( resp. status ( ) ) {
302288 return Err ( err) ;
@@ -321,7 +307,18 @@ async fn fetch_blob_bytes_with_cap(
321307 // even when Content-Length is missing or dishonest.
322308 let mut bytes = Vec :: new ( ) ;
323309 let mut stream = resp. bytes_stream ( ) ;
324- while let Some ( chunk) = stream. next ( ) . await {
310+ loop {
311+ let next = if let Some ( cancellation) = cancellation {
312+ tokio:: select! {
313+ _ = cancellation. cancelled( ) => return Err ( "media fetch cancelled" . to_string( ) ) ,
314+ next = stream. next( ) => next,
315+ }
316+ } else {
317+ stream. next ( ) . await
318+ } ;
319+ let Some ( chunk) = next else {
320+ break ;
321+ } ;
325322 let chunk = chunk. map_err ( |e| classify_request_error ( & e) ) ?;
326323 if bytes. len ( ) as u64 + chunk. len ( ) as u64 > cap {
327324 return Err ( format ! ( "file too large (max {} MiB)" , cap / ( 1024 * 1024 ) ) ) ;
@@ -482,7 +479,7 @@ pub async fn fetch_snapshot_bytes(
482479 ensure_declared_size_within_cap ( expected_size, kind) ?;
483480
484481 // ── Bounded fetch ─────────────────────────────────────────────────────
485- let bytes = fetch_blob_bytes_with_cap ( & url, & state, cap) . await ?;
482+ let bytes = fetch_blob_bytes_with_cap ( & url, & state, cap, None ) . await ?;
486483
487484 // ── Post-fetch validation ─────────────────────────────────────────────
488485 // 1. Byte length must equal the declared imeta size.
0 commit comments