forge
Explore
Log in

Don't you dare go Hollow

The public half joins the house — shell, player, domains, fast boots, phones

Browse files at this commit

16e8c67cafaadb55dcb60349b56dc3f76625b3e7Ahmet Kaan GümüşParent: c36b77c
  • feat
    • the public half joins the house — shell, player, domains, fast boots, phones
Show full message
feat(web): the public half joins the house — shell, player, domains, fast boots, phones

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.tomlmodified+4 -0
@@ -12,6 +12,10 @@ live_seconds = 300
12 purge_after_days = 3012 purge_after_days = 30
13 # The quota a newly provisioned account starts on, in bytes. 10 GiB.13 # The quota a newly provisioned account starts on, in bytes. 10 GiB.
14 default_quota_bytes = 1073741824014 default_quota_bytes = 10737418240
15+# The base of the share links In hands out. Set it when In answers on a
16+# different address than it binds — a domain, or a proxy in front. Left
17+# empty, links follow the listen address.
18+base_url = ""
15 # Where drive files, thumbnails and staged upload chunks live as files,19 # Where drive files, thumbnails and staged upload chunks live as files,
16 # created on boot. Not written here: it defaults to beside the database file,20 # created on boot. Not written here: it defaults to beside the database file,
17 # and the boot completes this file with the value it resolved.21 # and the boot completes this file with the value it resolved.
crates/in-core/src/config.rsmodified+112 -2
@@ -60,6 +60,10 @@ live_seconds = 300
60 purge_after_days = 3060 purge_after_days = 30
61 # The quota a newly provisioned account starts on, in bytes. 10 GiB.61 # The quota a newly provisioned account starts on, in bytes. 10 GiB.
62 default_quota_bytes = 1073741824062 default_quota_bytes = 10737418240
63+# The base of the share links In hands out. Set it when In answers on a
64+# different address than it binds — a domain, or a proxy in front. Left
65+# empty, links follow the listen address.
66+base_url = ""
63 # Where drive files, thumbnails and staged upload chunks live as files,67 # Where drive files, thumbnails and staged upload chunks live as files,
64 # created on boot. Not written here: it defaults to beside the database file,68 # created on boot. Not written here: it defaults to beside the database file,
65 # and the boot completes this file with the value it resolved.69 # and the boot completes this file with the value it resolved.
@@ -140,6 +144,15 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[
140 "default_quota_bytes = 10737418240\n"144 "default_quota_bytes = 10737418240\n"
141 ),145 ),
142 ),146 ),
147+ (
148+ "base_url",
149+ concat!(
150+ "# The base of the share links In hands out. Set it when In answers on a\n",
151+ "# different address than it binds — a domain, or a proxy in front. Left\n",
152+ "# empty, links follow the listen address.\n",
153+ "base_url = \"\"\n"
154+ ),
155+ ),
143 ];156 ];
144 157
145 /// The `[oidc]` table of `config/in.toml`, before the values are checked.158 /// The `[oidc]` table of `config/in.toml`, before the values are checked.
@@ -166,6 +179,7 @@ struct Toml {
166 live_seconds: Option<u64>,179 live_seconds: Option<u64>,
167 purge_after_days: Option<u32>,180 purge_after_days: Option<u32>,
168 default_quota_bytes: Option<u64>,181 default_quota_bytes: Option<u64>,
182+ base_url: Option<String>,
169 oidc: Option<OidcToml>,183 oidc: Option<OidcToml>,
170 #[serde(flatten)]184 #[serde(flatten)]
171 other: std::collections::BTreeMap<String, toml::Value>,185 other: std::collections::BTreeMap<String, toml::Value>,
@@ -206,6 +220,10 @@ pub struct Config {
206 pub purge_after_days: u32,220 pub purge_after_days: u32,
207 /// The quota a newly provisioned account starts on, in bytes.221 /// The quota a newly provisioned account starts on, in bytes.
208 pub default_quota_bytes: u64,222 pub default_quota_bytes: u64,
223+ /// The origin the public links carry — share links and the copy-once
224+ /// banners that mint them — when the file sets one. `None` follows the
225+ /// address bound.
226+ pub base_url: Option<String>,
209 /// The OIDC provider In trusts.227 /// The OIDC provider In trusts.
210 pub oidc: OidcConfig,228 pub oidc: OidcConfig,
211 /// Keys the file sets that nothing here reads, in the order the file229 /// Keys the file sets that nothing here reads, in the order the file
@@ -335,6 +353,31 @@ impl Config {
335 let purge_after_days = toml.purge_after_days.unwrap_or(DEFAULT_PURGE_AFTER_DAYS);353 let purge_after_days = toml.purge_after_days.unwrap_or(DEFAULT_PURGE_AFTER_DAYS);
336 let default_quota_bytes = toml.default_quota_bytes.unwrap_or(DEFAULT_QUOTA_BYTES);354 let default_quota_bytes = toml.default_quota_bytes.unwrap_or(DEFAULT_QUOTA_BYTES);
337 355
356+ // The origin public links carry. It has to be joinable to a link —
357+ // scheme and host, no trailing slash — because the link is built as
358+ // `{base_url}/s/{token}`; a value that would make that join a lie
359+ // (`iz.sh`, `https://iz.sh/`) is refused rather than quietly patched,
360+ // like every key here.
361+ let base_url = value(toml.base_url);
362+ if let Some(base) = &base_url {
363+ if !base.starts_with("http://") && !base.starts_with("https://") {
364+ return Err(ConfigError::Invalid {
365+ key: "base_url",
366+ why: format!(
367+ "{base:?} names no scheme — an origin like https://files.example.com is what links are built from"
368+ ),
369+ });
370+ }
371+ if base.ends_with('/') {
372+ return Err(ConfigError::Invalid {
373+ key: "base_url",
374+ why: format!(
375+ "{base:?} ends in a slash — set the bare origin; In joins the /s/ path itself"
376+ ),
377+ });
378+ }
379+ }
380+
338 let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?;381 let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?;
339 let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?;382 let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?;
340 let client_id = value(oidc_toml.client_id).ok_or(ConfigError::Missing("oidc.client_id"))?;383 let client_id = value(oidc_toml.client_id).ok_or(ConfigError::Missing("oidc.client_id"))?;
@@ -355,6 +398,7 @@ impl Config {
355 live_seconds,398 live_seconds,
356 purge_after_days,399 purge_after_days,
357 default_quota_bytes,400 default_quota_bytes,
401+ base_url,
358 oidc: OidcConfig {402 oidc: OidcConfig {
359 issuer,403 issuer,
360 client_id,404 client_id,
@@ -371,12 +415,24 @@ impl Config {
371 /// A bind that names no interface — `0.0.0.0`, `::` — answers everywhere415 /// A bind that names no interface — `0.0.0.0`, `::` — answers everywhere
372 /// and is reachable at none of it by name, so the loopback stands in: a416 /// and is reachable at none of it by name, so the loopback stands in: a
373 /// link somebody on the box can click beats a link nobody can. Whoever417 /// link somebody on the box can click beats a link nobody can. Whoever
374- /// puts In behind a proxy sets the real address where it is needed (and418+ /// puts In behind a proxy sets the real address where it is needed —
375- /// `redirect_uri` in `[oidc]`), which is the only thing this defers to.419+ /// `base_url` for the public links, `redirect_uri` in `[oidc]` for
420+ /// sign-ins — which is the only thing this defers to.
376 pub fn listen_url(&self) -> String {421 pub fn listen_url(&self) -> String {
377 listen_url_of(&self.listen)422 listen_url_of(&self.listen)
378 }423 }
379 424
425+ /// The origin the public links are told: `base_url` when the file sets
426+ /// one, otherwise the address bound. Only public URL construction — the
427+ /// share links and their copy-once banners — asks this; sign-ins keep
428+ /// following `redirect_uri` and the bind never moves.
429+ pub fn public_origin(&self) -> String {
430+ match self.base_url.as_deref() {
431+ Some(base) => base.to_string(),
432+ None => self.listen_url(),
433+ }
434+ }
435+
380 /// The lines to print once at startup. Nothing secret is among them.436 /// The lines to print once at startup. Nothing secret is among them.
381 pub fn report(&self) -> Vec<String> {437 pub fn report(&self) -> Vec<String> {
382 let mut lines = vec![438 let mut lines = vec![
@@ -665,6 +721,60 @@ redirect_uri = "https://files.example.com/auth/callback"
665 );721 );
666 }722 }
667 723
724+ /// The links In hands out follow `listen` unless the file says a public
725+ /// base — the mirror of `redirect_uri`, which is why the tests read the
726+ /// same way.
727+ #[test]
728+ fn base_url_defaults_to_the_listen_address() {
729+ let scratch = Scratch::new();
730+ scratch.write(FULL);
731+ let config = scratch.load().unwrap();
732+ assert_eq!(config.base_url, None);
733+ assert_eq!(config.public_origin(), "http://127.0.0.1:7655");
734+ // The file is completed with the key at its empty default, so a
735+ // reader learns the key exists.
736+ let completed = std::fs::read_to_string(scratch.dir.join(FILE_NAME)).unwrap();
737+ assert!(completed.contains("base_url = \"\""), "{completed}");
738+ }
739+
740+ #[test]
741+ fn an_explicit_base_url_wins() {
742+ let scratch = Scratch::new();
743+ scratch.write(&FULL.replace("[oidc]", "base_url = \"https://files.example.com\"\n[oidc]"));
744+ let config = scratch.load().unwrap();
745+ assert_eq!(config.base_url.as_deref(), Some("https://files.example.com"));
746+ assert_eq!(config.public_origin(), "https://files.example.com");
747+ }
748+
749+ #[test]
750+ fn an_empty_base_url_is_the_listen_fallback() {
751+ let scratch = Scratch::new();
752+ scratch.write(&FULL.replace("[oidc]", "base_url = \"\"\n[oidc]"));
753+ let config = scratch.load().unwrap();
754+ assert_eq!(config.base_url, None);
755+ assert_eq!(config.public_origin(), "http://127.0.0.1:7655");
756+ }
757+
758+ #[test]
759+ fn a_base_url_without_a_scheme_is_refused() {
760+ let scratch = Scratch::new();
761+ scratch.write(&FULL.replace("[oidc]", "base_url = \"files.example.com\"\n[oidc]"));
762+ assert!(matches!(
763+ scratch.load().unwrap_err(),
764+ ConfigError::Invalid { key: "base_url", .. }
765+ ));
766+ }
767+
768+ #[test]
769+ fn a_base_url_with_a_trailing_slash_is_refused() {
770+ let scratch = Scratch::new();
771+ scratch.write(&FULL.replace("[oidc]", "base_url = \"https://files.example.com/\"\n[oidc]"));
772+ assert!(matches!(
773+ scratch.load().unwrap_err(),
774+ ConfigError::Invalid { key: "base_url", .. }
775+ ));
776+ }
777+
668 #[test]778 #[test]
669 fn zero_live_seconds_is_refused() {779 fn zero_live_seconds_is_refused() {
670 let scratch = Scratch::new();780 let scratch = Scratch::new();
crates/in-core/src/store/turso_store.rsmodified+47 -17
@@ -84,9 +84,13 @@ impl TursoStore {
84 /// when `None`.84 /// when `None`.
85 ///85 ///
86 /// The boot, in order: create the storage tree, rebuild a stale database86 /// The boot, in order: create the storage tree, rebuild a stale database
87- /// before any long-lived handle opens it, migrate an empty one, abort87+ /// before any long-lived handle opens it, and migrate an empty one.
88- /// upload sessions past their expiry, and sweep files no row names.88+ /// That is all a first request needs. The hygiene sweeps — aborting
89- /// Trash is never purged here — see the note on the sweep below.89+ /// expired upload sessions, deleting files no row names — wait in
90+ /// [`Self::boot_sweeps`], which the server runs as a background task
91+ /// the moment `open` returns: a restart is not a reason to make the
92+ /// first page wait behind a walk of every file on disk. Trash is never
93+ /// purged here — see the note below.
90 pub async fn open(database: &str, storage: Option<&std::path::Path>) -> Result<Self> {94 pub async fn open(database: &str, storage: Option<&std::path::Path>) -> Result<Self> {
91 let storage_buf;95 let storage_buf;
92 let storage: &std::path::Path = match storage {96 let storage: &std::path::Path = match storage {
@@ -142,15 +146,10 @@ impl TursoStore {
142 storage: storage.to_path_buf(),146 storage: storage.to_path_buf(),
143 };147 };
144 store.migrate(database).await?;148 store.migrate(database).await?;
145- store149+ // Trash is deliberately NOT swept here either: the age cutoff is
146- .prune_expired_uploads(OffsetDateTime::now_utc())150+ // the deployment's `purge_after_days`, which this signature never
147- .await?;151+ // sees. The server purges with its configured cutoff in the same
148- // Trash is deliberately NOT purged here: the age cutoff is the152+ // background pass that runs [`Self::boot_sweeps`].
149- // deployment's `purge_after_days`, which this signature never sees.
150- // The server calls `purge_expired` with its configured cutoff right
151- // after opening; this boot only aborts expired uploads and sweeps
152- // files no row names.
153- store.sweep_orphan_files().await?;
154 // The file may have been rebuilt from a backup; its permissions and153 // The file may have been rebuilt from a backup; its permissions and
155 // any transient WAL/SHM siblings should still be private.154 // any transient WAL/SHM siblings should still be private.
156 if database != ":memory:" {155 if database != ":memory:" {
@@ -161,6 +160,20 @@ impl TursoStore {
161 Ok(store)160 Ok(store)
162 }161 }
163 162
163+ /// The hygiene a boot owes but a first request does not wait for:
164+ /// abort upload sessions past their expiry, then sweep files no row
165+ /// names. The server runs this as a background task the moment `open`
166+ /// returns, so the port answers while it works; a request racing the
167+ /// sweep still sees a consistent store, because the sweep's deletions
168+ /// are decided under the database's write lock (see
169+ /// [`Self::sweep_orphan_files`]).
170+ pub async fn boot_sweeps(&self) -> Result<()> {
171+ self.prune_expired_uploads(OffsetDateTime::now_utc())
172+ .await?;
173+ self.sweep_orphan_files().await
174+ }
175+
176+
164 /// Sets the storage tree against the database, once per boot. The177 /// Sets the storage tree against the database, once per boot. The
165 /// database and the tree are two halves of one state, and a crash between178 /// database and the tree are two halves of one state, and a crash between
166 /// a row write and its file write — either order — leaves exactly one179 /// a row write and its file write — either order — leaves exactly one
@@ -170,15 +183,29 @@ impl TursoStore {
170 /// deleting the row would turn a lost file into a lost fact — the row is183 /// deleting the row would turn a lost file into a lost fact — the row is
171 /// still what screens list, and a re-upload replaces it cleanly.184 /// still what screens list, and a re-upload replaces it cleanly.
172 async fn sweep_orphan_files(&self) -> Result<()> {185 async fn sweep_orphan_files(&self) -> Result<()> {
173- let conn = self.conn.lock().await;186+ // The whole pass — the id reads and the directory walks — holds the
174- let files = known_ids(&conn, "SELECT id FROM file").await?;187+ // database's write lock. A writer lands a new file while holding
175- let thumbs = known_ids(&conn, "SELECT id FROM file WHERE thumb_state = 'ready'").await?;188+ // that same lock (the bytes go down before the row, inside one
189+ // IMMEDIATE transaction), so a file the walk cannot name was either
190+ // written entirely before this lock was taken — and then its row is
191+ // in the id set — or is written entirely after the lock is released.
192+ // A sweep that could run between a file's bytes and its row would
193+ // delete an upload the server had already accepted; while the sweeps
194+ // ran inside `open`, before any request could arrive, the boot order
195+ // made that impossible, and this lock is what keeps it impossible
196+ // now that the server answers while the sweep runs.
197+ let mut conn = self.tx_conn().await?;
198+ let tx = conn
199+ .transaction_with_behavior(TransactionBehavior::Immediate)
200+ .await
201+ .map_err(backend)?;
202+ let files = known_ids(&tx, "SELECT id FROM file").await?;
203+ let thumbs = known_ids(&tx, "SELECT id FROM file WHERE thumb_state = 'ready'").await?;
176 let sessions = known_ids(204 let sessions = known_ids(
177- &conn,205+ &tx,
178 "SELECT id FROM upload_session WHERE state = 'active'",206 "SELECT id FROM upload_session WHERE state = 'active'",
179 )207 )
180 .await?;208 .await?;
181- drop(conn);
182 for (dir, known, kind) in [209 for (dir, known, kind) in [
183 (self.storage.join(FILES_DIR), &files, "file"),210 (self.storage.join(FILES_DIR), &files, "file"),
184 (self.storage.join(THUMBS_DIR), &thumbs, "thumbnail"),211 (self.storage.join(THUMBS_DIR), &thumbs, "thumbnail"),
@@ -237,6 +264,9 @@ impl TursoStore {
237 );264 );
238 }265 }
239 }266 }
267+ // Nothing was written through the transaction: it exists to hold
268+ // the write lock across the walk, and committing it ends the pass.
269+ tx.commit().await.map_err(backend)?;
240 Ok(())270 Ok(())
241 }271 }
242 272
crates/in-core/tests/store.rsmodified+71 -2
@@ -39,8 +39,9 @@ impl Scratch {
39 }39 }
40 }40 }
41 41
42- /// Reopens the same database file, running the boot path again — the42+ /// Reopens the same database file, then runs the hygiene passes the
43- /// sweep, the prune, the purge — against what the test left behind.43+ /// server runs in the background after `open` — the upload prune and
44+ /// the orphan sweep — against what the test left behind.
44 async fn reopen(&mut self) {45 async fn reopen(&mut self) {
45 drop(std::mem::replace(46 drop(std::mem::replace(
46 &mut self.store,47 &mut self.store,
@@ -48,6 +49,7 @@ impl Scratch {
48 .await49 .await
49 .unwrap(),50 .unwrap(),
50 ));51 ));
52+ self.store.boot_sweeps().await.unwrap();
51 }53 }
52 }54 }
53 55
@@ -1051,6 +1053,73 @@ async fn the_boot_prune_aborts_expired_sessions() {
1051 assert_eq!(back.state, UploadState::Aborted);1053 assert_eq!(back.state, UploadState::Aborted);
1052 assert!(!scratch.storage.join("uploads").join(&session.id).exists());1054 assert!(!scratch.storage.join("uploads").join(&session.id).exists());
1053 }1055 }
1056+
1057+/// The sweep runs beside live traffic now, and a writer's bytes land on
1058+/// disk before its row commits — both inside one write lock. This pins the
1059+/// lock's job: a writer mid-insert (its file already on disk, its row
1060+/// uncommitted, its transaction holding the write lock) must survive a
1061+/// sweep that starts while it works. The sweep waits for the writer's lock
1062+/// instead of reading the tree in between, so the committed file and its
1063+/// bytes both come out the other side — while a stray nothing names still
1064+/// goes, proving the sweep ran at all.
1065+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1066+async fn the_sweep_waits_for_a_writer_instead_of_deleting_its_file() {
1067+ let scratch = Scratch::open().await;
1068+ let user = alice(&scratch.store).await;
1069+
1070+ // A writer the way `insert_file` is built: IMMEDIATE transaction
1071+ // first, then bytes on disk, then the row — the lock held throughout.
1072+ let db_path = scratch.db.clone();
1073+ let file_path = scratch.storage.join("files").join("midwrite");
1074+ let writer_path = file_path.clone();
1075+ let (locked, locked_rx) = tokio::sync::oneshot::channel::<()>();
1076+ let (go, go_rx) = tokio::sync::oneshot::channel::<()>();
1077+ let writer = tokio::spawn(async move {
1078+ let db = turso::Builder::new_local(db_path.to_str().unwrap())
1079+ .build()
1080+ .await
1081+ .unwrap();
1082+ let conn = db.connect().unwrap();
1083+ conn.execute("BEGIN IMMEDIATE", ()).await.unwrap();
1084+ std::fs::write(&writer_path, b"arriving").unwrap();
1085+ conn.execute(
1086+ "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \
1087+ thumb_state, created_at, updated_at, deleted_at, download_count) \
1088+ VALUES ('midwrite', ?1, NULL, 'midwrite.txt', 'text/plain', 8, 'none', \
1089+ '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', NULL, 0)",
1090+ turso::params![user.id.as_str()],
1091+ )
1092+ .await
1093+ .unwrap();
1094+ let _ = locked.send(());
1095+ // Hold the write lock until the sweep is contending on it: only a
1096+ // sweep that waits can then see the committed row.
1097+ let _ = go_rx.await;
1098+ conn.execute("COMMIT", ()).await.unwrap();
1099+ });
1100+
1101+ locked_rx.await.unwrap();
1102+ std::fs::write(scratch.storage.join("files").join("stray"), b"orphan").unwrap();
1103+ let sweep = tokio::spawn({
1104+ let storage = scratch.storage.clone();
1105+ async move {
1106+ // The sweep contends here: its BEGIN IMMEDIATE cannot be
1107+ // granted until the writer commits, and the sleep only makes
1108+ // that contention certain rather than likely.
1109+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1110+ let _ = go.send(());
1111+ storage
1112+ }
1113+ });
1114+ scratch.store.boot_sweeps().await.unwrap();
1115+ writer.await.unwrap();
1116+ let storage = sweep.await.unwrap();
1117+ // The sweep ran — the stray is gone — and the writer's file survived,
1118+ // row and bytes both.
1119+ assert!(!storage.join("files").join("stray").exists());
1120+ assert!(scratch.store.file("midwrite").await.unwrap().is_some());
1121+ assert!(file_path.exists());
1122+}
1054 #[tokio::test]1123 #[tokio::test]
1055 async fn email_lookup_folds_case() {1124 async fn email_lookup_folds_case() {
1056 let scratch = Scratch::open().await;1125 let scratch = Scratch::open().await;
crates/in-web/src/drive.rsmodified+2 -2
@@ -505,7 +505,7 @@ async fn drive(cx: &Cx) -> Result {
505 // A link minted from this surface redirects back here with the plaintext505 // A link minted from this surface redirects back here with the plaintext
506 // token on `?created=` — rendered once, like the settings page does.506 // token on `?created=` — rendered once, like the settings page does.
507 let created = created_token(uri(cx).query().unwrap_or(""));507 let created = created_token(uri(cx).query().unwrap_or(""));
508- let origin = app(cx).config.listen_url();508+ let origin = app(cx).config.public_origin();
509 509
510 let current_id = current510 let current_id = current
511 .as_ref()511 .as_ref()
@@ -549,7 +549,7 @@ async fn drive(cx: &Cx) -> Result {
549 let share_pair = params.as_ref().and_then(|query| query.share.as_deref());549 let share_pair = params.as_ref().and_then(|query| query.share.as_deref());
550 let share_dialog = match share_pair.and_then(|pair| pair.split_once(':')) {550 let share_dialog = match share_pair.and_then(|pair| pair.split_once(':')) {
551 Some((kind, id)) => {551 Some((kind, id)) => {
552- crate::share::share_modal(cx, kind, id, &here, created.clone(), &origin).await?552+ crate::share::share_modal(cx, kind, id, &here, created.clone()).await?
553 }553 }
554 None => None,554 None => None,
555 };555 };
crates/in-web/src/files.rsmodified+35 -9
@@ -529,14 +529,8 @@ async fn view_file(cx: &Cx) -> Result {
529 if matches!(viewer_kind(&file.mime), Some(ViewerKind::Image | ViewerKind::Video | ViewerKind::Audio)) || may_download {529 if matches!(viewer_kind(&file.mime), Some(ViewerKind::Image | ViewerKind::Video | ViewerKind::Audio)) || may_download {
530 match viewer_kind(&file.mime) {530 match viewer_kind(&file.mime) {
531 Some(ViewerKind::Image) => <img class="viewer-media" src=(src.clone()) alt=(file.name.clone()) draggable="false">,531 Some(ViewerKind::Image) => <img class="viewer-media" src=(src.clone()) alt=(file.name.clone()) draggable="false">,
532- Some(ViewerKind::Video) => <div class="media-player media-player-video">532+ Some(ViewerKind::Video) => (media_player(cx, language, file.name.clone(), src.clone(), true).await?),
533- <video class="media-el viewer-video" src=(src.clone()) preload="metadata"></video>533+ Some(ViewerKind::Audio) => (media_player(cx, language, file.name.clone(), src.clone(), false).await?),
534- <div class="media-controls">(media_controls(cx, language, file.name.clone(), true).await?)</div>
535- </div>,
536- Some(ViewerKind::Audio) => <div class="media-player">
537- (media_controls(cx, language, file.name.clone(), false).await?)
538- <audio class="media-el" src=(src.clone()) preload="metadata"></audio>
539- </div>,
540 Some(ViewerKind::Pdf) => <object class="viewer-media viewer-pdf" data=(src.clone()) type="application/pdf">534 Some(ViewerKind::Pdf) => <object class="viewer-media viewer-pdf" data=(src.clone()) type="application/pdf">
541 <p class="field-note">(t(language, Key::PreviewUnavailable))</p>535 <p class="field-note">(t(language, Key::PreviewUnavailable))</p>
542 </object>,536 </object>,
@@ -576,6 +570,38 @@ async fn view_file(cx: &Cx) -> Result {
576 }570 }
577 }571 }
578 572
573+/// The house player for one inline media element, shared verbatim by the
574+/// signed-in viewer (`/view/{id}`, fed by `/file/{id}`) and the public
575+/// share card (`/s/{token}`, fed by `?media=1`): the controls-less
576+/// `<video>`/`<audio>` and the bar that drives it, wired by
577+/// [`media_player_script`]. `video` picks the stacked video layout —
578+/// picture with the bar beneath — over the audio bar.
579+pub(crate) async fn media_player(
580+ cx: &Cx,
581+ language: crate::i18n::Lang,
582+ name: String,
583+ src: String,
584+ video: bool,
585+) -> Result {
586+ if video {
587+ view! {
588+ cx =>
589+ <div class="media-player media-player-video">
590+ <video class="media-el viewer-video" src=(src) preload="metadata"></video>
591+ <div class="media-controls">(media_controls(cx, language, name, true).await?)</div>
592+ </div>
593+ }
594+ } else {
595+ view! {
596+ cx =>
597+ <div class="media-player">
598+ (media_controls(cx, language, name, false).await?)
599+ <audio class="media-el" src=(src) preload="metadata"></audio>
600+ </div>
601+ }
602+ }
603+}
604+
579 /// The one controls bar both media players draw: play toggle, clock, seek,605 /// The one controls bar both media players draw: play toggle, clock, seek,
580 /// volume (mute + level), a speed cycle, and fullscreen on video. The script606 /// volume (mute + level), a speed cycle, and fullscreen on video. The script
581 /// below wires it by class, so the bar stays markup-only.607 /// below wires it by class, so the bar stays markup-only.
@@ -612,7 +638,7 @@ async fn media_controls(cx: &Cx, language: crate::i18n::Lang, name: String, vide
612 /// (ported from iz's audio player, one player for both media kinds). Wiring638 /// (ported from iz's audio player, one player for both media kinds). Wiring
613 /// is per-player and idempotent (`data-wired`), re-run on `in:wire` so a639 /// is per-player and idempotent (`data-wired`), re-run on `in:wire` so a
614 /// player arriving in a soft page swap still gets its controls.640 /// player arriving in a soft page swap still gets its controls.
615-async fn media_player_script(cx: &Cx) -> Result {641+pub(crate) async fn media_player_script(cx: &Cx) -> Result {
616 use topcoat::view::Unescaped;642 use topcoat::view::Unescaped;
617 const JS: &str = "\643 const JS: &str = "\
618 (function () { \644 (function () { \
crates/in-web/src/layout.rsmodified+18 -2
@@ -993,8 +993,16 @@ async fn missing() -> Result {
993 /// `style/main.scss`, compiled by `build.rs` into `assets/main.css`.993 /// `style/main.scss`, compiled by `build.rs` into `assets/main.css`.
994 const STYLE: Asset = asset!("assets/main.css");994 const STYLE: Asset = asset!("assets/main.css");
995 995
996-#[layout("/")]996+/// The document shell itself: everything from `<html>` to `</html>`, the
997-async fn root_layout(cx: &Cx, slot: Result) -> Result {997+/// part `root_layout` pairs around every page. `#[route]` handlers bypass
998+/// layout pairing — the public share pages among them, whose query can ask
999+/// for bytes a page-shaped answer cannot carry — so this is `pub(crate)`:
1000+/// they wrap their views in the same shell by calling it directly instead of
1001+/// hand-copying the head. Signed-out visitors wear the provision defaults
1002+/// and the session-gated live stream stays off (`asking` is false without a
1003+/// session), so a stranger's page carries no user data and opens no
1004+/// `/api/live` connection.
1005+pub(crate) async fn document_shell(cx: &Cx, slot: Result) -> Result {
998 // The per-user chrome knobs, read off the request's own user: the theme1006 // The per-user chrome knobs, read off the request's own user: the theme
999 // into `data-theme`, the interface into `data-ui`, the language into1007 // into `data-theme`, the interface into `data-ui`, the language into
1000 // `<html lang>`. Signed-out (or unreadable) wears the provision defaults —1008 // `<html lang>`. Signed-out (or unreadable) wears the provision defaults —
@@ -1027,6 +1035,7 @@ async fn root_layout(cx: &Cx, slot: Result) -> Result {
1027 // the client's cue to hard-reload rather than wear the old css.1035 // the client's cue to hard-reload rather than wear the old css.
1028 let build = STYLE.id().as_u64().to_string();1036 let build = STYLE.id().as_u64().to_string();
1029 view! {1037 view! {
1038+ cx =>
1030 <!DOCTYPE html>1039 <!DOCTYPE html>
1031 <html lang=(lang.code()) data-theme=(dark.then_some("dark")) data-ui=(ui) data-build=(build)>1040 <html lang=(lang.code()) data-theme=(dark.then_some("dark")) data-ui=(ui) data-build=(build)>
1032 <head>1041 <head>
@@ -1064,3 +1073,10 @@ async fn root_layout(cx: &Cx, slot: Result) -> Result {
1064 </html>1073 </html>
1065 }1074 }
1066 }1075 }
1076+
1077+/// The router's own shell route: pairing is by path prefix, so every page
1078+/// under `/` wears `document_shell` through here.
1079+#[layout("/")]
1080+async fn root_layout(cx: &Cx, slot: Result) -> Result {
1081+ document_shell(cx, slot).await
1082+}
crates/in-web/src/main.rsmodified+25 -10
@@ -1,7 +1,7 @@
1 use std::sync::Arc;1 use std::sync::Arc;
2 2
3 use in_core::Config;3 use in_core::Config;
4-use in_core::store::TursoStore;4+use in_core::store::{Store, TursoStore};
5 use topcoat::Result;5 use topcoat::Result;
6 use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};6 use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};
7 use topcoat::cookie::RouterBuilderCookieExt;7 use topcoat::cookie::RouterBuilderCookieExt;
@@ -106,18 +106,33 @@ async fn main() {
106 let store = TursoStore::open(&config.database, Some(config.storage.as_path()))106 let store = TursoStore::open(&config.database, Some(config.storage.as_path()))
107 .await107 .await
108 .expect("failed to open the database");108 .expect("failed to open the database");
109- let store: Arc<dyn in_core::store::Store> = Arc::new(store);109+ let store = Arc::new(store);
110 110
111- // Trash purge is policy, not storage hygiene, so it happens here with the111+ // Trash purge is policy, not storage hygiene: it happens with the
112- // configured horizon rather than inside `open`: a deployment keeping trash112+ // configured horizon rather than any built-in default, so a deployment
113- // longer than any built-in default must never be over-purged by boot.113+ // keeping trash longer than the default is never over-purged.
114 let cutoff =114 let cutoff =
115 time::OffsetDateTime::now_utc() - time::Duration::days(i64::from(config.purge_after_days));115 time::OffsetDateTime::now_utc() - time::Duration::days(i64::from(config.purge_after_days));
116- match store.purge_expired(cutoff).await {116+
117- Ok(0) => {}117+ // Nothing the first request needs waits for the boot's hygiene: the
118- Ok(purged) => println!("in purged {purged} trashed item(s)"),118+ // walk of every file and thumbnail on disk, the aborted uploads, the
119- Err(problem) => eprintln!("in: trash purge failed: {problem}"),119+ // trash purge. The store is usable the moment `open` returns — schema
120- }120+ // live, storage tree in place — and the sweeps only delete what no row
121+ // names and what has already expired, so they run as a background task
122+ // while the port is about to answer. A sweep that fails is logged and
123+ // lived with: an unswept tree is slow, never wrong.
124+ let sweeper = store.clone();
125+ tokio::spawn(async move {
126+ if let Err(problem) = sweeper.boot_sweeps().await {
127+ eprintln!("in: boot sweeps failed: {problem}");
128+ }
129+ match sweeper.purge_expired(cutoff).await {
130+ Ok(0) => {}
131+ Ok(purged) => println!("in purged {purged} trashed item(s)"),
132+ Err(problem) => eprintln!("in: trash purge failed: {problem}"),
133+ }
134+ });
135+ let store: Arc<dyn in_core::store::Store> = store;
121 136
122 // The key sealing the OIDC session cookies, kept beside the database as137 // The key sealing the OIDC session cookies, kept beside the database as
123 // `in.key` — one key per deployment, never in the repository.138 // `in.key` — one key per deployment, never in the repository.
crates/in-web/src/settings.rsmodified+3 -2
@@ -273,7 +273,7 @@ async fn settings(cx: &Cx) -> Result {
273 Vec::new()273 Vec::new()
274 };274 };
275 let created = created_token(uri(cx).query().unwrap_or(""));275 let created = created_token(uri(cx).query().unwrap_or(""));
276- let origin = app(cx).config.listen_url();276+ let origin = app(cx).config.public_origin();
277 view! {277 view! {
278 cx =>278 cx =>
279 (topbar(cx, NavPage::Settings, &fresh, language).await?)279 (topbar(cx, NavPage::Settings, &fresh, language).await?)
@@ -352,10 +352,11 @@ async fn settings(cx: &Cx) -> Result {
352 <div class="member-row">352 <div class="member-row">
353 <span class="member-name">(format!("{} · {}", link.kind.as_str(), target_name.clone()))</span>353 <span class="member-name">(format!("{} · {}", link.kind.as_str(), target_name.clone()))</span>
354 <span class="field-note">(expiry_line(language, link.expires_at))</span>354 <span class="field-note">(expiry_line(language, link.expires_at))</span>
355+ <div class="spacer"></div>
355 <span class="field-note">(if link.can_download { t(language, Key::CanDownload) } else { t(language, Key::ViewOnly) })</span>356 <span class="field-note">(if link.can_download { t(language, Key::CanDownload) } else { t(language, Key::ViewOnly) })</span>
356 <form class="pop-row-form" method="post" action="/api/share/link/revoke">357 <form class="pop-row-form" method="post" action="/api/share/link/revoke">
357 <input type="hidden" name="id" value=(link.id.clone())>358 <input type="hidden" name="id" value=(link.id.clone())>
358- <button type="submit">(t(language, Key::RevokeLink))</button>359+ <button class="quiet quiet-danger" type="submit">(t(language, Key::RevokeLink))</button>
359 </form>360 </form>
360 </div>361 </div>
361 }362 }
crates/in-web/src/share.rsmodified+159 -41
@@ -4,9 +4,11 @@
4 //! file or folder (`can_download`, optional expiry in days; only the token4 //! file or folder (`can_download`, optional expiry in days; only the token
5 //! hash is stored). `POST /api/share/user/add|remove` grants and revokes5 //! hash is stored). `POST /api/share/user/add|remove` grants and revokes
6 //! named users the same way. `GET /s/{token}` is public — no auth —6 //! named users the same way. `GET /s/{token}` is public — no auth —
7-//! rendering the viewer page, the download only when `can_download` allows,7+//! rendering the viewer page in the document shell, the download only when
8-//! and the stored webp preview on `?thumb=1` regardless of the flag; a spent,8+//! `can_download` allows, the stored webp preview on `?thumb=1` regardless
9-//! expired or revoked token answers the dead card, never a stack.9+//! of the flag, and the card's `<video>`/`<audio>` player feed on
10+//! `?media=1` for the video and audio kinds; a spent, expired or revoked
11+//! token answers the dead card, never a stack.
10 //! `GET /shared` lists what others shared with the reader.12 //! `GET /shared` lists what others shared with the reader.
11 //!13 //!
12 //! Every mutation answers the way `board.rs` in iz does: a 303 back to the14 //! Every mutation answers the way `board.rs` in iz does: a 303 back to the
@@ -29,9 +31,9 @@ use topcoat::router::response::IntoResponse;
29 use topcoat::router::{HeaderName, StatusCode, header, page, path_param, query_params, route};31 use topcoat::router::{HeaderName, StatusCode, header, page, path_param, query_params, route};
30 use topcoat::view::view;32 use topcoat::view::view;
31 33
32-use crate::files::entry_chip;34+use crate::files::{ViewerKind, entry_chip, media_player, media_player_script, viewer_kind};
33 use crate::i18n::{Key, Lang, lang, t};35 use crate::i18n::{Key, Lang, lang, t};
34-use crate::layout::{NavPage, topbar, wordmark};36+use crate::layout::{NavPage, document_shell, topbar, wordmark};
35 use crate::server::{Refusal, app, back_to, require_user};37 use crate::server::{Refusal, app, back_to, require_user};
36 38
37 path_param!(token);39 path_param!(token);
@@ -405,13 +407,15 @@ async fn remove_share(cx: &Cx, Form(input): Form<ShareUserForm>) -> Redirect {
405 }407 }
406 408
407 /// The public viewer's query: which folder is browsed, which file is named,409 /// The public viewer's query: which folder is browsed, which file is named,
408-/// whether the bytes (rather than the card) are wanted, and whether the410+/// whether the bytes (rather than the card) are wanted, whether the stored
409-/// stored webp preview is wanted — the preview a view-only link grants.411+/// webp preview is wanted — the preview a view-only link grants — and
412+/// whether the inline media stream the card's player draws from is wanted.
410 struct SharedQuery {413 struct SharedQuery {
411 folder: Option<String>,414 folder: Option<String>,
412 file: Option<String>,415 file: Option<String>,
413 dl: bool,416 dl: bool,
414 thumb: bool,417 thumb: bool,
418+ media: bool,
415 }419 }
416 420
417 /// The query off the request's own URI. Unparseable pairs are ignored —421 /// The query off the request's own URI. Unparseable pairs are ignored —
@@ -423,6 +427,7 @@ fn shared_query(cx: &Cx) -> SharedQuery {
423 file: query_value(query, "file"),427 file: query_value(query, "file"),
424 dl: has_flag(query, "dl"),428 dl: has_flag(query, "dl"),
425 thumb: has_flag(query, "thumb"),429 thumb: has_flag(query, "thumb"),
430+ media: has_flag(query, "media"),
426 }431 }
427 }432 }
428 433
@@ -433,25 +438,38 @@ fn has_flag(query: &str, key: &str) -> bool {
433 .any(|pair| pair == key || pair.starts_with(&format!("{key}=")))438 .any(|pair| pair == key || pair.starts_with(&format!("{key}=")))
434 }439 }
435 440
441+/// A public page in the document shell. `#[page]` pairs its layouts at
442+/// build time, but this route's query asks for raw bytes (`?dl=1`,
443+/// `?thumb=1`, `?media=1`) that a page-shaped answer cannot carry, so the
444+/// `/s` surface stays a `#[route]` and wraps its views itself — in
445+/// `document_shell`, the same shell every `#[page]` under `/` wears, never
446+/// a hand-copied head.
447+async fn public_page(cx: &Cx, page: Result) -> topcoat::Result<topcoat::router::response::Response> {
448+ Ok(document_shell(cx, page).await?.into_response(cx)?)
449+}
450+
436 /// The dead card: a spent, expired, revoked or never-real token, a trashed451 /// The dead card: a spent, expired, revoked or never-real token, a trashed
437 /// target, or a download the link may not open. One answer for all of them —452 /// target, or a download the link may not open. One answer for all of them —
438 /// a stranger learns nothing about which tokens exist.453 /// a stranger learns nothing about which tokens exist.
439-async fn dead_link(cx: &Cx) -> Result {454+async fn dead_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
440 let language = lang(cx).await;455 let language = lang(cx).await;
441- view! {456+ let page = view! {
442 cx =>457 cx =>
443 <main class="scaffold-note">458 <main class="scaffold-note">
444 (wordmark(cx).await?)459 (wordmark(cx).await?)
445 <p>(Refusal::ShareRevoked.message_in(language))</p>460 <p>(Refusal::ShareRevoked.message_in(language))</p>
446 <p><a href="/">(t(language, Key::BackToDrive))</a></p>461 <p><a href="/">(t(language, Key::BackToDrive))</a></p>
447 </main>462 </main>
448- }463+ };
464+ public_page(cx, page).await
449 }465 }
450-
451 /// The public viewer. No auth: the token in the path is the whole466 /// The public viewer. No auth: the token in the path is the whole
452 /// credential. A file target renders its card (and its bytes on `?dl=1`467 /// credential. A file target renders its card (and its bytes on `?dl=1`
453 /// when the link may download); a folder target renders the listing of the468 /// when the link may download); a folder target renders the listing of the
454-/// browsed folder, downloads gated per file on the same flag.469+/// browsed folder, downloads gated per file on the same flag. The card's
470+/// player streams `?media=1` regardless of the flag — preview is what a
471+/// view-only link grants — for the video and audio kinds the signed-in
472+/// viewer plays inline.
455 #[route(GET "/s/{token}")]473 #[route(GET "/s/{token}")]
456 async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {474 async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
457 let token: &str = path_param::<Token>(cx);475 let token: &str = path_param::<Token>(cx);
@@ -463,7 +481,7 @@ async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Resp
463 .ok()481 .ok()
464 .flatten();482 .flatten();
465 let Some(link) = link else {483 let Some(link) = link else {
466- return dead_link(cx).await.into_response(cx);484+ return dead_link(cx).await;
467 };485 };
468 // A password-protected link answers nothing — card, bytes or thumbnail —486 // A password-protected link answers nothing — card, bytes or thumbnail —
469 // until this browser carries the unlock proof. One check up front gates487 // until this browser carries the unlock proof. One check up front gates
@@ -475,7 +493,7 @@ async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Resp
475 .get(&link_cookie_name(&link.id))493 .get(&link_cookie_name(&link.id))
476 .map(|cookie| cookie.value().to_string());494 .map(|cookie| cookie.value().to_string());
477 if presented.as_deref() != Some(proof.as_str()) {495 if presented.as_deref() != Some(proof.as_str()) {
478- return password_gate(cx).await.into_response(cx);496+ return password_gate(cx).await;
479 }497 }
480 }498 }
481 let query = shared_query(cx);499 let query = shared_query(cx);
@@ -486,10 +504,10 @@ async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Resp
486 .await504 .await
487 .map_err(|_| Refusal::Unavailable);505 .map_err(|_| Refusal::Unavailable);
488 let Ok(Some(file)) = file else {506 let Ok(Some(file)) = file else {
489- return dead_link(cx).await.into_response(cx);507+ return dead_link(cx).await;
490 };508 };
491 if file.deleted_at.is_some() {509 if file.deleted_at.is_some() {
492- return dead_link(cx).await.into_response(cx);510+ return dead_link(cx).await;
493 }511 }
494 if query.dl {512 if query.dl {
495 return download_bytes(513 return download_bytes(
@@ -503,6 +521,17 @@ async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Resp
503 )521 )
504 .await;522 .await;
505 }523 }
524+ if query.media {
525+ return media_bytes(
526+ cx,
527+ store.as_ref(),
528+ &file.id,
529+ file.size_bytes,
530+ &file.name,
531+ &file.mime,
532+ )
533+ .await;
534+ }
506 if query.thumb {535 if query.thumb {
507 return public_thumb(cx, store.as_ref(), &file.id).await;536 return public_thumb(cx, store.as_ref(), &file.id).await;
508 }537 }
@@ -514,28 +543,28 @@ async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Resp
514 .await543 .await
515 .map_err(|_| Refusal::Unavailable);544 .map_err(|_| Refusal::Unavailable);
516 let Ok(Some(root)) = root else {545 let Ok(Some(root)) = root else {
517- return dead_link(cx).await.into_response(cx);546+ return dead_link(cx).await;
518 };547 };
519 if root.deleted_at.is_some() {548 if root.deleted_at.is_some() {
520- return dead_link(cx).await.into_response(cx);549+ return dead_link(cx).await;
521 }550 }
522 let at = query.folder.as_deref().unwrap_or(&root.id).to_string();551 let at = query.folder.as_deref().unwrap_or(&root.id).to_string();
523 if !under_target(store.as_ref(), &root.owner_id, &root.id, &at).await {552 if !under_target(store.as_ref(), &root.owner_id, &root.id, &at).await {
524- return dead_link(cx).await.into_response(cx);553+ return dead_link(cx).await;
525 }554 }
526 if query.dl {555 if query.dl {
527 let Some(file_id) = query.file.as_deref() else {556 let Some(file_id) = query.file.as_deref() else {
528- return dead_link(cx).await.into_response(cx);557+ return dead_link(cx).await;
529 };558 };
530 let file = store.file(file_id).await.map_err(|_| Refusal::Unavailable);559 let file = store.file(file_id).await.map_err(|_| Refusal::Unavailable);
531 let Ok(Some(file)) = file else {560 let Ok(Some(file)) = file else {
532- return dead_link(cx).await.into_response(cx);561+ return dead_link(cx).await;
533 };562 };
534 if file.deleted_at.is_some()563 if file.deleted_at.is_some()
535 || file.owner_id != root.owner_id564 || file.owner_id != root.owner_id
536 || file.folder_id.as_deref() != Some(at.as_str())565 || file.folder_id.as_deref() != Some(at.as_str())
537 {566 {
538- return dead_link(cx).await.into_response(cx);567+ return dead_link(cx).await;
539 }568 }
540 return download_bytes(569 return download_bytes(
541 cx,570 cx,
@@ -548,19 +577,43 @@ async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Resp
548 )577 )
549 .await;578 .await;
550 }579 }
580+ if query.media {
581+ let Some(file_id) = query.file.as_deref() else {
582+ return dead_link(cx).await;
583+ };
584+ let file = store.file(file_id).await.map_err(|_| Refusal::Unavailable);
585+ let Ok(Some(file)) = file else {
586+ return dead_link(cx).await;
587+ };
588+ if file.deleted_at.is_some()
589+ || file.owner_id != root.owner_id
590+ || file.folder_id.as_deref() != Some(at.as_str())
591+ {
592+ return dead_link(cx).await;
593+ }
594+ return media_bytes(
595+ cx,
596+ store.as_ref(),
597+ &file.id,
598+ file.size_bytes,
599+ &file.name,
600+ &file.mime,
601+ )
602+ .await;
603+ }
551 if query.thumb {604 if query.thumb {
552 let Some(file_id) = query.file.as_deref() else {605 let Some(file_id) = query.file.as_deref() else {
553- return dead_link(cx).await.into_response(cx);606+ return dead_link(cx).await;
554 };607 };
555 let file = store.file(file_id).await.map_err(|_| Refusal::Unavailable);608 let file = store.file(file_id).await.map_err(|_| Refusal::Unavailable);
556 let Ok(Some(file)) = file else {609 let Ok(Some(file)) = file else {
557- return dead_link(cx).await.into_response(cx);610+ return dead_link(cx).await;
558 };611 };
559 if file.deleted_at.is_some()612 if file.deleted_at.is_some()
560 || file.owner_id != root.owner_id613 || file.owner_id != root.owner_id
561 || file.folder_id.as_deref() != Some(at.as_str())614 || file.folder_id.as_deref() != Some(at.as_str())
562 {615 {
563- return dead_link(cx).await.into_response(cx);616+ return dead_link(cx).await;
564 }617 }
565 return public_thumb(cx, store.as_ref(), &file.id).await;618 return public_thumb(cx, store.as_ref(), &file.id).await;
566 }619 }
@@ -578,11 +631,11 @@ fn link_cookie_name(link_id: &str) -> String {
578 /// The gate a password-protected link shows until the browser carries the631 /// The gate a password-protected link shows until the browser carries the
579 /// proof. Same public chrome as the cards — no hint of what waits behind632 /// proof. Same public chrome as the cards — no hint of what waits behind
580 /// the gate, not even the file's name.633 /// the gate, not even the file's name.
581-async fn password_gate(cx: &Cx) -> Result {634+async fn password_gate(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
582 let language = lang(cx).await;635 let language = lang(cx).await;
583 let action = current_path(cx);636 let action = current_path(cx);
584 let wrong = has_flag(uri(cx).query().unwrap_or(""), "wrong");637 let wrong = has_flag(uri(cx).query().unwrap_or(""), "wrong");
585- view! {638+ let page = view! {
586 cx =>639 cx =>
587 <main class="scaffold-note">640 <main class="scaffold-note">
588 (wordmark(cx).await?)641 (wordmark(cx).await?)
@@ -596,7 +649,8 @@ async fn password_gate(cx: &Cx) -> Result {
596 <button class="quiet" type="submit">(t(language, Key::Unlock))</button>649 <button class="quiet" type="submit">(t(language, Key::Unlock))</button>
597 </form>650 </form>
598 </main>651 </main>
599- }652+ };
653+ public_page(cx, page).await
600 }654 }
601 655
602 #[derive(Deserialize)]656 #[derive(Deserialize)]
@@ -624,7 +678,7 @@ async fn unlock_link(
624 .ok()678 .ok()
625 .flatten();679 .flatten();
626 let Some(link) = link else {680 let Some(link) = link else {
627- return dead_link(cx).await.into_response(cx);681+ return dead_link(cx).await;
628 };682 };
629 let Some(password_hash) = link.password_hash else {683 let Some(password_hash) = link.password_hash else {
630 // Nothing to unlock: the form has no business here. Back to the page.684 // Nothing to unlock: the form has no business here. Back to the page.
@@ -686,7 +740,7 @@ async fn download_bytes(
686 use topcoat::router::response::IntoResponse;740 use topcoat::router::response::IntoResponse;
687 use topcoat::router::{HeaderMap, HeaderValue};741 use topcoat::router::{HeaderMap, HeaderValue};
688 if !can_download {742 if !can_download {
689- return dead_link(cx).await.into_response(cx);743+ return dead_link(cx).await;
690 }744 }
691 // A fetch counts once: a full fetch, or a range resuming from byte 0.745 // A fetch counts once: a full fetch, or a range resuming from byte 0.
692 // A mid-file chunk is the same view going on, not a new one — the way746 // A mid-file chunk is the same view going on, not a new one — the way
@@ -716,7 +770,58 @@ async fn download_bytes(
716 let Some(parts) =770 let Some(parts) =
717 crate::files::bytes_response(store, file_id, size_bytes, range, headers).await771 crate::files::bytes_response(store, file_id, size_bytes, range, headers).await
718 else {772 else {
719- return dead_link(cx).await.into_response(cx);773+ return dead_link(cx).await;
774+ };
775+ Ok(parts.into_response(cx)?)
776+}
777+
778+/// The inline media stream behind a public link: the bytes the card's
779+/// `<video>`/`<audio>` player draws from, through
780+/// [`crate::files::bytes_response`] — a range reads only its span, the way
781+/// every byte route here serves. Only the kinds the signed-in viewer plays
782+/// through their native elements answer: preview is what a view-only link
783+/// grants, but a document's bytes (pdf, text) would leak through the same
784+/// inline fetch, so anything else — and anything unservable — is the dead
785+/// card, like every other answer on this surface. Never an attachment, and
786+/// never counted as a download: a view is not a download.
787+async fn media_bytes(
788+ cx: &Cx,
789+ store: &dyn Store,
790+ file_id: &str,
791+ size_bytes: u64,
792+ name: &str,
793+ mime: &str,
794+) -> topcoat::Result<topcoat::router::response::Response> {
795+ use topcoat::router::response::IntoResponse;
796+ use topcoat::router::{HeaderMap, HeaderValue};
797+ if !matches!(
798+ viewer_kind(mime),
799+ Some(ViewerKind::Video | ViewerKind::Audio)
800+ ) {
801+ return dead_link(cx).await;
802+ }
803+ let range = request_headers(cx)
804+ .get(header::RANGE)
805+ .and_then(|value| value.to_str().ok());
806+ let mut headers = HeaderMap::new();
807+ if let Ok(value) = HeaderValue::from_str(mime) {
808+ headers.insert(header::CONTENT_TYPE, value);
809+ }
810+ let disposition = format!("inline; filename=\"{}\"", safe_name(name));
811+ if let Ok(value) = HeaderValue::from_str(&disposition) {
812+ headers.insert(header::CONTENT_DISPOSITION, value);
813+ }
814+ // Safari refuses to play a media element without a `206` reply to its
815+ // own `Range` probe; the signed-in byte route declares the same.
816+ headers.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
817+ headers.insert(
818+ header::CACHE_CONTROL,
819+ HeaderValue::from_static("private, no-cache"),
820+ );
821+ let Some(parts) =
822+ crate::files::bytes_response(store, file_id, size_bytes, range, headers).await
823+ else {
824+ return dead_link(cx).await;
720 };825 };
721 Ok(parts.into_response(cx)?)826 Ok(parts.into_response(cx)?)
722 }827 }
@@ -749,7 +854,7 @@ async fn public_thumb(
749 use topcoat::router::response::IntoResponse;854 use topcoat::router::response::IntoResponse;
750 use topcoat::router::{HeaderMap, HeaderValue};855 use topcoat::router::{HeaderMap, HeaderValue};
751 let Ok(Some(bytes)) = store.thumb_bytes(file_id).await else {856 let Ok(Some(bytes)) = store.thumb_bytes(file_id).await else {
752- return dead_link(cx).await.into_response(cx);857+ return dead_link(cx).await;
753 };858 };
754 let etag = format!("\"{:x}\"", crate::files::fnv1a(&bytes));859 let etag = format!("\"{:x}\"", crate::files::fnv1a(&bytes));
755 let mut headers = HeaderMap::new();860 let mut headers = HeaderMap::new();
@@ -786,7 +891,11 @@ fn safe_name(name: &str) -> String {
786 }891 }
787 892
788 /// A shared file's card: its name, size and type, an image preview off the893 /// A shared file's card: its name, size and type, an image preview off the
789-/// public thumbnail route, and the download while the link allows it.894+/// public thumbnail route, the video/audio kinds through the house player
895+/// itself — [`crate::files::media_player`], the one markup + bar + script
896+/// the signed-in viewer renders, its classes (`media-player`, `media-el`,
897+/// `viewer-video`) verbatim, the stream off the public `?media=1` route —
898+/// and the download while the link allows it.
790 async fn file_card(899 async fn file_card(
791 cx: &Cx,900 cx: &Cx,
792 link: &in_core::store::ShareLink,901 link: &in_core::store::ShareLink,
@@ -795,7 +904,9 @@ async fn file_card(
795 let language = lang(cx).await;904 let language = lang(cx).await;
796 let preview = file.mime.starts_with("image/");905 let preview = file.mime.starts_with("image/");
797 let token_path = current_path(cx);906 let token_path = current_path(cx);
798- view! {907+ let media = viewer_kind(&file.mime);
908+ let media_src = format!("{token_path}?media=1");
909+ let page = view! {
799 cx =>910 cx =>
800 <main class="scaffold-note">911 <main class="scaffold-note">
801 (wordmark(cx).await?)912 (wordmark(cx).await?)
@@ -803,6 +914,10 @@ async fn file_card(
803 <p class="field-note">(format!("{} · {}", file.mime.clone(), crate::settings::human_bytes(file.size_bytes)))</p>914 <p class="field-note">(format!("{} · {}", file.mime.clone(), crate::settings::human_bytes(file.size_bytes)))</p>
804 if preview {915 if preview {
805 <img src=(format!("{token_path}?thumb=1")) alt=(file.name.clone())>916 <img src=(format!("{token_path}?thumb=1")) alt=(file.name.clone())>
917+ } else if matches!(media, Some(ViewerKind::Video)) {
918+ (media_player(cx, language, file.name.clone(), media_src.clone(), true).await?)
919+ } else if matches!(media, Some(ViewerKind::Audio)) {
920+ (media_player(cx, language, file.name.clone(), media_src.clone(), false).await?)
806 } else {921 } else {
807 <p class="field-note">(t(language, Key::PreviewUnavailable))</p>922 <p class="field-note">(t(language, Key::PreviewUnavailable))</p>
808 }923 }
@@ -812,8 +927,9 @@ async fn file_card(
812 <p class="field-note">(t(language, Key::ViewOnly))</p>927 <p class="field-note">(t(language, Key::ViewOnly))</p>
813 }928 }
814 </main>929 </main>
815- }930+ (media_player_script(cx).await?)
816- .into_response(cx)931+ };
932+ public_page(cx, page).await
817 }933 }
818 934
819 /// One file's chip on the public card: the link's own thumbnail where one935 /// One file's chip on the public card: the link's own thumbnail where one
@@ -874,7 +990,7 @@ async fn folder_card(
874 let language = lang(cx).await;990 let language = lang(cx).await;
875 let here = store.folder(at).await?;991 let here = store.folder(at).await?;
876 let Some(here) = here else {992 let Some(here) = here else {
877- return dead_link(cx).await.into_response(cx);993+ return dead_link(cx).await;
878 };994 };
879 let listing = store.list_children(&root.owner_id, Some(at)).await?;995 let listing = store.list_children(&root.owner_id, Some(at)).await?;
880 let base = format!("/s/{token}");996 let base = format!("/s/{token}");
@@ -882,7 +998,7 @@ async fn folder_card(
882 rows.extend(listing.folders.iter().map(PublicEntry::Folder));998 rows.extend(listing.folders.iter().map(PublicEntry::Folder));
883 rows.extend(listing.files.iter().map(PublicEntry::File));999 rows.extend(listing.files.iter().map(PublicEntry::File));
884 rows.sort_by(|a, b| a.name().to_lowercase().cmp(&b.name().to_lowercase()));1000 rows.sort_by(|a, b| a.name().to_lowercase().cmp(&b.name().to_lowercase()));
885- view! {1001+ let page = view! {
886 cx =>1002 cx =>
887 (wordmark(cx).await?)1003 (wordmark(cx).await?)
888 <main class="settings-stage stage-wide">1004 <main class="settings-stage stage-wide">
@@ -914,8 +1030,8 @@ async fn folder_card(
914 </div>1030 </div>
915 </section>1031 </section>
916 </main>1032 </main>
917- }1033+ };
918- .into_response(cx)1034+ public_page(cx, page).await
919 }1035 }
920 1036
921 /// The request's own path, without its query: the download links the public1037 /// The request's own path, without its query: the download links the public
@@ -1225,7 +1341,6 @@ pub(crate) async fn share_modal(
1225 target_id: &str,1341 target_id: &str,
1226 close_href: &str,1342 close_href: &str,
1227 created: Option<String>,1343 created: Option<String>,
1228- origin: &str,
1229 ) -> Result<Option<topcoat::view::View>> {1344 ) -> Result<Option<topcoat::view::View>> {
1230 let Some(kind) = parse_kind(kind_raw) else {1345 let Some(kind) = parse_kind(kind_raw) else {
1231 return Ok(None);1346 return Ok(None);
@@ -1235,6 +1350,9 @@ pub(crate) async fn share_modal(
1235 Err(_) => return Ok(None),1350 Err(_) => return Ok(None),
1236 };1351 };
1237 let language = lang(cx).await;1352 let language = lang(cx).await;
1353+ // The links this modal shows carry the public origin — the configured
1354+ // `base_url` when the deployment names one, the bound address otherwise.
1355+ let origin = app(cx).config.public_origin();
1238 let store = app(cx).store.clone();1356 let store = app(cx).store.clone();
1239 // The owned, live target: present, untrashed, and theirs. Anything else1357 // The owned, live target: present, untrashed, and theirs. Anything else
1240 // opens nothing — a stranger learns not even whose it is.1358 // opens nothing — a stranger learns not even whose it is.
crates/in-web/tests/http.rsmodified+463 -0
@@ -316,6 +316,12 @@ struct TestApp {
316 316
317 impl TestApp {317 impl TestApp {
318 async fn build() -> Self {318 async fn build() -> Self {
319+ Self::build_with(None).await
320+ }
321+
322+ /// The same workspace with a config `base_url` set — the key that
323+ /// decides where the public links are told to point.
324+ async fn build_with(base_url: Option<&str>) -> Self {
319 let dir = std::env::temp_dir().join(format!("in-http-{}", Ulid::new()));325 let dir = std::env::temp_dir().join(format!("in-http-{}", Ulid::new()));
320 std::fs::create_dir_all(&dir).unwrap();326 std::fs::create_dir_all(&dir).unwrap();
321 let db = dir.join("in.db");327 let db = dir.join("in.db");
@@ -341,6 +347,7 @@ impl TestApp {
341 live_seconds: 300,347 live_seconds: 300,
342 purge_after_days: 30,348 purge_after_days: 30,
343 default_quota_bytes: 10 * 1024 * 1024 * 1024,349 default_quota_bytes: 10 * 1024 * 1024 * 1024,
350+ base_url: base_url.map(str::to_string),
344 oidc: OidcConfig {351 oidc: OidcConfig {
345 issuer: fake.url(),352 issuer: fake.url(),
346 client_id: "in-test".to_string(),353 client_id: "in-test".to_string(),
@@ -2454,6 +2461,143 @@ async fn settings_quota_and_disable_guards() {
2454 );2461 );
2455 }2462 }
2456 2463
2464+/// A deployment with a domain tells that domain, never the bind: the
2465+/// settings copy-once banner and the drive modal's link rows all carry
2466+/// `base_url`.
2467+#[tokio::test]
2468+async fn share_links_carry_the_configured_base_url() {
2469+ let app = TestApp::build_with(Some("https://files.example.com")).await;
2470+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2471+ let owner = owner_of(&app, "sub-admin").await;
2472+ let file = file_id(&app, &owner, "notes.txt", b"hello in").await;
2473+
2474+ let answer = app
2475+ .post(
2476+ "/api/share/link/create",
2477+ Some(&admin),
2478+ &[
2479+ ("kind", "file"),
2480+ ("target_id", &file),
2481+ ("can_download", "1"),
2482+ ],
2483+ )
2484+ .await;
2485+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
2486+ let token = created_token(answer.location.as_deref().unwrap());
2487+
2488+ // The banner the mint redirects back to.
2489+ let page = app
2490+ .get(&format!("/settings?created={token}"), Some(&admin))
2491+ .await;
2492+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2493+ assert!(
2494+ page.text()
2495+ .contains(&format!("https://files.example.com/s/{token}")),
2496+ "banner showed no domain link: {}",
2497+ page.text()
2498+ );
2499+ assert!(
2500+ !page.text().contains("127.0.0.1:7655/s/"),
2501+ "banner leaked the bind address: {}",
2502+ page.text()
2503+ );
2504+
2505+ // The modal says the same: the minted row and the live-link
2506+ // placeholder alike.
2507+ let page = app
2508+ .get(
2509+ &format!("/drive?share=file:{file}&created={token}"),
2510+ Some(&admin),
2511+ )
2512+ .await;
2513+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2514+ assert!(
2515+ page.text()
2516+ .contains(&format!("https://files.example.com/s/{token}")),
2517+ "modal showed no domain link: {}",
2518+ page.text()
2519+ );
2520+ assert!(
2521+ page.text().contains("https://files.example.com/s/…"),
2522+ "modal placeholder showed no domain: {}",
2523+ page.text()
2524+ );
2525+}
2526+
2527+#[tokio::test]
2528+async fn share_links_follow_the_bind_without_a_base_url() {
2529+ let app = TestApp::build().await;
2530+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2531+ let owner = owner_of(&app, "sub-admin").await;
2532+ let file = file_id(&app, &owner, "notes.txt", b"hello in").await;
2533+
2534+ let answer = app
2535+ .post(
2536+ "/api/share/link/create",
2537+ Some(&admin),
2538+ &[
2539+ ("kind", "file"),
2540+ ("target_id", &file),
2541+ ("can_download", "1"),
2542+ ],
2543+ )
2544+ .await;
2545+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
2546+ let token = created_token(answer.location.as_deref().unwrap());
2547+
2548+ // No `base_url`: the links say the address bound, as they always
2549+ // have.
2550+ let page = app
2551+ .get(&format!("/settings?created={token}"), Some(&admin))
2552+ .await;
2553+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2554+ assert!(
2555+ page.text()
2556+ .contains(&format!("http://127.0.0.1:7655/s/{token}")),
2557+ "banner showed no bind link: {}",
2558+ page.text()
2559+ );
2560+}
2561+
2562+/// The revoke control is one inline quiet button at the row's end, like
2563+/// the modal's remove-access rows — not a full-width block of its own.
2564+#[tokio::test]
2565+async fn the_settings_revoke_button_sits_inline_in_its_row() {
2566+ let app = TestApp::build().await;
2567+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2568+ let owner = owner_of(&app, "sub-admin").await;
2569+ let file = file_id(&app, &owner, "notes.txt", b"hello in").await;
2570+ app.store
2571+ .create_share_link(&owner, ShareKind::File, &file, true, None, None)
2572+ .await
2573+ .unwrap();
2574+
2575+ let body = app.get("/settings", Some(&admin)).await.text();
2576+ let row_at = body
2577+ .find("<div class=\"member-row\">")
2578+ .expect("no share-link row");
2579+ let form_at = body[row_at..]
2580+ .find("<form class=\"pop-row-form\" method=\"post\" action=\"/api/share/link/revoke\">")
2581+ .expect("no revoke form in a member-row");
2582+ let form_close = row_at
2583+ + form_at
2584+ + body[row_at + form_at..]
2585+ .find("</form>")
2586+ .expect("form never closes");
2587+ // The row is still open around the form: its own close is the first
2588+ // `</div>` after the form's.
2589+ let row_close = form_close + body[form_close..].find("</div>").expect("row never closes");
2590+ let form = &body[row_at + form_at..form_close];
2591+ assert!(
2592+ form.contains("<button class=\"quiet quiet-danger\" type=\"submit\">"),
2593+ "revoke is not the inline quiet button: {form}"
2594+ );
2595+ assert!(
2596+ !form.contains("div"),
2597+ "the revoke control is wrapped or outside its row: {form}"
2598+ );
2599+}
2600+
2457 #[tokio::test]2601 #[tokio::test]
2458 async fn signed_out_mutations_ask_to_sign_in() {2602 async fn signed_out_mutations_ask_to_sign_in() {
2459 let app = TestApp::build().await;2603 let app = TestApp::build().await;
@@ -2549,6 +2693,325 @@ async fn empty_file_upload_round_trip() {
2549 );2693 );
2550 }2694 }
2551 2695
2696+/// The 16-byte ISO-BMFF header the mime sniffer reads as `video/mp4`.
2697+const CLIP: &[u8] = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00";
2698+
2699+/// The shell every public /s page must wear: a full document — DOCTYPE and
2700+/// the compiled stylesheet — carrying none of the session-gated machinery:
2701+/// a stranger's page opens no `/api/live` stream.
2702+fn assert_public_shell(page: &Raw, what: &str) {
2703+ let body = page.text();
2704+ assert!(
2705+ body.contains("<!DOCTYPE html>"),
2706+ "{what} carried no doctype: {body}"
2707+ );
2708+ assert!(
2709+ body.contains("assets/main-"),
2710+ "{what} carried no stylesheet: {body}"
2711+ );
2712+ assert!(
2713+ !body.contains("/api/live") && !body.contains("__inLive"),
2714+ "{what} leaked the session-gated live stream: {body}"
2715+ );
2716+}
2717+
2718+/// Every public /s answer — card, folder listing, password gate, dead card —
2719+/// is a full styled document now, not a bare fragment; none of them opens
2720+/// the signed-in live stream at a stranger.
2721+#[tokio::test]
2722+async fn public_link_pages_wear_the_document_shell() {
2723+ let app = TestApp::build().await;
2724+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2725+ let owner = owner_of(&app, "sub-admin").await;
2726+ let file = file_id(&app, &owner, "shelled.txt", b"shelled bytes").await;
2727+ let answer = app
2728+ .post(
2729+ "/api/share/link/create",
2730+ Some(&admin),
2731+ &[
2732+ ("kind", "file"),
2733+ ("target_id", &file),
2734+ ("can_download", "1"),
2735+ ("password", "open sesame"),
2736+ ],
2737+ )
2738+ .await;
2739+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
2740+ let token = created_token(answer.location.as_deref().unwrap());
2741+ let link = &app.store.share_links(&owner).await.unwrap()[0];
2742+ let proof = in_core::link_unlock_proof(&token, link.password_hash.as_deref().unwrap());
2743+ let unlocked = format!("in_link_{}={proof}", link.id);
2744+
2745+ // The gate: styled, and still saying nothing about the target.
2746+ let gate = app.get(&format!("/s/{token}"), None).await;
2747+ assert_eq!(gate.status, StatusCode::OK, "{}", gate.text());
2748+ assert_public_shell(&gate, "the gate");
2749+ assert!(gate.text().contains("type=\"password\""), "{}", gate.text());
2750+ assert!(!gate.text().contains("shelled.txt"), "{}", gate.text());
2751+
2752+ // The unlocked card: the same document shell around the name.
2753+ let card = app.get(&format!("/s/{token}"), Some(&unlocked)).await;
2754+ assert_eq!(card.status, StatusCode::OK, "{}", card.text());
2755+ assert_public_shell(&card, "the card");
2756+ assert!(card.text().contains("shelled.txt"), "{}", card.text());
2757+
2758+ // The dead card: same.
2759+ let dead = app.get("/s/never-real-token", None).await;
2760+ assert_eq!(dead.status, StatusCode::OK, "{}", dead.text());
2761+ assert_public_shell(&dead, "the dead card");
2762+
2763+ // So is a folder listing.
2764+ let folder = app
2765+ .store
2766+ .create_folder(&owner, None, "shelled folder")
2767+ .await
2768+ .unwrap();
2769+ let created = app
2770+ .store
2771+ .create_share_link(&owner, ShareKind::Folder, &folder.id, true, None, None)
2772+ .await
2773+ .unwrap();
2774+ let listing = app.get(&format!("/s/{}", created.token), None).await;
2775+ assert_eq!(listing.status, StatusCode::OK, "{}", listing.text());
2776+ assert_public_shell(&listing, "the folder card");
2777+ assert!(
2778+ listing.text().contains("shelled folder"),
2779+ "{}",
2780+ listing.text()
2781+ );
2782+}
2783+
2784+/// A video link plays inline through the house player itself — the same
2785+/// markup, controls bar and wiring script the signed-in viewer renders, no
2786+/// native controls — streaming `?media=1`, ranges included, even on a
2787+/// view-only link, while `?dl=1` stays dead and a view never counts as a
2788+/// download. A text link draws no player at all.
2789+#[tokio::test]
2790+async fn video_link_plays_inline_without_download_rights() {
2791+ let app = TestApp::build().await;
2792+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2793+ let owner = owner_of(&app, "sub-admin").await;
2794+ let clip = file_id(&app, &owner, "clip.mp4", CLIP).await;
2795+ let answer = app
2796+ .post(
2797+ "/api/share/link/create",
2798+ Some(&admin),
2799+ &[("kind", "file"), ("target_id", &clip)],
2800+ )
2801+ .await;
2802+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
2803+ let token = created_token(answer.location.as_deref().unwrap());
2804+
2805+ // The card: the viewer's player, fed by the public media stream, and no
2806+ // download on a view-only link.
2807+ let page = app.get(&format!("/s/{token}"), None).await;
2808+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2809+ let body = page.text();
2810+ assert!(
2811+ body.contains("<div class=\"media-player media-player-video\">"),
2812+ "no video player: {body}"
2813+ );
2814+ assert!(
2815+ body.contains("<video class=\"media-el viewer-video\""),
2816+ "player lost the viewer's classes: {body}"
2817+ );
2818+ assert!(
2819+ body.contains(&format!("<video class=\"media-el viewer-video\" src=\"/s/{token}?media=1\" preload=\"metadata\">")),
2820+ "player not fed by ?media=1: {body}"
2821+ );
2822+ // The house bar and its wiring script — the browser's own controls
2823+ // never appear on the element.
2824+ assert!(
2825+ body.contains("<div class=\"media-controls\">"),
2826+ "no house controls bar: {body}"
2827+ );
2828+ assert!(
2829+ body.contains("class=\"media-play\""),
2830+ "no play toggle: {body}"
2831+ );
2832+ assert!(
2833+ body.contains("class=\"media-full\""),
2834+ "no fullscreen toggle: {body}"
2835+ );
2836+ assert!(
2837+ body.contains("__inMediaWired"),
2838+ "house wiring script missing: {body}"
2839+ );
2840+ assert!(
2841+ !body.contains(" controls="),
2842+ "native controls leaked onto the card: {body}"
2843+ );
2844+ assert!(
2845+ !body.contains("?dl=1"),
2846+ "view-only card offered a download: {body}"
2847+ );
2848+
2849+ // The stream serves ranges: a mid-file probe reads only its span, 206,
2850+ // under the stored video mime.
2851+ let probe = app
2852+ .get_with_range(&format!("/s/{token}?media=1"), None, "bytes=0-3")
2853+ .await;
2854+ assert_eq!(
2855+ probe.status,
2856+ StatusCode::PARTIAL_CONTENT,
2857+ "{}",
2858+ probe.text()
2859+ );
2860+ assert_eq!(probe.content_type.as_deref(), Some("video/mp4"));
2861+ assert_eq!(probe.bytes, &CLIP[0..4]);
2862+ assert_eq!(probe.content_range.as_deref(), Some("bytes 0-3/16"));
2863+
2864+ // A whole fetch is the whole clip, offered inline, and never counted as
2865+ // a download — preview is what a view-only link grants.
2866+ let full = app.get(&format!("/s/{token}?media=1"), None).await;
2867+ assert_eq!(full.status, StatusCode::OK, "{}", full.text());
2868+ assert_eq!(full.bytes, CLIP);
2869+ assert!(
2870+ full.disposition
2871+ .as_deref()
2872+ .is_some_and(|disposition| disposition.starts_with("inline")),
2873+ "the stream was an attachment: {:?}",
2874+ full.disposition
2875+ );
2876+ let stored = app.store.file(&clip).await.unwrap().unwrap();
2877+ assert_eq!(stored.download_count, 0, "a media view counted a download");
2878+
2879+ // The forced download stays dead — the stream is a preview, not the
2880+ // grant.
2881+ let blocked = app.get(&format!("/s/{token}?dl=1"), None).await;
2882+ assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text());
2883+ assert!(
2884+ blocked.text().contains("no longer works"),
2885+ "{}",
2886+ blocked.text()
2887+ );
2888+
2889+ // A text link draws no player.
2890+ let doc = file_id(&app, &owner, "plain.txt", b"plain").await;
2891+ let answer = app
2892+ .post(
2893+ "/api/share/link/create",
2894+ Some(&admin),
2895+ &[("kind", "file"), ("target_id", &doc)],
2896+ )
2897+ .await;
2898+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
2899+ let text_token = created_token(answer.location.as_deref().unwrap());
2900+ let text_card = app.get(&format!("/s/{text_token}"), None).await;
2901+ assert_eq!(text_card.status, StatusCode::OK, "{}", text_card.text());
2902+ let text_body = text_card.text();
2903+ assert!(
2904+ !text_body.contains("<video") && !text_body.contains("<audio"),
2905+ "a text card drew a player: {text_body}"
2906+ );
2907+}
2908+
2909+/// An audio link wears the same house player — bar above the element,
2910+/// wiring script included, no native controls, no fullscreen button (that
2911+/// is the video variant's) — fed by the public `?media=1` stream.
2912+#[tokio::test]
2913+async fn audio_link_card_draws_the_house_player() {
2914+ let app = TestApp::build().await;
2915+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2916+ let owner = owner_of(&app, "sub-admin").await;
2917+ let tone = file_id(&app, &owner, "tone.ogg", b"OggS\x00\x00\x00\x00").await;
2918+ let answer = app
2919+ .post(
2920+ "/api/share/link/create",
2921+ Some(&admin),
2922+ &[("kind", "file"), ("target_id", &tone)],
2923+ )
2924+ .await;
2925+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
2926+ let token = created_token(answer.location.as_deref().unwrap());
2927+
2928+ let page = app.get(&format!("/s/{token}"), None).await;
2929+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2930+ let body = page.text();
2931+ assert!(
2932+ body.contains("<div class=\"media-player\">"),
2933+ "no audio player: {body}"
2934+ );
2935+ assert!(
2936+ body.contains(&format!(
2937+ "<audio class=\"media-el\" src=\"/s/{token}?media=1\" preload=\"metadata\">"
2938+ )),
2939+ "audio element not fed by ?media=1: {body}"
2940+ );
2941+ // The audio variant draws the bar straight into `.media-player` — no
2942+ // `.media-controls` wrapper; that is the video layout's.
2943+ assert!(body.contains("class=\"media-seek\""), "no seek bar: {body}");
2944+ assert!(
2945+ body.contains("class=\"media-play\""),
2946+ "no play toggle: {body}"
2947+ );
2948+ assert!(
2949+ body.contains("__inMediaWired"),
2950+ "house wiring script missing: {body}"
2951+ );
2952+ // The button itself stays video-only; the wiring script's `.media-full`
2953+ // query is on every player page regardless.
2954+ assert!(
2955+ !body.contains("class=\"media-full\""),
2956+ "audio card drew the fullscreen button: {body}"
2957+ );
2958+}
2959+
2960+/// The password gate covers the media stream too: a locked browser is
2961+/// answered with the gate, never the bytes, and an unlocked one streams —
2962+/// ranges included.
2963+#[tokio::test]
2964+async fn password_link_gates_the_media_stream() {
2965+ let app = TestApp::build().await;
2966+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
2967+ let owner = owner_of(&app, "sub-admin").await;
2968+ let clip = file_id(&app, &owner, "clip.mp4", CLIP).await;
2969+ let answer = app
2970+ .post(
2971+ "/api/share/link/create",
2972+ Some(&admin),
2973+ &[
2974+ ("kind", "file"),
2975+ ("target_id", &clip),
2976+ ("password", "open sesame"),
2977+ ],
2978+ )
2979+ .await;
2980+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
2981+ let token = created_token(answer.location.as_deref().unwrap());
2982+
2983+ // Locked: the gate, not the clip.
2984+ let gated = app.get(&format!("/s/{token}?media=1"), None).await;
2985+ assert_eq!(gated.status, StatusCode::OK);
2986+ assert!(
2987+ gated.text().contains("type=\"password\""),
2988+ "the gate did not gate the stream: {}",
2989+ gated.text()
2990+ );
2991+ assert_ne!(
2992+ gated.content_type.as_deref(),
2993+ Some("video/mp4"),
2994+ "the gate leaked the media mime"
2995+ );
2996+
2997+ // Unlocked: the stream serves, ranges included.
2998+ let link = &app.store.share_links(&owner).await.unwrap()[0];
2999+ let proof = in_core::link_unlock_proof(&token, link.password_hash.as_deref().unwrap());
3000+ let unlocked = format!("in_link_{}={proof}", link.id);
3001+ let served = app
3002+ .get(&format!("/s/{token}?media=1"), Some(&unlocked))
3003+ .await;
3004+ assert_eq!(served.status, StatusCode::OK, "{}", served.text());
3005+ assert_eq!(served.content_type.as_deref(), Some("video/mp4"));
3006+ assert_eq!(served.bytes, CLIP);
3007+ let span = app
3008+ .get_with_range(&format!("/s/{token}?media=1"), Some(&unlocked), "bytes=4-")
3009+ .await;
3010+ assert_eq!(span.status, StatusCode::PARTIAL_CONTENT);
3011+ assert_eq!(span.bytes, &CLIP[4..]);
3012+ assert_eq!(span.content_range.as_deref(), Some("bytes 4-15/16"));
3013+}
3014+
2552 // -- share review regressions (FullSilkworm) ------------------------------------3015 // -- share review regressions (FullSilkworm) ------------------------------------
2553 3016
2554 #[tokio::test]3017 #[tokio::test]
style/main.scssmodified+48 -1
@@ -488,6 +488,11 @@ a {
488 color: var(--muted);488 color: var(--muted);
489 }489 }
490 490
491+// The public card's image preview is a bare `<img>` — no class of its own —
492+// so a picture wider than the card must shrink to it instead of widening
493+// the page. Nothing that already fits changes size.
494+.scaffold-note img { max-width: 100%; }
495+
491 // --- Account screens (FirstLogin artboard) ---------------------------------496 // --- Account screens (FirstLogin artboard) ---------------------------------
492 497
493 .auth-stage {498 .auth-stage {
@@ -3160,12 +3165,15 @@ img.avatar {
3160 3165
3161 &:hover { color: var(--ink); }3166 &:hover { color: var(--ink); }
3162 }3167 }
3163-
3164 .settings-title {3168 .settings-title {
3165 margin: 0;3169 margin: 0;
3166 font-size: 18px;3170 font-size: 18px;
3167 font-weight: 700;3171 font-weight: 700;
3168 letter-spacing: -0.01em;3172 letter-spacing: -0.01em;
3173+ // Page titles on the drive surfaces are often file or folder names — an
3174+ // unbroken run of characters has no space to wrap at, and without this it
3175+ // runs off the card and the page with it.
3176+ overflow-wrap: anywhere;
3169 }3177 }
3170 3178
3171 .panel {3179 .panel {
@@ -4445,6 +4453,45 @@ input[type="radio"] {
4445 // -- account screens ---------------------------------------------------------4453 // -- account screens ---------------------------------------------------------
4446 4454
4447 .auth-stage { padding: 0 16px 24px; }4455 .auth-stage { padding: 0 16px 24px; }
4456+
4457+ // -- the viewer page and the house media player -----------------------------
4458+ // The bar's fixed controls (play, the two clocks, mute, speed, fullscreen)
4459+ // plus the seek input's intrinsic width outrun a phone, so the seek input
4460+ // takes a full-width row of its own and the volume slider folds away — a
4461+ // phone carries hardware volume keys, and the mute button stays. The bar
4462+ // fills its card instead of holding a desktop's 560px.
4463+ // The audio bar's controls are the player's own children (only the video
4464+ // stacks a separate .media-controls under the picture), so both containers
4465+ // take the wrap.
4466+ .media-player:not(.media-player-video),
4467+ .media-controls { flex-wrap: wrap; gap: 6px 8px; padding: 8px 10px; }
4468+ .media-seek { flex: 1 1 140px; min-width: 0; }
4469+ .media-vol-slider { display: none; }
4470+ .media-player { width: 100%; }
4471+
4472+ // A phone's chrome is narrower than the desktop budget the video's
4473+ // `calc(100vh - 380px)` assumes — and on a short landscape screen the
4474+ // subtraction would go negative (an invalid height the browser drops).
4475+ // A plain proportion cannot.
4476+ .media-player-video .media-el { max-height: 60vh; }
4477+
4478+ .viewer-stage { padding: 16px; }
4479+
4480+ // The modal viewer's media row: the desktop 24px insets leave a 320px
4481+ // screen less room than the audio bar needs.
4482+ .viewer-body { padding: 16px; }
4483+
4484+ // -- the public /s cards and the refusal notes -------------------------------
4485+ // The desktop card spends 24px of margin and 24px of padding on each side —
4486+ // half of a narrow screen's air, for a surface that is one column of text.
4487+ .scaffold-note { margin: 16px; padding: 16px 16px 20px; }
4488+
4489+ // -- the share modal ---------------------------------------------------------
4490+ // The add-people row and the public-link create row hold four or five
4491+ // controls on one desktop line — on a phone they fold instead of pushing
4492+ // the modal past the viewport. The access list's rows already wrap through
4493+ // the shared `div.member-row` rule.
4494+ .share-modal .pop-row-form { flex-wrap: wrap; }
4448 }4495 }
4449 4496
4450 // -- file viewer page ------------------------------------------------------------4497 // -- file viewer page ------------------------------------------------------------