host: gallery folders and the opt-in clipboard history
media: gallery settings (absolute folders, deduplicated), listing and resolving images only directly inside owner-chosen folders (links must stay inside), data URLs, the bounded clipboard history with its index and image files, PNG encoding. media::clipboard (tauri feature): reading the OS clipboard, the Windows change counter, skipping copies marked private by password managers, and the opt-in polling loop (records from the next copy after opting in; releases the clipboard while off).
This commit is contained in:
parent
877dd8fa58
commit
683c931ae8
5 changed files with 721 additions and 1 deletions
166
crates/waybetter-host/Cargo.lock
generated
166
crates/waybetter-host/Cargo.lock
generated
|
|
@ -57,6 +57,26 @@ version = "1.0.104"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf"
|
||||
dependencies = [
|
||||
"clipboard-win",
|
||||
"image",
|
||||
"log",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"objc2-foundation",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.59.0",
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2"
|
||||
version = "0.5.3"
|
||||
|
|
@ -377,6 +397,12 @@ version = "1.5.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder-lite"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.12.1"
|
||||
|
|
@ -544,6 +570,15 @@ dependencies = [
|
|||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clipboard-win"
|
||||
version = "5.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
|
||||
dependencies = [
|
||||
"error-code",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "combine"
|
||||
version = "4.6.8"
|
||||
|
|
@ -652,6 +687,12 @@ version = "0.8.23"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
|
||||
[[package]]
|
||||
name = "crunchy"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
|
|
@ -1061,6 +1102,12 @@ dependencies = [
|
|||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "error-code"
|
||||
version = "3.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"
|
||||
|
||||
[[package]]
|
||||
name = "event-listener"
|
||||
version = "5.4.2"
|
||||
|
|
@ -1087,6 +1134,12 @@ version = "2.5.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "fax"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
|
||||
|
||||
[[package]]
|
||||
name = "fdeflate"
|
||||
version = "0.3.7"
|
||||
|
|
@ -1370,6 +1423,16 @@ dependencies = [
|
|||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gethostname"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
|
||||
dependencies = [
|
||||
"rustix",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
|
|
@ -1552,6 +1615,17 @@ dependencies = [
|
|||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "half"
|
||||
version = "2.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"crunchy",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.12.3"
|
||||
|
|
@ -1840,6 +1914,20 @@ dependencies = [
|
|||
"icu_properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "image"
|
||||
version = "0.25.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"byteorder-lite",
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png 0.18.1",
|
||||
"tiff",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "1.9.3"
|
||||
|
|
@ -2255,6 +2343,16 @@ dependencies = [
|
|||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "moxcms"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
"pxfm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "muda"
|
||||
version = "0.20.0"
|
||||
|
|
@ -2383,6 +2481,7 @@ dependencies = [
|
|||
"block2",
|
||||
"objc2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"objc2-foundation",
|
||||
"objc2-quartz-core",
|
||||
]
|
||||
|
|
@ -2922,6 +3021,18 @@ dependencies = [
|
|||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pxfm"
|
||||
version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.42.0"
|
||||
|
|
@ -4159,6 +4270,20 @@ dependencies = [
|
|||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiff"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"flate2",
|
||||
"half",
|
||||
"quick-error",
|
||||
"weezl",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.55"
|
||||
|
|
@ -4675,13 +4800,16 @@ dependencies = [
|
|||
name = "waybetter-host"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"argon2",
|
||||
"base64 0.22.1",
|
||||
"chacha20poly1305",
|
||||
"chrono",
|
||||
"clipboard-win",
|
||||
"ed25519-dalek",
|
||||
"getrandom 0.2.17",
|
||||
"gtk",
|
||||
"image",
|
||||
"minisign-verify",
|
||||
"objc2-app-kit",
|
||||
"reqwest",
|
||||
|
|
@ -4818,6 +4946,12 @@ dependencies = [
|
|||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "weezl"
|
||||
version = "0.1.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
|
|
@ -5246,6 +5380,23 @@ dependencies = [
|
|||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x11rb"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
|
||||
dependencies = [
|
||||
"gethostname",
|
||||
"rustix",
|
||||
"x11rb-protocol",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x11rb-protocol"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.3"
|
||||
|
|
@ -5431,6 +5582,21 @@ version = "1.0.23"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
|
||||
[[package]]
|
||||
name = "zune-core"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpeg"
|
||||
version = "0.5.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
|
||||
dependencies = [
|
||||
"zune-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zvariant"
|
||||
version = "5.15.0"
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ path = "src/lib.rs"
|
|||
[features]
|
||||
default = []
|
||||
# Tauri glue (webview helpers, window system menu). Off for headless tests.
|
||||
tauri = ["dep:tauri", "dep:tauri-plugin-notification", "dep:windows", "dep:webview2-com", "dep:gtk", "dep:objc2-app-kit"]
|
||||
tauri = ["dep:tauri", "dep:tauri-plugin-notification", "dep:arboard", "dep:clipboard-win", "dep:windows", "dep:webview2-com", "dep:gtk", "dep:objc2-app-kit"]
|
||||
# Store downloads (`store::net`): allow-listed https, no redirects or cookies, size caps.
|
||||
net = ["dep:reqwest", "dep:rustls"]
|
||||
|
||||
|
|
@ -26,6 +26,8 @@ sha2 = "0.10"
|
|||
chrono = { version = "0.4", default-features = false, features = ["clock"] }
|
||||
minisign-verify = "0.2"
|
||||
base64 = "0.22"
|
||||
# PNG encoding of clipboard images (media::encode_png).
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
# Store catalog signatures (Ed25519 over the exact catalog bytes).
|
||||
ed25519-dalek = "2"
|
||||
# The OS language preference (first run, "Follow system"); no dependencies of its own on desktop.
|
||||
|
|
@ -38,6 +40,8 @@ getrandom = "0.2"
|
|||
tauri = { version = "2", features = ["unstable"], optional = true }
|
||||
# Native OS notifications (alerts::notify); the app registers the plugin.
|
||||
tauri-plugin-notification = { version = "2", optional = true }
|
||||
# Opt-in local clipboard history (media::clipboard), polled natively.
|
||||
arboard = { version = "3", optional = true }
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"], optional = true }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring"], optional = true }
|
||||
|
||||
|
|
@ -45,6 +49,8 @@ rustls = { version = "0.23", default-features = false, features = ["ring"], opti
|
|||
windows = { version = "0.62", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"], optional = true }
|
||||
# The WebView2 COM interfaces wry already links (hidden tabs: low memory target).
|
||||
webview2-com = { version = "0.39", optional = true }
|
||||
# Clipboard sequence number (skip unchanged polls) and password-manager exclusion formats.
|
||||
clipboard-win = { version = "5", optional = true }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# The GTK version tauri/wry link: child webviews are laid out in a GtkOverlay (host::place_child).
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@
|
|||
//! - [`workspaces`]: saved tab/pane/deck layouts, bounded and well-formed (never evaluated).
|
||||
//! - [`devmode`]: developer mode's debounced watcher of plugins, custom CSS and a theme file.
|
||||
//! - [`alerts`]: local keyword alerts (keywords, snippets, per-item/per-keyword rate limits).
|
||||
//! - [`media`]: gallery folders (path containment) and the opt-in clipboard history (private copies skipped).
|
||||
//! - [`store`]: installing themes and plugins from `waybetter://install` links, dropped files and the
|
||||
//! signed multi-app wayBetter Store (allow-list, caps, catalog signatures, staging, install records);
|
||||
//! downloads with the `net` feature.
|
||||
|
|
@ -33,6 +34,7 @@ pub mod devmode;
|
|||
pub mod hotfix;
|
||||
pub mod i18n;
|
||||
pub mod layout;
|
||||
pub mod media;
|
||||
pub mod plugins;
|
||||
pub mod policy;
|
||||
pub mod profiles;
|
||||
|
|
|
|||
438
crates/waybetter-host/src/media.rs
Normal file
438
crates/waybetter-host/src/media.rs
Normal file
|
|
@ -0,0 +1,438 @@
|
|||
//! Gallery folders and the local clipboard history for a shell "Media" side panel (attaching an
|
||||
//! image to the site's composer is the app's own script). Pure and headless-tested: settings
|
||||
//! validation, listing images only inside owner-chosen folders, path containment, the bounded
|
||||
//! clipboard history and its files, PNG encoding. With the `tauri` feature, [`clipboard`] reads the
|
||||
//! OS clipboard (opt-in, skipping copies password managers mark private). Nothing here posts anything.
|
||||
|
||||
use base64::Engine;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[cfg(feature = "tauri")]
|
||||
pub mod clipboard;
|
||||
|
||||
pub const MAX_FOLDERS: usize = 16;
|
||||
/// Recent images returned to the panel.
|
||||
pub const MAX_LISTED: usize = 120;
|
||||
/// Largest file the panel will preview or attach (X accepts up to 15 MB GIFs).
|
||||
pub const MAX_IMAGE_BYTES: u64 = 16 * 1024 * 1024;
|
||||
pub const MAX_CLIP_ITEMS: usize = 100;
|
||||
pub const DEFAULT_CLIP_ITEMS: usize = 30;
|
||||
pub const MAX_CLIP_TEXT_BYTES: usize = 65_536;
|
||||
/// The clipboard history index inside the app's clipboard folder (image items are `<id>.png` next to it).
|
||||
pub const CLIP_INDEX: &str = "history.json";
|
||||
|
||||
const IMAGE_EXTENSIONS: [&str; 5] = ["png", "jpg", "jpeg", "gif", "webp"];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct MediaSettings {
|
||||
/// Absolute folders the owner picked through the native folder dialog.
|
||||
pub folders: Vec<String>,
|
||||
/// Clipboard history is opt-in: nothing is read from the clipboard while this is false.
|
||||
pub clipboard_enabled: bool,
|
||||
pub clipboard_max: usize,
|
||||
}
|
||||
|
||||
impl Default for MediaSettings {
|
||||
fn default() -> Self {
|
||||
Self { folders: Vec::new(), clipboard_enabled: false, clipboard_max: DEFAULT_CLIP_ITEMS }
|
||||
}
|
||||
}
|
||||
|
||||
impl MediaSettings {
|
||||
/// Keeps only existing absolute directories (deduplicated), and bounds the history size.
|
||||
/// Folders are never added here from arbitrary input by callers other than the native dialog;
|
||||
/// validation still refuses relative paths so a shell bug cannot widen the scope silently.
|
||||
pub fn validated(mut self) -> Result<Self, String> {
|
||||
if self.folders.len() > MAX_FOLDERS {
|
||||
return Err(format!("VALIDATION: at most {MAX_FOLDERS} gallery folders"));
|
||||
}
|
||||
let mut folders: Vec<String> = Vec::new();
|
||||
for folder in &self.folders {
|
||||
let path = Path::new(folder);
|
||||
if !path.is_absolute() {
|
||||
return Err("VALIDATION: gallery folders must be absolute".into());
|
||||
}
|
||||
if !folders.iter().any(|f| same_path(f, folder)) {
|
||||
folders.push(folder.clone());
|
||||
}
|
||||
}
|
||||
self.folders = folders;
|
||||
if self.clipboard_max == 0 || self.clipboard_max > MAX_CLIP_ITEMS {
|
||||
return Err(format!("VALIDATION: clipboard history must keep 1-{MAX_CLIP_ITEMS} items"));
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Adds a folder (from the native dialog). Returns false when it was already present.
|
||||
pub fn add_folder(&mut self, folder: &Path) -> Result<bool, String> {
|
||||
if !folder.is_absolute() || !folder.is_dir() {
|
||||
return Err("VALIDATION: not a folder".into());
|
||||
}
|
||||
let text = folder.to_string_lossy().into_owned();
|
||||
if self.folders.iter().any(|f| same_path(f, &text)) {
|
||||
return Ok(false);
|
||||
}
|
||||
if self.folders.len() >= MAX_FOLDERS {
|
||||
return Err(format!("VALIDATION: at most {MAX_FOLDERS} gallery folders"));
|
||||
}
|
||||
self.folders.push(text);
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
fn same_path(a: &str, b: &str) -> bool {
|
||||
match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
|
||||
(Ok(a), Ok(b)) => a == b,
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_image_name(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.map(|ext| IMAGE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn mime_for(path: &Path) -> &'static str {
|
||||
match path.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase()).as_deref() {
|
||||
Some("png") => "image/png",
|
||||
Some("jpg" | "jpeg") => "image/jpeg",
|
||||
Some("gif") => "image/gif",
|
||||
Some("webp") => "image/webp",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ImageEntry {
|
||||
pub path: String,
|
||||
pub name: String,
|
||||
pub folder: String,
|
||||
pub modified_ms: i64,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
/// Newest images directly inside the chosen folders (not recursive, symlinks not followed out).
|
||||
pub fn list_recent(folders: &[String], limit: usize) -> Vec<ImageEntry> {
|
||||
let mut out = Vec::new();
|
||||
for folder in folders {
|
||||
let Ok(root) = std::fs::canonicalize(folder) else { continue };
|
||||
let Ok(entries) = std::fs::read_dir(&root) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if !is_image_name(&path) {
|
||||
continue;
|
||||
}
|
||||
// Resolve links and require the target to stay inside the folder.
|
||||
let Ok(real) = std::fs::canonicalize(&path) else { continue };
|
||||
if !real.starts_with(&root) {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = std::fs::metadata(&real) else { continue };
|
||||
if !meta.is_file() || meta.len() == 0 || meta.len() > MAX_IMAGE_BYTES {
|
||||
continue;
|
||||
}
|
||||
let modified_ms = meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or(0);
|
||||
out.push(ImageEntry {
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
name: entry.file_name().to_string_lossy().into_owned(),
|
||||
folder: folder.clone(),
|
||||
modified_ms,
|
||||
size: meta.len(),
|
||||
});
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| b.modified_ms.cmp(&a.modified_ms).then_with(|| a.path.cmp(&b.path)));
|
||||
out.truncate(limit.min(MAX_LISTED));
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolves `requested` and accepts it only when it is an image file inside one of `folders`.
|
||||
/// This is the only way a gallery path from the shell reaches a file read.
|
||||
pub fn resolve_in_folders(folders: &[String], requested: &str) -> Result<PathBuf, String> {
|
||||
let deny = || "FORBIDDEN: file is outside the gallery folders".to_string();
|
||||
let path = Path::new(requested);
|
||||
if !path.is_absolute() || !is_image_name(path) {
|
||||
return Err(deny());
|
||||
}
|
||||
let real = std::fs::canonicalize(path).map_err(|_| deny())?;
|
||||
let parent = real.parent().ok_or_else(deny)?;
|
||||
let inside = folders
|
||||
.iter()
|
||||
.filter_map(|f| std::fs::canonicalize(f).ok())
|
||||
.any(|root| parent == root);
|
||||
if !inside || !is_image_name(&real) {
|
||||
return Err(deny());
|
||||
}
|
||||
let meta = std::fs::metadata(&real).map_err(|_| deny())?;
|
||||
if !meta.is_file() || meta.len() == 0 || meta.len() > MAX_IMAGE_BYTES {
|
||||
return Err("VALIDATION: image must be 1 byte to 16 MB".into());
|
||||
}
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
pub fn data_url(mime: &str, bytes: &[u8]) -> String {
|
||||
format!("data:{mime};base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Clipboard history
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClipItem {
|
||||
pub id: String,
|
||||
/// "text" or "image".
|
||||
pub kind: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub text: Option<String>,
|
||||
/// PNG file name inside the clipboard folder (image items only).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub file: Option<String>,
|
||||
pub hash: String,
|
||||
pub at: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ClipHistory {
|
||||
pub items: Vec<ClipItem>,
|
||||
}
|
||||
|
||||
pub fn content_hash(kind: &str, bytes: &[u8]) -> String {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
kind.hash(&mut hasher);
|
||||
bytes.hash(&mut hasher);
|
||||
format!("{:016x}", hasher.finish())
|
||||
}
|
||||
|
||||
pub fn valid_clip_id(id: &str) -> bool {
|
||||
id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
impl ClipHistory {
|
||||
/// Drops malformed entries (e.g. a hand-edited file naming another path).
|
||||
pub fn sanitized(mut self) -> Self {
|
||||
self.items.retain(|item| {
|
||||
valid_clip_id(&item.id)
|
||||
&& match item.kind.as_str() {
|
||||
"text" => item.text.as_ref().is_some_and(|t| !t.is_empty() && t.len() <= MAX_CLIP_TEXT_BYTES),
|
||||
"image" => item.file.as_deref() == Some(format!("{}.png", item.id).as_str()),
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
/// Puts `item` first. A repeat of existing content moves that entry to the front instead of
|
||||
/// duplicating it. Returns items evicted beyond `max` (their image files must be deleted).
|
||||
pub fn push(&mut self, item: ClipItem, max: usize) -> Vec<ClipItem> {
|
||||
let mut evicted = Vec::new();
|
||||
if let Some(index) = self.items.iter().position(|i| i.hash == item.hash) {
|
||||
let mut existing = self.items.remove(index);
|
||||
existing.at = item.at;
|
||||
self.items.insert(0, existing);
|
||||
// The new item's own image file (if any) is redundant.
|
||||
if item.file.is_some() {
|
||||
evicted.push(item);
|
||||
}
|
||||
} else {
|
||||
self.items.insert(0, item);
|
||||
}
|
||||
evicted.extend(self.trim(max));
|
||||
evicted
|
||||
}
|
||||
|
||||
pub fn trim(&mut self, max: usize) -> Vec<ClipItem> {
|
||||
let keep = max.clamp(1, MAX_CLIP_ITEMS);
|
||||
if self.items.len() > keep {
|
||||
self.items.split_off(keep)
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, id: &str) -> Option<ClipItem> {
|
||||
let index = self.items.iter().position(|i| i.id == id)?;
|
||||
Some(self.items.remove(index))
|
||||
}
|
||||
|
||||
pub fn has_hash(&self, hash: &str) -> bool {
|
||||
self.items.iter().any(|i| i.hash == hash)
|
||||
}
|
||||
}
|
||||
|
||||
/// The history kept in clipboard folder `dir` (malformed entries dropped); empty when missing.
|
||||
pub fn load_history(dir: &Path) -> ClipHistory {
|
||||
std::fs::read_to_string(dir.join(CLIP_INDEX))
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<ClipHistory>(&text).ok())
|
||||
.map(ClipHistory::sanitized)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn save_history(dir: &Path, history: &ClipHistory) -> Result<(), String> {
|
||||
std::fs::create_dir_all(dir).map_err(|error| format!("STORAGE: {error}"))?;
|
||||
let json = serde_json::to_string(history).map_err(|_| "STORAGE: serialization failed")?;
|
||||
std::fs::write(dir.join(CLIP_INDEX), json).map_err(|error| format!("STORAGE: {error}"))
|
||||
}
|
||||
|
||||
/// Deletes the image files of `items` (evicted or removed entries) from clipboard folder `dir`.
|
||||
pub fn delete_files(dir: &Path, items: &[ClipItem]) {
|
||||
for item in items {
|
||||
if let Some(file) = &item.file {
|
||||
let _ = std::fs::remove_file(dir.join(file));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes raw RGBA pixels (as the OS clipboard hands them over) as a PNG.
|
||||
pub fn encode_png(width: usize, height: usize, rgba: Vec<u8>) -> Option<Vec<u8>> {
|
||||
let image = image::RgbaImage::from_raw(u32::try_from(width).ok()?, u32::try_from(height).ok()?, rgba)?;
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
image.write_to(&mut out, image::ImageFormat::Png).ok()?;
|
||||
Some(out.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn clip(id: char, hash: &str, image: bool) -> ClipItem {
|
||||
let id: String = std::iter::repeat(id).take(32).collect();
|
||||
ClipItem {
|
||||
file: image.then(|| format!("{id}.png")),
|
||||
text: (!image).then(|| "hello".into()),
|
||||
kind: if image { "image" } else { "text" }.into(),
|
||||
id,
|
||||
hash: hash.into(),
|
||||
at: 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_defaults_are_opt_in() {
|
||||
let settings = MediaSettings::default();
|
||||
assert!(!settings.clipboard_enabled);
|
||||
assert!(settings.folders.is_empty());
|
||||
assert!(settings.validated().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_reject_relative_folders_and_bad_sizes() {
|
||||
let bad = MediaSettings { folders: vec!["relative/dir".into()], ..Default::default() };
|
||||
assert!(bad.validated().is_err());
|
||||
let bad = MediaSettings { clipboard_max: 0, ..Default::default() };
|
||||
assert!(bad.validated().is_err());
|
||||
let bad = MediaSettings { clipboard_max: MAX_CLIP_ITEMS + 1, ..Default::default() };
|
||||
assert!(bad.validated().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_and_resolving_stay_inside_folders() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let gallery = root.path().join("gallery");
|
||||
let outside = root.path().join("outside");
|
||||
std::fs::create_dir_all(gallery.join("nested")).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(gallery.join("a.png"), b"png").unwrap();
|
||||
std::fs::write(gallery.join("notes.txt"), b"txt").unwrap();
|
||||
std::fs::write(gallery.join("empty.jpg"), b"").unwrap();
|
||||
std::fs::write(gallery.join("nested").join("deep.png"), b"png").unwrap();
|
||||
std::fs::write(outside.join("secret.png"), b"png").unwrap();
|
||||
let folders = vec![gallery.to_string_lossy().into_owned()];
|
||||
|
||||
let listed = list_recent(&folders, 50);
|
||||
assert_eq!(listed.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), vec!["a.png"]);
|
||||
|
||||
assert!(resolve_in_folders(&folders, &gallery.join("a.png").to_string_lossy()).is_ok());
|
||||
for denied in [
|
||||
outside.join("secret.png"),
|
||||
gallery.join("..").join("outside").join("secret.png"),
|
||||
gallery.join("nested").join("deep.png"),
|
||||
gallery.join("notes.txt"),
|
||||
gallery.join("missing.png"),
|
||||
] {
|
||||
assert!(resolve_in_folders(&folders, &denied.to_string_lossy()).is_err(), "{}", denied.display());
|
||||
}
|
||||
assert!(resolve_in_folders(&folders, "a.png").is_err());
|
||||
assert!(resolve_in_folders(&[], &gallery.join("a.png").to_string_lossy()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_folder_dedupes_and_requires_dirs() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let mut settings = MediaSettings::default();
|
||||
assert!(settings.add_folder(root.path()).unwrap());
|
||||
assert!(!settings.add_folder(root.path()).unwrap());
|
||||
assert!(settings.add_folder(&root.path().join("missing")).is_err());
|
||||
assert_eq!(settings.folders.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_dedupes_moves_to_front_and_trims() {
|
||||
let mut history = ClipHistory::default();
|
||||
assert!(history.push(clip('a', "h1", false), 2).is_empty());
|
||||
assert!(history.push(clip('b', "h2", true), 2).is_empty());
|
||||
// Same content again: no duplicate; the redundant new image file is reported for cleanup.
|
||||
let evicted = history.push(clip('c', "h2", true), 2);
|
||||
assert_eq!(evicted.len(), 1);
|
||||
assert_eq!(history.items.len(), 2);
|
||||
assert_eq!(history.items[0].hash, "h2");
|
||||
let evicted = history.push(clip('d', "h3", false), 2);
|
||||
assert_eq!(evicted.iter().map(|i| i.hash.as_str()).collect::<Vec<_>>(), vec!["h1"]);
|
||||
assert_eq!(history.items.iter().map(|i| i.hash.as_str()).collect::<Vec<_>>(), vec!["h3", "h2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_sanitize_drops_foreign_files() {
|
||||
let mut bad = clip('e', "h", true);
|
||||
bad.file = Some("../../secret.png".into());
|
||||
let history = ClipHistory { items: vec![bad, clip('f', "h2", true), clip('0', "h3", false)] }.sanitized();
|
||||
assert_eq!(history.items.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mime_and_extension() {
|
||||
assert_eq!(mime_for(Path::new("A.JPG")), "image/jpeg");
|
||||
assert!(is_image_name(Path::new("x.webp")));
|
||||
assert!(!is_image_name(Path::new("x.svg")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_files_round_trip_and_eviction_deletes_images() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let dir = root.path().join("clipboard");
|
||||
assert!(load_history(&dir).items.is_empty(), "missing folder: empty history");
|
||||
let image = clip('a', "h1", true);
|
||||
let history = ClipHistory { items: vec![image.clone(), clip('b', "h2", false)] };
|
||||
save_history(&dir, &history).unwrap();
|
||||
assert_eq!(load_history(&dir), history);
|
||||
std::fs::write(dir.join(image.file.as_ref().unwrap()), b"png").unwrap();
|
||||
delete_files(&dir, &[image.clone()]);
|
||||
assert!(!dir.join(image.file.unwrap()).exists());
|
||||
std::fs::write(dir.join(CLIP_INDEX), "{not json").unwrap();
|
||||
assert!(load_history(&dir).items.is_empty(), "a damaged index is an empty history");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_encoding_checks_dimensions() {
|
||||
let png = encode_png(2, 1, vec![255, 0, 0, 255, 0, 255, 0, 255]).unwrap();
|
||||
assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
|
||||
assert!(encode_png(2, 2, vec![0; 4]).is_none(), "too few pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_urls_are_base64() {
|
||||
assert_eq!(data_url("image/png", b"PNG"), "data:image/png;base64,UE5H");
|
||||
}
|
||||
}
|
||||
108
crates/waybetter-host/src/media/clipboard.rs
Normal file
108
crates/waybetter-host/src/media/clipboard.rs
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
//! The OS clipboard for the opt-in clipboard history (`tauri` feature): reading text or an image,
|
||||
//! skipping copies that password managers and similar apps mark as private, and the polling loop.
|
||||
//! Nothing is read while the owner's opt-in is off, and the OS clipboard handle is released then.
|
||||
|
||||
use super::{content_hash, MAX_CLIP_TEXT_BYTES};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Raw RGBA larger than this (e.g. a 4K screenshot is ~33 MB) is skipped.
|
||||
pub const MAX_CLIP_RGBA_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
/// A new copy: text, or an image as raw RGBA (`hash`, width, height, pixels).
|
||||
pub enum Seen {
|
||||
Text(String, String),
|
||||
Image(String, usize, usize, Vec<u8>),
|
||||
}
|
||||
|
||||
impl Seen {
|
||||
pub fn hash(&self) -> &str {
|
||||
match self {
|
||||
Seen::Text(hash, _) | Seen::Image(hash, ..) => hash,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read(clipboard: &mut arboard::Clipboard) -> Option<Seen> {
|
||||
if let Ok(text) = clipboard.get_text() {
|
||||
if !text.trim().is_empty() && text.len() <= MAX_CLIP_TEXT_BYTES {
|
||||
return Some(Seen::Text(content_hash("text", text.as_bytes()), text));
|
||||
}
|
||||
}
|
||||
let image = clipboard.get_image().ok()?;
|
||||
if image.bytes.is_empty() || image.bytes.len() > MAX_CLIP_RGBA_BYTES {
|
||||
return None;
|
||||
}
|
||||
Some(Seen::Image(content_hash("image", &image.bytes), image.width, image.height, image.bytes.into_owned()))
|
||||
}
|
||||
|
||||
/// Windows clipboard change counter: lets the poll skip reading (and hashing a possibly large
|
||||
/// image) every time when nothing was copied. `None` elsewhere, so every poll reads.
|
||||
#[cfg(windows)]
|
||||
fn change_marker() -> Option<u32> {
|
||||
clipboard_win::raw::seq_num().map(|n| n.get())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
fn change_marker() -> Option<u32> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Password managers and other apps mark secret copies with these registered formats; clipboard
|
||||
/// monitors (like Windows' own clipboard history) must not record them.
|
||||
#[cfg(windows)]
|
||||
pub fn marked_private() -> bool {
|
||||
["ExcludeClipboardContentFromMonitorProcessing", "Clipboard Viewer Ignore"].iter().any(|name| {
|
||||
clipboard_win::raw::register_format(name).is_some_and(|format| clipboard_win::raw::is_format_avail(format.get()))
|
||||
})
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
pub fn marked_private() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Polls the clipboard every `poll` forever (run it on its own thread). `enabled` is the owner's
|
||||
/// opt-in, asked every round; `on_copy` gets each new copy. Recording starts with the next copy
|
||||
/// after the opt-in, never with whatever was on the clipboard before, and a private copy is never
|
||||
/// read.
|
||||
pub fn watch(poll: Duration, enabled: impl Fn() -> bool, mut on_copy: impl FnMut(Seen)) {
|
||||
let mut clipboard: Option<arboard::Clipboard> = None;
|
||||
let mut last: Option<String> = None;
|
||||
let mut last_marker: Option<u32> = None;
|
||||
let mut was_enabled = false;
|
||||
loop {
|
||||
std::thread::sleep(poll);
|
||||
if !enabled() {
|
||||
// Release the OS clipboard handle entirely while the feature is off.
|
||||
clipboard = None;
|
||||
was_enabled = false;
|
||||
last_marker = None;
|
||||
continue;
|
||||
}
|
||||
let marker = change_marker();
|
||||
if marker.is_some() && marker == last_marker {
|
||||
continue;
|
||||
}
|
||||
last_marker = marker;
|
||||
if marked_private() {
|
||||
// Never read a secret copy; also arm the opt-in so it is not recorded later.
|
||||
was_enabled = true;
|
||||
continue;
|
||||
}
|
||||
if clipboard.is_none() {
|
||||
clipboard = arboard::Clipboard::new().ok();
|
||||
}
|
||||
let Some(board) = clipboard.as_mut() else { continue };
|
||||
let Some(seen) = read(board) else { continue };
|
||||
let hash = seen.hash().to_string();
|
||||
// Opt-in starts recording from the next copy, not whatever was on the clipboard before.
|
||||
if !was_enabled {
|
||||
was_enabled = true;
|
||||
last = Some(hash);
|
||||
continue;
|
||||
}
|
||||
if last.as_deref() == Some(hash.as_str()) {
|
||||
continue;
|
||||
}
|
||||
last = Some(hash);
|
||||
on_copy(seen);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue