From 16e8c67cafaadb55dcb60349b56dc3f76625b3e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 7 Sep 2026 07:22:04 +0300 Subject: [PATCH] =?UTF-8?q?feat(web):=20the=20public=20half=20joins=20the?= =?UTF-8?q?=20house=20=E2=80=94=20shell,=20player,=20domains,=20fast=20boo?= =?UTF-8?q?ts,=20phones?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The /s pages leave the bare-fragment era: every answer (card, folder, gate, dead link) now wears document_shell — the exact head root_layout pairs around pages, extracted once and delegated to — so a stranger's first sight of In is the app, not unstyled markup. The card's media kinds play through the house player itself: files.rs gains one media_player (markup + bar + script) that the signed-in viewer and the public card render verbatim, fed by a new ?media=1 stream — inline, range-capable, gated by password and liveness like every other answer, never counted as a download, granted to view-only links the way the signed-in viewer grants preview. Share links now say the deployment's name: base_url in config/in.toml (mirroring iz's key) feeds public_origin(), which only the share URLs and copy-once banners read — redirect_uri and the bind never move. Restarts stop walking the disk before answering: open() keeps only the structural work, and the boot sweeps (expired uploads, orphaned files, trash purge) run as a background task after bind, with the orphan sweep decided under BEGIN IMMEDIATE so a racing upload can never lose its bytes — the deletion set is unchanged, only its timing moved. And the whole thing now fits a phone: the media bar wraps with a full-width seek, the share modal's rows fold, public cards lose their desktop air, titles wrap — all inside the existing 620px breakpoint, desktop untouched. --- config/in.toml | 4 + crates/in-core/src/config.rs | 114 +++++- crates/in-core/src/store/turso_store.rs | 64 +++- crates/in-core/tests/store.rs | 73 +++- crates/in-web/src/drive.rs | 4 +- crates/in-web/src/files.rs | 44 ++- crates/in-web/src/layout.rs | 20 +- crates/in-web/src/main.rs | 35 +- crates/in-web/src/settings.rs | 5 +- crates/in-web/src/share.rs | 200 +++++++--- crates/in-web/tests/http.rs | 463 ++++++++++++++++++++++++ style/main.scss | 49 ++- 12 files changed, 987 insertions(+), 88 deletions(-) diff --git a/config/in.toml b/config/in.toml index 6130f86..2598329 100644 --- a/config/in.toml +++ b/config/in.toml @@ -12,6 +12,10 @@ live_seconds = 300 purge_after_days = 30 # The quota a newly provisioned account starts on, in bytes. 10 GiB. default_quota_bytes = 10737418240 +# The base of the share links In hands out. Set it when In answers on a +# different address than it binds — a domain, or a proxy in front. Left +# empty, links follow the listen address. +base_url = "" # Where drive files, thumbnails and staged upload chunks live as files, # created on boot. Not written here: it defaults to beside the database file, # and the boot completes this file with the value it resolved. diff --git a/crates/in-core/src/config.rs b/crates/in-core/src/config.rs index d231918..7759ae8 100644 --- a/crates/in-core/src/config.rs +++ b/crates/in-core/src/config.rs @@ -60,6 +60,10 @@ live_seconds = 300 purge_after_days = 30 # The quota a newly provisioned account starts on, in bytes. 10 GiB. default_quota_bytes = 10737418240 +# The base of the share links In hands out. Set it when In answers on a +# different address than it binds — a domain, or a proxy in front. Left +# empty, links follow the listen address. +base_url = "" # Where drive files, thumbnails and staged upload chunks live as files, # created on boot. Not written here: it defaults to beside the database file, # and the boot completes this file with the value it resolved. @@ -140,6 +144,15 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[ "default_quota_bytes = 10737418240\n" ), ), + ( + "base_url", + concat!( + "# The base of the share links In hands out. Set it when In answers on a\n", + "# different address than it binds — a domain, or a proxy in front. Left\n", + "# empty, links follow the listen address.\n", + "base_url = \"\"\n" + ), + ), ]; /// The `[oidc]` table of `config/in.toml`, before the values are checked. @@ -166,6 +179,7 @@ struct Toml { live_seconds: Option, purge_after_days: Option, default_quota_bytes: Option, + base_url: Option, oidc: Option, #[serde(flatten)] other: std::collections::BTreeMap, @@ -206,6 +220,10 @@ pub struct Config { pub purge_after_days: u32, /// The quota a newly provisioned account starts on, in bytes. pub default_quota_bytes: u64, + /// The origin the public links carry — share links and the copy-once + /// banners that mint them — when the file sets one. `None` follows the + /// address bound. + pub base_url: Option, /// The OIDC provider In trusts. pub oidc: OidcConfig, /// Keys the file sets that nothing here reads, in the order the file @@ -335,6 +353,31 @@ impl Config { let purge_after_days = toml.purge_after_days.unwrap_or(DEFAULT_PURGE_AFTER_DAYS); let default_quota_bytes = toml.default_quota_bytes.unwrap_or(DEFAULT_QUOTA_BYTES); + // The origin public links carry. It has to be joinable to a link — + // scheme and host, no trailing slash — because the link is built as + // `{base_url}/s/{token}`; a value that would make that join a lie + // (`iz.sh`, `https://iz.sh/`) is refused rather than quietly patched, + // like every key here. + let base_url = value(toml.base_url); + if let Some(base) = &base_url { + if !base.starts_with("http://") && !base.starts_with("https://") { + return Err(ConfigError::Invalid { + key: "base_url", + why: format!( + "{base:?} names no scheme — an origin like https://files.example.com is what links are built from" + ), + }); + } + if base.ends_with('/') { + return Err(ConfigError::Invalid { + key: "base_url", + why: format!( + "{base:?} ends in a slash — set the bare origin; In joins the /s/ path itself" + ), + }); + } + } + let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?; let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?; let client_id = value(oidc_toml.client_id).ok_or(ConfigError::Missing("oidc.client_id"))?; @@ -355,6 +398,7 @@ impl Config { live_seconds, purge_after_days, default_quota_bytes, + base_url, oidc: OidcConfig { issuer, client_id, @@ -371,12 +415,24 @@ impl Config { /// A bind that names no interface — `0.0.0.0`, `::` — answers everywhere /// and is reachable at none of it by name, so the loopback stands in: a /// link somebody on the box can click beats a link nobody can. Whoever - /// puts In behind a proxy sets the real address where it is needed (and - /// `redirect_uri` in `[oidc]`), which is the only thing this defers to. + /// puts In behind a proxy sets the real address where it is needed — + /// `base_url` for the public links, `redirect_uri` in `[oidc]` for + /// sign-ins — which is the only thing this defers to. pub fn listen_url(&self) -> String { listen_url_of(&self.listen) } + /// The origin the public links are told: `base_url` when the file sets + /// one, otherwise the address bound. Only public URL construction — the + /// share links and their copy-once banners — asks this; sign-ins keep + /// following `redirect_uri` and the bind never moves. + pub fn public_origin(&self) -> String { + match self.base_url.as_deref() { + Some(base) => base.to_string(), + None => self.listen_url(), + } + } + /// The lines to print once at startup. Nothing secret is among them. pub fn report(&self) -> Vec { let mut lines = vec![ @@ -665,6 +721,60 @@ redirect_uri = "https://files.example.com/auth/callback" ); } + /// The links In hands out follow `listen` unless the file says a public + /// base — the mirror of `redirect_uri`, which is why the tests read the + /// same way. + #[test] + fn base_url_defaults_to_the_listen_address() { + let scratch = Scratch::new(); + scratch.write(FULL); + let config = scratch.load().unwrap(); + assert_eq!(config.base_url, None); + assert_eq!(config.public_origin(), "http://127.0.0.1:7655"); + // The file is completed with the key at its empty default, so a + // reader learns the key exists. + let completed = std::fs::read_to_string(scratch.dir.join(FILE_NAME)).unwrap(); + assert!(completed.contains("base_url = \"\""), "{completed}"); + } + + #[test] + fn an_explicit_base_url_wins() { + let scratch = Scratch::new(); + scratch.write(&FULL.replace("[oidc]", "base_url = \"https://files.example.com\"\n[oidc]")); + let config = scratch.load().unwrap(); + assert_eq!(config.base_url.as_deref(), Some("https://files.example.com")); + assert_eq!(config.public_origin(), "https://files.example.com"); + } + + #[test] + fn an_empty_base_url_is_the_listen_fallback() { + let scratch = Scratch::new(); + scratch.write(&FULL.replace("[oidc]", "base_url = \"\"\n[oidc]")); + let config = scratch.load().unwrap(); + assert_eq!(config.base_url, None); + assert_eq!(config.public_origin(), "http://127.0.0.1:7655"); + } + + #[test] + fn a_base_url_without_a_scheme_is_refused() { + let scratch = Scratch::new(); + scratch.write(&FULL.replace("[oidc]", "base_url = \"files.example.com\"\n[oidc]")); + assert!(matches!( + scratch.load().unwrap_err(), + ConfigError::Invalid { key: "base_url", .. } + )); + } + + #[test] + fn a_base_url_with_a_trailing_slash_is_refused() { + let scratch = Scratch::new(); + scratch.write(&FULL.replace("[oidc]", "base_url = \"https://files.example.com/\"\n[oidc]")); + assert!(matches!( + scratch.load().unwrap_err(), + ConfigError::Invalid { key: "base_url", .. } + )); + } + #[test] fn zero_live_seconds_is_refused() { let scratch = Scratch::new(); diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index d9ac32b..7ae60ea 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -84,9 +84,13 @@ impl TursoStore { /// when `None`. /// /// The boot, in order: create the storage tree, rebuild a stale database - /// before any long-lived handle opens it, migrate an empty one, abort - /// upload sessions past their expiry, and sweep files no row names. - /// Trash is never purged here — see the note on the sweep below. + /// before any long-lived handle opens it, and migrate an empty one. + /// That is all a first request needs. The hygiene sweeps — aborting + /// expired upload sessions, deleting files no row names — wait in + /// [`Self::boot_sweeps`], which the server runs as a background task + /// the moment `open` returns: a restart is not a reason to make the + /// first page wait behind a walk of every file on disk. Trash is never + /// purged here — see the note below. pub async fn open(database: &str, storage: Option<&std::path::Path>) -> Result { let storage_buf; let storage: &std::path::Path = match storage { @@ -142,15 +146,10 @@ impl TursoStore { storage: storage.to_path_buf(), }; store.migrate(database).await?; - store - .prune_expired_uploads(OffsetDateTime::now_utc()) - .await?; - // Trash is deliberately NOT purged here: the age cutoff is the - // deployment's `purge_after_days`, which this signature never sees. - // The server calls `purge_expired` with its configured cutoff right - // after opening; this boot only aborts expired uploads and sweeps - // files no row names. - store.sweep_orphan_files().await?; + // Trash is deliberately NOT swept here either: the age cutoff is + // the deployment's `purge_after_days`, which this signature never + // sees. The server purges with its configured cutoff in the same + // background pass that runs [`Self::boot_sweeps`]. // The file may have been rebuilt from a backup; its permissions and // any transient WAL/SHM siblings should still be private. if database != ":memory:" { @@ -161,6 +160,20 @@ impl TursoStore { Ok(store) } + /// The hygiene a boot owes but a first request does not wait for: + /// abort upload sessions past their expiry, then sweep files no row + /// names. The server runs this as a background task the moment `open` + /// returns, so the port answers while it works; a request racing the + /// sweep still sees a consistent store, because the sweep's deletions + /// are decided under the database's write lock (see + /// [`Self::sweep_orphan_files`]). + pub async fn boot_sweeps(&self) -> Result<()> { + self.prune_expired_uploads(OffsetDateTime::now_utc()) + .await?; + self.sweep_orphan_files().await + } + + /// Sets the storage tree against the database, once per boot. The /// database and the tree are two halves of one state, and a crash between /// a row write and its file write — either order — leaves exactly one @@ -170,15 +183,29 @@ impl TursoStore { /// deleting the row would turn a lost file into a lost fact — the row is /// still what screens list, and a re-upload replaces it cleanly. async fn sweep_orphan_files(&self) -> Result<()> { - let conn = self.conn.lock().await; - let files = known_ids(&conn, "SELECT id FROM file").await?; - let thumbs = known_ids(&conn, "SELECT id FROM file WHERE thumb_state = 'ready'").await?; + // The whole pass — the id reads and the directory walks — holds the + // database's write lock. A writer lands a new file while holding + // that same lock (the bytes go down before the row, inside one + // IMMEDIATE transaction), so a file the walk cannot name was either + // written entirely before this lock was taken — and then its row is + // in the id set — or is written entirely after the lock is released. + // A sweep that could run between a file's bytes and its row would + // delete an upload the server had already accepted; while the sweeps + // ran inside `open`, before any request could arrive, the boot order + // made that impossible, and this lock is what keeps it impossible + // now that the server answers while the sweep runs. + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let files = known_ids(&tx, "SELECT id FROM file").await?; + let thumbs = known_ids(&tx, "SELECT id FROM file WHERE thumb_state = 'ready'").await?; let sessions = known_ids( - &conn, + &tx, "SELECT id FROM upload_session WHERE state = 'active'", ) .await?; - drop(conn); for (dir, known, kind) in [ (self.storage.join(FILES_DIR), &files, "file"), (self.storage.join(THUMBS_DIR), &thumbs, "thumbnail"), @@ -237,6 +264,9 @@ impl TursoStore { ); } } + // Nothing was written through the transaction: it exists to hold + // the write lock across the walk, and committing it ends the pass. + tx.commit().await.map_err(backend)?; Ok(()) } diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index 481536c..12c26d8 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -39,8 +39,9 @@ impl Scratch { } } - /// Reopens the same database file, running the boot path again — the - /// sweep, the prune, the purge — against what the test left behind. + /// Reopens the same database file, then runs the hygiene passes the + /// server runs in the background after `open` — the upload prune and + /// the orphan sweep — against what the test left behind. async fn reopen(&mut self) { drop(std::mem::replace( &mut self.store, @@ -48,6 +49,7 @@ impl Scratch { .await .unwrap(), )); + self.store.boot_sweeps().await.unwrap(); } } @@ -1051,6 +1053,73 @@ async fn the_boot_prune_aborts_expired_sessions() { assert_eq!(back.state, UploadState::Aborted); assert!(!scratch.storage.join("uploads").join(&session.id).exists()); } + +/// The sweep runs beside live traffic now, and a writer's bytes land on +/// disk before its row commits — both inside one write lock. This pins the +/// lock's job: a writer mid-insert (its file already on disk, its row +/// uncommitted, its transaction holding the write lock) must survive a +/// sweep that starts while it works. The sweep waits for the writer's lock +/// instead of reading the tree in between, so the committed file and its +/// bytes both come out the other side — while a stray nothing names still +/// goes, proving the sweep ran at all. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_sweep_waits_for_a_writer_instead_of_deleting_its_file() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + + // A writer the way `insert_file` is built: IMMEDIATE transaction + // first, then bytes on disk, then the row — the lock held throughout. + let db_path = scratch.db.clone(); + let file_path = scratch.storage.join("files").join("midwrite"); + let writer_path = file_path.clone(); + let (locked, locked_rx) = tokio::sync::oneshot::channel::<()>(); + let (go, go_rx) = tokio::sync::oneshot::channel::<()>(); + let writer = tokio::spawn(async move { + let db = turso::Builder::new_local(db_path.to_str().unwrap()) + .build() + .await + .unwrap(); + let conn = db.connect().unwrap(); + conn.execute("BEGIN IMMEDIATE", ()).await.unwrap(); + std::fs::write(&writer_path, b"arriving").unwrap(); + conn.execute( + "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \ + thumb_state, created_at, updated_at, deleted_at, download_count) \ + VALUES ('midwrite', ?1, NULL, 'midwrite.txt', 'text/plain', 8, 'none', \ + '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', NULL, 0)", + turso::params![user.id.as_str()], + ) + .await + .unwrap(); + let _ = locked.send(()); + // Hold the write lock until the sweep is contending on it: only a + // sweep that waits can then see the committed row. + let _ = go_rx.await; + conn.execute("COMMIT", ()).await.unwrap(); + }); + + locked_rx.await.unwrap(); + std::fs::write(scratch.storage.join("files").join("stray"), b"orphan").unwrap(); + let sweep = tokio::spawn({ + let storage = scratch.storage.clone(); + async move { + // The sweep contends here: its BEGIN IMMEDIATE cannot be + // granted until the writer commits, and the sleep only makes + // that contention certain rather than likely. + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + let _ = go.send(()); + storage + } + }); + scratch.store.boot_sweeps().await.unwrap(); + writer.await.unwrap(); + let storage = sweep.await.unwrap(); + // The sweep ran — the stray is gone — and the writer's file survived, + // row and bytes both. + assert!(!storage.join("files").join("stray").exists()); + assert!(scratch.store.file("midwrite").await.unwrap().is_some()); + assert!(file_path.exists()); +} #[tokio::test] async fn email_lookup_folds_case() { let scratch = Scratch::open().await; diff --git a/crates/in-web/src/drive.rs b/crates/in-web/src/drive.rs index 8706516..0b6da35 100644 --- a/crates/in-web/src/drive.rs +++ b/crates/in-web/src/drive.rs @@ -505,7 +505,7 @@ async fn drive(cx: &Cx) -> Result { // A link minted from this surface redirects back here with the plaintext // token on `?created=` — rendered once, like the settings page does. let created = created_token(uri(cx).query().unwrap_or("")); - let origin = app(cx).config.listen_url(); + let origin = app(cx).config.public_origin(); let current_id = current .as_ref() @@ -549,7 +549,7 @@ async fn drive(cx: &Cx) -> Result { let share_pair = params.as_ref().and_then(|query| query.share.as_deref()); let share_dialog = match share_pair.and_then(|pair| pair.split_once(':')) { Some((kind, id)) => { - crate::share::share_modal(cx, kind, id, &here, created.clone(), &origin).await? + crate::share::share_modal(cx, kind, id, &here, created.clone()).await? } None => None, }; diff --git a/crates/in-web/src/files.rs b/crates/in-web/src/files.rs index 9d25683..690d98c 100644 --- a/crates/in-web/src/files.rs +++ b/crates/in-web/src/files.rs @@ -529,14 +529,8 @@ async fn view_file(cx: &Cx) -> Result { if matches!(viewer_kind(&file.mime), Some(ViewerKind::Image | ViewerKind::Video | ViewerKind::Audio)) || may_download { match viewer_kind(&file.mime) { Some(ViewerKind::Image) => (file.name.clone()), - Some(ViewerKind::Video) =>
- -
(media_controls(cx, language, file.name.clone(), true).await?)
-
, - Some(ViewerKind::Audio) =>
- (media_controls(cx, language, file.name.clone(), false).await?) - -
, + Some(ViewerKind::Video) => (media_player(cx, language, file.name.clone(), src.clone(), true).await?), + Some(ViewerKind::Audio) => (media_player(cx, language, file.name.clone(), src.clone(), false).await?), Some(ViewerKind::Pdf) =>

(t(language, Key::PreviewUnavailable))

, @@ -576,6 +570,38 @@ async fn view_file(cx: &Cx) -> Result { } } +/// The house player for one inline media element, shared verbatim by the +/// signed-in viewer (`/view/{id}`, fed by `/file/{id}`) and the public +/// share card (`/s/{token}`, fed by `?media=1`): the controls-less +/// `