Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
fix: harden dock badge bridge
Tw93ddb9faa80819
diff --git a/src-tauri/src/app/invoke.rs b/src-tauri/src/app/invoke.rsindex 28d8b3f1..82022f42 100644--- a/src-tauri/src/app/invoke.rs+++ b/src-tauri/src/app/invoke.rs@@ -11,9 +11,29 @@ use tauri_plugin_http::reqwest::{ClientBuilder, Request};use tauri::Theme;static BADGE_COUNT: AtomicI64 = AtomicI64::new(0);+const MAX_BADGE_COUNT: i64 = 99_999;+const MAX_BADGE_LABEL_CHARS: usize = 16;++fn normalize_badge_count(count: Option<i64>) -> Option<i64> {+ count.filter(|n| (1..=MAX_BADGE_COUNT).contains(n))+}++fn normalize_badge_label(label: Option<&str>) -> Result<Option<String>, String> {+ let Some(label) = label.map(str::trim).filter(|label| !label.is_empty()) else {+ return Ok(None);+ };++ if label.chars().count() > MAX_BADGE_LABEL_CHARS {+ return Err(format!(+ "Badge label must be {MAX_BADGE_LABEL_CHARS} characters or fewer"+ ));+ }++ Ok(Some(label.to_string()))+}fn apply_badge(app: &AppHandle, count: Option<i64>) -> Result<(), String> {- let label = count.filter(|n| *n > 0).map(|n| n.to_string());+ let label = normalize_badge_count(count).map(|n| n.to_string());apply_badge_label(app, label.as_deref())}@@ -178,21 +198,24 @@ pub fn send_notification(app: AppHandle, params: NotificationParams) -> Result<(.icon(¶ms.icon).show().map_err(|e| format!("Failed to show notification: {}", e))?;-- let next = BADGE_COUNT.fetch_add(1, Ordering::SeqCst) + 1;- if let Err(error) = apply_badge(&app, Some(next)) {- eprintln!("[Pake] Failed to update dock badge: {error}");- }Ok(())}#[command]pub fn set_dock_badge(app: AppHandle, count: Option<i64>) -> Result<(), String> {- let normalized = count.filter(|n| *n > 0);+ let normalized = normalize_badge_count(count);BADGE_COUNT.store(normalized.unwrap_or(0), Ordering::SeqCst);apply_badge(&app, normalized)}+#[command]+pub fn increment_dock_badge(app: AppHandle) -> Result<(), String> {+ let current = BADGE_COUNT.load(Ordering::SeqCst);+ let next = current.saturating_add(1).clamp(1, MAX_BADGE_COUNT);+ BADGE_COUNT.store(next, Ordering::SeqCst);+ apply_badge(&app, Some(next))+}+#[command]pub fn clear_dock_badge(app: AppHandle) -> Result<(), String> {BADGE_COUNT.store(0, Ordering::SeqCst);@@ -202,7 +225,8 @@ pub fn clear_dock_badge(app: AppHandle) -> Result<(), String> {#[command]pub fn set_dock_badge_label(app: AppHandle, label: Option<String>) -> Result<(), String> {BADGE_COUNT.store(0, Ordering::SeqCst);- apply_badge_label(&app, label.as_deref().filter(|s| !s.is_empty()))+ let label = normalize_badge_label(label.as_deref())?;+ apply_badge_label(&app, label.as_deref())}#[command]diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.jsindex bd5bf88a..f3bb7cf9 100644--- a/src-tauri/src/inject/event.js+++ b/src-tauri/src/inject/event.js@@ -1042,15 +1042,29 @@ document.addEventListener("DOMContentLoaded", () => {let pageManagedBadge = false;let autoBadgeActive = false;+ const normalizeBadgeCount = (count) => {+ if (typeof count !== "number" || !Number.isFinite(count)) {+ throw new TypeError("Badge count must be a finite number.");+ }+ const normalized = Math.floor(count);+ return normalized > 0 ? Math.min(normalized, 99999) : null;+ };const setBadge = (count) => {pageManagedBadge = true;+ autoBadgeActive = false;return invoke("set_dock_badge", { count }).catch(() => {});};const clearBadge = () => invoke("clear_dock_badge").catch(() => {});const setLabel = (label) => {pageManagedBadge = true;+ autoBadgeActive = false;return invoke("set_dock_badge_label", { label }).catch(() => {});};+ const incrementAutoBadge = () => {+ if (pageManagedBadge) return Promise.resolve();+ autoBadgeActive = true;+ return invoke("increment_dock_badge").catch(() => {});+ };window.addEventListener("focus", () => {if (lastNotif?.onclick && Date.now() - lastNotifTime < 5000) {@@ -1084,11 +1098,11 @@ document.addEventListener("DOMContentLoaded", () => {lastNotifTime = Date.now();lastNotif = notif;- autoBadgeActive = true;-- invoke("send_notification", { params: { title, body, icon } }).then(() => {- if (notif.onshow) notif.onshow(new Event("show"));- });+ invoke("send_notification", { params: { title, body, icon } })+ .then(() => incrementAutoBadge())+ .then(() => {+ if (notif.onshow) notif.onshow(new Event("show"));+ });return notif;};@@ -1115,8 +1129,18 @@ document.addEventListener("DOMContentLoaded", () => {// shows the count (0 clears). clearAppBadge() removes the badge entirely.const setAppBadge = (count) => {if (count === undefined) return setLabel("•");- const n = typeof count === "number" && count > 0 ? Math.floor(count) : null;- return n === null ? clearBadge() : setBadge(n);+ let normalized;+ try {+ normalized = normalizeBadgeCount(count);+ } catch (error) {+ return Promise.reject(error);+ }+ if (normalized === null) {+ pageManagedBadge = false;+ autoBadgeActive = false;+ return clearBadge();+ }+ return setBadge(normalized);};const clearAppBadge = () => {pageManagedBadge = false;@@ -1135,33 +1159,6 @@ document.addEventListener("DOMContentLoaded", () => {value: clearAppBadge,});} catch (_) {}-- // Service worker notifications: forward to the same Rust command so badge- // bookkeeping stays consistent. Fall through to the original implementation- // (if any) so push subscriptions still work.- if (typeof ServiceWorkerRegistration !== "undefined") {- try {- const orig = ServiceWorkerRegistration.prototype.showNotification;- ServiceWorkerRegistration.prototype.showNotification = function (- title,- options,- ) {- const body = options?.body || "";- let icon = options?.icon || "";- if (icon.startsWith("/")) icon = window.location.origin + icon;- autoBadgeActive = true;- invoke("send_notification", { params: { title, body, icon } }).catch(- () => {},- );- if (orig) {- try {- return orig.call(this, title, options);- } catch (_) {}- }- return Promise.resolve();- };- } catch (_) {}- }})();function setDefaultZoom() {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 6fec4c0e..68b5a5ec 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -14,7 +14,8 @@ const WINDOW_SHOW_DELAY: u64 = 50;use app::{invoke::{clear_cache_and_restart, clear_dock_badge, download_file, download_file_by_binary,- send_notification, set_dock_badge, set_dock_badge_label, update_theme_mode,+ increment_dock_badge, send_notification, set_dock_badge, set_dock_badge_label,+ update_theme_mode,},setup::{set_global_shortcut, set_system_tray},window::{open_additional_window_safe, set_window, MultiWindowState},@@ -81,6 +82,7 @@ pub fn run_app() {download_file,download_file_by_binary,send_notification,+ increment_dock_badge,set_dock_badge,set_dock_badge_label,clear_dock_badge,diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.jsindex ff0fc31e..2172907a 100644--- a/tests/unit/event-link-guard.test.js+++ b/tests/unit/event-link-guard.test.js@@ -3,12 +3,18 @@ import path from "path";import { runInNewContext } from "node:vm";import { describe, expect, it } from "vitest";-function loadEventHelpers() {+function loadEventHelpers({ withTauri = false } = {}) {const source = fs.readFileSync(path.join(process.cwd(), "src-tauri/src/inject/event.js"),"utf-8",);+ const invokeCalls = [];+ const invoke = (command, payload) => {+ invokeCalls.push([command, payload]);+ return Promise.resolve();+ };+const context = {console,URL,@@ -28,12 +34,14 @@ function loadEventHelpers() {},location: {href: "https://example.com/app",+ origin: "https://example.com",reload: () => {},},localStorage: {getItem: () => null,setItem: () => {},},+ addEventListener: () => {},dispatchEvent: () => {},},document: {@@ -46,9 +54,13 @@ function loadEventHelpers() {execCommand: () => {},},};+ context.window.navigator = context.navigator;+ if (withTauri) {+ context.window.__TAURI__ = { core: { invoke } };+ }runInNewContext(source, context);- return context;+ return { ...context, invokeCalls };}describe("event link guard", () => {@@ -71,4 +83,40 @@ describe("event link guard", () => {false,);});++ it("bridges Web Badging API calls to explicit badge commands", async () => {+ const { navigator, invokeCalls } = loadEventHelpers({ withTauri: true });++ await navigator.setAppBadge(3.8);+ await navigator.setAppBadge();+ await navigator.setAppBadge(0);++ expect(invokeCalls).toEqual([+ ["set_dock_badge", { count: 3 }],+ ["set_dock_badge_label", { label: "•" }],+ ["clear_dock_badge", undefined],+ ]);+ });++ it("keeps notification display separate from badge increment", async () => {+ const { window, invokeCalls } = loadEventHelpers({ withTauri: true });++ new window.Notification("Hello", { body: "World", icon: "/icon.png" });+ await Promise.resolve();+ await Promise.resolve();++ expect(invokeCalls).toEqual([+ [+ "send_notification",+ {+ params: {+ title: "Hello",+ body: "World",+ icon: "https://example.com/icon.png",+ },+ },+ ],+ ["increment_dock_badge", undefined],+ ]);+ });});