diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index aa60003..0e22ff2 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -193,7 +193,7 @@ impl ThumbState { /// Which table a share points at — one file, or one folder and everything /// under it. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ShareKind { File, @@ -218,7 +218,9 @@ impl ShareKind { } /// A public share link. The row holds only the token's hash; the plaintext -/// is shown once at creation and never again. An owner may also give the +/// never sits in this table — the web layer seals it onto a +/// `share_token:{id}` setting row with the app key, so the full address can +/// be re-shown later. 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. @@ -244,7 +246,7 @@ impl ShareLink { } /// A freshly created link, with the one thing the row does not keep: the -/// plaintext token, shown once and then forgotten. +/// plaintext token, which the web layer seals away for later re-display. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CreatedLink { pub link: ShareLink, @@ -531,9 +533,9 @@ pub trait Store: 'static + Send + Sync { async fn empty_trash(&self, owner_id: &str) -> Result; // -- share links ------------------------------------------------------- - /// 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. + /// plaintext token — the only moment it exists unsealed; the web layer + /// seals it onto a setting row at once. /// `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 @@ -565,6 +567,12 @@ pub trait Store: 'static + Send + Sync { now: OffsetDateTime, ) -> Result>; + /// Every target the person shares today, as `(kind, target_id)` with + /// duplicates folded away: the live public links they minted — + /// unrevoked and unexpired — plus the targets they granted to other + /// people. The drive page marks these rows as shared. + async fn shared_target_ids(&self, owner_id: &str) -> Result>; + // -- per-person shares ------------------------------------------------- /// Shares one file or folder with one person. The caller must own the @@ -680,6 +688,10 @@ pub trait Store: 'static + Send + Sync { /// Keys are free-form; the web layer is the only writer today. async fn set_setting(&self, key: &str, value: &str) -> Result<()>; + /// Removes one instance-level setting. A key never set is not an error: + /// deleting what is not there leaves exactly what was asked for. + async fn delete_setting(&self, key: &str) -> Result<()>; + // -- search ------------------------------------------------------------ /// Owner-scoped substring search over live file and folder names, files diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 7ae60ea..1227bdc 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -554,7 +554,7 @@ fn like_pattern(query: &str) -> String { } /// A fresh public-link token: 32 random bytes, base64url without padding. -/// Shown once at creation; only its hash is stored. +/// Shown at creation and sealed by the web layer; only its hash is stored here. fn new_token() -> String { use base64::Engine as _; let mut bytes = [0u8; 32]; @@ -1641,6 +1641,14 @@ impl Store for TursoStore { Ok(()) } + async fn delete_setting(&self, key: &str) -> Result<()> { + let conn = self.conn.lock().await; + conn.execute("DELETE FROM setting WHERE key = ?1", params![key]) + .await + .map_err(backend)?; + Ok(()) + } + async fn thumb_bytes(&self, id: &str) -> Result>> { let conn = self.conn.lock().await; let mut rows = conn @@ -2156,6 +2164,47 @@ impl Store for TursoStore { } } + async fn shared_target_ids(&self, owner_id: &str) -> Result> { + let now = OffsetDateTime::now_utc(); + let mut found: std::collections::HashSet<(ShareKind, String)> = + std::collections::HashSet::new(); + let conn = self.conn.lock().await; + // Link liveness is decided here rather than in SQL, the way + // resolve_share_link decides it: one definition of live, the row's + // own timestamps. + let mut rows = conn + .query( + &format!("SELECT {LINK_COLUMNS} FROM share_link WHERE created_by = ?1"), + params![owner_id], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + let link = link_from(&row)?; + if link.is_live(now) { + found.insert((link.kind, link.target_id)); + } + } + drop(rows); + // Grants name no owner — the target's own row does — so the ids are + // matched against the person's files and folders directly. + let mut rows = conn + .query( + "SELECT DISTINCT kind, target_id FROM share_user \ + WHERE (kind = 'file' AND target_id IN (SELECT id FROM file WHERE owner_id = ?1)) \ + OR (kind = 'folder' AND target_id IN (SELECT id FROM folder WHERE owner_id = ?1))", + params![owner_id], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + found.insert((ShareKind::parse(&text(&row, 0)?)?, text(&row, 1)?)); + } + drop(rows); + drop(conn); + Ok(found.into_iter().collect()) + } + async fn add_share_user( &self, caller_id: &str, diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index 12c26d8..3a5f4f6 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -680,6 +680,94 @@ async fn share_links_open_until_revoked_or_expired() { assert_eq!(scratch.store.share_links(&user.id).await.unwrap().len(), 2); } +/// The drive page's Shared mark reads its set from here: live links and +/// given grants are in, revoked and expired links are out, and another +/// owner's grants never leak in. +#[tokio::test] +async fn shared_target_ids_holds_live_links_and_own_grants() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let friend = bob(&scratch.store).await; + let linked = scratch.store.insert_file(&user.id, None, "linked", b"d").await.unwrap(); + let granted = scratch.store.insert_file(&user.id, None, "granted", b"d").await.unwrap(); + let folder = scratch.store.create_folder(&user.id, None, "dossier").await.unwrap(); + let strangers = scratch.store.insert_file(&friend.id, None, "theirs", b"d").await.unwrap(); + + // Empty while nothing is shared. + assert!(scratch.store.shared_target_ids(&user.id).await.unwrap().is_empty()); + + let file_link = scratch + .store + .create_share_link(&user.id, ShareKind::File, &linked.id, true, None, None) + .await + .unwrap(); + scratch + .store + .add_share_user(&user.id, ShareKind::File, &granted.id, &friend.id, false) + .await + .unwrap(); + scratch + .store + .add_share_user(&user.id, ShareKind::Folder, &folder.id, &friend.id, true) + .await + .unwrap(); + + let shared: std::collections::HashSet<_> = scratch + .store + .shared_target_ids(&user.id) + .await + .unwrap() + .into_iter() + .collect(); + let expected: std::collections::HashSet<_> = vec![ + (ShareKind::File, granted.id.clone()), + (ShareKind::File, linked.id.clone()), + (ShareKind::Folder, folder.id.clone()), + ] + .into_iter() + .collect(); + assert_eq!(shared, expected); + // The friend shares nothing of their own: a grant received is not a + // grant given. + assert!(scratch.store.shared_target_ids(&friend.id).await.unwrap().is_empty()); + + // A revoked link drops out; the grant stays. + scratch.store.revoke_share_link(&file_link.link.id).await.unwrap(); + let shared = scratch.store.shared_target_ids(&user.id).await.unwrap(); + assert_eq!(shared.len(), 2); + assert!(!shared.contains(&(ShareKind::File, linked.id.clone()))); + + // An expired link drops out too. + let past = scratch + .store + .create_share_link( + &user.id, + ShareKind::File, + &linked.id, + true, + Some(OffsetDateTime::now_utc() - Duration::hours(1)), + None, + ) + .await + .unwrap(); + let shared = scratch.store.shared_target_ids(&user.id).await.unwrap(); + assert!(!shared.contains(&(ShareKind::File, past.link.target_id.clone()))); + assert!(!shared.contains(&(ShareKind::File, strangers.id.clone()))); + + // Deleting the grant removes the last mark its target had. + scratch + .store + .remove_share_user(ShareKind::File, &granted.id, &friend.id) + .await + .unwrap(); + let shared = scratch.store.shared_target_ids(&user.id).await.unwrap(); + assert_eq!( + shared, + vec![(ShareKind::Folder, folder.id.clone())], + "the folder link is all that is left" + ); +} + #[tokio::test] async fn a_password_link_round_trips_its_hash() { let scratch = Scratch::open().await; diff --git a/crates/in-web/src/drive.rs b/crates/in-web/src/drive.rs index 1050e93..860fc65 100644 --- a/crates/in-web/src/drive.rs +++ b/crates/in-web/src/drive.rs @@ -13,7 +13,9 @@ //! plain GET form. The old `GET /search?q=` address 303s here, so old links //! keep working. -use in_core::store::{Folder, Store, StoreError}; +use std::collections::HashSet; + +use in_core::store::{Folder, ShareKind, Store, StoreError}; use topcoat::router::request::uri; use topcoat::router::{HeaderName, HeaderValue, StatusCode, header, page, query_params, route}; @@ -511,6 +513,15 @@ async fn drive(cx: &Cx) -> Result { .as_ref() .map(|folder| folder.id.clone()) .unwrap_or_default(); + // The rows this account shares today — live public links it minted and + // grants it gave — marked on the listing. A failure reads as nothing + // marked: the chip is garnish, and the listing itself is the meal. + let shared: HashSet<(ShareKind, String)> = store + .shared_target_ids(&user.id) + .await + .unwrap_or_default() + .into_iter() + .collect(); let current_name = current .as_ref() .map(|folder| folder.name.clone()) @@ -706,7 +717,12 @@ async fn drive(cx: &Cx) -> Result {
- (folder.name.clone()) + + (folder.name.clone()) + if shared.contains(&(ShareKind::Folder, folder.id.clone())) { + (t(language, Key::Shared)) + } + (folder.created_at.date().to_string()) @@ -717,7 +733,12 @@ async fn drive(cx: &Cx) -> Result {
(crate::files::entry_chip(cx, file).await?) - (file.name.clone()) + + (file.name.clone()) + if shared.contains(&(ShareKind::File, file.id.clone())) { + (t(language, Key::Shared)) + } + (human_size(file.size_bytes)) (file.created_at.date().to_string()) (file.download_count.to_string()) @@ -762,7 +783,12 @@ async fn drive(cx: &Cx) -> Result { } else { - (folder.name.clone()) + + (folder.name.clone()) + if shared.contains(&(ShareKind::Folder, folder.id.clone())) { + (t(language, Key::Shared)) + } + (folder.created_at.date().to_string()) @@ -801,7 +827,12 @@ async fn drive(cx: &Cx) -> Result { } else { (crate::files::entry_chip(cx, file).await?) - (file.name.clone()) + + (file.name.clone()) + if shared.contains(&(ShareKind::File, file.id.clone())) { + (t(language, Key::Shared)) + } + (human_size(file.size_bytes)) (file.created_at.date().to_string()) (file.download_count.to_string()) diff --git a/crates/in-web/src/i18n.rs b/crates/in-web/src/i18n.rs index 859fd09..2ff9bcc 100644 --- a/crates/in-web/src/i18n.rs +++ b/crates/in-web/src/i18n.rs @@ -232,6 +232,9 @@ pub enum Key { EffectiveOrigin, BaseUrlLabel, BaseUrlNote, + // Re-viewable share links (LinkVisible owns this block). + Shared, + LegacyLinkNote, } pub fn t(lang: Lang, key: Key) -> &'static str { @@ -335,7 +338,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str { EnableUser => "Enable", DisabledBadge => "disabled", LinkCreated => "Link created.", - CopyLinkOnce => "Copy it now. It is shown once and never again.", + CopyLinkOnce => "Copy it now. The full address also stays on your Share links panel.", ExpiresLabel => "Expires", NeverExpires => "Never", ViewOnly => "View only: preview, no downloads", @@ -388,6 +391,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { EffectiveOrigin => "Effective origin", BaseUrlLabel => "Public base URL", BaseUrlNote => "The origin share links carry: a saved value wins, an empty one falls back to the configured base_url, then the bind address.", + Shared => "Shared", + LegacyLinkNote => "This link predates re-viewable addresses — revoke and mint a new one to carry it forward.", }, Lang::Tr => match key { Cancel => "Vazgeç", @@ -487,7 +492,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str { EnableUser => "Etkinleştir", DisabledBadge => "devre dışı", LinkCreated => "Bağlantı oluşturuldu.", - CopyLinkOnce => "Şimdi kopyala. Bir kez gösterilir, bir daha gösterilmez.", + CopyLinkOnce => "Şimdi kopyala. Tam adres, Paylaşım bağlantıları panelinde de görünür kalır.", ExpiresLabel => "Bitiş", NeverExpires => "Süresiz", ViewOnly => "Yalnızca görüntüleme: önizleme, indirme yok", @@ -540,6 +545,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { EffectiveOrigin => "Etkin kök adres", BaseUrlLabel => "Herkese açık kök adres", BaseUrlNote => "Paylaşım bağlantılarının taşıdığı kök adres: kaydedilen değer önceliklidir, boş bırakılırsa yapılandırılmış base_url'e, sonra bağlanılan adrese dönülür.", + Shared => "Paylaşılmış", + LegacyLinkNote => "Bu bağlantı, adreslerin yeniden görüntülenebildiği dönemden önce oluşturuldu — devam ettirmek için iptal edip yeni bir tane oluşturun.", }, } } diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index e819024..f2a108c 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -134,8 +134,10 @@ async fn main() { }); let store: Arc = store; - // The key sealing the OIDC session cookies, kept beside the database as - // `in.key` — one key per deployment, never in the repository. + // The `in.key` loaded here seals two things: the OIDC session cookies + // below, and — through the app context — the share-link tokens their + // creation seals onto setting rows, so the full link addresses can be + // re-shown later. One key per deployment, never in the repository. let key_path = std::path::Path::new(&config.database) .parent() .map(|parent| parent.join("in.key")) @@ -180,6 +182,7 @@ async fn main() { store, config, shutdown: in_web::live::Shutdown(stopping), + link_key: cookie_key, }) .app_context(in_web::live::LiveWindow(std::time::Duration::from_secs( live_seconds, diff --git a/crates/in-web/src/server.rs b/crates/in-web/src/server.rs index c0981ff..d9efe5a 100644 --- a/crates/in-web/src/server.rs +++ b/crates/in-web/src/server.rs @@ -35,6 +35,12 @@ pub struct App { /// Told when the process is stopping, so the live streams end instead of /// being waited out. pub shutdown: crate::live::Shutdown, + /// The `in.key` loaded at boot — the same key that seals the session + /// cookies. Share-link creation seals the minted token with it onto a + /// setting row, so the full link address can be re-shown later; a + /// database copy without the key file carries links that open but can + /// no longer be re-viewed. + pub link_key: in_core::store::secret::Key, } /// The application context this request runs under. @@ -54,6 +60,25 @@ pub async fn share_origin(cx: &Cx) -> String { } } +/// The full public address of a share link — `{origin}/s/{token}` — +/// re-derived from the token its creation sealed onto the +/// `share_token:{id}` setting row. +/// +/// `None` when the address cannot be told again: a link minted before the +/// sealing carries no row, and a key lost since minting opens nothing. Both +/// callers degrade the same way — the masked value plus the legacy note — +/// so the option is the whole contract. +pub async fn share_link_url(cx: &Cx, link: &in_core::store::ShareLink) -> Option { + let app = app(cx); + let sealed = app + .store + .get_setting(&format!("share_token:{}", link.id)) + .await + .ok()??; + let token = in_core::store::secret::open(&app.link_key, &sealed)?; + Some(format!("{}/s/{token}", share_origin(cx).await)) +} + /// A stable-enough label for the client, for rate limiting. A proxy header is /// only trusted because In is meant to sit behind one; the address bucket is /// the limit that actually protects the login round-trip either way. diff --git a/crates/in-web/src/settings.rs b/crates/in-web/src/settings.rs index 218ab13..9837997 100644 --- a/crates/in-web/src/settings.rs +++ b/crates/in-web/src/settings.rs @@ -21,11 +21,12 @@ use topcoat::router::content::Form; use topcoat::router::request::uri; use topcoat::router::{HeaderName, StatusCode, header, page, route}; use topcoat::view::view; - +use crate::server::{ + Refusal, app, back_to, require_admin, require_user, share_link_url, share_origin, +}; +use crate::share::{refusal_banner, refusal_of, share_copy_script}; use crate::i18n::{Key, lang, t}; use crate::layout::{NavPage, topbar}; -use crate::server::{Refusal, app, back_to, require_admin, require_user, share_origin}; -use crate::share::{refusal_banner, refusal_of}; /// Bytes in human units: `512 B`, `1.5 KiB`, `2.0 GiB`. One decimal past /// bytes so a quota line reads at a glance. @@ -315,7 +316,7 @@ async fn settings(cx: &Cx) -> Result { // Only the section on show pays for its rows: the links panel names // each live link's target, Everyone lists the accounts, and the server // panel needs the origin — nothing else reads them. - let mut link_names: Vec<(&in_core::store::ShareLink, String)> = Vec::new(); + let mut link_names: Vec<(&in_core::store::ShareLink, String, Option)> = Vec::new(); let links = if section == Section::Links { store.share_links(&user.id).await? } else { @@ -343,7 +344,10 @@ async fn settings(cx: &Cx) -> Result { .map(|folder| folder.name), } .unwrap_or_else(|| link.target_id.clone()); - link_names.push((link, name)); + // The full address, re-derived from the token the creation + // sealed away; `None` keeps the row masked with the note. + let url = share_link_url(cx, link).await; + link_names.push((link, name, url)); } } let users = if administers && section == Section::Everyone { @@ -455,7 +459,7 @@ async fn settings(cx: &Cx) -> Result { if link_names.is_empty() {

(t(language, Key::NoLinks))

} - for (link, target_name) in &link_names { + for (link, target_name, url) in &link_names {
(format!("{} · {}", link.kind.as_str(), target_name.clone())) (expiry_line(language, link.expires_at)) @@ -466,9 +470,26 @@ async fn settings(cx: &Cx) -> Result {
+ // The same affordance the modal's live row + // carries: the full address with its copy + // button, or the masked value plus the + // carry-forward note for a link from before + // the sealing. + }
+ // One delegated listener serves every row's copy button + // above; the script is idempotent across re-renders. + (share_copy_script(cx).await?) } if section == Section::Everyone {
diff --git a/crates/in-web/src/share.rs b/crates/in-web/src/share.rs index 93c4afc..a72e347 100644 --- a/crates/in-web/src/share.rs +++ b/crates/in-web/src/share.rs @@ -13,10 +13,12 @@ //! //! Every mutation answers the way `board.rs` in iz does: a 303 back to the //! page the form was posted from, the refusal (if any) on the redirect's -//! query. The one exception is link creation, whose plaintext token exists -//! only at creation: the redirect carries it once as `?created=` so -//! a browser without script can copy it, and the drive and settings pages -//! render the copy-once banner off that pair. +//! query. The one exception is link creation, whose plaintext token is +//! sealed with the app key onto the `share_token:{id}` setting row and +//! shown in the redirect's `?created=` pair, so a browser without +//! script can copy it; the drive and settings pages render the copy-once +//! banner off that pair, and re-derive the full address for the live-link +//! rows from the sealed one. 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}; @@ -34,7 +36,7 @@ use topcoat::view::view; use crate::files::{ViewerKind, entry_chip, media_player, media_player_script, viewer_kind}; use crate::i18n::{Key, Lang, lang, t}; use crate::layout::{NavPage, document_shell, topbar, wordmark}; -use crate::server::{Refusal, app, back_to, require_user, share_origin}; +use crate::server::{Refusal, app, back_to, require_user, share_link_url, share_origin}; path_param!(token); path_param!(kind); @@ -212,9 +214,11 @@ struct CreateLinkForm { password: Option, } -/// Mints a bearer link. The token is shown once — in the redirect's -/// `?created=` pair, which the drive and settings pages render as the -/// copy-once banner — and never again; only its hash is stored. +/// Mints a bearer link. The token rides the redirect's `?created=` pair — +/// which the drive and settings pages render as the copy-once banner — and +/// is sealed with the app key onto the `share_token:{id}` setting row, so +/// the full address can be re-shown later; the row itself keeps only the +/// token's hash. #[route(POST "/api/share/link/create")] async fn create_link(cx: &Cx, Form(input): Form) -> Redirect { let user = match require_user(cx).await { @@ -259,10 +263,21 @@ async fn create_link(cx: &Cx, Form(input): Form) -> Redirect { ) .await; match created { - Ok(link) => { + Ok(minted) => { + // The token is sealed onto its own setting row — the same + // `in.key` that seals the session cookies — so the share modal + // and the settings panel can re-show the full address later. A + // failed seal is lived with, not refused: refusing now would + // leave a live link whose token the one-time banner never + // showed, the worse half of that bargain. + let sealed = in_core::store::secret::seal(&app(cx).link_key, &minted.token); + let _ = app(cx) + .store + .set_setting(&format!("share_token:{}", minted.link.id), &sealed) + .await; let back = back_to(cx, "/settings?section=links"); let separator = if back.contains('?') { '&' } else { '?' }; - let location = format!("{back}{separator}created={}", link.token); + let location = format!("{back}{separator}created={}", minted.token); Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)])) } Err(error) => redirect_back(cx, "/settings?section=links", "create", Some(refusal_of(error))), @@ -297,7 +312,21 @@ async fn revoke_link(cx: &Cx, Form(input): Form) -> Redirect { return redirect_back(cx, "/settings?section=links", "revoke", Some(Refusal::NotFound)); } match store.revoke_share_link(&input.id).await { - Ok(()) => redirect_back(cx, "/settings?section=links", "revoke", None), + Ok(()) => { + // The sealed address dies with the link: deleting the row is + // part of revoking, not cleanup after it, so a failed delete + // reports the revoke as refused. A retry finishes the job — + // revoking twice is not an error. + match store + .delete_setting(&format!("share_token:{}", input.id)) + .await + { + Ok(()) => redirect_back(cx, "/settings?section=links", "revoke", None), + Err(error) => { + redirect_back(cx, "/settings?section=links", "revoke", Some(refusal_of(error))) + } + } + } Err(error) => redirect_back(cx, "/settings?section=links", "revoke", Some(refusal_of(error))), } } @@ -1504,6 +1533,10 @@ pub(crate) async fn share_modal( } for link in live.iter().take(1) { + // The full address, re-derived from the token the creation sealed + // away. A link from before the sealing — or one whose key is gone — + // keeps the masked value and carries the carry-forward note. + let url = share_link_url(cx, *link).await;
(t(language, Key::AnyoneWithLink))
@@ -1514,7 +1547,13 @@ pub(crate) async fn share_modal( (access_chip(language, link.can_download))