From fea1d3f52699f6942190ccfda7cbfb6ce4c78fd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 10:10:59 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20viewer,=20thumbnails=20work?= =?UTF-8?q?er,=20full=20sweeper;=20byte=20responses=20keep=20their=20own?= =?UTF-8?q?=20CSP=20and=20allow=20same-origin=20framing,=20PDFs=20unsandbo?= =?UTF-8?q?xed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 165 ++++++++++++++ Cargo.toml | 1 + crates/in-core/Cargo.toml | 1 + crates/in-core/src/lib.rs | 1 + crates/in-core/src/store/files.rs | 76 ++++++- crates/in-core/src/store/members.rs | 50 ++++- crates/in-core/src/thumbs.rs | 119 ++++++++++ crates/in-web/assets/viewer.js | 31 +++ crates/in-web/build.rs | 4 +- crates/in-web/src/api/upload.rs | 7 + crates/in-web/src/assets.rs | 15 ++ crates/in-web/src/boot.rs | 2 + crates/in-web/src/i18n/drive.rs | 20 +- crates/in-web/src/main.rs | 1 + crates/in-web/src/pages/drive.rs | 6 +- crates/in-web/src/pages/mod.rs | 1 + crates/in-web/src/pages/thumbs.rs | 90 ++++++++ crates/in-web/src/pages/view.rs | 329 ++++++++++++++++++++++++++-- crates/in-web/src/security.rs | 21 +- crates/in-web/src/serve_bytes.rs | 27 ++- crates/in-web/src/sweeper.rs | 244 ++++++++++++++++++++- crates/in-web/src/thumbs_worker.rs | 180 +++++++++++++++ crates/in-web/src/views/drive.rs | 28 ++- crates/in-web/src/views/mod.rs | 3 +- style/_components.scss | 85 +++++++ 25 files changed, 1447 insertions(+), 60 deletions(-) create mode 100644 crates/in-core/src/thumbs.rs create mode 100644 crates/in-web/assets/viewer.js create mode 100644 crates/in-web/src/pages/thumbs.rs create mode 100644 crates/in-web/src/thumbs_worker.rs diff --git a/Cargo.lock b/Cargo.lock index e1eba03..5040c46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aead" version = "0.5.2" @@ -448,6 +454,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" @@ -617,6 +629,12 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24" +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + [[package]] name = "colorchoice" version = "1.0.5" @@ -1152,6 +1170,15 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + [[package]] name = "ff" version = "0.13.1" @@ -1174,6 +1201,17 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + [[package]] name = "fnv" version = "1.0.7" @@ -1370,6 +1408,16 @@ dependencies = [ "polyval", ] +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + [[package]] name = "glob" version = "0.3.4" @@ -1856,6 +1904,34 @@ 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", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + [[package]] name = "in-core" version = "0.1.0" @@ -1868,6 +1944,7 @@ dependencies = [ "futures-util", "hex", "hmac 0.13.0", + "image", "ipnet", "object_store", "rand 0.10.3", @@ -2374,6 +2451,26 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.4" @@ -2385,6 +2482,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 = "multer" version = "3.1.0" @@ -2784,6 +2891,19 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "polling" version = "3.11.0" @@ -2916,6 +3036,18 @@ dependencies = [ "syn 2.0.119", ] +[[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.41.0" @@ -3694,6 +3826,12 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -5201,6 +5339,12 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + [[package]] name = "which" version = "4.4.2" @@ -5549,6 +5693,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" @@ -5582,3 +5732,18 @@ dependencies = [ "cc", "pkg-config", ] + +[[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", +] diff --git a/Cargo.toml b/Cargo.toml index 0391c33..3c81460 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,6 +53,7 @@ hmac = "0.13.0" http = "1.5.0" http-body = "1.1.0" http-body-util = "0.1.5" +image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "gif", "webp"] } in-core = { path = "crates/in-core" } ipnet = "2.12.2" jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto"] } diff --git a/crates/in-core/Cargo.toml b/crates/in-core/Cargo.toml index 07ad69b..5b54387 100644 --- a/crates/in-core/Cargo.toml +++ b/crates/in-core/Cargo.toml @@ -13,6 +13,7 @@ base64.workspace = true bytes.workspace = true chacha20poly1305.workspace = true futures-util.workspace = true +image.workspace = true hex.workspace = true hmac.workspace = true ipnet.workspace = true diff --git a/crates/in-core/src/lib.rs b/crates/in-core/src/lib.rs index 5d63e90..bdf733a 100644 --- a/crates/in-core/src/lib.rs +++ b/crates/in-core/src/lib.rs @@ -13,5 +13,6 @@ pub mod secret; pub mod sniff; pub mod staging; pub mod store; +pub mod thumbs; pub mod time; pub mod token; diff --git a/crates/in-core/src/store/files.rs b/crates/in-core/src/store/files.rs index 5274db0..98230d5 100644 --- a/crates/in-core/src/store/files.rs +++ b/crates/in-core/src/store/files.rs @@ -82,9 +82,18 @@ pub fn files_blob_key(id: &str) -> String { format!("files/{}/{id}", &id[..2]) } -/// The blob key of a file's thumbnail: `thumbs//.webp`. +/// The blob key of a file's thumbnail: `thumbs/`. The key is flat, so one purge deletes it by id. pub fn thumb_blob_key(id: &str) -> String { - format!("thumbs/{}/{id}.webp", &id[..2]) + format!("thumbs/{id}") +} + +/// The thumbnail state a new file starts in. Only the picture types the thumbnail decoder reads are +/// `pending`; every other type is `none` and never gets a thumbnail. +pub fn thumb_state_for(mime: &str) -> &'static str { + match mime { + "image/png" | "image/jpeg" | "image/webp" | "image/gif" => "pending", + _ => "none", + } } /// Maps a row selected with [`FILE_COLS`]. @@ -177,8 +186,8 @@ pub(crate) async fn insert_file_in(conn: &Connection, new: NewFile) -> Result Result Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {FILE_COLS} FROM files WHERE thumb_state = 'pending' \ + ORDER BY created_at, id LIMIT ?1" + ), + (limit.max(1) as i64,), + map_file, + ) + .await + } + + /// Sets the thumbnail state of a file to `ready` or `failed`. Returns `false` when the file has no row + /// (it was purged while its thumbnail was made), so the caller can remove the bytes it stored. + pub async fn set_thumb_state(&self, id: &str, state: &str) -> Result { + if state != "ready" && state != "failed" { + return Err(Error::Invalid("bad_thumb_state".into())); + } + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE files SET thumb_state = ?2 WHERE id = ?1", + (id.to_string(), state.to_string()), + ) + .await + .map_err(db_err)?; + Ok(changed > 0) + } + + /// Every blob key that a row names: the bytes of each file, the thumbnail of each file, and the bytes of + /// each object. The sweeper keeps these and removes any other blob that is old enough. + pub async fn referenced_blob_keys(&self) -> Result> { + let conn = self.read_conn().await; + let mut keys = fetch_all(&conn, "SELECT id, blob_key FROM files", (), |row| { + Ok((col_text(row, 0)?, col_text(row, 1)?)) + }) + .await? + .into_iter() + .flat_map(|(id, blob_key)| [blob_key, thumb_blob_key(&id)]) + .collect::>(); + keys.extend( + fetch_all(&conn, "SELECT blob_key FROM objects", (), |row| { + col_text(row, 0) + }) + .await?, + ); + Ok(keys) + } + /// Counts one forced download of a file. The caller counts only a download that starts at byte 0. pub async fn record_download(&self, id: &str) -> Result<()> { let conn = self.inner.conn.lock().await; @@ -321,9 +383,11 @@ mod tests { use super::*; #[test] - fn blob_keys_follow_the_id_prefix_layout() { + fn blob_keys_follow_the_id_layout() { assert_eq!(files_blob_key("01abcdef"), "files/01/01abcdef"); - assert_eq!(thumb_blob_key("01abcdef"), "thumbs/01/01abcdef.webp"); + assert_eq!(thumb_blob_key("01abcdef"), "thumbs/01abcdef"); + assert_eq!(thumb_state_for("image/png"), "pending"); + assert_eq!(thumb_state_for("application/pdf"), "none"); } #[test] diff --git a/crates/in-core/src/store/members.rs b/crates/in-core/src/store/members.rs index 64dc39e..88bd69c 100644 --- a/crates/in-core/src/store/members.rs +++ b/crates/in-core/src/store/members.rs @@ -6,7 +6,7 @@ use turso::Row; use crate::error::{Error, Result}; -use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt}; +use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish}; use crate::time::now_stamp; /// Column list for [`map_member`]. Keep the two in step. @@ -74,6 +74,17 @@ pub struct MemberFields { } /// Maps a row selected with [`MEMBER_COLS`]. +/// A member whose stored `used_bytes` disagreed with the sum of their files. `actual` is the value written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QuotaDrift { + /// The member. + pub sub: String, + /// The value the row held before the check. + pub stored: i64, + /// The sum of the member's file sizes, now the stored value. + pub actual: i64, +} + pub fn map_member(row: &Row) -> Result { Ok(Member { sub: col_text(row, 0)?, @@ -250,6 +261,43 @@ impl Store { Ok(()) } + /// Recomputes every member's `used_bytes` from their files and writes back the ones that differ, in one + /// transaction. Returns each corrected member with the stored and the recomputed value, so the caller + /// can log the drift. Trashed files count, as they do in the quota rule. + pub async fn reconcile_quota(&self) -> Result> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result> = async { + let drift = fetch_all( + &tx, + "SELECT m.sub, m.used_bytes, \ + (SELECT COALESCE(SUM(f.size), 0) FROM files f WHERE f.owner = m.sub) \ + FROM members m \ + WHERE m.used_bytes <> (SELECT COALESCE(SUM(f.size), 0) FROM files f WHERE f.owner = m.sub)", + (), + |row| { + Ok(QuotaDrift { + sub: col_text(row, 0)?, + stored: col_int(row, 1)?, + actual: col_int(row, 2)?, + }) + }, + ) + .await?; + for item in &drift { + tx.execute( + "UPDATE members SET used_bytes = ?2 WHERE sub = ?1", + (item.sub.clone(), item.actual), + ) + .await + .map_err(db_err)?; + } + Ok(drift) + } + .await; + finish(tx, outcome).await + } + /// Sets a member's theme. Only `system`, `light` and `dark` are accepted. pub async fn set_theme(&self, sub: &str, theme: &str) -> Result<()> { if !THEMES.contains(&theme) { diff --git a/crates/in-core/src/thumbs.rs b/crates/in-core/src/thumbs.rs new file mode 100644 index 0000000..c3b7654 --- /dev/null +++ b/crates/in-core/src/thumbs.rs @@ -0,0 +1,119 @@ +//! Thumbnails of pictures: decode a PNG, JPEG, WebP or GIF and write a small lossless WebP no wider or taller +//! than [`THUMB_EDGE`]. It is pure: bytes in, bytes out, no file access and no external program. +//! +//! The decoder runs under hard limits. A picture that claims more than [`MAX_DIMENSION`] pixels on a side, or +//! would need more than [`MAX_ALLOC_BYTES`] to decode, is refused from its header, before any large buffer is +//! allocated. A refused picture is `Invalid("bad_image")`; the thumbnail worker marks such a file `failed`. + +use std::io::Cursor; + +use image::{ImageFormat, ImageReader, Limits}; + +use crate::error::{Error, Result}; + +/// Longest edge of a thumbnail, in pixels. The aspect ratio is kept. +pub const THUMB_EDGE: u32 = 320; + +/// Largest source picture the worker reads, in bytes. Larger files get no thumbnail. +pub const MAX_SOURCE_BYTES: u64 = 64 * 1024 * 1024; + +/// Largest width or height the decoder accepts, in pixels: 10000 by 10000 is 100 megapixels. +pub const MAX_DIMENSION: u32 = 10_000; + +/// Most memory the decoder may allocate for one picture: 256 MiB. +pub const MAX_ALLOC_BYTES: u64 = 256 * 1024 * 1024; + +/// The formats that get thumbnails. Anything else is not decoded. +const FORMATS: [ImageFormat; 4] = [ + ImageFormat::Png, + ImageFormat::Jpeg, + ImageFormat::WebP, + ImageFormat::Gif, +]; + +/// Decodes `source` under the limits and returns a WebP thumbnail of it. +/// +/// The format is found from the leading bytes, never from a file name, and must be one of [`FORMATS`]. Any +/// decoder error, including a limit, is `Invalid("bad_image")`. Nothing here panics on hostile input. +pub fn make_thumbnail(source: &[u8]) -> Result> { + let bad = || Error::Invalid("bad_image".into()); + let mut reader = ImageReader::new(Cursor::new(source)) + .with_guessed_format() + .map_err(|_| bad())?; + if !reader.format().is_some_and(|f| FORMATS.contains(&f)) { + return Err(bad()); + } + let mut limits = Limits::default(); + limits.max_image_width = Some(MAX_DIMENSION); + limits.max_image_height = Some(MAX_DIMENSION); + limits.max_alloc = Some(MAX_ALLOC_BYTES); + reader.limits(limits); + let picture = reader.decode().map_err(|_| bad())?; + let thumb = picture.thumbnail(THUMB_EDGE, THUMB_EDGE); + let mut out = Cursor::new(Vec::new()); + thumb + .write_to(&mut out, ImageFormat::WebP) + .map_err(|_| bad())?; + Ok(out.into_inner()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A 4x2 PNG made by the encoder, the source of the tests below. + fn small_png() -> Vec { + let img = image::RgbaImage::from_pixel(4, 2, image::Rgba([200, 30, 30, 255])); + let mut out = Cursor::new(Vec::new()); + img.write_to(&mut out, ImageFormat::Png).unwrap(); + out.into_inner() + } + + /// CRC-32 (the PNG chunk checksum), bit by bit. Only the tests use it. + fn crc32(bytes: &[u8]) -> u32 { + let mut crc = !0u32; + for &byte in bytes { + crc ^= u32::from(byte); + for _ in 0..8 { + crc = if crc & 1 == 1 { + (crc >> 1) ^ 0xEDB8_8320 + } else { + crc >> 1 + }; + } + } + !crc + } + + #[test] + fn a_small_png_becomes_a_webp_thumbnail() { + let thumb = make_thumbnail(&small_png()).unwrap(); + assert_eq!(&thumb[..4], b"RIFF"); + assert_eq!(&thumb[8..12], b"WEBP"); + assert!(image::load_from_memory(&thumb).is_ok()); + } + + /// A PNG whose header claims 100000 by 100000 pixels. Its IHDR checksum is fixed up so that only the + /// dimension limit can refuse it. It must fail cleanly, without a panic or a huge allocation. + #[test] + fn a_decompression_bomb_png_is_refused_without_a_panic() { + let mut png = small_png(); + // The IHDR chunk starts at byte 8: length (4), type (4), then width and height (4 each). + assert_eq!(&png[12..16], b"IHDR"); + png[16..20].copy_from_slice(&100_000u32.to_be_bytes()); + png[20..24].copy_from_slice(&100_000u32.to_be_bytes()); + let crc = crc32(&png[12..29]); + png[29..33].copy_from_slice(&crc.to_be_bytes()); + let result = make_thumbnail(&png); + assert!( + matches!(result, Err(Error::Invalid(ref m)) if m == "bad_image"), + "a bomb must be refused: {result:?}" + ); + } + + #[test] + fn non_pictures_are_refused() { + assert!(make_thumbnail(b"plain text, not a picture").is_err()); + assert!(make_thumbnail(b"").is_err()); + } +} diff --git a/crates/in-web/assets/viewer.js b/crates/in-web/assets/viewer.js new file mode 100644 index 0000000..82d9bc1 --- /dev/null +++ b/crates/in-web/assets/viewer.js @@ -0,0 +1,31 @@ +/** + * viewer.js: the keyboard steps of the file viewer. Left goes to the previous file of the folder and right + * to the next one. It follows the same links a mouse would (`a[data-nav]`), so soft navigation handles them. + * It does nothing while a form field has the focus, while a modifier key is held, or on a page without those + * links. + */ +(function () { + "use strict"; + + document.addEventListener("keydown", function (event) { + if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { + return; + } + if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") { + return; + } + var target = event.target; + if (target instanceof HTMLElement && + (target.isContentEditable || /^(input|textarea|select)$/i.test(target.tagName))) { + return; + } + var link = document.querySelector( + event.key === "ArrowLeft" ? 'a[data-nav="prev"]' : 'a[data-nav="next"]' + ); + if (!link) { + return; + } + event.preventDefault(); + link.click(); + }); +})(); diff --git a/crates/in-web/build.rs b/crates/in-web/build.rs index 59b5d02..a638bfb 100644 --- a/crates/in-web/build.rs +++ b/crates/in-web/build.rs @@ -1,6 +1,7 @@ //! Build script of the `in` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it //! emits the build identity and the content hashes that the page links use as cache-busting -//! queries: `IN_MAIN_CSS_V`, `IN_NAV_JS_V`, `IN_PAGES_JS_V`, `IN_DRIVE_JS_V` and `IN_BUILD_SHA`. +//! queries: `IN_MAIN_CSS_V`, `IN_NAV_JS_V`, `IN_PAGES_JS_V`, `IN_DRIVE_JS_V`, `IN_VIEWER_JS_V` and +//! `IN_BUILD_SHA`. //! //! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a //! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles @@ -46,6 +47,7 @@ fn main() { ("IN_NAV_JS_V", "assets/nav.js"), ("IN_PAGES_JS_V", "assets/pages.js"), ("IN_DRIVE_JS_V", "assets/drive.js"), + ("IN_VIEWER_JS_V", "assets/viewer.js"), ] { let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}")); println!("cargo:rustc-env={var}={}", content_version(&bytes)); diff --git a/crates/in-web/src/api/upload.rs b/crates/in-web/src/api/upload.rs index e3d3748..db1477f 100644 --- a/crates/in-web/src/api/upload.rs +++ b/crates/in-web/src/api/upload.rs @@ -608,6 +608,13 @@ mod tests { .expect("request"); let response = router(state.clone()).handle(request).await; assert_eq!(response.status(), StatusCode::OK); + // The byte policy alone: the page policy must not be added on top of it. + let policies: Vec<_> = response + .headers() + .get_all(http::header::CONTENT_SECURITY_POLICY) + .iter() + .collect(); + assert_eq!(policies, [crate::serve_bytes::BYTES_CSP]); let bytes = to_bytes(response.into_body(), 64 * 1024) .await .expect("body"); diff --git a/crates/in-web/src/assets.rs b/crates/in-web/src/assets.rs index ed911c1..fc995a6 100644 --- a/crates/in-web/src/assets.rs +++ b/crates/in-web/src/assets.rs @@ -18,6 +18,10 @@ pub const NAV_JS_HREF: &str = concat!("/assets/nav.js?v=", env!("IN_NAV_JS_V")); /// Link to the script of individual pages. pub const PAGES_JS_HREF: &str = concat!("/assets/pages.js?v=", env!("IN_PAGES_JS_V")); +/// Link to the script of the viewer: the keyboard steps between files. Every page loads it; it does +/// nothing unless a page has previous and next links. +pub const VIEWER_JS_HREF: &str = concat!("/assets/viewer.js?v=", env!("IN_VIEWER_JS_V")); + /// Link to the upload queue of the drive pages. Only those pages load it. pub const DRIVE_JS_HREF: &str = concat!("/assets/drive.js?v=", env!("IN_DRIVE_JS_V")); @@ -25,6 +29,7 @@ const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); const NAV_JS: &str = include_str!("../assets/nav.js"); const PAGES_JS: &str = include_str!("../assets/pages.js"); const DRIVE_JS: &str = include_str!("../assets/drive.js"); +const VIEWER_JS: &str = include_str!("../assets/viewer.js"); const OFFLINE_HTML: &str = include_str!("../assets/offline.html"); const SW_JS: &str = include_str!("../assets/sw.js"); @@ -69,6 +74,16 @@ async fn drive_js() -> Result { Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, DRIVE_JS)) } +/// `GET /assets/viewer.js`. +#[route(GET "/assets/viewer.js")] +async fn viewer_js() -> Result { + Ok(asset( + "text/javascript; charset=utf-8", + IMMUTABLE, + VIEWER_JS, + )) +} + /// `GET /assets/offline.html`. Also precached by the service worker. #[route(GET "/assets/offline.html")] async fn offline_html() -> Result { diff --git a/crates/in-web/src/boot.rs b/crates/in-web/src/boot.rs index b287de9..d1e0482 100644 --- a/crates/in-web/src/boot.rs +++ b/crates/in-web/src/boot.rs @@ -31,6 +31,7 @@ use crate::pages::not_found::NotFoundLayer; use crate::security::{self, SecurityHeaders}; use crate::state::AppState; use crate::sweeper; +use crate::thumbs_worker; /// Name of the instance key file inside the data directory. const KEY_FILE: &str = "in.key"; @@ -49,6 +50,7 @@ pub async fn serve(config_path: &Path) -> Result<()> { tokio::spawn(directory::run(state.clone(), stop_rx.clone())); } tokio::spawn(sweeper::run(state.clone(), stop_rx.clone())); + tokio::spawn(thumbs_worker::run(state.clone(), stop_rx.clone())); let listener = TcpListener::bind(listen).await.map_err(|error| { std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) diff --git a/crates/in-web/src/i18n/drive.rs b/crates/in-web/src/i18n/drive.rs index ba12ffc..002b856 100644 --- a/crates/in-web/src/i18n/drive.rs +++ b/crates/in-web/src/i18n/drive.rs @@ -80,8 +80,6 @@ pub enum DK { PickHint, /// Cancel a form and go back. Back, - /// Field label: the MIME type. - MimeType, /// Drop overlay text on a drive page. UploadDrop, /// Queue row: an upload in progress. @@ -140,6 +138,14 @@ pub enum DK { RefuseGeneric, /// Refusal: the upload had no file in it. RefuseNoFile, + /// The button to the previous file of the folder, in the current sort order. + Previous, + /// The button to the next file of the folder, in the current sort order. + Next, + /// The note under a text preview that is only the start of a longer file. + TextTruncated, + /// The note on the viewer of a type the page cannot show. + NoPreview, } /// The text of `key` in `lang`. @@ -219,8 +225,6 @@ pub fn d(lang: Lang, key: DK) -> &'static str { (DK::PickHint, Lang::Tr) => "Taşınacağı klasörü seçin.", (DK::Back, Lang::En) => "Back", (DK::Back, Lang::Tr) => "Geri", - (DK::MimeType, Lang::En) => "Type", - (DK::MimeType, Lang::Tr) => "Tür", (DK::UploadDrop, Lang::En) => "Drop files anywhere on this page to upload them.", (DK::UploadDrop, Lang::Tr) => "Yüklemek için dosyaları bu sayfaya bırakın.", (DK::UploadUploading, Lang::En) => "Uploading", @@ -283,6 +287,14 @@ pub fn d(lang: Lang, key: DK) -> &'static str { (DK::RefuseGeneric, Lang::Tr) => "Değişiklik yapılamadı.", (DK::RefuseNoFile, Lang::En) => "Choose at least one file.", (DK::RefuseNoFile, Lang::Tr) => "En az bir dosya seçin.", + (DK::Previous, Lang::En) => "Previous", + (DK::Previous, Lang::Tr) => "Önceki", + (DK::Next, Lang::En) => "Next", + (DK::Next, Lang::Tr) => "Sonraki", + (DK::TextTruncated, Lang::En) => "Only the first 256 KiB of this file is shown.", + (DK::TextTruncated, Lang::Tr) => "Bu dosyanın yalnızca ilk 256 KiB'si gösteriliyor.", + (DK::NoPreview, Lang::En) => "This type of file cannot be previewed here.", + (DK::NoPreview, Lang::Tr) => "Bu dosya türü burada önizlenemez.", } } diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index f23d533..948d8b4 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -18,6 +18,7 @@ mod security; mod serve_bytes; mod state; mod sweeper; +mod thumbs_worker; mod views; use std::path::{Path, PathBuf}; diff --git a/crates/in-web/src/pages/drive.rs b/crates/in-web/src/pages/drive.rs index dca4b76..ecd808c 100644 --- a/crates/in-web/src/pages/drive.rs +++ b/crates/in-web/src/pages/drive.rs @@ -436,7 +436,7 @@ struct LiveQuery { folder: String, } -/// A fingerprint of what a listing shows: every row's id, name, size and last change. Equal text means +/// A fingerprint of what a listing shows: every row's id, name, size, last change and thumbnail state. Equal text means /// the page would look the same, so the stream stays quiet. fn fingerprint(listing: &Listing) -> String { let mut text = String::new(); @@ -450,8 +450,8 @@ fn fingerprint(listing: &Listing) -> String { for file in &listing.files { let _ = writeln!( text, - "f|{}|{}|{}|{}", - file.id, file.name, file.size, file.updated_at + "f|{}|{}|{}|{}|{}", + file.id, file.name, file.size, file.updated_at, file.thumb_state ); } text diff --git a/crates/in-web/src/pages/mod.rs b/crates/in-web/src/pages/mod.rs index d8ebca1..00254b9 100644 --- a/crates/in-web/src/pages/mod.rs +++ b/crates/in-web/src/pages/mod.rs @@ -7,5 +7,6 @@ pub mod home; pub mod not_found; pub mod photo; pub mod sign_in; +pub mod thumbs; pub mod trash; pub mod view; diff --git a/crates/in-web/src/pages/thumbs.rs b/crates/in-web/src/pages/thumbs.rs new file mode 100644 index 0000000..41bc37e --- /dev/null +++ b/crates/in-web/src/pages/thumbs.rs @@ -0,0 +1,90 @@ +//! The thumbnail of a file (`GET /thumb/{id}`). It is served by `serve_bytes`, so it has the same range, +//! validator and header rules as the file bytes. Only a file whose thumbnail is `ready` has one; any other +//! file, including a video, a PDF, a text file, a pending or a failed picture, is `404`. +//! +//! Authorization is the file's `View` check (`files::file_for`): a file the viewer may not see is `404`. + +use in_core::authz::Action; +use in_core::store::files::thumb_blob_key; +use sha2::{Digest, Sha256}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::error::not_found; +use topcoat::router::{path_param_segment, route}; + +use crate::auth::require_member; +use crate::pages::files::file_for; +use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, serve_bytes}; +use crate::state::AppState; + +/// The validator of a thumbnail: the SHA-256 of a fixed label and the file's own digest. It differs from the +/// file's ETag, because the thumbnail is other bytes, and it changes only when the file's bytes change. +pub fn thumb_validator(file_sha256: &str) -> String { + Sha256::digest(format!("thumb:{file_sha256}")) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// `GET /thumb/{id}`: the WebP thumbnail of a picture. +#[route(GET "/thumb/{id}")] +async fn thumb(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let id = path_param_segment(cx, "id").to_owned(); + let file = file_for(state, &viewer, &id, Action::View).await?; + if file.thumb_state != "ready" { + return Err(not_found().into()); + } + let key = thumb_blob_key(&file.id); + let size = state.blobs.size(&key).await?.ok_or_else(not_found)?; + let validator = thumb_validator(&file.sha256); + let source = ByteSource { + blob_key: &key, + size, + sha256: &validator, + mime: "image/webp", + name: &file.name, + }; + serve_bytes(cx, state.blobs.as_ref(), &source, Disposition::Inline).await +} + +#[cfg(test)] +mod tests { + use crate::auth::{SESSION_COOKIE, test_support::signed_in}; + use crate::boot::{router, test_state}; + use http::Request; + use http::header::COOKIE; + use in_core::quota::DEFAULT_MEMBER_QUOTA; + use in_core::store::files::NewFile; + use in_core::store::new_id; + use topcoat::router::Body; + + /// A thumbnail of a text file is `404`: only pictures get thumbnails. + #[tokio::test] + async fn a_thumbnail_of_a_non_picture_is_not_found() { + let (_dir, state) = test_state().await; + let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let id = new_id(); + state + .store + .insert_file(NewFile { + id: id.clone(), + owner: "ann".into(), + folder: None, + name: "notes.txt".into(), + mime: "text/plain".into(), + size: 0, + sha256: "0".repeat(64), + staged_claims: 0, + }) + .await + .expect("row"); + let request = Request::get(format!("/thumb/{id}")) + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) + .body(Body::empty()) + .expect("request"); + let response = router(state.clone()).handle(request).await; + assert_eq!(response.status(), 404); + } +} diff --git a/crates/in-web/src/pages/view.rs b/crates/in-web/src/pages/view.rs index e9b4b8c..4cef360 100644 --- a/crates/in-web/src/pages/view.rs +++ b/crates/in-web/src/pages/view.rs @@ -1,46 +1,205 @@ -//! The viewer page of a file (`GET /view/{id}`). This is the minimal version: the name, size, type, the -//! last change, and the links to the bytes (shown, and downloaded). The image, video, audio, PDF and -//! text viewers come with the viewer step, and replace the body of this page. +//! The viewer of a file (`GET /view/{id}`). The file is shown by its type: an image in an ``, video and +//! audio in `