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 passkey activation, extension popup close, shortcut guards, and remove obsolete hacks
Tw93d413602c056c
diff --git a/.gitattributes b/.gitattributesindex 388bde0e..54b3a29b 100644--- a/.gitattributes+++ b/.gitattributes@@ -10,7 +10,6 @@ node_modules/**/* linguist-vendored# Exclude build artifacts and config files/cli.js linguist-vendored/rollup.config.js linguist-vendored-/icns2png.py linguist-vendored*.json linguist-vendored# Exclude Tauri generated and vendor codediff --git a/bin/builders/BaseBuilder.ts b/bin/builders/BaseBuilder.tsindex 26c3e49c..538429ed 100644--- a/bin/builders/BaseBuilder.ts+++ b/bin/builders/BaseBuilder.ts@@ -1,3 +1,4 @@+import os from 'os';import path from 'path';import fsExtra from 'fs-extra';import chalk from 'chalk';@@ -97,7 +98,7 @@ export default abstract class BaseBuilder {const stat = await fsExtra.stat(artifactPath);let sizeBytes = stat.size;if (stat.isDirectory()) {- sizeBytes = await BaseBuilder.getPathSize(artifactPath);+ sizeBytes = await this.getPathSize(artifactPath);}this.artifacts.push({path: path.resolve(artifactPath),@@ -114,14 +115,14 @@ export default abstract class BaseBuilder {}}- private static async getPathSize(directory: string): Promise<number> {+ protected async getPathSize(directory: string): Promise<number> {let size = 0;for (const entry of await fsExtra.readdir(directory, {withFileTypes: true,})) {const entryPath = path.join(directory, entry.name);if (entry.isDirectory()) {- size += await BaseBuilder.getPathSize(entryPath);+ size += await this.getPathSize(entryPath);} else if (entry.isFile()) {size += (await fsExtra.stat(entryPath)).size;}@@ -540,11 +541,10 @@ export default abstract class BaseBuilder {protected getMacOSMajorVersion(): number {try {- const os = require('os');const release = os.release();const majorVersion = parseInt(release.split('.')[0], 10);- return majorVersion;- } catch (error) {+ return Number.isNaN(majorVersion) ? 0 : majorVersion;+ } catch {return 0; // Disable proxy feature if version detection fails}}diff --git a/bin/builders/LinuxBuilder.ts b/bin/builders/LinuxBuilder.tsindex 1ddd6583..16b81ead 100644--- a/bin/builders/LinuxBuilder.ts+++ b/bin/builders/LinuxBuilder.ts@@ -188,7 +188,7 @@ export default class LinuxBuilder extends BaseBuilder {executable: 'tar',args: ['-xf', path.join(controlDir, dataArchive), '-C', dataDir],});- const installedSize = await this.getDirectorySize(dataDir);+ const installedSize = await this.getPathSize(dataDir);const pkgInfo = `pkgname = ${packageName}pkgbase = ${packageName}pkgver = ${version}-1@@ -252,21 +252,6 @@ post_remove() {}}- private async getDirectorySize(directory: string): Promise<number> {- let size = 0;- for (const entry of await fsExtra.readdir(directory, {- withFileTypes: true,- })) {- const entryPath = path.join(directory, entry.name);- if (entry.isDirectory()) {- size += await this.getDirectorySize(entryPath);- } else if (entry.isFile()) {- size += (await fsExtra.stat(entryPath)).size;- }- }- return size;- }-// Override buildAndCopy to ensure currentBuildType is synced if called directly, though the loop above handles it most of the time.async buildAndCopy(url: string, target: string, logSuccess = true) {this.currentBuildType = target;diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.tsindex 9df50008..ef04c8c6 100644--- a/bin/helpers/merge.ts+++ b/bin/helpers/merge.ts@@ -4,7 +4,6 @@ import fsExtra from 'fs-extra';import combineFiles from '@/utils/combine';import logger from '@/options/logger';import {- generateSafeFilename,generateIdentifierSafeName,getSafeAppName,generateLinuxPackageName,@@ -615,7 +614,6 @@ export async function mergeConfig(identifier,name = 'pake-app',installerLanguage,- wasm,camera,microphone,} = options;diff --git a/bin/helpers/tauriConfig.ts b/bin/helpers/tauriConfig.tsindex c083f512..9c1fce62 100644--- a/bin/helpers/tauriConfig.ts+++ b/bin/helpers/tauriConfig.ts@@ -33,9 +33,6 @@ let tauriConfig = {bundle: platformConfig.bundle,app: {...CommonConf.app,- trayIcon: {- ...(platformConfig?.app?.trayIcon ?? {}),- },},build: CommonConf.build,pake: pakeConf,diff --git a/bin/options/icon.ts b/bin/options/icon.tsindex fcf2ba30..2771ecf0 100644--- a/bin/options/icon.ts+++ b/bin/options/icon.ts@@ -517,21 +517,20 @@ export async function handleIcon(* Generates icon service URLs for a domain*/function generateIconServiceUrls(domain: string): string[] {- const logoDevUrls = API_KEYS.logoDev+ const logoDevUrls = [...API_KEYS.logoDev].sort(() => Math.random() - 0.5).map((token) =>`https://img.logo.dev/${domain}?token=${token}&format=png&size=256`,);- const brandfetchUrls = API_KEYS.brandfetch+ const brandfetchUrls = [...API_KEYS.brandfetch].sort(() => Math.random() - 0.5).map((key) => `https://cdn.brandfetch.io/${domain}/w/400/h/400?c=${key}`);return [...logoDevUrls,...brandfetchUrls,- `https://logo.clearbit.com/${domain}?size=256`,`https://www.google.com/s2/favicons?domain=${domain}&sz=256`,`https://favicon.is/${domain}`,`https://${domain}/favicon.ico`,diff --git a/dist/cli.js b/dist/cli.jsindex 256be233..5711a0c8 100644--- a/dist/cli.js+++ b/dist/cli.js@@ -3,9 +3,9 @@ import log from 'loglevel';import chalk from 'chalk';import updateNotifier from 'update-notifier';import path from 'path';+import os from 'os';import fsExtra from 'fs-extra';import prompts from 'prompts';-import os from 'os';import { execa, execaSync } from 'execa';import crypto from 'crypto';import ora from 'ora';@@ -77,7 +77,6 @@ var type = "module";var exports$1 = "./dist/cli.js";var license = "GPL-3.0-or-later";var dependencies = {- "@tauri-apps/api": "~2.12.5","@tauri-apps/cli": "^2.12.6",chalk: "^6.0.1",commander: "^15.1.0",@@ -1730,7 +1729,7 @@ async function writeAllConfigs(tauriConf, platform) {}async function mergeConfig(url, options, tauriConf) {await copyTemplateConfigs();- const { appVersion, userAgent, showSystemTray, useLocalFile, identifier, name = 'pake-app', installerLanguage, wasm, camera, microphone, } = options;+ const { appVersion, userAgent, showSystemTray, useLocalFile, identifier, name = 'pake-app', installerLanguage, camera, microphone, } = options;const platform = asSupportedPlatform(process.platform);if (options.hideTitleBar && platform !== 'darwin') {logger.warn('✼ --hide-title-bar is only supported on macOS and will be ignored on this platform.');@@ -1807,9 +1806,6 @@ let tauriConfig = {bundle: platformConfig.bundle,app: {...CommonConf.app,- trayIcon: {- ...(platformConfig?.app?.trayIcon ?? {}),- },},build: CommonConf.build,pake: pakeConf,@@ -2057,7 +2053,7 @@ class BaseBuilder {const stat = await fsExtra.stat(artifactPath);let sizeBytes = stat.size;if (stat.isDirectory()) {- sizeBytes = await BaseBuilder.getPathSize(artifactPath);+ sizeBytes = await this.getPathSize(artifactPath);}this.artifacts.push({path: path.resolve(artifactPath),@@ -2074,14 +2070,14 @@ class BaseBuilder {});}}- static async getPathSize(directory) {+ async getPathSize(directory) {let size = 0;for (const entry of await fsExtra.readdir(directory, {withFileTypes: true,})) {const entryPath = path.join(directory, entry.name);if (entry.isDirectory()) {- size += await BaseBuilder.getPathSize(entryPath);+ size += await this.getPathSize(entryPath);}else if (entry.isFile()) {size += (await fsExtra.stat(entryPath)).size;@@ -2370,12 +2366,11 @@ class BaseBuilder {}getMacOSMajorVersion() {try {- const os = require('os');const release = os.release();const majorVersion = parseInt(release.split('.')[0], 10);- return majorVersion;+ return Number.isNaN(majorVersion) ? 0 : majorVersion;}- catch (error) {+ catch {return 0; // Disable proxy feature if version detection fails}}@@ -2799,7 +2794,7 @@ class LinuxBuilder extends BaseBuilder {executable: 'tar',args: ['-xf', path.join(controlDir, dataArchive), '-C', dataDir],});- const installedSize = await this.getDirectorySize(dataDir);+ const installedSize = await this.getPathSize(dataDir);const pkgInfo = `pkgname = ${packageName}pkgbase = ${packageName}pkgver = ${version}-1@@ -2860,21 +2855,6 @@ post_remove() {await fsExtra.remove(workDir);}}- async getDirectorySize(directory) {- let size = 0;- for (const entry of await fsExtra.readdir(directory, {- withFileTypes: true,- })) {- const entryPath = path.join(directory, entry.name);- if (entry.isDirectory()) {- size += await this.getDirectorySize(entryPath);- }- else if (entry.isFile()) {- size += (await fsExtra.stat(entryPath)).size;- }- }- return size;- }// Override buildAndCopy to ensure currentBuildType is synced if called directly, though the loop above handles it most of the time.async buildAndCopy(url, target, logSuccess = true) {this.currentBuildType = target;@@ -3650,16 +3630,15 @@ async function handleIcon(options, url) {* Generates icon service URLs for a domain*/function generateIconServiceUrls(domain) {- const logoDevUrls = API_KEYS.logoDev+ const logoDevUrls = [...API_KEYS.logoDev].sort(() => Math.random() - 0.5).map((token) => `https://img.logo.dev/${domain}?token=${token}&format=png&size=256`);- const brandfetchUrls = API_KEYS.brandfetch+ const brandfetchUrls = [...API_KEYS.brandfetch].sort(() => Math.random() - 0.5).map((key) => `https://cdn.brandfetch.io/${domain}/w/400/h/400?c=${key}`);return [...logoDevUrls,...brandfetchUrls,- `https://logo.clearbit.com/${domain}?size=256`,`https://www.google.com/s2/favicons?domain=${domain}&sz=256`,`https://favicon.is/${domain}`,`https://${domain}/favicon.ico`,diff --git a/icns2png.py b/icns2png.pydeleted file mode 100644index 6c749fa9..00000000--- a/icns2png.py+++ /dev/null@@ -1,35 +0,0 @@-"""-批量将icns文件转成png文件-Batch convert ICNS files to PNG files-"""-import os--try:- from PIL import Image-except ImportError:- os.system("pip install Pillow")- from PIL import Image--if __name__ == "__main__":- now_dir = os.path.dirname(os.path.abspath(__file__))- icons_dir = os.path.join(now_dir, "src-tauri", "icons")- png_dir = os.path.join(now_dir, "src-tauri", "png")- if not os.path.exists(png_dir):- os.mkdir(png_dir)- file_list = os.listdir(icons_dir)- file_list = [file for file in file_list if file.endswith(".icns")]- for file in file_list:- icns_path = os.path.join(icons_dir, file)- image = Image.open(icns_path)- image_512 = image.copy().resize((512, 512))- image_256 = image.copy().resize((256, 256))- image_32 = image.copy().resize((32, 32))- image_name = os.path.splitext(file)[0]- image_512_path = os.path.join(png_dir, image_name + "_512.png")- image_256_path = os.path.join(png_dir, image_name + "_256.ico")- image_32_path = os.path.join(png_dir, image_name + "_32.ico")- image_512.save(image_512_path, "PNG")- image_256.save(image_256_path, "ICO")- image_32.save(image_32_path, "ICO")- print("png file write success.")- print(f"There are {len(os.listdir(png_dir))} png picture in ", png_dir)diff --git a/package.json b/package.jsonindex 279173cb..c74f9055 100644--- a/package.json+++ b/package.json@@ -58,7 +58,6 @@"exports": "./dist/cli.js","license": "GPL-3.0-or-later","dependencies": {- "@tauri-apps/api": "~2.12.5","@tauri-apps/cli": "^2.12.6","chalk": "^6.0.1","commander": "^15.1.0",diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 5a1e8458..70aa3a03 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2853,16 +2853,6 @@ dependencies = ["pin-project-lite",]-[[package]]-name = "os_pipe"-version = "1.2.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"-dependencies = [- "libc",- "windows-sys 0.45.0",-]-[[package]]name = "pake"version = "3.21.0"@@ -2888,7 +2878,6 @@ dependencies = ["tauri-plugin-http","tauri-plugin-notification","tauri-plugin-opener",- "tauri-plugin-shell","tauri-plugin-single-instance","tauri-plugin-window-state","tokio",@@ -3932,16 +3921,6 @@ dependencies = ["digest 0.11.3",]-[[package]]-name = "shared_child"-version = "1.1.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "607549934f6cc26b89cfecfdc46fa90f1e5d1536a68349b0c3a4f9d1c0d37959"-dependencies = [- "libc",- "windows-sys 0.61.2",-]-[[package]]name = "shlex"version = "2.0.1"@@ -4510,29 +4489,6 @@ dependencies = ["zbus 5.19.0",]-[[package]]-name = "tauri-plugin-shell"-version = "2.6.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7375b25f72f70f6168f27f1ba3a413e30eaa0a2098cff53a4046ebfe9e2f142d"-dependencies = [- "encoding_rs",- "libc",- "log",- "open",- "os_pipe",- "regex",- "schemars 0.8.22",- "serde",- "serde_json",- "shared_child",- "tauri",- "tauri-plugin",- "thiserror 2.0.21",- "tokio",- "windows-sys 0.60.2",-]-[[package]]name = "tauri-plugin-single-instance"version = "2.5.5"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 7b39e769..6e5d20ee 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -41,7 +41,6 @@ tauri = { version = "2.12.7", features = [tauri-plugin-window-state = "2.5.0"tauri-plugin-http = { version = "2.9.0", features = ["socks"] }tauri-plugin-global-shortcut = { version = "2.4.1" }-tauri-plugin-shell = { version = "2.6.0" }tauri-plugin-opener = { version = "2.7.3" }tauri-plugin-single-instance = "2.5.5"tauri-plugin-notification = "2.8.1"diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 7c8088f5..c2c279b4 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -17,7 +17,8 @@"allow-set-title-bar-color","allow-quit-app","allow-reveal-download",- "shell:allow-open",+ "opener:allow-open-url",+ "opener:allow-default-urls","core:window:allow-theme","core:window:allow-start-dragging","core:window:allow-toggle-maximize",@@ -29,12 +30,6 @@"core:window:allow-close","core:webview:allow-internal-toggle-devtools","core:webview:allow-print",- "notification:allow-is-permission-granted",- "notification:allow-notify",- "notification:allow-get-active",- "notification:allow-register-listener",- "notification:allow-register-action-types",- "notification:default",- "core:path:default"+ "notification:default"]}diff --git a/src-tauri/icons/wechat.icns b/src-tauri/icons/wechat.icnsdeleted file mode 100644index 28d39454..00000000Binary files a/src-tauri/icons/wechat.icns and /dev/null differdiff --git a/src-tauri/png/wechat_256.ico b/src-tauri/png/wechat_256.icodeleted file mode 100644index a3d2fecf..00000000Binary files a/src-tauri/png/wechat_256.ico and /dev/null differdiff --git a/src-tauri/png/wechat_32.ico b/src-tauri/png/wechat_32.icodeleted file mode 100644index b31867f0..00000000Binary files a/src-tauri/png/wechat_32.ico and /dev/null differdiff --git a/src-tauri/png/wechat_512.png b/src-tauri/png/wechat_512.pngdeleted file mode 100644index 550d5a87..00000000Binary files a/src-tauri/png/wechat_512.png and /dev/null differdiff --git a/src-tauri/src/app/config.rs b/src-tauri/src/app/config.rsindex 487abef7..6df0b10a 100644--- a/src-tauri/src/app/config.rs+++ b/src-tauri/src/app/config.rs@@ -411,6 +411,7 @@ mod tests {"send_notification","close_notification","set_zoom",+ "plugin:opener|open_url","plugin:window|is_fullscreen",] {for label in ["pake", "pake-1"] {@@ -580,5 +581,18 @@ mod tests {"pake",Some("https://example.com/")));+ for forbidden in [+ "plugin:opener|open_path",+ "plugin:opener|reveal_item_in_dir",+ ] {+ assert!(+ !allows(&acl, forbidden, "pake", None),+ "unexpected local permission for {forbidden}"+ );+ assert!(+ !allows(&acl, forbidden, "pake", Some("https://example.com/")),+ "unexpected remote permission for {forbidden}"+ );+ }}}diff --git a/src-tauri/src/app/extensions/macos.rs b/src-tauri/src/app/extensions/macos.rsindex 6ffc3187..51c4c833 100644--- a/src-tauri/src/app/extensions/macos.rs+++ b/src-tauri/src/app/extensions/macos.rs@@ -42,6 +42,8 @@ struct Host {store: Retained<WKWebsiteDataStore>,// The controller holds its delegate weakly._delegate: Retained<HostDelegate>,+ // Each extension popup webview holds its UI delegate weakly.+ page_ui_delegate: Retained<ExtensionPageUIDelegate>,pending: usize,opened: bool,callbacks: Vec<Callback>,@@ -343,6 +345,37 @@ impl HostDelegate {}}+define_class!(+ // SAFETY: NSObject has no subclassing requirements and ExtensionPageUIDelegate has no Drop.+ #[unsafe(super(NSObject))]+ #[thread_kind = MainThreadOnly]+ #[name = "PakeExtensionPageUIDelegate"]+ struct ExtensionPageUIDelegate;++ unsafe impl NSObjectProtocol for ExtensionPageUIDelegate {}++ impl ExtensionPageUIDelegate {+ // Extension popups (e.g. a Done button) call `window.close()`; without a+ // UIDelegate implementing `webViewDidClose:`, WebKit ignores it.+ #[unsafe(method(webViewDidClose:))]+ fn did_close(&self, webview: &AnyObject) {+ unsafe {+ let window: *mut AnyObject = msg_send![webview, window];+ if !window.is_null() {+ let _: () = msg_send![window, close];+ }+ }+ }+ }+);++impl ExtensionPageUIDelegate {+ fn new(mtm: MainThreadMarker) -> Retained<Self> {+ let this = Self::alloc(mtm).set_ivars(());+ unsafe { msg_send![super(this), init] }+ }+}+/// A webview configuration that carries the extension controller, or `None`/// where WebKit has none (before macOS 15.4) or nothing is installed.///@@ -400,6 +433,7 @@ fn start(mtm: MainThreadMarker, directory: &Path, incognito: bool) -> Option<Hos};let window = HostWindow::new(mtm);let delegate = HostDelegate::new(mtm, window.clone());+ let page_ui_delegate = ExtensionPageUIDelegate::new(mtm);unsafe { controller.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) };for folder in &folders {@@ -428,6 +462,7 @@ fn start(mtm: MainThreadMarker, directory: &Path, incognito: bool) -> Option<Hoswindow,store,_delegate: delegate,+ page_ui_delegate,pending: folders.len(),opened: false,callbacks: Vec::new(),@@ -804,6 +839,7 @@ fn show_page(id: &str, page: Option<&str>) {let webview: Allocated<AnyObject> = msg_send![class!(WKWebView), alloc];let webview: Retained<AnyObject> =msg_send![webview, initWithFrame: frame, configuration: &*configuration];+ let _: () = msg_send![&*webview, setUIDelegate: &*host.page_ui_delegate];// Titled, closable, miniaturizable, resizable; buffered backing.let window: Allocated<AnyObject> = msg_send![class!(NSWindow), alloc];let window: Retained<AnyObject> = msg_send![diff --git a/src-tauri/src/app/invoke.rs b/src-tauri/src/app/invoke.rsindex 40198b6e..60afa364 100644--- a/src-tauri/src/app/invoke.rs+++ b/src-tauri/src/app/invoke.rs@@ -1372,15 +1372,34 @@ pub fn set_dock_badge_label(app: AppHandle, label: Option<String>) -> Result<(),}}+fn parse_theme_mode(mode: &str) -> Option<Option<Theme>> {+ match mode {+ "dark" => Some(Some(Theme::Dark)),+ "light" => Some(Some(Theme::Light)),+ "system" => Some(None),+ _ => None,+ }+}+#[command]pub async fn update_theme_mode(app: AppHandle, mode: String) {- let theme = if mode == "dark" {- Theme::Dark- } else {- Theme::Light+ if app+ .try_state::<crate::app::window::MultiWindowState>()+ .is_some_and(|state| {+ state+ .pake_config+ .windows+ .first()+ .is_some_and(|window| window.dark_mode)+ })+ {+ return;+ }+ let Some(theme) = parse_theme_mode(&mode) else {+ return;};for window in app.webview_windows().values() {- let _ = window.set_theme(Some(theme));+ let _ = window.set_theme(theme);}}@@ -2190,4 +2209,13 @@ mod tests {assert!(red_pixels > 200, "missing red badge pixels for {sample}");}}++ #[test]+ fn theme_mode_parser_maps_dark_light_system_and_rejects_unknown_values() {+ assert_eq!(parse_theme_mode("dark"), Some(Some(Theme::Dark)));+ assert_eq!(parse_theme_mode("light"), Some(Some(Theme::Light)));+ assert_eq!(parse_theme_mode("system"), Some(None));+ assert_eq!(parse_theme_mode(""), None);+ assert_eq!(parse_theme_mode("auto"), None);+ }}diff --git a/src-tauri/src/app/passkey/macos.rs b/src-tauri/src/app/passkey/macos.rsindex 01e4a9ff..68175f00 100644--- a/src-tauri/src/app/passkey/macos.rs+++ b/src-tauri/src/app/passkey/macos.rs@@ -17,8 +17,8 @@use super::{assertion_message, existing_text, failure_reply, finish_create, finish_get, missing_text,- picker_labels, picker_text, plan_create, plan_get, prompt_reason, resolve_rp_id, Envelope,- Failure, Origin, Request, Store, HANDLER_NAME,+ picker_labels, picker_text, plan_create, plan_get, prompt_reason, resolve_rp_id,+ should_show_missing_notice, Envelope, Failure, Origin, Request, Store, HANDLER_NAME,};use crate::util::UiLanguage;use block2::{DynBlock, RcBlock};@@ -29,6 +29,7 @@ use objc2_app_kit::{NSAlert, NSAlertFirstButtonReturn, NSAlertSecondButtonReturnuse objc2_foundation::{NSData, NSPoint, NSRect, NSSize, NSString};use objc2_web_kit::{WKScriptMessage, WKScriptMessageHandlerWithReply, WKUserContentController};use std::cell::{Cell, RefCell};+use std::collections::HashSet;use std::ffi::c_void;use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicU64, Ordering};@@ -338,6 +339,7 @@ struct Ceremony {thread_local! {static CURRENT: RefCell<Option<Ceremony>> = const { RefCell::new(None) };+ static NOTICED_MISSING: RefCell<HashSet<String>> = RefCell::new(HashSet::new());}/// Update the running ceremony, only if it is still the one holding `token`.@@ -592,8 +594,12 @@ fn create(store_path: PathBuf,origin: Origin,options: super::CreateOptions,+ user_active: bool,reply: Reply,) {+ if !user_active {+ return reply.fail(Failure::NotAllowed);+ }let Ok(store) = load(&store_path) else {return reply.fail(Failure::NotAllowed);};@@ -649,7 +655,11 @@ fn create(let Ok(mut store) = load(&store_path) else {return reply.fail(Failure::NotAllowed);};+ let rp_id = passkey.rp_id.clone();store.upsert(passkey);+ NOTICED_MISSING.with(|noticed| {+ noticed.borrow_mut().remove(&rp_id);+ });match save(&store_path, &store) {Ok(()) => reply.send(answer),Err(error) => {@@ -693,8 +703,12 @@ fn get(store_path: PathBuf,origin: Origin,options: super::GetOptions,+ user_active: bool,reply: Reply,) {+ if !user_active {+ return reply.fail(Failure::NotAllowed);+ }// An unreadable store is left as it is (load logged it): saying there is// no passkey would send the user to add one, which create then refuses.let Ok(store) = load(&store_path) else {@@ -706,6 +720,12 @@ fn get(};match plan.candidates.len() {0 => {+ let show_notice = NOTICED_MISSING.with(|noticed| {+ should_show_missing_notice(&plan.rp_id, user_active, &mut noticed.borrow_mut())+ });+ if !show_notice {+ return reply.fail(Failure::NotAllowed);+ }let (title, line, button) = missing_text(&plan.rp_id, UiLanguage::system());notice(mtm,@@ -839,8 +859,14 @@ fn receive(})});match request {- Request::Create { options } => create(mtm, window, store_path, origin, options, reply),- Request::Get { options } => get(mtm, window, store_path, origin, options, reply),+ Request::Create {+ options,+ user_active,+ } => create(mtm, window, store_path, origin, options, user_active, reply),+ Request::Get {+ options,+ user_active,+ } => get(mtm, window, store_path, origin, options, user_active, reply),Request::Available | Request::Cancel => {}}}diff --git a/src-tauri/src/app/passkey/mod.rs b/src-tauri/src/app/passkey/mod.rsindex 59768f40..793a2d19 100644--- a/src-tauri/src/app/passkey/mod.rs+++ b/src-tauri/src/app/passkey/mod.rs@@ -262,6 +262,28 @@ pub struct Envelope {pub request: Request,}+fn default_true() -> bool {+ true+}++/// Whether a sign-in request with no saved passkey should raise the modal notice+/// explaining that iCloud Keychain passkeys cannot be used here.+///+/// Unprompted requests (page-load probes or background retries without active user+/// activation) stay silent so sites like x.com never pop up a sheet unasked; even+/// on a user click, each relying party is noticed at most once per session so a+/// site that retries after `NotAllowedError` cannot spam sheets.+pub fn should_show_missing_notice(+ rp_id: &str,+ user_active: bool,+ noticed: &mut std::collections::HashSet<String>,+) -> bool {+ if !user_active {+ return false;+ }+ noticed.insert(rp_id.to_owned())+}+/// What the page asked, as `passkey.js` posts it: WebAuthn's options with every buffer in base64url.#[derive(Debug, Deserialize)]#[serde(tag = "kind", rename_all = "lowercase")]@@ -271,10 +293,14 @@ pub enum Request {Create {#[serde(rename = "publicKey")]options: CreateOptions,+ #[serde(default = "default_true", rename = "userActive")]+ user_active: bool,},Get {#[serde(rename = "publicKey")]options: GetOptions,+ #[serde(default = "default_true", rename = "userActive")]+ user_active: bool,},}@@ -788,7 +814,7 @@ mod tests {fn create_request(json: serde_json::Value) -> CreateOptions {match serde_json::from_value::<Request>(json).unwrap() {- Request::Create { options } => options,+ Request::Create { options, .. } => options,other => panic!("{other:?}"),}}@@ -923,7 +949,7 @@ mod tests {fn get_request(json: serde_json::Value) -> GetOptions {match serde_json::from_value::<Request>(json).unwrap() {- Request::Get { options } => options,+ Request::Get { options, .. } => options,other => panic!("{other:?}"),}}@@ -1030,4 +1056,90 @@ mod tests {assert!(!enabled(true, false));assert!(!enabled(false, true));}++ #[test]+ fn missing_passkey_notice_requires_user_activation_and_shows_once_per_rp() {+ let mut noticed = std::collections::HashSet::new();+ // Background page-load probes never raise a modal and do not consume the notice.+ assert!(!should_show_missing_notice("x.com", false, &mut noticed));+ assert!(!should_show_missing_notice("x.com", false, &mut noticed));+ assert!(noticed.is_empty());++ // The first user-initiated request explains the iCloud Keychain limit once.+ assert!(should_show_missing_notice("x.com", true, &mut noticed));+ // Automatic retries within the same session stay silent.+ assert!(!should_show_missing_notice("x.com", true, &mut noticed));+ // A different relying party still gets its one-time notice.+ assert!(should_show_missing_notice("github.com", true, &mut noticed));+ }++ #[test]+ fn get_request_reads_user_active_and_defaults_to_true() {+ let passive: Envelope = serde_json::from_value(serde_json::json!({+ "kind": "get",+ "id": 9,+ "userActive": false,+ "publicKey": { "challenge": "AQ" }+ }))+ .unwrap();+ assert!(matches!(+ passive.request,+ Request::Get {+ user_active: false,+ ..+ }+ ));++ let omitted: Envelope = serde_json::from_value(serde_json::json!({+ "kind": "get",+ "id": 10,+ "publicKey": { "challenge": "AQ" }+ }))+ .unwrap();+ assert!(matches!(+ omitted.request,+ Request::Get {+ user_active: true,+ ..+ }+ ));+ }++ #[test]+ fn create_request_reads_user_active_and_defaults_to_true() {+ let mut passive = sample_create();+ passive["id"] = serde_json::json!(11);+ passive["userActive"] = serde_json::json!(false);+ let passive: Envelope = serde_json::from_value(passive).unwrap();+ assert!(matches!(+ passive.request,+ Request::Create {+ user_active: false,+ ..+ }+ ));++ let mut active = sample_create();+ active["id"] = serde_json::json!(12);+ active["userActive"] = serde_json::json!(true);+ let active: Envelope = serde_json::from_value(active).unwrap();+ assert!(matches!(+ active.request,+ Request::Create {+ user_active: true,+ ..+ }+ ));++ let mut omitted = sample_create();+ omitted["id"] = serde_json::json!(13);+ let omitted: Envelope = serde_json::from_value(omitted).unwrap();+ assert!(matches!(+ omitted.request,+ Request::Create {+ user_active: true,+ ..+ }+ ));+ }}diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex 427b04ca..726710df 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -1070,8 +1070,12 @@ fn build_window(window_builder = window_builder.initialization_script(include_str!("../inject/event.js"))- .initialization_script(include_str!("../inject/style.js"))- .initialization_script(include_str!("../inject/theme_refresh.js"));+ .initialization_script(include_str!("../inject/style.js"));++ if !window_config.dark_mode {+ window_builder =+ window_builder.initialization_script(include_str!("../inject/theme_refresh.js"));+ }#[cfg(target_os = "macos")]if window_config.title_bar_follows_page() {@@ -1527,9 +1531,10 @@ fn build_window(// WebView2 raises WindowCloseRequested for the same call, and Wry answers// by destroying the web view's own container, which left the popup's frame- // on screen with nothing in it (measured in a Windows 11 VM).+ // on screen with nothing in it (measured in a Windows 11 VM). Extension+ // settings windows (e.g. a popup's Done button) close the same way.#[cfg(target_os = "windows")]- if page_popup {+ if page_popup || label == "extension-settings" {let popup = window.clone();if let Err(error) = window.with_webview(move |webview| {use webview2_com::WindowCloseRequestedEventHandler;diff --git a/src-tauri/src/inject/bridge.js b/src-tauri/src/inject/bridge.jsindex 1b385937..1f822e1c 100644--- a/src-tauri/src/inject/bridge.js+++ b/src-tauri/src/inject/bridge.js@@ -51,8 +51,8 @@core: Object.freeze({ invoke }),window: Object.freeze({ getCurrentWindow: () => currentWindow }),shell: Object.freeze({- open: (path, openWith) =>- invoke("plugin:shell|open", { path, with: openWith }),+ open: (url, openWith) =>+ invoke("plugin:opener|open_url", { url, with: openWith }),}),}),});diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.jsindex 5b4aa766..b4d42272 100644--- a/src-tauri/src/inject/event.js+++ b/src-tauri/src/inject/event.js@@ -68,11 +68,16 @@ function setZoom(zoom) {invoke("set_zoom", { percent: zoomPercent }).catch(() => {});}- window.localStorage.setItem("htmlZoom", normalizedZoom);+ try {+ window.localStorage.setItem("htmlZoom", normalizedZoom);+ } catch {}}function zoomCommon(zoomChange) {- const currentZoom = window.localStorage.getItem("htmlZoom") || "100%";+ let currentZoom = "100%";+ try {+ currentZoom = window.localStorage.getItem("htmlZoom") || "100%";+ } catch {}setZoom(zoomChange(normalizeZoomPercent(currentZoom)));}@@ -192,8 +197,23 @@ function handleWindowShortcut(event) {action();}+const EDITABLE_SKIPPED_SHORTCUTS = new Set(["ArrowUp", "ArrowDown", "[", "]"]);+function handleWebShortcut(event) {- if (isNonMacDesktop() && event.ctrlKey) {+ if (event.defaultPrevented || event.altKey) {+ return;+ }+ if (event.shiftKey && event.key !== "+") {+ return;+ }+ if (+ EDITABLE_SKIPPED_SHORTCUTS.has(event.key) &&+ isEditableElement(document.activeElement)+ ) {+ return;+ }++ if (isNonMacDesktop() && event.ctrlKey && !event.metaKey) {handleShortcut(event);return;}@@ -201,7 +221,7 @@ function handleWebShortcut(event) {const isMac = /mac/i.test(getDesktopPlatform());const isMacScrollShortcut =event.key === "ArrowUp" || event.key === "ArrowDown";- if (isMac && event.metaKey && isMacScrollShortcut) {+ if (isMac && event.metaKey && !event.ctrlKey && isMacScrollShortcut) {handleShortcut(event);}}@@ -561,12 +581,12 @@ const PREVIEWABLE_MEDIA_EXTENSIONS = ["m4a",];-// Path fragments that often host real file downloads. Keep this list narrow:-// SPA roots such as "/assets/", "/dist/", "/files/", "/releases/", and-// "/attachments/" have already been mistaken for downloads in the wild.-// Prefer real file extensions, the download attribute, or ?download /-// ?attachment query hints whenever possible.-const DOWNLOAD_PATH_PATTERNS = ["/download/"];+// Path fragments that often host real file downloads. Keep this list empty:+// SPA routes such as "/assets/", "/dist/", "/files/", "/releases/",+// "/attachments/", and "/download/" (e.g. "/download/mac") have been mistaken+// for downloads in the wild. Real downloads still match via the download+// attribute, ?download / ?attachment query hints, or file extensions.+const DOWNLOAD_PATH_PATTERNS = [];// Language detection utilitiesfunction getUserLanguage() {@@ -583,20 +603,15 @@ function isChineseLanguage(language = getUserLanguage()) {);}-// User notification helper+// User notification helper. Rust download_file already shows an in-page toast+// on failure via show_toast, so avoid raising a second Web Notification (which+// would also increment the Dock unread badge).function showDownloadError(filename) {const isChinese = isChineseLanguage();const message = isChinese? `下载失败: ${filename}`: `Download failed: ${filename}`;-- if (window.Notification && Notification.permission === "granted") {- new Notification(isChinese ? "下载错误" : "Download Error", {- body: message,- });- } else {- console.error(message);- }+ console.error(message);}function getExtension(url) {@@ -826,7 +841,7 @@ document.addEventListener("DOMContentLoaded", () => {handleWindowFullscreenShortcut,true,);- document.addEventListener("keyup", handleWebShortcut);+ document.addEventListener("keydown", handleWebShortcut);window.addEventListener("keydown", handleWindowShortcut);}}@@ -876,10 +891,10 @@ document.addEventListener("DOMContentLoaded", () => {return;}- invoke("plugin:shell|open", {- path: url,+ invoke("plugin:opener|open_url", {+ url,}).catch((error) => {- console.error("Failed to open URL with shell:", url, error);+ console.error("Failed to open URL with opener:", url, error);});};@@ -1074,7 +1089,12 @@ document.addEventListener("DOMContentLoaded", () => {}const target = anchorElement.target;- const hrefUrl = new URL(anchorElement.href);+ let hrefUrl;+ try {+ hrefUrl = new URL(anchorElement.href);+ } catch {+ return;+ }if (["mailto:", "tel:"].includes(hrefUrl.protocol)) return;const absoluteUrl = hrefUrl.href;let filename = anchorElement.download || getFilenameFromUrl(absoluteUrl);@@ -1627,7 +1647,10 @@ document.addEventListener("DOMContentLoaded", () => {})();function setDefaultZoom() {- const htmlZoom = window.localStorage.getItem("htmlZoom");+ let htmlZoom = null;+ try {+ htmlZoom = window.localStorage.getItem("htmlZoom");+ } catch {}if (htmlZoom) {setZoom(htmlZoom);} else if (window.pakeConfig?.zoom && window.pakeConfig.zoom !== 100) {diff --git a/src-tauri/src/inject/passkey.js b/src-tauri/src/inject/passkey.jsindex 70ebcff3..87ae4a8c 100644--- a/src-tauri/src/inject/passkey.js+++ b/src-tauri/src/inject/passkey.js@@ -70,11 +70,17 @@id: toBase64Url(descriptor.id),}));+ const isUserActive = () => {+ const activation = window.navigator && window.navigator.userActivation;+ return activation ? Boolean(activation.isActive) : true;+ };+const createRequest = (options) => {const selection = options.authenticatorSelection;const extensions = options.extensions;return {kind: "create",+ userActive: isUserActive(),publicKey: {challenge: toBase64Url(options.challenge),rp: { id: options.rp && options.rp.id },@@ -103,6 +109,7 @@const getRequest = (options) => ({kind: "get",+ userActive: isUserActive(),publicKey: {challenge: toBase64Url(options.challenge),rpId: options.rpId,diff --git a/src-tauri/src/inject/style.js b/src-tauri/src/inject/style.jsindex 54179a9f..3d5d1aba 100644--- a/src-tauri/src/inject/style.js+++ b/src-tauri/src/inject/style.js@@ -43,186 +43,14 @@}`,},- {- hosts: ["x.com", "twitter.com"],- content: `- #react-root [data-testid="placementTracking"] article,- #react-root a[href*="quick_promote_web"] {- display: none !important;- }-- #react-root [data-testid="GrokDrawer"],- #react-root [data-testid="chat-drawer-root"] {- visibility: hidden !important;- }-- #react-root [data-testid="primaryColumn"] > div > div {- position: relative !important;- }-- #react-root [data-testid="sidebarColumn"] {- visibility: hidden !important;- width: 0 !important;- margin: 0 !important;- padding: 0 !important;- z-index: 1 !important;- }-- /* Keep Grok quote cards inside the column, including long author names. */- #react-root [data-testid="primaryColumn"] [aria-label="Grok"]- div:has(> div > div[role="link"]) {- max-width: 100% !important;- }-- @media only screen and (min-width: 1000px) {- #react-root main[role="main"] {- align-items: center !important;- overflow-x: clip !important;- }-- #react-root [data-testid="primaryColumn"] {- width: 700px !important;- max-width: 700px !important;- margin: 0 auto !important;- }- #react-root [data-testid="primaryColumn"] > div > div:last-child,- #react-root [data-testid="primaryColumn"] > div > div:last-child div {- max-width: unset !important;- }-- #react-root div[aria-label][role="group"][id^="id__"] {- margin-right: 81px !important;- }-- #react-root header[role="banner"] {- position: fixed !important;- left: 0 !important;- }-- #react-root header[role="banner"] > div > div > div {- justify-content: center !important;- padding-top: 0;- overflow-x: hidden;- }-- #react-root form[role="search"] > div:nth-child(1) > div {- background-color: transparent !important;- }-- #react-root h1[role="heading"] {- padding-top: 4px !important;- }-- #react-root header[role="banner"] nav[role="navigation"]:hover > * > div {- backdrop-filter: blur(12px) !important;- }- #react-root header[role="banner"] nav[role="navigation"] > a {- position: relative;- }-- #react-root header[role="banner"] nav[role="navigation"] > a::before {- content: "";- position: absolute;- top: 0px;- right: -40px;- bottom: 0px;- left: 0px;- }- #react-root [data-testid="SideNav_AccountSwitcher_Button"] {- bottom: 18px !important;- left: 1px !important;- }-- #react-root [data-testid="SideNav_NewTweet_Button"] {- display: none;- }- }-- @media only screen and (min-width: 1000px) and (max-width: 1264px) {- #react-root [data-testid="sidebarColumn"] form[role="search"] {- visibility: visible !important;- position: fixed !important;- top: 12px !important;- right: 16px !important;- left: auto !important;- width: 182px !important;- }-- #react-root [data-testid="sidebarColumn"] form[role="search"] input[data-testid="SearchBox_Search_Input"] {- width: 100% !important;- }-- #react-root [data-testid="sidebarColumn"] form[role="search"]:focus-within {- width: 280px !important;- backdrop-filter: blur(12px) !important;- }- }-- @media only screen and (min-width: 1265px) {- #react-root [data-testid="sidebarColumn"] form[role="search"] {- visibility: visible !important;- position: fixed !important;- top: 12px !important;- right: 16px !important;- left: auto !important;- width: 182px !important;- }-- #react-root [data-testid="sidebarColumn"] form[role="search"] input[data-testid="SearchBox_Search_Input"] {- width: 100% !important;- }-- #react-root [data-testid="sidebarColumn"] form[role="search"]:focus-within {- width: 374px !important;- backdrop-filter: blur(12px) !important;- }-- #react-root div[style*="left: -12px"] {- left: unset !important;- }-- #react-root div[style="left: -8px; width: 306px;"] {- left: unset !important;- width: 374px !important;- }-- #react-root .searchFilters {- visibility: visible !important;- position: fixed;- top: 12px;- right: 16px;- width: 240px;- }- #react-root .searchFilters > div > div:first-child {- display: none;- }- }- `,- },{hosts: ["grok.com"],immersive: `- .flex.w-full.h-full.overflow-hidden{- padding-top:20px;- }-#grok-app-root [data-sidebar="sidebar"] {padding-top: 24px;}`,},- {- hosts: ["chat.deepseek.com"],- immersive: `- body:not(.rtl) ._5a20a69 {- margin-left: 84px;- }-- .b8812f16 {- padding-top: 16px;- }- `,- },{hosts: ["gemini.google.com"],immersive: `@@ -250,11 +78,6 @@},{hosts: ["youtube.com"],- content: `- #masthead-ad {- display: none !important;- }- `,immersive: `#layout > ytmusic-nav-bar{padding-top: 20px;@@ -271,25 +94,6 @@},{hosts: ["xiaohongshu.com"],- content: `- #app > header > div > div.menu,- #app > div.layout > div.main-container > div.side-bar > li.divider {- display: none !important;- }-- #app > header .right .avatar.logged-in{- opacity: 0;- transition: opacity 0.3s;- }-- #app > header .right .avatar.logged-in:hover{- opacity: 1;- }-- #global > div.header-container.showSearchBoxOrHeaderFixed > header > div.right > div > div.dropdown-nav{- display: none;- }- `,immersive: `#app > div.layout > div.header-container.showSearchBoxOrHeaderFixed > header > a {padding-top:10px;@@ -304,30 +108,6 @@}`,},- {- hosts: ["v.flomoapp.com"],- content: `- #page #footer-wrapper {- display: none !important;- }- `,- },- {- hosts: ["qwerty.kaiyi.cool"],- content: `- #root > main > footer.justify-center.ease-in {- visibility: hidden !important;- }- `,- },- {- hosts: ["lizhi.dengdengju.com", "lizhi.turkyden.com"],- content: `- #root > div > div.fixed.top-0.left-0.w-64.h-screen.p-10.pb-0.flex.flex-col.justify-between > div > div.space-y-4 > a:nth-child(3) {- display: none !important;- }- `,- },];const hostname = window.location.hostname;diff --git a/src-tauri/src/inject/theme_refresh.js b/src-tauri/src/inject/theme_refresh.jsindex 0802285d..9975fe44 100644--- a/src-tauri/src/inject/theme_refresh.js+++ b/src-tauri/src/inject/theme_refresh.js@@ -1,7 +1,10 @@(function () {if (window.top && window.top !== window) return;+ if (window.pakeConfig?.dark_mode) return;document.addEventListener("DOMContentLoaded", () => {+ if (window.pakeConfig?.dark_mode) return;+const debounce = (func, wait) => {let timeout;return (...args) => {@@ -10,33 +13,70 @@};};- const updateTheme = () => {+ const mediaQuery =+ typeof window.matchMedia === "function"+ ? window.matchMedia("(prefers-color-scheme: dark)")+ : null;++ const systemMode = () => (mediaQuery?.matches ? "dark" : "light");++ const detectPageMode = () => {const doc = document.documentElement;+ if (!doc) return null;const body = document.body;- let mode = null;// Check for explicit theme classes or attributesconst isDark =doc.classList.contains("dark") ||- body.classList.contains("dark") ||+ body?.classList?.contains("dark") ||doc.getAttribute("data-theme") === "dark" ||- body.getAttribute("data-theme") === "dark" ||+ body?.getAttribute?.("data-theme") === "dark" ||doc.style.colorScheme === "dark";const isLight =doc.classList.contains("light") ||- body.classList.contains("light") ||+ body?.classList?.contains("light") ||doc.getAttribute("data-theme") === "light" ||- body.getAttribute("data-theme") === "light" ||+ body?.getAttribute?.("data-theme") === "light" ||doc.style.colorScheme === "light";- if (isDark) mode = "dark";- else if (isLight) mode = "light";+ if (isDark) return "dark";+ if (isLight) return "light";+ return null;+ };++ let appliedMode = null;++ const sendThemeMode = (mode) => {+ const invoke = window.__PAKE_NATIVE__?.core?.invoke;+ if (!invoke) return;+ Promise.resolve(invoke("update_theme_mode", { mode })).catch(() => {});+ };- // Only invoke Rust command if an explicit theme override is detected- if (mode && window.__PAKE_NATIVE__?.core) {- window.__PAKE_NATIVE__.core.invoke("update_theme_mode", { mode });+ const updateTheme = () => {+ if (window.pakeConfig?.dark_mode) return;+ const mode = detectPageMode();++ if (mode === null) {+ if (appliedMode !== null) {+ appliedMode = null;+ sendThemeMode("system");+ }+ return;+ }++ // While following the OS appearance, skip pinning a mode that already+ // matches the OS so native appearance switches keep working.+ if (appliedMode === null && mode === systemMode()) {+ return;}++ if (mode === appliedMode) {+ return;+ }++ appliedMode = mode;+ sendThemeMode(mode);};const debouncedUpdateTheme = debounce(updateTheme, 200);@@ -52,12 +92,13 @@subtree: false,};- observer.observe(document.documentElement, config);- observer.observe(document.body, config);+ if (document.documentElement) {+ observer.observe(document.documentElement, config);+ }+ if (document.body) {+ observer.observe(document.body, config);+ }- // Watch for system theme changes (though window should handle this natively now)- window- .matchMedia("(prefers-color-scheme: dark)")- .addEventListener("change", updateTheme);+ mediaQuery?.addEventListener?.("change", updateTheme);});})();diff --git a/src-tauri/src/inject/toast.js b/src-tauri/src/inject/toast.jsindex 5bb8a851..e1560bb7 100644--- a/src-tauri/src/inject/toast.js+++ b/src-tauri/src/inject/toast.js@@ -7,8 +7,9 @@// `action` names a Pake command a click on the toast runs (showing a finished// download in the file manager); such a toast stays twice as long.function pakeToast(msg, action) {+ if (!document.body) return;const m = document.createElement("div");- m.innerHTML = msg;+ m.textContent = msg;m.style.cssText ="max-width:60%;min-width: 80px;padding:0 12px;height: 32px;color: rgb(255, 255, 255);line-height: 32px;text-align: center;border-radius: 8px;position: fixed; bottom:24px;right: 28px;z-index: 999999;background: rgba(0, 0, 0,.8);font-size: 13px;";if (action) {@@ -26,7 +27,7 @@"transform " + d + "s ease-in, opacity " + d + "s ease-in";m.style.opacity = "0";setTimeout(function () {- document.body.removeChild(m);+ m.remove();}, d * 1000);},action ? 6000 : 3000,diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex c1e990ea..a116de1a 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -353,13 +353,15 @@ pub fn run_app() {.with_filter(|label| !label.starts_with(app::window::POPUP_WINDOW_LABEL_PREFIX)).build();- #[allow(deprecated)]let mut app_builder = tauri_app.plugin(window_state_plugin).plugin(tauri_plugin_http::init())- .plugin(tauri_plugin_shell::init()).plugin(tauri_plugin_notification::init())- .plugin(tauri_plugin_opener::init()); // Add this+ .plugin(+ tauri_plugin_opener::Builder::new()+ .open_js_links_on_click(false)+ .build(),+ );// Only add single instance plugin if multiple instances are not allowedif !multi_instance {diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 0fe0113f..10b21bcd 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -4,11 +4,6 @@"version": "3.21.0","app": {"withGlobalTauri": false,- "trayIcon": {- "iconPath": "png/weekly_512.png",- "iconAsTemplate": false,- "id": "pake-tray"- },"security": {"headers": {},"csp": nulldiff --git a/tests/browser/popup-routing.mjs b/tests/browser/popup-routing.mjsindex e341c522..eb6f6eef 100644--- a/tests/browser/popup-routing.mjs+++ b/tests/browser/popup-routing.mjs@@ -38,7 +38,8 @@ async function fixture(frame, run, config = {}) {window.__PAKE_NATIVE__ = {core: {invoke: (cmd, args) => {- if (cmd === "plugin:shell|open") window.opened.push(args.path);+ if (cmd === "plugin:opener|open_url")+ window.opened.push(args.url);return Promise.resolve();},},@@ -48,9 +49,9 @@ async function fixture(frame, run, config = {}) {? source: source.slice(0, 3))(0, eval)(script);- // tauri-plugin-shell 2.3.5 ships this listener in every app: any- // target="_blank" link goes to the system browser, whether or not- // the page prevented the click.+ // Simulate a host click listener that opens any target="_blank" link+ // that still bubbles as _blank, verifying Pake's click guard retargets+ // internal and addressless new-tab links before the bubble.if (window === window.top)document.addEventListener("DOMContentLoaded", () => {document.body.addEventListener("click", (event) => {@@ -62,9 +63,12 @@ async function fixture(frame, run, config = {}) {/^https?:\/\//.test(node.href) &&node.target === "_blank") {- window.__PAKE_NATIVE__.core.invoke("plugin:shell|open", {- path: node.href,- });+ window.__PAKE_NATIVE__.core.invoke(+ "plugin:opener|open_url",+ {+ url: node.href,+ },+ );event.preventDefault();}break;diff --git a/tests/browser/protocol-links.mjs b/tests/browser/protocol-links.mjsindex e8752222..1869dced 100644--- a/tests/browser/protocol-links.mjs+++ b/tests/browser/protocol-links.mjs@@ -41,8 +41,8 @@ for (const frame of [false, true]) {window.__PAKE_NATIVE__ = {core: {invoke: (cmd, args) => {- if (cmd === "plugin:shell|open")- window.opened.push(args.path);+ if (cmd === "plugin:opener|open_url")+ window.opened.push(args.url);return Promise.resolve();},},diff --git a/tests/unit/base-builder.test.ts b/tests/unit/base-builder.test.tsindex 5d67821b..d4e839b2 100644--- a/tests/unit/base-builder.test.ts+++ b/tests/unit/base-builder.test.ts@@ -417,4 +417,24 @@ describe('BaseBuilder guards', () => {'cargo:rerun-if-changed=.pake/tauri.conf.json',);});++ it('enables macos-proxy on macOS 14+ without CJS require', () => {+ const builder = new TestBuilder({ debug: false } as any);+ const releaseSpy = vi.spyOn(os, 'release');++ releaseSpy.mockReturnValue('23.6.0');+ expect((builder as any).getMacOSMajorVersion()).toBe(23);+ if (process.platform === 'darwin') {+ expect((builder as any).getBuildFeatures()).toEqual([+ 'cli-build',+ 'macos-proxy',+ ]);+ }++ releaseSpy.mockReturnValue('22.6.0');+ expect((builder as any).getMacOSMajorVersion()).toBe(22);+ if (process.platform === 'darwin') {+ expect((builder as any).getBuildFeatures()).toEqual(['cli-build']);+ }+ });});diff --git a/tests/unit/download-http-status.test.ts b/tests/unit/download-http-status.test.tsindex 3d9364e6..e376d463 100644--- a/tests/unit/download-http-status.test.ts+++ b/tests/unit/download-http-status.test.ts@@ -71,17 +71,18 @@ describe('download HTTP status handling', () => {);});- it('keeps download path heuristics narrow (no SPA roots)', () => {+ it('keeps download path heuristics empty (no SPA roots)', () => {const patternsBlock = eventSource.match(/const DOWNLOAD_PATH_PATTERNS = \[([\s\S]*?)\];/,)?.[1];- expect(patternsBlock).toBeTruthy();+ expect(patternsBlock).not.toBeUndefined();+ expect(patternsBlock!.trim()).toBe('');expect(patternsBlock).not.toContain('/assets/');expect(patternsBlock).not.toContain('/dist/');expect(patternsBlock).not.toContain('/files/');expect(patternsBlock).not.toContain('/attachments/');expect(patternsBlock).not.toContain('/releases/');- expect(patternsBlock).toContain('/download/');+ expect(patternsBlock).not.toContain('/download/');});it('toasts download progress on the calling window, not a hard-coded main label', () => {diff --git a/tests/unit/event-fullscreen-shortcuts.test.js b/tests/unit/event-fullscreen-shortcuts.test.jsindex aa8bd221..9981dd80 100644--- a/tests/unit/event-fullscreen-shortcuts.test.js+++ b/tests/unit/event-fullscreen-shortcuts.test.js@@ -186,7 +186,7 @@ function getWindowShortcutHandler(context) {}function getWebShortcutHandler(context) {- return context.eventListeners.keyup.find(+ return context.eventListeners.keydown.find(({ handler }) => handler.name === "handleWebShortcut",).handler;}@@ -427,6 +427,92 @@ describe("event fullscreen shortcuts", () => {expect(event.preventDefault).toHaveBeenCalled();});+ it("registers handleWebShortcut on keydown in the bubble phase", () => {+ const context = loadEventHelpers();+ const entry = context.eventListeners.keydown.find(+ ({ handler }) => handler.name === "handleWebShortcut",+ );+ expect(entry).toBeDefined();+ expect(entry.options).toBeUndefined();+ expect(+ context.eventListeners.keyup?.find(+ ({ handler }) => handler.name === "handleWebShortcut",+ ),+ ).toBeUndefined();+ });++ it("skips web shortcuts when defaultPrevented or extra modifiers are set", () => {+ const winContext = loadEventHelpers();+ const winHandler = getWebShortcutHandler(winContext);+ winHandler(createKeyEvent("r", { ctrlKey: true, defaultPrevented: true }));+ winHandler(createKeyEvent("r", { ctrlKey: true, shiftKey: true }));+ winHandler(createKeyEvent("r", { ctrlKey: true, altKey: true }));+ winHandler(createKeyEvent("r", { ctrlKey: true, metaKey: true }));+ expect(winContext.navigateCalls).toEqual([]);++ const macContext = loadEventHelpers({+ userAgent:+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15",+ platform: "MacIntel",+ });+ const macHandler = getWebShortcutHandler(macContext);+ const shiftUp = createKeyEvent("ArrowUp", {+ metaKey: true,+ shiftKey: true,+ });+ const altDown = createKeyEvent("ArrowDown", {+ metaKey: true,+ altKey: true,+ });+ const preventedUp = createKeyEvent("ArrowUp", {+ metaKey: true,+ defaultPrevented: true,+ });+ macHandler(shiftUp);+ macHandler(altDown);+ macHandler(preventedUp);+ expect(shiftUp.preventDefault).not.toHaveBeenCalled();+ expect(altDown.preventDefault).not.toHaveBeenCalled();+ expect(preventedUp.preventDefault).not.toHaveBeenCalled();+ });++ it("skips ArrowUp, ArrowDown, [, and ] in editable fields", () => {+ for (const makeField of [+ () => createElement("input"),+ () => createElement("textarea"),+ () => ({ ...createElement("div"), isContentEditable: true }),+ ]) {+ const winContext = loadEventHelpers();+ winContext.document.activeElement = makeField();+ const winHandler = getWebShortcutHandler(winContext);+ for (const key of ["ArrowUp", "ArrowDown", "[", "]"]) {+ const event = createKeyEvent(key, { ctrlKey: true });+ winHandler(event);+ expect(event.preventDefault).not.toHaveBeenCalled();+ }+ expect(winContext.navigateCalls).toEqual([]);++ // Reload still works from an editable field on Windows/Linux.+ const reloadEvent = createKeyEvent("r", { ctrlKey: true });+ winHandler(reloadEvent);+ expect(reloadEvent.preventDefault).toHaveBeenCalled();+ expect(winContext.navigateCalls).toEqual(["reload"]);++ const macContext = loadEventHelpers({+ userAgent:+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15",+ platform: "MacIntel",+ });+ macContext.document.activeElement = makeField();+ const macHandler = getWebShortcutHandler(macContext);+ for (const key of ["ArrowUp", "ArrowDown"]) {+ const event = createKeyEvent(key, { metaKey: true });+ macHandler(event);+ expect(event.preventDefault).not.toHaveBeenCalled();+ }+ }+ });+it("toggles native fullscreen on F11 for Windows", async () => {const context = loadEventHelpers();const handler = getFullscreenShortcutHandler(context);diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.jsindex db126bcb..5b32047b 100644--- a/tests/unit/event-link-guard.test.js+++ b/tests/unit/event-link-guard.test.js@@ -283,7 +283,7 @@ describe("event link guard", () => {result.location.href = "https://cdn.example.net/attachment";expect(context.window.location.href).toBe("https://example.com/app");expect(- context.invokeCalls.filter(([cmd]) => cmd === "plugin:shell|open"),+ context.invokeCalls.filter(([cmd]) => cmd === "plugin:opener|open_url"),).toEqual([]);},);@@ -501,8 +501,8 @@ describe("event link guard", () => {).toBeNull();expect(nativeOpen).not.toHaveBeenCalled();expect(context.invokeCalls).toContainEqual([- "plugin:shell|open",- { path: "https://outside.example/share" },+ "plugin:opener|open_url",+ { url: "https://outside.example/share" },]);expect(context.window.location.href).toBe("https://example.com/app");});@@ -516,8 +516,8 @@ describe("event link guard", () => {context.window.open(url, "reportWindow");if (url.startsWith("https://outside.example/")) {expect(context.invokeCalls).toContainEqual([- "plugin:shell|open",- { path: url },+ "plugin:opener|open_url",+ { url },]);} else {expect(context.window.location.href).toBe(url);@@ -561,7 +561,7 @@ describe("event link guard", () => {expect(nativeOpen).not.toHaveBeenCalled();expect(context.invokeCalls.filter(- ([command]) => command === "plugin:shell|open",+ ([command]) => command === "plugin:opener|open_url",),).toEqual([]);},@@ -592,11 +592,11 @@ describe("event link guard", () => {runDomReady(context);expect(context.invokeCalls.filter(- ([command]) => command === "plugin:shell|open",+ ([command]) => command === "plugin:opener|open_url",),).toEqual([- ["plugin:shell|open", { path: "https://outside.example/first" }],- ["plugin:shell|open", { path: "https://outside.example/second" }],+ ["plugin:opener|open_url", { url: "https://outside.example/first" }],+ ["plugin:opener|open_url", { url: "https://outside.example/second" }],]);expect(context.eventListeners.DOMContentLoaded).toHaveLength(1);});@@ -618,7 +618,7 @@ describe("event link guard", () => {runDomReady(context);expect(context.invokeCalls.filter(- ([command]) => command === "plugin:shell|open",+ ([command]) => command === "plugin:opener|open_url",),).toEqual([]);});@@ -633,8 +633,8 @@ describe("event link guard", () => {listener({ source, data: { type: "pake:frame-external-link", url } });send(frame, "https://outside.example/article");expect(context.invokeCalls).toContainEqual([- "plugin:shell|open",- { path: "https://outside.example/article" },+ "plugin:opener|open_url",+ { url: "https://outside.example/article" },]);const count = context.invokeCalls.length;send({ frames: [] }, "https://outside.example/unrelated");@@ -759,13 +759,20 @@ describe("event link guard", () => {).toBe(true);});- it("keeps intentional download-path interception for extensionless /download/ links", () => {+ it("does not treat extensionless /download/ pages as downloads", () => {const { isDownloadableFile } = loadEventHelpers();+ expect(isDownloadableFile("https://example.com/download/mac")).toBe(false);expect(isDownloadableFile("https://example.com/download/export")).toBe(+ false,+ );+ // Explicit download hints and file extensions still trigger downloads.+ expect(+ isDownloadableFile("https://example.com/download/export?download=1"),+ ).toBe(true);+ expect(isDownloadableFile("https://example.com/download/app.dmg")).toBe(true,);- // Real files under /files/ still match by extension, not the path root.expect(isDownloadableFile("https://example.com/files/report.pdf")).toBe(true,);@@ -801,7 +808,7 @@ describe("event link guard", () => {expect(event.preventDefault).toHaveBeenCalledOnce();expect(context.invokeCalls).toEqual([- ["plugin:shell|open", { path: "https://example.com/app/settings" }],+ ["plugin:opener|open_url", { url: "https://example.com/app/settings" }],]);});@@ -826,7 +833,7 @@ describe("event link guard", () => {getClickGuard(context)(event);expect(event.preventDefault).toHaveBeenCalledOnce();expect(context.invokeCalls).toEqual([- ["plugin:shell|open", { path: href }],+ ["plugin:opener|open_url", { url: href }],]);}},@@ -860,7 +867,7 @@ describe("event link guard", () => {middle(event);expect(event.preventDefault).toHaveBeenCalledOnce();expect(context.invokeCalls).toEqual([- ["plugin:shell|open", { path: "https://example.com/app/next" }],+ ["plugin:opener|open_url", { url: "https://example.com/app/next" }],]);const right = makeClickEvent(@@ -880,7 +887,7 @@ describe("event link guard", () => {event.metaKey = true;getClickGuard(context)(event);expect(context.invokeCalls).not.toContainEqual([- "plugin:shell|open",+ "plugin:opener|open_url",expect.anything(),]);});@@ -1177,7 +1184,7 @@ describe("event link guard", () => {expect(nativeOpen).not.toHaveBeenCalled();expect(event.preventDefault).not.toHaveBeenCalled();expect(- context.invokeCalls.filter(([cmd]) => cmd === "plugin:shell|open"),+ context.invokeCalls.filter(([cmd]) => cmd === "plugin:opener|open_url"),).toEqual([]);vi.runAllTimers();expect(anchor.target).toBe("_blank");@@ -1196,7 +1203,7 @@ describe("event link guard", () => {expect(anchor.target).toBe("_self");expect(event.preventDefault).not.toHaveBeenCalled();expect(- context.invokeCalls.filter(([cmd]) => cmd === "plugin:shell|open"),+ context.invokeCalls.filter(([cmd]) => cmd === "plugin:opener|open_url"),).toEqual([]);});@@ -1213,7 +1220,7 @@ describe("event link guard", () => {return { context, nativeOpen, lastInBubble };};const shellOpens = (context) =>- context.invokeCalls.filter(([cmd]) => cmd === "plugin:shell|open");+ context.invokeCalls.filter(([cmd]) => cmd === "plugin:opener|open_url");for (const newWindow of [false, true]) {it(`takes the new-tab target off a link with no address for the click (new_window ${newWindow})`, () => {@@ -1325,8 +1332,8 @@ describe("event link guard", () => {expect(event.preventDefault).toHaveBeenCalled();expect(event.stopImmediatePropagation).toHaveBeenCalled();expect(context.invokeCalls).toContainEqual([- "plugin:shell|open",- { path: "https://other.example.org/page" },+ "plugin:opener|open_url",+ { url: "https://other.example.org/page" },]);});@@ -1355,7 +1362,7 @@ describe("event link guard", () => {]);expect(context.invokeCalls.filter(- ([command]) => command === "plugin:shell|open",+ ([command]) => command === "plugin:opener|open_url",),).toEqual([]);});@@ -1541,9 +1548,11 @@ describe("links in a web mail app", () => {);expect(fresh.invokeCalls.filter(- ([command]) => command === "plugin:shell|open",+ ([command]) => command === "plugin:opener|open_url",),- ).toEqual([["plugin:shell|open", { path: "https://github.com/login" }]]);+ ).toEqual([+ ["plugin:opener|open_url", { url: "https://github.com/login" }],+ ]);}});@@ -1554,7 +1563,7 @@ describe("links in a web mail app", () => {expect(context.window.location.href).toBe(url);expect(context.invokeCalls.filter(- ([command]) => command === "plugin:shell|open",+ ([command]) => command === "plugin:opener|open_url",),).toEqual([]);});@@ -1623,4 +1632,43 @@ describe("extensionless download filenames and native context menu", () => {],]);});++ it("logs download errors without raising a duplicate Web Notification", () => {+ const context = loadEventHelpers({ withTauri: true });+ const errorSpy = vi+ .spyOn(context.console, "error")+ .mockImplementation(() => {});+ context.showDownloadError("report.pdf");+ expect(errorSpy).toHaveBeenCalledWith("Download failed: report.pdf");+ expect(+ context.invokeCalls.filter(([cmd]) => cmd === "send_notification"),+ ).toEqual([]);+ expect(+ context.invokeCalls.filter(([cmd]) => cmd === "increment_dock_badge"),+ ).toEqual([]);+ });++ it("handles localStorage errors in zoom helpers and malformed anchor hrefs safely", () => {+ const context = loadEventHelpers({ withTauri: true });+ context.window.localStorage = {+ getItem: () => {+ throw new Error("SecurityError");+ },+ setItem: () => {+ throw new Error("QuotaExceededError");+ },+ };+ expect(() => context.zoomIn()).not.toThrow();+ expect(() => context.setZoom("120%")).not.toThrow();+ expect(context.invokeCalls.filter(([cmd]) => cmd === "set_zoom")).toEqual([+ ["set_zoom", { percent: 110 }],+ ["set_zoom", { percent: 120 }],+ ]);++ runDomReady(context);+ const badAnchor = makeAnchor("http://[::1", "_self");+ expect(() =>+ getClickGuard(context)(makeClickEvent(badAnchor)),+ ).not.toThrow();+ });});diff --git a/tests/unit/native-bridge.test.js b/tests/unit/native-bridge.test.jsindex a60067bc..e478ab59 100644--- a/tests/unit/native-bridge.test.js+++ b/tests/unit/native-bridge.test.js@@ -77,7 +77,10 @@ describe("Pake's native bridge", () => {["plugin:window|minimize", { label: "pake-2" }],["plugin:window|set_resizable", { label: "pake-2", value: true }],["plugin:window|theme", { label: "pake-2" }],- ["plugin:shell|open", { path: "https://example.com", with: undefined }],+ [+ "plugin:opener|open_url",+ { url: "https://example.com", with: undefined },+ ],["set_zoom", { percent: 90 }],]);});diff --git a/tests/unit/passkey-bridge.test.js b/tests/unit/passkey-bridge.test.jsindex 37a8db1e..ca5f9d61 100644--- a/tests/unit/passkey-bridge.test.js+++ b/tests/unit/passkey-bridge.test.js@@ -17,7 +17,7 @@ const b64url = (bytes) =>.replace(/\//g, "_").replace(/=+$/, "");-function load({ reply, handler = true, top = true } = {}) {+function load({ reply, handler = true, top = true, userActive } = {}) {class PublicKeyCredential {static isUserVerifyingPlatformAuthenticatorAvailable() {return Promise.resolve(false);@@ -48,6 +48,10 @@ function load({ reply, handler = true, top = true } = {}) {addEventListener: page.addEventListener.bind(page),removeEventListener: page.removeEventListener.bind(page),dispatchEvent: page.dispatchEvent.bind(page),+ navigator:+ userActive === undefined+ ? undefined+ : { userActivation: { isActive: userActive } },PublicKeyCredential,CredentialsContainer,AuthenticatorAttestationResponse,@@ -187,13 +191,17 @@ describe("passkey bridge", () => {});it("answers a sign-in with an assertion carrying the user handle", async () => {- const { window, credentials, posted } = load({ reply: () => signedIn });+ const { window, credentials, posted } = load({+ reply: () => signedIn,+ userActive: true,+ });const credential = await credentials.get({publicKey: { challenge: new Uint8Array([1]), rpId: "example.com" },});expect(posted[0]).toEqual({id: 1,kind: "get",+ userActive: true,publicKey: { challenge: "AQ", rpId: "example.com", allowCredentials: [] },});expect(@@ -205,6 +213,30 @@ describe("passkey bridge", () => {);});+ it("forwards userActivation on create and get so background probes stay silent", async () => {+ const inactive = load({+ reply: (req) => (req.kind === "create" ? created : signedIn),+ userActive: false,+ });+ await inactive.credentials.get({+ publicKey: { challenge: new Uint8Array([1]), rpId: "x.com" },+ });+ await inactive.credentials.create(createOptions);+ expect(inactive.posted[0].userActive).toBe(false);+ expect(inactive.posted[1].userActive).toBe(false);++ const active = load({+ reply: () => created,+ userActive: true,+ });+ await active.credentials.create(createOptions);+ expect(active.posted[0].userActive).toBe(true);++ const fallback = load({ reply: () => created });+ await fallback.credentials.create(createOptions);+ expect(fallback.posted[0].userActive).toBe(true);+ });+it("raises the native side's failure as the DOMException a browser would", async () => {const { credentials } = load({reply: () => ({ error: "NotAllowedError", message: "" }),diff --git a/tests/unit/popup-close.test.ts b/tests/unit/popup-close.test.tsindex 1186ccd9..ee271db9 100644--- a/tests/unit/popup-close.test.ts+++ b/tests/unit/popup-close.test.ts@@ -79,7 +79,7 @@ describe('a popup its page closes', () => {it('closes the window on Windows, where Wry destroys only the web view', () => {// The popup had answered its opener and stayed on screen, empty.expect(buildWindow()).toMatch(- /#\[cfg\(target_os = "windows"\)\]\s+if page_popup \{[\s\S]+?core\.add_WindowCloseRequested\([\s\S]+?if let Err\(error\) = popup\.close\(\)/,+ /#\[cfg\(target_os = "windows"\)\]\s+if page_popup(?:\s*\|\|\s*label == "extension-settings")? \{[\s\S]+?core\.add_WindowCloseRequested\([\s\S]+?if let Err\(error\) = popup\.close\(\)/,);});diff --git a/tests/unit/site-styles.test.js b/tests/unit/site-styles.test.jsindex f9806476..8c8b3215 100644--- a/tests/unit/site-styles.test.js+++ b/tests/unit/site-styles.test.js@@ -48,47 +48,72 @@ describe("site styles", () => {});it("loads a site's rules on its host and subdomains", () => {- expect(injectedStyles("x.com").content).toContain("#react-root");expect(injectedStyles("music.youtube.com").immersive).toContain("ytmusic-nav-bar",);expect(injectedStyles("www.notion.so").immersive).toContain(".notion-sidebar",);+ expect(injectedStyles("grok.com").immersive).toContain(+ '#grok-app-root [data-sidebar="sidebar"]',+ );+ expect(injectedStyles("grok.com").immersive).not.toContain(+ ".flex.w-full.h-full.overflow-hidden",+ );+ });++ it("omits removed brittle site content hacks and hashed selectors", () => {+ expect(injectedStyles("youtube.com").content).not.toContain("#masthead-ad");+ expect(injectedStyles("x.com").content).not.toContain("#react-root");+ expect(injectedStyles("xiaohongshu.com").content).not.toContain(+ ".avatar.logged-in",+ );+ expect(injectedStyles("xiaohongshu.com").immersive).toContain(+ "#header-area .logoIcon .user-info",+ );+ expect(injectedStyles("chat.deepseek.com").immersive).not.toContain(+ "._5a20a69",+ );+ expect(injectedStyles("v.flomoapp.com").content).not.toContain(+ "#footer-wrapper",+ );+ expect(injectedStyles("qwerty.kaiyi.cool").content).not.toContain(+ "footer.justify-center",+ );+ expect(injectedStyles("lizhi.dengdengju.com").content).not.toContain(+ "a:nth-child(3)",+ );});it("does not match lookalike hosts", () => {- expect(injectedStyles("notx.com").content).not.toContain("#react-root");- expect(injectedStyles("x.com.example.org").content).not.toContain(- "#react-root",+ expect(injectedStyles("notyoutube.com").immersive).not.toContain(+ "ytd-masthead",+ );+ expect(injectedStyles("youtube.com.example.org").immersive).not.toContain(+ "ytd-masthead",+ );+ expect(injectedStyles("notnotion.so").immersive).not.toContain(+ ".notion-sidebar",);});it("keeps site immersive spacing to the macOS hidden title bar", () => {- expect(injectedStyles("chat.deepseek.com").immersive).toContain(- "._5a20a69",- );- expect(- injectedStyles("chat.deepseek.com", { mac: false }).immersive,- ).not.toContain("._5a20a69");+ expect(injectedStyles("youtube.com").immersive).toContain("ytd-masthead");expect(- injectedStyles("chat.deepseek.com", { immersive: false }).immersive,- ).toBe("");+ injectedStyles("youtube.com", { mac: false }).immersive,+ ).not.toContain("ytd-masthead");+ expect(injectedStyles("youtube.com", { immersive: false }).immersive).toBe(+ "",+ );});- it("leaves a site's content rules to an extension that restyles it", () => {- const off = injectedStyles("x.com", { pakeConfig: { site_styles: false } });+ it("keeps global and window immersive rules when site_styles is false", () => {+ const off = injectedStyles("youtube.com", {+ pakeConfig: { site_styles: false },+ });expect(off.content).toContain("html::-webkit-scrollbar");- expect(off.content).not.toContain("#react-root");// The window's own rules stay: the drag strip and the traffic-light room.expect(off.immersive).toContain("#pake-top-dom");- expect(- injectedStyles("chat.deepseek.com", {- pakeConfig: { site_styles: false },- }).immersive,- ).toContain("._5a20a69");- expect(- injectedStyles("x.com", { pakeConfig: { site_styles: true } }).content,- ).toContain("#react-root");+ expect(off.immersive).toContain("ytd-masthead");});});diff --git a/tests/unit/theme-refresh.test.js b/tests/unit/theme-refresh.test.jsnew file mode 100644index 00000000..516d6344--- /dev/null+++ b/tests/unit/theme-refresh.test.js@@ -0,0 +1,195 @@+import fs from "node:fs";+import path from "node:path";+import vm from "node:vm";+import { afterEach, describe, expect, it, vi } from "vitest";++const source = fs.readFileSync(+ path.join(process.cwd(), "src-tauri/src/inject/theme_refresh.js"),+ "utf-8",+);++function makeElement({+ classes = [],+ dataTheme = null,+ colorScheme = "",+} = {}) {+ const classSet = new Set(classes);+ let themeAttr = dataTheme;+ return {+ classList: {+ contains: (name) => classSet.has(name),+ add: (name) => classSet.add(name),+ remove: (name) => classSet.delete(name),+ },+ getAttribute: (name) => (name === "data-theme" ? themeAttr : null),+ setAttribute: (name, value) => {+ if (name === "data-theme") themeAttr = value;+ },+ removeAttribute: (name) => {+ if (name === "data-theme") themeAttr = null;+ },+ style: { colorScheme },+ };+}++function loadThemeRefresh({+ darkMode = false,+ systemDark = false,+ docOptions = {},+ bodyOptions = {},+ noBody = false,+ rejectInvoke = false,+} = {}) {+ const invokeCalls = [];+ const observed = [];+ let observerCallback = null;+ let domReady = null;+ let mediaChange = null;+ const media = {+ matches: systemDark,+ addEventListener: (event, fn) => {+ if (event === "change") mediaChange = fn;+ },+ };++ const documentElement = makeElement(docOptions);+ const body = noBody ? null : makeElement(bodyOptions);++ class MutationObserver {+ constructor(cb) {+ observerCallback = cb;+ }+ observe(target, config) {+ if (!target) {+ throw new TypeError("Failed to execute 'observe': target is null");+ }+ observed.push({ target, config });+ }+ }++ const window = {+ pakeConfig: { dark_mode: darkMode },+ matchMedia: () => media,+ __PAKE_NATIVE__: {+ core: {+ invoke: (command, payload) => {+ invokeCalls.push([command, payload]);+ return rejectInvoke+ ? Promise.reject(new Error("Command update_theme_mode not allowed"))+ : Promise.resolve();+ },+ },+ },+ };+ window.top = window;++ const document = {+ documentElement,+ body,+ addEventListener: (event, fn) => {+ if (event === "DOMContentLoaded") domReady = fn;+ },+ };++ vm.runInNewContext(source, {+ window,+ document,+ MutationObserver,+ Promise,+ setTimeout,+ clearTimeout,+ });++ return {+ window,+ document,+ documentElement,+ body,+ media,+ invokeCalls,+ observed,+ triggerDomReady: () => domReady?.(),+ triggerMutation: () => observerCallback?.(),+ triggerMediaChange: (matches) => {+ media.matches = matches;+ mediaChange?.();+ },+ };+}++describe("theme_refresh", () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it("never overrides an explicit dark_mode: true config", () => {+ vi.useFakeTimers();+ const env = loadThemeRefresh({+ darkMode: true,+ docOptions: { classes: ["light"] },+ });+ env.triggerDomReady();+ vi.advanceTimersByTime(1000);+ expect(env.invokeCalls).toEqual([]);+ expect(env.observed).toEqual([]);+ });++ it("does not pin the window when page theme matches the OS appearance", () => {+ vi.useFakeTimers();+ const env = loadThemeRefresh({+ systemDark: false,+ docOptions: { classes: ["light"] },+ });+ env.triggerDomReady();+ vi.advanceTimersByTime(600);+ expect(env.invokeCalls).toEqual([]);++ // OS switches to dark and the page updates to match: still no pinning.+ env.documentElement.classList.remove("light");+ env.documentElement.classList.add("dark");+ env.triggerMediaChange(true);+ expect(env.invokeCalls).toEqual([]);+ });++ it("applies an explicit page override and restores system mode when cleared", () => {+ vi.useFakeTimers();+ const env = loadThemeRefresh({+ systemDark: false,+ docOptions: { classes: ["dark"] },+ });+ env.triggerDomReady();+ vi.advanceTimersByTime(600);+ expect(env.invokeCalls).toEqual([["update_theme_mode", { mode: "dark" }]]);++ // Unchanged mutations do not re-invoke.+ env.triggerMutation();+ vi.advanceTimersByTime(300);+ expect(env.invokeCalls).toHaveLength(1);++ // Removing the explicit theme returns the window to OS tracking.+ env.documentElement.classList.remove("dark");+ env.triggerMutation();+ vi.advanceTimersByTime(300);+ expect(env.invokeCalls).toEqual([+ ["update_theme_mode", { mode: "dark" }],+ ["update_theme_mode", { mode: "system" }],+ ]);+ });++ it("null-guards document.body before observing and catches rejected invokes", async () => {+ vi.useFakeTimers();+ const env = loadThemeRefresh({+ systemDark: false,+ noBody: true,+ docOptions: { dataTheme: "dark" },+ rejectInvoke: true,+ });+ expect(() => env.triggerDomReady()).not.toThrow();+ expect(env.observed).toHaveLength(1);+ expect(env.observed[0].target).toBe(env.documentElement);++ vi.advanceTimersByTime(600);+ await Promise.resolve();+ expect(env.invokeCalls).toEqual([["update_theme_mode", { mode: "dark" }]]);+ });+});