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:
CRTkafa 2026-09-29 11:13:01 +07:00
parent 3c238d9e2d
commit caef87775f
5 changed files with 721 additions and 1 deletions

View 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");
}
}