From c36b77cb0d54d78a81c748cd37231745169e53db 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 06:00:08 +0300 Subject: [PATCH] feat(share): public links may carry a password MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The create-link form gains an optional password; a link minted with one keeps only its Argon2id hash (params mirrored from im) on the row — migration 0005 adds share_link.password_hash, reconcile backfills NULL. A visitor opening such a link meets a gate instead of the card, and every branch behind it (download, thumb, folder browse) stays shut until POST /s/{token} answers the right password; then an in_link_ cookie (Path=/s, HttpOnly, SameSite=Lax, Secure on https issuers) carrying sha256(token:hash) keeps that browser inside. The wrong password re-renders the gate with a note and sets nothing; a revoked or spent link dead-ends even an unlocked browser, the same answer a wrong token gets. Links minted without a password are untouched. --- Cargo.lock | 33 ++++ Cargo.toml | 1 + crates/in-core/Cargo.toml | 2 + .../in-core/migrations/0005_link_password.sql | 11 ++ crates/in-core/src/lib.rs | 3 +- crates/in-core/src/store/mod.rs | 16 +- crates/in-core/src/store/reconcile.rs | 37 +++-- crates/in-core/src/store/schema.rs | 1 + crates/in-core/src/store/turso_store.rs | 69 +++++++- crates/in-core/tests/store.rs | 157 +++++++++++++++++- crates/in-web/src/i18n.rs | 19 +++ crates/in-web/src/share.rs | 145 +++++++++++++++- crates/in-web/tests/http.rs | 129 +++++++++++++- 13 files changed, 599 insertions(+), 24 deletions(-) create mode 100644 crates/in-core/migrations/0005_link_password.sql diff --git a/Cargo.lock b/Cargo.lock index 4cb3116..a86a509 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -197,6 +197,18 @@ dependencies = [ "rustversion", ] +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures 0.2.17", + "password-hash", +] + [[package]] name = "aristo" version = "0.4.1" @@ -362,6 +374,15 @@ dependencies = [ "wyz", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -1797,6 +1818,7 @@ dependencies = [ name = "in-core" version = "0.1.0" dependencies = [ + "argon2", "async-trait", "base64 0.22.1", "bytes", @@ -2491,6 +2513,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "pastey" version = "0.2.3" diff --git a/Cargo.toml b/Cargo.toml index b33f77d..d6da0e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ turso = "=0.8.0-pre.8" rand = "0.10.2" sha2 = "0.11.0" subtle = "2.6.1" +argon2 = "0.5" chacha20poly1305 = "0.10.1" base64 = "0.22.1" toml = "1" diff --git a/crates/in-core/Cargo.toml b/crates/in-core/Cargo.toml index b9401d2..26dacda 100644 --- a/crates/in-core/Cargo.toml +++ b/crates/in-core/Cargo.toml @@ -17,6 +17,7 @@ server = [ "dep:futures-core", "dep:tokio-util", "dep:base64", + "dep:argon2", "dep:chacha20poly1305", "dep:image", "dep:rand", @@ -33,6 +34,7 @@ bytes = { version = "1", optional = true } futures-core = { version = "0.3", optional = true } tokio-util = { version = "0.7", features = ["io"], optional = true } base64 = { workspace = true, optional = true } +argon2 = { workspace = true, optional = true } chacha20poly1305 = { workspace = true, optional = true } image = { workspace = true, optional = true } rand = { workspace = true, optional = true } diff --git a/crates/in-core/migrations/0005_link_password.sql b/crates/in-core/migrations/0005_link_password.sql new file mode 100644 index 0000000..d71845e --- /dev/null +++ b/crates/in-core/migrations/0005_link_password.sql @@ -0,0 +1,11 @@ +-- Optional passwords on public share links. +-- +-- `share_link.password_hash` holds an Argon2id PHC string when the owner +-- gave the link a password, and NULL when the link opens like any other. +-- A visitor who answers the gate keeps their proof in a cookie named for +-- the link's own id — the row needs no session of its own, and a link +-- without a password behaves exactly as it did before this column. +-- Databases already carrying the column never see this file applied +-- piecemeal — they reach the declared shape through `in reconcile`, whose +-- copy map carries the column across. +ALTER TABLE share_link ADD COLUMN password_hash TEXT; diff --git a/crates/in-core/src/lib.rs b/crates/in-core/src/lib.rs index 5eeead6..771c786 100644 --- a/crates/in-core/src/lib.rs +++ b/crates/in-core/src/lib.rs @@ -25,5 +25,6 @@ pub use config::{Config, ConfigError, OidcConfig}; pub use live::{Change, Topic, next_seq}; #[cfg(feature = "server")] pub use store::{ - ReconcileOptions, Result, Store, StoreError, TursoStore, hash_share_token, reconcile, + ReconcileOptions, Result, Store, StoreError, TursoStore, hash_link_password, hash_share_token, + link_password_matches, link_unlock_proof, reconcile, }; diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 91f8267..aa60003 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -26,7 +26,9 @@ pub mod turso_store; #[cfg(feature = "server")] pub use reconcile::{ReconcileOptions, reconcile}; #[cfg(feature = "server")] -pub use turso_store::{TursoStore, hash_share_token}; +pub use turso_store::{ + TursoStore, hash_link_password, hash_share_token, link_password_matches, link_unlock_proof, +}; /// What the store can fail with. A caller that needs to distinguish "no such /// row" from "someone else's row" gets [`StoreError::NotFound`] for the @@ -216,7 +218,10 @@ impl ShareKind { } /// A public share link. The row holds only the token's hash; the plaintext -/// is shown once at creation and never again. +/// is shown once at creation and never again. An owner may also give the +/// link a password: the row then keeps the password's Argon2id PHC string, +/// and a visitor answers the gate once per browser — the proof lives in a +/// cookie, never in a server-side session. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ShareLink { pub id: String, @@ -228,6 +233,7 @@ pub struct ShareLink { pub created_at: OffsetDateTime, pub expires_at: Option, pub revoked_at: Option, + pub password_hash: Option, } impl ShareLink { @@ -528,7 +534,10 @@ pub trait Store: 'static + Send + Sync { /// Creates a public link onto one file or folder. Returns the row and the /// plaintext token — the only moment the token exists outside its hash. - /// A target of another owner is [`StoreError::CrossOwner`]. + /// `password_hash` is stored as given: the caller hashes the password + /// with [`hash_link_password`], because Argon2id is CPU-slow on + /// purpose and only the caller knows whether the hash belongs off the + /// async path. A target of another owner is [`StoreError::CrossOwner`]. async fn create_share_link( &self, created_by: &str, @@ -536,6 +545,7 @@ pub trait Store: 'static + Send + Sync { target_id: &str, can_download: bool, expires_at: Option, + password_hash: Option, ) -> Result; /// Revokes a link. The row stays, so a dead link reads as revoked rather diff --git a/crates/in-core/src/store/reconcile.rs b/crates/in-core/src/store/reconcile.rs index bc3582c..bebc38a 100644 --- a/crates/in-core/src/store/reconcile.rs +++ b/crates/in-core/src/store/reconcile.rs @@ -207,7 +207,9 @@ struct TableMap { /// `ui`, `theme` and `language`, and the file table one for /// `download_count`: a database old enough to predate a column starts on the /// schema's own default rather than on an empty string, which no writer -/// would ever store and no reader would ever honour. Tables the old database +/// would ever store and no reader would ever honour. The share-link table +/// carries `password_hash` the same way, backfilled with NULL — a link from +/// before passwords opens like it always did. Tables the old database /// predates entirely (today: `setting`) map column-for-column and are /// skipped at copy time, starting empty. fn build_maps( @@ -215,6 +217,7 @@ fn build_maps( old_has_theme: bool, old_has_language: bool, old_has_download_count: bool, + old_has_password_hash: bool, ) -> Vec { vec![ TableMap { @@ -285,17 +288,25 @@ fn build_maps( }, TableMap { name: "share_link", - columns: old_cols(&[ - "id", - "token_hash", - "kind", - "target_id", - "created_by", - "can_download", - "created_at", - "expires_at", - "revoked_at", - ]), + columns: { + let mut columns = old_cols(&[ + "id", + "token_hash", + "kind", + "target_id", + "created_by", + "can_download", + "created_at", + "expires_at", + "revoked_at", + ]); + columns.push(if old_has_password_hash { + ("password_hash", "old.password_hash".into()) + } else { + ("password_hash", "NULL".into()) + }); + columns + }, }, TableMap { name: "share_user", @@ -412,11 +423,13 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> let old_has_theme = old_has_column(old_conn, "user", "theme").await?; let old_has_language = old_has_column(old_conn, "user", "language").await?; let old_has_download_count = old_has_column(old_conn, "file", "download_count").await?; + let old_has_password_hash = old_has_column(old_conn, "share_link", "password_hash").await?; let maps = build_maps( old_has_ui, old_has_theme, old_has_language, old_has_download_count, + old_has_password_hash, ); validate_maps(new_conn, &maps).await?; diff --git a/crates/in-core/src/store/schema.rs b/crates/in-core/src/store/schema.rs index faf3e7d..b3763ad 100644 --- a/crates/in-core/src/store/schema.rs +++ b/crates/in-core/src/store/schema.rs @@ -18,6 +18,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[ include_str!("../../migrations/0002_ui.sql"), include_str!("../../migrations/0003_preferences.sql"), include_str!("../../migrations/0004_downloads_settings.sql"), + include_str!("../../migrations/0005_link_password.sql"), ]; /// The whole declared schema — every migration applied in order — as one diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 6e8b99e..d9ac32b 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -38,8 +38,7 @@ const THUMB_SOURCE_CAP: u64 = 64 * 1024 * 1024; const USER_COLUMNS: &str = "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language"; const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at"; const FILE_COLUMNS: &str = "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at, download_count"; -const LINK_COLUMNS: &str = - "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at"; +const LINK_COLUMNS: &str = "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at, password_hash"; const SESSION_COLUMNS: &str = "id, owner_id, folder_id, name, size_bytes, chunk_size, received_bytes, state, created_at, expires_at"; pub struct TursoStore { @@ -544,6 +543,63 @@ pub fn hash_share_token(token: &str) -> String { use sha2::Digest as _; base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(token.as_bytes())) } + +/// Argon2id's cost, mirrored from im's account hasher: 19 MiB of memory, +/// two iterations, one lane. Slow enough that a guess costs real work, +/// cheap enough that unlocking a link never reads as an outage. +pub const ARGON2_MEMORY_KIB: u32 = 19 * 1024; +pub const ARGON2_ITERATIONS: u32 = 2; +pub const ARGON2_PARALLELISM: u32 = 1; + +fn link_argon2() -> argon2::Argon2<'static> { + let params = argon2::Params::new( + ARGON2_MEMORY_KIB, + ARGON2_ITERATIONS, + ARGON2_PARALLELISM, + None, + ) + .expect("argon2 parameters are constants and are in range"); + argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params) +} + +/// Hashes a link password into a PHC string, salt included. The parameters +/// ride in the string itself, so raising the cost later does not lock +/// holders of the link out. +/// +/// CPU-slow on purpose: the caller owns the async boundary and runs this +/// under `tokio::task::spawn_blocking`. +pub fn hash_link_password(password: &str) -> Result { + use argon2::password_hash::{PasswordHasher, SaltString, rand_core::OsRng}; + let salt = SaltString::generate(&mut OsRng); + link_argon2() + .hash_password(password.as_bytes(), &salt) + .map(|hash| hash.to_string()) + .map_err(|e| StoreError::Backend(format!("password hashing failed: {e}"))) +} + +/// Checks a candidate password against a stored PHC string. A malformed +/// hash answers false — a gate that could panic would be a gate an attacker +/// could aim. +pub fn link_password_matches(phc: &str, candidate: &str) -> bool { + use argon2::password_hash::{PasswordHash, PasswordVerifier}; + match PasswordHash::new(phc) { + Ok(parsed) => link_argon2() + .verify_password(candidate.as_bytes(), &parsed) + .is_ok(), + Err(_) => false, + } +} + +/// The unlock proof a visitor's browser carries as `in_link_{id}`: the +/// token and the stored hash bound together, so a proof stolen from one +/// link is worthless on another and a re-keyed password voids every cookie +/// minted before. Same encode as [`hash_share_token`]. +pub fn link_unlock_proof(token: &str, password_hash: &str) -> String { + use base64::Engine as _; + use sha2::Digest as _; + let bound = format!("{token}:{password_hash}"); + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(bound.as_bytes())) +} /// zero-byte upload has no chunks; its finish assembles the empty file. fn chunk_count(size_bytes: u64) -> u64 { if size_bytes == 0 { @@ -807,6 +863,7 @@ fn link_from(row: &Row) -> Result { created_at: parse_stamp(&text(row, 6)?)?, expires_at: opt_stamp(row, 7)?, revoked_at: opt_stamp(row, 8)?, + password_hash: opt_text(row, 9)?, }) } @@ -1951,6 +2008,7 @@ impl Store for TursoStore { target_id: &str, can_download: bool, expires_at: Option, + password_hash: Option, ) -> Result { // The sharer must own a live target: a stranger's, a missing, or a // trashed target refuses before any token exists to leak. @@ -1967,8 +2025,8 @@ impl Store for TursoStore { let conn = self.conn.lock().await; conn.execute( "INSERT INTO share_link (id, token_hash, kind, target_id, created_by, \ - can_download, created_at, expires_at, revoked_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, NULL)", + can_download, created_at, expires_at, revoked_at, password_hash) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, NULL, ?9)", params![ id.clone(), token_hash, @@ -1977,7 +2035,8 @@ impl Store for TursoStore { created_by, if can_download { 1 } else { 0 }, now, - expires + expires, + password_hash, ], ) .await diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index a5c2fac..481536c 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -636,7 +636,7 @@ async fn share_links_open_until_revoked_or_expired() { let created = scratch .store - .create_share_link(&user.id, ShareKind::File, &file.id, true, None) + .create_share_link(&user.id, ShareKind::File, &file.id, true, None, None) .await .unwrap(); // The token is shown once; the row keeps only the hash. @@ -669,6 +669,7 @@ async fn share_links_open_until_revoked_or_expired() { &file.id, false, Some(now - Duration::hours(1)), + None, ) .await .unwrap(); @@ -677,6 +678,160 @@ async fn share_links_open_until_revoked_or_expired() { assert_eq!(scratch.store.share_links(&user.id).await.unwrap().len(), 2); } +#[tokio::test] +async fn a_password_link_round_trips_its_hash() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let file = scratch + .store + .insert_file(&user.id, None, "locked", b"data") + .await + .unwrap(); + let now = OffsetDateTime::now_utc(); + + let hash = in_core::hash_link_password("open sesame").unwrap(); + let created = scratch + .store + .create_share_link( + &user.id, + ShareKind::File, + &file.id, + true, + None, + Some(hash.clone()), + ) + .await + .unwrap(); + + // The hash is really on disk: a fresh database carries the column, and + // the row reads back through a second connection the way it sits. + let raw = raw_conn(&scratch).await; + let mut rows = raw + .query( + "SELECT password_hash FROM share_link WHERE id = ?1", + turso::params![created.link.id.as_str()], + ) + .await + .unwrap(); + let stored = rows.next().await.unwrap().unwrap(); + assert_eq!(stored.get::(0).unwrap(), hash); + + // Resolving hands the hash back, so the route can mint the proof + // without a second read. + let resolved = scratch + .store + .resolve_share_link(&created.link.token_hash, now) + .await + .unwrap() + .unwrap(); + assert_eq!(resolved.password_hash.as_deref(), Some(hash.as_str())); + + // The check answers the right password and refuses the rest — and a + // malformed hash refuses without panicking, the way a gate must. + assert!(in_core::link_password_matches(&hash, "open sesame")); + assert!(!in_core::link_password_matches(&hash, "Open Sesame")); + assert!(!in_core::link_password_matches(&hash, "")); + assert!(!in_core::link_password_matches( + "not a phc string", + "open sesame" + )); + + // The proof binds the token to the stored hash: same pair, same proof; + // any other pair — another link's, or a re-keyed hash — answers + // differently. + assert_eq!( + in_core::link_unlock_proof(&created.token, &hash), + in_core::link_unlock_proof(&created.token, &hash) + ); + assert_ne!( + in_core::link_unlock_proof(&created.token, &hash), + in_core::link_unlock_proof("another-token", &hash) + ); +} +#[tokio::test] +async fn a_pre_password_link_reconciles_to_no_password_and_a_new_one_survives_reopen() { + // A database built from 0001+0004 — the shape In ran with before links + // could carry passwords — has a share_link table with no + // `password_hash` column. Opening it with the current code reconciles + // it onto the declared schema: the link row is carried across and wears + // NULL, opening like it always did, and a password minted after the + // rebuild survives the next boot whole. + let dir = std::env::temp_dir().join(format!("in-test-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("in.db").to_string_lossy().into_owned(); + { + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + conn.execute_batch(include_str!("../migrations/0001_init.sql")) + .await + .unwrap(); + conn.execute_batch(include_str!("../migrations/0002_ui.sql")) + .await + .unwrap(); + conn.execute_batch(include_str!("../migrations/0003_preferences.sql")) + .await + .unwrap(); + conn.execute_batch(include_str!("../migrations/0004_downloads_settings.sql")) + .await + .unwrap(); + conn.execute( + "INSERT INTO user (id, oidc_sub, email, display_name, admin, disabled, \ + quota_bytes, used_bytes, created_at, last_seen_at) \ + VALUES ('u-old', 'sub-old', 'old@example.com', 'Old', 1, 0, 100, 0, \ + '2026-08-01T00:00:00Z', '2026-08-01T00:00:00Z')", + (), + ) + .await + .unwrap(); + conn.execute( + "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \ + thumb_state, created_at, updated_at, deleted_at) \ + VALUES ('f-old', 'u-old', NULL, 'old.txt', 'text/plain', 3, 'none', \ + '2026-08-01T00:00:00Z', '2026-08-01T00:00:00Z', NULL)", + (), + ) + .await + .unwrap(); + conn.execute( + "INSERT INTO share_link (id, token_hash, kind, target_id, created_by, \ + can_download, created_at, expires_at, revoked_at) \ + VALUES ('l-old', 'hash-old', 'file', 'f-old', 'u-old', 1, \ + '2026-08-01T00:00:00Z', NULL, NULL)", + (), + ) + .await + .unwrap(); + } + let storage = dir.join("storage"); + let store = TursoStore::open(&path, Some(&storage)).await.unwrap(); + let links = store.share_links("u-old").await.unwrap(); + assert_eq!(links.len(), 1); + assert_eq!(links[0].id, "l-old"); + assert_eq!(links[0].password_hash, None); + + // A password minted after the rebuild is an ordinary row: the next open + // sees the declared shape, changes nothing, and the hash survives. + let hash = in_core::hash_link_password("open sesame").unwrap(); + store + .create_share_link( + "u-old", + ShareKind::File, + "f-old", + true, + None, + Some(hash.clone()), + ) + .await + .unwrap(); + drop(store); + let store = TursoStore::open(&path, Some(&storage)).await.unwrap(); + let links = store.share_links("u-old").await.unwrap(); + assert_eq!(links.len(), 2); + let carried = links.iter().find(|link| link.id != "l-old").unwrap(); + assert_eq!(carried.password_hash.as_deref(), Some(hash.as_str())); + drop(store); + let _ = std::fs::remove_dir_all(&dir); +} #[tokio::test] async fn per_person_shares_gate_visibility() { let scratch = Scratch::open().await; diff --git a/crates/in-web/src/i18n.rs b/crates/in-web/src/i18n.rs index 026b411..6c7e8b9 100644 --- a/crates/in-web/src/i18n.rs +++ b/crates/in-web/src/i18n.rs @@ -220,6 +220,13 @@ pub enum Key { PublicLinkLabel, AnyoneWithLink, NotActive, + // Link passwords (LinkPassword owns this block). + PasswordOptional, + PasswordProtected, + PasswordPrompt, + PasswordLabel, + WrongPassword, + Unlock, } pub fn t(lang: Lang, key: Key) -> &'static str { @@ -366,6 +373,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { CreateLink => "Create link", ExpiresInDays => "Expires in days", NoShares => "Not shared with anyone yet.", + PasswordOptional => "Password (optional)", + PasswordProtected => "This link is locked", + PasswordPrompt => "Enter the password to open this link.", + PasswordLabel => "Password", + WrongPassword => "Wrong password.", + Unlock => "Unlock", }, Lang::Tr => match key { Cancel => "Vazgeç", @@ -508,6 +521,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { NotActive => "Etkin değil", ExpiresInDays => "Bitiş (gün)", NoShares => "Henüz kimseyle paylaşılmadı.", + PasswordOptional => "Parola (isteğe bağlı)", + PasswordProtected => "Bu bağlantı kilitli", + PasswordPrompt => "Bağlantıyı açmak için parolayı girin.", + PasswordLabel => "Parola", + WrongPassword => "Parola hatalı.", + Unlock => "Kilidi aç", }, } } diff --git a/crates/in-web/src/share.rs b/crates/in-web/src/share.rs index d9f50f8..ba02d14 100644 --- a/crates/in-web/src/share.rs +++ b/crates/in-web/src/share.rs @@ -16,12 +16,13 @@ //! a browser without script can copy it, and the drive and settings pages //! render the copy-once banner off that pair. -use in_core::hash_share_token; use in_core::store::{File, ShareKind, Store, StoreError, ThumbState, User}; +use in_core::{hash_link_password, hash_share_token, link_password_matches, link_unlock_proof}; use serde::Deserialize; use time::OffsetDateTime; use topcoat::Result; use topcoat::context::Cx; +use topcoat::cookie::{Cookies, cookie, cookies}; use topcoat::router::content::Form; use topcoat::router::request::{headers as request_headers, uri}; use topcoat::router::response::IntoResponse; @@ -134,6 +135,15 @@ fn parse_expiry(raw: Option<&str>) -> std::result::Result .ok_or(Refusal::Forbidden) } +/// The link password off the form: absent, blank, or all whitespace is no +/// password — the field is optional, and a blank string nobody typed is +/// never a secret worth keeping. +fn form_password(raw: Option<&str>) -> Option { + raw.map(str::trim) + .filter(|password| !password.is_empty()) + .map(str::to_string) +} + /// The target the caller must own: present, untrashed, and theirs. Anything /// else is not-found — a stranger learns nothing about whose it is. async fn owned_target( @@ -196,6 +206,8 @@ struct CreateLinkForm { can_download: Option, #[serde(default)] expires_in_days: Option, + #[serde(default)] + password: Option, } /// Mints a bearer link. The token is shown once — in the redirect's @@ -218,6 +230,19 @@ async fn create_link(cx: &Cx, Form(input): Form) -> Redirect { Ok(expires_at) => expires_at, Err(refusal) => return redirect_back(cx, "/settings", "create", Some(refusal)), }; + // An optional password on the link: a trimmed empty field is no + // password at all. Argon2id is CPU-slow on purpose, so the hash runs + // off the async path — a hash this cheap would be a hash worth + // guessing. + let password_hash = match form_password(input.password.as_deref()) { + Some(password) => { + match tokio::task::spawn_blocking(move || hash_link_password(&password)).await { + Ok(Ok(hash)) => Some(hash), + _ => return redirect_back(cx, "/settings", "create", Some(Refusal::Unavailable)), + } + } + None => None, + }; let created = app(cx) .store .create_share_link( @@ -228,6 +253,7 @@ async fn create_link(cx: &Cx, Form(input): Form) -> Redirect { // box posts `1`; nothing posted must never mint a download. parse_flag(input.can_download.as_deref(), false), expires_at, + password_hash, ) .await; match created { @@ -439,6 +465,19 @@ async fn shared_link(cx: &Cx) -> topcoat::Result { @@ -530,6 +569,106 @@ async fn shared_link(cx: &Cx) -> topcoat::Result String { + format!("in_link_{link_id}") +} + +/// The gate a password-protected link shows until the browser carries the +/// proof. Same public chrome as the cards — no hint of what waits behind +/// the gate, not even the file's name. +async fn password_gate(cx: &Cx) -> Result { + let language = lang(cx).await; + let action = current_path(cx); + let wrong = has_flag(uri(cx).query().unwrap_or(""), "wrong"); + view! { + cx => +
+ (wordmark(cx).await?) +

