diff --git a/Cargo.lock b/Cargo.lock
index bb4bd51..e1eba03 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1883,6 +1883,7 @@ dependencies = [
"tracing",
"turso",
"ulid",
+ "unicode-normalization",
]
[[package]]
@@ -1895,12 +1896,15 @@ dependencies = [
"grass",
"hex",
"http",
+ "http-body",
+ "http-body-util",
"in-core",
"jsonwebtoken",
"rand 0.10.3",
"reqwest",
"serde",
"serde_json",
+ "serde_urlencoded",
"sha2 0.11.1",
"tempfile",
"thiserror",
@@ -4963,6 +4967,15 @@ version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+[[package]]
+name = "unicode-normalization"
+version = "0.1.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
+dependencies = [
+ "tinyvec",
+]
+
[[package]]
name = "unicode-width"
version = "0.1.14"
diff --git a/Cargo.toml b/Cargo.toml
index 5685138..0391c33 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -51,6 +51,8 @@ grass = "0.13.4"
hex = "0.4.3"
hmac = "0.13.0"
http = "1.5.0"
+http-body = "1.1.0"
+http-body-util = "0.1.5"
in-core = { path = "crates/in-core" }
ipnet = "2.12.2"
jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto"] }
@@ -59,6 +61,7 @@ rand = "0.10.3"
reqwest = { version = "0.13.5", default-features = false, features = ["form", "rustls", "stream"] }
serde = "1.0.229"
serde_json = "1.0.154"
+serde_urlencoded = "0.7.1"
sha2 = "0.11.1"
subtle = "2.6.1"
tempfile = "3.27.0"
@@ -71,4 +74,5 @@ tracing = "0.1.44"
tracing-subscriber = "0.3.23"
turso = "0.8.3"
ulid = "3.0.0"
+unicode-normalization = "0.1.26"
diff --git a/crates/in-core/Cargo.toml b/crates/in-core/Cargo.toml
index 782d3f6..07ad69b 100644
--- a/crates/in-core/Cargo.toml
+++ b/crates/in-core/Cargo.toml
@@ -29,6 +29,7 @@ toml.workspace = true
tracing.workspace = true
turso.workspace = true
ulid.workspace = true
+unicode-normalization.workspace = true
[dev-dependencies]
tempfile.workspace = true
diff --git a/crates/in-core/src/names.rs b/crates/in-core/src/names.rs
index 9a995fa..72542f7 100644
--- a/crates/in-core/src/names.rs
+++ b/crates/in-core/src/names.rs
@@ -1,12 +1,64 @@
//! Display-name rules for files and folders. A name is shown as typed, but it never carries folders,
//! control characters or more than 255 characters. Names are compared exactly; the database enforces
//! uniqueness among live items in one folder.
+//!
+//! Two entry points, one per trust level. [`validate_name`] is for names a person types: it refuses
+//! what it does not like, so the person sees why. [`upload_name`] is for the file name a browser sends
+//! with an upload: that name is untrusted, so it is cleaned instead of refused. Both return the name in
+//! Unicode NFC, so `e` plus a combining accent and the precomposed letter compare equal.
+
+use unicode_normalization::UnicodeNormalization;
+
+use crate::error::{Error, Result};
/// Longest name in characters (not bytes).
pub const MAX_NAME_CHARS: usize = 255;
+/// Longest name in bytes, the limit that [`validate_name`] enforces.
+pub const MAX_NAME_BYTES: usize = 255;
/// Name given to an item whose input has no usable characters left.
pub const UNTITLED: &str = "Untitled";
+/// Checks a name typed by a person and returns it trimmed and in NFC. Refusals are
+/// `Invalid` with a fixed reason word: `name_empty`, `name_reserved` (`.` or `..`), `name_too_long`
+/// (over [`MAX_NAME_BYTES`]) or `name_bad_char` (a `/`, a `\`, a NUL or any other control character).
+pub fn validate_name(input: &str) -> Result {
+ let name: String = input.trim().nfc().collect();
+ if name.is_empty() {
+ return Err(Error::Invalid("name_empty".into()));
+ }
+ if name == "." || name == ".." {
+ return Err(Error::Invalid("name_reserved".into()));
+ }
+ if name.len() > MAX_NAME_BYTES {
+ return Err(Error::Invalid("name_too_long".into()));
+ }
+ if name
+ .chars()
+ .any(|c| matches!(c, '/' | '\\') || c.is_control())
+ {
+ return Err(Error::Invalid("name_bad_char".into()));
+ }
+ Ok(name)
+}
+
+/// Cleans the file name a browser sent with an upload. Path components are dropped, control
+/// characters removed, the result put in NFC and cut to [`MAX_NAME_BYTES`] at a character boundary.
+/// Input with nothing usable left becomes [`UNTITLED`]. The result always passes [`validate_name`].
+pub fn upload_name(client_name: &str) -> String {
+ let cleaned: String = display_name(client_name).nfc().collect();
+ let mut out = String::new();
+ for c in cleaned.chars() {
+ if out.len() + c.len_utf8() > MAX_NAME_BYTES {
+ break;
+ }
+ out.push(c);
+ }
+ if out.is_empty() || out == "." || out == ".." {
+ return UNTITLED.to_string();
+ }
+ out
+}
+
/// Makes a safe display name from user input. Only the last path component survives, so `a/b/c.txt`
/// becomes `c.txt`. Control characters are dropped, surrounding spaces are trimmed, and input with
/// nothing left (or `.` / `..`) becomes [`UNTITLED`]. The result is cut to [`MAX_NAME_CHARS`].
@@ -83,6 +135,32 @@ mod tests {
}
}
+ #[test]
+ fn validate_name_refuses_what_a_person_should_not_type() {
+ assert_eq!(validate_name(" Trip ").unwrap(), "Trip");
+ assert!(matches!(validate_name(" "), Err(Error::Invalid(m)) if m == "name_empty"));
+ assert!(matches!(validate_name(".."), Err(Error::Invalid(m)) if m == "name_reserved"));
+ assert!(matches!(validate_name("a/b"), Err(Error::Invalid(m)) if m == "name_bad_char"));
+ assert!(matches!(validate_name("a\\b"), Err(Error::Invalid(m)) if m == "name_bad_char"));
+ assert!(matches!(validate_name("a\0b"), Err(Error::Invalid(m)) if m == "name_bad_char"));
+ assert!(
+ matches!(validate_name(&"a".repeat(256)), Err(Error::Invalid(m)) if m == "name_too_long")
+ );
+ // Precomposed and decomposed forms of the same letter come out equal.
+ assert_eq!(validate_name("e\u{301}").unwrap(), "\u{e9}");
+ }
+
+ #[test]
+ fn upload_name_cleans_instead_of_refusing() {
+ assert_eq!(upload_name("..\\..\\evil\u{0}.exe"), "evil.exe");
+ assert_eq!(upload_name("/etc/passwd"), "passwd");
+ assert_eq!(upload_name(".."), UNTITLED);
+ let long = format!("{}.txt", "\u{e9}".repeat(200));
+ let cut = upload_name(&long);
+ assert!(cut.len() <= MAX_NAME_BYTES);
+ assert!(validate_name(&cut).is_ok());
+ }
+
#[test]
fn display_name_cuts_long_names_by_characters() {
let long = "é".repeat(300);
diff --git a/crates/in-core/src/store/folders.rs b/crates/in-core/src/store/folders.rs
index 500c119..d186246 100644
--- a/crates/in-core/src/store/folders.rs
+++ b/crates/in-core/src/store/folders.rs
@@ -271,6 +271,21 @@ impl Store {
Ok(Listing { folders, files })
}
+ /// Every live folder of `owner`, sorted by name. The move picker builds the tree from it.
+ pub async fn live_folders(&self, owner: &str) -> Result> {
+ let conn = self.read_conn().await;
+ fetch_all(
+ &conn,
+ &format!(
+ "SELECT {FOLDER_COLS} FROM folders WHERE owner = ?1 AND trashed_at IS NULL \
+ ORDER BY name, id"
+ ),
+ (owner.to_string(),),
+ map_folder,
+ )
+ .await
+ }
+
/// The chain of folders from the top level down to `folder`, inclusive, for breadcrumbs. The folder
/// must be owned by `owner`; trashed folders are shown too, so the trash page can use it.
pub async fn folder_path(&self, owner: &str, folder: &str) -> Result> {
diff --git a/crates/in-web/Cargo.toml b/crates/in-web/Cargo.toml
index 1a37ce0..f7ab435 100644
--- a/crates/in-web/Cargo.toml
+++ b/crates/in-web/Cargo.toml
@@ -14,6 +14,8 @@ path = "src/main.rs"
base64.workspace = true
futures-util.workspace = true
http.workspace = true
+http-body.workspace = true
+http-body-util.workspace = true
in-core.workspace = true
jsonwebtoken.workspace = true
rand.workspace = true
@@ -31,6 +33,7 @@ tracing.workspace = true
tracing-subscriber = { workspace = true, features = ["env-filter"] }
[dev-dependencies]
+serde_urlencoded.workspace = true
# jsonwebtoken 11 pins ed25519-dalek 2.x; the tests make Ed25519 keys with the same version.
ed25519-dalek = { workspace = true, features = ["pkcs8"] }
tempfile.workspace = true
diff --git a/crates/in-web/src/boot.rs b/crates/in-web/src/boot.rs
index a5b5668..f6200ff 100644
--- a/crates/in-web/src/boot.rs
+++ b/crates/in-web/src/boot.rs
@@ -21,11 +21,12 @@ use tokio::net::TcpListener;
use tokio::signal::unix::{SignalKind, signal};
use tokio::sync::watch;
use topcoat::cookie::RouterBuilderCookieExt;
-use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService};
+use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService};
use crate::directory;
use crate::live::LiveHub;
use crate::oidc::OidcClient;
+use crate::pages::files;
use crate::pages::not_found::NotFoundLayer;
use crate::security::{self, SecurityHeaders};
use crate::state::AppState;
@@ -166,6 +167,8 @@ pub fn router(state: AppState) -> Router {
.discover()
.app_context(state)
.cookies()
+ // The upload form streams, but the body limit still caps how much one request may send.
+ .layer(BodyLimit::max(files::SMALL_UPLOAD_CEILING).at("/files"))
.layer(security)
.layer(NotFoundLayer)
.build()
diff --git a/crates/in-web/src/i18n/drive.rs b/crates/in-web/src/i18n/drive.rs
new file mode 100644
index 0000000..c054d17
--- /dev/null
+++ b/crates/in-web/src/i18n/drive.rs
@@ -0,0 +1,317 @@
+//! Strings of the drive: listings, folders, uploads, the trash, the move picker, the file page and the
+//! notices and refusals that Post/Redirect/Get carries back. The keys are exhaustive per language, so a
+//! missing Turkish text does not compile.
+//!
+//! Notices and refusals travel in the query string as fixed words (`?notice=uploaded`). The page maps a
+//! word to its text here; a word it does not know is shown as nothing, never echoed.
+
+use super::Lang;
+
+/// One variant per phrase of the drive.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum DK {
+ /// The title of the drive and the first breadcrumb.
+ Drive,
+ /// Title of the trash page.
+ Trash,
+ /// Title of the search results.
+ SearchResults,
+ /// Placeholder of the search box.
+ SearchPlaceholder,
+ /// The search button.
+ Search,
+ /// Label of the new-folder form.
+ NewFolder,
+ /// Label of the folder name field.
+ FolderName,
+ /// The button that creates a folder.
+ Create,
+ /// The button that uploads.
+ Upload,
+ /// Label of the file input.
+ ChooseFiles,
+ /// Column heading: name.
+ Name,
+ /// Column heading: size.
+ Size,
+ /// Column heading: when it was last changed.
+ Modified,
+ /// Column heading: kind of item.
+ Kind,
+ /// Column heading: row actions.
+ Actions,
+ /// Kind label: a folder.
+ FolderKind,
+ /// Kind label: a file.
+ FileKind,
+ /// The link that downloads a file.
+ Download,
+ /// The rename action.
+ Rename,
+ /// The save button of the rename form.
+ Save,
+ /// The move action.
+ Move,
+ /// Trash one item.
+ TrashItem,
+ /// Trash every checked item.
+ TrashSelected,
+ /// Empty folder heading.
+ EmptyFolder,
+ /// Empty folder hint.
+ EmptyFolderHint,
+ /// Search with no hits.
+ NoResults,
+ /// Trash with nothing in it.
+ TrashEmpty,
+ /// Explains what the trash does.
+ TrashNote,
+ /// Restore a trashed item.
+ Restore,
+ /// Delete a trashed item now.
+ PurgeNow,
+ /// Delete everything in the trash.
+ EmptyTrash,
+ /// Heading of the move picker.
+ MoveTo,
+ /// The top level of the drive in the move picker.
+ TopLevel,
+ /// The picker's hint.
+ PickHint,
+ /// Cancel a form and go back.
+ Back,
+ /// Field label: the place the file is in.
+ Location,
+ /// Field label: the MIME type.
+ MimeType,
+ /// Field label: when it was uploaded.
+ Uploaded,
+ /// Field label: how many times it was downloaded.
+ Downloads,
+ /// Link to view the bytes in the browser.
+ OpenRaw,
+ /// Accessible name of the breadcrumb trail.
+ Location2,
+ /// Label of the quota bar.
+ Storage,
+ /// Notice: a folder was created.
+ NoticeCreated,
+ /// Notice: a name was changed.
+ NoticeRenamed,
+ /// Notice: an item was moved.
+ NoticeMoved,
+ /// Notice: items went to the trash.
+ NoticeTrashed,
+ /// Notice: items were restored.
+ NoticeRestored,
+ /// Notice: items were deleted for good.
+ NoticePurged,
+ /// Notice: the trash was emptied.
+ NoticeEmptied,
+ /// Notice: the upload finished.
+ NoticeUploaded,
+ /// Refusal: a live name is taken.
+ RefuseNameTaken,
+ /// Refusal: the quota has no room.
+ RefuseQuota,
+ /// Refusal: the file is over the upload limit.
+ RefuseTooLarge,
+ /// Refusal: the name is empty.
+ RefuseNameEmpty,
+ /// Refusal: the name is `.` or `..`.
+ RefuseNameReserved,
+ /// Refusal: the name is too long.
+ RefuseNameTooLong,
+ /// Refusal: the name holds a slash, backslash or control character.
+ RefuseNameBadChar,
+ /// Refusal: a folder would move into itself.
+ RefuseCycle,
+ /// Refusal: the item is not in the trash.
+ RefuseNotInTrash,
+ /// Refusal: no free postfix exists.
+ RefuseTooManyNames,
+ /// Refusal: nothing else is known.
+ RefuseGeneric,
+ /// Refusal: the upload had no file in it.
+ RefuseNoFile,
+}
+
+/// The text of `key` in `lang`.
+pub fn d(lang: Lang, key: DK) -> &'static str {
+ match (key, lang) {
+ (DK::Drive, Lang::En) => "Drive",
+ (DK::Drive, Lang::Tr) => "Sürücü",
+ (DK::Trash, Lang::En) => "Trash",
+ (DK::Trash, Lang::Tr) => "Çöp",
+ (DK::SearchResults, Lang::En) => "Search results",
+ (DK::SearchResults, Lang::Tr) => "Arama sonuçları",
+ (DK::SearchPlaceholder, Lang::En) => "Search your files",
+ (DK::SearchPlaceholder, Lang::Tr) => "Dosyalarınızda ara",
+ (DK::Search, Lang::En) => "Search",
+ (DK::Search, Lang::Tr) => "Ara",
+ (DK::NewFolder, Lang::En) => "New folder",
+ (DK::NewFolder, Lang::Tr) => "Yeni klasör",
+ (DK::FolderName, Lang::En) => "Folder name",
+ (DK::FolderName, Lang::Tr) => "Klasör adı",
+ (DK::Create, Lang::En) => "Create",
+ (DK::Create, Lang::Tr) => "Oluştur",
+ (DK::Upload, Lang::En) => "Upload",
+ (DK::Upload, Lang::Tr) => "Yükle",
+ (DK::ChooseFiles, Lang::En) => "Files",
+ (DK::ChooseFiles, Lang::Tr) => "Dosyalar",
+ (DK::Name, Lang::En) => "Name",
+ (DK::Name, Lang::Tr) => "Ad",
+ (DK::Size, Lang::En) => "Size",
+ (DK::Size, Lang::Tr) => "Boyut",
+ (DK::Modified, Lang::En) => "Modified",
+ (DK::Modified, Lang::Tr) => "Değişiklik",
+ (DK::Kind, Lang::En) => "Kind",
+ (DK::Kind, Lang::Tr) => "Tür",
+ (DK::Actions, Lang::En) => "Actions",
+ (DK::Actions, Lang::Tr) => "İşlemler",
+ (DK::FolderKind, Lang::En) => "Folder",
+ (DK::FolderKind, Lang::Tr) => "Klasör",
+ (DK::FileKind, Lang::En) => "File",
+ (DK::FileKind, Lang::Tr) => "Dosya",
+ (DK::Download, Lang::En) => "Download",
+ (DK::Download, Lang::Tr) => "İndir",
+ (DK::Rename, Lang::En) => "Rename",
+ (DK::Rename, Lang::Tr) => "Yeniden adlandır",
+ (DK::Save, Lang::En) => "Save",
+ (DK::Save, Lang::Tr) => "Kaydet",
+ (DK::Move, Lang::En) => "Move",
+ (DK::Move, Lang::Tr) => "Taşı",
+ (DK::TrashItem, Lang::En) => "Move to trash",
+ (DK::TrashItem, Lang::Tr) => "Çöpe taşı",
+ (DK::TrashSelected, Lang::En) => "Move selected to trash",
+ (DK::TrashSelected, Lang::Tr) => "Seçilenleri çöpe taşı",
+ (DK::EmptyFolder, Lang::En) => "This folder is empty.",
+ (DK::EmptyFolder, Lang::Tr) => "Bu klasör boş.",
+ (DK::EmptyFolderHint, Lang::En) => "Upload files or create a folder to start.",
+ (DK::EmptyFolderHint, Lang::Tr) => "Başlamak için dosya yükleyin ya da klasör oluşturun.",
+ (DK::NoResults, Lang::En) => "Nothing matches your search.",
+ (DK::NoResults, Lang::Tr) => "Aramanızla eşleşen bir şey yok.",
+ (DK::TrashEmpty, Lang::En) => "The trash is empty.",
+ (DK::TrashEmpty, Lang::Tr) => "Çöp boş.",
+ (DK::TrashNote, Lang::En) => {
+ "Items stay here until you delete them for good or empty the trash."
+ }
+ (DK::TrashNote, Lang::Tr) => {
+ "Öğeler, siz kalıcı olarak silene ya da çöpü boşaltana kadar burada kalır."
+ }
+ (DK::Restore, Lang::En) => "Restore",
+ (DK::Restore, Lang::Tr) => "Geri yükle",
+ (DK::PurgeNow, Lang::En) => "Delete for good",
+ (DK::PurgeNow, Lang::Tr) => "Kalıcı olarak sil",
+ (DK::EmptyTrash, Lang::En) => "Empty trash",
+ (DK::EmptyTrash, Lang::Tr) => "Çöpü boşalt",
+ (DK::MoveTo, Lang::En) => "Move to",
+ (DK::MoveTo, Lang::Tr) => "Şuraya taşı",
+ (DK::TopLevel, Lang::En) => "Drive (top level)",
+ (DK::TopLevel, Lang::Tr) => "Sürücü (en üst düzey)",
+ (DK::PickHint, Lang::En) => "Choose the folder to move into.",
+ (DK::PickHint, Lang::Tr) => "Taşınacağı klasörü seçin.",
+ (DK::Back, Lang::En) => "Back",
+ (DK::Back, Lang::Tr) => "Geri",
+ (DK::Location, Lang::En) => "Location",
+ (DK::Location, Lang::Tr) => "Konum",
+ (DK::MimeType, Lang::En) => "Type",
+ (DK::MimeType, Lang::Tr) => "Tür",
+ (DK::Uploaded, Lang::En) => "Uploaded",
+ (DK::Uploaded, Lang::Tr) => "Yüklendi",
+ (DK::Downloads, Lang::En) => "Downloads",
+ (DK::Downloads, Lang::Tr) => "İndirme",
+ (DK::OpenRaw, Lang::En) => "Open in the browser",
+ (DK::OpenRaw, Lang::Tr) => "Tarayıcıda aç",
+ (DK::Location2, Lang::En) => "Location",
+ (DK::Location2, Lang::Tr) => "Konum",
+ (DK::Storage, Lang::En) => "Storage",
+ (DK::Storage, Lang::Tr) => "Depolama",
+ (DK::NoticeCreated, Lang::En) => "The folder was created.",
+ (DK::NoticeCreated, Lang::Tr) => "Klasör oluşturuldu.",
+ (DK::NoticeRenamed, Lang::En) => "The name was changed.",
+ (DK::NoticeRenamed, Lang::Tr) => "Ad değiştirildi.",
+ (DK::NoticeMoved, Lang::En) => "The item was moved.",
+ (DK::NoticeMoved, Lang::Tr) => "Öğe taşındı.",
+ (DK::NoticeTrashed, Lang::En) => "The items were moved to the trash.",
+ (DK::NoticeTrashed, Lang::Tr) => "Öğeler çöpe taşındı.",
+ (DK::NoticeRestored, Lang::En) => "The items were restored.",
+ (DK::NoticeRestored, Lang::Tr) => "Öğeler geri yüklendi.",
+ (DK::NoticePurged, Lang::En) => "The items were deleted for good.",
+ (DK::NoticePurged, Lang::Tr) => "Öğeler kalıcı olarak silindi.",
+ (DK::NoticeEmptied, Lang::En) => "The trash was emptied.",
+ (DK::NoticeEmptied, Lang::Tr) => "Çöp boşaltıldı.",
+ (DK::NoticeUploaded, Lang::En) => "The upload finished.",
+ (DK::NoticeUploaded, Lang::Tr) => "Yükleme tamamlandı.",
+ (DK::RefuseNameTaken, Lang::En) => "An item with this name already exists here.",
+ (DK::RefuseNameTaken, Lang::Tr) => "Bu konumda bu adla bir öğe zaten var.",
+ (DK::RefuseQuota, Lang::En) => "There is not enough storage left for this file.",
+ (DK::RefuseQuota, Lang::Tr) => "Bu dosya için yeterli depolama alanı kalmadı.",
+ (DK::RefuseTooLarge, Lang::En) => "The file is larger than the upload limit.",
+ (DK::RefuseTooLarge, Lang::Tr) => "Dosya yükleme sınırından büyük.",
+ (DK::RefuseNameEmpty, Lang::En) => "The name is empty.",
+ (DK::RefuseNameEmpty, Lang::Tr) => "Ad boş.",
+ (DK::RefuseNameReserved, Lang::En) => "This name is not allowed.",
+ (DK::RefuseNameReserved, Lang::Tr) => "Bu ad kullanılamaz.",
+ (DK::RefuseNameTooLong, Lang::En) => "The name is too long (255 bytes at most).",
+ (DK::RefuseNameTooLong, Lang::Tr) => "Ad çok uzun (en fazla 255 bayt).",
+ (DK::RefuseNameBadChar, Lang::En) => {
+ "The name contains a slash, a backslash or a control character."
+ }
+ (DK::RefuseNameBadChar, Lang::Tr) => {
+ "Ad eğik çizgi, ters eğik çizgi ya da denetim karakteri içeriyor."
+ }
+ (DK::RefuseCycle, Lang::En) => "A folder cannot be moved into itself.",
+ (DK::RefuseCycle, Lang::Tr) => "Bir klasör kendi içine taşınamaz.",
+ (DK::RefuseNotInTrash, Lang::En) => "That item is not in the trash.",
+ (DK::RefuseNotInTrash, Lang::Tr) => "Bu öğe çöpte değil.",
+ (DK::RefuseTooManyNames, Lang::En) => "Too many items already use this name.",
+ (DK::RefuseTooManyNames, Lang::Tr) => "Bu adı kullanan çok fazla öğe var.",
+ (DK::RefuseGeneric, Lang::En) => "The change could not be made.",
+ (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.",
+ }
+}
+
+/// The quota line: how much is used of the quota, both already formatted.
+pub fn quota_text(lang: Lang, used: &str, quota: &str) -> String {
+ match lang {
+ Lang::En => format!("{used} of {quota} used"),
+ Lang::Tr => format!("{quota} içinden {used} kullanıldı"),
+ }
+}
+
+/// The text of a notice word from a redirect, or `None` for a word this build does not know.
+pub fn notice_text(lang: Lang, word: &str) -> Option<&'static str> {
+ Some(match word {
+ "created" => d(lang, DK::NoticeCreated),
+ "renamed" => d(lang, DK::NoticeRenamed),
+ "moved" => d(lang, DK::NoticeMoved),
+ "trashed" => d(lang, DK::NoticeTrashed),
+ "restored" => d(lang, DK::NoticeRestored),
+ "purged" => d(lang, DK::NoticePurged),
+ "emptied" => d(lang, DK::NoticeEmptied),
+ "uploaded" => d(lang, DK::NoticeUploaded),
+ _ => return None,
+ })
+}
+
+/// The text of a refusal word from a redirect, or `None` for a word this build does not know.
+pub fn refusal_text(lang: Lang, word: &str) -> Option<&'static str> {
+ Some(match word {
+ "name_taken" => d(lang, DK::RefuseNameTaken),
+ "quota_exceeded" => d(lang, DK::RefuseQuota),
+ "too_large" => d(lang, DK::RefuseTooLarge),
+ "name_empty" => d(lang, DK::RefuseNameEmpty),
+ "name_reserved" => d(lang, DK::RefuseNameReserved),
+ "name_too_long" => d(lang, DK::RefuseNameTooLong),
+ "name_bad_char" => d(lang, DK::RefuseNameBadChar),
+ "cycle" => d(lang, DK::RefuseCycle),
+ "not_in_trash" => d(lang, DK::RefuseNotInTrash),
+ "too_many_names" => d(lang, DK::RefuseTooManyNames),
+ "no_file" => d(lang, DK::RefuseNoFile),
+ "generic" => d(lang, DK::RefuseGeneric),
+ _ => return None,
+ })
+}
diff --git a/crates/in-web/src/i18n/mod.rs b/crates/in-web/src/i18n/mod.rs
index 5f336b9..f2476a1 100644
--- a/crates/in-web/src/i18n/mod.rs
+++ b/crates/in-web/src/i18n/mod.rs
@@ -7,6 +7,7 @@
//! This module decides the language. It does not format sentences with values; those get small
//! helper functions next to their keys.
+pub mod drive;
pub mod shell;
use topcoat::context::Cx;
diff --git a/crates/in-web/src/i18n/shell.rs b/crates/in-web/src/i18n/shell.rs
index 38a57eb..5beb72d 100644
--- a/crates/in-web/src/i18n/shell.rs
+++ b/crates/in-web/src/i18n/shell.rs
@@ -26,8 +26,6 @@ pub enum K {
SignedOutBody,
/// The button that starts sign-in.
SignIn,
- /// The placeholder under the greeting until the drive exists.
- DriveComesNext,
/// The button in the user menu that ends the session.
SignOut,
/// Heading of the page that explains a sign-in that did not finish.
@@ -44,14 +42,6 @@ pub enum K {
ProblemDeniedBody,
}
-/// The greeting for a signed-in person. The name is inserted as text; the view escapes it.
-pub fn greeting(lang: Lang, name: &str) -> String {
- match lang {
- Lang::En => format!("Hello, {name}."),
- Lang::Tr => format!("Merhaba, {name}."),
- }
-}
-
/// The text of `key` in `lang`.
pub fn t(lang: Lang, key: K) -> &'static str {
match (key, lang) {
@@ -75,8 +65,6 @@ pub fn t(lang: Lang, key: K) -> &'static str {
(K::SignedOutBody, Lang::Tr) => "Dosyalarınızı açmak için aile hesabınızla oturum açın.",
(K::SignIn, Lang::En) => "Sign in",
(K::SignIn, Lang::Tr) => "Oturum aç",
- (K::DriveComesNext, Lang::En) => "The drive comes next. Your files will appear here.",
- (K::DriveComesNext, Lang::Tr) => "Sürücü sıradaki adım. Dosyalarınız burada görünecek.",
(K::SignOut, Lang::En) => "Sign out",
(K::SignOut, Lang::Tr) => "Oturumu kapat",
(K::ProblemFailedTitle, Lang::En) => "Sign-in did not finish",
diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs
index 324ab51..b301206 100644
--- a/crates/in-web/src/main.rs
+++ b/crates/in-web/src/main.rs
@@ -14,6 +14,7 @@ mod live;
mod oidc;
mod pages;
mod security;
+mod serve_bytes;
mod state;
mod views;
diff --git a/crates/in-web/src/pages/drive.rs b/crates/in-web/src/pages/drive.rs
new file mode 100644
index 0000000..efeab45
--- /dev/null
+++ b/crates/in-web/src/pages/drive.rs
@@ -0,0 +1,702 @@
+//! The drive's listing pages: the root (`/`), a folder (`/f/{id}`), search (`/search`), the live stream
+//! that refreshes an open listing, the folder writes (create, rename, move, trash) and the folder move
+//! picker. The file pages live in `files.rs`, the trash in `trash.rs`.
+//!
+//! Authorization: each item is loaded by id and passed to `authz::authorize`. A refusal to see the item
+//! is `404`, so a foreign or missing id looks the same as no item at all. A refusal to change an item the
+//! viewer can see is `403`. Every write checks its CSRF token before it touches anything, and every write
+//! ends in a redirect (Post/Redirect/Get) back to the page named in the form's `back` field, which must
+//! pass `safe_next`. Failures come back as a `refusal` word, successes as a `notice` word.
+
+use std::collections::{HashMap, HashSet};
+use std::fmt::Write as _;
+
+use in_core::authz::{self, Action, Actor, Denied, Grant, Target};
+use in_core::error::Error as CoreError;
+use in_core::names::validate_name;
+use in_core::store::files::File;
+use in_core::store::folders::{Folder, Listing};
+use serde::Deserialize;
+use topcoat::Result;
+use topcoat::context::{Cx, app_context};
+use topcoat::router::content::Form;
+use topcoat::router::error::{SeeOther, forbidden, not_found, see_other};
+use topcoat::router::response::Response;
+use topcoat::router::{page, parse_query_params, path_param_segment, route};
+use topcoat::view::{View, component, view};
+
+use crate::auth::{Viewer, require_csrf, require_member, safe_next};
+use crate::i18n::Lang;
+use crate::i18n::drive::{DK, d, refusal_text};
+use crate::i18n::lang;
+use crate::live::{Topic, stream_changes};
+use crate::oidc::percent_encode;
+use crate::state::AppState;
+use crate::views::drive::{crumbs, flash, listing_table};
+use crate::views::{ViewerInfo, empty_state, shell};
+
+/// How many search hits each kind shows.
+const SEARCH_LIMIT: usize = 100;
+
+/// The query of a listing page. Every field is optional; unknown ones are ignored.
+#[derive(Debug, Default, Deserialize)]
+#[serde(default)]
+pub struct ListQuery {
+ /// Sort key: `name` (default), `size` or `modified`.
+ pub sort: String,
+ /// `asc` (default) or `desc`.
+ pub dir: String,
+ /// The search text, on `/search` only.
+ pub q: String,
+ /// A notice word from a finished action.
+ pub notice: String,
+ /// A refusal word from a refused action.
+ pub refusal: String,
+}
+
+/// The column a listing is sorted by.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SortKey {
+ /// By name (the default).
+ Name,
+ /// By size. Folders have none, so they keep name order.
+ Size,
+ /// By the last change.
+ Modified,
+}
+
+impl SortKey {
+ /// The key a query asks for. Anything unknown is the default.
+ pub fn of(raw: &str) -> Self {
+ match raw {
+ "size" => SortKey::Size,
+ "modified" => SortKey::Modified,
+ _ => SortKey::Name,
+ }
+ }
+
+ /// The word the key has in a URL.
+ pub fn word(self) -> &'static str {
+ match self {
+ SortKey::Name => "name",
+ SortKey::Size => "size",
+ SortKey::Modified => "modified",
+ }
+ }
+}
+
+/// Everything a listing page shows, built before the page is rendered.
+pub struct Board {
+ /// The page title and the heading of the listing.
+ pub heading: String,
+ /// The folders above the current one, top level first.
+ pub trail: Vec,
+ /// The current folder, `None` at the drive root and on search.
+ pub folder: Option,
+ /// The search text, empty for a listing.
+ pub query: String,
+ /// The folders shown, sorted.
+ pub folders: Vec,
+ /// The files shown, sorted.
+ pub files: Vec,
+ /// The sort column.
+ pub sort: SortKey,
+ /// Whether the sort is descending.
+ pub descending: bool,
+ /// The session's CSRF token for the forms.
+ pub csrf: String,
+ /// The page the forms return to.
+ pub back: String,
+ /// A notice word from the query, if any.
+ pub notice: String,
+ /// A refusal word from the query, if any.
+ pub refusal: String,
+ /// The stream that refreshes the listing, if it is live.
+ pub live: Option,
+ /// The start of the sort links: the listing's URL, ending in `?` or `&`.
+ pub base: String,
+}
+
+/// The language of a viewer: the stored override, else the `im` language, else the request.
+pub fn viewer_lang(cx: &Cx, viewer: &Viewer) -> Lang {
+ lang(
+ cx,
+ Some(
+ viewer
+ .member
+ .locale_override
+ .as_deref()
+ .unwrap_or(viewer.member.locale.as_str()),
+ ),
+ )
+}
+
+/// Maps a refusal of the drive's authorization to the HTTP answer. A listing or a view that is refused
+/// is always `404`; a change that is refused to someone who can see the item is `403`.
+pub fn check(viewer: &Viewer, owner: &str, trashed: bool, action: Action) -> Result<()> {
+ let target = Target {
+ owner,
+ trashed,
+ inside_link: false,
+ };
+ let actor = Actor::Member {
+ sub: &viewer.member.sub,
+ is_admin: viewer.member.is_admin,
+ };
+ match authz::authorize(actor, target, Grant::None, action) {
+ Ok(()) => Ok(()),
+ Err(Denied::NotFound) => Err(not_found().into()),
+ Err(Denied::Forbidden) if matches!(action, Action::List | Action::View) => {
+ Err(not_found().into())
+ }
+ Err(Denied::Forbidden) => Err(forbidden().into()),
+ }
+}
+
+/// A live folder by id, after the authorization for `action`. A missing id is `404`.
+pub async fn folder_for(
+ state: &AppState,
+ viewer: &Viewer,
+ id: &str,
+ action: Action,
+) -> Result {
+ let folder = state.store.folder(id).await?.ok_or_else(not_found)?;
+ check(viewer, &folder.owner, folder.trashed_at.is_some(), action)?;
+ Ok(folder)
+}
+
+/// The folder a form names in its `parent` (or `folder`) field, checked for `Write`. A blank field is
+/// the top level and gives `None`.
+pub async fn optional_folder(
+ state: &AppState,
+ viewer: &Viewer,
+ raw: &str,
+) -> Result
+ }
+
+ })
+}
+
+/// `GET /file/{id}`: the file page.
+#[page("/file/{id}")]
+async fn file_page(cx: &Cx) -> Result {
+ let state = app_context::(cx);
+ let viewer = require_member(cx).await?;
+ let lang = viewer_lang(cx, &viewer);
+ let id = path_param_segment(cx, "id").to_owned();
+ let file = file_for(state, &viewer, &id, Action::View).await?;
+ let location = match file.folder_id.as_deref() {
+ Some(folder) => match state.store.folder(folder).await? {
+ Some(row) if row.trashed_at.is_none() => row.name,
+ _ => d(lang, DK::Drive).to_owned(),
+ },
+ None => d(lang, DK::Drive).to_owned(),
+ };
+ let writable =
+ file.trashed_at.is_none() && check(&viewer, &file.owner, false, Action::Write).is_ok();
+ let query: ListQuery = parse_query_params(cx).unwrap_or_default();
+ let info = ViewerInfo::of(&viewer);
+ let csrf = viewer.session.csrf_token.clone();
+ let title = file.name.clone();
+ Ok(view! {
+ shell(title: title.as_str(), lang: lang, viewer: Some(&info),
+ file_body(lang: lang, file: &file, location: location.as_str(), csrf: csrf.as_str(), writable: writable, notice: query.notice.as_str(), refusal: query.refusal.as_str())
+ )
+ })
+}
+
+/// Serves the bytes of a file the viewer may act on with `action`.
+async fn serve_file(
+ cx: &Cx,
+ action: Action,
+ disposition: Disposition,
+ count: bool,
+) -> 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).await?;
+ let size = u64::try_from(file.size).unwrap_or(0);
+ if count && counts_as_download(headers(cx), &file.sha256, size) {
+ state.store.record_download(&file.id).await?;
+ }
+ let source = ByteSource {
+ blob_key: &file.blob_key,
+ size,
+ sha256: &file.sha256,
+ mime: &file.mime,
+ name: &file.name,
+ };
+ serve_bytes(cx, state.blobs.as_ref(), &source, disposition).await
+}
+
+/// `GET /file/{id}/download`: the bytes as a download. Counts one download when it starts at byte 0.
+#[route(GET "/file/{id}/download")]
+async fn download_bytes(cx: &Cx) -> Result {
+ serve_file(cx, Action::Download, Disposition::Attachment, true).await
+}
+
+/// `GET /file/{id}/raw`: the bytes to show in the browser. The type decides whether they are shown or
+/// saved.
+#[route(GET "/file/{id}/raw")]
+async fn raw_bytes(cx: &Cx) -> Result {
+ serve_file(cx, Action::View, Disposition::Inline, false).await
+}
+
+/// `POST /files/{id}/rename`.
+#[route(POST "/files/{id}/rename")]
+async fn rename_file(cx: &Cx, Form(form): Form) -> Result {
+ let state = app_context::(cx);
+ let viewer = require_csrf(cx, &form.csrf).await?;
+ let id = path_param_segment(cx, "id").to_owned();
+ let back = back_or(&form.back, "/");
+ file_for(state, &viewer, &id, Action::Write).await?;
+ let name = match validate_name(&form.name) {
+ Ok(name) => name,
+ Err(error) => return refused(&back, error),
+ };
+ match state
+ .store
+ .rename_file(&viewer.member.sub, &id, &name)
+ .await
+ {
+ Ok(_) => {
+ changed(state, &viewer.member.sub);
+ Ok(done(&back, "renamed"))
+ }
+ Err(error) => refused(&back, error),
+ }
+}
+
+/// `POST /files/{id}/move`: the folder in the form is the new place (blank for the top level).
+#[route(POST "/files/{id}/move")]
+async fn move_file(cx: &Cx, Form(form): Form) -> Result {
+ let state = app_context::(cx);
+ let viewer = require_csrf(cx, &form.csrf).await?;
+ let id = path_param_segment(cx, "id").to_owned();
+ let back = back_or(&form.back, "/");
+ file_for(state, &viewer, &id, Action::Write).await?;
+ let parent = optional_folder(state, &viewer, &form.parent).await?;
+ match state
+ .store
+ .move_file(&viewer.member.sub, &id, parent.as_deref())
+ .await
+ {
+ Ok(_) => {
+ changed(state, &viewer.member.sub);
+ Ok(done(&back, "moved"))
+ }
+ Err(error) => refused(&back, error),
+ }
+}
+
+/// `POST /files/{id}/trash`.
+#[route(POST "/files/{id}/trash")]
+async fn trash_file(cx: &Cx, Form(form): Form) -> Result {
+ let state = app_context::(cx);
+ let viewer = require_csrf(cx, &form.csrf).await?;
+ let id = path_param_segment(cx, "id").to_owned();
+ let back = back_or(&form.back, "/");
+ file_for(state, &viewer, &id, Action::Write).await?;
+ match state.store.trash_file(&viewer.member.sub, &id).await {
+ Ok(()) => {
+ changed(state, &viewer.member.sub);
+ Ok(done(&back, "trashed"))
+ }
+ Err(error) => refused(&back, error),
+ }
+}
+
+/// `GET /files/{id}/pick`: the move picker of a file. The folders are listed as in the folder picker.
+#[page("/files/{id}/pick")]
+async fn pick_file(cx: &Cx) -> Result {
+ let state = app_context::(cx);
+ let viewer = require_member(cx).await?;
+ let lang = viewer_lang(cx, &viewer);
+ let id = path_param_segment(cx, "id").to_owned();
+ let file = file_for(state, &viewer, &id, Action::Write).await?;
+ let all = state.store.live_folders(&viewer.member.sub).await?;
+ let rows = tree_rows(&all, None);
+ let action = format!("/files/{id}/move");
+ let back = format!("/file/{id}");
+ let csrf = viewer.session.csrf_token.clone();
+ let info = ViewerInfo::of(&viewer);
+ let title = d(lang, DK::MoveTo);
+ Ok(view! {
+ shell(title: title, lang: lang, viewer: Some(&info),
+ pick_body(lang: lang, subject: file.name.as_str(), action: action.as_str(), csrf: csrf.as_str(), back: back.as_str(), rows: &rows)
+ )
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::auth::{SESSION_COOKIE, SESSION_TTL};
+ use crate::boot::{router, test_state};
+ use http::Request;
+ use http::header::{CONTENT_TYPE, COOKIE};
+ use in_core::quota::DEFAULT_MEMBER_QUOTA;
+ use in_core::store::members::MemberFields;
+ use in_core::store::new_id;
+ use in_core::store::sessions::NewSession;
+ use in_core::time::stamp_after;
+ use in_core::token::{generate_token, hash_token};
+ use topcoat::router::Body;
+
+ /// A member with a session: returns the session cookie value.
+ async fn signed_in(state: &AppState, sub: &str, quota: i64) -> String {
+ state
+ .store
+ .upsert_member_from_claims(
+ &MemberFields {
+ sub: sub.into(),
+ email: format!("{sub}@example.test"),
+ name: sub.into(),
+ is_admin: false,
+ locale: "en".into(),
+ zoneinfo: "UTC".into(),
+ picture_version: 0,
+ im_updated_at: String::new(),
+ },
+ DEFAULT_MEMBER_QUOTA,
+ )
+ .await
+ .expect("member");
+ state.store.set_quota(sub, quota).await.expect("quota");
+ let token = generate_token();
+ state
+ .store
+ .create_session(NewSession {
+ sub: sub.into(),
+ token_hash: hash_token(&token),
+ csrf_token: format!("csrf-{sub}"),
+ im_sid: format!("im-{sub}"),
+ expires_at: stamp_after(SESSION_TTL),
+ ip: None,
+ user_agent: None,
+ id_token_sealed: None,
+ })
+ .await
+ .expect("session");
+ token
+ }
+
+ /// A file stored the way an upload stores it, owned by `owner`.
+ async fn stored_file(state: &AppState, owner: &str, name: &str, bytes: &[u8]) -> File {
+ let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20)
+ .await
+ .expect("staging");
+ staged.write(bytes).await.expect("write");
+ let Staged { path, sha256, .. } = staged.finish().await.expect("finish");
+ let id = new_id();
+ state
+ .blobs
+ .put_file(&files_blob_key(&id), &path)
+ .await
+ .expect("blob");
+ state
+ .store
+ .insert_file(NewFile {
+ id,
+ owner: owner.into(),
+ folder: None,
+ name: name.into(),
+ mime: sniff(bytes),
+ size: bytes.len() as i64,
+ sha256,
+ staged_claims: 0,
+ })
+ .await
+ .expect("row")
+ }
+
+ /// A multipart body with one part per entry: `(field, file name, content)`.
+ fn multipart_body(boundary: &str, parts: &[(&str, Option<&str>, &[u8])]) -> Vec {
+ let mut body = Vec::new();
+ for (field, file, content) in parts {
+ body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
+ match file {
+ Some(file) => body.extend_from_slice(
+ format!(
+ "Content-Disposition: form-data; name=\"{field}\"; filename=\"{file}\"\r\n\
+ Content-Type: application/octet-stream\r\n\r\n"
+ )
+ .as_bytes(),
+ ),
+ None => body.extend_from_slice(
+ format!("Content-Disposition: form-data; name=\"{field}\"\r\n\r\n").as_bytes(),
+ ),
+ }
+ body.extend_from_slice(content);
+ body.extend_from_slice(b"\r\n");
+ }
+ body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
+ body
+ }
+
+ #[tokio::test]
+ async fn another_members_file_id_is_not_found_on_its_bytes() {
+ let (_dir, state) = test_state().await;
+ let owner_token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await;
+ let other_token = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await;
+ let file = stored_file(&state, "ann", "notes.txt", b"hello").await;
+ let path = format!("/file/{}/download", file.id);
+
+ let as_other = Request::get(&path)
+ .header(COOKIE, format!("{SESSION_COOKIE}={other_token}"))
+ .body(Body::empty())
+ .expect("request");
+ let response = router(state.clone()).handle(as_other).await;
+ assert_eq!(response.status(), 404, "a foreign id must look missing");
+
+ let as_owner = Request::get(&path)
+ .header(COOKIE, format!("{SESSION_COOKIE}={owner_token}"))
+ .body(Body::empty())
+ .expect("request");
+ let response = router(state.clone()).handle(as_owner).await;
+ assert_eq!(response.status(), 200);
+ assert!(
+ response.headers()["content-disposition"]
+ .to_str()
+ .expect("ascii")
+ .starts_with("attachment;"),
+ "a download is an attachment"
+ );
+ }
+
+ #[tokio::test]
+ async fn an_upload_over_quota_is_refused_and_leaves_no_blob_behind() {
+ let (dir, state) = test_state().await;
+ let token = signed_in(&state, "ann", 10).await;
+ let boundary = "in-test-boundary";
+ let body = multipart_body(
+ boundary,
+ &[
+ ("csrf", None, b"csrf-ann"),
+ ("back", None, b"/"),
+ ("folder", None, b""),
+ ("files", Some("../../big.bin"), &[7u8; 100]),
+ ],
+ );
+ let request = Request::post("/files")
+ .header(COOKIE, format!("{SESSION_COOKIE}={token}"))
+ .header(
+ CONTENT_TYPE,
+ format!("multipart/form-data; boundary={boundary}"),
+ )
+ .body(Body::from(body))
+ .expect("request");
+ let response = router(state.clone()).handle(request).await;
+
+ assert_eq!(response.status(), 303);
+ let location = response.headers()["location"].to_str().expect("ascii");
+ assert!(
+ location.ends_with("refusal=quota_exceeded"),
+ "got {location}"
+ );
+ assert!(
+ state.blobs.list("files/").await.expect("list").is_empty(),
+ "a refused file must not reach the blob store"
+ );
+ let staged_left = std::fs::read_dir(dir.path().join("tmp"))
+ .map(|entries| entries.count())
+ .unwrap_or(0);
+ assert_eq!(staged_left, 0, "the staging file is removed");
+ let member = state
+ .store
+ .member("ann")
+ .await
+ .expect("lookup")
+ .expect("member");
+ assert_eq!(member.used_bytes, 0, "nothing was charged");
+ }
+}
diff --git a/crates/in-web/src/pages/home.rs b/crates/in-web/src/pages/home.rs
index fae16c7..876fbcb 100644
--- a/crates/in-web/src/pages/home.rs
+++ b/crates/in-web/src/pages/home.rs
@@ -1,52 +1,49 @@
-//! The start page. Signed out, it offers sign-in. Signed in, it greets the person; the drive that
-//! follows it is not built yet, so it says so.
+//! The start page (`/`). Signed out, it offers sign-in. Signed in, it is the drive root: the same listing
+//! as `/f/{id}` for the top level, built by `drive.rs`.
use topcoat::Result;
-use topcoat::context::Cx;
-use topcoat::router::page;
+use topcoat::context::{Cx, app_context};
+use topcoat::router::{page, parse_query_params};
use topcoat::view::{View, view};
use crate::auth::current_member;
use crate::i18n::lang;
-use crate::i18n::shell::{K, greeting, t};
+use crate::i18n::shell::{K, t};
+use crate::pages::drive::{ListQuery, drive_board, root_board, viewer_lang};
+use crate::state::AppState;
use crate::views::{ViewerInfo, shell};
/// `GET /`.
#[page("/")]
async fn home(cx: &Cx) -> Result {
+ let state = app_context::(cx);
let viewer = current_member(cx).await?;
- // The language follows the stored override, else the one `im` reports, else the request.
- let lang = lang(
- cx,
- viewer.as_ref().map(|viewer| {
- viewer
- .member
- .locale_override
- .as_deref()
- .unwrap_or(viewer.member.locale.as_str())
- }),
- );
- let info = viewer.map(|viewer| ViewerInfo {
- name: viewer.member.name,
- is_admin: viewer.member.is_admin,
- csrf: viewer.session.csrf_token,
- });
- let heading = match &info {
- Some(info) => greeting(lang, &info.name),
+ let query: ListQuery = parse_query_params(cx).unwrap_or_default();
+ let lang = match &viewer {
+ Some(viewer) => viewer_lang(cx, viewer),
+ None => lang(cx, None),
+ };
+ let info = viewer.as_ref().map(ViewerInfo::of);
+ let board = match &viewer {
+ Some(viewer) => Some(root_board(state, viewer, &query, lang).await?),
+ None => None,
+ };
+ let heading = match &board {
+ Some(board) => board.heading.clone(),
None => t(lang, K::SignedOutTitle).to_owned(),
};
Ok(view! {
shell(title: heading.as_str(), lang: lang, viewer: info.as_ref(),
-
-
"in"
-
(heading.as_str())
- if info.is_some() {
-
(t(lang, K::DriveComesNext))
+ if let Some(board) = &board {
+ drive_board(lang: lang, board: board)
} else {
+
+
"in"
+
(t(lang, K::SignedOutTitle))
(t(lang, K::SignedOutBody))
(t(lang, K::SignIn))
+
}
-
)
})
}
diff --git a/crates/in-web/src/pages/mod.rs b/crates/in-web/src/pages/mod.rs
index 700b695..18eb898 100644
--- a/crates/in-web/src/pages/mod.rs
+++ b/crates/in-web/src/pages/mod.rs
@@ -1,7 +1,10 @@
//! The pages and the page-level layers. One file per page or per closely related group of pages.
pub mod backchannel;
+pub mod drive;
+pub mod files;
pub mod home;
pub mod not_found;
pub mod photo;
pub mod sign_in;
+pub mod trash;
diff --git a/crates/in-web/src/pages/trash.rs b/crates/in-web/src/pages/trash.rs
new file mode 100644
index 0000000..346ed52
--- /dev/null
+++ b/crates/in-web/src/pages/trash.rs
@@ -0,0 +1,321 @@
+//! The trash: `/trash` lists what the viewer trashed, and the forms under it restore, delete for good or
+//! empty it. `POST /items/trash` moves a set of live items to the trash in one request.
+//!
+//! Only the owner acts on trashed items (`authz`: restore and purge). The purge routes return the blob keys
+//! the store released; they are deleted after the row is gone, and a failed delete is logged, not shown,
+//! because the row no longer names those bytes. A bulk trash checks every item before it changes one, so a
+//! request that names a foreign or missing item changes nothing.
+
+use in_core::authz::Action;
+use in_core::error::Error as CoreError;
+use in_core::store::folders::Listing;
+use in_core::store::trash::ItemKind;
+use serde::Deserialize;
+use topcoat::Result;
+use topcoat::context::{Cx, app_context};
+use topcoat::router::content::Form;
+use topcoat::router::error::SeeOther;
+use topcoat::router::{page, parse_query_params, route};
+use topcoat::view::{View, component, view};
+
+use crate::auth::{require_csrf, require_member};
+use crate::i18n::Lang;
+use crate::i18n::drive::{DK, d};
+use crate::pages::drive::{ListQuery, back_or, changed, done, folder_for, refused, viewer_lang};
+use crate::pages::files::file_for;
+use crate::state::AppState;
+use crate::views::drive::{flash, size_text, stamp_text};
+use crate::views::{ViewerInfo, empty_state, shell};
+
+/// The form of the trash actions: a CSRF token, the return page, and the item kind and id for a single
+/// item.
+#[derive(Debug, Default, Deserialize)]
+#[serde(default)]
+pub struct TrashForm {
+ /// The CSRF token of the session.
+ pub csrf: String,
+ /// The page to return to.
+ pub back: String,
+ /// `file` or `folder`.
+ pub kind: String,
+ /// The item's id.
+ pub id: String,
+}
+
+/// The kind word of a trash form, or `None` for anything else.
+fn kind_of(word: &str) -> Option {
+ match word {
+ "file" => Some(ItemKind::File),
+ "folder" => Some(ItemKind::Folder),
+ _ => None,
+ }
+}
+
+/// Deletes the blobs the store released. A failure is logged: the rows that named them are gone.
+async fn release(state: &AppState, keys: Vec) {
+ for key in keys {
+ if let Err(error) = state.blobs.delete(&key).await {
+ tracing::error!(error = %error, "trash: a released blob could not be deleted");
+ }
+ }
+}
+
+/// The trash page's content: the trashed roots, with a restore and a delete button for each, and the
+/// button that empties the trash.
+#[component]
+pub async fn trash_body(
+ lang: Lang,
+ listing: &Listing,
+ csrf: &str,
+ notice: &str,
+ refusal: &str,
+) -> Result {
+ let empty = listing.folders.is_empty() && listing.files.is_empty();
+ Ok(view! {
+
+
+ }
+
+ })
+}
+
+/// `GET /trash`.
+#[page("/trash")]
+async fn trash_page(cx: &Cx) -> Result {
+ let state = app_context::(cx);
+ let viewer = require_member(cx).await?;
+ let lang = viewer_lang(cx, &viewer);
+ let query: ListQuery = parse_query_params(cx).unwrap_or_default();
+ let listing = state.store.list_trash(&viewer.member.sub).await?;
+ let info = ViewerInfo::of(&viewer);
+ let csrf = viewer.session.csrf_token.clone();
+ let title = d(lang, DK::Trash);
+ Ok(view! {
+ shell(title: title, lang: lang, viewer: Some(&info),
+ trash_body(lang: lang, listing: &listing, csrf: csrf.as_str(), notice: query.notice.as_str(), refusal: query.refusal.as_str())
+ )
+ })
+}
+
+/// `POST /trash/restore`: puts a trashed item back in its place.
+#[route(POST "/trash/restore")]
+async fn restore(cx: &Cx, Form(form): Form) -> Result {
+ let state = app_context::(cx);
+ let viewer = require_csrf(cx, &form.csrf).await?;
+ let back = back_or(&form.back, "/trash");
+ let Some(kind) = kind_of(&form.kind) else {
+ return Err(CoreError::NotFound.into());
+ };
+ match kind {
+ ItemKind::File => {
+ file_for(state, &viewer, &form.id, Action::Restore).await?;
+ }
+ ItemKind::Folder => {
+ folder_for(state, &viewer, &form.id, Action::Restore).await?;
+ }
+ }
+ finish(state, &viewer.member.sub, &back, kind, &form.id, "restored").await
+}
+
+/// Runs a restore after its authorization. Shared by the file and folder branches.
+async fn finish(
+ state: &AppState,
+ owner: &str,
+ back: &str,
+ kind: ItemKind,
+ id: &str,
+ notice: &str,
+) -> Result {
+ match state.store.restore(owner, kind, id).await {
+ Ok(()) => {
+ changed(state, owner);
+ Ok(done(back, notice))
+ }
+ Err(error) => refused(back, error),
+ }
+}
+
+/// `POST /trash/purge`: deletes a trashed item for good, with its bytes.
+#[route(POST "/trash/purge")]
+async fn purge(cx: &Cx, Form(form): Form) -> Result {
+ let state = app_context::(cx);
+ let viewer = require_csrf(cx, &form.csrf).await?;
+ let back = back_or(&form.back, "/trash");
+ let Some(kind) = kind_of(&form.kind) else {
+ return Err(CoreError::NotFound.into());
+ };
+ match kind {
+ ItemKind::File => {
+ file_for(state, &viewer, &form.id, Action::Purge).await?;
+ }
+ ItemKind::Folder => {
+ folder_for(state, &viewer, &form.id, Action::Purge).await?;
+ }
+ }
+ let owner = viewer.member.sub.clone();
+ let released = match kind {
+ ItemKind::File => state.store.purge_file(&owner, &form.id).await,
+ ItemKind::Folder => state.store.purge_folder(&owner, &form.id).await,
+ };
+ match released {
+ Ok(keys) => {
+ release(state, keys).await;
+ changed(state, &owner);
+ Ok(done(&back, "purged"))
+ }
+ Err(error) => refused(&back, error),
+ }
+}
+
+/// `POST /trash/empty`: deletes everything in the trash for good.
+#[route(POST "/trash/empty")]
+async fn empty_trash(cx: &Cx, Form(form): Form) -> Result {
+ let state = app_context::(cx);
+ let viewer = require_csrf(cx, &form.csrf).await?;
+ let back = back_or(&form.back, "/trash");
+ let owner = viewer.member.sub.clone();
+ match state.store.empty_trash(&owner).await {
+ Ok(keys) => {
+ release(state, keys).await;
+ changed(state, &owner);
+ Ok(done(&back, "emptied"))
+ }
+ Err(error) => refused(&back, error),
+ }
+}
+
+/// `POST /items/trash`: moves the checked live items to the trash. The form is read as raw key/value pairs,
+/// because one `item` key repeats once per checked row. Every item is checked first; if one of them is not
+/// the viewer's, nothing is trashed and that item's answer is returned.
+#[route(POST "/items/trash")]
+async fn trash_items(cx: &Cx, Form(pairs): Form>) -> Result {
+ let state = app_context::(cx);
+ let mut csrf = String::new();
+ let mut back = String::new();
+ let mut items = Vec::new();
+ for (key, value) in pairs {
+ match key.as_str() {
+ "csrf" => csrf = value,
+ "back" => back = value,
+ "item" => items.push(value),
+ _ => {}
+ }
+ }
+ let viewer = require_csrf(cx, &csrf).await?;
+ let back = back_or(&back, "/");
+ let mut files = Vec::new();
+ let mut folders = Vec::new();
+ for item in &items {
+ match item.split_once(':') {
+ Some(("file", id)) => {
+ file_for(state, &viewer, id, Action::Write).await?;
+ files.push(id.to_owned());
+ }
+ Some(("folder", id)) => {
+ folder_for(state, &viewer, id, Action::Write).await?;
+ folders.push(id.to_owned());
+ }
+ _ => return Err(CoreError::NotFound.into()),
+ }
+ }
+ let owner = viewer.member.sub.clone();
+ for id in &files {
+ if let Err(error) = state.store.trash_file(&owner, id).await {
+ return refused(&back, error);
+ }
+ }
+ for id in &folders {
+ if let Err(error) = state.store.trash_folder(&owner, id).await {
+ return refused(&back, error);
+ }
+ }
+ if !files.is_empty() || !folders.is_empty() {
+ changed(state, &owner);
+ }
+ Ok(done(&back, "trashed"))
+}
+
+#[cfg(test)]
+mod tests {
+ /// The browser repeats `item` once per checked row; the pairs keep every one, in order.
+ #[test]
+ fn repeated_item_fields_are_all_kept() {
+ let pairs: Vec<(String, String)> = serde_urlencoded::from_str(
+ "csrf=t&back=%2F&item=file%3Aa&item=folder%3Ab&item=file%3Ac",
+ )
+ .expect("form");
+ let items: Vec<&str> = pairs
+ .iter()
+ .filter(|(key, _)| key == "item")
+ .map(|(_, value)| value.as_str())
+ .collect();
+ assert_eq!(items, vec!["file:a", "folder:b", "file:c"]);
+ }
+}
diff --git a/crates/in-web/src/serve_bytes.rs b/crates/in-web/src/serve_bytes.rs
new file mode 100644
index 0000000..d0156c0
--- /dev/null
+++ b/crates/in-web/src/serve_bytes.rs
@@ -0,0 +1,458 @@
+//! The one function that sends a stored blob to a browser. Every byte route (download, raw, and the
+//! shared and public ones that come later) calls [`serve_bytes`], so the headers and the range rules
+//! exist in exactly one place (architecture section 7).
+//!
+//! The caller has already decided that the viewer may see the bytes (`authz`). This module decides how
+//! they are sent: a single byte range, a validator (`ETag`) and its conditional requests, a disposition
+//! that is `inline` only for types a browser can show without running them, and the response headers
+//! that stop the bytes from being used as a page. The body is streamed from the blob store in frames of
+//! [`in_core::blob::FRAME_BYTES`]; nothing is buffered whole.
+//!
+//! Range rules: one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with several ranges gets the
+//! whole file with `200`. A malformed, reversed or unsatisfiable range gets `416` with
+//! `Content-Range: bytes */`. `If-Range` with a validator that is not the current one gets the whole
+//! file.
+
+use futures_util::TryStreamExt;
+use http::header::{
+ ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE,
+ CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE,
+ X_CONTENT_TYPE_OPTIONS,
+};
+use http_body::Frame;
+use http_body_util::StreamBody;
+use in_core::blob::BlobStore;
+use topcoat::Result;
+use topcoat::context::Cx;
+use topcoat::router::request::headers;
+use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode};
+
+/// What a browser may do with a byte response: show it in the page, or save it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Disposition {
+ /// Show the bytes in the page. Granted only to the types in [`inline_safe`].
+ Inline,
+ /// Save the bytes as a file.
+ Attachment,
+}
+
+/// Everything about a stored file that a byte response needs. The caller fills it from the row.
+#[derive(Clone, Copy, Debug)]
+pub struct ByteSource<'a> {
+ /// Key of the bytes in the blob store.
+ pub blob_key: &'a str,
+ /// Length of the bytes in bytes.
+ pub size: u64,
+ /// Lowercase hex SHA-256 of the bytes. It is the strong validator, so equal hashes mean equal bytes.
+ pub sha256: &'a str,
+ /// The sniffed MIME type, as stored. It is never the uploader's claim.
+ pub mime: &'a str,
+ /// The display name, used for the `Content-Disposition` file name.
+ pub name: &'a str,
+}
+
+/// The status, headers and body of a byte response. Handlers return it as they are.
+pub type ByteAnswer = (StatusCode, HeaderMap, Body);
+
+/// `Content-Security-Policy` of every byte response. The sandbox makes the document opaque, and
+/// `default-src 'none'` stops it from loading anything but its own image, media or style.
+pub const BYTES_CSP: &str =
+ "sandbox; default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'";
+
+/// Cache policy of content addressed by id and hash: the bytes behind a URL never change.
+const BYTES_CACHE: &str = "private, max-age=31536000, immutable";
+
+/// The outcome of reading a `Range` header against a length.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Ranged {
+ /// Send the whole file (no range, or several ranges).
+ Full,
+ /// Send the bytes from `start` to `end`, both inclusive, and both inside the file.
+ Part {
+ /// First byte, inclusive.
+ start: u64,
+ /// Last byte, inclusive.
+ end: u64,
+ },
+ /// The header is malformed, reversed, or asks for nothing the file has. Answer `416`.
+ Unsatisfiable,
+}
+
+/// Parses the value of a `Range` header for a file of `len` bytes.
+///
+/// Accepted: `bytes=a-b` (clamped to the end of the file), `bytes=a-` (to the end), `bytes=-n` (the last
+/// `n` bytes; a longer `n` means the whole file). Several ranges, separated by commas, give
+/// [`Ranged::Full`]. Everything else is [`Ranged::Unsatisfiable`]: a missing unit, a non-digit, a value
+/// that overflows `u64`, `-0`, a last byte before the first, or a first byte at or past the end.
+pub fn parse_range(value: &str, len: u64) -> Ranged {
+ let Some(spec) = value.trim().strip_prefix("bytes=") else {
+ return Ranged::Unsatisfiable;
+ };
+ if spec.contains(',') {
+ return Ranged::Full;
+ }
+ let Some((first, last)) = spec.trim().split_once('-') else {
+ return Ranged::Unsatisfiable;
+ };
+ let (first, last) = (first.trim(), last.trim());
+ if first.is_empty() {
+ // A suffix range: the last `n` bytes.
+ let Some(n) = digits(last) else {
+ return Ranged::Unsatisfiable;
+ };
+ if n == 0 || len == 0 {
+ return Ranged::Unsatisfiable;
+ }
+ let n = n.min(len);
+ return Ranged::Part {
+ start: len - n,
+ end: len - 1,
+ };
+ }
+ let Some(start) = digits(first) else {
+ return Ranged::Unsatisfiable;
+ };
+ let end = if last.is_empty() {
+ None
+ } else {
+ match digits(last) {
+ Some(end) if end >= start => Some(end),
+ _ => return Ranged::Unsatisfiable,
+ }
+ };
+ if start >= len {
+ return Ranged::Unsatisfiable;
+ }
+ let end = end.map_or(len - 1, |end| end.min(len - 1));
+ Ranged::Part { start, end }
+}
+
+/// A non-empty run of ASCII digits as a number. Anything else, including an overflow, is `None`.
+fn digits(text: &str) -> Option {
+ if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
+ return None;
+ }
+ text.parse().ok()
+}
+
+/// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong
+/// form here, which is the rule for `GET` validators (RFC 9110).
+fn none_match_hits(request: &HeaderMap, etag: &str) -> bool {
+ request
+ .get(IF_NONE_MATCH)
+ .and_then(|value| value.to_str().ok())
+ .is_some_and(|value| {
+ value.split(',').map(str::trim).any(|candidate| {
+ candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag
+ })
+ })
+}
+
+/// Whether a range may be honoured under `If-Range`. Without the header it always may. With it, only a
+/// strong validator equal to `etag` allows the range; a date or a weak tag never does.
+fn if_range_allows(request: &HeaderMap, etag: &str) -> bool {
+ match request.get(IF_RANGE).and_then(|value| value.to_str().ok()) {
+ None => true,
+ Some(value) => value.trim() == etag,
+ }
+}
+
+/// The range that applies to this request, after `If-Range` has had its say.
+fn requested_range(request: &HeaderMap, etag: &str, len: u64) -> Ranged {
+ let Some(value) = request.get(RANGE).and_then(|value| value.to_str().ok()) else {
+ return Ranged::Full;
+ };
+ if !if_range_allows(request, etag) {
+ return Ranged::Full;
+ }
+ parse_range(value, len)
+}
+
+/// Whether serving this request counts as a download that started at byte 0. A `304`, a range that
+/// starts later, and an unsatisfiable range do not count; a whole file, or a range from byte 0, does.
+/// The download counter is bumped by the caller before it serves the body.
+pub fn counts_as_download(request: &HeaderMap, sha256: &str, size: u64) -> bool {
+ let etag = format!("\"{sha256}\"");
+ if none_match_hits(request, &etag) {
+ return false;
+ }
+ match requested_range(request, &etag, size) {
+ Ranged::Full => true,
+ Ranged::Part { start, .. } => start == 0,
+ Ranged::Unsatisfiable => false,
+ }
+}
+
+/// Whether a type may be shown inline. SVG is never inline: it can carry script. HTML is never inline.
+/// Images (except SVG and HEIC/HEIF, which browsers do not show everywhere), audio, video, PDF and plain
+/// text are.
+pub fn inline_safe(mime: &str) -> bool {
+ let essence = mime
+ .split(';')
+ .next()
+ .unwrap_or_default()
+ .trim()
+ .to_ascii_lowercase();
+ match essence.as_str() {
+ "image/svg+xml" | "image/heic" | "image/heif" => false,
+ "application/pdf" | "text/plain" => true,
+ other => {
+ other.starts_with("image/")
+ || other.starts_with("audio/")
+ || other.starts_with("video/")
+ }
+ }
+}
+
+/// The `Content-Type` value for a stored type. Plain text is always sent as UTF-8.
+fn content_type_value(mime: &str) -> String {
+ if mime.trim().eq_ignore_ascii_case("text/plain") {
+ "text/plain; charset=utf-8".into()
+ } else {
+ mime.to_string()
+ }
+}
+
+/// Characters that may appear unescaped in an RFC 5987 `filename*` value (`attr-char`).
+fn is_attr_char(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || b"!#$&+-.^_`|~".contains(&b)
+}
+
+/// The `Content-Disposition` header for a file name: `inline` or `attachment`, a quoted ASCII fallback
+/// and the UTF-8 name percent-encoded per RFC 5987.
+///
+/// The fallback keeps printable ASCII except the quote and the backslash, and turns everything else
+/// (control characters, including CR and LF, non-ASCII letters) into `_`. So no name can close the
+/// quoted string or start a new header line. The `filename*` value encodes every byte that is not an
+/// `attr-char`, which covers the same characters.
+pub fn content_disposition(kind: Disposition, name: &str) -> String {
+ let fallback: String = name
+ .chars()
+ .map(|c| {
+ if c.is_ascii() && (c.is_ascii_graphic() || c == ' ') && c != '"' && c != '\\' {
+ c
+ } else {
+ '_'
+ }
+ })
+ .collect();
+ let fallback = if fallback.trim().is_empty() {
+ "download".to_string()
+ } else {
+ fallback
+ };
+ let mut encoded = String::with_capacity(name.len());
+ for b in name.bytes() {
+ if is_attr_char(b) {
+ encoded.push(char::from(b));
+ } else {
+ encoded.push_str(&format!("%{b:02X}"));
+ }
+ }
+ let kind = match kind {
+ Disposition::Inline => "inline",
+ Disposition::Attachment => "attachment",
+ };
+ format!("{kind}; filename=\"{fallback}\"; filename*=UTF-8''{encoded}")
+}
+
+/// The headers every byte response carries, whatever its status.
+fn common_headers(etag: &str) -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ insert(&mut headers, ETAG, etag);
+ headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes"));
+ headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
+ headers.insert(CONTENT_SECURITY_POLICY, HeaderValue::from_static(BYTES_CSP));
+ headers.insert(
+ HeaderName::from_static("cross-origin-resource-policy"),
+ HeaderValue::from_static("same-origin"),
+ );
+ headers.insert(CACHE_CONTROL, HeaderValue::from_static(BYTES_CACHE));
+ headers
+}
+
+/// Inserts a header whose value is text the code controls. A value that is not a valid header value is
+/// dropped, never sent half-formed; every caller passes ASCII that the code made.
+fn insert(headers: &mut HeaderMap, name: http::HeaderName, value: &str) {
+ if let Ok(value) = HeaderValue::from_str(value) {
+ headers.insert(name, value);
+ }
+}
+
+/// The `416` answer: no body, and the length the client may ask again within.
+fn unsatisfiable(etag: &str, len: u64) -> ByteAnswer {
+ let mut headers = common_headers(etag);
+ insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}"));
+ (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty())
+}
+
+/// Sends the bytes of `source` for the request in `cx`.
+///
+/// `disposition` is the caller's wish. It becomes [`Disposition::Attachment`] unless the type is in
+/// [`inline_safe`]. The body streams from the blob store from the first byte the answer needs. A
+/// missing blob is an error (the row names bytes that are not there), which the router answers as a
+/// `500`.
+pub async fn serve_bytes(
+ cx: &Cx,
+ blobs: &dyn BlobStore,
+ source: &ByteSource<'_>,
+ disposition: Disposition,
+) -> Result {
+ let request = headers(cx);
+ let etag = format!("\"{}\"", source.sha256);
+ let disposition = match disposition {
+ Disposition::Inline if inline_safe(source.mime) => Disposition::Inline,
+ _ => Disposition::Attachment,
+ };
+ let mut answer_headers = common_headers(&etag);
+ insert(
+ &mut answer_headers,
+ CONTENT_DISPOSITION,
+ &content_disposition(disposition, source.name),
+ );
+ insert(
+ &mut answer_headers,
+ CONTENT_TYPE,
+ &content_type_value(source.mime),
+ );
+
+ if none_match_hits(request, &etag) {
+ return Ok((StatusCode::NOT_MODIFIED, answer_headers, Body::empty()));
+ }
+
+ match requested_range(request, &etag, source.size) {
+ Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size)),
+ Ranged::Full => {
+ insert(
+ &mut answer_headers,
+ CONTENT_LENGTH,
+ &source.size.to_string(),
+ );
+ let stream = blobs.open_range(source.blob_key, 0, source.size).await?;
+ Ok((StatusCode::OK, answer_headers, streamed(stream)))
+ }
+ Ranged::Part { start, end } => {
+ let length = end - start + 1;
+ insert(&mut answer_headers, CONTENT_LENGTH, &length.to_string());
+ insert(
+ &mut answer_headers,
+ CONTENT_RANGE,
+ &format!("bytes {start}-{end}/{}", source.size),
+ );
+ let stream = blobs.open_range(source.blob_key, start, length).await?;
+ Ok((
+ StatusCode::PARTIAL_CONTENT,
+ answer_headers,
+ streamed(stream),
+ ))
+ }
+ }
+}
+
+/// Turns a blob stream into a response body. Frames are passed through as they come.
+fn streamed(stream: in_core::blob::BlobStream) -> Body {
+ Body::new(StreamBody::new(stream.map_ok(Frame::data)))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A table of `Range` values for a 100-byte file, with the answer for each.
+ #[test]
+ fn range_table() {
+ use Ranged::*;
+ let cases: &[(&str, Ranged)] = &[
+ ("bytes=0-0", Part { start: 0, end: 0 }),
+ ("bytes=0-99", Part { start: 0, end: 99 }),
+ ("bytes=10-19", Part { start: 10, end: 19 }),
+ // Past the end is clamped, not refused.
+ ("bytes=50-500", Part { start: 50, end: 99 }),
+ ("bytes=90-", Part { start: 90, end: 99 }),
+ ("bytes=-10", Part { start: 90, end: 99 }),
+ // A suffix longer than the file is the whole file.
+ ("bytes=-1000", Part { start: 0, end: 99 }),
+ (" bytes=1 - 2 ", Part { start: 1, end: 2 }),
+ // Several ranges: the whole file.
+ ("bytes=0-1,5-6", Full),
+ // Unsatisfiable or malformed.
+ ("bytes=-0", Unsatisfiable),
+ ("bytes=100-", Unsatisfiable),
+ ("bytes=100-120", Unsatisfiable),
+ ("bytes=20-10", Unsatisfiable),
+ ("bytes=5-4", Unsatisfiable),
+ ("bytes=-", Unsatisfiable),
+ ("bytes=", Unsatisfiable),
+ ("bytes=-x", Unsatisfiable),
+ ("bytes=+1-2", Unsatisfiable),
+ ("bytes=1e2-", Unsatisfiable),
+ ("bytes=--1", Unsatisfiable),
+ ("items=0-1", Unsatisfiable),
+ ("0-1", Unsatisfiable),
+ // Overflow of u64 is refused, not wrapped.
+ ("bytes=18446744073709551616-", Unsatisfiable),
+ ("bytes=0-18446744073709551616", Unsatisfiable),
+ ("bytes=-18446744073709551616", Unsatisfiable),
+ ];
+ for (header, want) in cases {
+ assert_eq!(parse_range(header, 100), *want, "header {header:?}");
+ }
+ }
+
+ #[test]
+ fn an_empty_file_has_no_satisfiable_range() {
+ assert_eq!(parse_range("bytes=0-", 0), Ranged::Unsatisfiable);
+ assert_eq!(parse_range("bytes=-5", 0), Ranged::Unsatisfiable);
+ }
+
+ #[test]
+ fn disposition_is_inline_only_for_safe_types() {
+ assert!(inline_safe("image/png"));
+ assert!(inline_safe("application/pdf"));
+ assert!(inline_safe("text/plain; charset=utf-8"));
+ assert!(inline_safe("video/mp4"));
+ assert!(!inline_safe("image/svg+xml"));
+ assert!(!inline_safe("image/heic"));
+ assert!(!inline_safe("text/html"));
+ assert!(!inline_safe("application/octet-stream"));
+ assert_eq!(
+ content_type_value("text/plain"),
+ "text/plain; charset=utf-8"
+ );
+ }
+
+ /// Quotes, CR and LF, and a non-ASCII name cannot close the quoted string or add a header line.
+ #[test]
+ fn content_disposition_neutralises_quotes_crlf_and_unicode() {
+ let value = content_disposition(Disposition::Attachment, "a\"b\r\nc é.pdf");
+ assert!(!value.contains('\r') && !value.contains('\n'));
+ assert_eq!(
+ value.matches('"').count(),
+ 2,
+ "only the two quotes: {value}"
+ );
+ assert_eq!(
+ value,
+ "attachment; filename=\"a_b__c _.pdf\"; filename*=UTF-8''a%22b%0D%0Ac%20%C3%A9.pdf"
+ );
+ let inline = content_disposition(Disposition::Inline, "plain.txt");
+ assert_eq!(
+ inline,
+ "inline; filename=\"plain.txt\"; filename*=UTF-8''plain.txt"
+ );
+ assert!(content_disposition(Disposition::Attachment, "").contains("filename=\"download\""));
+ }
+
+ #[test]
+ fn a_download_counts_only_when_it_starts_at_byte_zero() {
+ let mut request = HeaderMap::new();
+ assert!(counts_as_download(&request, "ab", 10));
+ request.insert(RANGE, HeaderValue::from_static("bytes=0-3"));
+ assert!(counts_as_download(&request, "ab", 10));
+ request.insert(RANGE, HeaderValue::from_static("bytes=4-"));
+ assert!(!counts_as_download(&request, "ab", 10));
+ request.insert(RANGE, HeaderValue::from_static("bytes=0-3"));
+ request.insert(IF_NONE_MATCH, HeaderValue::from_static("\"ab\""));
+ assert!(!counts_as_download(&request, "ab", 10));
+ }
+}
diff --git a/crates/in-web/src/views/drive.rs b/crates/in-web/src/views/drive.rs
new file mode 100644
index 0000000..4e52de1
--- /dev/null
+++ b/crates/in-web/src/views/drive.rs
@@ -0,0 +1,212 @@
+//! The drive's page parts: breadcrumbs, the listing table with its row menus, the flash line that shows a
+//! notice or a refusal, the quota bar and the small formatters they use.
+//!
+//! Every form here posts with a `csrf` field and a `back` field. `back` is the page to return to; the
+//! handler checks it with `safe_next` before it redirects there. Nothing here runs script: the row menus
+//! are `` elements and the selection is the `form` attribute of a checkbox.
+
+use topcoat::Result;
+use topcoat::view::{View, component, view};
+
+use crate::i18n::Lang;
+use crate::i18n::drive::{DK, d, notice_text, quota_text, refusal_text};
+use in_core::store::files::File;
+use in_core::store::folders::Folder;
+
+/// Formats a byte count for people: `B`, `KB`, `MB`, `GB` or `TB`, one decimal above bytes. Base 1024.
+pub fn size_text(bytes: i64) -> String {
+ const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
+ let mut value = bytes.max(0) as f64;
+ let mut unit = 0;
+ while value >= 1024.0 && unit < UNITS.len() - 1 {
+ value /= 1024.0;
+ unit += 1;
+ }
+ if unit == 0 {
+ format!("{} B", bytes.max(0))
+ } else {
+ format!("{value:.1} {}", UNITS[unit])
+ }
+}
+
+/// Shortens a stored UTC stamp (`2026-10-28T10:00:00.123456789Z`) to `2026-10-28 10:00`.
+pub fn stamp_text(stamp: &str) -> String {
+ stamp.chars().take(16).collect::().replace('T', " ")
+}
+
+/// The quota bar: a `progress` element and its line of text. Used by the shell.
+#[component]
+pub async fn quota_bar(lang: Lang, used: i64, quota: i64) -> Result {
+ let line = quota_text(lang, &size_text(used), &size_text(quota));
+ Ok(view! {
+
+
+ (line)
+
+ })
+}
+
+/// The flash line of a page: a notice from a finished action, or a refusal of one. Unknown words show
+/// nothing.
+#[component]
+pub async fn flash(lang: Lang, notice: &str, refusal: &str) -> Result {
+ let notice_line = notice_text(lang, notice);
+ let refusal_line = refusal_text(lang, refusal);
+ Ok(view! {
+ if let Some(text) = refusal_line {
+
(text)
+ }
+ if let Some(text) = notice_line {
+
(text)
+ }
+ })
+}
+
+/// The breadcrumb trail, top level first. Empty for the top level, which needs no trail.
+#[component]
+pub async fn crumbs(lang: Lang, trail: &[Folder]) -> Result {
+ Ok(view! {
+
+ })
+}
+
+/// The sort links of the listing header: each column header links to the same listing with the sort
+/// key and direction the next click would choose.
+#[component]
+pub async fn sort_link(
+ base: &str,
+ key: &str,
+ label: &str,
+ current: bool,
+ descending: bool,
+) -> Result {
+ // Clicking the active column flips its direction; a new column starts ascending.
+ let next = if current && !descending {
+ "desc"
+ } else {
+ "asc"
+ };
+ let mark = match (current, descending) {
+ (true, false) => " \u{25b2}",
+ (true, true) => " \u{25bc}",
+ _ => "",
+ };
+ let href = format!("{base}sort={key}&dir={next}");
+ Ok(view! {
+ (label)(mark)
+ })
+}
+
+/// The row menu of one item: the actions that an owner may take on it. Each action is a form, so the
+/// menu works without script.
+#[component]
+pub async fn row_menu(
+ lang: Lang,
+ csrf: &str,
+ back: &str,
+ kind: &str,
+ id: &str,
+ name: &str,
+) -> Result {
+ let rename_action = format!("/{kind}s/{id}/rename");
+ let move_page = format!("/{kind}s/{id}/pick");
+ let trash_action = format!("/{kind}s/{id}/trash");
+ Ok(view! {
+
+ (d(lang, DK::Actions))
+
+
+ })
+}
+
+/// A table of folders and files: the rows, their selection box for the bulk trash, and the row menus.
+/// `base` is the listing's own URL without a query, and `query` the sort part already in it.
+#[component]
+pub async fn listing_table(
+ lang: Lang,
+ folders: &[Folder],
+ files: &[File],
+ csrf: &str,
+ back: &str,
+ sort: &str,
+ dir: &str,
+ base: &str,
+) -> Result {
+ let descending = dir == "desc";
+ let name_sort = sort == "name";
+ let size_sort = sort == "size";
+ let modified_sort = sort == "modified";
+ Ok(view! {
+
+ })
+}
diff --git a/crates/in-web/src/views/mod.rs b/crates/in-web/src/views/mod.rs
index a8d50df..c8e63b1 100644
--- a/crates/in-web/src/views/mod.rs
+++ b/crates/in-web/src/views/mod.rs
@@ -7,8 +7,13 @@ use topcoat::Result;
use topcoat::view::{Child, View, component, view};
use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF};
+use crate::auth::Viewer;
use crate::i18n::Lang;
+use crate::i18n::drive::{DK, d};
use crate::i18n::shell::{K, t};
+use crate::views::drive::quota_bar;
+
+pub mod drive;
/// What the shell shows about the signed-in person: the name, the administrator badge, and the CSRF
/// token of the session for the sign-out form.
@@ -19,6 +24,23 @@ pub struct ViewerInfo {
pub is_admin: bool,
/// The session's CSRF token, which the sign-out form sends.
pub csrf: String,
+ /// Bytes the viewer's files use, trashed ones included.
+ pub used: i64,
+ /// The viewer's quota in bytes.
+ pub quota: i64,
+}
+
+impl ViewerInfo {
+ /// What the shell needs to know about a signed-in viewer.
+ pub fn of(viewer: &Viewer) -> Self {
+ Self {
+ name: viewer.member.name.clone(),
+ is_admin: viewer.member.is_admin,
+ csrf: viewer.session.csrf_token.clone(),
+ used: viewer.member.used_bytes,
+ quota: viewer.member.quota_bytes,
+ }
+ }
}
/// The HTML document around a page. `title` is the page's own title; the document title adds the
@@ -50,9 +72,15 @@ pub async fn shell(
(t(lang, K::SkipToContent))"in"
-
+
if let Some(viewer) = viewer {
+ quota_bar(lang: lang, used: viewer.used, quota: viewer.quota)
(viewer.name.as_str())