The personal finance app for everyone (by everyone)
Ruby
fix(desktop): support a server hosted under a sub-path (#3127)
ServaTilis77a55fff5ba3
diff --git a/desktop/src-tauri/src/commands.rs b/desktop/src-tauri/src/commands.rsindex edeb6cf8c4..06c664c73f 100644--- a/desktop/src-tauri/src/commands.rs+++ b/desktop/src-tauri/src/commands.rs@@ -1,5 +1,6 @@use crate::servers::{- health_check_url, is_healthy_status, normalize_server_url, ServerEntry, ServerStore,+ base_candidates, health_check_url, is_healthy_status, normalize_server_url, ServerEntry,+ ServerStore,};use crate::state::AppState;use tauri::{Emitter, Manager, State};@@ -22,15 +23,23 @@ pub fn remove_server(url: String) -> Result<Vec<ServerEntry>, String> {ServerStore::remove(&url).map_err(|e| e.to_string())}+/// The base `url`'s server is actually served under — a sub-path or the bare+/// origin, whichever answers `/up` with a 200 — or `None` if neither does. That+/// base is what the caller should save and navigate to.#[tauri::command]-pub fn check_server(url: String) -> Result<bool, String> {+pub fn check_server(url: String) -> Result<Option<String>, String> {let canonical = normalize_server_url(&url).map_err(|e| e.to_string())?;- let health = health_check_url(&canonical);- match ureq::get(&health).timeout(std::time::Duration::from_secs(6)).call() {- Ok(resp) => Ok(is_healthy_status(resp.status())),- Err(ureq::Error::Status(code, _)) => Ok(is_healthy_status(code)),- Err(e) => Err(e.to_string()),+ for base in base_candidates(&canonical) {+ let health = health_check_url(&base);+ match ureq::get(&health).timeout(std::time::Duration::from_secs(6)).call() {+ Ok(resp) if is_healthy_status(resp.status()) => return Ok(Some(base)),+ // A non-200 rules out this base only; keep walking up. A transport+ // failure is the whole origin, so it falls through and returns.+ Ok(_) | Err(ureq::Error::Status(_, _)) => continue,+ Err(e) => return Err(e.to_string()),+ }}+ Ok(None)}#[tauri::command]diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex 7d3ec20e93..5c31797574 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -117,9 +117,12 @@ pub fn run() {// server the user has saved, so a malicious deep link// can't load an arbitrary origin into the main webview.if let Some(target) = deep_link::parse(u) {- if servers::is_known_server(&target.server) {+ // Gate on the destination, not the bare origin: a+ // saved server may be mounted under a path, and the+ // link's own path is what lands inside it.+ let dest = format!("{}{}", target.server, target.path);+ if servers::is_known_server(&dest) {if let Some(w) = handle.get_webview_window("main") {- let dest = format!("{}{}", target.server, target.path);let _ = w.eval(&format!("window.location.assign({:?})", dest));}}diff --git a/desktop/src-tauri/src/servers.rs b/desktop/src-tauri/src/servers.rsindex 182d518993..df3ca9dabe 100644--- a/desktop/src-tauri/src/servers.rs+++ b/desktop/src-tauri/src/servers.rs@@ -32,7 +32,12 @@ pub struct ServerEntry {pub label: String,}-pub fn normalize_server_url(input: &str) -> Result<String, ServerError> {+/// Deepest mount path discovery supports, in path segments — a proxy mount is+/// one or two deep in practice. Bounds the probing when the address is a link+/// pasted from inside the app; a base typed exactly is probed at any depth.+pub const MAX_MOUNT_DEPTH: usize = 3;++fn split_base(input: &str) -> Result<(String, String), ServerError> {let trimmed = input.trim();if trimmed.is_empty() {return Err(ServerError::InvalidUrl("empty".into()));@@ -52,7 +57,40 @@ pub fn normalize_server_url(input: &str) -> Result<String, ServerError> {Some(p) => format!("{scheme}://{host}:{p}"),None => format!("{scheme}://{host}"),};- Ok(origin)+ Ok((origin, parsed.path().trim_end_matches('/').to_string()))+}++/// Canonical form of a server address: origin plus the path it is served under.+/// The path is kept, so a Sure mounted under a prefix (`https://host/sure`)+/// works; `base_candidates` is what still resolves a pasted deep link.+pub fn normalize_server_url(input: &str) -> Result<String, ServerError> {+ let (origin, path) = split_base(input)?;+ Ok(format!("{origin}{path}"))+}++/// Bases to try for a normalized URL, most specific first and always ending at+/// the origin. A prefix-mounted server and a pasted deep link are the same+/// shape, so the server decides: the first candidate whose `/up` answers wins.+///+/// The address as typed comes first, so a base entered exactly is probed however+/// deep it is. The rest are every mount depth up to `MAX_MOUNT_DEPTH`, which is+/// what makes the walk finite for a link pasted from inside the app.+pub fn base_candidates(normalized: &str) -> Vec<String> {+ let Ok((origin, path)) = split_base(normalized) else {+ return vec![normalized.to_string()];+ };+ let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();+ let base_at = |depth: usize| {+ format!("{origin}{}", segments[..depth].iter().map(|s| format!("/{s}")).collect::<String>())+ };+ let mut candidates = vec![base_at(segments.len())];+ candidates.extend(+ (0..=segments.len().min(MAX_MOUNT_DEPTH))+ .rev()+ .filter(|&depth| depth != segments.len()) // already first+ .map(base_at),+ );+ candidates}pub fn health_check_url(base: &str) -> String {@@ -163,12 +201,18 @@ pub fn save_active(url: &str) -> Result<(), ServerError> {file_write("active_server", url)}-/// True if `url` normalizes to a server the user has saved (or the active one).+/// True if `url` is `base` itself or sits under it. The boundary check is what+/// keeps `https://sure.example.com.evil.test` from passing as `https://sure.example.com`.+pub fn base_covers(base: &str, url: &str) -> bool {+ url == base || url.strip_prefix(base).is_some_and(|rest| rest.starts_with('/'))+}++/// True if `url` is served by a server the user has saved (or the active one)./// Gates deep-link navigation and SSO so only trusted origins can drive them.pub fn is_known_server(url: &str) -> bool {let Ok(canonical) = normalize_server_url(url) else {return false;};- ServerStore::load().iter().any(|e| e.url == canonical)- || load_active().as_deref() == Some(canonical.as_str())+ ServerStore::load().iter().any(|e| base_covers(&e.url, &canonical))+ || load_active().is_some_and(|active| base_covers(&active, &canonical))}diff --git a/desktop/src-tauri/tests/servers_test.rs b/desktop/src-tauri/tests/servers_test.rsindex 87abea0bc4..4a2384e5c7 100644--- a/desktop/src-tauri/tests/servers_test.rs+++ b/desktop/src-tauri/tests/servers_test.rs@@ -1,4 +1,7 @@-use sure_desktop_lib::servers::{normalize_server_url, health_check_url, is_healthy_status};+use sure_desktop_lib::servers::{+ base_candidates, base_covers, health_check_url, is_healthy_status, normalize_server_url,+ MAX_MOUNT_DEPTH,+};#[test]fn normalizes_bare_host_to_https_origin() {@@ -11,8 +14,14 @@ fn preserves_explicit_http_scheme_and_port() {}#[test]-fn strips_path_and_trailing_slash() {- assert_eq!(normalize_server_url("https://s.example.com/session/new").unwrap(), "https://s.example.com");+fn keeps_the_sub_path_a_server_is_mounted_under() {+ assert_eq!(normalize_server_url("https://s.example.com/sure").unwrap(), "https://s.example.com/sure");+}++#[test]+fn strips_trailing_slash_query_and_fragment() {+ assert_eq!(normalize_server_url("https://s.example.com/sure/").unwrap(), "https://s.example.com/sure");+ assert_eq!(normalize_server_url("https://s.example.com/?a=1#x").unwrap(), "https://s.example.com");}#[test]@@ -23,6 +32,88 @@ fn rejects_empty_input() {#[test]fn builds_health_url() {assert_eq!(health_check_url("https://s.example.com"), "https://s.example.com/up");+ assert_eq!(health_check_url("https://s.example.com/sure"), "https://s.example.com/sure/up");+}++#[test]+fn origin_is_its_own_only_candidate() {+ assert_eq!(base_candidates("https://s.example.com"), vec!["https://s.example.com"]);+}++#[test]+fn walks_a_pasted_deep_link_back_up_to_the_origin() {+ assert_eq!(+ base_candidates("https://s.example.com/sessions/new"),+ vec![+ "https://s.example.com/sessions/new",+ "https://s.example.com/sessions",+ "https://s.example.com",+ ]+ );+}++#[test]+fn keeps_the_port_on_every_candidate() {+ assert_eq!(+ base_candidates("http://localhost:3000/sure"),+ vec!["http://localhost:3000/sure", "http://localhost:3000"]+ );+}++#[test]+fn a_base_covers_itself_and_what_sits_under_it() {+ assert!(base_covers("https://s.example.com", "https://s.example.com"));+ assert!(base_covers("https://s.example.com", "https://s.example.com/accounts"));+ assert!(base_covers("https://s.example.com/sure", "https://s.example.com/sure/accounts"));+}++#[test]+fn a_base_does_not_cover_a_lookalike_host_or_a_sibling_path() {+ assert!(!base_covers("https://s.example.com", "https://s.example.com.evil.test/accounts"));+ assert!(!base_covers("https://s.example.com/sure", "https://s.example.com/surely"));+ assert!(!base_covers("https://s.example.com/sure", "https://s.example.com"));+}++// A deep link is probed against the address as typed and against every mount+// depth up to MAX_MOUNT_DEPTH — no supported mount is skipped, at any depth.+#[test]+fn probes_the_typed_address_and_every_supported_mount_depth() {+ assert_eq!(+ base_candidates("https://s.example.com/a/b/c/d/e"),+ vec![+ "https://s.example.com/a/b/c/d/e",+ "https://s.example.com/a/b/c",+ "https://s.example.com/a/b",+ "https://s.example.com/a",+ "https://s.example.com",+ ]+ );+}++#[test]+fn probes_the_shallow_mount_a_deep_link_sits_under() {+ let candidates = base_candidates("https://s.example.com/sure/transactions/123/edit");+ assert!(+ candidates.contains(&"https://s.example.com/sure".to_string()),+ "the mount base was dropped: {candidates:?}"+ );+ assert_eq!(candidates[0], "https://s.example.com/sure/transactions/123/edit");+ assert_eq!(candidates.last().unwrap(), "https://s.example.com");+}++#[test]+fn a_multi_segment_mount_is_reached_through_a_deep_link() {+ let candidates = base_candidates("https://s.example.com/apps/finance/sure/accounts/42");+ assert!(+ candidates.contains(&"https://s.example.com/apps/finance/sure".to_string()),+ "a {MAX_MOUNT_DEPTH}-segment mount was dropped: {candidates:?}"+ );+}++#[test]+fn the_walk_stays_bounded() {+ let deep = format!("https://s.example.com/{}", vec!["seg"; 40].join("/"));+ assert_eq!(base_candidates(&deep).len(), MAX_MOUNT_DEPTH + 2); // typed + depths 3..0}#[test]diff --git a/desktop/src/bridge.ts b/desktop/src/bridge.tsindex 2352b8e48f..8778bb116a 100644--- a/desktop/src/bridge.ts+++ b/desktop/src/bridge.ts@@ -74,15 +74,17 @@} catch {return;}- const m = path.match(/^\/auth\/([A-Za-z0-9_-]+)$/);+ // Leading group is the base the server is mounted under: "" at a domain+ // root, "/sure" behind a path-prefixing proxy.+ const m = path.match(/^(.*)\/auth\/([A-Za-z0-9_-]+)$/);if (!m) return; // not an SSO provider form (e.g. /sessions, /auth/x/callback)ev.preventDefault();ev.stopImmediatePropagation();// Emit an event (remote pages can emit but not invoke custom commands);// Rust listens for "sure://start-sso" and opens the browser.// eslint-disable-next-line no-console- console.log("[sure] SSO intercept -> emit sure://start-sso", m[1]);- Promise.resolve(emit("sure://start-sso", { server: location.origin, provider: m[1] }))+ console.log("[sure] SSO intercept -> emit sure://start-sso", m[2]);+ Promise.resolve(emit("sure://start-sso", { server: location.origin + m[1], provider: m[2] }))// eslint-disable-next-line no-console.then(() => console.log("[sure] start-sso emitted"))// eslint-disable-next-line no-consolediff --git a/desktop/src/main.ts b/desktop/src/main.tsindex c942dad96f..dcae9fa9d3 100644--- a/desktop/src/main.ts+++ b/desktop/src/main.ts@@ -39,17 +39,18 @@ function setStatus(msg: string, kind: "info" | "error" = "info") {async function connect(rawUrl: string) {setStatus(S.checking, "info");- let healthy: boolean;+ // Remember the base check_server resolved to, not the raw input.+ let base: string | null;try {- healthy = await invoke<boolean>("check_server", { url: rawUrl });+ base = await invoke<string | null>("check_server", { url: rawUrl });} catch (e) {setStatus(serverErrorMessage(e), "error");return;}- if (!healthy) { setStatus(S.unreachable, "error"); return; }+ if (!base) { setStatus(S.unreachable, "error"); return; }try {- const list = await invoke<ServerEntry[]>("add_server", { url: rawUrl, label: "" });- const canonical = list.find((s) => s.url === rawUrl)?.url ?? list[0].url;+ const list = await invoke<ServerEntry[]>("add_server", { url: base, label: "" });+ const canonical = list.find((s) => s.url === base)?.url ?? list[0].url;await invoke("set_active_server", { url: canonical });goToServer(canonical);} catch (e) {diff --git a/desktop/src/prefs.ts b/desktop/src/prefs.tsindex 432708c901..1259fca3c4 100644--- a/desktop/src/prefs.ts+++ b/desktop/src/prefs.ts@@ -52,9 +52,9 @@ $("prefs-add").addEventListener("submit", async (e) => {if (!url) return;$("prefs-status").textContent = S.checking;try {- const ok = await invoke<boolean>("check_server", { url });- if (!ok) { $("prefs-status").textContent = S.unreachable; return; }- await invoke("add_server", { url, label: "" });+ const base = await invoke<string | null>("check_server", { url });+ if (!base) { $("prefs-status").textContent = S.unreachable; return; }+ await invoke("add_server", { url: base, label: "" });($("prefs-url") as HTMLInputElement).value = "";$("prefs-status").textContent = "";renderServers();