Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(desktop): add report download & print handling (#3480)

Anthonya4ae3e2be450
diff --git a/desktop/README.md b/desktop/README.md
index edbe1a9745..03f5f35f5f 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -57,6 +57,29 @@ cd desktop/src-tauri
cargo test
```
+## Reports and downloads
+
+CSV exports are saved in the macOS Downloads folder. Sure sends a native
+notification when a download finishes or fails; allow Sure notifications in
+System Settings to see them. Repeated downloads get a numbered filename.
+
+Print Report opens a separate Sure window using the current signed-in session,
+then the native print dialog once the report has loaded. Print it, or choose
+PDF → Save as PDF. Close the report window to return to the app.
+
+Other links that open a new window follow the same rule: pages of your Sure
+server open in a separate Sure window with your session, and other websites
+open in your default browser. Only the main window has the desktop
+integrations: notifications, SSO in your browser and report CSV exports.
+Downloads are only accepted from pages of your saved servers.
+
+To verify changes to this flow, run `npm test` and `npm run build` in `desktop`,
+then `cargo test --locked` in `desktop/src-tauri`. In the desktop app, export a
+CSV twice, check both files in Downloads, and open Print Report to save a PDF.
+Open an external link (for example the Discord help icon) and check that it
+opens in your browser. Repeat against a server mounted under a URL prefix, if
+applicable.
+
## Deep links
Registered scheme: `sure://{host}[:port]/{path}` → opens the app to that
server/page. Example: `open "sure://localhost:3000/accounts"`. (Works from the
diff --git a/desktop/package.json b/desktop/package.json
index 237b6ec8ee..f76d571f2b 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -6,6 +6,7 @@
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
+ "test": "node --test tests/*.test.mjs",
"tauri": "tauri"
},
"devDependencies": {
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index 5c31797574..18853b1c98 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -133,7 +133,9 @@ pub fn run() {
Ok(())
})
.on_page_load(|window, payload| {
- if payload.event() == tauri::webview::PageLoadEvent::Finished {
+ if matches!(window.label(), "main" | "prefs")
+ && payload.event() == tauri::webview::PageLoadEvent::Finished
+ {
const BRIDGE: &str = include_str!("../../dist/bridge.js");
let _ = window.eval(BRIDGE);
}
diff --git a/desktop/src-tauri/src/window.rs b/desktop/src-tauri/src/window.rs
index 98d4b0c230..8a5c37de41 100644
--- a/desktop/src-tauri/src/window.rs
+++ b/desktop/src-tauri/src/window.rs
@@ -1,8 +1,42 @@
-use tauri::Manager;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use tauri::webview::{DownloadEvent, NewWindowResponse, PageLoadEvent, PageLoadPayload};
+use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindow, WebviewWindowBuilder, Wry};
use tauri_plugin_decorum::WebviewWindowExt;
+use tauri_plugin_notification::NotificationExt;
+use url::Url;
+
+static POPUP_WINDOW_ID: AtomicUsize = AtomicUsize::new(0);
+
+/// Wait after a printable report loads before opening the print dialog. This
+/// matches the delay in Sure's print layout, which lets styles settle.
+const PRINT_DELAY: Duration = Duration::from_millis(500);
pub fn setup(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
- let window = app.get_webview_window("main").expect("main window exists");
+ // Build the configured window here so native download and popup handlers
+ // are attached before the webview loads the server.
+ let config = app
+ .config()
+ .app
+ .windows
+ .iter()
+ .find(|window| window.label == "main")
+ .expect("main window configuration exists");
+ let handle = app.handle().clone();
+ let page = ShownPage::default();
+ let window = WebviewWindowBuilder::from_config(app, config)?
+ .on_page_load({
+ let page = page.clone();
+ move |_, payload| page.record(&payload)
+ })
+ .on_download({
+ let page = page.clone();
+ let refused = RefusedDownloads::default();
+ move |webview, event| on_download(&page, &refused, webview, event)
+ })
+ .on_new_window(move |url, _| on_new_window(&handle, &page, url))
+ .build()?;
// The window is opaque (the app paints its own solid backgrounds), so we
// skip the transparent-window vibrancy blur — it never showed through and
@@ -14,3 +48,214 @@ pub fn setup(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
+
+/// Where a page's request to open a new window (a `target="_blank"` link or
+/// `window.open`) should go.
+#[derive(Debug, PartialEq, Eq)]
+pub enum PopupAction {
+ /// A page of a saved server opens in a Sure window that keeps the session.
+ ServerWindow,
+ /// Any other website opens in the default browser, which has no session.
+ Browser,
+ /// Anything else is ignored.
+ Deny,
+}
+
+/// Decide where a popup goes. Popups are honored only while the opener window
+/// shows a page of a saved server (`opener_trusted`). Frames embedded in that
+/// page count as the page, because the requesting frame is not exposed. Only
+/// plain http(s) addresses without credentials are opened, so no page can hand
+/// other schemes to the system. `is_known_server` is injected so the policy can
+/// be tested without the saved server list.
+pub fn popup_action(
+ url: &Url,
+ opener_trusted: bool,
+ is_known_server: impl Fn(&str) -> bool,
+) -> PopupAction {
+ if !opener_trusted || !is_plain_web_url(url) {
+ return PopupAction::Deny;
+ }
+ if is_known_server(url.as_str()) {
+ PopupAction::ServerWindow
+ } else {
+ PopupAction::Browser
+ }
+}
+
+/// Extract the server mount from a printable-report URL, excluding all other
+/// pages. The caller checks that this server was saved by the user.
+pub fn print_report_server(url: &Url) -> Option<String> {
+ if !is_plain_web_url(url) {
+ return None;
+ }
+ let mount = url.path().strip_suffix("/reports/print")?;
+ Some(format!("{}{mount}", url.origin().ascii_serialization()))
+}
+
+fn is_plain_web_url(url: &Url) -> bool {
+ matches!(url.scheme(), "http" | "https")
+ && url.username().is_empty()
+ && url.password().is_none()
+}
+
+/// The page a window shows, recorded each time a navigation commits.
+/// `WebviewWindow::url()` cannot stand in for it: WebKit already reports the
+/// target of a pending navigation there, while the previous page still runs.
+#[derive(Clone, Default)]
+struct ShownPage(Arc<Mutex<Option<Url>>>);
+
+impl ShownPage {
+ fn record(&self, payload: &PageLoadPayload<'_>) {
+ // wry reports Started from didCommitNavigation, when the page changes.
+ if payload.event() == PageLoadEvent::Started {
+ *self.0.lock().unwrap() = Some(payload.url().clone());
+ }
+ }
+
+ fn is_saved_server(&self) -> bool {
+ let page = self.0.lock().unwrap().clone();
+ page.is_some_and(|page| crate::servers::is_known_server(page.as_str()))
+ }
+}
+
+fn on_new_window(handle: &AppHandle, opener: &ShownPage, url: Url) -> NewWindowResponse<Wry> {
+ let opener_trusted = opener.is_saved_server();
+ match popup_action(&url, opener_trusted, crate::servers::is_known_server) {
+ PopupAction::ServerWindow => open_server_window(handle, url),
+ PopupAction::Browser => {
+ if let Err(error) = open::that(url.as_str()) {
+ eprintln!("[sure] failed to open link in the browser: {error}");
+ }
+ }
+ PopupAction::Deny => {}
+ }
+ // Allowed popups are opened above, so WebKit never creates its own.
+ NewWindowResponse::Deny
+}
+
+/// Open a page of a saved server in its own Sure window. It is a separate
+/// webview rather than a WebKit popup, which would run on the main window's
+/// configuration and so reach Rust through the main window's IPC handlers. Both
+/// windows use the default website data store, so the session carries over.
+/// Only the main window gets the bridge script and its desktop integrations.
+fn open_server_window(handle: &AppHandle, url: Url) {
+ let label = format!("popup-{}", POPUP_WINDOW_ID.fetch_add(1, Ordering::Relaxed));
+ // Until a page commits, the window stands for the saved-server address it
+ // was opened with, so a file served directly at that address can download.
+ let page = ShownPage(Arc::new(Mutex::new(Some(url.clone()))));
+ let popup_handle = handle.clone();
+ let result = WebviewWindowBuilder::new(handle, label, WebviewUrl::External(url))
+ .title("Sure")
+ .inner_size(1000.0, 800.0)
+ .on_page_load({
+ let page = page.clone();
+ move |window, payload| {
+ page.record(&payload);
+ print_loaded_report(window, payload);
+ }
+ })
+ .on_download({
+ let page = page.clone();
+ let refused = RefusedDownloads::default();
+ move |webview, event| on_download(&page, &refused, webview, event)
+ })
+ .on_new_window(move |url, _| on_new_window(&popup_handle, &page, url))
+ .on_document_title_changed(|window, title| {
+ let _ = window.set_title(&title);
+ })
+ .build();
+ if let Err(error) = result {
+ eprintln!("[sure] failed to open window: {error}");
+ }
+}
+
+/// Open the native print dialog once a printable report has loaded. Rust prints
+/// the report's own webview; the page's `window.print()` has no IPC permission,
+/// so it cannot open a second dialog.
+fn print_loaded_report(window: WebviewWindow, payload: PageLoadPayload<'_>) {
+ if payload.event() != PageLoadEvent::Finished
+ || !print_report_server(payload.url())
+ .is_some_and(|server| crate::servers::is_known_server(&server))
+ {
+ return;
+ }
+ std::thread::spawn(move || {
+ std::thread::sleep(PRINT_DELAY);
+ if let Err(error) = window.print() {
+ eprintln!("[sure] failed to print report: {error}");
+ }
+ });
+}
+
+/// Downloads a window refused. WebKit ends a refused download as a failure for
+/// the same request URL, which must not be reported to the user as one.
+#[derive(Clone, Default)]
+pub struct RefusedDownloads(Arc<Mutex<Vec<Url>>>);
+
+impl RefusedDownloads {
+ /// Remember the decision for a requested download, and return it.
+ pub fn remember(&self, url: &Url, allowed: bool) -> bool {
+ if !allowed {
+ self.0.lock().unwrap().push(url.clone());
+ }
+ allowed
+ }
+
+ /// Whether a finished download is reported: all of them but the refused.
+ pub fn should_report(&self, url: &Url, success: bool) -> bool {
+ if success {
+ return true;
+ }
+ let mut refused = self.0.lock().unwrap();
+ match refused.iter().position(|refused_url| refused_url == url) {
+ Some(index) => {
+ refused.remove(index);
+ false
+ }
+ None => true,
+ }
+ }
+}
+
+fn on_download(
+ page: &ShownPage,
+ refused: &RefusedDownloads,
+ webview: tauri::Webview,
+ event: DownloadEvent<'_>,
+) -> bool {
+ match event {
+ // Only a page of a saved server may save files into Downloads.
+ DownloadEvent::Requested { url, .. } => {
+ let allowed = page.is_saved_server();
+ if !allowed {
+ eprintln!("[sure] blocked a download from a page outside saved servers");
+ }
+ refused.remember(&url, allowed)
+ }
+ DownloadEvent::Finished { url, success, .. } => {
+ if !refused.should_report(&url, success) {
+ return true;
+ }
+ // macOS does not return a path in Finished. Wry saves downloads to the
+ // Downloads directory and adds a suffix when a filename already exists.
+ let body = if success {
+ "Download complete. The file is in your Downloads folder."
+ } else {
+ eprintln!("[sure] download failed");
+ "Download failed. Please try again."
+ };
+ if let Err(error) = webview
+ .app_handle()
+ .notification()
+ .builder()
+ .title("Sure")
+ .body(body)
+ .show()
+ {
+ eprintln!("[sure] failed to show download notification: {error}");
+ }
+ true
+ }
+ _ => true,
+ }
+}
diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json
index eb8cb89074..65dd742fbf 100644
--- a/desktop/src-tauri/tauri.conf.json
+++ b/desktop/src-tauri/tauri.conf.json
@@ -15,6 +15,7 @@
"windows": [
{
"label": "main",
+ "create": false,
"title": "Sure",
"width": 1200,
"height": 800,
diff --git a/desktop/src-tauri/tests/window_test.rs b/desktop/src-tauri/tests/window_test.rs
new file mode 100644
index 0000000000..5219ae3301
--- /dev/null
+++ b/desktop/src-tauri/tests/window_test.rs
@@ -0,0 +1,138 @@
+use sure_desktop_lib::servers::{base_covers, normalize_server_url};
+use sure_desktop_lib::window::{popup_action, print_report_server, PopupAction, RefusedDownloads};
+use url::Url;
+
+#[test]
+fn identifies_print_reports_with_filters_and_server_mounts() {
+ for (url, expected) in [
+ (
+ "https://sure.example.com/reports/print?period_type=monthly",
+ "https://sure.example.com",
+ ),
+ (
+ "http://localhost:3000/sure/reports/print?start_date=2026-09-01&end_date=2026-09-09",
+ "http://localhost:3000/sure",
+ ),
+ (
+ "https://sure.example.com/nested/sure/reports/print",
+ "https://sure.example.com/nested/sure",
+ ),
+ ] {
+ assert_eq!(
+ print_report_server(&Url::parse(url).unwrap()).as_deref(),
+ Some(expected)
+ );
+ }
+}
+
+#[test]
+fn rejects_other_popup_routes_and_non_server_urls() {
+ for url in [
+ "https://sure.example.com/reports",
+ "https://sure.example.com/reports/print/other",
+ "https://sure.example.com/reports/printable",
+ "https://sure.example.com/accounts?next=/reports/print",
+ "https://user:[email protected]/reports/print",
+ "file:///reports/print",
+ "javascript:window.print()",
+ "about:blank",
+ ] {
+ assert!(
+ print_report_server(&Url::parse(url).unwrap()).is_none(),
+ "accepted {url}"
+ );
+ }
+}
+
+// Mirrors servers::is_known_server without reading the saved server list.
+fn saved_server(url: &str) -> bool {
+ normalize_server_url(url).is_ok_and(|url| {
+ ["https://sure.example.com", "https://home.example.com/sure"]
+ .iter()
+ .any(|base| base_covers(base, &url))
+ })
+}
+
+fn action(url: &str, opener_trusted: bool) -> PopupAction {
+ popup_action(&Url::parse(url).unwrap(), opener_trusted, saved_server)
+}
+
+#[test]
+fn opens_saved_server_pages_in_a_sure_window() {
+ for url in [
+ "https://sure.example.com/reports/print?period_type=monthly",
+ "https://sure.example.com/transactions/1/attachments/2?disposition=inline",
+ "https://sure.example.com/privacy",
+ "https://home.example.com/sure/reports/print",
+ ] {
+ assert_eq!(action(url, true), PopupAction::ServerWindow, "{url}");
+ }
+}
+
+#[test]
+fn opens_other_websites_in_the_browser() {
+ for url in [
+ "https://app.snaptrade.com/device?user_code=ABCD-1234",
+ "https://discord.gg/36ZGBsxYEK",
+ "http://example.org/help",
+ "https://sure.example.com.evil.test/reports/print",
+ "http://sure.example.com/reports/print",
+ "https://home.example.com/other",
+ "https://home.example.com/surely",
+ ] {
+ assert_eq!(action(url, true), PopupAction::Browser, "{url}");
+ }
+}
+
+#[test]
+fn ignores_popups_from_pages_outside_saved_servers() {
+ for url in [
+ "https://sure.example.com/reports/print",
+ "https://app.snaptrade.com/device",
+ ] {
+ assert_eq!(action(url, false), PopupAction::Deny, "{url}");
+ }
+}
+
+#[test]
+fn ignores_non_web_schemes_and_credentials() {
+ for url in [
+ "file:///etc/passwd",
+ "javascript:alert(1)",
+ "about:blank",
+ "data:text/html,hello",
+ "mailto:[email protected]",
+ "sure://sure.example.com/accounts",
+ "x-apple.systempreferences:com.apple.preference.security",
+ "https://user:[email protected]/reports/print",
+ "https://[email protected]/",
+ ] {
+ assert_eq!(action(url, true), PopupAction::Deny, "{url}");
+ }
+}
+
+// The decision made when a download starts holds until it finishes, whatever
+// page the window has navigated to in between.
+#[test]
+fn reports_every_download_outcome_except_refused_downloads() {
+ let downloads = RefusedDownloads::default();
+ let export = Url::parse("https://sure.example.com/reports/export_transactions.csv").unwrap();
+ let tracker = Url::parse("https://tracker.example/file.zip").unwrap();
+
+ assert!(downloads.remember(&export, true));
+ assert!(!downloads.remember(&tracker, false));
+
+ assert!(
+ downloads.should_report(&export, false),
+ "an allowed download that fails is reported"
+ );
+ assert!(downloads.should_report(&export, true));
+ assert!(
+ !downloads.should_report(&tracker, false),
+ "a refused download ends quietly"
+ );
+ assert!(
+ downloads.should_report(&tracker, false),
+ "each refusal silences only its own failure"
+ );
+}
diff --git a/desktop/src/bridge.ts b/desktop/src/bridge.ts
index 8778bb116a..dd2d9d9431 100644
--- a/desktop/src/bridge.ts
+++ b/desktop/src/bridge.ts
@@ -1,7 +1,7 @@
// Injected into every page loaded in the main window (local onboarding + the
// remote Sure site). Adds native-titlebar chrome, drags the window, forwards
-// notifications/badge to Rust, intercepts SSO into the system browser, and
-// navigates on server switches.
+// notifications/badge to Rust, enables report downloads, intercepts SSO into the
+// system browser, and navigates on server switches.
(() => {
const tauri = (window as any).__TAURI__;
@@ -16,6 +16,36 @@
hasWindow: !!tauri?.window,
});
+ // WKWebView needs the download attribute for renderable types such as CSV.
+ // Keep the request in this webview so its authenticated session is retained.
+ // Capture runs before Turbo, while leaving the native click action intact.
+ if (!(window as any).__sureReportDownloadHook) {
+ (window as any).__sureReportDownloadHook = true;
+ document.addEventListener(
+ "click",
+ (ev) => {
+ const link = (ev.target as Element | null)?.closest?.("a[href]") as HTMLAnchorElement | null;
+ if (!link) return;
+ let url: URL;
+ try {
+ url = new URL(link.href, location.href);
+ } catch {
+ return;
+ }
+ if (
+ url.origin !== location.origin ||
+ !url.pathname.endsWith("/reports/export_transactions.csv")
+ ) {
+ return;
+ }
+ if (!link.hasAttribute("download")) link.setAttribute("download", "");
+ link.setAttribute("data-turbo", "false");
+ link.setAttribute("target", "_self");
+ },
+ true
+ );
+ }
+
// Native titlebar chrome — offset the left icon rail so its logo clears the
// traffic lights, and make the top ~34px band drag the window. Using a
// document-level mousedown (rather than a fixed overlay strip) means dragging
diff --git a/desktop/tests/bridge.test.mjs b/desktop/tests/bridge.test.mjs
new file mode 100644
index 0000000000..a957a56772
--- /dev/null
+++ b/desktop/tests/bridge.test.mjs
@@ -0,0 +1,147 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import vm from "node:vm";
+import ts from "typescript";
+
+const source = readFileSync(new URL("../src/bridge.ts", import.meta.url), "utf8");
+const script = new vm.Script(
+ ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2021 } }).outputText
+);
+
+function loadBridge(pageUrl = "https://sure.example/reports") {
+ const listeners = new Map();
+ const context = vm.createContext({
+ URL,
+ window: {},
+ location: new URL(pageUrl),
+ console: { log() {}, warn() {} },
+ document: {
+ head: { appendChild() {} },
+ createElement: () => ({}),
+ addEventListener(type, listener, capture) {
+ const entries = listeners.get(type) || [];
+ entries.push({ listener, capture });
+ listeners.set(type, entries);
+ },
+ },
+ });
+ script.runInContext(context);
+
+ return {
+ reinject: () => script.runInContext(context),
+ listeners,
+ click(target) {
+ const event = {
+ target,
+ defaultPrevented: false,
+ propagationStopped: false,
+ preventDefault() { this.defaultPrevented = true; },
+ stopImmediatePropagation() { this.propagationStopped = true; },
+ };
+ for (const { listener, capture } of listeners.get("click") || []) {
+ assert.equal(capture, true, "the export link must be prepared before Turbo handles the click");
+ listener(event);
+ }
+ return event;
+ },
+ };
+}
+
+function anchor(href, attributes = {}) {
+ const values = { href, ...attributes };
+ const link = {
+ href,
+ attributes: values,
+ hasAttribute: (name) => Object.hasOwn(values, name),
+ setAttribute: (name, value) => { values[name] = value; },
+ closest: (selector) => {
+ assert.equal(selector, "a[href]");
+ return link;
+ },
+ };
+ return link;
+}
+
+function nestedTarget(link) {
+ return {
+ closest(selector) {
+ assert.equal(selector, "a[href]");
+ return link;
+ },
+ };
+}
+
+test("CSV clicks select native download without cancelling the authenticated request", () => {
+ const bridge = loadBridge();
+ const href = "/reports/export_transactions.csv?period_type=custom&start_date=2026-09-01&end_date=2026-09-09";
+ const link = anchor(href, { target: "_blank" });
+
+ const event = bridge.click(nestedTarget(link));
+
+ assert.deepEqual(link.attributes, {
+ href,
+ target: "_self",
+ download: "",
+ "data-turbo": "false",
+ });
+ assert.equal(link.href, href, "the export URL and date filters must stay unchanged");
+ assert.equal(event.defaultPrevented, false);
+ assert.equal(event.propagationStopped, false);
+});
+
+test("CSV downloads support a server mounted beneath a path prefix", () => {
+ const bridge = loadBridge("https://sure.example/finance/sure/reports");
+ const link = anchor("https://sure.example/finance/sure/reports/export_transactions.csv?period_type=ytd");
+
+ bridge.click(link);
+
+ assert.equal(link.attributes.download, "");
+ assert.equal(link.attributes.target, "_self");
+});
+
+test("an explicit filename is retained when marking a report download", () => {
+ const bridge = loadBridge();
+ const link = anchor("/reports/export_transactions.csv", { download: "report.csv" });
+
+ bridge.click(nestedTarget(link));
+
+ assert.equal(link.attributes.download, "report.csv");
+});
+
+test("other origins, routes and formats are left unchanged", () => {
+ const bridge = loadBridge();
+ for (const href of [
+ "https://other.example/reports/export_transactions.csv",
+ "http://sure.example/reports/export_transactions.csv",
+ "https://sure.example:8443/reports/export_transactions.csv",
+ "/reports/print",
+ "/reports/export_transactions.pdf",
+ "/reports/export_transactions.csv/preview",
+ "/other.csv",
+ "http://[invalid",
+ ]) {
+ const link = anchor(href, { target: "_blank" });
+
+ bridge.click(nestedTarget(link));
+
+ assert.deepEqual(link.attributes, { href, target: "_blank" }, href);
+ }
+});
+
+test("clicks outside links remain unaffected", () => {
+ const bridge = loadBridge();
+ assert.doesNotThrow(() => bridge.click(nestedTarget(null)));
+ assert.doesNotThrow(() => bridge.click({}));
+ assert.doesNotThrow(() => bridge.click(null));
+});
+
+test("reinjection installs only one report download listener, even without Tauri IPC", () => {
+ const bridge = loadBridge();
+ bridge.reinject();
+
+ assert.equal(bridge.listeners.get("click").length, 1);
+ const link = anchor("/reports/export_transactions.csv");
+ bridge.click(nestedTarget(link));
+ assert.equal(link.attributes.download, "");
+});