forge
Explore
Log in

Don't you dare go Hollow

Byte serving with ranges and safe dispositions

Browse files at this commit

a693d7df425fdfc7eab9d4b13f1b190b517de4faAhmet Kaan GümüşParent: bf41400
  • feat
    • byte serving with ranges and safe dispositions
    • drive pages: folders, uploads, rename, move, trash, search, quota
Show full message
✨ feat: byte serving with ranges and safe dispositions; drive pages: folders, uploads, rename, move, trash, search, quota
Cargo.lockmodified+13 -0
@@ -1883,6 +1883,7 @@ dependencies = [
1883 "tracing",1883 "tracing",
1884 "turso",1884 "turso",
1885 "ulid",1885 "ulid",
1886+ "unicode-normalization",
1886 ]1887 ]
1887 1888
1888 [[package]]1889 [[package]]
@@ -1895,12 +1896,15 @@ dependencies = [
1895 "grass",1896 "grass",
1896 "hex",1897 "hex",
1897 "http",1898 "http",
1899+ "http-body",
1900+ "http-body-util",
1898 "in-core",1901 "in-core",
1899 "jsonwebtoken",1902 "jsonwebtoken",
1900 "rand 0.10.3",1903 "rand 0.10.3",
1901 "reqwest",1904 "reqwest",
1902 "serde",1905 "serde",
1903 "serde_json",1906 "serde_json",
1907+ "serde_urlencoded",
1904 "sha2 0.11.1",1908 "sha2 0.11.1",
1905 "tempfile",1909 "tempfile",
1906 "thiserror",1910 "thiserror",
@@ -4963,6 +4967,15 @@ version = "1.0.27"
4963 source = "registry+https://github.com/rust-lang/crates.io-index"4967 source = "registry+https://github.com/rust-lang/crates.io-index"
4964 checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"4968 checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
4965 4969
4970+[[package]]
4971+name = "unicode-normalization"
4972+version = "0.1.26"
4973+source = "registry+https://github.com/rust-lang/crates.io-index"
4974+checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
4975+dependencies = [
4976+ "tinyvec",
4977+]
4978+
4966 [[package]]4979 [[package]]
4967 name = "unicode-width"4980 name = "unicode-width"
4968 version = "0.1.14"4981 version = "0.1.14"
Cargo.tomlmodified+4 -0
@@ -51,6 +51,8 @@ grass = "0.13.4"
51 hex = "0.4.3"51 hex = "0.4.3"
52 hmac = "0.13.0"52 hmac = "0.13.0"
53 http = "1.5.0"53 http = "1.5.0"
54+http-body = "1.1.0"
55+http-body-util = "0.1.5"
54 in-core = { path = "crates/in-core" }56 in-core = { path = "crates/in-core" }
55 ipnet = "2.12.2"57 ipnet = "2.12.2"
56 jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto"] }58 jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto"] }
@@ -59,6 +61,7 @@ rand = "0.10.3"
59 reqwest = { version = "0.13.5", default-features = false, features = ["form", "rustls", "stream"] }61 reqwest = { version = "0.13.5", default-features = false, features = ["form", "rustls", "stream"] }
60 serde = "1.0.229"62 serde = "1.0.229"
61 serde_json = "1.0.154"63 serde_json = "1.0.154"
64+serde_urlencoded = "0.7.1"
62 sha2 = "0.11.1"65 sha2 = "0.11.1"
63 subtle = "2.6.1"66 subtle = "2.6.1"
64 tempfile = "3.27.0"67 tempfile = "3.27.0"
@@ -71,4 +74,5 @@ tracing = "0.1.44"
71 tracing-subscriber = "0.3.23"74 tracing-subscriber = "0.3.23"
72 turso = "0.8.3"75 turso = "0.8.3"
73 ulid = "3.0.0"76 ulid = "3.0.0"
77+unicode-normalization = "0.1.26"
74 78
crates/in-core/Cargo.tomlmodified+1 -0
@@ -29,6 +29,7 @@ toml.workspace = true
29 tracing.workspace = true29 tracing.workspace = true
30 turso.workspace = true30 turso.workspace = true
31 ulid.workspace = true31 ulid.workspace = true
32+unicode-normalization.workspace = true
32 33
33 [dev-dependencies]34 [dev-dependencies]
34 tempfile.workspace = true35 tempfile.workspace = true
crates/in-core/src/names.rsmodified+78 -0
@@ -1,12 +1,64 @@
1 //! Display-name rules for files and folders. A name is shown as typed, but it never carries folders,1 //! Display-name rules for files and folders. A name is shown as typed, but it never carries folders,
2 //! control characters or more than 255 characters. Names are compared exactly; the database enforces2 //! control characters or more than 255 characters. Names are compared exactly; the database enforces
3 //! uniqueness among live items in one folder.3 //! uniqueness among live items in one folder.
4+//!
5+//! Two entry points, one per trust level. [`validate_name`] is for names a person types: it refuses
6+//! what it does not like, so the person sees why. [`upload_name`] is for the file name a browser sends
7+//! with an upload: that name is untrusted, so it is cleaned instead of refused. Both return the name in
8+//! Unicode NFC, so `e` plus a combining accent and the precomposed letter compare equal.
9+
10+use unicode_normalization::UnicodeNormalization;
11+
12+use crate::error::{Error, Result};
4 13
5 /// Longest name in characters (not bytes).14 /// Longest name in characters (not bytes).
6 pub const MAX_NAME_CHARS: usize = 255;15 pub const MAX_NAME_CHARS: usize = 255;
16+/// Longest name in bytes, the limit that [`validate_name`] enforces.
17+pub const MAX_NAME_BYTES: usize = 255;
7 /// Name given to an item whose input has no usable characters left.18 /// Name given to an item whose input has no usable characters left.
8 pub const UNTITLED: &str = "Untitled";19 pub const UNTITLED: &str = "Untitled";
9 20
21+/// Checks a name typed by a person and returns it trimmed and in NFC. Refusals are
22+/// `Invalid` with a fixed reason word: `name_empty`, `name_reserved` (`.` or `..`), `name_too_long`
23+/// (over [`MAX_NAME_BYTES`]) or `name_bad_char` (a `/`, a `\`, a NUL or any other control character).
24+pub fn validate_name(input: &str) -> Result<String> {
25+ let name: String = input.trim().nfc().collect();
26+ if name.is_empty() {
27+ return Err(Error::Invalid("name_empty".into()));
28+ }
29+ if name == "." || name == ".." {
30+ return Err(Error::Invalid("name_reserved".into()));
31+ }
32+ if name.len() > MAX_NAME_BYTES {
33+ return Err(Error::Invalid("name_too_long".into()));
34+ }
35+ if name
36+ .chars()
37+ .any(|c| matches!(c, '/' | '\\') || c.is_control())
38+ {
39+ return Err(Error::Invalid("name_bad_char".into()));
40+ }
41+ Ok(name)
42+}
43+
44+/// Cleans the file name a browser sent with an upload. Path components are dropped, control
45+/// characters removed, the result put in NFC and cut to [`MAX_NAME_BYTES`] at a character boundary.
46+/// Input with nothing usable left becomes [`UNTITLED`]. The result always passes [`validate_name`].
47+pub fn upload_name(client_name: &str) -> String {
48+ let cleaned: String = display_name(client_name).nfc().collect();
49+ let mut out = String::new();
50+ for c in cleaned.chars() {
51+ if out.len() + c.len_utf8() > MAX_NAME_BYTES {
52+ break;
53+ }
54+ out.push(c);
55+ }
56+ if out.is_empty() || out == "." || out == ".." {
57+ return UNTITLED.to_string();
58+ }
59+ out
60+}
61+
10 /// Makes a safe display name from user input. Only the last path component survives, so `a/b/c.txt`62 /// Makes a safe display name from user input. Only the last path component survives, so `a/b/c.txt`
11 /// becomes `c.txt`. Control characters are dropped, surrounding spaces are trimmed, and input with63 /// becomes `c.txt`. Control characters are dropped, surrounding spaces are trimmed, and input with
12 /// nothing left (or `.` / `..`) becomes [`UNTITLED`]. The result is cut to [`MAX_NAME_CHARS`].64 /// nothing left (or `.` / `..`) becomes [`UNTITLED`]. The result is cut to [`MAX_NAME_CHARS`].
@@ -83,6 +135,32 @@ mod tests {
83 }135 }
84 }136 }
85 137
138+ #[test]
139+ fn validate_name_refuses_what_a_person_should_not_type() {
140+ assert_eq!(validate_name(" Trip ").unwrap(), "Trip");
141+ assert!(matches!(validate_name(" "), Err(Error::Invalid(m)) if m == "name_empty"));
142+ assert!(matches!(validate_name(".."), Err(Error::Invalid(m)) if m == "name_reserved"));
143+ assert!(matches!(validate_name("a/b"), Err(Error::Invalid(m)) if m == "name_bad_char"));
144+ assert!(matches!(validate_name("a\\b"), Err(Error::Invalid(m)) if m == "name_bad_char"));
145+ assert!(matches!(validate_name("a\0b"), Err(Error::Invalid(m)) if m == "name_bad_char"));
146+ assert!(
147+ matches!(validate_name(&"a".repeat(256)), Err(Error::Invalid(m)) if m == "name_too_long")
148+ );
149+ // Precomposed and decomposed forms of the same letter come out equal.
150+ assert_eq!(validate_name("e\u{301}").unwrap(), "\u{e9}");
151+ }
152+
153+ #[test]
154+ fn upload_name_cleans_instead_of_refusing() {
155+ assert_eq!(upload_name("..\\..\\evil\u{0}.exe"), "evil.exe");
156+ assert_eq!(upload_name("/etc/passwd"), "passwd");
157+ assert_eq!(upload_name(".."), UNTITLED);
158+ let long = format!("{}.txt", "\u{e9}".repeat(200));
159+ let cut = upload_name(&long);
160+ assert!(cut.len() <= MAX_NAME_BYTES);
161+ assert!(validate_name(&cut).is_ok());
162+ }
163+
86 #[test]164 #[test]
87 fn display_name_cuts_long_names_by_characters() {165 fn display_name_cuts_long_names_by_characters() {
88 let long = "é".repeat(300);166 let long = "é".repeat(300);
crates/in-core/src/store/folders.rsmodified+15 -0
@@ -271,6 +271,21 @@ impl Store {
271 Ok(Listing { folders, files })271 Ok(Listing { folders, files })
272 }272 }
273 273
274+ /// Every live folder of `owner`, sorted by name. The move picker builds the tree from it.
275+ pub async fn live_folders(&self, owner: &str) -> Result<Vec<Folder>> {
276+ let conn = self.read_conn().await;
277+ fetch_all(
278+ &conn,
279+ &format!(
280+ "SELECT {FOLDER_COLS} FROM folders WHERE owner = ?1 AND trashed_at IS NULL \
281+ ORDER BY name, id"
282+ ),
283+ (owner.to_string(),),
284+ map_folder,
285+ )
286+ .await
287+ }
288+
274 /// The chain of folders from the top level down to `folder`, inclusive, for breadcrumbs. The folder289 /// The chain of folders from the top level down to `folder`, inclusive, for breadcrumbs. The folder
275 /// must be owned by `owner`; trashed folders are shown too, so the trash page can use it.290 /// must be owned by `owner`; trashed folders are shown too, so the trash page can use it.
276 pub async fn folder_path(&self, owner: &str, folder: &str) -> Result<Vec<Folder>> {291 pub async fn folder_path(&self, owner: &str, folder: &str) -> Result<Vec<Folder>> {
crates/in-web/Cargo.tomlmodified+3 -0
@@ -14,6 +14,8 @@ path = "src/main.rs"
14 base64.workspace = true14 base64.workspace = true
15 futures-util.workspace = true15 futures-util.workspace = true
16 http.workspace = true16 http.workspace = true
17+http-body.workspace = true
18+http-body-util.workspace = true
17 in-core.workspace = true19 in-core.workspace = true
18 jsonwebtoken.workspace = true20 jsonwebtoken.workspace = true
19 rand.workspace = true21 rand.workspace = true
@@ -31,6 +33,7 @@ tracing.workspace = true
31 tracing-subscriber = { workspace = true, features = ["env-filter"] }33 tracing-subscriber = { workspace = true, features = ["env-filter"] }
32 34
33 [dev-dependencies]35 [dev-dependencies]
36+serde_urlencoded.workspace = true
34 # jsonwebtoken 11 pins ed25519-dalek 2.x; the tests make Ed25519 keys with the same version.37 # jsonwebtoken 11 pins ed25519-dalek 2.x; the tests make Ed25519 keys with the same version.
35 ed25519-dalek = { workspace = true, features = ["pkcs8"] }38 ed25519-dalek = { workspace = true, features = ["pkcs8"] }
36 tempfile.workspace = true39 tempfile.workspace = true
crates/in-web/src/boot.rsmodified+4 -1
@@ -21,11 +21,12 @@ use tokio::net::TcpListener;
21 use tokio::signal::unix::{SignalKind, signal};21 use tokio::signal::unix::{SignalKind, signal};
22 use tokio::sync::watch;22 use tokio::sync::watch;
23 use topcoat::cookie::RouterBuilderCookieExt;23 use topcoat::cookie::RouterBuilderCookieExt;
24-use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService};24+use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService};
25 25
26 use crate::directory;26 use crate::directory;
27 use crate::live::LiveHub;27 use crate::live::LiveHub;
28 use crate::oidc::OidcClient;28 use crate::oidc::OidcClient;
29+use crate::pages::files;
29 use crate::pages::not_found::NotFoundLayer;30 use crate::pages::not_found::NotFoundLayer;
30 use crate::security::{self, SecurityHeaders};31 use crate::security::{self, SecurityHeaders};
31 use crate::state::AppState;32 use crate::state::AppState;
@@ -166,6 +167,8 @@ pub fn router(state: AppState) -> Router {
166 .discover()167 .discover()
167 .app_context(state)168 .app_context(state)
168 .cookies()169 .cookies()
170+ // The upload form streams, but the body limit still caps how much one request may send.
171+ .layer(BodyLimit::max(files::SMALL_UPLOAD_CEILING).at("/files"))
169 .layer(security)172 .layer(security)
170 .layer(NotFoundLayer)173 .layer(NotFoundLayer)
171 .build()174 .build()
crates/in-web/src/i18n/drive.rsadded+317 -0
@@ -0,0 +1,317 @@
1+//! Strings of the drive: listings, folders, uploads, the trash, the move picker, the file page and the
2+//! notices and refusals that Post/Redirect/Get carries back. The keys are exhaustive per language, so a
3+//! missing Turkish text does not compile.
4+//!
5+//! Notices and refusals travel in the query string as fixed words (`?notice=uploaded`). The page maps a
6+//! word to its text here; a word it does not know is shown as nothing, never echoed.
7+
8+use super::Lang;
9+
10+/// One variant per phrase of the drive.
11+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12+pub enum DK {
13+ /// The title of the drive and the first breadcrumb.
14+ Drive,
15+ /// Title of the trash page.
16+ Trash,
17+ /// Title of the search results.
18+ SearchResults,
19+ /// Placeholder of the search box.
20+ SearchPlaceholder,
21+ /// The search button.
22+ Search,
23+ /// Label of the new-folder form.
24+ NewFolder,
25+ /// Label of the folder name field.
26+ FolderName,
27+ /// The button that creates a folder.
28+ Create,
29+ /// The button that uploads.
30+ Upload,
31+ /// Label of the file input.
32+ ChooseFiles,
33+ /// Column heading: name.
34+ Name,
35+ /// Column heading: size.
36+ Size,
37+ /// Column heading: when it was last changed.
38+ Modified,
39+ /// Column heading: kind of item.
40+ Kind,
41+ /// Column heading: row actions.
42+ Actions,
43+ /// Kind label: a folder.
44+ FolderKind,
45+ /// Kind label: a file.
46+ FileKind,
47+ /// The link that downloads a file.
48+ Download,
49+ /// The rename action.
50+ Rename,
51+ /// The save button of the rename form.
52+ Save,
53+ /// The move action.
54+ Move,
55+ /// Trash one item.
56+ TrashItem,
57+ /// Trash every checked item.
58+ TrashSelected,
59+ /// Empty folder heading.
60+ EmptyFolder,
61+ /// Empty folder hint.
62+ EmptyFolderHint,
63+ /// Search with no hits.
64+ NoResults,
65+ /// Trash with nothing in it.
66+ TrashEmpty,
67+ /// Explains what the trash does.
68+ TrashNote,
69+ /// Restore a trashed item.
70+ Restore,
71+ /// Delete a trashed item now.
72+ PurgeNow,
73+ /// Delete everything in the trash.
74+ EmptyTrash,
75+ /// Heading of the move picker.
76+ MoveTo,
77+ /// The top level of the drive in the move picker.
78+ TopLevel,
79+ /// The picker's hint.
80+ PickHint,
81+ /// Cancel a form and go back.
82+ Back,
83+ /// Field label: the place the file is in.
84+ Location,
85+ /// Field label: the MIME type.
86+ MimeType,
87+ /// Field label: when it was uploaded.
88+ Uploaded,
89+ /// Field label: how many times it was downloaded.
90+ Downloads,
91+ /// Link to view the bytes in the browser.
92+ OpenRaw,
93+ /// Accessible name of the breadcrumb trail.
94+ Location2,
95+ /// Label of the quota bar.
96+ Storage,
97+ /// Notice: a folder was created.
98+ NoticeCreated,
99+ /// Notice: a name was changed.
100+ NoticeRenamed,
101+ /// Notice: an item was moved.
102+ NoticeMoved,
103+ /// Notice: items went to the trash.
104+ NoticeTrashed,
105+ /// Notice: items were restored.
106+ NoticeRestored,
107+ /// Notice: items were deleted for good.
108+ NoticePurged,
109+ /// Notice: the trash was emptied.
110+ NoticeEmptied,
111+ /// Notice: the upload finished.
112+ NoticeUploaded,
113+ /// Refusal: a live name is taken.
114+ RefuseNameTaken,
115+ /// Refusal: the quota has no room.
116+ RefuseQuota,
117+ /// Refusal: the file is over the upload limit.
118+ RefuseTooLarge,
119+ /// Refusal: the name is empty.
120+ RefuseNameEmpty,
121+ /// Refusal: the name is `.` or `..`.
122+ RefuseNameReserved,
123+ /// Refusal: the name is too long.
124+ RefuseNameTooLong,
125+ /// Refusal: the name holds a slash, backslash or control character.
126+ RefuseNameBadChar,
127+ /// Refusal: a folder would move into itself.
128+ RefuseCycle,
129+ /// Refusal: the item is not in the trash.
130+ RefuseNotInTrash,
131+ /// Refusal: no free postfix exists.
132+ RefuseTooManyNames,
133+ /// Refusal: nothing else is known.
134+ RefuseGeneric,
135+ /// Refusal: the upload had no file in it.
136+ RefuseNoFile,
137+}
138+
139+/// The text of `key` in `lang`.
140+pub fn d(lang: Lang, key: DK) -> &'static str {
141+ match (key, lang) {
142+ (DK::Drive, Lang::En) => "Drive",
143+ (DK::Drive, Lang::Tr) => "Sürücü",
144+ (DK::Trash, Lang::En) => "Trash",
145+ (DK::Trash, Lang::Tr) => "Çöp",
146+ (DK::SearchResults, Lang::En) => "Search results",
147+ (DK::SearchResults, Lang::Tr) => "Arama sonuçları",
148+ (DK::SearchPlaceholder, Lang::En) => "Search your files",
149+ (DK::SearchPlaceholder, Lang::Tr) => "Dosyalarınızda ara",
150+ (DK::Search, Lang::En) => "Search",
151+ (DK::Search, Lang::Tr) => "Ara",
152+ (DK::NewFolder, Lang::En) => "New folder",
153+ (DK::NewFolder, Lang::Tr) => "Yeni klasör",
154+ (DK::FolderName, Lang::En) => "Folder name",
155+ (DK::FolderName, Lang::Tr) => "Klasör adı",
156+ (DK::Create, Lang::En) => "Create",
157+ (DK::Create, Lang::Tr) => "Oluştur",
158+ (DK::Upload, Lang::En) => "Upload",
159+ (DK::Upload, Lang::Tr) => "Yükle",
160+ (DK::ChooseFiles, Lang::En) => "Files",
161+ (DK::ChooseFiles, Lang::Tr) => "Dosyalar",
162+ (DK::Name, Lang::En) => "Name",
163+ (DK::Name, Lang::Tr) => "Ad",
164+ (DK::Size, Lang::En) => "Size",
165+ (DK::Size, Lang::Tr) => "Boyut",
166+ (DK::Modified, Lang::En) => "Modified",
167+ (DK::Modified, Lang::Tr) => "Değişiklik",
168+ (DK::Kind, Lang::En) => "Kind",
169+ (DK::Kind, Lang::Tr) => "Tür",
170+ (DK::Actions, Lang::En) => "Actions",
171+ (DK::Actions, Lang::Tr) => "İşlemler",
172+ (DK::FolderKind, Lang::En) => "Folder",
173+ (DK::FolderKind, Lang::Tr) => "Klasör",
174+ (DK::FileKind, Lang::En) => "File",
175+ (DK::FileKind, Lang::Tr) => "Dosya",
176+ (DK::Download, Lang::En) => "Download",
177+ (DK::Download, Lang::Tr) => "İndir",
178+ (DK::Rename, Lang::En) => "Rename",
179+ (DK::Rename, Lang::Tr) => "Yeniden adlandır",
180+ (DK::Save, Lang::En) => "Save",
181+ (DK::Save, Lang::Tr) => "Kaydet",
182+ (DK::Move, Lang::En) => "Move",
183+ (DK::Move, Lang::Tr) => "Taşı",
184+ (DK::TrashItem, Lang::En) => "Move to trash",
185+ (DK::TrashItem, Lang::Tr) => "Çöpe taşı",
186+ (DK::TrashSelected, Lang::En) => "Move selected to trash",
187+ (DK::TrashSelected, Lang::Tr) => "Seçilenleri çöpe taşı",
188+ (DK::EmptyFolder, Lang::En) => "This folder is empty.",
189+ (DK::EmptyFolder, Lang::Tr) => "Bu klasör boş.",
190+ (DK::EmptyFolderHint, Lang::En) => "Upload files or create a folder to start.",
191+ (DK::EmptyFolderHint, Lang::Tr) => "Başlamak için dosya yükleyin ya da klasör oluşturun.",
192+ (DK::NoResults, Lang::En) => "Nothing matches your search.",
193+ (DK::NoResults, Lang::Tr) => "Aramanızla eşleşen bir şey yok.",
194+ (DK::TrashEmpty, Lang::En) => "The trash is empty.",
195+ (DK::TrashEmpty, Lang::Tr) => "Çöp boş.",
196+ (DK::TrashNote, Lang::En) => {
197+ "Items stay here until you delete them for good or empty the trash."
198+ }
199+ (DK::TrashNote, Lang::Tr) => {
200+ "Öğeler, siz kalıcı olarak silene ya da çöpü boşaltana kadar burada kalır."
201+ }
202+ (DK::Restore, Lang::En) => "Restore",
203+ (DK::Restore, Lang::Tr) => "Geri yükle",
204+ (DK::PurgeNow, Lang::En) => "Delete for good",
205+ (DK::PurgeNow, Lang::Tr) => "Kalıcı olarak sil",
206+ (DK::EmptyTrash, Lang::En) => "Empty trash",
207+ (DK::EmptyTrash, Lang::Tr) => "Çöpü boşalt",
208+ (DK::MoveTo, Lang::En) => "Move to",
209+ (DK::MoveTo, Lang::Tr) => "Şuraya taşı",
210+ (DK::TopLevel, Lang::En) => "Drive (top level)",
211+ (DK::TopLevel, Lang::Tr) => "Sürücü (en üst düzey)",
212+ (DK::PickHint, Lang::En) => "Choose the folder to move into.",
213+ (DK::PickHint, Lang::Tr) => "Taşınacağı klasörü seçin.",
214+ (DK::Back, Lang::En) => "Back",
215+ (DK::Back, Lang::Tr) => "Geri",
216+ (DK::Location, Lang::En) => "Location",
217+ (DK::Location, Lang::Tr) => "Konum",
218+ (DK::MimeType, Lang::En) => "Type",
219+ (DK::MimeType, Lang::Tr) => "Tür",
220+ (DK::Uploaded, Lang::En) => "Uploaded",
221+ (DK::Uploaded, Lang::Tr) => "Yüklendi",
222+ (DK::Downloads, Lang::En) => "Downloads",
223+ (DK::Downloads, Lang::Tr) => "İndirme",
224+ (DK::OpenRaw, Lang::En) => "Open in the browser",
225+ (DK::OpenRaw, Lang::Tr) => "Tarayıcıda aç",
226+ (DK::Location2, Lang::En) => "Location",
227+ (DK::Location2, Lang::Tr) => "Konum",
228+ (DK::Storage, Lang::En) => "Storage",
229+ (DK::Storage, Lang::Tr) => "Depolama",
230+ (DK::NoticeCreated, Lang::En) => "The folder was created.",
231+ (DK::NoticeCreated, Lang::Tr) => "Klasör oluşturuldu.",
232+ (DK::NoticeRenamed, Lang::En) => "The name was changed.",
233+ (DK::NoticeRenamed, Lang::Tr) => "Ad değiştirildi.",
234+ (DK::NoticeMoved, Lang::En) => "The item was moved.",
235+ (DK::NoticeMoved, Lang::Tr) => "Öğe taşındı.",
236+ (DK::NoticeTrashed, Lang::En) => "The items were moved to the trash.",
237+ (DK::NoticeTrashed, Lang::Tr) => "Öğeler çöpe taşındı.",
238+ (DK::NoticeRestored, Lang::En) => "The items were restored.",
239+ (DK::NoticeRestored, Lang::Tr) => "Öğeler geri yüklendi.",
240+ (DK::NoticePurged, Lang::En) => "The items were deleted for good.",
241+ (DK::NoticePurged, Lang::Tr) => "Öğeler kalıcı olarak silindi.",
242+ (DK::NoticeEmptied, Lang::En) => "The trash was emptied.",
243+ (DK::NoticeEmptied, Lang::Tr) => "Çöp boşaltıldı.",
244+ (DK::NoticeUploaded, Lang::En) => "The upload finished.",
245+ (DK::NoticeUploaded, Lang::Tr) => "Yükleme tamamlandı.",
246+ (DK::RefuseNameTaken, Lang::En) => "An item with this name already exists here.",
247+ (DK::RefuseNameTaken, Lang::Tr) => "Bu konumda bu adla bir öğe zaten var.",
248+ (DK::RefuseQuota, Lang::En) => "There is not enough storage left for this file.",
249+ (DK::RefuseQuota, Lang::Tr) => "Bu dosya için yeterli depolama alanı kalmadı.",
250+ (DK::RefuseTooLarge, Lang::En) => "The file is larger than the upload limit.",
251+ (DK::RefuseTooLarge, Lang::Tr) => "Dosya yükleme sınırından büyük.",
252+ (DK::RefuseNameEmpty, Lang::En) => "The name is empty.",
253+ (DK::RefuseNameEmpty, Lang::Tr) => "Ad boş.",
254+ (DK::RefuseNameReserved, Lang::En) => "This name is not allowed.",
255+ (DK::RefuseNameReserved, Lang::Tr) => "Bu ad kullanılamaz.",
256+ (DK::RefuseNameTooLong, Lang::En) => "The name is too long (255 bytes at most).",
257+ (DK::RefuseNameTooLong, Lang::Tr) => "Ad çok uzun (en fazla 255 bayt).",
258+ (DK::RefuseNameBadChar, Lang::En) => {
259+ "The name contains a slash, a backslash or a control character."
260+ }
261+ (DK::RefuseNameBadChar, Lang::Tr) => {
262+ "Ad eğik çizgi, ters eğik çizgi ya da denetim karakteri içeriyor."
263+ }
264+ (DK::RefuseCycle, Lang::En) => "A folder cannot be moved into itself.",
265+ (DK::RefuseCycle, Lang::Tr) => "Bir klasör kendi içine taşınamaz.",
266+ (DK::RefuseNotInTrash, Lang::En) => "That item is not in the trash.",
267+ (DK::RefuseNotInTrash, Lang::Tr) => "Bu öğe çöpte değil.",
268+ (DK::RefuseTooManyNames, Lang::En) => "Too many items already use this name.",
269+ (DK::RefuseTooManyNames, Lang::Tr) => "Bu adı kullanan çok fazla öğe var.",
270+ (DK::RefuseGeneric, Lang::En) => "The change could not be made.",
271+ (DK::RefuseGeneric, Lang::Tr) => "Değişiklik yapılamadı.",
272+ (DK::RefuseNoFile, Lang::En) => "Choose at least one file.",
273+ (DK::RefuseNoFile, Lang::Tr) => "En az bir dosya seçin.",
274+ }
275+}
276+
277+/// The quota line: how much is used of the quota, both already formatted.
278+pub fn quota_text(lang: Lang, used: &str, quota: &str) -> String {
279+ match lang {
280+ Lang::En => format!("{used} of {quota} used"),
281+ Lang::Tr => format!("{quota} içinden {used} kullanıldı"),
282+ }
283+}
284+
285+/// The text of a notice word from a redirect, or `None` for a word this build does not know.
286+pub fn notice_text(lang: Lang, word: &str) -> Option<&'static str> {
287+ Some(match word {
288+ "created" => d(lang, DK::NoticeCreated),
289+ "renamed" => d(lang, DK::NoticeRenamed),
290+ "moved" => d(lang, DK::NoticeMoved),
291+ "trashed" => d(lang, DK::NoticeTrashed),
292+ "restored" => d(lang, DK::NoticeRestored),
293+ "purged" => d(lang, DK::NoticePurged),
294+ "emptied" => d(lang, DK::NoticeEmptied),
295+ "uploaded" => d(lang, DK::NoticeUploaded),
296+ _ => return None,
297+ })
298+}
299+
300+/// The text of a refusal word from a redirect, or `None` for a word this build does not know.
301+pub fn refusal_text(lang: Lang, word: &str) -> Option<&'static str> {
302+ Some(match word {
303+ "name_taken" => d(lang, DK::RefuseNameTaken),
304+ "quota_exceeded" => d(lang, DK::RefuseQuota),
305+ "too_large" => d(lang, DK::RefuseTooLarge),
306+ "name_empty" => d(lang, DK::RefuseNameEmpty),
307+ "name_reserved" => d(lang, DK::RefuseNameReserved),
308+ "name_too_long" => d(lang, DK::RefuseNameTooLong),
309+ "name_bad_char" => d(lang, DK::RefuseNameBadChar),
310+ "cycle" => d(lang, DK::RefuseCycle),
311+ "not_in_trash" => d(lang, DK::RefuseNotInTrash),
312+ "too_many_names" => d(lang, DK::RefuseTooManyNames),
313+ "no_file" => d(lang, DK::RefuseNoFile),
314+ "generic" => d(lang, DK::RefuseGeneric),
315+ _ => return None,
316+ })
317+}
crates/in-web/src/i18n/mod.rsmodified+1 -0
@@ -7,6 +7,7 @@
7 //! This module decides the language. It does not format sentences with values; those get small7 //! This module decides the language. It does not format sentences with values; those get small
8 //! helper functions next to their keys.8 //! helper functions next to their keys.
9 9
10+pub mod drive;
10 pub mod shell;11 pub mod shell;
11 12
12 use topcoat::context::Cx;13 use topcoat::context::Cx;
crates/in-web/src/i18n/shell.rsmodified+0 -12
@@ -26,8 +26,6 @@ pub enum K {
26 SignedOutBody,26 SignedOutBody,
27 /// The button that starts sign-in.27 /// The button that starts sign-in.
28 SignIn,28 SignIn,
29- /// The placeholder under the greeting until the drive exists.
30- DriveComesNext,
31 /// The button in the user menu that ends the session.29 /// The button in the user menu that ends the session.
32 SignOut,30 SignOut,
33 /// Heading of the page that explains a sign-in that did not finish.31 /// Heading of the page that explains a sign-in that did not finish.
@@ -44,14 +42,6 @@ pub enum K {
44 ProblemDeniedBody,42 ProblemDeniedBody,
45 }43 }
46 44
47-/// The greeting for a signed-in person. The name is inserted as text; the view escapes it.
48-pub fn greeting(lang: Lang, name: &str) -> String {
49- match lang {
50- Lang::En => format!("Hello, {name}."),
51- Lang::Tr => format!("Merhaba, {name}."),
52- }
53-}
54-
55 /// The text of `key` in `lang`.45 /// The text of `key` in `lang`.
56 pub fn t(lang: Lang, key: K) -> &'static str {46 pub fn t(lang: Lang, key: K) -> &'static str {
57 match (key, lang) {47 match (key, lang) {
@@ -75,8 +65,6 @@ pub fn t(lang: Lang, key: K) -> &'static str {
75 (K::SignedOutBody, Lang::Tr) => "Dosyalarınızı açmak için aile hesabınızla oturum açın.",65 (K::SignedOutBody, Lang::Tr) => "Dosyalarınızı açmak için aile hesabınızla oturum açın.",
76 (K::SignIn, Lang::En) => "Sign in",66 (K::SignIn, Lang::En) => "Sign in",
77 (K::SignIn, Lang::Tr) => "Oturum aç",67 (K::SignIn, Lang::Tr) => "Oturum aç",
78- (K::DriveComesNext, Lang::En) => "The drive comes next. Your files will appear here.",
79- (K::DriveComesNext, Lang::Tr) => "Sürücü sıradaki adım. Dosyalarınız burada görünecek.",
80 (K::SignOut, Lang::En) => "Sign out",68 (K::SignOut, Lang::En) => "Sign out",
81 (K::SignOut, Lang::Tr) => "Oturumu kapat",69 (K::SignOut, Lang::Tr) => "Oturumu kapat",
82 (K::ProblemFailedTitle, Lang::En) => "Sign-in did not finish",70 (K::ProblemFailedTitle, Lang::En) => "Sign-in did not finish",
crates/in-web/src/main.rsmodified+1 -0
@@ -14,6 +14,7 @@ mod live;
14 mod oidc;14 mod oidc;
15 mod pages;15 mod pages;
16 mod security;16 mod security;
17+mod serve_bytes;
17 mod state;18 mod state;
18 mod views;19 mod views;
19 20
crates/in-web/src/pages/drive.rsadded+702 -0
@@ -0,0 +1,702 @@
1+//! The drive's listing pages: the root (`/`), a folder (`/f/{id}`), search (`/search`), the live stream
2+//! that refreshes an open listing, the folder writes (create, rename, move, trash) and the folder move
3+//! picker. The file pages live in `files.rs`, the trash in `trash.rs`.
4+//!
5+//! Authorization: each item is loaded by id and passed to `authz::authorize`. A refusal to see the item
6+//! is `404`, so a foreign or missing id looks the same as no item at all. A refusal to change an item the
7+//! viewer can see is `403`. Every write checks its CSRF token before it touches anything, and every write
8+//! ends in a redirect (Post/Redirect/Get) back to the page named in the form's `back` field, which must
9+//! pass `safe_next`. Failures come back as a `refusal` word, successes as a `notice` word.
10+
11+use std::collections::{HashMap, HashSet};
12+use std::fmt::Write as _;
13+
14+use in_core::authz::{self, Action, Actor, Denied, Grant, Target};
15+use in_core::error::Error as CoreError;
16+use in_core::names::validate_name;
17+use in_core::store::files::File;
18+use in_core::store::folders::{Folder, Listing};
19+use serde::Deserialize;
20+use topcoat::Result;
21+use topcoat::context::{Cx, app_context};
22+use topcoat::router::content::Form;
23+use topcoat::router::error::{SeeOther, forbidden, not_found, see_other};
24+use topcoat::router::response::Response;
25+use topcoat::router::{page, parse_query_params, path_param_segment, route};
26+use topcoat::view::{View, component, view};
27+
28+use crate::auth::{Viewer, require_csrf, require_member, safe_next};
29+use crate::i18n::Lang;
30+use crate::i18n::drive::{DK, d, refusal_text};
31+use crate::i18n::lang;
32+use crate::live::{Topic, stream_changes};
33+use crate::oidc::percent_encode;
34+use crate::state::AppState;
35+use crate::views::drive::{crumbs, flash, listing_table};
36+use crate::views::{ViewerInfo, empty_state, shell};
37+
38+/// How many search hits each kind shows.
39+const SEARCH_LIMIT: usize = 100;
40+
41+/// The query of a listing page. Every field is optional; unknown ones are ignored.
42+#[derive(Debug, Default, Deserialize)]
43+#[serde(default)]
44+pub struct ListQuery {
45+ /// Sort key: `name` (default), `size` or `modified`.
46+ pub sort: String,
47+ /// `asc` (default) or `desc`.
48+ pub dir: String,
49+ /// The search text, on `/search` only.
50+ pub q: String,
51+ /// A notice word from a finished action.
52+ pub notice: String,
53+ /// A refusal word from a refused action.
54+ pub refusal: String,
55+}
56+
57+/// The column a listing is sorted by.
58+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59+pub enum SortKey {
60+ /// By name (the default).
61+ Name,
62+ /// By size. Folders have none, so they keep name order.
63+ Size,
64+ /// By the last change.
65+ Modified,
66+}
67+
68+impl SortKey {
69+ /// The key a query asks for. Anything unknown is the default.
70+ pub fn of(raw: &str) -> Self {
71+ match raw {
72+ "size" => SortKey::Size,
73+ "modified" => SortKey::Modified,
74+ _ => SortKey::Name,
75+ }
76+ }
77+
78+ /// The word the key has in a URL.
79+ pub fn word(self) -> &'static str {
80+ match self {
81+ SortKey::Name => "name",
82+ SortKey::Size => "size",
83+ SortKey::Modified => "modified",
84+ }
85+ }
86+}
87+
88+/// Everything a listing page shows, built before the page is rendered.
89+pub struct Board {
90+ /// The page title and the heading of the listing.
91+ pub heading: String,
92+ /// The folders above the current one, top level first.
93+ pub trail: Vec<Folder>,
94+ /// The current folder, `None` at the drive root and on search.
95+ pub folder: Option<String>,
96+ /// The search text, empty for a listing.
97+ pub query: String,
98+ /// The folders shown, sorted.
99+ pub folders: Vec<Folder>,
100+ /// The files shown, sorted.
101+ pub files: Vec<File>,
102+ /// The sort column.
103+ pub sort: SortKey,
104+ /// Whether the sort is descending.
105+ pub descending: bool,
106+ /// The session's CSRF token for the forms.
107+ pub csrf: String,
108+ /// The page the forms return to.
109+ pub back: String,
110+ /// A notice word from the query, if any.
111+ pub notice: String,
112+ /// A refusal word from the query, if any.
113+ pub refusal: String,
114+ /// The stream that refreshes the listing, if it is live.
115+ pub live: Option<String>,
116+ /// The start of the sort links: the listing's URL, ending in `?` or `&`.
117+ pub base: String,
118+}
119+
120+/// The language of a viewer: the stored override, else the `im` language, else the request.
121+pub fn viewer_lang(cx: &Cx, viewer: &Viewer) -> Lang {
122+ lang(
123+ cx,
124+ Some(
125+ viewer
126+ .member
127+ .locale_override
128+ .as_deref()
129+ .unwrap_or(viewer.member.locale.as_str()),
130+ ),
131+ )
132+}
133+
134+/// Maps a refusal of the drive's authorization to the HTTP answer. A listing or a view that is refused
135+/// is always `404`; a change that is refused to someone who can see the item is `403`.
136+pub fn check(viewer: &Viewer, owner: &str, trashed: bool, action: Action) -> Result<()> {
137+ let target = Target {
138+ owner,
139+ trashed,
140+ inside_link: false,
141+ };
142+ let actor = Actor::Member {
143+ sub: &viewer.member.sub,
144+ is_admin: viewer.member.is_admin,
145+ };
146+ match authz::authorize(actor, target, Grant::None, action) {
147+ Ok(()) => Ok(()),
148+ Err(Denied::NotFound) => Err(not_found().into()),
149+ Err(Denied::Forbidden) if matches!(action, Action::List | Action::View) => {
150+ Err(not_found().into())
151+ }
152+ Err(Denied::Forbidden) => Err(forbidden().into()),
153+ }
154+}
155+
156+/// A live folder by id, after the authorization for `action`. A missing id is `404`.
157+pub async fn folder_for(
158+ state: &AppState,
159+ viewer: &Viewer,
160+ id: &str,
161+ action: Action,
162+) -> Result<Folder> {
163+ let folder = state.store.folder(id).await?.ok_or_else(not_found)?;
164+ check(viewer, &folder.owner, folder.trashed_at.is_some(), action)?;
165+ Ok(folder)
166+}
167+
168+/// The folder a form names in its `parent` (or `folder`) field, checked for `Write`. A blank field is
169+/// the top level and gives `None`.
170+pub async fn optional_folder(
171+ state: &AppState,
172+ viewer: &Viewer,
173+ raw: &str,
174+) -> Result<Option<String>> {
175+ let raw = raw.trim();
176+ if raw.is_empty() {
177+ return Ok(None);
178+ }
179+ let folder = folder_for(state, viewer, raw, Action::Write).await?;
180+ Ok(Some(folder.id))
181+}
182+
183+/// The refusal word of an error the person can act on: a name taken, a quota, a bad name, a cycle. Other
184+/// errors have none and are server failures or missing items.
185+pub fn refusal_word(error: &CoreError) -> Option<String> {
186+ match error {
187+ CoreError::Conflict(word) | CoreError::Invalid(word) | CoreError::Forbidden(word) => {
188+ Some(if refusal_text(Lang::En, word).is_some() {
189+ word.clone()
190+ } else {
191+ "generic".to_owned()
192+ })
193+ }
194+ _ => None,
195+ }
196+}
197+
198+/// The return target of a form: its `back` field when that is a safe path, else the given default.
199+pub fn back_or(raw: &str, default: &str) -> String {
200+ safe_next(raw.trim()).unwrap_or(default).to_owned()
201+}
202+
203+/// Adds a `key=value` pair to a path's query. The values used here are fixed words, so no escaping is
204+/// needed.
205+pub fn with_param(path: &str, key: &str, value: &str) -> String {
206+ let sep = if path.contains('?') { '&' } else { '?' };
207+ format!("{path}{sep}{key}={value}")
208+}
209+
210+/// The redirect after a successful change, carrying a notice word.
211+pub fn done(back: &str, notice: &str) -> SeeOther {
212+ see_other(with_param(back, "notice", notice))
213+}
214+
215+/// The answer to a failed change. A refusal the person can act on goes back to `back` with a refusal
216+/// word; a missing item is `404`; anything else is a server error.
217+pub fn refused(back: &str, error: CoreError) -> Result<SeeOther> {
218+ if matches!(error, CoreError::NotFound) {
219+ return Err(not_found().into());
220+ }
221+ match refusal_word(&error) {
222+ Some(word) => Ok(see_other(with_param(back, "refusal", &word))),
223+ None => Err(error.into()),
224+ }
225+}
226+
227+/// Tells the owner's open pages that their drive changed.
228+pub fn changed(state: &AppState, owner: &str) {
229+ state.live.bump(&Topic::Drive(owner.to_owned()));
230+}
231+
232+/// Sorts a listing: folders first, then files; each group by the key, ties by id. Descending reverses
233+/// the whole order inside each group.
234+pub fn sort_listing(listing: &mut Listing, key: SortKey, descending: bool) {
235+ listing.folders.sort_by(|a, b| {
236+ let by_key = match key {
237+ SortKey::Modified => a.updated_at.cmp(&b.updated_at),
238+ _ => a.name.cmp(&b.name),
239+ };
240+ by_key.then_with(|| a.id.cmp(&b.id))
241+ });
242+ listing.files.sort_by(|a, b| {
243+ let by_key = match key {
244+ SortKey::Name => a.name.cmp(&b.name),
245+ SortKey::Size => a.size.cmp(&b.size),
246+ SortKey::Modified => a.updated_at.cmp(&b.updated_at),
247+ };
248+ by_key.then_with(|| a.id.cmp(&b.id))
249+ });
250+ if descending {
251+ listing.folders.reverse();
252+ listing.files.reverse();
253+ }
254+}
255+
256+/// The folders of a tree, depth first, each with its depth, in the order the picker shows them. The
257+/// folder `skip` and everything beneath it are left out, so a folder cannot be picked into itself.
258+pub fn tree_rows(folders: &[Folder], skip: Option<&str>) -> Vec<(usize, Folder)> {
259+ let ids: HashSet<&str> = folders.iter().map(|f| f.id.as_str()).collect();
260+ let mut children: HashMap<&str, Vec<&Folder>> = HashMap::new();
261+ let mut roots: Vec<&Folder> = Vec::new();
262+ for folder in folders {
263+ match folder.parent_id.as_deref() {
264+ Some(parent) if ids.contains(parent) => {
265+ children.entry(parent).or_default().push(folder);
266+ }
267+ _ => roots.push(folder),
268+ }
269+ }
270+ let mut out = Vec::new();
271+ let mut stack: Vec<(usize, &Folder)> = roots.iter().rev().map(|f| (0, *f)).collect();
272+ while let Some((depth, folder)) = stack.pop() {
273+ if Some(folder.id.as_str()) == skip {
274+ continue;
275+ }
276+ out.push((depth, folder.clone()));
277+ if let Some(kids) = children.get(folder.id.as_str()) {
278+ for kid in kids.iter().rev() {
279+ stack.push((depth + 1, kid));
280+ }
281+ }
282+ }
283+ out
284+}
285+
286+/// Builds the listing of a folder (or of the drive root) for a viewer.
287+pub async fn folder_board(
288+ state: &AppState,
289+ viewer: &Viewer,
290+ folder: Option<String>,
291+ query: &ListQuery,
292+ lang: Lang,
293+) -> Result<Board> {
294+ let owner = viewer.member.sub.clone();
295+ let (heading, trail) = match folder.as_deref() {
296+ None => (d(lang, DK::Drive).to_owned(), Vec::new()),
297+ Some(id) => {
298+ let row = folder_for(state, viewer, id, Action::List).await?;
299+ let trail = state.store.folder_path(&owner, id).await?;
300+ (row.name.clone(), trail)
301+ }
302+ };
303+ let mut listing = state.store.list_children(&owner, folder.as_deref()).await?;
304+ let sort = SortKey::of(&query.sort);
305+ let descending = query.dir == "desc";
306+ sort_listing(&mut listing, sort, descending);
307+ let (base, live, back) = match folder.as_deref() {
308+ None => ("/?".to_owned(), "/live/drive".to_owned(), "/".to_owned()),
309+ Some(id) => (
310+ format!("/f/{id}?"),
311+ format!("/live/drive?folder={id}"),
312+ format!("/f/{id}"),
313+ ),
314+ };
315+ Ok(Board {
316+ heading,
317+ trail,
318+ folder,
319+ query: String::new(),
320+ folders: listing.folders,
321+ files: listing.files,
322+ sort,
323+ descending,
324+ csrf: viewer.session.csrf_token.clone(),
325+ back,
326+ notice: query.notice.clone(),
327+ refusal: query.refusal.clone(),
328+ live: Some(live),
329+ base,
330+ })
331+}
332+
333+/// Builds the search results of a viewer's own items. `q` must not be empty.
334+pub async fn search_board(
335+ state: &AppState,
336+ viewer: &Viewer,
337+ query: &ListQuery,
338+ lang: Lang,
339+) -> Result<Board> {
340+ let q = query.q.trim().to_owned();
341+ let mut listing = state
342+ .store
343+ .search(&viewer.member.sub, &q, SEARCH_LIMIT)
344+ .await?;
345+ let sort = SortKey::of(&query.sort);
346+ let descending = query.dir == "desc";
347+ sort_listing(&mut listing, sort, descending);
348+ let enc = percent_encode(&q);
349+ Ok(Board {
350+ heading: d(lang, DK::SearchResults).to_owned(),
351+ trail: Vec::new(),
352+ folder: None,
353+ query: q,
354+ folders: listing.folders,
355+ files: listing.files,
356+ sort,
357+ descending,
358+ csrf: viewer.session.csrf_token.clone(),
359+ back: format!("/search?q={enc}"),
360+ notice: query.notice.clone(),
361+ refusal: query.refusal.clone(),
362+ live: None,
363+ base: format!("/search?q={enc}&"),
364+ })
365+}
366+
367+/// The drive root's listing for a signed-in viewer. The start page uses it.
368+pub async fn root_board(
369+ state: &AppState,
370+ viewer: &Viewer,
371+ query: &ListQuery,
372+ lang: Lang,
373+) -> Result<Board> {
374+ folder_board(state, viewer, None, query, lang).await
375+}
376+
377+/// The main content of a listing page: the heading, the trail, the flash line, the forms that create
378+/// and upload, and the table. Used by the drive pages and by the start page for a signed-in viewer.
379+#[component]
380+pub async fn drive_board(lang: Lang, board: &Board) -> Result<impl View> {
381+ let parent = board.folder.clone().unwrap_or_default();
382+ let in_search = !board.query.is_empty();
383+ let empty = board.folders.is_empty() && board.files.is_empty();
384+ let search_value = board.query.clone();
385+ Ok(view! {
386+ <section class="drive" data-live=(board.live.as_deref())>
387+ <h1>(board.heading.as_str())</h1>
388+ if board.folder.is_some() {
389+ crumbs(lang: lang, trail: &board.trail)
390+ }
391+ flash(lang: lang, notice: board.notice.as_str(), refusal: board.refusal.as_str())
392+ <div class="toolbar">
393+ <form method="get" action="/search" class="inline-form" role="search">
394+ <label class="sr-only" for="drive-search">(d(lang, DK::SearchPlaceholder))</label>
395+ <input id="drive-search" type="search" name="q" value=(search_value.as_str()) placeholder=(d(lang, DK::SearchPlaceholder))>
396+ <button class="button" type="submit">(d(lang, DK::Search))</button>
397+ </form>
398+ if !in_search {
399+ <form method="post" action="/folders" class="inline-form">
400+ <input type="hidden" name="csrf" value=(board.csrf.as_str())>
401+ <input type="hidden" name="back" value=(board.back.as_str())>
402+ <input type="hidden" name="parent" value=(parent.as_str())>
403+ <label class="sr-only" for="new-folder">(d(lang, DK::FolderName))</label>
404+ <input id="new-folder" name="name" maxlength="255" required="" placeholder=(d(lang, DK::NewFolder))>
405+ <button class="button" type="submit">(d(lang, DK::Create))</button>
406+ </form>
407+ <form method="post" action="/files" enctype="multipart/form-data" class="inline-form">
408+ <input type="hidden" name="csrf" value=(board.csrf.as_str())>
409+ <input type="hidden" name="back" value=(board.back.as_str())>
410+ <input type="hidden" name="folder" value=(parent.as_str())>
411+ <label class="sr-only" for="upload-files">(d(lang, DK::ChooseFiles))</label>
412+ <input id="upload-files" type="file" name="files" multiple="" required="">
413+ <button class="button primary" type="submit">(d(lang, DK::Upload))</button>
414+ </form>
415+ }
416+ </div>
417+ if empty {
418+ if in_search {
419+ empty_state(title: d(lang, DK::NoResults))
420+ } else {
421+ empty_state(title: d(lang, DK::EmptyFolder), <p>(d(lang, DK::EmptyFolderHint))</p>)
422+ }
423+ } else {
424+ listing_table(lang: lang, folders: &board.folders, files: &board.files, csrf: board.csrf.as_str(), back: board.back.as_str(), sort: board.sort.word(), dir: if board.descending { "desc" } else { "asc" }, base: board.base.as_str())
425+ }
426+ </section>
427+ })
428+}
429+
430+/// The query of the live stream: the folder to follow, empty for the root.
431+#[derive(Debug, Default, Deserialize)]
432+#[serde(default)]
433+struct LiveQuery {
434+ folder: String,
435+}
436+
437+/// A fingerprint of what a listing shows: every row's id, name, size and last change. Equal text means
438+/// the page would look the same, so the stream stays quiet.
439+fn fingerprint(listing: &Listing) -> String {
440+ let mut text = String::new();
441+ for folder in &listing.folders {
442+ let _ = writeln!(
443+ text,
444+ "d|{}|{}|{}",
445+ folder.id, folder.name, folder.updated_at
446+ );
447+ }
448+ for file in &listing.files {
449+ let _ = writeln!(
450+ text,
451+ "f|{}|{}|{}|{}",
452+ file.id, file.name, file.size, file.updated_at
453+ );
454+ }
455+ text
456+}
457+
458+/// `GET /f/{folder_id}`: one folder's listing.
459+#[page("/f/{folder_id}")]
460+async fn folder_page(cx: &Cx) -> Result<impl View> {
461+ let state = app_context::<AppState>(cx);
462+ let viewer = require_member(cx).await?;
463+ let lang = viewer_lang(cx, &viewer);
464+ let folder_id = path_param_segment(cx, "folder_id").to_owned();
465+ let query: ListQuery = parse_query_params(cx).unwrap_or_default();
466+ let board = folder_board(state, &viewer, Some(folder_id), &query, lang).await?;
467+ let info = ViewerInfo::of(&viewer);
468+ Ok(view! {
469+ shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info),
470+ drive_board(lang: lang, board: &board)
471+ )
472+ })
473+}
474+
475+/// `GET /search?q=`: the viewer's own items whose names contain the text. Blank text goes to the root.
476+#[page("/search")]
477+async fn search_page(cx: &Cx) -> Result<impl View> {
478+ let state = app_context::<AppState>(cx);
479+ let viewer = require_member(cx).await?;
480+ let lang = viewer_lang(cx, &viewer);
481+ let query: ListQuery = parse_query_params(cx).unwrap_or_default();
482+ if query.q.trim().is_empty() {
483+ return Err(see_other("/").into());
484+ }
485+ let board = search_board(state, &viewer, &query, lang).await?;
486+ let info = ViewerInfo::of(&viewer);
487+ Ok(view! {
488+ shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info),
489+ drive_board(lang: lang, board: &board)
490+ )
491+ })
492+}
493+
494+/// `GET /live/drive?folder=`: the stream that tells an open listing to refresh. It sends a data-less
495+/// `changed` event when the rows change, and ends when the session is gone or the folder is.
496+#[route(GET "/live/drive")]
497+async fn drive_live(cx: &Cx, query: Option<Form<LiveQuery>>) -> Result<Response> {
498+ let state = app_context::<AppState>(cx);
499+ let viewer = require_member(cx).await?;
500+ let folder = query
501+ .map(|Form(query)| query.folder)
502+ .filter(|folder| !folder.trim().is_empty());
503+ if let Some(id) = folder.as_deref() {
504+ folder_for(state, &viewer, id, Action::List).await?;
505+ }
506+ let owner = viewer.member.sub.clone();
507+ let token_hash = viewer.session.token_hash.clone();
508+ let store = state.store.clone();
509+ let topics = vec![Topic::Drive(owner.clone())];
510+ stream_changes(cx, &state.live, &topics, move || {
511+ let store = store.clone();
512+ let owner = owner.clone();
513+ let folder = folder.clone();
514+ let token_hash = token_hash.clone();
515+ async move {
516+ // A signed-out session ends the stream, so it stops showing the drive.
517+ if store.session_by_token_hash(&token_hash).await?.is_none() {
518+ return Err(not_found().into());
519+ }
520+ let listing = store.list_children(&owner, folder.as_deref()).await?;
521+ Ok(fingerprint(&listing))
522+ }
523+ })
524+ .await
525+}
526+
527+/// The form of `POST /folders`: the CSRF token, the return page, the parent (blank for the top level)
528+/// and the name.
529+#[derive(Debug, Default, Deserialize)]
530+#[serde(default)]
531+struct CreateFolderForm {
532+ csrf: String,
533+ back: String,
534+ parent: String,
535+ name: String,
536+}
537+
538+/// `POST /folders`: creates a folder. A taken name gets the next postfix from the store.
539+#[route(POST "/folders")]
540+async fn create_folder(cx: &Cx, Form(form): Form<CreateFolderForm>) -> Result<SeeOther> {
541+ let state = app_context::<AppState>(cx);
542+ let viewer = require_csrf(cx, &form.csrf).await?;
543+ let back = back_or(&form.back, "/");
544+ let parent = optional_folder(state, &viewer, &form.parent).await?;
545+ let name = match validate_name(&form.name) {
546+ Ok(name) => name,
547+ Err(error) => return refused(&back, error),
548+ };
549+ match state
550+ .store
551+ .create_folder(&viewer.member.sub, parent.as_deref(), &name)
552+ .await
553+ {
554+ Ok(_) => {
555+ changed(state, &viewer.member.sub);
556+ Ok(done(&back, "created"))
557+ }
558+ Err(error) => refused(&back, error),
559+ }
560+}
561+
562+/// The form of the folder and file rename, trash and move actions.
563+#[derive(Debug, Default, Deserialize)]
564+#[serde(default)]
565+pub struct ItemForm {
566+ /// The CSRF token of the session.
567+ pub csrf: String,
568+ /// The page to return to.
569+ pub back: String,
570+ /// A new name, for a rename.
571+ pub name: String,
572+ /// The destination folder, for a move. Blank is the top level.
573+ pub parent: String,
574+}
575+
576+/// `POST /folders/{id}/rename`.
577+#[route(POST "/folders/{id}/rename")]
578+async fn rename_folder(cx: &Cx, Form(form): Form<ItemForm>) -> Result<SeeOther> {
579+ let state = app_context::<AppState>(cx);
580+ let viewer = require_csrf(cx, &form.csrf).await?;
581+ let id = path_param_segment(cx, "id").to_owned();
582+ let back = back_or(&form.back, "/");
583+ folder_for(state, &viewer, &id, Action::Write).await?;
584+ let name = match validate_name(&form.name) {
585+ Ok(name) => name,
586+ Err(error) => return refused(&back, error),
587+ };
588+ match state
589+ .store
590+ .rename_folder(&viewer.member.sub, &id, &name)
591+ .await
592+ {
593+ Ok(_) => {
594+ changed(state, &viewer.member.sub);
595+ Ok(done(&back, "renamed"))
596+ }
597+ Err(error) => refused(&back, error),
598+ }
599+}
600+
601+/// `POST /folders/{id}/move`: the parent in the form is the new place (blank for the top level). A move
602+/// into the folder itself or its subtree is refused as a cycle.
603+#[route(POST "/folders/{id}/move")]
604+async fn move_folder(cx: &Cx, Form(form): Form<ItemForm>) -> Result<SeeOther> {
605+ let state = app_context::<AppState>(cx);
606+ let viewer = require_csrf(cx, &form.csrf).await?;
607+ let id = path_param_segment(cx, "id").to_owned();
608+ let back = back_or(&form.back, "/");
609+ folder_for(state, &viewer, &id, Action::Write).await?;
610+ let parent = optional_folder(state, &viewer, &form.parent).await?;
611+ match state
612+ .store
613+ .move_folder(&viewer.member.sub, &id, parent.as_deref())
614+ .await
615+ {
616+ Ok(_) => {
617+ changed(state, &viewer.member.sub);
618+ Ok(done(&back, "moved"))
619+ }
620+ Err(error) => refused(&back, error),
621+ }
622+}
623+
624+/// `POST /folders/{id}/trash`: moves the folder and everything in it to the trash.
625+#[route(POST "/folders/{id}/trash")]
626+async fn trash_folder(cx: &Cx, Form(form): Form<ItemForm>) -> Result<SeeOther> {
627+ let state = app_context::<AppState>(cx);
628+ let viewer = require_csrf(cx, &form.csrf).await?;
629+ let id = path_param_segment(cx, "id").to_owned();
630+ let back = back_or(&form.back, "/");
631+ folder_for(state, &viewer, &id, Action::Write).await?;
632+ match state.store.trash_folder(&viewer.member.sub, &id).await {
633+ Ok(()) => {
634+ changed(state, &viewer.member.sub);
635+ Ok(done(&back, "trashed"))
636+ }
637+ Err(error) => refused(&back, error),
638+ }
639+}
640+
641+/// `GET /folders/{id}/pick`: the move picker of a folder. Every live folder of the viewer is a button; the
642+/// folder itself and its subtree are left out.
643+#[page("/folders/{id}/pick")]
644+async fn pick_folder(cx: &Cx) -> Result<impl View> {
645+ let state = app_context::<AppState>(cx);
646+ let viewer = require_member(cx).await?;
647+ let lang = viewer_lang(cx, &viewer);
648+ let id = path_param_segment(cx, "id").to_owned();
649+ let folder = folder_for(state, &viewer, &id, Action::Write).await?;
650+ let all = state.store.live_folders(&viewer.member.sub).await?;
651+ let rows = tree_rows(&all, Some(&id));
652+ let action = format!("/folders/{id}/move");
653+ let back = format!("/f/{id}");
654+ let csrf = viewer.session.csrf_token.clone();
655+ let info = ViewerInfo::of(&viewer);
656+ let title = d(lang, DK::MoveTo);
657+ Ok(view! {
658+ shell(title: title, lang: lang, viewer: Some(&info),
659+ pick_body(lang: lang, subject: folder.name.as_str(), action: action.as_str(), csrf: csrf.as_str(), back: back.as_str(), rows: &rows)
660+ )
661+ })
662+}
663+
664+/// The move picker's content: a button per destination, each a form that posts the move. Shared with the
665+/// file picker.
666+#[component]
667+pub async fn pick_body(
668+ lang: Lang,
669+ subject: &str,
670+ action: &str,
671+ csrf: &str,
672+ back: &str,
673+ rows: &[(usize, Folder)],
674+) -> Result<impl View> {
675+ Ok(view! {
676+ <section class="drive pick">
677+ <h1>(d(lang, DK::MoveTo)) " \u{201c}" (subject) "\u{201d}"</h1>
678+ <p class="muted">(d(lang, DK::PickHint))</p>
679+ <ul class="pick-list">
680+ <li>
681+ <form method="post" action=(action) class="inline-form">
682+ <input type="hidden" name="csrf" value=(csrf)>
683+ <input type="hidden" name="back" value=(back)>
684+ <input type="hidden" name="parent" value="">
685+ <button class="button ghost" type="submit">(d(lang, DK::TopLevel))</button>
686+ </form>
687+ </li>
688+ for (depth, folder) in rows {
689+ <li>
690+ <form method="post" action=(action) class="inline-form">
691+ <input type="hidden" name="csrf" value=(csrf)>
692+ <input type="hidden" name="back" value=(back)>
693+ <input type="hidden" name="parent" value=(folder.id.as_str())>
694+ <button class="button ghost" type="submit">(format!("{}{}", "\u{2003}".repeat(*depth), folder.name))</button>
695+ </form>
696+ </li>
697+ }
698+ </ul>
699+ <p><a class="button" href=(back)>(d(lang, DK::Back))</a></p>
700+ </section>
701+ })
702+}
crates/in-web/src/pages/files.rsadded+620 -0
@@ -0,0 +1,620 @@
1+//! The file pages: the upload (`POST /files`), the file page (`/file/{id}`), its bytes
2+//! (`/file/{id}/download` and `/file/{id}/raw`, both through `serve_bytes`), the file writes (rename,
3+//! move, trash) and the file move picker.
4+//!
5+//! An upload streams. Each file part goes to a staging file under `data_dir/tmp` while its SHA-256 and
6+//! its first bytes are taken; the sniffed type decides the MIME type, never the uploader's claim. The quota
7+//! is checked before the bytes reach the blob store, so a refused file leaves nothing behind. The store
8+//! checks the quota again inside the insert transaction, which is what makes parallel uploads safe. If the
9+//! insert fails after the bytes were stored, the bytes are deleted, since no row names them.
10+
11+use in_core::authz::Action;
12+use in_core::names::{upload_name, validate_name};
13+use in_core::quota;
14+use in_core::sniff::sniff;
15+use in_core::staging::{Staged, StagedFile};
16+use in_core::store::files::{File, NewFile, files_blob_key};
17+use in_core::store::new_id;
18+use topcoat::Result;
19+use topcoat::context::{Cx, app_context};
20+use topcoat::router::content::Form;
21+use topcoat::router::content::multipart::{Field, Multipart};
22+use topcoat::router::error::{SeeOther, bad_request, forbidden, not_found, see_other};
23+use topcoat::router::page;
24+use topcoat::router::request::headers;
25+use topcoat::router::{parse_query_params, path_param_segment, route};
26+use topcoat::view::{View, component, view};
27+
28+use crate::auth::{Viewer, require_csrf, require_member};
29+use crate::i18n::Lang;
30+use crate::i18n::drive::{DK, d};
31+use crate::pages::drive::{
32+ ItemForm, ListQuery, back_or, changed, check, done, optional_folder, pick_body, refusal_word,
33+ refused, tree_rows, viewer_lang, with_param,
34+};
35+use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, counts_as_download, serve_bytes};
36+use crate::state::AppState;
37+use crate::views::drive::{flash, size_text, stamp_text};
38+use crate::views::{ViewerInfo, shell};
39+
40+/// How many leading bytes of an upload the sniffer reads. Enough for every signature it knows.
41+const SNIFF_BYTES: usize = 8192;
42+
43+/// The upload limit a fresh instance uses: 64 MiB per file, unless the settings say otherwise.
44+pub const DEFAULT_SMALL_UPLOAD: u64 = 64 * 1024 * 1024;
45+
46+/// The most a single upload request may carry in total, in bytes. It is the body limit of `POST /files`;
47+/// a per-file limit above it has no effect.
48+pub const SMALL_UPLOAD_CEILING: usize = 1024 * 1024 * 1024;
49+
50+/// The settings key of the per-file upload limit, in bytes.
51+pub const SMALL_UPLOAD_SETTING: &str = "small_upload_bytes";
52+
53+/// Longest text a form field may carry. Ids and names are far shorter; the cap stops a huge field from
54+/// being buffered.
55+const MAX_FIELD_BYTES: usize = 2048;
56+
57+/// The per-file upload limit in force now: the setting when it holds a sane number, else the default.
58+/// It is never above [`SMALL_UPLOAD_CEILING`].
59+pub async fn upload_limit(state: &AppState) -> Result<u64> {
60+ let setting = state.store.get_setting(SMALL_UPLOAD_SETTING).await?;
61+ let limit = setting
62+ .and_then(|value| value.trim().parse::<u64>().ok())
63+ .unwrap_or(DEFAULT_SMALL_UPLOAD);
64+ Ok(limit.clamp(1, SMALL_UPLOAD_CEILING as u64))
65+}
66+
67+/// A live or trashed file by id, after the authorization for `action`. A missing id is `404`.
68+pub async fn file_for(state: &AppState, viewer: &Viewer, id: &str, action: Action) -> Result<File> {
69+ let file = state.store.file(id).await?.ok_or_else(not_found)?;
70+ check(viewer, &file.owner, file.trashed_at.is_some(), action)?;
71+ Ok(file)
72+}
73+
74+/// Reads a small text field. A field longer than `cap` bytes is a bad request.
75+async fn read_text(field: &mut Field<'_>, cap: usize) -> Result<String> {
76+ let mut bytes = Vec::new();
77+ while let Some(chunk) = field.chunk().await? {
78+ if bytes.len() + chunk.len() > cap {
79+ return Err(bad_request("field too long").into());
80+ }
81+ bytes.extend_from_slice(&chunk);
82+ }
83+ String::from_utf8(bytes).map_err(|_| bad_request("field is not UTF-8").into())
84+}
85+
86+/// Streams one file part into the store. `Ok(Err(word))` is a refusal the person can read (the quota, the
87+/// size limit); `Err` is a server failure. Nothing is left behind on either path.
88+async fn store_one(
89+ state: &AppState,
90+ owner: &str,
91+ folder: Option<&str>,
92+ client_name: &str,
93+ field: &mut Field<'_>,
94+ limit: u64,
95+) -> Result<std::result::Result<File, String>> {
96+ let mut staged = StagedFile::create(&state.config.data_dir, limit).await?;
97+ let mut prefix: Vec<u8> = Vec::with_capacity(SNIFF_BYTES);
98+ loop {
99+ let chunk = match field.chunk().await {
100+ Ok(Some(chunk)) => chunk,
101+ Ok(None) => break,
102+ Err(error) => {
103+ staged.abort().await;
104+ return Err(error);
105+ }
106+ };
107+ if prefix.len() < SNIFF_BYTES {
108+ let take = (SNIFF_BYTES - prefix.len()).min(chunk.len());
109+ prefix.extend_from_slice(&chunk[..take]);
110+ }
111+ if let Err(error) = staged.write(&chunk).await {
112+ staged.abort().await;
113+ return match refusal_word(&error) {
114+ Some(word) => Ok(Err(word)),
115+ None => Err(error.into()),
116+ };
117+ }
118+ }
119+ let Staged { path, size, sha256 } = staged.finish().await?;
120+ let size = i64::try_from(size).unwrap_or(i64::MAX);
121+ // The quota is checked before the bytes move, so a refused file never reaches the blob store.
122+ let member = state.store.member(owner).await?.ok_or_else(not_found)?;
123+ let room = quota::headroom(member.quota_bytes, member.used_bytes, 0);
124+ if !quota::fits(size, room) {
125+ let _ = tokio::fs::remove_file(&path).await;
126+ return Ok(Err("quota_exceeded".to_owned()));
127+ }
128+ let id = new_id();
129+ let key = files_blob_key(&id);
130+ if let Err(error) = state.blobs.put_file(&key, &path).await {
131+ let _ = tokio::fs::remove_file(&path).await;
132+ return Err(error.into());
133+ }
134+ let new = NewFile {
135+ id,
136+ owner: owner.to_owned(),
137+ folder: folder.map(str::to_owned),
138+ name: upload_name(client_name),
139+ mime: sniff(&prefix),
140+ size,
141+ sha256,
142+ staged_claims: 0,
143+ };
144+ match state.store.insert_file(new).await {
145+ Ok(file) => Ok(Ok(file)),
146+ Err(error) => {
147+ // No row names these bytes now, so they go.
148+ let _ = state.blobs.delete(&key).await;
149+ match refusal_word(&error) {
150+ Some(word) => Ok(Err(word)),
151+ None => Err(error.into()),
152+ }
153+ }
154+ }
155+}
156+
157+/// `POST /files`: the upload. The form's fields come in this order: `csrf` (checked before anything
158+/// else), `back`, `folder`, then one or more `files` parts. A file part with no name (an empty file
159+/// input) is skipped.
160+#[route(POST "/files")]
161+async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<SeeOther> {
162+ let state = app_context::<AppState>(cx);
163+ let limit = upload_limit(state).await?;
164+ let mut viewer: Option<Viewer> = None;
165+ let mut back = String::new();
166+ let mut folder_raw = String::new();
167+ let mut folder: Option<Option<String>> = None;
168+ let mut stored = 0usize;
169+ let mut refusal: Option<String> = None;
170+ while let Some(mut field) = multipart.next_field().await? {
171+ let name = field.name().unwrap_or_default().to_owned();
172+ match name.as_str() {
173+ "csrf" => {
174+ let token = read_text(&mut field, MAX_FIELD_BYTES).await?;
175+ viewer = Some(require_csrf(cx, &token).await?);
176+ }
177+ "back" => back = read_text(&mut field, MAX_FIELD_BYTES).await?,
178+ "folder" => folder_raw = read_text(&mut field, MAX_FIELD_BYTES).await?,
179+ "files" => {
180+ let Some(owner) = viewer.as_ref() else {
181+ return Err(forbidden().into());
182+ };
183+ let client_name = field.file_name().unwrap_or_default().to_owned();
184+ if client_name.is_empty() {
185+ continue;
186+ }
187+ if folder.is_none() {
188+ folder = Some(optional_folder(state, owner, &folder_raw).await?);
189+ }
190+ let target = folder.clone().flatten();
191+ match store_one(
192+ state,
193+ &owner.member.sub,
194+ target.as_deref(),
195+ &client_name,
196+ &mut field,
197+ limit,
198+ )
199+ .await?
200+ {
201+ Ok(_) => stored += 1,
202+ Err(word) => {
203+ refusal = Some(word);
204+ break;
205+ }
206+ }
207+ }
208+ _ => {}
209+ }
210+ }
211+ let Some(owner) = viewer else {
212+ return Err(forbidden().into());
213+ };
214+ let default_back = if folder_raw.trim().is_empty() {
215+ "/".to_owned()
216+ } else {
217+ format!("/f/{}", folder_raw.trim())
218+ };
219+ let back = back_or(&back, &default_back);
220+ if stored > 0 {
221+ changed(state, &owner.member.sub);
222+ }
223+ if let Some(word) = refusal {
224+ return Ok(see_other(with_param(&back, "refusal", &word)));
225+ }
226+ if stored == 0 {
227+ return Ok(see_other(with_param(&back, "refusal", "no_file")));
228+ }
229+ Ok(done(&back, "uploaded"))
230+}
231+
232+/// The file page's content: its details, the links to its bytes and, for the owner of a live file, the
233+/// actions.
234+#[component]
235+pub async fn file_body(
236+ lang: Lang,
237+ file: &File,
238+ location: &str,
239+ csrf: &str,
240+ writable: bool,
241+ notice: &str,
242+ refusal: &str,
243+) -> Result<impl View> {
244+ let back = format!("/file/{}", file.id);
245+ let move_page = format!("/files/{}/pick", file.id);
246+ let rename_action = format!("/files/{}/rename", file.id);
247+ let trash_action = format!("/files/{}/trash", file.id);
248+ let download_url = format!("/file/{}/download", file.id);
249+ let raw_url = format!("/file/{}/raw", file.id);
250+ Ok(view! {
251+ <section class="drive file-page">
252+ <h1>(file.name.as_str())</h1>
253+ flash(lang: lang, notice: notice, refusal: refusal)
254+ <dl class="details">
255+ <dt>(d(lang, DK::Location))</dt><dd>(location)</dd>
256+ <dt>(d(lang, DK::Size))</dt><dd>(size_text(file.size))</dd>
257+ <dt>(d(lang, DK::MimeType))</dt><dd>(file.mime.as_str())</dd>
258+ <dt>(d(lang, DK::Uploaded))</dt><dd>(stamp_text(&file.created_at))</dd>
259+ <dt>(d(lang, DK::Downloads))</dt><dd>(file.download_count.to_string())</dd>
260+ </dl>
261+ <p class="actions">
262+ <a class="button primary" href=(download_url)>(d(lang, DK::Download))</a>
263+ <a class="button" href=(raw_url)>(d(lang, DK::OpenRaw))</a>
264+ </p>
265+ if writable {
266+ <form method="post" action=(rename_action) class="inline-form">
267+ <input type="hidden" name="csrf" value=(csrf)>
268+ <input type="hidden" name="back" value=(back.as_str())>
269+ <label for="rename-file">(d(lang, DK::Rename))</label>
270+ <input id="rename-file" name="name" value=(file.name.as_str()) maxlength="255" required="">
271+ <button class="button" type="submit">(d(lang, DK::Save))</button>
272+ </form>
273+ <p class="actions">
274+ <a class="button" href=(move_page)>(d(lang, DK::Move))</a>
275+ <form method="post" action=(trash_action) class="inline-form">
276+ <input type="hidden" name="csrf" value=(csrf)>
277+ <input type="hidden" name="back" value="/">
278+ <button class="button danger" type="submit">(d(lang, DK::TrashItem))</button>
279+ </form>
280+ </p>
281+ }
282+ </section>
283+ })
284+}
285+
286+/// `GET /file/{id}`: the file page.
287+#[page("/file/{id}")]
288+async fn file_page(cx: &Cx) -> Result<impl View> {
289+ let state = app_context::<AppState>(cx);
290+ let viewer = require_member(cx).await?;
291+ let lang = viewer_lang(cx, &viewer);
292+ let id = path_param_segment(cx, "id").to_owned();
293+ let file = file_for(state, &viewer, &id, Action::View).await?;
294+ let location = match file.folder_id.as_deref() {
295+ Some(folder) => match state.store.folder(folder).await? {
296+ Some(row) if row.trashed_at.is_none() => row.name,
297+ _ => d(lang, DK::Drive).to_owned(),
298+ },
299+ None => d(lang, DK::Drive).to_owned(),
300+ };
301+ let writable =
302+ file.trashed_at.is_none() && check(&viewer, &file.owner, false, Action::Write).is_ok();
303+ let query: ListQuery = parse_query_params(cx).unwrap_or_default();
304+ let info = ViewerInfo::of(&viewer);
305+ let csrf = viewer.session.csrf_token.clone();
306+ let title = file.name.clone();
307+ Ok(view! {
308+ shell(title: title.as_str(), lang: lang, viewer: Some(&info),
309+ 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())
310+ )
311+ })
312+}
313+
314+/// Serves the bytes of a file the viewer may act on with `action`.
315+async fn serve_file(
316+ cx: &Cx,
317+ action: Action,
318+ disposition: Disposition,
319+ count: bool,
320+) -> Result<ByteAnswer> {
321+ let state = app_context::<AppState>(cx);
322+ let viewer = require_member(cx).await?;
323+ let id = path_param_segment(cx, "id").to_owned();
324+ let file = file_for(state, &viewer, &id, action).await?;
325+ let size = u64::try_from(file.size).unwrap_or(0);
326+ if count && counts_as_download(headers(cx), &file.sha256, size) {
327+ state.store.record_download(&file.id).await?;
328+ }
329+ let source = ByteSource {
330+ blob_key: &file.blob_key,
331+ size,
332+ sha256: &file.sha256,
333+ mime: &file.mime,
334+ name: &file.name,
335+ };
336+ serve_bytes(cx, state.blobs.as_ref(), &source, disposition).await
337+}
338+
339+/// `GET /file/{id}/download`: the bytes as a download. Counts one download when it starts at byte 0.
340+#[route(GET "/file/{id}/download")]
341+async fn download_bytes(cx: &Cx) -> Result<ByteAnswer> {
342+ serve_file(cx, Action::Download, Disposition::Attachment, true).await
343+}
344+
345+/// `GET /file/{id}/raw`: the bytes to show in the browser. The type decides whether they are shown or
346+/// saved.
347+#[route(GET "/file/{id}/raw")]
348+async fn raw_bytes(cx: &Cx) -> Result<ByteAnswer> {
349+ serve_file(cx, Action::View, Disposition::Inline, false).await
350+}
351+
352+/// `POST /files/{id}/rename`.
353+#[route(POST "/files/{id}/rename")]
354+async fn rename_file(cx: &Cx, Form(form): Form<ItemForm>) -> Result<SeeOther> {
355+ let state = app_context::<AppState>(cx);
356+ let viewer = require_csrf(cx, &form.csrf).await?;
357+ let id = path_param_segment(cx, "id").to_owned();
358+ let back = back_or(&form.back, "/");
359+ file_for(state, &viewer, &id, Action::Write).await?;
360+ let name = match validate_name(&form.name) {
361+ Ok(name) => name,
362+ Err(error) => return refused(&back, error),
363+ };
364+ match state
365+ .store
366+ .rename_file(&viewer.member.sub, &id, &name)
367+ .await
368+ {
369+ Ok(_) => {
370+ changed(state, &viewer.member.sub);
371+ Ok(done(&back, "renamed"))
372+ }
373+ Err(error) => refused(&back, error),
374+ }
375+}
376+
377+/// `POST /files/{id}/move`: the folder in the form is the new place (blank for the top level).
378+#[route(POST "/files/{id}/move")]
379+async fn move_file(cx: &Cx, Form(form): Form<ItemForm>) -> Result<SeeOther> {
380+ let state = app_context::<AppState>(cx);
381+ let viewer = require_csrf(cx, &form.csrf).await?;
382+ let id = path_param_segment(cx, "id").to_owned();
383+ let back = back_or(&form.back, "/");
384+ file_for(state, &viewer, &id, Action::Write).await?;
385+ let parent = optional_folder(state, &viewer, &form.parent).await?;
386+ match state
387+ .store
388+ .move_file(&viewer.member.sub, &id, parent.as_deref())
389+ .await
390+ {
391+ Ok(_) => {
392+ changed(state, &viewer.member.sub);
393+ Ok(done(&back, "moved"))
394+ }
395+ Err(error) => refused(&back, error),
396+ }
397+}
398+
399+/// `POST /files/{id}/trash`.
400+#[route(POST "/files/{id}/trash")]
401+async fn trash_file(cx: &Cx, Form(form): Form<ItemForm>) -> Result<SeeOther> {
402+ let state = app_context::<AppState>(cx);
403+ let viewer = require_csrf(cx, &form.csrf).await?;
404+ let id = path_param_segment(cx, "id").to_owned();
405+ let back = back_or(&form.back, "/");
406+ file_for(state, &viewer, &id, Action::Write).await?;
407+ match state.store.trash_file(&viewer.member.sub, &id).await {
408+ Ok(()) => {
409+ changed(state, &viewer.member.sub);
410+ Ok(done(&back, "trashed"))
411+ }
412+ Err(error) => refused(&back, error),
413+ }
414+}
415+
416+/// `GET /files/{id}/pick`: the move picker of a file. The folders are listed as in the folder picker.
417+#[page("/files/{id}/pick")]
418+async fn pick_file(cx: &Cx) -> Result<impl View> {
419+ let state = app_context::<AppState>(cx);
420+ let viewer = require_member(cx).await?;
421+ let lang = viewer_lang(cx, &viewer);
422+ let id = path_param_segment(cx, "id").to_owned();
423+ let file = file_for(state, &viewer, &id, Action::Write).await?;
424+ let all = state.store.live_folders(&viewer.member.sub).await?;
425+ let rows = tree_rows(&all, None);
426+ let action = format!("/files/{id}/move");
427+ let back = format!("/file/{id}");
428+ let csrf = viewer.session.csrf_token.clone();
429+ let info = ViewerInfo::of(&viewer);
430+ let title = d(lang, DK::MoveTo);
431+ Ok(view! {
432+ shell(title: title, lang: lang, viewer: Some(&info),
433+ pick_body(lang: lang, subject: file.name.as_str(), action: action.as_str(), csrf: csrf.as_str(), back: back.as_str(), rows: &rows)
434+ )
435+ })
436+}
437+
438+#[cfg(test)]
439+mod tests {
440+ use super::*;
441+ use crate::auth::{SESSION_COOKIE, SESSION_TTL};
442+ use crate::boot::{router, test_state};
443+ use http::Request;
444+ use http::header::{CONTENT_TYPE, COOKIE};
445+ use in_core::quota::DEFAULT_MEMBER_QUOTA;
446+ use in_core::store::members::MemberFields;
447+ use in_core::store::new_id;
448+ use in_core::store::sessions::NewSession;
449+ use in_core::time::stamp_after;
450+ use in_core::token::{generate_token, hash_token};
451+ use topcoat::router::Body;
452+
453+ /// A member with a session: returns the session cookie value.
454+ async fn signed_in(state: &AppState, sub: &str, quota: i64) -> String {
455+ state
456+ .store
457+ .upsert_member_from_claims(
458+ &MemberFields {
459+ sub: sub.into(),
460+ email: format!("{sub}@example.test"),
461+ name: sub.into(),
462+ is_admin: false,
463+ locale: "en".into(),
464+ zoneinfo: "UTC".into(),
465+ picture_version: 0,
466+ im_updated_at: String::new(),
467+ },
468+ DEFAULT_MEMBER_QUOTA,
469+ )
470+ .await
471+ .expect("member");
472+ state.store.set_quota(sub, quota).await.expect("quota");
473+ let token = generate_token();
474+ state
475+ .store
476+ .create_session(NewSession {
477+ sub: sub.into(),
478+ token_hash: hash_token(&token),
479+ csrf_token: format!("csrf-{sub}"),
480+ im_sid: format!("im-{sub}"),
481+ expires_at: stamp_after(SESSION_TTL),
482+ ip: None,
483+ user_agent: None,
484+ id_token_sealed: None,
485+ })
486+ .await
487+ .expect("session");
488+ token
489+ }
490+
491+ /// A file stored the way an upload stores it, owned by `owner`.
492+ async fn stored_file(state: &AppState, owner: &str, name: &str, bytes: &[u8]) -> File {
493+ let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20)
494+ .await
495+ .expect("staging");
496+ staged.write(bytes).await.expect("write");
497+ let Staged { path, sha256, .. } = staged.finish().await.expect("finish");
498+ let id = new_id();
499+ state
500+ .blobs
501+ .put_file(&files_blob_key(&id), &path)
502+ .await
503+ .expect("blob");
504+ state
505+ .store
506+ .insert_file(NewFile {
507+ id,
508+ owner: owner.into(),
509+ folder: None,
510+ name: name.into(),
511+ mime: sniff(bytes),
512+ size: bytes.len() as i64,
513+ sha256,
514+ staged_claims: 0,
515+ })
516+ .await
517+ .expect("row")
518+ }
519+
520+ /// A multipart body with one part per entry: `(field, file name, content)`.
521+ fn multipart_body(boundary: &str, parts: &[(&str, Option<&str>, &[u8])]) -> Vec<u8> {
522+ let mut body = Vec::new();
523+ for (field, file, content) in parts {
524+ body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
525+ match file {
526+ Some(file) => body.extend_from_slice(
527+ format!(
528+ "Content-Disposition: form-data; name=\"{field}\"; filename=\"{file}\"\r\n\
529+ Content-Type: application/octet-stream\r\n\r\n"
530+ )
531+ .as_bytes(),
532+ ),
533+ None => body.extend_from_slice(
534+ format!("Content-Disposition: form-data; name=\"{field}\"\r\n\r\n").as_bytes(),
535+ ),
536+ }
537+ body.extend_from_slice(content);
538+ body.extend_from_slice(b"\r\n");
539+ }
540+ body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
541+ body
542+ }
543+
544+ #[tokio::test]
545+ async fn another_members_file_id_is_not_found_on_its_bytes() {
546+ let (_dir, state) = test_state().await;
547+ let owner_token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await;
548+ let other_token = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await;
549+ let file = stored_file(&state, "ann", "notes.txt", b"hello").await;
550+ let path = format!("/file/{}/download", file.id);
551+
552+ let as_other = Request::get(&path)
553+ .header(COOKIE, format!("{SESSION_COOKIE}={other_token}"))
554+ .body(Body::empty())
555+ .expect("request");
556+ let response = router(state.clone()).handle(as_other).await;
557+ assert_eq!(response.status(), 404, "a foreign id must look missing");
558+
559+ let as_owner = Request::get(&path)
560+ .header(COOKIE, format!("{SESSION_COOKIE}={owner_token}"))
561+ .body(Body::empty())
562+ .expect("request");
563+ let response = router(state.clone()).handle(as_owner).await;
564+ assert_eq!(response.status(), 200);
565+ assert!(
566+ response.headers()["content-disposition"]
567+ .to_str()
568+ .expect("ascii")
569+ .starts_with("attachment;"),
570+ "a download is an attachment"
571+ );
572+ }
573+
574+ #[tokio::test]
575+ async fn an_upload_over_quota_is_refused_and_leaves_no_blob_behind() {
576+ let (dir, state) = test_state().await;
577+ let token = signed_in(&state, "ann", 10).await;
578+ let boundary = "in-test-boundary";
579+ let body = multipart_body(
580+ boundary,
581+ &[
582+ ("csrf", None, b"csrf-ann"),
583+ ("back", None, b"/"),
584+ ("folder", None, b""),
585+ ("files", Some("../../big.bin"), &[7u8; 100]),
586+ ],
587+ );
588+ let request = Request::post("/files")
589+ .header(COOKIE, format!("{SESSION_COOKIE}={token}"))
590+ .header(
591+ CONTENT_TYPE,
592+ format!("multipart/form-data; boundary={boundary}"),
593+ )
594+ .body(Body::from(body))
595+ .expect("request");
596+ let response = router(state.clone()).handle(request).await;
597+
598+ assert_eq!(response.status(), 303);
599+ let location = response.headers()["location"].to_str().expect("ascii");
600+ assert!(
601+ location.ends_with("refusal=quota_exceeded"),
602+ "got {location}"
603+ );
604+ assert!(
605+ state.blobs.list("files/").await.expect("list").is_empty(),
606+ "a refused file must not reach the blob store"
607+ );
608+ let staged_left = std::fs::read_dir(dir.path().join("tmp"))
609+ .map(|entries| entries.count())
610+ .unwrap_or(0);
611+ assert_eq!(staged_left, 0, "the staging file is removed");
612+ let member = state
613+ .store
614+ .member("ann")
615+ .await
616+ .expect("lookup")
617+ .expect("member");
618+ assert_eq!(member.used_bytes, 0, "nothing was charged");
619+ }
620+}
crates/in-web/src/pages/home.rsmodified+26 -29
@@ -1,52 +1,49 @@
1-//! The start page. Signed out, it offers sign-in. Signed in, it greets the person; the drive that1+//! The start page (`/`). Signed out, it offers sign-in. Signed in, it is the drive root: the same listing
2-//! follows it is not built yet, so it says so.2+//! as `/f/{id}` for the top level, built by `drive.rs`.
3 3
4 use topcoat::Result;4 use topcoat::Result;
5-use topcoat::context::Cx;5+use topcoat::context::{Cx, app_context};
6-use topcoat::router::page;6+use topcoat::router::{page, parse_query_params};
7 use topcoat::view::{View, view};7 use topcoat::view::{View, view};
8 8
9 use crate::auth::current_member;9 use crate::auth::current_member;
10 use crate::i18n::lang;10 use crate::i18n::lang;
11-use crate::i18n::shell::{K, greeting, t};11+use crate::i18n::shell::{K, t};
12+use crate::pages::drive::{ListQuery, drive_board, root_board, viewer_lang};
13+use crate::state::AppState;
12 use crate::views::{ViewerInfo, shell};14 use crate::views::{ViewerInfo, shell};
13 15
14 /// `GET /`.16 /// `GET /`.
15 #[page("/")]17 #[page("/")]
16 async fn home(cx: &Cx) -> Result<impl View> {18 async fn home(cx: &Cx) -> Result<impl View> {
19+ let state = app_context::<AppState>(cx);
17 let viewer = current_member(cx).await?;20 let viewer = current_member(cx).await?;
18- // The language follows the stored override, else the one `im` reports, else the request.21+ let query: ListQuery = parse_query_params(cx).unwrap_or_default();
19- let lang = lang(22+ let lang = match &viewer {
20- cx,23+ Some(viewer) => viewer_lang(cx, viewer),
21- viewer.as_ref().map(|viewer| {24+ None => lang(cx, None),
22- viewer25+ };
23- .member26+ let info = viewer.as_ref().map(ViewerInfo::of);
24- .locale_override27+ let board = match &viewer {
25- .as_deref()28+ Some(viewer) => Some(root_board(state, viewer, &query, lang).await?),
26- .unwrap_or(viewer.member.locale.as_str())29+ None => None,
27- }),30+ };
28- );31+ let heading = match &board {
29- let info = viewer.map(|viewer| ViewerInfo {32+ Some(board) => board.heading.clone(),
30- name: viewer.member.name,
31- is_admin: viewer.member.is_admin,
32- csrf: viewer.session.csrf_token,
33- });
34- let heading = match &info {
35- Some(info) => greeting(lang, &info.name),
36 None => t(lang, K::SignedOutTitle).to_owned(),33 None => t(lang, K::SignedOutTitle).to_owned(),
37 };34 };
38 Ok(view! {35 Ok(view! {
39 shell(title: heading.as_str(), lang: lang, viewer: info.as_ref(),36 shell(title: heading.as_str(), lang: lang, viewer: info.as_ref(),
40- <section class="card">37+ if let Some(board) = &board {
41- <p class="kicker">"in"</p>38+ drive_board(lang: lang, board: board)
42- <h1>(heading.as_str())</h1>
43- if info.is_some() {
44- <p>(t(lang, K::DriveComesNext))</p>
45 } else {39 } else {
40+ <section class="card">
41+ <p class="kicker">"in"</p>
42+ <h1>(t(lang, K::SignedOutTitle))</h1>
46 <p>(t(lang, K::SignedOutBody))</p>43 <p>(t(lang, K::SignedOutBody))</p>
47 <a class="button primary" href="/auth/login">(t(lang, K::SignIn))</a>44 <a class="button primary" href="/auth/login">(t(lang, K::SignIn))</a>
45+ </section>
48 }46 }
49- </section>
50 )47 )
51 })48 })
52 }49 }
crates/in-web/src/pages/mod.rsmodified+3 -0
@@ -1,7 +1,10 @@
1 //! The pages and the page-level layers. One file per page or per closely related group of pages.1 //! The pages and the page-level layers. One file per page or per closely related group of pages.
2 2
3 pub mod backchannel;3 pub mod backchannel;
4+pub mod drive;
5+pub mod files;
4 pub mod home;6 pub mod home;
5 pub mod not_found;7 pub mod not_found;
6 pub mod photo;8 pub mod photo;
7 pub mod sign_in;9 pub mod sign_in;
10+pub mod trash;
crates/in-web/src/pages/trash.rsadded+321 -0
@@ -0,0 +1,321 @@
1+//! The trash: `/trash` lists what the viewer trashed, and the forms under it restore, delete for good or
2+//! empty it. `POST /items/trash` moves a set of live items to the trash in one request.
3+//!
4+//! Only the owner acts on trashed items (`authz`: restore and purge). The purge routes return the blob keys
5+//! the store released; they are deleted after the row is gone, and a failed delete is logged, not shown,
6+//! because the row no longer names those bytes. A bulk trash checks every item before it changes one, so a
7+//! request that names a foreign or missing item changes nothing.
8+
9+use in_core::authz::Action;
10+use in_core::error::Error as CoreError;
11+use in_core::store::folders::Listing;
12+use in_core::store::trash::ItemKind;
13+use serde::Deserialize;
14+use topcoat::Result;
15+use topcoat::context::{Cx, app_context};
16+use topcoat::router::content::Form;
17+use topcoat::router::error::SeeOther;
18+use topcoat::router::{page, parse_query_params, route};
19+use topcoat::view::{View, component, view};
20+
21+use crate::auth::{require_csrf, require_member};
22+use crate::i18n::Lang;
23+use crate::i18n::drive::{DK, d};
24+use crate::pages::drive::{ListQuery, back_or, changed, done, folder_for, refused, viewer_lang};
25+use crate::pages::files::file_for;
26+use crate::state::AppState;
27+use crate::views::drive::{flash, size_text, stamp_text};
28+use crate::views::{ViewerInfo, empty_state, shell};
29+
30+/// The form of the trash actions: a CSRF token, the return page, and the item kind and id for a single
31+/// item.
32+#[derive(Debug, Default, Deserialize)]
33+#[serde(default)]
34+pub struct TrashForm {
35+ /// The CSRF token of the session.
36+ pub csrf: String,
37+ /// The page to return to.
38+ pub back: String,
39+ /// `file` or `folder`.
40+ pub kind: String,
41+ /// The item's id.
42+ pub id: String,
43+}
44+
45+/// The kind word of a trash form, or `None` for anything else.
46+fn kind_of(word: &str) -> Option<ItemKind> {
47+ match word {
48+ "file" => Some(ItemKind::File),
49+ "folder" => Some(ItemKind::Folder),
50+ _ => None,
51+ }
52+}
53+
54+/// Deletes the blobs the store released. A failure is logged: the rows that named them are gone.
55+async fn release(state: &AppState, keys: Vec<String>) {
56+ for key in keys {
57+ if let Err(error) = state.blobs.delete(&key).await {
58+ tracing::error!(error = %error, "trash: a released blob could not be deleted");
59+ }
60+ }
61+}
62+
63+/// The trash page's content: the trashed roots, with a restore and a delete button for each, and the
64+/// button that empties the trash.
65+#[component]
66+pub async fn trash_body(
67+ lang: Lang,
68+ listing: &Listing,
69+ csrf: &str,
70+ notice: &str,
71+ refusal: &str,
72+) -> Result<impl View> {
73+ let empty = listing.folders.is_empty() && listing.files.is_empty();
74+ Ok(view! {
75+ <section class="drive trash">
76+ <h1>(d(lang, DK::Trash))</h1>
77+ flash(lang: lang, notice: notice, refusal: refusal)
78+ <p class="muted">(d(lang, DK::TrashNote))</p>
79+ if empty {
80+ empty_state(title: d(lang, DK::TrashEmpty))
81+ } else {
82+ <div class="table-wrap">
83+ <table class="table">
84+ <thead><tr>
85+ <th scope="col">(d(lang, DK::Name))</th>
86+ <th scope="col">(d(lang, DK::Size))</th>
87+ <th scope="col">(d(lang, DK::Modified))</th>
88+ <th scope="col">(d(lang, DK::Actions))</th>
89+ </tr></thead>
90+ <tbody>
91+ for folder in &listing.folders {
92+ <tr>
93+ <td>(folder.name.as_str())</td>
94+ <td class="muted">"\u{2014}"</td>
95+ <td class="muted">(stamp_text(folder.trashed_at.as_deref().unwrap_or_default()))</td>
96+ <td>
97+ <form method="post" action="/trash/restore" class="inline-form">
98+ <input type="hidden" name="csrf" value=(csrf)>
99+ <input type="hidden" name="back" value="/trash">
100+ <input type="hidden" name="kind" value="folder">
101+ <input type="hidden" name="id" value=(folder.id.as_str())>
102+ <button class="button" type="submit">(d(lang, DK::Restore))</button>
103+ </form>
104+ <form method="post" action="/trash/purge" class="inline-form">
105+ <input type="hidden" name="csrf" value=(csrf)>
106+ <input type="hidden" name="back" value="/trash">
107+ <input type="hidden" name="kind" value="folder">
108+ <input type="hidden" name="id" value=(folder.id.as_str())>
109+ <button class="button danger" type="submit">(d(lang, DK::PurgeNow))</button>
110+ </form>
111+ </td>
112+ </tr>
113+ }
114+ for file in &listing.files {
115+ <tr>
116+ <td>(file.name.as_str())</td>
117+ <td>(size_text(file.size))</td>
118+ <td class="muted">(stamp_text(file.trashed_at.as_deref().unwrap_or_default()))</td>
119+ <td>
120+ <form method="post" action="/trash/restore" class="inline-form">
121+ <input type="hidden" name="csrf" value=(csrf)>
122+ <input type="hidden" name="back" value="/trash">
123+ <input type="hidden" name="kind" value="file">
124+ <input type="hidden" name="id" value=(file.id.as_str())>
125+ <button class="button" type="submit">(d(lang, DK::Restore))</button>
126+ </form>
127+ <form method="post" action="/trash/purge" class="inline-form">
128+ <input type="hidden" name="csrf" value=(csrf)>
129+ <input type="hidden" name="back" value="/trash">
130+ <input type="hidden" name="kind" value="file">
131+ <input type="hidden" name="id" value=(file.id.as_str())>
132+ <button class="button danger" type="submit">(d(lang, DK::PurgeNow))</button>
133+ </form>
134+ </td>
135+ </tr>
136+ }
137+ </tbody>
138+ </table>
139+ </div>
140+ <form method="post" action="/trash/empty" class="inline-form">
141+ <input type="hidden" name="csrf" value=(csrf)>
142+ <button class="button danger" type="submit">(d(lang, DK::EmptyTrash))</button>
143+ </form>
144+ }
145+ </section>
146+ })
147+}
148+
149+/// `GET /trash`.
150+#[page("/trash")]
151+async fn trash_page(cx: &Cx) -> Result<impl View> {
152+ let state = app_context::<AppState>(cx);
153+ let viewer = require_member(cx).await?;
154+ let lang = viewer_lang(cx, &viewer);
155+ let query: ListQuery = parse_query_params(cx).unwrap_or_default();
156+ let listing = state.store.list_trash(&viewer.member.sub).await?;
157+ let info = ViewerInfo::of(&viewer);
158+ let csrf = viewer.session.csrf_token.clone();
159+ let title = d(lang, DK::Trash);
160+ Ok(view! {
161+ shell(title: title, lang: lang, viewer: Some(&info),
162+ trash_body(lang: lang, listing: &listing, csrf: csrf.as_str(), notice: query.notice.as_str(), refusal: query.refusal.as_str())
163+ )
164+ })
165+}
166+
167+/// `POST /trash/restore`: puts a trashed item back in its place.
168+#[route(POST "/trash/restore")]
169+async fn restore(cx: &Cx, Form(form): Form<TrashForm>) -> Result<SeeOther> {
170+ let state = app_context::<AppState>(cx);
171+ let viewer = require_csrf(cx, &form.csrf).await?;
172+ let back = back_or(&form.back, "/trash");
173+ let Some(kind) = kind_of(&form.kind) else {
174+ return Err(CoreError::NotFound.into());
175+ };
176+ match kind {
177+ ItemKind::File => {
178+ file_for(state, &viewer, &form.id, Action::Restore).await?;
179+ }
180+ ItemKind::Folder => {
181+ folder_for(state, &viewer, &form.id, Action::Restore).await?;
182+ }
183+ }
184+ finish(state, &viewer.member.sub, &back, kind, &form.id, "restored").await
185+}
186+
187+/// Runs a restore after its authorization. Shared by the file and folder branches.
188+async fn finish(
189+ state: &AppState,
190+ owner: &str,
191+ back: &str,
192+ kind: ItemKind,
193+ id: &str,
194+ notice: &str,
195+) -> Result<SeeOther> {
196+ match state.store.restore(owner, kind, id).await {
197+ Ok(()) => {
198+ changed(state, owner);
199+ Ok(done(back, notice))
200+ }
201+ Err(error) => refused(back, error),
202+ }
203+}
204+
205+/// `POST /trash/purge`: deletes a trashed item for good, with its bytes.
206+#[route(POST "/trash/purge")]
207+async fn purge(cx: &Cx, Form(form): Form<TrashForm>) -> Result<SeeOther> {
208+ let state = app_context::<AppState>(cx);
209+ let viewer = require_csrf(cx, &form.csrf).await?;
210+ let back = back_or(&form.back, "/trash");
211+ let Some(kind) = kind_of(&form.kind) else {
212+ return Err(CoreError::NotFound.into());
213+ };
214+ match kind {
215+ ItemKind::File => {
216+ file_for(state, &viewer, &form.id, Action::Purge).await?;
217+ }
218+ ItemKind::Folder => {
219+ folder_for(state, &viewer, &form.id, Action::Purge).await?;
220+ }
221+ }
222+ let owner = viewer.member.sub.clone();
223+ let released = match kind {
224+ ItemKind::File => state.store.purge_file(&owner, &form.id).await,
225+ ItemKind::Folder => state.store.purge_folder(&owner, &form.id).await,
226+ };
227+ match released {
228+ Ok(keys) => {
229+ release(state, keys).await;
230+ changed(state, &owner);
231+ Ok(done(&back, "purged"))
232+ }
233+ Err(error) => refused(&back, error),
234+ }
235+}
236+
237+/// `POST /trash/empty`: deletes everything in the trash for good.
238+#[route(POST "/trash/empty")]
239+async fn empty_trash(cx: &Cx, Form(form): Form<TrashForm>) -> Result<SeeOther> {
240+ let state = app_context::<AppState>(cx);
241+ let viewer = require_csrf(cx, &form.csrf).await?;
242+ let back = back_or(&form.back, "/trash");
243+ let owner = viewer.member.sub.clone();
244+ match state.store.empty_trash(&owner).await {
245+ Ok(keys) => {
246+ release(state, keys).await;
247+ changed(state, &owner);
248+ Ok(done(&back, "emptied"))
249+ }
250+ Err(error) => refused(&back, error),
251+ }
252+}
253+
254+/// `POST /items/trash`: moves the checked live items to the trash. The form is read as raw key/value pairs,
255+/// because one `item` key repeats once per checked row. Every item is checked first; if one of them is not
256+/// the viewer's, nothing is trashed and that item's answer is returned.
257+#[route(POST "/items/trash")]
258+async fn trash_items(cx: &Cx, Form(pairs): Form<Vec<(String, String)>>) -> Result<SeeOther> {
259+ let state = app_context::<AppState>(cx);
260+ let mut csrf = String::new();
261+ let mut back = String::new();
262+ let mut items = Vec::new();
263+ for (key, value) in pairs {
264+ match key.as_str() {
265+ "csrf" => csrf = value,
266+ "back" => back = value,
267+ "item" => items.push(value),
268+ _ => {}
269+ }
270+ }
271+ let viewer = require_csrf(cx, &csrf).await?;
272+ let back = back_or(&back, "/");
273+ let mut files = Vec::new();
274+ let mut folders = Vec::new();
275+ for item in &items {
276+ match item.split_once(':') {
277+ Some(("file", id)) => {
278+ file_for(state, &viewer, id, Action::Write).await?;
279+ files.push(id.to_owned());
280+ }
281+ Some(("folder", id)) => {
282+ folder_for(state, &viewer, id, Action::Write).await?;
283+ folders.push(id.to_owned());
284+ }
285+ _ => return Err(CoreError::NotFound.into()),
286+ }
287+ }
288+ let owner = viewer.member.sub.clone();
289+ for id in &files {
290+ if let Err(error) = state.store.trash_file(&owner, id).await {
291+ return refused(&back, error);
292+ }
293+ }
294+ for id in &folders {
295+ if let Err(error) = state.store.trash_folder(&owner, id).await {
296+ return refused(&back, error);
297+ }
298+ }
299+ if !files.is_empty() || !folders.is_empty() {
300+ changed(state, &owner);
301+ }
302+ Ok(done(&back, "trashed"))
303+}
304+
305+#[cfg(test)]
306+mod tests {
307+ /// The browser repeats `item` once per checked row; the pairs keep every one, in order.
308+ #[test]
309+ fn repeated_item_fields_are_all_kept() {
310+ let pairs: Vec<(String, String)> = serde_urlencoded::from_str(
311+ "csrf=t&back=%2F&item=file%3Aa&item=folder%3Ab&item=file%3Ac",
312+ )
313+ .expect("form");
314+ let items: Vec<&str> = pairs
315+ .iter()
316+ .filter(|(key, _)| key == "item")
317+ .map(|(_, value)| value.as_str())
318+ .collect();
319+ assert_eq!(items, vec!["file:a", "folder:b", "file:c"]);
320+ }
321+}
crates/in-web/src/serve_bytes.rsadded+458 -0
@@ -0,0 +1,458 @@
1+//! The one function that sends a stored blob to a browser. Every byte route (download, raw, and the
2+//! shared and public ones that come later) calls [`serve_bytes`], so the headers and the range rules
3+//! exist in exactly one place (architecture section 7).
4+//!
5+//! The caller has already decided that the viewer may see the bytes (`authz`). This module decides how
6+//! they are sent: a single byte range, a validator (`ETag`) and its conditional requests, a disposition
7+//! that is `inline` only for types a browser can show without running them, and the response headers
8+//! that stop the bytes from being used as a page. The body is streamed from the blob store in frames of
9+//! [`in_core::blob::FRAME_BYTES`]; nothing is buffered whole.
10+//!
11+//! Range rules: one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with several ranges gets the
12+//! whole file with `200`. A malformed, reversed or unsatisfiable range gets `416` with
13+//! `Content-Range: bytes */<len>`. `If-Range` with a validator that is not the current one gets the whole
14+//! file.
15+
16+use futures_util::TryStreamExt;
17+use http::header::{
18+ ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE,
19+ CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE,
20+ X_CONTENT_TYPE_OPTIONS,
21+};
22+use http_body::Frame;
23+use http_body_util::StreamBody;
24+use in_core::blob::BlobStore;
25+use topcoat::Result;
26+use topcoat::context::Cx;
27+use topcoat::router::request::headers;
28+use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode};
29+
30+/// What a browser may do with a byte response: show it in the page, or save it.
31+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32+pub enum Disposition {
33+ /// Show the bytes in the page. Granted only to the types in [`inline_safe`].
34+ Inline,
35+ /// Save the bytes as a file.
36+ Attachment,
37+}
38+
39+/// Everything about a stored file that a byte response needs. The caller fills it from the row.
40+#[derive(Clone, Copy, Debug)]
41+pub struct ByteSource<'a> {
42+ /// Key of the bytes in the blob store.
43+ pub blob_key: &'a str,
44+ /// Length of the bytes in bytes.
45+ pub size: u64,
46+ /// Lowercase hex SHA-256 of the bytes. It is the strong validator, so equal hashes mean equal bytes.
47+ pub sha256: &'a str,
48+ /// The sniffed MIME type, as stored. It is never the uploader's claim.
49+ pub mime: &'a str,
50+ /// The display name, used for the `Content-Disposition` file name.
51+ pub name: &'a str,
52+}
53+
54+/// The status, headers and body of a byte response. Handlers return it as they are.
55+pub type ByteAnswer = (StatusCode, HeaderMap, Body);
56+
57+/// `Content-Security-Policy` of every byte response. The sandbox makes the document opaque, and
58+/// `default-src 'none'` stops it from loading anything but its own image, media or style.
59+pub const BYTES_CSP: &str =
60+ "sandbox; default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'";
61+
62+/// Cache policy of content addressed by id and hash: the bytes behind a URL never change.
63+const BYTES_CACHE: &str = "private, max-age=31536000, immutable";
64+
65+/// The outcome of reading a `Range` header against a length.
66+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67+pub enum Ranged {
68+ /// Send the whole file (no range, or several ranges).
69+ Full,
70+ /// Send the bytes from `start` to `end`, both inclusive, and both inside the file.
71+ Part {
72+ /// First byte, inclusive.
73+ start: u64,
74+ /// Last byte, inclusive.
75+ end: u64,
76+ },
77+ /// The header is malformed, reversed, or asks for nothing the file has. Answer `416`.
78+ Unsatisfiable,
79+}
80+
81+/// Parses the value of a `Range` header for a file of `len` bytes.
82+///
83+/// Accepted: `bytes=a-b` (clamped to the end of the file), `bytes=a-` (to the end), `bytes=-n` (the last
84+/// `n` bytes; a longer `n` means the whole file). Several ranges, separated by commas, give
85+/// [`Ranged::Full`]. Everything else is [`Ranged::Unsatisfiable`]: a missing unit, a non-digit, a value
86+/// that overflows `u64`, `-0`, a last byte before the first, or a first byte at or past the end.
87+pub fn parse_range(value: &str, len: u64) -> Ranged {
88+ let Some(spec) = value.trim().strip_prefix("bytes=") else {
89+ return Ranged::Unsatisfiable;
90+ };
91+ if spec.contains(',') {
92+ return Ranged::Full;
93+ }
94+ let Some((first, last)) = spec.trim().split_once('-') else {
95+ return Ranged::Unsatisfiable;
96+ };
97+ let (first, last) = (first.trim(), last.trim());
98+ if first.is_empty() {
99+ // A suffix range: the last `n` bytes.
100+ let Some(n) = digits(last) else {
101+ return Ranged::Unsatisfiable;
102+ };
103+ if n == 0 || len == 0 {
104+ return Ranged::Unsatisfiable;
105+ }
106+ let n = n.min(len);
107+ return Ranged::Part {
108+ start: len - n,
109+ end: len - 1,
110+ };
111+ }
112+ let Some(start) = digits(first) else {
113+ return Ranged::Unsatisfiable;
114+ };
115+ let end = if last.is_empty() {
116+ None
117+ } else {
118+ match digits(last) {
119+ Some(end) if end >= start => Some(end),
120+ _ => return Ranged::Unsatisfiable,
121+ }
122+ };
123+ if start >= len {
124+ return Ranged::Unsatisfiable;
125+ }
126+ let end = end.map_or(len - 1, |end| end.min(len - 1));
127+ Ranged::Part { start, end }
128+}
129+
130+/// A non-empty run of ASCII digits as a number. Anything else, including an overflow, is `None`.
131+fn digits(text: &str) -> Option<u64> {
132+ if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
133+ return None;
134+ }
135+ text.parse().ok()
136+}
137+
138+/// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong
139+/// form here, which is the rule for `GET` validators (RFC 9110).
140+fn none_match_hits(request: &HeaderMap, etag: &str) -> bool {
141+ request
142+ .get(IF_NONE_MATCH)
143+ .and_then(|value| value.to_str().ok())
144+ .is_some_and(|value| {
145+ value.split(',').map(str::trim).any(|candidate| {
146+ candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag
147+ })
148+ })
149+}
150+
151+/// Whether a range may be honoured under `If-Range`. Without the header it always may. With it, only a
152+/// strong validator equal to `etag` allows the range; a date or a weak tag never does.
153+fn if_range_allows(request: &HeaderMap, etag: &str) -> bool {
154+ match request.get(IF_RANGE).and_then(|value| value.to_str().ok()) {
155+ None => true,
156+ Some(value) => value.trim() == etag,
157+ }
158+}
159+
160+/// The range that applies to this request, after `If-Range` has had its say.
161+fn requested_range(request: &HeaderMap, etag: &str, len: u64) -> Ranged {
162+ let Some(value) = request.get(RANGE).and_then(|value| value.to_str().ok()) else {
163+ return Ranged::Full;
164+ };
165+ if !if_range_allows(request, etag) {
166+ return Ranged::Full;
167+ }
168+ parse_range(value, len)
169+}
170+
171+/// Whether serving this request counts as a download that started at byte 0. A `304`, a range that
172+/// starts later, and an unsatisfiable range do not count; a whole file, or a range from byte 0, does.
173+/// The download counter is bumped by the caller before it serves the body.
174+pub fn counts_as_download(request: &HeaderMap, sha256: &str, size: u64) -> bool {
175+ let etag = format!("\"{sha256}\"");
176+ if none_match_hits(request, &etag) {
177+ return false;
178+ }
179+ match requested_range(request, &etag, size) {
180+ Ranged::Full => true,
181+ Ranged::Part { start, .. } => start == 0,
182+ Ranged::Unsatisfiable => false,
183+ }
184+}
185+
186+/// Whether a type may be shown inline. SVG is never inline: it can carry script. HTML is never inline.
187+/// Images (except SVG and HEIC/HEIF, which browsers do not show everywhere), audio, video, PDF and plain
188+/// text are.
189+pub fn inline_safe(mime: &str) -> bool {
190+ let essence = mime
191+ .split(';')
192+ .next()
193+ .unwrap_or_default()
194+ .trim()
195+ .to_ascii_lowercase();
196+ match essence.as_str() {
197+ "image/svg+xml" | "image/heic" | "image/heif" => false,
198+ "application/pdf" | "text/plain" => true,
199+ other => {
200+ other.starts_with("image/")
201+ || other.starts_with("audio/")
202+ || other.starts_with("video/")
203+ }
204+ }
205+}
206+
207+/// The `Content-Type` value for a stored type. Plain text is always sent as UTF-8.
208+fn content_type_value(mime: &str) -> String {
209+ if mime.trim().eq_ignore_ascii_case("text/plain") {
210+ "text/plain; charset=utf-8".into()
211+ } else {
212+ mime.to_string()
213+ }
214+}
215+
216+/// Characters that may appear unescaped in an RFC 5987 `filename*` value (`attr-char`).
217+fn is_attr_char(b: u8) -> bool {
218+ b.is_ascii_alphanumeric() || b"!#$&+-.^_`|~".contains(&b)
219+}
220+
221+/// The `Content-Disposition` header for a file name: `inline` or `attachment`, a quoted ASCII fallback
222+/// and the UTF-8 name percent-encoded per RFC 5987.
223+///
224+/// The fallback keeps printable ASCII except the quote and the backslash, and turns everything else
225+/// (control characters, including CR and LF, non-ASCII letters) into `_`. So no name can close the
226+/// quoted string or start a new header line. The `filename*` value encodes every byte that is not an
227+/// `attr-char`, which covers the same characters.
228+pub fn content_disposition(kind: Disposition, name: &str) -> String {
229+ let fallback: String = name
230+ .chars()
231+ .map(|c| {
232+ if c.is_ascii() && (c.is_ascii_graphic() || c == ' ') && c != '"' && c != '\\' {
233+ c
234+ } else {
235+ '_'
236+ }
237+ })
238+ .collect();
239+ let fallback = if fallback.trim().is_empty() {
240+ "download".to_string()
241+ } else {
242+ fallback
243+ };
244+ let mut encoded = String::with_capacity(name.len());
245+ for b in name.bytes() {
246+ if is_attr_char(b) {
247+ encoded.push(char::from(b));
248+ } else {
249+ encoded.push_str(&format!("%{b:02X}"));
250+ }
251+ }
252+ let kind = match kind {
253+ Disposition::Inline => "inline",
254+ Disposition::Attachment => "attachment",
255+ };
256+ format!("{kind}; filename=\"{fallback}\"; filename*=UTF-8''{encoded}")
257+}
258+
259+/// The headers every byte response carries, whatever its status.
260+fn common_headers(etag: &str) -> HeaderMap {
261+ let mut headers = HeaderMap::new();
262+ insert(&mut headers, ETAG, etag);
263+ headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes"));
264+ headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
265+ headers.insert(CONTENT_SECURITY_POLICY, HeaderValue::from_static(BYTES_CSP));
266+ headers.insert(
267+ HeaderName::from_static("cross-origin-resource-policy"),
268+ HeaderValue::from_static("same-origin"),
269+ );
270+ headers.insert(CACHE_CONTROL, HeaderValue::from_static(BYTES_CACHE));
271+ headers
272+}
273+
274+/// Inserts a header whose value is text the code controls. A value that is not a valid header value is
275+/// dropped, never sent half-formed; every caller passes ASCII that the code made.
276+fn insert(headers: &mut HeaderMap, name: http::HeaderName, value: &str) {
277+ if let Ok(value) = HeaderValue::from_str(value) {
278+ headers.insert(name, value);
279+ }
280+}
281+
282+/// The `416` answer: no body, and the length the client may ask again within.
283+fn unsatisfiable(etag: &str, len: u64) -> ByteAnswer {
284+ let mut headers = common_headers(etag);
285+ insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}"));
286+ (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty())
287+}
288+
289+/// Sends the bytes of `source` for the request in `cx`.
290+///
291+/// `disposition` is the caller's wish. It becomes [`Disposition::Attachment`] unless the type is in
292+/// [`inline_safe`]. The body streams from the blob store from the first byte the answer needs. A
293+/// missing blob is an error (the row names bytes that are not there), which the router answers as a
294+/// `500`.
295+pub async fn serve_bytes(
296+ cx: &Cx,
297+ blobs: &dyn BlobStore,
298+ source: &ByteSource<'_>,
299+ disposition: Disposition,
300+) -> Result<ByteAnswer> {
301+ let request = headers(cx);
302+ let etag = format!("\"{}\"", source.sha256);
303+ let disposition = match disposition {
304+ Disposition::Inline if inline_safe(source.mime) => Disposition::Inline,
305+ _ => Disposition::Attachment,
306+ };
307+ let mut answer_headers = common_headers(&etag);
308+ insert(
309+ &mut answer_headers,
310+ CONTENT_DISPOSITION,
311+ &content_disposition(disposition, source.name),
312+ );
313+ insert(
314+ &mut answer_headers,
315+ CONTENT_TYPE,
316+ &content_type_value(source.mime),
317+ );
318+
319+ if none_match_hits(request, &etag) {
320+ return Ok((StatusCode::NOT_MODIFIED, answer_headers, Body::empty()));
321+ }
322+
323+ match requested_range(request, &etag, source.size) {
324+ Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size)),
325+ Ranged::Full => {
326+ insert(
327+ &mut answer_headers,
328+ CONTENT_LENGTH,
329+ &source.size.to_string(),
330+ );
331+ let stream = blobs.open_range(source.blob_key, 0, source.size).await?;
332+ Ok((StatusCode::OK, answer_headers, streamed(stream)))
333+ }
334+ Ranged::Part { start, end } => {
335+ let length = end - start + 1;
336+ insert(&mut answer_headers, CONTENT_LENGTH, &length.to_string());
337+ insert(
338+ &mut answer_headers,
339+ CONTENT_RANGE,
340+ &format!("bytes {start}-{end}/{}", source.size),
341+ );
342+ let stream = blobs.open_range(source.blob_key, start, length).await?;
343+ Ok((
344+ StatusCode::PARTIAL_CONTENT,
345+ answer_headers,
346+ streamed(stream),
347+ ))
348+ }
349+ }
350+}
351+
352+/// Turns a blob stream into a response body. Frames are passed through as they come.
353+fn streamed(stream: in_core::blob::BlobStream) -> Body {
354+ Body::new(StreamBody::new(stream.map_ok(Frame::data)))
355+}
356+
357+#[cfg(test)]
358+mod tests {
359+ use super::*;
360+
361+ /// A table of `Range` values for a 100-byte file, with the answer for each.
362+ #[test]
363+ fn range_table() {
364+ use Ranged::*;
365+ let cases: &[(&str, Ranged)] = &[
366+ ("bytes=0-0", Part { start: 0, end: 0 }),
367+ ("bytes=0-99", Part { start: 0, end: 99 }),
368+ ("bytes=10-19", Part { start: 10, end: 19 }),
369+ // Past the end is clamped, not refused.
370+ ("bytes=50-500", Part { start: 50, end: 99 }),
371+ ("bytes=90-", Part { start: 90, end: 99 }),
372+ ("bytes=-10", Part { start: 90, end: 99 }),
373+ // A suffix longer than the file is the whole file.
374+ ("bytes=-1000", Part { start: 0, end: 99 }),
375+ (" bytes=1 - 2 ", Part { start: 1, end: 2 }),
376+ // Several ranges: the whole file.
377+ ("bytes=0-1,5-6", Full),
378+ // Unsatisfiable or malformed.
379+ ("bytes=-0", Unsatisfiable),
380+ ("bytes=100-", Unsatisfiable),
381+ ("bytes=100-120", Unsatisfiable),
382+ ("bytes=20-10", Unsatisfiable),
383+ ("bytes=5-4", Unsatisfiable),
384+ ("bytes=-", Unsatisfiable),
385+ ("bytes=", Unsatisfiable),
386+ ("bytes=-x", Unsatisfiable),
387+ ("bytes=+1-2", Unsatisfiable),
388+ ("bytes=1e2-", Unsatisfiable),
389+ ("bytes=--1", Unsatisfiable),
390+ ("items=0-1", Unsatisfiable),
391+ ("0-1", Unsatisfiable),
392+ // Overflow of u64 is refused, not wrapped.
393+ ("bytes=18446744073709551616-", Unsatisfiable),
394+ ("bytes=0-18446744073709551616", Unsatisfiable),
395+ ("bytes=-18446744073709551616", Unsatisfiable),
396+ ];
397+ for (header, want) in cases {
398+ assert_eq!(parse_range(header, 100), *want, "header {header:?}");
399+ }
400+ }
401+
402+ #[test]
403+ fn an_empty_file_has_no_satisfiable_range() {
404+ assert_eq!(parse_range("bytes=0-", 0), Ranged::Unsatisfiable);
405+ assert_eq!(parse_range("bytes=-5", 0), Ranged::Unsatisfiable);
406+ }
407+
408+ #[test]
409+ fn disposition_is_inline_only_for_safe_types() {
410+ assert!(inline_safe("image/png"));
411+ assert!(inline_safe("application/pdf"));
412+ assert!(inline_safe("text/plain; charset=utf-8"));
413+ assert!(inline_safe("video/mp4"));
414+ assert!(!inline_safe("image/svg+xml"));
415+ assert!(!inline_safe("image/heic"));
416+ assert!(!inline_safe("text/html"));
417+ assert!(!inline_safe("application/octet-stream"));
418+ assert_eq!(
419+ content_type_value("text/plain"),
420+ "text/plain; charset=utf-8"
421+ );
422+ }
423+
424+ /// Quotes, CR and LF, and a non-ASCII name cannot close the quoted string or add a header line.
425+ #[test]
426+ fn content_disposition_neutralises_quotes_crlf_and_unicode() {
427+ let value = content_disposition(Disposition::Attachment, "a\"b\r\nc é.pdf");
428+ assert!(!value.contains('\r') && !value.contains('\n'));
429+ assert_eq!(
430+ value.matches('"').count(),
431+ 2,
432+ "only the two quotes: {value}"
433+ );
434+ assert_eq!(
435+ value,
436+ "attachment; filename=\"a_b__c _.pdf\"; filename*=UTF-8''a%22b%0D%0Ac%20%C3%A9.pdf"
437+ );
438+ let inline = content_disposition(Disposition::Inline, "plain.txt");
439+ assert_eq!(
440+ inline,
441+ "inline; filename=\"plain.txt\"; filename*=UTF-8''plain.txt"
442+ );
443+ assert!(content_disposition(Disposition::Attachment, "").contains("filename=\"download\""));
444+ }
445+
446+ #[test]
447+ fn a_download_counts_only_when_it_starts_at_byte_zero() {
448+ let mut request = HeaderMap::new();
449+ assert!(counts_as_download(&request, "ab", 10));
450+ request.insert(RANGE, HeaderValue::from_static("bytes=0-3"));
451+ assert!(counts_as_download(&request, "ab", 10));
452+ request.insert(RANGE, HeaderValue::from_static("bytes=4-"));
453+ assert!(!counts_as_download(&request, "ab", 10));
454+ request.insert(RANGE, HeaderValue::from_static("bytes=0-3"));
455+ request.insert(IF_NONE_MATCH, HeaderValue::from_static("\"ab\""));
456+ assert!(!counts_as_download(&request, "ab", 10));
457+ }
458+}
crates/in-web/src/views/drive.rsadded+212 -0
@@ -0,0 +1,212 @@
1+//! The drive's page parts: breadcrumbs, the listing table with its row menus, the flash line that shows a
2+//! notice or a refusal, the quota bar and the small formatters they use.
3+//!
4+//! Every form here posts with a `csrf` field and a `back` field. `back` is the page to return to; the
5+//! handler checks it with `safe_next` before it redirects there. Nothing here runs script: the row menus
6+//! are `<details>` elements and the selection is the `form` attribute of a checkbox.
7+
8+use topcoat::Result;
9+use topcoat::view::{View, component, view};
10+
11+use crate::i18n::Lang;
12+use crate::i18n::drive::{DK, d, notice_text, quota_text, refusal_text};
13+use in_core::store::files::File;
14+use in_core::store::folders::Folder;
15+
16+/// Formats a byte count for people: `B`, `KB`, `MB`, `GB` or `TB`, one decimal above bytes. Base 1024.
17+pub fn size_text(bytes: i64) -> String {
18+ const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
19+ let mut value = bytes.max(0) as f64;
20+ let mut unit = 0;
21+ while value >= 1024.0 && unit < UNITS.len() - 1 {
22+ value /= 1024.0;
23+ unit += 1;
24+ }
25+ if unit == 0 {
26+ format!("{} B", bytes.max(0))
27+ } else {
28+ format!("{value:.1} {}", UNITS[unit])
29+ }
30+}
31+
32+/// Shortens a stored UTC stamp (`2026-10-28T10:00:00.123456789Z`) to `2026-10-28 10:00`.
33+pub fn stamp_text(stamp: &str) -> String {
34+ stamp.chars().take(16).collect::<String>().replace('T', " ")
35+}
36+
37+/// The quota bar: a `progress` element and its line of text. Used by the shell.
38+#[component]
39+pub async fn quota_bar(lang: Lang, used: i64, quota: i64) -> Result<impl View> {
40+ let line = quota_text(lang, &size_text(used), &size_text(quota));
41+ Ok(view! {
42+ <div class="quota" aria-label=(d(lang, DK::Storage))>
43+ <progress max=(quota.max(1).to_string()) value=(used.max(0).to_string())></progress>
44+ <span class="muted">(line)</span>
45+ </div>
46+ })
47+}
48+
49+/// The flash line of a page: a notice from a finished action, or a refusal of one. Unknown words show
50+/// nothing.
51+#[component]
52+pub async fn flash(lang: Lang, notice: &str, refusal: &str) -> Result<impl View> {
53+ let notice_line = notice_text(lang, notice);
54+ let refusal_line = refusal_text(lang, refusal);
55+ Ok(view! {
56+ if let Some(text) = refusal_line {
57+ <div class="alert" role="alert">(text)</div>
58+ }
59+ if let Some(text) = notice_line {
60+ <div class="notice" role="status">(text)</div>
61+ }
62+ })
63+}
64+
65+/// The breadcrumb trail, top level first. Empty for the top level, which needs no trail.
66+#[component]
67+pub async fn crumbs(lang: Lang, trail: &[Folder]) -> Result<impl View> {
68+ Ok(view! {
69+ <nav class="crumbs" aria-label=(d(lang, DK::Location2))>
70+ <ol>
71+ <li><a href="/">(d(lang, DK::Drive))</a></li>
72+ for folder in trail {
73+ <li><a href=(format!("/f/{}", folder.id))>(folder.name.as_str())</a></li>
74+ }
75+ </ol>
76+ </nav>
77+ })
78+}
79+
80+/// The sort links of the listing header: each column header links to the same listing with the sort
81+/// key and direction the next click would choose.
82+#[component]
83+pub async fn sort_link(
84+ base: &str,
85+ key: &str,
86+ label: &str,
87+ current: bool,
88+ descending: bool,
89+) -> Result<impl View> {
90+ // Clicking the active column flips its direction; a new column starts ascending.
91+ let next = if current && !descending {
92+ "desc"
93+ } else {
94+ "asc"
95+ };
96+ let mark = match (current, descending) {
97+ (true, false) => " \u{25b2}",
98+ (true, true) => " \u{25bc}",
99+ _ => "",
100+ };
101+ let href = format!("{base}sort={key}&dir={next}");
102+ Ok(view! {
103+ <a href=(href)>(label)(mark)</a>
104+ })
105+}
106+
107+/// The row menu of one item: the actions that an owner may take on it. Each action is a form, so the
108+/// menu works without script.
109+#[component]
110+pub async fn row_menu(
111+ lang: Lang,
112+ csrf: &str,
113+ back: &str,
114+ kind: &str,
115+ id: &str,
116+ name: &str,
117+) -> Result<impl View> {
118+ let rename_action = format!("/{kind}s/{id}/rename");
119+ let move_page = format!("/{kind}s/{id}/pick");
120+ let trash_action = format!("/{kind}s/{id}/trash");
121+ Ok(view! {
122+ <details class="row-menu">
123+ <summary>(d(lang, DK::Actions))</summary>
124+ <div class="row-menu-body">
125+ <form method="post" action=(rename_action) class="inline-form">
126+ <input type="hidden" name="csrf" value=(csrf)>
127+ <input type="hidden" name="back" value=(back)>
128+ <label class="sr-only" for=(format!("rn-{id}"))>(d(lang, DK::Rename))</label>
129+ <input id=(format!("rn-{id}")) name="name" value=(name) maxlength="255" required="">
130+ <button class="button" type="submit">(d(lang, DK::Save))</button>
131+ </form>
132+ <a class="button" href=(move_page)>(d(lang, DK::Move))</a>
133+ <form method="post" action=(trash_action) class="inline-form">
134+ <input type="hidden" name="csrf" value=(csrf)>
135+ <input type="hidden" name="back" value=(back)>
136+ <button class="button danger" type="submit">(d(lang, DK::TrashItem))</button>
137+ </form>
138+ </div>
139+ </details>
140+ })
141+}
142+
143+/// A table of folders and files: the rows, their selection box for the bulk trash, and the row menus.
144+/// `base` is the listing's own URL without a query, and `query` the sort part already in it.
145+#[component]
146+pub async fn listing_table(
147+ lang: Lang,
148+ folders: &[Folder],
149+ files: &[File],
150+ csrf: &str,
151+ back: &str,
152+ sort: &str,
153+ dir: &str,
154+ base: &str,
155+) -> Result<impl View> {
156+ let descending = dir == "desc";
157+ let name_sort = sort == "name";
158+ let size_sort = sort == "size";
159+ let modified_sort = sort == "modified";
160+ Ok(view! {
161+ <div class="table-wrap">
162+ <table class="table">
163+ <thead>
164+ <tr>
165+ <th scope="col"><span class="sr-only">"\u{2713}"</span></th>
166+ <th scope="col">
167+ sort_link(base: base, key: "name", label: d(lang, DK::Name), current: name_sort, descending: descending)
168+ </th>
169+ <th scope="col">
170+ sort_link(base: base, key: "size", label: d(lang, DK::Size), current: size_sort, descending: descending)
171+ </th>
172+ <th scope="col">
173+ sort_link(base: base, key: "modified", label: d(lang, DK::Modified), current: modified_sort, descending: descending)
174+ </th>
175+ <th scope="col">(d(lang, DK::Kind))</th>
176+ <th scope="col">(d(lang, DK::Actions))</th>
177+ </tr>
178+ </thead>
179+ <tbody>
180+ for folder in folders {
181+ <tr>
182+ <td><input type="checkbox" name="item" value=(format!("folder:{}", folder.id)) form="bulk-trash" aria-label=(folder.name.as_str())></td>
183+ <td><a href=(format!("/f/{}", folder.id))>(folder.name.as_str())</a></td>
184+ <td class="muted">"\u{2014}"</td>
185+ <td class="muted">(stamp_text(&folder.updated_at))</td>
186+ <td>(d(lang, DK::FolderKind))</td>
187+ <td>row_menu(lang: lang, csrf: csrf, back: back, kind: "folder", id: folder.id.as_str(), name: folder.name.as_str())</td>
188+ </tr>
189+ }
190+ for file in files {
191+ <tr>
192+ <td><input type="checkbox" name="item" value=(format!("file:{}", file.id)) form="bulk-trash" aria-label=(file.name.as_str())></td>
193+ <td><a href=(format!("/file/{}", file.id))>(file.name.as_str())</a></td>
194+ <td>(size_text(file.size))</td>
195+ <td class="muted">(stamp_text(&file.updated_at))</td>
196+ <td>(d(lang, DK::FileKind))</td>
197+ <td>
198+ <a class="button ghost" href=(format!("/file/{}/download", file.id))>(d(lang, DK::Download))</a>
199+ row_menu(lang: lang, csrf: csrf, back: back, kind: "file", id: file.id.as_str(), name: file.name.as_str())
200+ </td>
201+ </tr>
202+ }
203+ </tbody>
204+ </table>
205+ </div>
206+ <form id="bulk-trash" method="post" action="/items/trash" class="bulk">
207+ <input type="hidden" name="csrf" value=(csrf)>
208+ <input type="hidden" name="back" value=(back)>
209+ <button class="button danger" type="submit">(d(lang, DK::TrashSelected))</button>
210+ </form>
211+ })
212+}
crates/in-web/src/views/mod.rsmodified+29 -1
@@ -7,8 +7,13 @@ use topcoat::Result;
7 use topcoat::view::{Child, View, component, view};7 use topcoat::view::{Child, View, component, view};
8 8
9 use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF};9 use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF};
10+use crate::auth::Viewer;
10 use crate::i18n::Lang;11 use crate::i18n::Lang;
12+use crate::i18n::drive::{DK, d};
11 use crate::i18n::shell::{K, t};13 use crate::i18n::shell::{K, t};
14+use crate::views::drive::quota_bar;
15+
16+pub mod drive;
12 17
13 /// What the shell shows about the signed-in person: the name, the administrator badge, and the CSRF18 /// What the shell shows about the signed-in person: the name, the administrator badge, and the CSRF
14 /// token of the session for the sign-out form.19 /// token of the session for the sign-out form.
@@ -19,6 +24,23 @@ pub struct ViewerInfo {
19 pub is_admin: bool,24 pub is_admin: bool,
20 /// The session's CSRF token, which the sign-out form sends.25 /// The session's CSRF token, which the sign-out form sends.
21 pub csrf: String,26 pub csrf: String,
27+ /// Bytes the viewer's files use, trashed ones included.
28+ pub used: i64,
29+ /// The viewer's quota in bytes.
30+ pub quota: i64,
31+}
32+
33+impl ViewerInfo {
34+ /// What the shell needs to know about a signed-in viewer.
35+ pub fn of(viewer: &Viewer) -> Self {
36+ Self {
37+ name: viewer.member.name.clone(),
38+ is_admin: viewer.member.is_admin,
39+ csrf: viewer.session.csrf_token.clone(),
40+ used: viewer.member.used_bytes,
41+ quota: viewer.member.quota_bytes,
42+ }
43+ }
22 }44 }
23 45
24 /// The HTML document around a page. `title` is the page's own title; the document title adds the46 /// 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(
50 <a class="skip-link" href="#main">(t(lang, K::SkipToContent))</a>72 <a class="skip-link" href="#main">(t(lang, K::SkipToContent))</a>
51 <header class="topbar">73 <header class="topbar">
52 <a class="topbar-brand" href="/">"in"</a>74 <a class="topbar-brand" href="/">"in"</a>
53- <nav class="switcher" aria-label=(t(lang, K::Services))></nav>75+ <nav class="switcher" aria-label=(t(lang, K::Services))>
76+ if viewer.is_some() {
77+ <a href="/">(d(lang, DK::Drive))</a>
78+ <a href="/trash">(d(lang, DK::Trash))</a>
79+ }
80+ </nav>
54 <div class="topbar-end">81 <div class="topbar-end">
55 if let Some(viewer) = viewer {82 if let Some(viewer) = viewer {
83+ quota_bar(lang: lang, used: viewer.used, quota: viewer.quota)
56 <details class="user-menu">84 <details class="user-menu">
57 <summary>(viewer.name.as_str())</summary>85 <summary>(viewer.name.as_str())</summary>
58 <form method="post" action="/auth/logout" data-hard="">86 <form method="post" action="/auth/logout" data-hard="">
style/_components.scssmodified+113 -0
@@ -313,3 +313,116 @@ textarea::placeholder {
313 transition: none;313 transition: none;
314 }314 }
315 }315 }
316+
317+// The drive: listings, forms that sit in a row, row menus, breadcrumbs, the quota bar and the pickers.
318+.drive {
319+ display: flex;
320+ flex-direction: column;
321+ gap: 1rem;
322+}
323+
324+.crumbs ol {
325+ display: flex;
326+ flex-wrap: wrap;
327+ gap: 0.35rem;
328+ list-style: none;
329+ margin: 0;
330+ padding: 0;
331+ color: var(--muted);
332+}
333+
334+.crumbs li + li::before {
335+ content: "/";
336+ padding-inline-end: 0.35rem;
337+}
338+
339+.toolbar {
340+ display: flex;
341+ flex-wrap: wrap;
342+ gap: 0.75rem;
343+ align-items: center;
344+}
345+
346+.inline-form {
347+ display: inline-flex;
348+ flex-wrap: wrap;
349+ gap: 0.4rem;
350+ align-items: center;
351+ margin: 0;
352+}
353+
354+.inline-form input[type="text"],
355+.inline-form input:not([type]),
356+.inline-form input[type="search"],
357+.inline-form input[type="file"] {
358+ min-width: 12rem;
359+}
360+
361+.actions {
362+ display: flex;
363+ flex-wrap: wrap;
364+ gap: 0.5rem;
365+ align-items: center;
366+}
367+
368+.row-menu summary {
369+ cursor: pointer;
370+ color: var(--accent);
371+}
372+
373+.row-menu-body {
374+ display: flex;
375+ flex-wrap: wrap;
376+ gap: 0.5rem;
377+ align-items: center;
378+ margin-block-start: 0.5rem;
379+}
380+
381+.details {
382+ display: grid;
383+ grid-template-columns: max-content 1fr;
384+ gap: 0.35rem 1rem;
385+ margin: 0;
386+}
387+
388+.details dt {
389+ color: var(--muted);
390+}
391+
392+.details dd {
393+ margin: 0;
394+}
395+
396+.quota {
397+ display: flex;
398+ flex-direction: column;
399+ align-items: flex-end;
400+ font-size: 0.85rem;
401+}
402+
403+.quota progress {
404+ width: 9rem;
405+}
406+
407+.pick-list {
408+ list-style: none;
409+ margin: 0;
410+ padding: 0;
411+ display: flex;
412+ flex-direction: column;
413+ gap: 0.35rem;
414+}
415+
416+.pick-list .button {
417+ justify-content: flex-start;
418+ width: 100%;
419+ text-align: start;
420+}
421+
422+.bulk {
423+ margin-block-start: 0.5rem;
424+}
425+
426+.trash .table td form {
427+ display: inline-flex;
428+}