Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

fix: save right-click image/video downloads natively under strict CSP

Claude66ae24b9d125
diff --git a/src-tauri/src/app/invoke.rs b/src-tauri/src/app/invoke.rs
index 82022f42..4a6d5c31 100644
--- a/src-tauri/src/app/invoke.rs
+++ b/src-tauri/src/app/invoke.rs
@@ -1,5 +1,5 @@
use crate::util::{check_file_or_append, get_download_message_with_lang, show_toast, MessageType};
-use std::fs::{self, File};
+use std::fs::File;
use std::io::Write;
use std::str::FromStr;
use std::sync::atomic::{AtomicI64, Ordering};
@@ -73,13 +73,6 @@ pub struct DownloadFileParams {
language: Option<String>,
}
-#[derive(serde::Deserialize)]
-pub struct BinaryDownloadParams {
- filename: String,
- binary: Vec<u8>,
- language: Option<String>,
-}
-
#[derive(serde::Deserialize)]
pub struct NotificationParams {
title: String,
@@ -147,47 +140,6 @@ pub async fn download_file(app: AppHandle, params: DownloadFileParams) -> Result
}
}
-#[command]
-pub async fn download_file_by_binary(
- app: AppHandle,
- params: BinaryDownloadParams,
-) -> Result<(), String> {
- let window: WebviewWindow = app.get_webview_window("pake").ok_or("Window not found")?;
-
- show_toast(
- &window,
- &get_download_message_with_lang(MessageType::Start, params.language.clone()),
- );
-
- let download_dir = app
- .path()
- .download_dir()
- .map_err(|e| format!("Failed to get download dir: {}", e))?;
-
- let output_path = download_dir.join(&params.filename);
-
- let path_str = output_path.to_str().ok_or("Invalid output path")?;
-
- let file_path = check_file_or_append(path_str);
-
- match fs::write(file_path, &params.binary) {
- Ok(_) => {
- show_toast(
- &window,
- &get_download_message_with_lang(MessageType::Success, params.language.clone()),
- );
- Ok(())
- }
- Err(e) => {
- show_toast(
- &window,
- &get_download_message_with_lang(MessageType::Failure, params.language),
- );
- Err(e.to_string())
- }
- }
-}
-
#[command]
pub fn send_notification(app: AppHandle, params: NotificationParams) -> Result<(), String> {
use tauri_plugin_notification::NotificationExt;
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index d5eb88ce..7e327e70 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -340,87 +340,19 @@ document.addEventListener("DOMContentLoaded", () => {
true,
);
- // Collect blob urls to blob by overriding window.URL.createObjectURL
- function collectUrlToBlobs() {
- const backupCreateObjectURL = window.URL.createObjectURL;
- window.blobToUrlCaches = new Map();
- window.URL.createObjectURL = (blob) => {
- const url = backupCreateObjectURL.call(window.URL, blob);
- window.blobToUrlCaches.set(url, blob);
- return url;
- };
- }
-
- function convertBlobUrlToBinary(blobUrl) {
- return new Promise((resolve, reject) => {
- const blob = window.blobToUrlCaches.get(blobUrl);
- if (!blob) {
- fetch(blobUrl)
- .then((res) => res.arrayBuffer())
- .then((buffer) => resolve(Array.from(new Uint8Array(buffer))))
- .catch(reject);
- return;
- }
- const reader = new FileReader();
- reader.readAsArrayBuffer(blob);
- reader.onload = () => {
- resolve(Array.from(new Uint8Array(reader.result)));
- };
- reader.onerror = () => reject(reader.error);
- });
- }
-
- function downloadFromDataUri(dataURI, filename) {
- try {
- const byteString = atob(dataURI.split(",")[1]);
- // write the bytes of the string to an ArrayBuffer
- const bufferArray = new ArrayBuffer(byteString.length);
-
- // create a view into the buffer
- const binary = new Uint8Array(bufferArray);
-
- // set the bytes of the buffer to the correct values
- for (let i = 0; i < byteString.length; i++) {
- binary[i] = byteString.charCodeAt(i);
- }
-
- // write the ArrayBuffer to a binary, and you're done
- const userLanguage = getUserLanguage();
- invoke("download_file_by_binary", {
- params: {
- filename,
- binary: Array.from(binary),
- language: userLanguage,
- },
- }).catch((error) => {
- console.error("Failed to download data URI file:", filename, error);
- showDownloadError(filename);
- });
- } catch (error) {
- console.error("Failed to process data URI:", dataURI, error);
- showDownloadError(filename || "file");
- }
- }
-
- function downloadFromBlobUrl(blobUrl, filename) {
- convertBlobUrlToBinary(blobUrl)
- .then((binary) => {
- const userLanguage = getUserLanguage();
- invoke("download_file_by_binary", {
- params: {
- filename,
- binary,
- language: userLanguage,
- },
- }).catch((error) => {
- console.error("Failed to download blob file:", filename, error);
- showDownloadError(filename);
- });
- })
- .catch((error) => {
- console.error("Failed to convert blob to binary:", blobUrl, error);
- showDownloadError(filename);
- });
+ // Trigger a native browser download via a transient anchor click. The Rust
+ // on_download handler then writes the file to the Downloads folder. This is
+ // used for blob:/data: URLs because routing their bytes through the Tauri
+ // IPC fails on strict-CSP sites (e.g. Gemini), whose connect-src blocks the
+ // IPC origin. The native download path is independent of the page CSP.
+ function triggerNativeDownload(url, filename) {
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = filename || "";
+ anchor.style.display = "none";
+ document.body.appendChild(anchor);
+ anchor.click();
+ document.body.removeChild(anchor);
}
// process special download protocol['data:','blob:']
@@ -599,8 +531,6 @@ document.addEventListener("DOMContentLoaded", () => {
// Prevent some special websites from executing in advance, before the click event is triggered.
document.addEventListener("click", detectAnchorElementClick, true);
- collectUrlToBlobs();
-
// Rewrite the window.open function.
const originalWindowOpen = window.open;
window.open = function (url, name, specs) {
@@ -836,12 +766,10 @@ document.addEventListener("DOMContentLoaded", () => {
const filename = getFilenameFromUrl(imageUrl) || "image";
// Handle different URL types
- if (imageUrl.startsWith("data:")) {
- downloadFromDataUri(imageUrl, filename);
- } else if (imageUrl.startsWith("blob:")) {
- if (window.blobToUrlCaches && window.blobToUrlCaches.has(imageUrl)) {
- downloadFromBlobUrl(imageUrl, filename);
- }
+ if (isSpecialDownload(imageUrl)) {
+ // Download blob:/data: natively so it works under strict CSP; the Rust
+ // on_download handler saves it to the Downloads folder.
+ triggerNativeDownload(imageUrl, filename);
} else {
// Regular HTTP(S) image
const userLanguage = getUserLanguage();
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index c4c90ad9..93c6c0f9 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -13,9 +13,8 @@ const WINDOW_SHOW_DELAY: u64 = 50;
use app::{
invoke::{
- clear_cache_and_restart, clear_dock_badge, download_file, download_file_by_binary,
- increment_dock_badge, send_notification, set_dock_badge, set_dock_badge_label,
- update_theme_mode,
+ clear_cache_and_restart, clear_dock_badge, download_file, increment_dock_badge,
+ send_notification, set_dock_badge, set_dock_badge_label, update_theme_mode,
},
setup::{set_global_shortcut, set_system_tray},
window::{open_additional_window_safe, set_window, MultiWindowState},
@@ -81,7 +80,6 @@ pub fn run_app() {
app_builder
.invoke_handler(tauri::generate_handler![
download_file,
- download_file_by_binary,
send_notification,
increment_dock_badge,
set_dock_badge,