(t(language, Key::PasswordProtected))

+

(t(language, Key::PasswordPrompt))

+ if wrong { + + } +
+ + +
+
+ } +} + +#[derive(Deserialize)] +struct UnlockForm { + #[serde(default)] + password: Option, +} + +/// Unlocks a password-protected link: the right password mints the proof +/// cookie and the visitor is sent on to the page as if the gate had never +/// been there; anything else is the gate again, the error riding `?wrong=1`. +/// The whole surface answers a 303 either way, so the response says nothing +/// about whether the guess was close. +#[route(POST "/s/{token}")] +async fn unlock_link( + cx: &Cx, + Form(input): Form, +) -> topcoat::Result { + let token: &str = path_param::(cx); + let store = app(cx).store; + let now = OffsetDateTime::now_utc(); + let link = store + .resolve_share_link(&hash_share_token(token), now) + .await + .ok() + .flatten(); + let Some(link) = link else { + return dead_link(cx).await.into_response(cx); + }; + let Some(password_hash) = link.password_hash else { + // Nothing to unlock: the form has no business here. Back to the page. + return ( + StatusCode::SEE_OTHER, + [(header::LOCATION, format!("/s/{token}"))], + ) + .into_response(cx); + }; + let candidate = input.password.unwrap_or_default(); + // The proof needs the hash after the verify, so the verify gets a copy. + let hash_for_verify = password_hash.clone(); + let matches = + tokio::task::spawn_blocking(move || link_password_matches(&hash_for_verify, &candidate)) + .await + .unwrap_or(false); + if matches { + let proof = link_unlock_proof(token, &password_hash); + // Secure mirrors the session cookie: on when the identity provider + // itself is reached over https, so a plain-http rehearsal stays + // plain. + let secure = app(cx).config.oidc.issuer.starts_with("https://"); + let name = link_cookie_name(&link.id); + cookies(cx).add(cookie! { + name = proof; + Path = "/s"; + HttpOnly; + SameSite = Lax; + Secure = secure + }); + ( + StatusCode::SEE_OTHER, + [(header::LOCATION, format!("/s/{token}"))], + ) + .into_response(cx) + } else { + ( + StatusCode::SEE_OTHER, + [(header::LOCATION, format!("/s/{token}?wrong=1"))], + ) + .into_response(cx) + } +} + /// The bytes behind a public link. A view-only link answers the dead card /// here — the same answer as a spent token — so the surface never says which /// tokens exist. The body streams off disk through @@ -1241,6 +1380,7 @@ pub(crate) async fn share_modal( + } @@ -1249,6 +1389,9 @@ pub(crate) async fn share_modal( (t(language, Key::AnyoneWithLink))
(expiry_line(language, link.expires_at)) + if link.password_hash.is_some() { + "▪ "(t(language, Key::PasswordLabel)) + } (access_chip(language, link.can_download))